@mikro-orm/mssql 7.3.0-dev.2 → 7.3.0-dev.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -138,6 +138,9 @@ export class MsSqlConnection extends AbstractSqlConnection {
138
138
  }
139
139
  async commit(ctx, eventBroadcaster) {
140
140
  if ('savepointName' in ctx) {
141
+ if (!ctx.isRolledBack && 'failedSavepointRollback' in ctx) {
142
+ throw ctx.failedSavepointRollback;
143
+ }
141
144
  return;
142
145
  }
143
146
  return super.commit(ctx, eventBroadcaster);
package/MsSqlDriver.js CHANGED
@@ -1,4 +1,4 @@
1
- import { QueryFlag, Utils, isRaw, } from '@mikro-orm/core';
1
+ import { QueryFlag, Utils, } from '@mikro-orm/core';
2
2
  import { AbstractSqlDriver } from '@mikro-orm/sql';
3
3
  import { MsSqlConnection } from './MsSqlConnection.js';
4
4
  import { MsSqlPlatform } from './MsSqlPlatform.js';
@@ -31,20 +31,13 @@ export class MsSqlDriver extends AbstractSqlDriver {
31
31
  sql = this.appendOutputTable(entityName, returningFields, sql, sql.length - 1, options);
32
32
  }
33
33
  const res = await this.execute(sql, [], 'run', options.ctx);
34
- const pks = this.getPrimaryKeyFields(meta);
35
- if (pks.length === 1) {
36
- res.row ??= {};
37
- res.rows ??= [];
38
- res.insertId = res.insertId || res.row[pks[0]];
39
- }
34
+ this.resolveInsertedPrimaryKeys(meta, data, res);
40
35
  return res;
41
36
  }
42
37
  return super.nativeInsertMany(entityName, data, options, sql => {
43
38
  if (meta.hasTriggers) {
44
39
  // must match the OUTPUT columns of the parent implementation, which resolves STI children to the root
45
- const returning = this.getTableProps(meta.inheritanceType === 'tpt' ? meta : meta.root).filter(prop => prop.returning ||
46
- (((prop.persist !== false && prop.defaultRaw) || prop.autoincrement || prop.generated) &&
47
- (!(prop.name in data[0]) || isRaw(data[0][prop.name]))));
40
+ const returning = this.getInsertReturningProperties(meta.inheritanceType === 'tpt' ? meta : meta.root, data);
48
41
  sql = this.appendOutputTable(entityName, returning.flatMap(p => p.fieldNames), sql, sql.indexOf(' values '), options);
49
42
  }
50
43
  // For TPT children, the parent table owns the identity column.
@@ -1,4 +1,4 @@
1
- import { AbstractSqlPlatform, type EntityManager, type EntityMetadata, type IDatabaseDriver, type IPrimaryKey, type MikroORM, MsSqlNativeQueryBuilder, type Primary, QueryOrder, RawQueryFragment, Type } from '@mikro-orm/sql';
1
+ import { AbstractSqlPlatform, type EntityManager, type EntityMetadata, type IDatabaseDriver, type IPrimaryKey, type MikroORM, MsSqlNativeQueryBuilder, type Primary, QueryOrder, RawQueryFragment, type TransformContext, Type } from '@mikro-orm/sql';
2
2
  import { MsSqlSchemaHelper } from './MsSqlSchemaHelper.js';
3
3
  import { MsSqlExceptionConverter } from './MsSqlExceptionConverter.js';
4
4
  import { MsSqlSchemaGenerator } from './MsSqlSchemaGenerator.js';
@@ -22,6 +22,7 @@ export declare class MsSqlPlatform extends AbstractSqlPlatform {
22
22
  usesOutputStatement(): boolean;
23
23
  convertDateToJSValue(value: string | Date): string;
24
24
  convertsJsonAutomatically(): boolean;
25
+ convertJsonToDatabaseValue(value: unknown, context?: TransformContext): unknown;
25
26
  indexForeignKeys(): boolean;
26
27
  /** SQL Server identifier limit (sysname). */
27
28
  getMaxIdentifierLength(): number;
package/MsSqlPlatform.js CHANGED
@@ -47,7 +47,6 @@ export class MsSqlPlatform extends AbstractSqlPlatform {
47
47
  return true;
48
48
  }
49
49
  convertDateToJSValue(value) {
50
- /* v8 ignore next */
51
50
  if (typeof value === 'string') {
52
51
  return value;
53
52
  }
@@ -56,6 +55,11 @@ export class MsSqlPlatform extends AbstractSqlPlatform {
56
55
  convertsJsonAutomatically() {
57
56
  return false;
58
57
  }
58
+ convertJsonToDatabaseValue(value, context) {
59
+ const json = super.convertJsonToDatabaseValue(value, context);
60
+ // JSON is stored in `nvarchar(max)`, so write it as a Unicode literal, otherwise non-Latin characters are lost
61
+ return context?.mode === 'hydration' || context?.mode === 'discovery' ? json : new UnicodeString(json);
62
+ }
59
63
  indexForeignKeys() {
60
64
  return false;
61
65
  }
@@ -29,12 +29,16 @@ export class MsSqlSchemaGenerator extends SchemaGenerator {
29
29
  }
30
30
  // https://stackoverflow.com/questions/253849/cannot-truncate-table-because-it-is-being-referenced-by-a-foreign-key-constraint
31
31
  for (const meta of this.getOrderedMetadataForClear(options?.schema).reverse()) {
32
- const res = await this.driver.nativeDelete(meta.class, {}, options);
33
- if (meta.getPrimaryProps().some(pk => pk.autoincrement)) {
32
+ await this.driver.nativeDelete(meta.class, {}, options);
33
+ // a table has at most one identity column: a TPT child's inherited PK references the parent instead, and a non-PK one is only reseeded when it declares `sequence`
34
+ const props = meta.tptParent ? (meta.ownProps ?? []) : meta.props;
35
+ const identity = props.find(prop => prop.autoincrement && (prop.primary || !!prop.sequence));
36
+ if (identity) {
34
37
  const tableName = this.driver.getTableName(meta, { schema: options?.schema }, false);
35
- await this.execute(`dbcc checkident ('${tableName}', reseed, ${res.affectedRows > 0 ? 0 : 1})`, {
36
- ctx: this.em?.getTransactionContext(),
37
- });
38
+ const { incrementBy = 1, startWith = incrementBy < 0 ? -1 : 1 } = identity.sequence ?? {};
39
+ // once the identity was used (`last_value` is set), the next value is the reseed value plus the table's actual increment
40
+ const lastValue = `(select last_value from sys.identity_columns where object_id = object_id('${tableName}'))`;
41
+ await this.execute(`declare @reseed bigint = case when ${lastValue} is null then ${startWith} else ${startWith} - ident_incr('${tableName}') end; dbcc checkident ('${tableName}', reseed, @reseed)`, { ctx: this.em?.getTransactionContext() });
38
42
  }
39
43
  }
40
44
  this.clearIdentityMap();
@@ -9,6 +9,10 @@ export declare class MsSqlSchemaHelper extends SchemaHelper {
9
9
  private static readonly AUTO_NOT_NULL_RE;
10
10
  protected get bracketQuotedIdentifiers(): boolean;
11
11
  getManagementDbName(): string;
12
+ getMigrationLockSQL(): {
13
+ acquire: string;
14
+ release: string;
15
+ };
12
16
  getDropDatabaseSQL(name: string): string;
13
17
  disableForeignKeysSQL(): string;
14
18
  enableForeignKeysSQL(): string;
@@ -20,7 +24,6 @@ export declare class MsSqlSchemaHelper extends SchemaHelper {
20
24
  normalizeDefaultValue(defaultValue: string, length: number, defaultValues?: Dictionary<string[]>, stripQuotes?: boolean): string | number;
21
25
  getAllColumns(connection: AbstractSqlConnection, tablesBySchemas: Map<string | undefined, Table[]>, ctx?: Transaction): Promise<Dictionary<Column[]>>;
22
26
  getAllIndexes(connection: AbstractSqlConnection, tablesBySchemas: Map<string | undefined, Table[]>, ctx?: Transaction): Promise<Dictionary<IndexDef[]>>;
23
- mapForeignKeys(fks: any[], tableName: string, schemaName?: string): Dictionary;
24
27
  getAllForeignKeys(connection: AbstractSqlConnection, tablesBySchemas: Map<string | undefined, Table[]>, ctx?: Transaction): Promise<Dictionary<Dictionary<ForeignKey>>>;
25
28
  private getEnumDefinitions;
26
29
  private getChecksSQL;
@@ -20,6 +20,14 @@ export class MsSqlSchemaHelper extends SchemaHelper {
20
20
  getManagementDbName() {
21
21
  return 'master';
22
22
  }
23
+ getMigrationLockSQL() {
24
+ // app locks are scoped to the current database; a zero timeout keeps the call clear of the request timeout
25
+ return {
26
+ acquire: `declare @result int; exec @result = sp_getapplock @Resource = ?, @LockMode = 'Exclusive', @LockOwner = 'Session', @LockTimeout = 0; ` +
27
+ `select case when @result >= 0 then 1 else 0 end as locked`,
28
+ release: `exec sp_releaseapplock @Resource = ?, @LockOwner = 'Session'`,
29
+ };
30
+ }
23
31
  getDropDatabaseSQL(name) {
24
32
  // `set offline` rejects all connections including the issuing session, so there is no
25
33
  // single-user race window where a torn-down pool connection can reconnect between the
@@ -85,17 +93,17 @@ export class MsSqlSchemaHelper extends SchemaHelper {
85
93
  return res.map(row => row.schema_name);
86
94
  }
87
95
  normalizeDefaultValue(defaultValue, length, defaultValues = {}, stripQuotes = false) {
88
- let match = /^\((.*)\)$/.exec(defaultValue);
96
+ let match = /^\((.*)\)$/s.exec(defaultValue);
89
97
  if (match) {
90
98
  defaultValue = match[1];
91
99
  }
92
- match = /^\((.*)\)$/.exec(defaultValue);
100
+ match = /^\((.*)\)$/s.exec(defaultValue);
93
101
  if (match) {
94
102
  defaultValue = match[1];
95
103
  }
96
- match = /^'(.*)'$/.exec(defaultValue);
104
+ match = /^'(.*)'$/s.exec(defaultValue);
97
105
  if (stripQuotes && match) {
98
- defaultValue = match[1];
106
+ defaultValue = match[1].replaceAll("''", "'");
99
107
  }
100
108
  return super.normalizeDefaultValue(defaultValue, length, MsSqlSchemaHelper.DEFAULT_VALUES);
101
109
  }
@@ -115,9 +123,12 @@ export class MsSqlSchemaHelper extends SchemaHelper {
115
123
  datetime_precision as datetime_precision,
116
124
  character_maximum_length as character_maximum_length,
117
125
  columnproperty(sc.object_id, column_name, 'IsIdentity') is_identity,
118
- nullif(ic.collation_name, convert(nvarchar(128), databasepropertyex(db_name(), 'Collation'))) as collation_name
126
+ nullif(ic.collation_name, convert(nvarchar(128), databasepropertyex(db_name(), 'Collation'))) as collation_name,
127
+ cast(idc.seed_value as bigint) as sequence_start,
128
+ cast(idc.increment_value as bigint) as sequence_increment
119
129
  from information_schema.columns ic
120
130
  inner join sys.columns sc on sc.name = ic.column_name and sc.object_id = object_id(ic.table_schema + '.' + ic.table_name)
131
+ left join sys.identity_columns idc on idc.object_id = sc.object_id and idc.column_id = sc.column_id
121
132
  left join sys.computed_columns cmp on cmp.name = ic.column_name and cmp.object_id = object_id(ic.table_schema + '.' + ic.table_name)
122
133
  left join sys.extended_properties t4 on t4.major_id = object_id(ic.table_schema + '.' + ic.table_name) and t4.name = 'MS_Description' and t4.minor_id = sc.column_id
123
134
  left join sys.default_constraints t5 on sc.default_object_id = t5.object_id
@@ -164,6 +175,7 @@ export class MsSqlSchemaHelper extends SchemaHelper {
164
175
  defaultConstraint: col.column_default_name,
165
176
  nullable: col.is_nullable === 'YES',
166
177
  autoincrement: increments,
178
+ sequence: increments ? this.getIntrospectedSequence(col.sequence_start, col.sequence_increment) : undefined,
167
179
  precision: col.numeric_precision,
168
180
  scale: col.numeric_scale,
169
181
  comment: col.column_comment,
@@ -254,26 +266,24 @@ export class MsSqlSchemaHelper extends SchemaHelper {
254
266
  }
255
267
  return ret;
256
268
  }
257
- mapForeignKeys(fks, tableName, schemaName) {
258
- const ret = super.mapForeignKeys(fks, tableName, schemaName);
259
- for (const fk of Utils.values(ret)) {
260
- fk.columnNames = Utils.unique(fk.columnNames);
261
- fk.referencedColumnNames = Utils.unique(fk.referencedColumnNames);
262
- }
263
- return ret;
264
- }
265
269
  async getAllForeignKeys(connection, tablesBySchemas, ctx) {
266
- const sql = `select ccu.constraint_name, ccu.table_name, ccu.table_schema schema_name, ccu.column_name,
267
- kcu.constraint_schema referenced_schema_name,
268
- kcu.column_name referenced_column_name,
269
- kcu.table_name referenced_table_name,
270
- rc.update_rule,
271
- rc.delete_rule
272
- from information_schema.constraint_column_usage ccu
273
- inner join information_schema.referential_constraints rc on ccu.constraint_name = rc.constraint_name and rc.constraint_schema = ccu.constraint_schema
274
- inner join information_schema.key_column_usage kcu on kcu.constraint_name = rc.unique_constraint_name and rc.unique_constraint_schema = kcu.constraint_schema
275
- where (${[...tablesBySchemas.entries()].map(([schema, tables]) => `(ccu.table_name in (${tables.map(t => this.platform.quoteValue(t.table_name)).join(',')}) and ccu.table_schema = '${schema}')`).join(' or ')})
276
- order by kcu.table_schema, kcu.table_name, kcu.ordinal_position, kcu.constraint_name`;
270
+ // `sys.foreign_key_columns` pairs local and referenced columns of composite FKs, `information_schema` can't
271
+ const sql = `select fk.name constraint_name, t.name table_name, s.name schema_name, c.name column_name,
272
+ rs.name referenced_schema_name,
273
+ rc.name referenced_column_name,
274
+ rt.name referenced_table_name,
275
+ replace(fk.update_referential_action_desc, '_', ' ') update_rule,
276
+ replace(fk.delete_referential_action_desc, '_', ' ') delete_rule
277
+ from sys.foreign_keys fk
278
+ inner join sys.foreign_key_columns fkc on fkc.constraint_object_id = fk.object_id
279
+ inner join sys.tables t on t.object_id = fk.parent_object_id
280
+ inner join sys.schemas s on s.schema_id = t.schema_id
281
+ inner join sys.columns c on c.object_id = fkc.parent_object_id and c.column_id = fkc.parent_column_id
282
+ inner join sys.tables rt on rt.object_id = fk.referenced_object_id
283
+ inner join sys.schemas rs on rs.schema_id = rt.schema_id
284
+ inner join sys.columns rc on rc.object_id = fkc.referenced_object_id and rc.column_id = fkc.referenced_column_id
285
+ where (${[...tablesBySchemas.entries()].map(([schema, tables]) => `(t.name in (${tables.map(t => this.platform.quoteValue(t.table_name)).join(',')}) and s.name = '${schema}')`).join(' or ')})
286
+ order by rs.name, rt.name, fkc.constraint_column_id, fk.name`;
277
287
  const allFks = await connection.execute(sql, [], 'all', ctx);
278
288
  const ret = {};
279
289
  for (const fk of allFks) {
@@ -660,9 +670,11 @@ export class MsSqlSchemaHelper extends SchemaHelper {
660
670
  col.push(columnType);
661
671
  }
662
672
  Utils.runIfNotEmpty(() => col.push(this.getCollateSQL(column.collation)), column.collation);
673
+ // a descending identity starts at -1 by default, same as on the other drivers
674
+ const { incrementBy = 1, startWith = incrementBy < 0 ? -1 : 1 } = column.sequence ?? {};
663
675
  // `IDENTITY(1,1)` is rejected inside `ALTER COLUMN`, so it must only be emitted when the
664
676
  // change actually involves the identity attribute or is a fresh column (no `changedProperties`).
665
- Utils.runIfNotEmpty(() => col.push('identity(1,1)'), column.autoincrement &&
677
+ Utils.runIfNotEmpty(() => col.push(`identity(${startWith},${incrementBy})`), column.autoincrement &&
666
678
  (!changedProperties || changedProperties.has('autoincrement') || changedProperties.has('type')));
667
679
  Utils.runIfNotEmpty(() => col.push('null'), column.nullable);
668
680
  Utils.runIfNotEmpty(() => col.push('not null'), !column.nullable && !column.generated);
@@ -760,7 +772,7 @@ export class MsSqlSchemaHelper extends SchemaHelper {
760
772
  }
761
773
  createIndex(index, table, createPrimary = false) {
762
774
  if (index.primary) {
763
- return '';
775
+ return createPrimary ? super.createIndex(index, table, true) : '';
764
776
  }
765
777
  if (index.expression) {
766
778
  return index.expression;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mikro-orm/mssql",
3
- "version": "7.3.0-dev.2",
3
+ "version": "7.3.0-dev.20",
4
4
  "description": "TypeScript ORM for Node.js based on Data Mapper, Unit of Work and Identity Map patterns. Supports MongoDB, MySQL, PostgreSQL and SQLite databases as well as usage with vanilla JavaScript.",
5
5
  "keywords": [
6
6
  "data-mapper",
@@ -47,17 +47,17 @@
47
47
  "copy": "node ../../scripts/copy.mjs"
48
48
  },
49
49
  "dependencies": {
50
- "@mikro-orm/sql": "7.3.0-dev.2",
51
- "kysely": "0.29.6",
50
+ "@mikro-orm/sql": "7.3.0-dev.20",
51
+ "kysely": "0.29.8",
52
52
  "tarn": "3.1.2",
53
- "tedious": "20.0.0",
53
+ "tedious": "20.3.8",
54
54
  "tsqlstring": "1.0.1"
55
55
  },
56
56
  "devDependencies": {
57
- "@mikro-orm/core": "^7.2.1"
57
+ "@mikro-orm/core": "^7.2.7"
58
58
  },
59
59
  "peerDependencies": {
60
- "@mikro-orm/core": "7.3.0-dev.2"
60
+ "@mikro-orm/core": "7.3.0-dev.20"
61
61
  },
62
62
  "engines": {
63
63
  "node": ">= 22.17.0"