@mikro-orm/sql 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.
Files changed (41) hide show
  1. package/AbstractSqlConnection.js +11 -0
  2. package/AbstractSqlDriver.d.ts +10 -0
  3. package/AbstractSqlDriver.js +133 -64
  4. package/AbstractSqlPlatform.js +1 -1
  5. package/SqlEntityManager.js +2 -1
  6. package/dialects/mysql/BaseMySqlPlatform.d.ts +3 -0
  7. package/dialects/mysql/BaseMySqlPlatform.js +7 -0
  8. package/dialects/mysql/MySqlSchemaHelper.d.ts +8 -0
  9. package/dialects/mysql/MySqlSchemaHelper.js +33 -2
  10. package/dialects/postgresql/BasePostgreSqlPlatform.d.ts +1 -0
  11. package/dialects/postgresql/BasePostgreSqlPlatform.js +3 -0
  12. package/dialects/postgresql/PostgreSqlExceptionConverter.js +1 -0
  13. package/dialects/postgresql/PostgreSqlSchemaHelper.d.ts +7 -0
  14. package/dialects/postgresql/PostgreSqlSchemaHelper.js +159 -18
  15. package/dialects/sqlite/SqlitePlatform.d.ts +3 -1
  16. package/dialects/sqlite/SqlitePlatform.js +12 -0
  17. package/dialects/sqlite/SqliteSchemaHelper.d.ts +2 -0
  18. package/dialects/sqlite/SqliteSchemaHelper.js +32 -9
  19. package/package.json +4 -4
  20. package/plugin/transformer.d.ts +2 -1
  21. package/plugin/transformer.js +39 -13
  22. package/query/CriteriaNode.d.ts +1 -0
  23. package/query/CriteriaNode.js +12 -3
  24. package/query/CriteriaNodeFactory.js +1 -1
  25. package/query/NativeQueryBuilder.d.ts +2 -0
  26. package/query/NativeQueryBuilder.js +18 -3
  27. package/query/ObjectCriteriaNode.d.ts +2 -0
  28. package/query/ObjectCriteriaNode.js +46 -20
  29. package/query/QueryBuilder.d.ts +8 -3
  30. package/query/QueryBuilder.js +78 -40
  31. package/query/QueryBuilderHelper.d.ts +2 -0
  32. package/query/QueryBuilderHelper.js +58 -21
  33. package/schema/DatabaseTable.js +34 -8
  34. package/schema/SchemaComparator.d.ts +1 -1
  35. package/schema/SchemaComparator.js +35 -22
  36. package/schema/SchemaHelper.d.ts +25 -1
  37. package/schema/SchemaHelper.js +68 -5
  38. package/schema/SqlSchemaGenerator.d.ts +7 -4
  39. package/schema/SqlSchemaGenerator.js +29 -10
  40. package/schema/partitioning.js +6 -6
  41. package/typings.d.ts +3 -1
@@ -1,4 +1,4 @@
1
- import { DecimalType, EntitySchema, isRaw, ReferenceKind, t, Type, UnknownType, Utils, } from '@mikro-orm/core';
1
+ import { DecimalType, EntitySchema, isRaw, MetadataError, ReferenceKind, t, Type, UnknownType, Utils, } from '@mikro-orm/core';
2
2
  import { toEntityPartitionBy } from './partitioning.js';
3
3
  /**
4
4
  * @internal
@@ -155,6 +155,7 @@ export class DatabaseTable {
155
155
  comment: prop.comment,
156
156
  collation: prop.collation,
157
157
  extra: prop.extra,
158
+ sequence: prop.sequence,
158
159
  ignoreSchemaChanges: prop.ignoreSchemaChanges,
159
160
  };
160
161
  this.#columns[field].unsigned ??= this.#columns[field].autoincrement;
@@ -760,6 +761,10 @@ export class DatabaseTable {
760
761
  !idx.primary &&
761
762
  !idx.where &&
762
763
  !this.hasAdvancedIndexOptions(idx));
764
+ // `getMappedType('timestamptz(3)[]')` resolves to the element type so diffing keeps the modifier, but the property is still an array
765
+ if (column.type?.endsWith('[]') && !column.enumItems?.length) {
766
+ column = { ...column, mappedType: Type.getType(t.array) };
767
+ }
763
768
  const kind = this.getReferenceKind(fk, unique);
764
769
  const runtimeType = this.getPropertyTypeForColumn(namingStrategy, column, fk);
765
770
  const type = fk
@@ -796,6 +801,7 @@ export class DatabaseTable {
796
801
  nullable: column.nullable,
797
802
  primary: column.primary && persist,
798
803
  autoincrement: column.autoincrement,
804
+ sequence: column.sequence,
799
805
  fieldName: column.name,
800
806
  unsigned: column.unsigned,
801
807
  length: column.length,
@@ -876,9 +882,9 @@ export class DatabaseTable {
876
882
  return +defaultValue;
877
883
  }
878
884
  // unquote string defaults if `raw = false`
879
- const match = /^'(.*)'$/.exec('' + val);
885
+ const match = /^'(.*)'$/s.exec('' + val);
880
886
  if (!raw && match) {
881
- return match[1];
887
+ return schemaHelper.unescapeDefault(match[1]);
882
888
  }
883
889
  return '' + val;
884
890
  }
@@ -924,6 +930,17 @@ export class DatabaseTable {
924
930
  };
925
931
  return [expand(rootProp, 1)];
926
932
  }
933
+ // object embedded property index, the JSON keys are the field names of the embedded properties
934
+ if (rootProp?.embeddable && rootProp.object && rootProp.embeddedProps[parts[1]]) {
935
+ let p = rootProp.embeddedProps[parts[1]];
936
+ let i = 2;
937
+ while (i < parts.length && p.embeddedProps?.[parts[i]]) {
938
+ p = p.embeddedProps[parts[i]];
939
+ i++;
940
+ }
941
+ // a path below the last embedded property targets plain JSON keys, kept as they are
942
+ return [[...p.embeddedPath, ...parts.slice(i)].join('.')];
943
+ }
927
944
  // json index, we need to rename the column only
928
945
  if (rootProp) {
929
946
  return [prop.replace(root, rootProp.fieldNames[0])];
@@ -960,32 +977,41 @@ export class DatabaseTable {
960
977
  if (columns?.length && properties.length > 0) {
961
978
  for (const col of columns) {
962
979
  if (!properties.includes(col.name)) {
963
- throw new Error(`Index '${name}' on entity '${meta.className}': column option references field '${col.name}' which is not in the index properties`);
980
+ throw new MetadataError(`Index '${name}' on entity '${meta.className}': column option references field '${col.name}' which is not in the index properties`);
964
981
  }
965
982
  }
966
983
  }
967
984
  // Validate fillFactor range
968
985
  if (index.fillFactor != null && (index.fillFactor < 0 || index.fillFactor > 100)) {
969
- throw new Error(`fillFactor must be between 0 and 100, got ${index.fillFactor} for index '${name}' on entity '${meta.className}'`);
986
+ throw new MetadataError(`fillFactor must be between 0 and 100, got ${index.fillFactor} for index '${name}' on entity '${meta.className}'`);
970
987
  }
971
988
  // The `expression` escape hatch takes the full index definition as raw SQL; combining it
972
989
  // with `where` is dialect-dependent (PG/Oracle/MySQL drop `where`, MSSQL appends it) so we
973
990
  // reject the combination up-front and ask users to inline the predicate into `expression`.
974
991
  if (index.expression && index.where != null) {
975
- throw new Error(`Index '${name}' on entity '${meta.className}': cannot combine \`expression\` with \`where\` — inline the WHERE clause into the \`expression\` escape hatch, or drop \`expression\` and use structured \`properties\` + \`where\`.`);
992
+ throw new MetadataError(`Index '${name}' on entity '${meta.className}': cannot combine \`expression\` with \`where\` — inline the WHERE clause into the \`expression\` escape hatch, or drop \`expression\` and use structured \`properties\` + \`where\`.`);
993
+ }
994
+ // `where` forces the `create unique index` form, and no dialect accepts `deferrable` on an index.
995
+ if (index.where != null && index.deferMode) {
996
+ throw new MetadataError(`Index '${name}' on entity '${meta.className}': cannot combine \`deferMode\` with \`where\` — partial unique indexes cannot be deferrable. On PostgreSQL, declare an exclusion constraint instead, e.g. \`exclude using btree (col with =) where (...) deferrable initially ${index.deferMode}\`.`);
976
997
  }
977
998
  const where = this.processIndexWhere(index.where, meta);
999
+ const expression = this.processIndexExpression(name, index.expression, meta);
978
1000
  this.#indexes.push({
979
1001
  keyName: name,
980
1002
  columnNames: properties,
981
1003
  composite: properties.length > 1,
982
1004
  // JSON columns can have unique index but not unique constraint, and we need to distinguish those, so we can properly drop them.
983
1005
  // Partial indexes (`where`) must use CREATE [UNIQUE] INDEX form — constraints can't carry predicates.
984
- constraint: type !== 'index' && !properties.some((d) => d.includes('.')) && !where,
1006
+ // Raw `create [unique] index` expressions are plain indexes, not constraints.
1007
+ constraint: type !== 'index' &&
1008
+ !properties.some((d) => d.includes('.')) &&
1009
+ !where &&
1010
+ !/^\s*create\s/i.test(expression ?? ''),
985
1011
  primary: type === 'primary',
986
1012
  unique: type !== 'index',
987
1013
  type: index.type,
988
- expression: this.processIndexExpression(name, index.expression, meta),
1014
+ expression,
989
1015
  where,
990
1016
  options: index.options,
991
1017
  deferMode: index.deferMode,
@@ -30,7 +30,7 @@ export declare class SchemaComparator {
30
30
  * Returns the difference between the tables fromTable and toTable.
31
31
  * If there are no differences this method returns the boolean false.
32
32
  */
33
- diffTable(fromTable: DatabaseTable, toTable: DatabaseTable, inverseTableDiff?: TableDifference): TableDifference | false;
33
+ diffTable(fromTable: DatabaseTable, toTable: DatabaseTable, inverseTableDiff?: TableDifference, inverse?: boolean): TableDifference | false;
34
34
  /**
35
35
  * Try to find columns that only changed their name, rename operations maybe cheaper than add/drop
36
36
  * however ambiguities between different possibilities should not lead to renaming at all.
@@ -77,7 +77,7 @@ export class SchemaComparator {
77
77
  diff.newTables[tableName] = toSchema.getTable(tableName);
78
78
  }
79
79
  else {
80
- const tableDifferences = this.diffTable(fromSchema.getTable(tableName), toSchema.getTable(tableName), inverseDiff?.changedTables[tableName]);
80
+ const tableDifferences = this.diffTable(fromSchema.getTable(tableName), toSchema.getTable(tableName), inverseDiff?.changedTables[tableName], !!inverseDiff);
81
81
  if (tableDifferences !== false) {
82
82
  diff.changedTables[tableName] = tableDifferences;
83
83
  }
@@ -166,11 +166,12 @@ export class SchemaComparator {
166
166
  diff.changedTables[viewName] = tableDiff;
167
167
  }
168
168
  }
169
- this.compareRoutines(fromSchema, toSchema, diff);
169
+ this.compareRoutines(fromSchema, toSchema, diff, !!inverseDiff);
170
170
  return diff;
171
171
  }
172
- compareRoutines(fromSchema, toSchema, diff) {
172
+ compareRoutines(fromSchema, toSchema, diff, inverse) {
173
173
  // `ignoreRoutines` makes routines create-only: new ones are still added, but existing routines are never diffed for drop/alter.
174
+ // The down diff (`inverse`) mirrors that: it drops what `up` created and never recreates routines unknown to the metadata.
174
175
  const ignoreRoutines = this.#platform.getConfig().get('schemaGenerator').ignoreRoutines;
175
176
  // Case-fold so user-written `'sql_hash'` matches Oracle's introspected `'SQL_HASH'`.
176
177
  const routineKey = (r) => ((r.schema ? `${r.schema}.` : '') + r.name).toLowerCase();
@@ -179,6 +180,9 @@ export class SchemaComparator {
179
180
  for (const [key, toRoutine] of toByKey) {
180
181
  const fromRoutine = fromByKey.get(key);
181
182
  if (!fromRoutine) {
183
+ if (ignoreRoutines && inverse) {
184
+ continue;
185
+ }
182
186
  diff.newRoutines[key] = toRoutine;
183
187
  this.log(`routine ${key} added`);
184
188
  continue;
@@ -188,7 +192,7 @@ export class SchemaComparator {
188
192
  this.log(`routine ${key} changed`, { fromRoutine, toRoutine });
189
193
  }
190
194
  }
191
- if (!ignoreRoutines) {
195
+ if (!ignoreRoutines || inverse) {
192
196
  for (const [key, fromRoutine] of fromByKey) {
193
197
  if (!toByKey.has(key)) {
194
198
  diff.removedRoutines[key] = fromRoutine;
@@ -319,7 +323,7 @@ export class SchemaComparator {
319
323
  * Returns the difference between the tables fromTable and toTable.
320
324
  * If there are no differences this method returns the boolean false.
321
325
  */
322
- diffTable(fromTable, toTable, inverseTableDiff) {
326
+ diffTable(fromTable, toTable, inverseTableDiff, inverse = false) {
323
327
  let changes = 0;
324
328
  const tableDifferences = {
325
329
  name: fromTable.getShortestName(),
@@ -353,7 +357,9 @@ export class SchemaComparator {
353
357
  });
354
358
  changes++;
355
359
  }
356
- if (diffPartitioning(fromTable.getPartitioning(), toTable.getPartitioning(), this.#platform.getDefaultSchemaName())) {
360
+ // partitioning is diffed one way (declared vs. existing), so the down diff has to compare it like the up one did
361
+ const [existingTable, declaredTable] = inverse ? [toTable, fromTable] : [fromTable, toTable];
362
+ if (diffPartitioning(existingTable.getPartitioning(), declaredTable.getPartitioning(), this.#platform.getDefaultSchemaName())) {
357
363
  tableDifferences.changedPartitioning = {
358
364
  from: fromTable.getPartitioning(),
359
365
  to: toTable.getPartitioning(),
@@ -477,8 +483,10 @@ export class SchemaComparator {
477
483
  if (!this.diffExpression(check.expression, toTableCheck.expression)) {
478
484
  continue;
479
485
  }
486
+ // only auto-generated enum checks, a user check tagged with an enum column must be diffed by expression
480
487
  if (fromColumn?.enumItems &&
481
488
  toColumn?.enumItems &&
489
+ check.name === this.#platform.getIndexName(fromTable.name, [fromColumn.name], 'check') &&
482
490
  !this.diffEnumItems(fromColumn.enumItems, toColumn.enumItems)) {
483
491
  continue;
484
492
  }
@@ -489,10 +497,12 @@ export class SchemaComparator {
489
497
  tableDifferences.changedChecks[check.name] = toTableCheck;
490
498
  changes++;
491
499
  }
500
+ const ignoreTriggers = this.#platform.getConfig().get('schemaGenerator').ignoreTriggers;
492
501
  const fromTableTriggers = fromTable.getTriggers();
493
502
  const toTableTriggers = toTable.getTriggers();
494
503
  for (const trigger of toTableTriggers) {
495
- if (fromTable.hasTrigger(trigger.name)) {
504
+ // see `compareRoutines` for how `ignoreTriggers` applies to the down diff
505
+ if (fromTable.hasTrigger(trigger.name) || (ignoreTriggers && inverse)) {
496
506
  continue;
497
507
  }
498
508
  tableDifferences.addedTriggers[trigger.name] = trigger;
@@ -500,7 +510,7 @@ export class SchemaComparator {
500
510
  changes++;
501
511
  }
502
512
  // `ignoreTriggers` makes triggers create-only: declared ones are still added above, but existing triggers are never diffed for drop/alter.
503
- if (!this.#platform.getConfig().get('schemaGenerator').ignoreTriggers) {
513
+ if (!ignoreTriggers || inverse) {
504
514
  for (const trigger of fromTableTriggers) {
505
515
  if (!toTable.hasTrigger(trigger.name)) {
506
516
  tableDifferences.removedTriggers[trigger.name] = trigger;
@@ -509,7 +519,7 @@ export class SchemaComparator {
509
519
  continue;
510
520
  }
511
521
  const toTableTrigger = toTable.getTrigger(trigger.name);
512
- if (this.diffTrigger(trigger, toTableTrigger)) {
522
+ if (!ignoreTriggers && this.diffTrigger(trigger, toTableTrigger)) {
513
523
  this.log(`trigger ${trigger.name} changed in table ${tableDifferences.name}`, {
514
524
  fromTableTrigger: trigger,
515
525
  toTableTrigger,
@@ -708,7 +718,9 @@ export class SchemaComparator {
708
718
  log(`'nullable' changed for column ${fromTable.name}.${fromColumn.name}`, { fromColumn, toColumn });
709
719
  changedProperties.add('nullable');
710
720
  }
711
- if (this.diffExpression(fromColumn.generated, toColumn.generated)) {
721
+ // identity options (start/increment) are applied on create only, same as the `sequence` option
722
+ const withoutIdentityOptions = (generated) => generated?.replace(/^((?:by default as )?identity)\s*\(.*\)$/is, '$1');
723
+ if (this.diffExpression(withoutIdentityOptions(fromColumn.generated), withoutIdentityOptions(toColumn.generated))) {
712
724
  log(`'generated' changed for column ${fromTable.name}.${fromColumn.name}`, { fromColumn, toColumn });
713
725
  changedProperties.add('generated');
714
726
  }
@@ -856,16 +868,10 @@ export class SchemaComparator {
856
868
  if (cols1.length === 0 && cols2.length === 0) {
857
869
  return true;
858
870
  }
859
- // If only one has column options, they don't match
860
- if (cols1.length !== cols2.length) {
861
- return false;
862
- }
863
- // Compare each column's options
864
- // Note: We don't check c1.name !== c2.name because the indexes already have matching columnNames
865
- // and the columns array is derived from those same column names
866
- for (let i = 0; i < cols1.length; i++) {
867
- const c1 = cols1[i];
868
- const c2 = cols2[i];
871
+ // introspection may omit entries for columns with default options, so match them by name
872
+ for (const name of index1.columnNames) {
873
+ const c1 = cols1.find(c => c.name === name) ?? { name };
874
+ const c2 = cols2.find(c => c.name === name) ?? { name };
869
875
  const sort1 = c1.sort?.toUpperCase() ?? 'ASC';
870
876
  const sort2 = c2.sort?.toUpperCase() ?? 'ASC';
871
877
  if (sort1 !== sort2) {
@@ -902,11 +908,16 @@ export class SchemaComparator {
902
908
  // expressions like check constraints might be normalized by the driver,
903
909
  // e.g. quotes might be added (https://github.com/mikro-orm/mikro-orm/issues/3827)
904
910
  const simplify = (str) => {
905
- return (str
911
+ if (str == null) {
912
+ return str;
913
+ }
914
+ return (this.#helper
915
+ .normalizeExpression(str)
906
916
  // lookbehind: only strip a real charset introducer, never an underscore inside a literal like 'a_b'
907
- ?.replace(/(?<![\w'])_\w+'(.*?)'/g, '$1')
917
+ .replace(/(?<![\w'])_\w+'(.*?)'/g, '$1')
908
918
  .replace(/!=/g, '<>')
909
919
  // `\b` keeps this from firing inside identifiers like `min(...)`
920
+ .replace(/\bnot\s+in\s*\((.*?)\)/gi, '<> all (array[$1])')
910
921
  .replace(/\bin\s*\((.*?)\)/gi, '= any (array[$1])')
911
922
  // MySQL normalizes count(*) to count(0)
912
923
  .replace(/\bcount\s*\(\s*0\s*\)/gi, 'count(*)')
@@ -922,6 +933,8 @@ export class SchemaComparator {
922
933
  // MySQL adds table/alias prefixes to columns (e.g., a.name or table_name.column vs just column)
923
934
  // Strip these prefixes - match word.word patterns and keep only the last part
924
935
  .replace(/\b\w+\.(\w+)/g, '$1')
936
+ // PostgreSQL rewrites `x [not] between a and b` to `x >= a and x <= b` (`x < a or x > b`), cast targets are skipped
937
+ .replace(/(?<!::\s*)\b(?!not\b)(\w+)\s+(not\s+)?between\s+(\S+)\s+and\s+(\S+)/gi, (_, x, not, a, b) => not ? `${x} < ${a} or ${x} > ${b}` : `${x} >= ${a} and ${x} <= ${b}`)
925
938
  // Normalize JOIN syntax: inner join -> join (equivalent in SQL)
926
939
  .replace(/\binner\s+join\b/gi, 'join')
927
940
  // PostgreSQL names an unaliased bare function call after the function itself,
@@ -1,4 +1,4 @@
1
- import { type Connection, type Dictionary, type Options, type Transaction, type RawQueryFragment } from '@mikro-orm/core';
1
+ import { type Connection, type Dictionary, type Options, type Transaction, type RawQueryFragment, type SequenceOptions } from '@mikro-orm/core';
2
2
  import type { AbstractSqlConnection } from '../AbstractSqlConnection.js';
3
3
  import type { AbstractSqlPlatform } from '../AbstractSqlPlatform.js';
4
4
  import type { CheckDef, Column, ForeignKey, IndexDef, Table, TableDifference, SqlTriggerDef, SqlRoutineDef } from '../typings.js';
@@ -33,6 +33,8 @@ export declare abstract class SchemaHelper {
33
33
  disableForeignKeysSQL(): string;
34
34
  /** Returns SQL to re-enable foreign key checks. */
35
35
  enableForeignKeysSQL(): string;
36
+ /** Returns SQL listing rows that violate foreign keys; when non-empty, migrations run with FK checks off and verify afterwards (SQLite). */
37
+ getForeignKeyCheckSQL(): string;
36
38
  /** Returns SQL to append to schema migration scripts (e.g., re-enabling FK checks). */
37
39
  getSchemaEnd(disableForeignKeys?: boolean): string;
38
40
  /** Sets the current schema for the session (e.g. `SET search_path`). */
@@ -41,10 +43,25 @@ export declare abstract class SchemaHelper {
41
43
  supportsMigrationSchema(): boolean;
42
44
  /** Restores the session's schema to the connection's default after a migration. */
43
45
  getResetSchemaSQL(_defaultSchema: string): string;
46
+ /**
47
+ * Returns the SQL to try taking (without waiting) and to release the session-level lock serializing migration runs,
48
+ * with `name` bound as the only parameter. The try query returns a truthy `locked` column when the lock was taken.
49
+ * `undefined` means the driver has no lock primitive and runs are not serialized.
50
+ */
51
+ getMigrationLockSQL(): {
52
+ acquire: string;
53
+ release: string;
54
+ } | undefined;
44
55
  /** Returns `undefined` for schemaless drivers, throws for drivers that have schemas but no session switch. */
45
56
  resolveMigrationSchema(schema: string | undefined): string | undefined;
46
57
  finalizeTable(table: DatabaseTable, charset: string, collate?: string): string;
47
58
  appendComments(table: DatabaseTable): string[];
59
+ /** Returns SQL that moves the autoincrement counter back to `sequence.startWith` after `clear()` truncated the table. */
60
+ getResetSequenceSQL(tableName: string, schemaName: string | undefined, columnName: string, startWith: number): string;
61
+ /** Maps the introspected start and increment of an autoincrement column to its `sequence` option, omitting defaults. */
62
+ protected getIntrospectedSequence(start: unknown, increment: unknown): SequenceOptions | undefined;
63
+ /** Renders the `start with … increment by …` clause for the `sequence` option of an autoincrement column. */
64
+ protected getSequenceOptionsSQL(column: Column): string;
48
65
  supportsSchemaConstraints(): boolean;
49
66
  getPrimaryKeys(connection: AbstractSqlConnection, indexes: IndexDef[] | undefined, tableName: string, schemaName?: string): Promise<string[]>;
50
67
  inferLengthFromColumnType(type: string): number | undefined;
@@ -163,6 +180,13 @@ export declare abstract class SchemaHelper {
163
180
  getNamespaces(connection: AbstractSqlConnection, ctx?: Transaction): Promise<string[]>;
164
181
  protected mapIndexes(indexes: IndexDef[]): Promise<IndexDef[]>;
165
182
  mapForeignKeys(fks: any[], tableName: string, schemaName?: string): Dictionary;
183
+ /**
184
+ * Rewrites the parts of a user-provided expression the database stores in a different form, so that
185
+ * `SchemaComparator.diffExpression()` compares it to the introspected definition on equal footing.
186
+ */
187
+ normalizeExpression(expr: string): string;
188
+ /** Decodes the content of an introspected string literal, the inverse of `Platform.quoteDefaultValue()`. */
189
+ unescapeDefault(val: string): string;
166
190
  normalizeDefaultValue(defaultValue: string | RawQueryFragment, length?: number, defaultValues?: Dictionary<string[]>): string | number;
167
191
  getCreateDatabaseSQL(name: string): string;
168
192
  getDropDatabaseSQL(name: string): string;
@@ -52,6 +52,10 @@ export class SchemaHelper {
52
52
  enableForeignKeysSQL() {
53
53
  return '';
54
54
  }
55
+ /** Returns SQL listing rows that violate foreign keys; when non-empty, migrations run with FK checks off and verify afterwards (SQLite). */
56
+ getForeignKeyCheckSQL() {
57
+ return '';
58
+ }
55
59
  /** Returns SQL to append to schema migration scripts (e.g., re-enabling FK checks). */
56
60
  getSchemaEnd(disableForeignKeys) {
57
61
  if (disableForeignKeys) {
@@ -71,6 +75,14 @@ export class SchemaHelper {
71
75
  getResetSchemaSQL(_defaultSchema) {
72
76
  return '';
73
77
  }
78
+ /**
79
+ * Returns the SQL to try taking (without waiting) and to release the session-level lock serializing migration runs,
80
+ * with `name` bound as the only parameter. The try query returns a truthy `locked` column when the lock was taken.
81
+ * `undefined` means the driver has no lock primitive and runs are not serialized.
82
+ */
83
+ getMigrationLockSQL() {
84
+ return undefined;
85
+ }
74
86
  /** Returns `undefined` for schemaless drivers, throws for drivers that have schemas but no session switch. */
75
87
  resolveMigrationSchema(schema) {
76
88
  if (!schema) {
@@ -91,6 +103,38 @@ export class SchemaHelper {
91
103
  appendComments(table) {
92
104
  return [];
93
105
  }
106
+ /** Returns SQL that moves the autoincrement counter back to `sequence.startWith` after `clear()` truncated the table. */
107
+ /* v8 ignore next */
108
+ getResetSequenceSQL(tableName, schemaName, columnName, startWith) {
109
+ return '';
110
+ }
111
+ /** Maps the introspected start and increment of an autoincrement column to its `sequence` option, omitting defaults. */
112
+ getIntrospectedSequence(start, increment) {
113
+ if (start == null) {
114
+ return undefined;
115
+ }
116
+ const incrementBy = Number(increment ?? 1);
117
+ const startWith = Number(start);
118
+ const sequence = {};
119
+ if (startWith !== (incrementBy < 0 ? -1 : 1)) {
120
+ sequence.startWith = startWith;
121
+ }
122
+ if (incrementBy !== 1) {
123
+ sequence.incrementBy = incrementBy;
124
+ }
125
+ return Utils.hasObjectKeys(sequence) ? sequence : undefined;
126
+ }
127
+ /** Renders the `start with … increment by …` clause for the `sequence` option of an autoincrement column. */
128
+ getSequenceOptionsSQL(column) {
129
+ const { startWith, incrementBy } = column.sequence ?? {};
130
+ const descending = incrementBy != null && incrementBy < 0;
131
+ // a sequence is bounded by 1 (ascending) or -1 (descending) by default, a start beyond that has to move the bound
132
+ const bound = startWith != null &&
133
+ (descending ? startWith > -1 && `maxvalue ${startWith}` : startWith < 1 && `minvalue ${startWith}`);
134
+ return [startWith != null && `start with ${startWith}`, incrementBy != null && `increment by ${incrementBy}`, bound]
135
+ .filter(Boolean)
136
+ .join(' ');
137
+ }
94
138
  supportsSchemaConstraints() {
95
139
  return true;
96
140
  }
@@ -474,10 +518,16 @@ export class SchemaHelper {
474
518
  for (const foreignKey of Object.values(diff.changedForeignKeys)) {
475
519
  ret.push(this.createForeignKey(diff.toTable, foreignKey));
476
520
  }
477
- for (const index of Object.values(diff.addedIndexes)) {
478
- ret.push(this.createIndex(index, diff.toTable));
479
- }
480
- for (const index of Object.values(diff.changedIndexes)) {
521
+ for (const index of [...Object.values(diff.addedIndexes), ...Object.values(diff.changedIndexes)]) {
522
+ const addedColumn = diff.addedColumns[index.columnNames[0]];
523
+ // an added autoincrement PK column already declares the primary key inline
524
+ if (index.primary &&
525
+ !index.composite &&
526
+ addedColumn?.autoincrement &&
527
+ addedColumn.primary &&
528
+ !this.hasNonDefaultPrimaryKeyName(diff.toTable)) {
529
+ continue;
530
+ }
481
531
  ret.push(this.createIndex(index, diff.toTable, true));
482
532
  }
483
533
  for (const [oldIndexName, index] of Object.entries(diff.renamedIndexes)) {
@@ -608,6 +658,8 @@ export class SchemaHelper {
608
658
  }
609
659
  if (useDefault) {
610
660
  // https://dev.mysql.com/doc/refman/9.0/en/data-type-defaults.html
661
+ // `tinytext`, `mediumtext`, `longblob` etc. follow the same rule as `text` and `blob`
662
+ const baseType = column.type.toLowerCase().replace(/^(tiny|medium|long)/, '');
611
663
  const needsExpression = [
612
664
  'blob',
613
665
  'text',
@@ -619,7 +671,7 @@ export class SchemaHelper {
619
671
  'multilinestring',
620
672
  'multipolygon',
621
673
  'geometrycollection',
622
- ].some(type => column.type.toLowerCase().startsWith(type));
674
+ ].some(type => baseType.startsWith(type));
623
675
  const defaultSql = needsExpression && !column.default.startsWith('(') ? `(${column.default})` : column.default;
624
676
  col.push(`default ${defaultSql}`);
625
677
  }
@@ -710,6 +762,17 @@ export class SchemaHelper {
710
762
  return ret;
711
763
  }, {});
712
764
  }
765
+ /**
766
+ * Rewrites the parts of a user-provided expression the database stores in a different form, so that
767
+ * `SchemaComparator.diffExpression()` compares it to the introspected definition on equal footing.
768
+ */
769
+ normalizeExpression(expr) {
770
+ return expr;
771
+ }
772
+ /** Decodes the content of an introspected string literal, the inverse of `Platform.quoteDefaultValue()`. */
773
+ unescapeDefault(val) {
774
+ return val.replaceAll("''", "'");
775
+ }
713
776
  normalizeDefaultValue(defaultValue, length, defaultValues = {}) {
714
777
  if (defaultValue == null) {
715
778
  return defaultValue;
@@ -38,10 +38,13 @@ export declare class SqlSchemaGenerator extends AbstractSchemaGenerator<Abstract
38
38
  schema?: string;
39
39
  }): string;
40
40
  /**
41
- * We need to drop foreign keys first for all tables to allow dropping PK constraints.
41
+ * Collects foreign keys from other tables that reference `table` (self-references are excluded — those travel with the rebuild).
42
+ * Foreign keys the referencing table drops or changes in the same diff are left to its own alter, and those of dropped tables are skipped.
42
43
  */
43
- /** Collects foreign keys from other tables that reference `table` (self-references are excluded — those travel with the rebuild). */
44
44
  private getInboundForeignKeys;
45
+ /**
46
+ * We need to drop foreign keys first for all tables to allow dropping PK constraints.
47
+ */
45
48
  private preAlterTable;
46
49
  /**
47
50
  * creates new database and connects to it
@@ -56,8 +59,8 @@ export declare class SqlSchemaGenerator extends AbstractSchemaGenerator<Abstract
56
59
  }): Promise<void>;
57
60
  /** Splits the SQL on the separator, keeping the separators that fall inside a string literal. */
58
61
  private splitOutsideLiterals;
59
- /** Whether the statement has to be the first one in a query batch, e.g. `create trigger` on MSSQL. */
60
- protected startsBatch(_statement: string): boolean;
62
+ /** Whether the statement has to be the first one in a query batch, e.g. `create trigger` on MSSQL. `previous` is the line before it in the current batch. */
63
+ protected startsBatch(_statement: string, _previous: string): boolean;
61
64
  dropTableIfExists(name: string, schema?: string): Promise<void>;
62
65
  private wrapSchema;
63
66
  private append;
@@ -141,6 +141,14 @@ export class SqlSchemaGenerator extends AbstractSchemaGenerator {
141
141
  .withSchema(schema)
142
142
  .truncate()
143
143
  .execute();
144
+ // the counters of a TPT child's inherited columns (PK included) belong to the parent table
145
+ const props = meta.tptParent ? (meta.ownProps ?? []) : meta.props;
146
+ for (const prop of props.filter(prop => prop.autoincrement && prop.sequence?.startWith != null)) {
147
+ const sql = this.helper.getResetSequenceSQL(meta.tableName, this.getSchemaName(meta, { schema }), prop.fieldNames[0], prop.sequence.startWith);
148
+ if (sql) {
149
+ await this.execute(sql, { ctx: this.em?.getTransactionContext() });
150
+ }
151
+ }
144
152
  }
145
153
  catch (e) {
146
154
  if (this.platform.getExceptionConverter().convertException(e) instanceof TableNotFoundException) {
@@ -327,14 +335,16 @@ export class SqlSchemaGenerator extends AbstractSchemaGenerator {
327
335
  // Tables whose partitioning was added/changed can't be altered in place — they are rebuilt as a unit
328
336
  // (the helper handles the data-preserving swap), so keep them out of the regular alter passes.
329
337
  const changedTables = Object.values(schemaDiff.changedTables);
338
+ const dropsTables = !!options.dropTables && !options.safe;
330
339
  const partitioningRebuilds = changedTables
331
340
  .filter(changedTable => changedTable.changedPartitioning)
332
- .map(diff => ({ diff, inboundForeignKeys: this.getInboundForeignKeys(schemaDiff.fromSchema, diff.toTable) }));
341
+ .map(diff => ({ diff, inboundForeignKeys: this.getInboundForeignKeys(schemaDiff, diff.toTable, dropsTables) }));
333
342
  const alteredTables = changedTables.filter(changedTable => !changedTable.changedPartitioning);
334
- this.append(ret, this.helper.getPartitioningRebuildSQL(partitioningRebuilds, options.safe), true);
343
+ // before the rebuild, so inbound FKs the referencing table drops or changes are gone by then
335
344
  for (const changedTable of alteredTables) {
336
345
  this.append(ret, this.preAlterTable(changedTable, options.safe), true);
337
346
  }
347
+ this.append(ret, this.helper.getPartitioningRebuildSQL(partitioningRebuilds, options.safe), true);
338
348
  for (const changedTable of alteredTables) {
339
349
  this.append(ret, this.helper.alterTable(changedTable, options.safe), true);
340
350
  }
@@ -394,18 +404,24 @@ export class SqlSchemaGenerator extends AbstractSchemaGenerator {
394
404
  return this.wrapSchema(ret, options);
395
405
  }
396
406
  /**
397
- * We need to drop foreign keys first for all tables to allow dropping PK constraints.
407
+ * Collects foreign keys from other tables that reference `table` (self-references are excluded — those travel with the rebuild).
408
+ * Foreign keys the referencing table drops or changes in the same diff are left to its own alter, and those of dropped tables are skipped.
398
409
  */
399
- /** Collects foreign keys from other tables that reference `table` (self-references are excluded — those travel with the rebuild). */
400
- getInboundForeignKeys(fromSchema, table) {
410
+ getInboundForeignKeys(schemaDiff, table, dropsTables) {
401
411
  const unqualified = (name) => name.split('.').pop();
402
412
  const targetName = unqualified(table.name);
403
413
  const ret = [];
404
- for (const other of fromSchema.getTables()) {
405
- if (other.name === table.name && other.schema === table.schema) {
414
+ for (const other of schemaDiff.fromSchema.getTables()) {
415
+ if ((other.name === table.name && other.schema === table.schema) ||
416
+ (dropsTables && other.getShortestName() in schemaDiff.removedTables)) {
406
417
  continue;
407
418
  }
419
+ const otherDiff = schemaDiff.changedTables[other.getShortestName(false)];
408
420
  for (const foreignKey of Object.values(other.getForeignKeys())) {
421
+ const name = foreignKey.constraintName;
422
+ if (otherDiff && (name in otherDiff.removedForeignKeys || name in otherDiff.changedForeignKeys)) {
423
+ continue;
424
+ }
409
425
  if (unqualified(foreignKey.referencedTableName) === targetName) {
410
426
  ret.push({ table: other, foreignKey });
411
427
  }
@@ -413,6 +429,9 @@ export class SqlSchemaGenerator extends AbstractSchemaGenerator {
413
429
  }
414
430
  return ret;
415
431
  }
432
+ /**
433
+ * We need to drop foreign keys first for all tables to allow dropping PK constraints.
434
+ */
416
435
  preAlterTable(diff, safe) {
417
436
  const ret = [];
418
437
  // removed/changed policies must be dropped before any column type alter, including the pre-alter
@@ -460,7 +479,7 @@ export class SqlSchemaGenerator extends AbstractSchemaGenerator {
460
479
  continue;
461
480
  }
462
481
  // same boundary an empty line creates, for statements that have to start their own batch
463
- if (groups[i]?.length > 0 && this.startsBatch(stmt)) {
482
+ if (groups[i]?.length > 0 && this.startsBatch(stmt, groups[i].at(-1))) {
464
483
  i++;
465
484
  }
466
485
  groups[i] ??= [];
@@ -504,8 +523,8 @@ export class SqlSchemaGenerator extends AbstractSchemaGenerator {
504
523
  }
505
524
  return parts;
506
525
  }
507
- /** Whether the statement has to be the first one in a query batch, e.g. `create trigger` on MSSQL. */
508
- startsBatch(_statement) {
526
+ /** Whether the statement has to be the first one in a query batch, e.g. `create trigger` on MSSQL. `previous` is the line before it in the current batch. */
527
+ startsBatch(_statement, _previous) {
509
528
  return false;
510
529
  }
511
530
  async dropTableIfExists(name, schema) {
@@ -270,18 +270,18 @@ export const diffPartitioning = (from, to, defaultSchema) => {
270
270
  if (!from) {
271
271
  return true;
272
272
  }
273
- if (normalizeQuotedIdentifiers(normalizePartitionDefinition(from.definition)) !==
274
- normalizeQuotedIdentifiers(normalizePartitionDefinition(to.definition))) {
273
+ const toDefinition = normalizeQuotedIdentifiers(normalizePartitionDefinition(to.definition));
274
+ if (normalizeQuotedIdentifiers(normalizePartitionDefinition(from.definition)) !== toDefinition) {
275
275
  return true;
276
276
  }
277
- if (from.partitions.length !== to.partitions.length) {
277
+ // list/range partitions created outside of metadata (e.g. at runtime) are left unmanaged, hash partitions are not
278
+ if (toDefinition.startsWith('hash') && from.partitions.length !== to.partitions.length) {
278
279
  return true;
279
280
  }
280
281
  const normalizeSchema = (schema) => (schema && schema !== defaultSchema ? schema : '');
281
282
  const serializePartition = (partition) => `${normalizeSchema(partition.schema)}.${partition.name}:${normalizeQuotedIdentifiers(normalizePartitionBound(partition.bound))}`;
282
- const fromPartitions = from.partitions.map(serializePartition).sort();
283
- const toPartitions = to.partitions.map(serializePartition).sort();
284
- return fromPartitions.some((partition, index) => partition !== toPartitions[index]);
283
+ const fromPartitions = new Set(from.partitions.map(serializePartition));
284
+ return to.partitions.some(partition => !fromPartitions.has(serializePartition(partition)));
285
285
  };
286
286
  const SUPPORTED_PARTITION_TYPES = ['hash', 'list', 'range'];
287
287
  const isSupportedPartitionType = (value) => SUPPORTED_PARTITION_TYPES.includes(value);
package/typings.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { Generated, Kysely } from 'kysely';
2
- import type { CheckCallback, DeferMode, Dictionary, EntityName, EntityMetadata, EntityProperty, EntitySchemaWithMeta, ExtractDefineEntityProperties, FilterQuery, GroupOperator, IndexColumnOptions, InferEntityName, Opt, Primary, PrimaryProperty, QueryFlag, QueryOrderMap, RawQueryFragment, RoutineIgnoreField, Scalar, Type } from '@mikro-orm/core';
2
+ import type { CheckCallback, DeferMode, Dictionary, EntityName, EntityMetadata, EntityProperty, EntitySchemaWithMeta, ExtractDefineEntityProperties, FilterQuery, GroupOperator, IndexColumnOptions, InferEntityName, Opt, Primary, PrimaryProperty, QueryFlag, QueryOrderMap, RawQueryFragment, RoutineIgnoreField, Scalar, SequenceOptions, Type } from '@mikro-orm/core';
3
3
  import type { JoinType, QueryType } from './query/enums.js';
4
4
  import type { DatabaseSchema } from './schema/DatabaseSchema.js';
5
5
  import type { DatabaseTable } from './schema/DatabaseTable.js';
@@ -37,6 +37,8 @@ export interface Column {
37
37
  mappedType: Type<unknown>;
38
38
  unsigned?: boolean;
39
39
  autoincrement?: boolean;
40
+ /** applied only when the column is created, never diffed */
41
+ sequence?: SequenceOptions;
40
42
  nullable?: boolean;
41
43
  length?: number;
42
44
  precision?: number;