masterrecord 1.5.17 → 1.22.1

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,3 +1,4 @@
1
+ import { defaultSqlClause, computedClause, checkClause, assertDdlOptions, compositePrimaryKeyClause } from "./ddlClauses.js";
1
2
 
2
3
  // verison 0.0.7
3
4
  class migrationSQLiteQuery {
@@ -21,7 +22,7 @@ class migrationSQLiteQuery {
21
22
  return columnList.join(',');
22
23
  }
23
24
 
24
- #columnMapping(table){
25
+ #columnMapping(table, suppressPk = false){
25
26
  /*
26
27
  var mapping = {
27
28
  "name": "id", // if this chnages then call rename column
@@ -38,10 +39,11 @@ class migrationSQLiteQuery {
38
39
  */
39
40
  // name TEXT NOT NULL,
40
41
 
41
- const auto = table.auto ? " AUTOINCREMENT":"";
42
- const primaryKey = table.primary ? " PRIMARY KEY" : "";
43
- const nullName = table.nullable ? "" : " NOT NULL";
44
- const unique = table.unique ? " UNIQUE" : "";
42
+ // suppressPk: part of a composite key -> emitted as a table-level PRIMARY KEY (a, b)
43
+ const auto = (table.auto && !suppressPk) ? " AUTOINCREMENT":"";
44
+ const primaryKey = (table.primary && !suppressPk) ? " PRIMARY KEY" : "";
45
+ const nullName = (table.nullable && !(table.primary && suppressPk)) ? "" : " NOT NULL";
46
+ const unique = (table.unique && !(table.primary && suppressPk)) ? " UNIQUE" : ""; // primary() implies unique; a composite key is unique as a whole
45
47
  const type = this.#typeManager(table.type);
46
48
  let colName = table.name;
47
49
  if(table.relationshipType === 'belongsTo' && table.foreignKey){
@@ -64,7 +66,12 @@ class migrationSQLiteQuery {
64
66
  }
65
67
  }
66
68
 
67
- return `${colName} ${type}${nullName}${defaultClause}${unique}${primaryKey}${auto}`;
69
+ assertDdlOptions(table);
70
+ if (table.computedSql) {
71
+ // DB-generated: no default / PK / autoincrement; the ORM never writes it.
72
+ return `${colName} ${type}${computedClause(table, 'sqlite')}${nullName}${unique}${checkClause(table)}`;
73
+ }
74
+ return `${colName} ${type}${nullName}${defaultClause || defaultSqlClause(table, 'sqlite')}${checkClause(table)}${unique}${primaryKey}${auto}`;
68
75
  }
69
76
 
70
77
  // Public accessor for the resolved SQLite column type (affinity) of a
@@ -136,7 +143,11 @@ class migrationSQLiteQuery {
136
143
  // Fixed: Support direct column definitions (when table itself IS the column spec)
137
144
  // This matches MySQL/PostgreSQL behavior for explicit column definitions
138
145
  if(table.type && table.tableName && table.name){
139
- const def = this.#columnMapping(table);
146
+ let def = this.#columnMapping(table);
147
+ // A new belongsTo column carries its FOREIGN KEY inline (SQLite
148
+ // allows REFERENCES on ADD COLUMN; the column must default to NULL
149
+ // when foreign keys are enforced, which schema.js ensures).
150
+ if (table.__fkRef) def += this.columnReferencesClause(table.__fkRef);
140
151
  return `ALTER TABLE ${table.tableName}
141
152
  ADD COLUMN ${def}`;
142
153
  }
@@ -172,6 +183,7 @@ class migrationSQLiteQuery {
172
183
 
173
184
  createTable(table){
174
185
  let queryVar = "";
186
+ const compositePk = compositePrimaryKeyClause(table); // '' unless 2+ primary columns
175
187
  for (const key in table) {
176
188
  // Skip metadata properties (indexes, __compositeIndexes, __name, etc.)
177
189
  if(key === 'indexes' || key.startsWith('__')){
@@ -191,9 +203,16 @@ class migrationSQLiteQuery {
191
203
  continue;
192
204
  }
193
205
 
194
- queryVar += `${this.#columnMapping(col)}, `;
206
+ queryVar += `${this.#columnMapping(col, !!compositePk)}, `;
195
207
  }
196
208
  }
209
+ if (compositePk) queryVar += `${compositePk}, `; // EF HasKey(a, b): table-level PRIMARY KEY (a, b)
210
+
211
+ // FOREIGN KEY constraints (resolved by schema.js into table.__foreignKeys).
212
+ // SQLite cannot ADD CONSTRAINT after the fact, so they must be inline.
213
+ for (const fk of (table.__foreignKeys || [])) {
214
+ queryVar += `${this.foreignKeyClause(fk)}, `;
215
+ }
197
216
 
198
217
  return `CREATE TABLE IF NOT EXISTS ${table.__name} (${queryVar.replace(/,\s*$/, "")});`;
199
218
 
@@ -229,6 +248,21 @@ class migrationSQLiteQuery {
229
248
  return `ALTER TABLE ${table.tableName} RENAME COLUMN ${table.name} TO ${table.newName}`
230
249
  }
231
250
 
251
+ /** Table-level FOREIGN KEY clause (inline in CREATE TABLE). */
252
+ foreignKeyClause(fk){
253
+ return `CONSTRAINT [${fk.name}] FOREIGN KEY ([${fk.column}]) REFERENCES [${fk.refTable}]([${fk.refColumn}]) ON DELETE ${fk.onDelete || 'CASCADE'}`;
254
+ }
255
+
256
+ /** Column-level REFERENCES clause (SQLite allows it on ADD COLUMN). */
257
+ columnReferencesClause(fk){
258
+ return ` REFERENCES [${fk.refTable}]([${fk.refColumn}]) ON DELETE ${fk.onDelete || 'CASCADE'}`;
259
+ }
260
+
261
+ // SQLite has no ALTER TABLE ... ADD/DROP CONSTRAINT: constraints live in
262
+ // CREATE TABLE (inline above) or via a table rebuild (schema.syncTable).
263
+ addForeignKey(_fk){ return null; }
264
+ dropForeignKey(_fk){ return null; }
265
+
232
266
  createIndex(indexInfo){
233
267
  const indexName = indexInfo.indexName === true
234
268
  ? `idx_${indexInfo.tableName.toLowerCase()}_${indexInfo.columnName.toLowerCase()}`
@@ -54,6 +54,30 @@ export default ${this.name};
54
54
  }
55
55
  }
56
56
 
57
+ // Emit a data-preserving renameColumn call.
58
+ renameColumn(type, spec){
59
+ if(!spec || !spec.tableName || !spec.name || !spec.newName){ return; }
60
+ const stmt = ` await this.renameColumn(${JSON.stringify(spec)});`;
61
+ if(type === "up"){ this.#up += os.EOL + stmt; }
62
+ else{ this.#down += os.EOL + stmt; }
63
+ }
64
+
65
+ // Like EF Core, a possible rename is NOT applied automatically (the differ
66
+ // can't know a rename from an unrelated drop + add). Emit an advisory
67
+ // comment with the exact renameColumn call so the developer can replace
68
+ // the dropColumn/addColumn pair before applying — drop + add destroys data.
69
+ renameAdvisory(type, spec){
70
+ if(!spec || !spec.tableName || !spec.name || !spec.newName){ return; }
71
+ const lines = [
72
+ ` // POSSIBLE RENAME: '${spec.name}' -> '${spec.newName}' on ${spec.tableName} (same definition).`,
73
+ ` // If this is a rename, DELETE the dropColumn/addColumn pair for these columns below and use instead:`,
74
+ ` // await this.renameColumn(${JSON.stringify(spec)});`,
75
+ ` // (dropColumn + addColumn would DESTROY the column's data.)`,
76
+ ].join(os.EOL);
77
+ if(type === "up"){ this.#up += os.EOL + lines; }
78
+ else{ this.#down += os.EOL + lines; }
79
+ }
80
+
57
81
  // A column statement needs a column name to produce valid DDL. When the
58
82
  // diff can't resolve one (e.g. a phantom column from a metadata key), the
59
83
  // spec is `{tableName}` with no `name` — emitting it would bake a malformed
@@ -124,6 +124,64 @@ class Migrations{
124
124
  return tables;
125
125
  }
126
126
 
127
+ // Flag POSSIBLE column renames. Like EF Core, the differ does NOT silently
128
+ // turn a drop+add into a rename — it cannot know whether `title` became
129
+ // `headline` or `title` was dropped and an unrelated `headline` added, and
130
+ // guessing wrong would move the old column's data under the new name. EF
131
+ // scaffolds dropColumn + addColumn and tells you to review and change it to
132
+ // RenameColumn; we do the same, but make the review easy: when exactly ONE
133
+ // deleted column and ONE new column share an identical definition signature,
134
+ // the generated migration carries an advisory comment with the exact
135
+ // renameColumn(...) call to use instead (and add-migration prints a warning).
136
+ #findRenamedColumns(tables){
137
+ const columnByName = (schema, name) => {
138
+ for (const key of Object.keys(schema || {})) {
139
+ const c = schema[key];
140
+ if (c && typeof c === 'object' && c.name === name) return c;
141
+ }
142
+ return null;
143
+ };
144
+ const signature = (c) => JSON.stringify({
145
+ type: c.type, nullable: !!c.nullable, unique: !!c.unique,
146
+ primary: !!c.primary, auto: !!c.auto,
147
+ default: c.default === undefined ? null : c.default,
148
+ relationshipType: c.relationshipType || null,
149
+ foreignTable: c.foreignTable || null, foreignKey: c.foreignKey || null,
150
+ });
151
+ tables.forEach(function (item) {
152
+ item.possibleRenames = item.possibleRenames || [];
153
+ if (!item.deletedColumns || !item.newColumns) return;
154
+ if (item.deletedColumns.length === 0 || item.newColumns.length === 0) return;
155
+ if (item.newTables && item.newTables.length > 0) return;
156
+
157
+ const bySigOld = new Map(), bySigNew = new Map();
158
+ for (const name of item.deletedColumns) {
159
+ const c = columnByName(item.old, name); if (!c) continue;
160
+ const s = signature(c); if (!bySigOld.has(s)) bySigOld.set(s, []); bySigOld.get(s).push(name);
161
+ }
162
+ for (const name of item.newColumns) {
163
+ const c = columnByName(item.new, name); if (!c) continue;
164
+ const s = signature(c); if (!bySigNew.has(s)) bySigNew.set(s, []); bySigNew.get(s).push(name);
165
+ }
166
+ for (const [s, olds] of bySigOld) {
167
+ const news = bySigNew.get(s);
168
+ if (!news || olds.length !== 1 || news.length !== 1) continue; // ambiguous -> no advisory
169
+ item.possibleRenames.push({ from: olds[0], to: news[0] });
170
+ }
171
+ if (item.possibleRenames.length && process.env.MR_SILENT_MIGRATIONS !== 'true') {
172
+ for (const r of item.possibleRenames) {
173
+ console.warn(
174
+ `[masterrecord:add-migration] ${item.name}: '${r.from}' was removed and '${r.to}' was added with the same definition. ` +
175
+ `If this is a RENAME, edit the generated migration: replace the dropColumn/addColumn pair with ` +
176
+ `await this.renameColumn({ tableName: '${item.name}', name: '${r.from}', newName: '${r.to}' }) ` +
177
+ `(drop + add would DESTROY the column's data).`
178
+ );
179
+ }
180
+ }
181
+ });
182
+ return tables;
183
+ }
184
+
127
185
  #findUpdatedColumns(tables){
128
186
 
129
187
 
@@ -207,6 +265,7 @@ class Migrations{
207
265
  tables = this.#findNewTables(tables);
208
266
  tables = this.#findNewColumns(tables);
209
267
  tables = this.#findDeletedColumns(tables);
268
+ tables = this.#findRenamedColumns(tables);
210
269
  tables = this.#findUpdatedColumns(tables);
211
270
  tables = this.#findNewIndexes(tables);
212
271
  tables = this.#findDeletedIndexes(tables);
@@ -493,7 +552,11 @@ class Migrations{
493
552
  snapShotLocation: relSnapshotLocation,
494
553
  schema : normalizedSchema,
495
554
  seedData: orderedSeedData,
496
- seedConfig: snap.contextSeedConfig || {}
555
+ seedConfig: snap.contextSeedConfig || {},
556
+ // EF 11: the latest migration id is recorded in the snapshot so two
557
+ // branches that each add a migration conflict on merge (surfacing a
558
+ // divergent migration tree) instead of silently diverging.
559
+ latestMigration: snap.latestMigration || null
497
560
  };
498
561
 
499
562
  const jsonContent = JSON.stringify(content, null, 2);
@@ -621,6 +684,14 @@ class Migrations{
621
684
  MT.dropTable("down", item.name);
622
685
  });
623
686
 
687
+ // Possible renames: like EF, emit drop + add (below) but flag the
688
+ // likely rename in the migration so the developer can swap in the
689
+ // data-preserving renameColumn call before applying.
690
+ (item.possibleRenames || []).forEach(function (r) {
691
+ MT.renameAdvisory("up", { tableName: item.name, name: r.from, newName: r.to });
692
+ MT.renameAdvisory("down", { tableName: item.name, name: r.to, newName: r.from });
693
+ });
694
+
624
695
  // Add new columns. Bake the FULL column spec into the generated
625
696
  // migration (self-contained) instead of `table.<col>`, which was
626
697
  // re-derived from a live snapshot↔entities diff at apply time and
@@ -260,6 +260,17 @@ class schema{
260
260
  }
261
261
  }
262
262
 
263
+ // A new belongsTo column gets a FOREIGN KEY constraint (unless the
264
+ // relationship is excluded from migrations). SQLite: inline REFERENCES
265
+ // on ADD COLUMN (SQLite requires the new column to default to NULL when
266
+ // foreign keys are enforced, so an inline FK is only emitted for a
267
+ // nullable/defaulted column). MySQL/Postgres: ADD CONSTRAINT after the
268
+ // column, now or deferred to finalize().
269
+ const fkRef = this._fkRefFor(table, table.tableName);
270
+ if (fkRef && this.context.isSQLite && (table.nullable === true || (table.default !== undefined && table.default !== null))) {
271
+ Object.defineProperty(table, '__fkRef', { value: fkRef, enumerable: false, writable: true, configurable: true });
272
+ }
273
+
263
274
  if(this.context.isSQLite){
264
275
  var queryBuilder = new sqliteQuery();
265
276
  var query = queryBuilder.addColum(table);
@@ -278,6 +289,9 @@ class schema{
278
289
  await this.context._execute(query);
279
290
  }
280
291
 
292
+ if (fkRef && !this.context.isSQLite) {
293
+ await this._addForeignKeyNowOrDefer(fkRef);
294
+ }
281
295
  // add column to database
282
296
  }
283
297
 
@@ -344,6 +358,17 @@ class schema{
344
358
  if(this.context._SQLEngine.tableExists && await this.context._SQLEngine.tableExists(tableName)){
345
359
  await this.syncTable(table);
346
360
  } else {
361
+ // Resolve FOREIGN KEY constraints for this table's belongsTo
362
+ // columns (EF always creates FK constraints for relationships).
363
+ // SQLite: emitted inline in CREATE TABLE (it cannot ADD
364
+ // CONSTRAINT later). MySQL/Postgres: added AFTER the table via
365
+ // ALTER TABLE ... ADD CONSTRAINT — immediately if the referenced
366
+ // table already exists, otherwise deferred to finalize() (run at
367
+ // the end of the migration) so table creation order and cycles
368
+ // never matter.
369
+ const foreignKeys = this._foreignKeysFor(table);
370
+ Object.defineProperty(table, '__foreignKeys', { value: foreignKeys, enumerable: false, writable: true, configurable: true });
371
+
347
372
  if(this.context.isSQLite){
348
373
  var queryBuilder = new sqliteQuery();
349
374
  var query = queryBuilder.createTable(table);
@@ -362,6 +387,25 @@ class schema{
362
387
  await this.context._execute(query);
363
388
  }
364
389
 
390
+ if(!this.context.isSQLite){
391
+ for(const fk of foreignKeys){
392
+ await this._addForeignKeyNowOrDefer(fk);
393
+ }
394
+ }
395
+ // EF creates an index on every FK column. MySQL does this
396
+ // automatically for FK constraints; SQLite/Postgres do not.
397
+ if(!this.context.isMySQL){
398
+ for(const fk of foreignKeys){
399
+ try {
400
+ await this.createIndex({ tableName, columnName: fk.column, indexName: `ix_${tableName}_${fk.column}` });
401
+ } catch (e) {
402
+ if(process.env.MR_SILENT_MIGRATIONS !== 'true'){
403
+ console.log(`[masterrecord:migration] could not create FK index on ${tableName}.${fk.column}: ${e.message}`);
404
+ }
405
+ }
406
+ }
407
+ }
408
+
365
409
  // Create indexes for columns that have .index() defined
366
410
  for(const key of Object.keys(table)){
367
411
  if(typeof table[key] === "object" && table[key].indexes && !key.startsWith('__')){
@@ -403,6 +447,7 @@ class schema{
403
447
  // Build a set of existing columns (sqlite: name, mysql: name)
404
448
  const existingNames = new Set((existing || []).map(c => (c.name || c.COLUMN_NAME))); // both engines map to name
405
449
  // Add missing columns only (safe path)
450
+ let sqliteForceRebuild = false;
406
451
  for (var key in table) {
407
452
  // Skip metadata properties (indexes, __compositeIndexes, __name, etc.)
408
453
  if(key === 'indexes' || key.startsWith('__')) continue;
@@ -427,6 +472,10 @@ class schema{
427
472
  };
428
473
  // MySQL path uses addColum with realDataType
429
474
  if(this.context.isSQLite){
475
+ // A generated (computed) column cannot be ADDed as STORED in
476
+ // SQLite — rebuild the table from the definition instead
477
+ // (EF's SQLite provider rebuilds for unsupported ALTERs).
478
+ if (col.computedSql) { sqliteForceRebuild = true; continue; }
430
479
  var queryBuilder = new sqliteQuery();
431
480
  // Build a conservative column add (no NOT NULL without default)
432
481
  const add = queryBuilder.addColum({ tableName, name: colName });
@@ -462,6 +511,7 @@ class schema{
462
511
 
463
512
  const needRebuildSQLite = () => {
464
513
  if(!this.context.isSQLite) return false;
514
+ if(sqliteForceRebuild) return true;
465
515
  const sqliteBuilder = new sqliteQuery();
466
516
  const byName = {};
467
517
  for(const row of existing){ byName[row.name] = row; }
@@ -476,9 +526,14 @@ class schema{
476
526
  if(typeof exDef === 'string' && exDef.length >= 2 && exDef.startsWith("'") && exDef.endsWith("'")){
477
527
  exDef = exDef.slice(1, -1);
478
528
  }
479
- const dsDef = d.col.default == null ? null : String(d.col.default);
529
+ // defaultSql() is an expression: compare it to the stored
530
+ // expression text (SQLite keeps it verbatim, possibly parenthesized).
531
+ const normExpr = (s) => s == null ? null : String(s).trim().replace(/^\((.*)\)$/s, '$1').trim().toUpperCase();
532
+ const hasDefaultSql = d.col.default == null && d.col.defaultSql != null;
533
+ const dsDef = hasDefaultSql ? normExpr(d.col.defaultSql) : (d.col.default == null ? null : String(d.col.default));
534
+ const exCmp = hasDefaultSql ? normExpr(exDefRaw) : exDef;
480
535
  if(desiredNotNull !== notnull) return true;
481
- if(exDef !== dsDef) return true;
536
+ if(exCmp !== dsDef) return true;
482
537
  // Type change at SQLite's AFFINITY level. Compare the resolved
483
538
  // SQLite type of the desired column to the existing column's
484
539
  // declared type. This catches ANY real change (integer->text,
@@ -599,6 +654,8 @@ class schema{
599
654
 
600
655
  await this.context._execute(queryBuilder.renameTable({ tableName, newName: TEMP }));
601
656
  try {
657
+ // The rebuilt table must keep its FOREIGN KEY constraints.
658
+ Object.defineProperty(table, '__foreignKeys', { value: this._foreignKeysFor(table), enumerable: false, writable: true, configurable: true });
602
659
  await this.context._execute(queryBuilder.createTable(table));
603
660
 
604
661
  const oldInfo = await engine.getTableInfo(TEMP);
@@ -609,8 +666,11 @@ class schema{
609
666
  // before it was required. Copying those verbatim fails the
610
667
  // constraint and costs the whole table, so they take the
611
668
  // column's default — or a typed zero value when it has none.
612
- const cols = common.map(d => d.name).join(',');
613
- const selects = common.map(d => {
669
+ // Computed (generated) columns cannot be inserted into — the
670
+ // rebuilt table derives them again.
671
+ const copyable = common.filter(d => !(d.col && d.col.computedSql));
672
+ const cols = copyable.map(d => d.name).join(',');
673
+ const selects = copyable.map(d => {
614
674
  if(d.col.nullable !== false) return d.name;
615
675
  let fallback = d.col.default;
616
676
  if(fallback == null){
@@ -715,7 +775,11 @@ class schema{
715
775
  }
716
776
 
717
777
  async renameColumn(table){
778
+ await this._ensureReady();
718
779
  if(table){
780
+ if(!table.tableName || !table.name || !table.newName){
781
+ throw new Error(`masterrecord: renameColumn requires { tableName, name, newName }, got ${JSON.stringify(table)}`);
782
+ }
719
783
  if(this.context.isSQLite){
720
784
  var queryBuilder = new sqliteQuery();
721
785
  var query = queryBuilder.renameColumn(table);
@@ -736,6 +800,121 @@ class schema{
736
800
  }
737
801
  }
738
802
 
803
+ /** Rename a table: `{ tableName, newName }` (data-preserving). */
804
+ async renameTable(spec){
805
+ await this._ensureReady();
806
+ if(!spec || !spec.tableName || !spec.newName){
807
+ throw new Error(`masterrecord: renameTable requires { tableName, newName }, got ${JSON.stringify(spec)}`);
808
+ }
809
+ const builder = this.context.isSQLite ? new sqliteQuery() : this.context.isMySQL ? new sqlquery() : new postgresQuery();
810
+ await this.context._execute(builder.renameTable(spec));
811
+ }
812
+
813
+ // ---- Foreign keys (EF always creates FK constraints for relationships) ----
814
+
815
+ /** Primary-key column name of the entity that owns table `name` (default 'id'). */
816
+ _primaryKeyOf(name){
817
+ const ents = (this.context && this.context.__entities) || [];
818
+ const ent = ents.find(e => e && e.__name === name);
819
+ if(ent){
820
+ for(const key of Object.keys(ent)){
821
+ const f = ent[key];
822
+ if(f && typeof f === 'object' && f.primary === true) return f.name || key;
823
+ }
824
+ }
825
+ return 'id';
826
+ }
827
+
828
+ /**
829
+ * FK descriptor for ONE belongsTo column (or null): { tableName, column,
830
+ * refTable, refColumn, onDelete, name }. Honors `onDelete(...)`,
831
+ * `stopCascadeOnDelete()` (→ SET NULL if nullable else RESTRICT) and
832
+ * `excludeForeignKeyFromMigrations()`.
833
+ */
834
+ _fkRefFor(col, tableName){
835
+ if(!col || typeof col !== 'object') return null;
836
+ if(col.relationshipType !== 'belongsTo' || !col.foreignTable) return null;
837
+ if(col.fkConstraint === false) return null;
838
+ const column = col.foreignKey || col.name;
839
+ const refTable = col.foreignTable;
840
+ const refColumn = this._primaryKeyOf(refTable);
841
+ let onDelete = col.onDelete;
842
+ if(!onDelete){
843
+ onDelete = (col.cascadeOnDelete === false) ? (col.nullable ? 'SET NULL' : 'RESTRICT') : 'CASCADE';
844
+ }
845
+ return { tableName, column, refTable, refColumn, onDelete, name: `fk_${tableName}_${column}` };
846
+ }
847
+
848
+ /** All FK descriptors for a table definition. */
849
+ _foreignKeysFor(table){
850
+ const out = [];
851
+ if(!table) return out;
852
+ for(const key of Object.keys(table)){
853
+ if(key === 'indexes' || key.startsWith('__')) continue;
854
+ const fk = this._fkRefFor(table[key], table.__name);
855
+ if(fk) out.push(fk);
856
+ }
857
+ return out;
858
+ }
859
+
860
+ /** ALTER TABLE ... ADD CONSTRAINT FOREIGN KEY (MySQL/Postgres; SQLite needs a rebuild). */
861
+ async addForeignKey(fk){
862
+ await this._ensureReady();
863
+ if(this.context.isSQLite){
864
+ throw new Error('masterrecord: SQLite cannot add a FOREIGN KEY to an existing table (no ADD CONSTRAINT). Declare it on the entity and let createTable/syncTable emit it inline.');
865
+ }
866
+ const builder = this.context.isMySQL ? new sqlquery() : new postgresQuery();
867
+ await this.context._execute(builder.addForeignKey(fk), undefined, { migration: true });
868
+ }
869
+
870
+ /** Drop a FOREIGN KEY constraint by name (MySQL/Postgres). */
871
+ async dropForeignKey(fk){
872
+ await this._ensureReady();
873
+ if(this.context.isSQLite){
874
+ throw new Error('masterrecord: SQLite cannot drop a FOREIGN KEY from an existing table (no DROP CONSTRAINT); remove it from the entity and rebuild via syncTable.');
875
+ }
876
+ const builder = this.context.isMySQL ? new sqlquery() : new postgresQuery();
877
+ await this.context._execute(builder.dropForeignKey(fk));
878
+ }
879
+
880
+ /** Add the FK now if the referenced table exists, else defer to finalize(). */
881
+ async _addForeignKeyNowOrDefer(fk){
882
+ const eng = this.context._SQLEngine;
883
+ const refExists = eng && typeof eng.tableExists === 'function' ? await eng.tableExists(fk.refTable) : true;
884
+ if(refExists){
885
+ await this.addForeignKey(fk);
886
+ } else {
887
+ this._pendingForeignKeys = this._pendingForeignKeys || [];
888
+ this._pendingForeignKeys.push(fk);
889
+ }
890
+ }
891
+
892
+ /**
893
+ * Flush deferred FOREIGN KEY constraints. Called by the CLI after a
894
+ * migration's up()/down() has run, so constraints whose referenced table
895
+ * was created later in the same migration are added once both exist.
896
+ * Throws if a referenced table still does not exist (a real model error).
897
+ */
898
+ async finalize(){
899
+ const pending = this._pendingForeignKeys || [];
900
+ this._pendingForeignKeys = [];
901
+ if(pending.length === 0) return;
902
+ const eng = this.context._SQLEngine;
903
+ const missing = [];
904
+ for(const fk of pending){
905
+ const refExists = eng && typeof eng.tableExists === 'function' ? await eng.tableExists(fk.refTable) : true;
906
+ if(refExists) await this.addForeignKey(fk);
907
+ else missing.push(fk);
908
+ }
909
+ if(missing.length){
910
+ throw new Error(
911
+ `masterrecord: cannot create FOREIGN KEY constraint(s) — referenced table(s) do not exist: ` +
912
+ missing.map(m => `${m.tableName}.${m.column} -> ${m.refTable}(${m.refColumn})`).join(', ') +
913
+ `. Create the referenced table first, or mark the relationship .excludeForeignKeyFromMigrations().`
914
+ );
915
+ }
916
+ }
917
+
739
918
  async createIndex(indexInfo){
740
919
  if(indexInfo){
741
920
  if(this.context.isSQLite){