masterrecord 1.2.1 → 1.2.3
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.
- package/CHANGES.md +29 -0
- package/Migrations/migrationTemplate.js +14 -16
- package/Migrations/migrations.js +83 -12
- package/Migrations/schema.js +36 -11
- package/package.json +1 -1
package/CHANGES.md
CHANGED
|
@@ -1,5 +1,34 @@
|
|
|
1
1
|
# MasterRecord Changelog
|
|
2
2
|
|
|
3
|
+
## v1.2.3 — self-contained incremental migrations (fixes silent addColumn no-op across DBs)
|
|
4
|
+
|
|
5
|
+
**Bug:** an incremental `addColumn` migration could silently no-op on a second database (column never added, migration still recorded as applied). Reproduced and root-caused on prod MySQL.
|
|
6
|
+
|
|
7
|
+
**Mechanism:** `update-database` does not run the literal op in the migration file — it calls `buildUpObject(committedSnapshot.schema, currentEntities)` and passes the result as `table` to `up(table)`. The generated `await this.addColumn(table.public_token)` therefore depended on `table.public_token` being populated, which only happens when that column is in the **snapshot↔entities diff** (`item.newColumns`). The committed snapshot is shared and gets advanced by whichever DB you migrate first (e.g. dev); every subsequent DB (e.g. prod) then diffs to **empty** for that column → `table.public_token` is `undefined` → `schema.addColumn(undefined)` hit its silent `if(table){…}` guard → nothing ran, migration marked applied. `createTable` was immune because `buildUpObject` populates every table regardless of diff; only incremental column ops were affected.
|
|
8
|
+
|
|
9
|
+
**Fixes:**
|
|
10
|
+
1. **Self-contained generation.** `add-migration` now bakes the full column spec inline — `await this.addColumn({ tableName, name, type, … })` instead of `await this.addColumn(table.public_token)`. Migrations replay deterministically on every database, independent of snapshot state (the standard Rails/Knex/TypeORM model). Applies to `addColumn` and the symmetric `dropColumn` (incl. up/down).
|
|
11
|
+
2. **Fail loudly.** `schema.addColumn` / `dropColumn` now throw a descriptive error on an incomplete/undefined operand ("…snapshot is ahead of this database…") instead of silently skipping — so legacy `table.<col>`-style migrations can never silently lose a column again.
|
|
12
|
+
3. **Readiness symmetry.** `addColumn` / `dropColumn` now `await this._ensureReady()` (like `createTable`), and throw if no dialect is active — closing the related (theoretical) async-init gap.
|
|
13
|
+
|
|
14
|
+
New tests: `test/migration-self-contained.test.js` (generation bakes a literal; self-contained add applies despite an empty diff; loud throw on incomplete operand). Suite green (same single pre-existing failure); 0 lint errors.
|
|
15
|
+
|
|
16
|
+
> Existing already-generated migrations keep working; if one uses the old `table.<col>` form and hits the empty-diff case, it now **throws loudly** (fix #2) instead of silently skipping — regenerate it to get the self-contained form.
|
|
17
|
+
|
|
18
|
+
## v1.2.2 — deterministic migration snapshots (no transient `tableName` leak)
|
|
19
|
+
|
|
20
|
+
The generated `*_contextSnapShot.json` could differ run-to-run for an unchanged schema, producing noisy git diffs and occasional spurious "schema changed" detections.
|
|
21
|
+
|
|
22
|
+
**Root cause:** `buildUpObject()` attached a transient `tableName` to column objects in place (`columnInfo.new[column].tableName = item.name`). Because `cleanEntities()` shallow-copies, those column objects are shared with the schema serialized into the snapshot — so `tableName` leaked in, but only onto the columns that happened to change that run.
|
|
23
|
+
|
|
24
|
+
**Fix:**
|
|
25
|
+
- `buildUpObject()` now tags a **copy** (`{ ...col, tableName }`) instead of mutating the shared column object — the migration template/query-builder still gets the `tableName` it needs, but the schema definitions stay clean.
|
|
26
|
+
- `createSnapShot()` normalizes the schema before writing (strips any transient `tableName` from column defs), so the persisted snapshot is deterministic regardless of upstream mutation.
|
|
27
|
+
|
|
28
|
+
Result: two consecutive snapshot generations of an unchanged schema are now **byte-identical**. New test: `test/snapshot-determinism.test.js`.
|
|
29
|
+
|
|
30
|
+
> Note: the related *live-timestamp* non-determinism (a `created_at`-style snapshot value changing each run) is **not** a masterrecord bug — it comes from a model/seed using a JS-evaluated default (`Date.now()`/`new Date()`), which is re-evaluated per context build. Pin it with a SQL default (`default('CURRENT_TIMESTAMP')`) or set it in a `beforeSave` hook.
|
|
31
|
+
|
|
3
32
|
## v1.2.1 — Postgres multi-schema support (configurable schema / search_path)
|
|
4
33
|
|
|
5
34
|
Closes the gap noted in 1.2.0: a table living in a schema outside the connection's `search_path` was read as "absent" during migrations. You can now target a schema explicitly:
|
|
@@ -54,16 +54,17 @@ export default ${this.name};
|
|
|
54
54
|
}
|
|
55
55
|
}
|
|
56
56
|
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
}
|
|
57
|
+
// Bake the resolved column spec inline so the migration is self-contained
|
|
58
|
+
// and replays deterministically on every database — independent of the
|
|
59
|
+
// committed snapshot's state at apply time. (Previously emitted
|
|
60
|
+
// `table.<col>`, re-derived from a live diff, which silently no-op'd when
|
|
61
|
+
// the snapshot was already ahead of the target DB.)
|
|
62
|
+
addColumn(type, spec){
|
|
63
|
+
const stmt = ` await this.addColumn(${JSON.stringify(spec)});`;
|
|
64
|
+
if(type === "up"){ this.#up += os.EOL + stmt; }
|
|
65
|
+
else{ this.#down += os.EOL + stmt; }
|
|
64
66
|
}
|
|
65
|
-
|
|
66
|
-
|
|
67
|
+
|
|
67
68
|
dropTable(type, name){
|
|
68
69
|
if(type === "up"){
|
|
69
70
|
this.#down += os.EOL + ` await this.dropTable(table.${name});`
|
|
@@ -73,13 +74,10 @@ export default ${this.name};
|
|
|
73
74
|
}
|
|
74
75
|
}
|
|
75
76
|
|
|
76
|
-
dropColumn(type,
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
}
|
|
80
|
-
else{
|
|
81
|
-
this.#down += os.EOL + ` await this.dropColumn(table.${name});`
|
|
82
|
-
}
|
|
77
|
+
dropColumn(type, spec){
|
|
78
|
+
const stmt = ` await this.dropColumn(${JSON.stringify(spec)});`;
|
|
79
|
+
if(type === "up"){ this.#up += os.EOL + stmt; }
|
|
80
|
+
else{ this.#down += os.EOL + stmt; }
|
|
83
81
|
}
|
|
84
82
|
|
|
85
83
|
createIndex(type, indexInfo){
|
package/Migrations/migrations.js
CHANGED
|
@@ -409,6 +409,30 @@ class Migrations{
|
|
|
409
409
|
return newEntity;
|
|
410
410
|
}
|
|
411
411
|
|
|
412
|
+
// Produce a clean, snapshot-safe copy of the schema: shallow-copy each
|
|
413
|
+
// entity and each column definition, dropping the transient `tableName`
|
|
414
|
+
// key (attached at migration-build time). Functions on column defs
|
|
415
|
+
// (transform/validators/get/set) are not JSON-serializable and are
|
|
416
|
+
// already dropped by JSON.stringify, so omitting them here is harmless.
|
|
417
|
+
#normalizeSchemaForSnapshot(entities){
|
|
418
|
+
if (!Array.isArray(entities)) return entities;
|
|
419
|
+
return entities.map((entity) => {
|
|
420
|
+
if (!entity || typeof entity !== 'object') return entity;
|
|
421
|
+
const cleanEntity = {};
|
|
422
|
+
for (const key of Object.keys(entity)) {
|
|
423
|
+
const value = entity[key];
|
|
424
|
+
if (value && typeof value === 'object' && !Array.isArray(value)) {
|
|
425
|
+
const { tableName, ...rest } = value; // drop transient tableName
|
|
426
|
+
void tableName;
|
|
427
|
+
cleanEntity[key] = rest;
|
|
428
|
+
} else {
|
|
429
|
+
cleanEntity[key] = value;
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
return cleanEntity;
|
|
433
|
+
});
|
|
434
|
+
}
|
|
435
|
+
|
|
412
436
|
createSnapShot(snap){
|
|
413
437
|
// Place migrations alongside the Context file by default:
|
|
414
438
|
// <ContextDir>/db/migrations/<context>_contextSnapShot.json
|
|
@@ -433,11 +457,18 @@ class Migrations{
|
|
|
433
457
|
? snap.context.getOrderedSeedData()
|
|
434
458
|
: snap.contextSeedData || {};
|
|
435
459
|
|
|
460
|
+
// Normalize the schema before serializing so the snapshot is
|
|
461
|
+
// DETERMINISTIC: strip the transient `tableName` field that the
|
|
462
|
+
// migration builder may have attached to column objects. It is not
|
|
463
|
+
// part of the schema definition (a column's table is implied by its
|
|
464
|
+
// parent entity's __name), and leaking it produced run-to-run diffs.
|
|
465
|
+
const normalizedSchema = this.#normalizeSchemaForSnapshot(snap.contextEntities);
|
|
466
|
+
|
|
436
467
|
const content = {
|
|
437
468
|
contextLocation: relContextLocation,
|
|
438
469
|
migrationFolder: relMigrationFolder,
|
|
439
470
|
snapShotLocation: relSnapshotLocation,
|
|
440
|
-
schema :
|
|
471
|
+
schema : normalizedSchema,
|
|
441
472
|
seedData: orderedSeedData,
|
|
442
473
|
seedConfig: snap.contextSeedConfig || {}
|
|
443
474
|
};
|
|
@@ -468,14 +499,21 @@ class Migrations{
|
|
|
468
499
|
tableObj[item.name] = columnInfo.new;
|
|
469
500
|
});
|
|
470
501
|
|
|
502
|
+
// NOTE: `tableName` is a transient field the migration
|
|
503
|
+
// template/query-builder needs to know which table a
|
|
504
|
+
// column belongs to. It must be attached to a COPY — the
|
|
505
|
+
// source column objects are shared (cleanEntities shallow-
|
|
506
|
+
// copies them) with the schema that gets serialized into
|
|
507
|
+
// the snapshot. Mutating them in place leaked `tableName`
|
|
508
|
+
// into the snapshot non-deterministically (only on the
|
|
509
|
+
// columns that happened to change that run), producing
|
|
510
|
+
// noisy diffs and spurious "schema changed" detections.
|
|
471
511
|
item.newColumns.forEach(function (column, _ind) {
|
|
472
|
-
columnInfo.new[column]
|
|
473
|
-
tableObj[column] = columnInfo.new[column];
|
|
512
|
+
tableObj[column] = { ...columnInfo.new[column], tableName: item.name };
|
|
474
513
|
});
|
|
475
514
|
|
|
476
515
|
item.deletedColumns.forEach(function (column, _ind) {
|
|
477
|
-
columnInfo.old[column]
|
|
478
|
-
tableObj[column] = columnInfo.old[column];
|
|
516
|
+
tableObj[column] = { ...columnInfo.old[column], tableName: item.name };
|
|
479
517
|
});
|
|
480
518
|
|
|
481
519
|
item.updatedColumns.forEach(function (column, _ind) {
|
|
@@ -483,8 +521,7 @@ class Migrations{
|
|
|
483
521
|
});
|
|
484
522
|
|
|
485
523
|
if(item.new === null){
|
|
486
|
-
columnInfo.old
|
|
487
|
-
tableObj["new"] = columnInfo.old;
|
|
524
|
+
tableObj["new"] = { ...columnInfo.old, tableName: item.name };
|
|
488
525
|
}
|
|
489
526
|
|
|
490
527
|
tableObj.___table = item;
|
|
@@ -513,6 +550,33 @@ class Migrations{
|
|
|
513
550
|
return false;
|
|
514
551
|
}
|
|
515
552
|
|
|
553
|
+
// Resolve a column's full, JSON-safe definition (for baking a
|
|
554
|
+
// self-contained add/drop into a generated migration). Looks the column
|
|
555
|
+
// up by its DB name (or belongsTo foreignKey) in the entity and copies
|
|
556
|
+
// the DDL-relevant fields plus an explicit tableName. Functions
|
|
557
|
+
// (transform/validators/get/set) are intentionally omitted — they aren't
|
|
558
|
+
// needed for DDL and aren't serializable.
|
|
559
|
+
#columnLiteral(entity, columnName, tableName){
|
|
560
|
+
let def = null;
|
|
561
|
+
for (const key of Object.keys(entity || {})) {
|
|
562
|
+
const d = entity[key];
|
|
563
|
+
if (d && typeof d === 'object') {
|
|
564
|
+
if (d.name === columnName) { def = d; break; }
|
|
565
|
+
if (d.relationshipType === 'belongsTo' && d.foreignKey === columnName) { def = d; break; }
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
if (!def) {
|
|
569
|
+
// Should not happen for a detected column; keep minimal + let the
|
|
570
|
+
// schema layer's loud guard catch any incompleteness at apply time.
|
|
571
|
+
return { tableName, name: columnName };
|
|
572
|
+
}
|
|
573
|
+
const spec = { tableName, name: def.name, type: def.type };
|
|
574
|
+
for (const k of ['nullable', 'default', 'unique', 'auto', 'primary', 'typeSize', 'relationshipType', 'foreignKey', 'foreignTable']) {
|
|
575
|
+
if (def[k] !== undefined && def[k] !== null) spec[k] = def[k];
|
|
576
|
+
}
|
|
577
|
+
return spec;
|
|
578
|
+
}
|
|
579
|
+
|
|
516
580
|
template(name, oldSchema, newSchema, newSeedData = {}, seedConfig = {}, currentEnv = null){
|
|
517
581
|
const MT = new MigrationTemplate(name);
|
|
518
582
|
// Determine current environment if not provided
|
|
@@ -520,6 +584,7 @@ class Migrations{
|
|
|
520
584
|
currentEnv = process.env.NODE_ENV || process.env.master || 'development';
|
|
521
585
|
}
|
|
522
586
|
const tables = this.#buildMigrationObject(oldSchema, newSchema, newSeedData);
|
|
587
|
+
const self = this;
|
|
523
588
|
|
|
524
589
|
tables.forEach(function (item, _index) {
|
|
525
590
|
// (Whole-table create/drop is handled below via item.newTables /
|
|
@@ -533,15 +598,21 @@ class Migrations{
|
|
|
533
598
|
MT.dropTable("down", item.name);
|
|
534
599
|
});
|
|
535
600
|
|
|
536
|
-
//
|
|
601
|
+
// Add new columns. Bake the FULL column spec into the generated
|
|
602
|
+
// migration (self-contained) instead of `table.<col>`, which was
|
|
603
|
+
// re-derived from a live snapshot↔entities diff at apply time and
|
|
604
|
+
// silently no-op'd on any database whose diff was empty (snapshot
|
|
605
|
+
// already advanced by the first DB migrated).
|
|
537
606
|
item.newColumns.forEach(function (column, _index) {
|
|
538
|
-
|
|
539
|
-
MT.
|
|
607
|
+
const spec = self.#columnLiteral(item.new, column, item.name);
|
|
608
|
+
MT.addColumn("up", spec);
|
|
609
|
+
MT.dropColumn("down", spec);
|
|
540
610
|
});
|
|
541
611
|
|
|
542
612
|
item.deletedColumns.forEach(function (column, _index) {
|
|
543
|
-
|
|
544
|
-
MT.
|
|
613
|
+
const spec = self.#columnLiteral(item.old, column, item.name);
|
|
614
|
+
MT.dropColumn("up", spec);
|
|
615
|
+
MT.addColumn("down", spec);
|
|
545
616
|
});
|
|
546
617
|
|
|
547
618
|
item.updatedColumns.forEach(function (column, _index) {
|
package/Migrations/schema.js
CHANGED
|
@@ -215,38 +215,63 @@ class schema{
|
|
|
215
215
|
|
|
216
216
|
// create obj to convert into create sql
|
|
217
217
|
async addColumn(table){
|
|
218
|
-
//
|
|
219
|
-
//
|
|
220
|
-
//
|
|
221
|
-
|
|
222
|
-
|
|
218
|
+
// Ensure the async DB init (MySQL/Postgres) has completed before we
|
|
219
|
+
// read dialect flags / run DDL — matches createTable(), which always
|
|
220
|
+
// did this. (addColumn/dropColumn previously skipped it.)
|
|
221
|
+
await this._ensureReady();
|
|
222
|
+
|
|
223
|
+
// FAIL LOUDLY instead of silently skipping. An older generated
|
|
224
|
+
// migration re-derives its column from a live diff (`table.<col>`) at
|
|
225
|
+
// apply time; when the committed snapshot is already AHEAD of THIS
|
|
226
|
+
// database the diff is empty and `table` is undefined — which used to
|
|
227
|
+
// hit a silent `if(table){…}` guard, mark the migration applied, and
|
|
228
|
+
// never add the column. (Newer migrations bake the full spec inline,
|
|
229
|
+
// so this only guards legacy/edge cases.)
|
|
230
|
+
if(!table || !table.tableName || !table.name || !table.type){
|
|
231
|
+
throw new Error(
|
|
232
|
+
`masterrecord: addColumn received an incomplete column definition (${JSON.stringify(table)}). ` +
|
|
233
|
+
`This usually means the committed snapshot is already ahead of this database, so the migration ` +
|
|
234
|
+
`could not re-derive the column from the diff. Regenerate the migration (it now bakes the full ` +
|
|
235
|
+
`column spec inline) or apply it against a database whose snapshot matches.`
|
|
236
|
+
);
|
|
237
|
+
}
|
|
238
|
+
if(!this.context.isSQLite && !this.context.isMySQL && !this.context.isPostgres){
|
|
239
|
+
throw new Error('masterrecord: addColumn — no database dialect is active (context not initialized).');
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
if(this.context.isSQLite){
|
|
223
243
|
var queryBuilder = new sqliteQuery();
|
|
224
|
-
// Fixed: Use addColum (consistent with MySQL/PostgreSQL) instead of alterColumn
|
|
225
|
-
// This allows explicit column definitions to work, not just CLI-generated migrations
|
|
226
|
-
// Note: No need to set table.realDataType - columnMapping handles type conversion internally
|
|
227
244
|
var query = queryBuilder.addColum(table);
|
|
228
245
|
await this.context._execute(query);
|
|
229
246
|
}
|
|
230
247
|
|
|
231
248
|
if(this.context.isMySQL){
|
|
232
249
|
var queryBuilder = new sqlquery();
|
|
233
|
-
// Note: No need to set table.realDataType - columnMapping handles type conversion internally
|
|
234
250
|
var query = queryBuilder.addColum(table);
|
|
235
251
|
await this.context._execute(query);
|
|
236
252
|
}
|
|
237
253
|
|
|
238
254
|
if(this.context.isPostgres){
|
|
239
255
|
var queryBuilder = new postgresQuery();
|
|
240
|
-
// Note: No need to set table.realDataType - columnMapping handles type conversion internally
|
|
241
256
|
var query = queryBuilder.addColum(table);
|
|
242
257
|
await this.context._execute(query);
|
|
243
258
|
}
|
|
244
|
-
}
|
|
245
259
|
|
|
246
260
|
// add column to database
|
|
247
261
|
}
|
|
248
262
|
|
|
249
263
|
async dropColumn(table){
|
|
264
|
+
await this._ensureReady();
|
|
265
|
+
// Fail loudly rather than silently skipping (see addColumn) — a drift
|
|
266
|
+
// between the committed snapshot and this database can leave the
|
|
267
|
+
// migration's re-derived `table.<col>` undefined.
|
|
268
|
+
if(!table || !table.tableName || !table.name){
|
|
269
|
+
throw new Error(
|
|
270
|
+
`masterrecord: dropColumn received an incomplete column definition (${JSON.stringify(table)}). ` +
|
|
271
|
+
`The committed snapshot may be ahead of this database. Regenerate the migration (it now bakes the ` +
|
|
272
|
+
`full column spec inline) or apply it against a database whose snapshot matches.`
|
|
273
|
+
);
|
|
274
|
+
}
|
|
250
275
|
if(table){
|
|
251
276
|
if(this.fullTable){
|
|
252
277
|
// SQLite doesn't support `IF EXISTS` on DROP COLUMN, so
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "masterrecord",
|
|
3
|
-
"version": "1.2.
|
|
3
|
+
"version": "1.2.3",
|
|
4
4
|
"description": "An Object-relational mapping for the Master framework. Master Record connects classes to relational database tables to establish a database with almost zero-configuration ",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./MasterRecord.js",
|