masterrecord 1.5.16 → 1.22.0

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.
@@ -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){