@mikro-orm/sql 7.3.0-dev.17 → 7.3.0-dev.18

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.
@@ -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
@@ -761,6 +761,10 @@ export class DatabaseTable {
761
761
  !idx.primary &&
762
762
  !idx.where &&
763
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
+ }
764
768
  const kind = this.getReferenceKind(fk, unique);
765
769
  const runtimeType = this.getPropertyTypeForColumn(namingStrategy, column, fk);
766
770
  const type = fk
@@ -878,9 +882,9 @@ export class DatabaseTable {
878
882
  return +defaultValue;
879
883
  }
880
884
  // unquote string defaults if `raw = false`
881
- const match = /^'(.*)'$/.exec('' + val);
885
+ const match = /^'(.*)'$/s.exec('' + val);
882
886
  if (!raw && match) {
883
- return match[1];
887
+ return schemaHelper.unescapeDefault(match[1]);
884
888
  }
885
889
  return '' + val;
886
890
  }
@@ -926,6 +930,17 @@ export class DatabaseTable {
926
930
  };
927
931
  return [expand(rootProp, 1)];
928
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
+ }
929
944
  // json index, we need to rename the column only
930
945
  if (rootProp) {
931
946
  return [prop.replace(root, rootProp.fieldNames[0])];
@@ -962,19 +977,23 @@ export class DatabaseTable {
962
977
  if (columns?.length && properties.length > 0) {
963
978
  for (const col of columns) {
964
979
  if (!properties.includes(col.name)) {
965
- 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`);
966
981
  }
967
982
  }
968
983
  }
969
984
  // Validate fillFactor range
970
985
  if (index.fillFactor != null && (index.fillFactor < 0 || index.fillFactor > 100)) {
971
- 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}'`);
972
987
  }
973
988
  // The `expression` escape hatch takes the full index definition as raw SQL; combining it
974
989
  // with `where` is dialect-dependent (PG/Oracle/MySQL drop `where`, MSSQL appends it) so we
975
990
  // reject the combination up-front and ask users to inline the predicate into `expression`.
976
991
  if (index.expression && index.where != null) {
977
- 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}\`.`);
978
997
  }
979
998
  const where = this.processIndexWhere(index.where, meta);
980
999
  const expression = this.processIndexExpression(name, index.expression, meta);
@@ -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;
@@ -493,10 +497,12 @@ export class SchemaComparator {
493
497
  tableDifferences.changedChecks[check.name] = toTableCheck;
494
498
  changes++;
495
499
  }
500
+ const ignoreTriggers = this.#platform.getConfig().get('schemaGenerator').ignoreTriggers;
496
501
  const fromTableTriggers = fromTable.getTriggers();
497
502
  const toTableTriggers = toTable.getTriggers();
498
503
  for (const trigger of toTableTriggers) {
499
- if (fromTable.hasTrigger(trigger.name)) {
504
+ // see `compareRoutines` for how `ignoreTriggers` applies to the down diff
505
+ if (fromTable.hasTrigger(trigger.name) || (ignoreTriggers && inverse)) {
500
506
  continue;
501
507
  }
502
508
  tableDifferences.addedTriggers[trigger.name] = trigger;
@@ -504,7 +510,7 @@ export class SchemaComparator {
504
510
  changes++;
505
511
  }
506
512
  // `ignoreTriggers` makes triggers create-only: declared ones are still added above, but existing triggers are never diffed for drop/alter.
507
- if (!this.#platform.getConfig().get('schemaGenerator').ignoreTriggers) {
513
+ if (!ignoreTriggers || inverse) {
508
514
  for (const trigger of fromTableTriggers) {
509
515
  if (!toTable.hasTrigger(trigger.name)) {
510
516
  tableDifferences.removedTriggers[trigger.name] = trigger;
@@ -513,7 +519,7 @@ export class SchemaComparator {
513
519
  continue;
514
520
  }
515
521
  const toTableTrigger = toTable.getTrigger(trigger.name);
516
- if (this.diffTrigger(trigger, toTableTrigger)) {
522
+ if (!ignoreTriggers && this.diffTrigger(trigger, toTableTrigger)) {
517
523
  this.log(`trigger ${trigger.name} changed in table ${tableDifferences.name}`, {
518
524
  fromTableTrigger: trigger,
519
525
  toTableTrigger,
@@ -862,16 +868,10 @@ export class SchemaComparator {
862
868
  if (cols1.length === 0 && cols2.length === 0) {
863
869
  return true;
864
870
  }
865
- // If only one has column options, they don't match
866
- if (cols1.length !== cols2.length) {
867
- return false;
868
- }
869
- // Compare each column's options
870
- // Note: We don't check c1.name !== c2.name because the indexes already have matching columnNames
871
- // and the columns array is derived from those same column names
872
- for (let i = 0; i < cols1.length; i++) {
873
- const c1 = cols1[i];
874
- 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 };
875
875
  const sort1 = c1.sort?.toUpperCase() ?? 'ASC';
876
876
  const sort2 = c2.sort?.toUpperCase() ?? 'ASC';
877
877
  if (sort1 !== sort2) {
@@ -908,9 +908,13 @@ export class SchemaComparator {
908
908
  // expressions like check constraints might be normalized by the driver,
909
909
  // e.g. quotes might be added (https://github.com/mikro-orm/mikro-orm/issues/3827)
910
910
  const simplify = (str) => {
911
- return (str
911
+ if (str == null) {
912
+ return str;
913
+ }
914
+ return (this.#helper
915
+ .normalizeExpression(str)
912
916
  // lookbehind: only strip a real charset introducer, never an underscore inside a literal like 'a_b'
913
- ?.replace(/(?<![\w'])_\w+'(.*?)'/g, '$1')
917
+ .replace(/(?<![\w'])_\w+'(.*?)'/g, '$1')
914
918
  .replace(/!=/g, '<>')
915
919
  // `\b` keeps this from firing inside identifiers like `min(...)`
916
920
  .replace(/\bnot\s+in\s*\((.*?)\)/gi, '<> all (array[$1])')
@@ -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`). */
@@ -178,6 +180,13 @@ export declare abstract class SchemaHelper {
178
180
  getNamespaces(connection: AbstractSqlConnection, ctx?: Transaction): Promise<string[]>;
179
181
  protected mapIndexes(indexes: IndexDef[]): Promise<IndexDef[]>;
180
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;
181
190
  normalizeDefaultValue(defaultValue: string | RawQueryFragment, length?: number, defaultValues?: Dictionary<string[]>): string | number;
182
191
  getCreateDatabaseSQL(name: string): string;
183
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) {
@@ -654,6 +658,8 @@ export class SchemaHelper {
654
658
  }
655
659
  if (useDefault) {
656
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)/, '');
657
663
  const needsExpression = [
658
664
  'blob',
659
665
  'text',
@@ -665,7 +671,7 @@ export class SchemaHelper {
665
671
  'multilinestring',
666
672
  'multipolygon',
667
673
  'geometrycollection',
668
- ].some(type => column.type.toLowerCase().startsWith(type));
674
+ ].some(type => baseType.startsWith(type));
669
675
  const defaultSql = needsExpression && !column.default.startsWith('(') ? `(${column.default})` : column.default;
670
676
  col.push(`default ${defaultSql}`);
671
677
  }
@@ -756,6 +762,17 @@ export class SchemaHelper {
756
762
  return ret;
757
763
  }, {});
758
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
+ }
759
776
  normalizeDefaultValue(defaultValue, length, defaultValues = {}) {
760
777
  if (defaultValue == null) {
761
778
  return defaultValue;