masterrecord 1.3.3 → 1.5.5

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.
@@ -37,155 +37,9 @@ class EntityTrackerModel {
37
37
 
38
38
  // set the value dynamiclly
39
39
  if(!$that._isRelationship(currentEntity[modelField])){
40
- // šŸ”„ Apply fromDatabase transformer when building entity from DB row
41
- let transformedValue = modelFieldValue;
42
- try {
43
- transformedValue = FieldTransformer.fromDatabase(
44
- modelFieldValue,
45
- currentEntity[modelField],
46
- currentEntity.__name,
47
- modelField
48
- );
49
- } catch(transformError) {
50
- console.error(`Warning: Failed to transform ${currentEntity.__name}.${modelField} from database: ${transformError.message}`);
51
- // Use original value if transformation fails (non-fatal)
52
- transformedValue = modelFieldValue;
53
- }
54
-
55
- // current entity has a value then add
56
- modelClass["__proto__"]["_" + modelField] = transformedValue;
57
-
58
- Object.defineProperty(modelClass,modelField, {
59
- enumerable: true,
60
- set: function(value) {
61
- // Run validators before setting value
62
- const fieldDef = currentEntity[modelField];
63
- if (fieldDef && fieldDef.validators && Array.isArray(fieldDef.validators)) {
64
- for (const validator of fieldDef.validators) {
65
- let isValid = true;
66
- const errorMsg = validator.message;
67
-
68
- switch (validator.type) {
69
- case 'required':
70
- isValid = value !== null && value !== undefined && value !== '';
71
- break;
72
-
73
- case 'email':
74
- if (value) {
75
- isValid = validator.pattern.test(value);
76
- }
77
- break;
78
-
79
- case 'minLength':
80
- if (value && typeof value === 'string') {
81
- isValid = value.length >= validator.length;
82
- }
83
- break;
84
-
85
- case 'maxLength':
86
- if (value && typeof value === 'string') {
87
- isValid = value.length <= validator.length;
88
- }
89
- break;
90
-
91
- case 'pattern':
92
- if (value) {
93
- isValid = validator.pattern.test(value);
94
- }
95
- break;
96
-
97
- case 'min':
98
- if (value !== null && value !== undefined) {
99
- isValid = Number(value) >= validator.min;
100
- }
101
- break;
102
-
103
- case 'max':
104
- if (value !== null && value !== undefined) {
105
- isValid = Number(value) <= validator.max;
106
- }
107
- break;
108
-
109
- case 'custom':
110
- if (typeof validator.validator === 'function') {
111
- isValid = validator.validator(value);
112
- }
113
- break;
114
- }
115
-
116
- if (!isValid) {
117
- throw new Error(`Validation failed: ${errorMsg}`);
118
- }
119
- }
120
- }
121
-
122
- modelClass.__state = "modified";
123
-
124
- // belongsTo FK columns appear in the DB row but not as
125
- // a top-level key in `__entity` (the entity defines
126
- // the navigation property `Run` with foreignKey:
127
- // 'run_id'; there's no separate 'run_id' field). The
128
- // engine UPDATE/INSERT builders detect belongsTo by
129
- // looking up __entity[<dirtyField>]; pushing 'run_id'
130
- // would crash on `__entity['run_id'].type`. Translate
131
- // the dirty field to the navigation name and mirror
132
- // the value into both backing fields so existing
133
- // belongsTo handling (which reads `_<navName>`) and
134
- // FK-name reads (which read `_<modelField>`) both
135
- // return the new value.
136
- const navNameForFk = (!currentEntity[modelField] && fkToNavName[modelField])
137
- ? fkToNavName[modelField]
138
- : null;
139
- const dirtyName = navNameForFk || modelField;
140
-
141
- // Deduplicate: setting the same field twice used to push
142
- // the name twice, producing duplicate assignments in the
143
- // UPDATE SET clause (`SET col = ?, col = ?`) which is a
144
- // hard error in Postgres and may silently take-last in
145
- // MySQL/SQLite.
146
- if (!modelClass.__dirtyFields.includes(dirtyName)) {
147
- modelClass.__dirtyFields.push(dirtyName);
148
- }
149
- // ensure this entity is tracked on any modification
150
- if(modelClass.__context && typeof modelClass.__context.__track === 'function'){
151
- modelClass.__context.__track(modelClass);
152
- }
153
- // Guard against currentEntity[modelField] being
154
- // undefined (the FK column case described above).
155
- const fieldDefForSet = currentEntity[modelField];
156
- let storedValue;
157
- if(fieldDefForSet && typeof fieldDefForSet.set === "function"){
158
- storedValue = fieldDefForSet.set(value);
159
- }else{
160
- storedValue = value;
161
- }
162
- this["__proto__"]["_" + modelField] = storedValue;
163
- if (navNameForFk) {
164
- // Mirror into the nav-property backing so the
165
- // engine UPDATE builders (which read
166
- // `_<dirtyField>` for belongsTo) find the new
167
- // value.
168
- this["__proto__"]["_" + navNameForFk] = storedValue;
169
- }
170
- },
171
- get:function(){
172
- // TODO: fix only when updating
173
- if(currentEntity[modelField]){
174
- if(!currentEntity[modelField].skipGetFunction){
175
- if(typeof currentEntity[modelField].get === "function"){
176
- return currentEntity[modelField].get(this["__proto__"]["_" + modelField]);
177
- }else{
178
- return this["__proto__"]["_" + modelField];
179
- }
180
- }else{
181
- // If skipGetFunction is true, return the raw value
182
- return this["__proto__"]["_" + modelField];
183
- }
184
- }else{
185
- return this["__proto__"]["_" + modelField];
186
- }
187
- }
188
- });
40
+ // Shared with attachTrackingTo() so a query-built entity and an
41
+ // insert-then-attached entity get IDENTICAL accessors.
42
+ this._defineTrackedColumn(modelClass, modelField, modelFieldValue, currentEntity, fkToNavName, true);
189
43
  }
190
44
  }
191
45
 
@@ -420,6 +274,205 @@ class EntityTrackerModel {
420
274
  return modelClass;
421
275
  }
422
276
 
277
+ /**
278
+ * Define a single tracked column accessor on `target`. Factored out of
279
+ * build() so the SAME code powers query-built entities and entities that
280
+ * are attached in place after an insert (attachTrackingTo). Closures use
281
+ * `this` — the accessor owner — for entity state, so the definition is
282
+ * target-agnostic.
283
+ *
284
+ * @param {boolean} applyFromDb - true when `rawValue` came straight from a
285
+ * DB row (apply the fromDatabase transformer); false when it is already
286
+ * the in-memory domain value of a just-inserted entity.
287
+ */
288
+ _defineTrackedColumn(target, modelField, rawValue, currentEntity, fkToNavName, applyFromDb) {
289
+ let transformedValue = rawValue;
290
+ if (applyFromDb) {
291
+ try {
292
+ transformedValue = FieldTransformer.fromDatabase(
293
+ rawValue,
294
+ currentEntity[modelField],
295
+ currentEntity.__name,
296
+ modelField
297
+ );
298
+ } catch (transformError) {
299
+ console.error(`Warning: Failed to transform ${currentEntity.__name}.${modelField} from database: ${transformError.message}`);
300
+ transformedValue = rawValue;
301
+ }
302
+ }
303
+
304
+ target["__proto__"]["_" + modelField] = transformedValue;
305
+
306
+ Object.defineProperty(target, modelField, {
307
+ enumerable: true,
308
+ set: function(value) {
309
+ // Run validators before setting value
310
+ const fieldDef = currentEntity[modelField];
311
+ if (fieldDef && fieldDef.validators && Array.isArray(fieldDef.validators)) {
312
+ for (const validator of fieldDef.validators) {
313
+ let isValid = true;
314
+ const errorMsg = validator.message;
315
+
316
+ switch (validator.type) {
317
+ case 'required':
318
+ isValid = value !== null && value !== undefined && value !== '';
319
+ break;
320
+
321
+ case 'email':
322
+ if (value) {
323
+ isValid = validator.pattern.test(value);
324
+ }
325
+ break;
326
+
327
+ case 'minLength':
328
+ if (value && typeof value === 'string') {
329
+ isValid = value.length >= validator.length;
330
+ }
331
+ break;
332
+
333
+ case 'maxLength':
334
+ if (value && typeof value === 'string') {
335
+ isValid = value.length <= validator.length;
336
+ }
337
+ break;
338
+
339
+ case 'pattern':
340
+ if (value) {
341
+ isValid = validator.pattern.test(value);
342
+ }
343
+ break;
344
+
345
+ case 'min':
346
+ if (value !== null && value !== undefined) {
347
+ isValid = Number(value) >= validator.min;
348
+ }
349
+ break;
350
+
351
+ case 'max':
352
+ if (value !== null && value !== undefined) {
353
+ isValid = Number(value) <= validator.max;
354
+ }
355
+ break;
356
+
357
+ case 'custom':
358
+ if (typeof validator.validator === 'function') {
359
+ isValid = validator.validator(value);
360
+ }
361
+ break;
362
+ }
363
+
364
+ if (!isValid) {
365
+ throw new Error(`Validation failed: ${errorMsg}`);
366
+ }
367
+ }
368
+ }
369
+
370
+ this.__state = "modified";
371
+
372
+ // belongsTo FK columns appear in the DB row but not as a
373
+ // top-level key in `__entity`; translate the dirty field to the
374
+ // navigation name and mirror the value into both backing fields.
375
+ const navNameForFk = (!currentEntity[modelField] && fkToNavName[modelField])
376
+ ? fkToNavName[modelField]
377
+ : null;
378
+ const dirtyName = navNameForFk || modelField;
379
+
380
+ // Deduplicate: setting the same field twice must not push the
381
+ // name twice (duplicate assignments in the UPDATE SET clause).
382
+ if (!this.__dirtyFields.includes(dirtyName)) {
383
+ this.__dirtyFields.push(dirtyName);
384
+ }
385
+ // Ensure this entity is tracked on any modification. THIS is the
386
+ // line that makes a just-inserted, attached entity's later edits
387
+ // persist instead of being silently dropped.
388
+ if (this.__context && typeof this.__context.__track === 'function') {
389
+ this.__context.__track(this);
390
+ }
391
+ const fieldDefForSet = currentEntity[modelField];
392
+ let storedValue;
393
+ if (fieldDefForSet && typeof fieldDefForSet.set === "function") {
394
+ storedValue = fieldDefForSet.set(value);
395
+ } else {
396
+ storedValue = value;
397
+ }
398
+ this["__proto__"]["_" + modelField] = storedValue;
399
+ if (navNameForFk) {
400
+ this["__proto__"]["_" + navNameForFk] = storedValue;
401
+ }
402
+ },
403
+ get: function() {
404
+ if (currentEntity[modelField]) {
405
+ if (!currentEntity[modelField].skipGetFunction) {
406
+ if (typeof currentEntity[modelField].get === "function") {
407
+ return currentEntity[modelField].get(this["__proto__"]["_" + modelField]);
408
+ } else {
409
+ return this["__proto__"]["_" + modelField];
410
+ }
411
+ } else {
412
+ return this["__proto__"]["_" + modelField];
413
+ }
414
+ } else {
415
+ return this["__proto__"]["_" + modelField];
416
+ }
417
+ }
418
+ });
419
+ }
420
+
421
+ /**
422
+ * Install tracked-column accessors on an EXISTING entity object — a user's
423
+ * `new Model()` that was `add()`ed and just INSERTed. Without this the
424
+ * entity's fields are ordinary own properties, so a later edit
425
+ * (`row.name = 'x'`) is a plain write that never flips the entity to
426
+ * 'modified' — the change is silently dropped on the next saveChanges().
427
+ * After this, the inserted entity behaves like a queried one: edits mark it
428
+ * modified and produce an UPDATE.
429
+ *
430
+ * A per-entity backing layer is spliced into the prototype chain
431
+ * (`Object.create(originalProto)`) so `_<field>` backings stay per-instance
432
+ * while the class prototype — and any lifecycle-hook methods on it — remain
433
+ * reachable.
434
+ */
435
+ attachTrackingTo(target) {
436
+ const currentEntity = target && target.__entity;
437
+ if (!currentEntity) return target;
438
+ if (target.__trackingAttached) return target;
439
+
440
+ const fkToNavName = {};
441
+ for (const k of Object.keys(currentEntity)) {
442
+ const def = currentEntity[k];
443
+ if (def && def.relationshipType === 'belongsTo' && def.foreignKey) {
444
+ fkToNavName[def.foreignKey] = k;
445
+ }
446
+ }
447
+
448
+ // Capture the current scalar values before we replace them with
449
+ // accessors. If a field is already an accessor the entity was built via
450
+ // build() and needs no attaching.
451
+ const scalarFields = [];
452
+ const captured = {};
453
+ for (const modelField of Object.keys(currentEntity)) {
454
+ if (this._isRelationship(currentEntity[modelField])) continue;
455
+ const desc = Object.getOwnPropertyDescriptor(target, modelField);
456
+ if (desc && !('value' in desc)) return target; // already tracked
457
+ captured[modelField] = target[modelField];
458
+ scalarFields.push(modelField);
459
+ }
460
+
461
+ // Splice a fresh backing layer in front of the original prototype so the
462
+ // class prototype (and its lifecycle hooks) stays reachable.
463
+ Object.setPrototypeOf(target, Object.create(Object.getPrototypeOf(target)));
464
+ Object.defineProperty(target, '__trackingAttached', {
465
+ value: true, enumerable: false, writable: true, configurable: true,
466
+ });
467
+
468
+ for (const modelField of scalarFields) {
469
+ // applyFromDb=false: the captured value is already the domain value
470
+ // the user set and that the INSERT persisted — not a raw DB row.
471
+ this._defineTrackedColumn(target, modelField, captured[modelField], currentEntity, fkToNavName, false);
472
+ }
473
+ return target;
474
+ }
475
+
423
476
  buildObject(){
424
477
  return {
425
478
  __ID : Math.floor((Math.random() * 100000) + 1),
package/Migrations/cli.js CHANGED
@@ -11,6 +11,7 @@ import { fileURLToPath, pathToFileURL } from 'node:url';
11
11
  import { globSync } from 'glob';
12
12
  import { resolveMigrationsDirectory, toPosixPath } from './pathUtils.js';
13
13
  import Migration from './migrations.js';
14
+ import schema from './schema.js';
14
15
  import { instantiateReadyContext } from './contextInit.js';
15
16
 
16
17
  const __filename = fileURLToPath(import.meta.url);
@@ -24,8 +25,31 @@ const __dirname = path.dirname(__filename);
24
25
  * @returns {Promise<*>} The default export (or whole module if no default)
25
26
  */
26
27
  async function __loadUserModule(filePath) {
27
- const mod = await import(pathToFileURL(filePath).href);
28
- return (mod && mod.default !== undefined) ? mod.default : mod;
28
+ try {
29
+ const mod = await import(pathToFileURL(filePath).href);
30
+ return (mod && mod.default !== undefined) ? mod.default : mod;
31
+ } catch (err) {
32
+ // A context/migration file typically does `import masterrecord from
33
+ // 'masterrecord'`. In a checkout without installed dependencies, Node
34
+ // throws a cryptic ERR_MODULE_NOT_FOUND naming the BARE specifier, buried
35
+ // in a stack trace. Translate that into an actionable message.
36
+ if (err && err.code === 'ERR_MODULE_NOT_FOUND') {
37
+ const m = /Cannot find package '([^']+)'|Cannot find module '([^']+)'/.exec(err.message || '');
38
+ const missing = m ? (m[1] || m[2]) : null;
39
+ // A bare specifier (not a relative/absolute path) => a missing dependency,
40
+ // not a bad file path. Point the user at `npm install`.
41
+ if (missing && !missing.startsWith('.') && !path.isAbsolute(missing)) {
42
+ const friendly = new Error(
43
+ `masterrecord: could not load '${path.basename(filePath)}' — its dependency '${missing}' is not installed. ` +
44
+ `Run \`npm install\` in your project root first (node_modules is missing or incomplete).`
45
+ );
46
+ friendly.code = 'ERR_MODULE_NOT_FOUND';
47
+ friendly.cause = err;
48
+ throw friendly;
49
+ }
50
+ }
51
+ throw err;
52
+ }
29
53
  }
30
54
 
31
55
  const pkg = JSON.parse(fs.readFileSync(path.join(__dirname, '..', 'package.json'), 'utf8'));
@@ -218,18 +242,6 @@ program.option('-V', 'output the version');
218
242
  console.warn(` Falling back to snapshot directory: ${snapDir}`);
219
243
  migBase = snapDir;
220
244
  }
221
- // Find latest migration file (so we can use its class which extends schema)
222
- let migrationFiles = globSync(`**/*_migration.js`, { cwd: migBase, dot: true, windowsPathsNoEscape: true });
223
- migrationFiles = (migrationFiles || []).map(f => path.resolve(migBase, f));
224
- if(!(migrationFiles && migrationFiles.length)){
225
- console.log("Error - Cannot read or find migration file");
226
- process.exit(1);
227
- }
228
- const mFiles = migrationFiles.slice().sort(function(a, b){
229
- return __getMigrationTimestamp(a) - __getMigrationTimestamp(b);
230
- });
231
- const mFile = mFiles[mFiles.length -1];
232
-
233
245
  let ContextCtor;
234
246
  try{
235
247
  ContextCtor = await __loadUserModule(contextAbs);
@@ -244,9 +256,27 @@ program.option('-V', 'output the version');
244
256
  process.exit(1);
245
257
  }
246
258
 
247
- // Use the migration class (extends schema) so createdatabase is available
248
- const MigrationCtor = await __loadUserModule(mFile);
249
- const mig = new MigrationCtor(ContextCtor);
259
+ // ensure-database's job is to make the database EXIST — that must NOT
260
+ // depend on a migration having been authored yet (otherwise a brand-new
261
+ // context can't be bootstrapped until you've written a migration). When
262
+ // migrations exist we use the latest migration class (it extends schema);
263
+ // otherwise we fall back to the `schema` layer directly, whose
264
+ // createDatabase() is the very method the migration class inherits.
265
+ let migrationFiles = globSync(`**/*_migration.js`, { cwd: migBase, dot: true, windowsPathsNoEscape: true });
266
+ migrationFiles = (migrationFiles || []).map(f => path.resolve(migBase, f));
267
+
268
+ let mig;
269
+ if(migrationFiles.length){
270
+ const mFiles = migrationFiles.slice().sort(function(a, b){
271
+ return __getMigrationTimestamp(a) - __getMigrationTimestamp(b);
272
+ });
273
+ const mFile = mFiles[mFiles.length -1];
274
+ const MigrationCtor = await __loadUserModule(mFile);
275
+ mig = new MigrationCtor(ContextCtor);
276
+ }else{
277
+ console.log('No migration files found — creating the database directly from the context (no migration required).');
278
+ mig = new schema(ContextCtor);
279
+ }
250
280
  contextInstance = mig._context || mig.context || null;
251
281
 
252
282
  if(typeof mig.createdatabase === 'function'){
@@ -1132,20 +1162,24 @@ program.option('-V', 'output the version');
1132
1162
 
1133
1163
  const migration = new Migration();
1134
1164
  const ctxNames = Object.keys(groups);
1165
+ const summary = []; // { ctxName, status, applied } — one row per context
1166
+ let anyFailed = false;
1167
+
1135
1168
  for(const name of ctxNames){
1169
+ let contextInstance;
1136
1170
  try{
1137
1171
  const list = groups[name];
1138
1172
  // Prefer entries that actually have migration files
1139
1173
  const withMigs = list.filter(e => e.migs && e.migs.length > 0);
1140
1174
  const entry = withMigs.length ? withMigs[withMigs.length - 1] : list[0];
1141
1175
  if(!(entry.migs && entry.migs.length)){
1142
- console.log(`Skipping ${entry.ctxName}: no migration files found.`);
1176
+ console.log(`ā­ļø Skipping ${entry.ctxName}: no migration files found.`);
1177
+ summary.push({ ctxName: entry.ctxName, status: 'skipped (no migrations)', applied: 0 });
1143
1178
  continue;
1144
1179
  }
1145
1180
  const mFiles = entry.migs.slice().sort(function(a, b){
1146
1181
  return __getMigrationTimestamp(a) - __getMigrationTimestamp(b);
1147
1182
  });
1148
- const mFile = mFiles[mFiles.length - 1];
1149
1183
 
1150
1184
  var ContextCtor;
1151
1185
  try{
@@ -1153,9 +1187,10 @@ program.option('-V', 'output the version');
1153
1187
  }catch(err){
1154
1188
  console.error(`āš ļø Skipping ${entry.ctxName}: cannot load Context file`);
1155
1189
  console.error(` Details: ${err.message}`);
1190
+ summary.push({ ctxName: entry.ctxName, status: 'FAILED (context load)', applied: 0 });
1191
+ anyFailed = true;
1156
1192
  continue;
1157
1193
  }
1158
- var contextInstance;
1159
1194
  try{
1160
1195
  // Auto-create a missing MySQL/Postgres database (and await async
1161
1196
  // init) via the schema layer before applying migrations.
@@ -1164,35 +1199,116 @@ program.option('-V', 'output the version');
1164
1199
  }catch(err){
1165
1200
  console.error(`āš ļø Skipping ${entry.ctxName}: failed to construct Context`);
1166
1201
  console.error(` Details: ${err.message}`);
1202
+ summary.push({ ctxName: entry.ctxName, status: 'FAILED (context init)', applied: 0 });
1203
+ anyFailed = true;
1167
1204
  continue;
1168
1205
  }
1169
- const migrationProjectFile = await __loadUserModule(mFile);
1170
- const newMigrationProjectInstance = new migrationProjectFile(ContextCtor);
1206
+
1171
1207
  const cleanEntities = migration.cleanEntities(contextInstance.__entities);
1208
+ // Build tableObj once from the current entity state — all pending
1209
+ // migrations share it (mirrors the single-context update-database).
1172
1210
  const tableObj = migration.buildUpObject(entry.cs.schema, cleanEntities);
1173
- await newMigrationProjectInstance.up(tableObj);
1174
- const snap = {
1175
- file : entry.contextAbs,
1176
- executedLocation : executedLocation,
1177
- context : contextInstance,
1178
- contextEntities : cleanEntities,
1179
- contextSeedData: contextInstance.__contextSeedData || {},
1180
- contextSeedConfig: contextInstance.__contextSeedConfig || {},
1181
- contextFileName: entry.ctxName
1211
+
1212
+ // Run EVERY pending migration in order and record each in the
1213
+ // tracking table — the SAME behavior as the single-context
1214
+ // `update-database`. Previously this batch command applied ONLY the
1215
+ // latest migration file and never consulted/wrote the tracking table,
1216
+ // so earlier pending migrations were silently skipped and nothing was
1217
+ // recorded ("schema changes silently stop applying").
1218
+ try {
1219
+ await __ensureMigrationsTable(contextInstance);
1220
+ } catch (err) {
1221
+ console.error(`āŒ ${entry.ctxName}: could not create migration tracking table — ${err.message}`);
1222
+ summary.push({ ctxName: entry.ctxName, status: 'FAILED (tracking table)', applied: 0 });
1223
+ anyFailed = true;
1224
+ continue;
1225
+ }
1226
+
1227
+ const appliedMigrations = await __getAppliedMigrations(contextInstance);
1228
+ const pending = mFiles.filter(f => !appliedMigrations.has(path.basename(f)));
1229
+
1230
+ let appliedCount = 0;
1231
+ let ctxFailed = false;
1232
+ for (const mFile of pending) {
1233
+ const migrationName = path.basename(mFile);
1234
+ try {
1235
+ const MigrationCtor = await __loadUserModule(mFile);
1236
+ const inst = new MigrationCtor(ContextCtor);
1237
+ await inst.up(tableObj);
1238
+ await __recordMigrationApplied(contextInstance, migrationName);
1239
+ appliedCount++;
1240
+ // Release the migration's own context (opened by its schema
1241
+ // constructor) so connections don't accumulate across the batch.
1242
+ try {
1243
+ const mc = inst && (inst.context || inst._context);
1244
+ if (mc && mc !== contextInstance && typeof mc.close === 'function') { await mc.close(); }
1245
+ } catch(_){ /* best-effort teardown */ }
1246
+ } catch (err) {
1247
+ console.error(`āŒ ${entry.ctxName}: migration '${migrationName}' failed — ${err.message}`);
1248
+ console.error(` Earlier migrations (if any) were applied and recorded. Fix and re-run to resume.`);
1249
+ ctxFailed = true;
1250
+ anyFailed = true;
1251
+ break;
1252
+ }
1253
+ }
1254
+
1255
+ if (ctxFailed) {
1256
+ summary.push({ ctxName: entry.ctxName, status: `FAILED (after ${appliedCount} applied)`, applied: appliedCount });
1257
+ } else {
1258
+ if (appliedCount === 0) {
1259
+ console.log(`āœ“ ${entry.ctxName}: up to date (${appliedMigrations.size} on record)`);
1260
+ } else {
1261
+ console.log(`āœ“ ${entry.ctxName}: applied ${appliedCount} migration(s)`);
1262
+ }
1263
+ // Snapshot only a context that fully applied without error.
1264
+ const snap = {
1265
+ file : entry.contextAbs,
1266
+ executedLocation : executedLocation,
1267
+ context : contextInstance,
1268
+ contextEntities : cleanEntities,
1269
+ contextSeedData: contextInstance.__contextSeedData || {},
1270
+ contextSeedConfig: contextInstance.__contextSeedConfig || {},
1271
+ contextFileName: entry.ctxName
1272
+ }
1273
+ migration.createSnapShot(snap);
1274
+ summary.push({ ctxName: entry.ctxName, status: appliedCount === 0 ? 'up to date' : `applied ${appliedCount}`, applied: appliedCount });
1182
1275
  }
1183
- migration.createSnapShot(snap);
1184
- console.log(`āœ“ Database updated successfully for ${entry.ctxName}`);
1185
1276
  }catch(errCtx){
1186
- console.log('Error updating context: ', errCtx);
1277
+ console.log(`Error updating context '${name}': `, errCtx);
1278
+ anyFailed = true;
1279
+ summary.push({ ctxName: name, status: 'FAILED (unexpected)', applied: 0 });
1280
+ } finally {
1281
+ // ISOLATION: release this context's connection(s) before the next.
1282
+ // update-database-all runs every context in one process sharing the
1283
+ // global connection-pool map; tearing each context down per-iteration
1284
+ // makes the batch behave like the safe one-process-per-context run
1285
+ // (1.4.6) and prevents one context's connection state bleeding into
1286
+ // the next.
1287
+ try {
1288
+ if (contextInstance && typeof contextInstance.close === 'function') { await contextInstance.close(); }
1289
+ }catch(_){ /* best-effort teardown */ }
1187
1290
  }
1188
1291
  }
1189
- // Cleanup all contexts
1292
+ // Safety-net cleanup (per-iteration close above already released these;
1293
+ // close() is a no-op once the engine is torn down).
1190
1294
  for(const ctx of contextInstances) {
1191
1295
  if (ctx && typeof ctx.close === 'function') {
1192
1296
  await ctx.close();
1193
1297
  }
1194
1298
  }
1195
- process.exit(0);
1299
+
1300
+ // Loud summary so a deploy log makes it obvious what actually happened —
1301
+ // "0 applied across all contexts" and per-context failures used to look
1302
+ // identical to success.
1303
+ const totalApplied = summary.reduce((n, s) => n + (s.applied || 0), 0);
1304
+ console.log(`\n── update-database-all summary ──`);
1305
+ for (const s of summary) { console.log(` ${s.ctxName}: ${s.status}`); }
1306
+ console.log(` ────`);
1307
+ console.log(` ${summary.length} context(s), ${totalApplied} migration(s) applied${anyFailed ? ', SOME FAILED' : ''}.`);
1308
+
1309
+ // Exit non-zero if any context failed so CI / deploy pipelines detect it
1310
+ // (previously this command always exited 0, hiding failures).
1311
+ process.exit(anyFailed ? 1 : 0);
1196
1312
  }catch(e){
1197
1313
  console.log('Error - Cannot read or find file ', e);
1198
1314
  // Cleanup all contexts