masterrecord 1.3.3 → 1.5.6

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/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
@@ -94,13 +94,18 @@ class migrationMySQLQuery {
94
94
  case "decimal":
95
95
  return "DECIMAL"
96
96
  case "datetime":
97
- return "DATETIME"
98
97
  case "timestamp":
99
- return "TIMESTAMP"
100
98
  case "date":
101
- return "DATE"
102
99
  case "time":
103
- return "TIME"
100
+ // Match the SQLite and Postgres engines, which store every
101
+ // temporal type as TEXT "for cross-engine portability":
102
+ // masterrecord apps write epoch-millis / ISO strings into these
103
+ // columns (entity get/set hooks like `db.get((v) => v || Date.now())`),
104
+ // which native DATETIME/TIMESTAMP/DATE/TIME columns reject at
105
+ // INSERT (e.g. "Incorrect datetime value" for a bigint). TEXT
106
+ // keeps the engines interchangeable. (Postgres was fixed in
107
+ // 1.4.7; MySQL had the identical bug.)
108
+ return "TEXT"
104
109
  case "boolean":
105
110
  return "TINYINT"
106
111
  case "integer":
@@ -129,7 +134,7 @@ class migrationMySQLQuery {
129
134
 
130
135
  if(table){
131
136
 
132
- return `ALTER TABLE \`${table.tableName}\` MODIFY COLUMN ${this.#columnMapping(table.table)} `;
137
+ return `ALTER TABLE \`${table.tableName}\` MODIFY COLUMN ${this.#columnMapping(table.table || table)} `;
133
138
  }
134
139
  else{
135
140
  console.log("table information is null");
@@ -174,14 +179,13 @@ class migrationMySQLQuery {
174
179
  is indexed
175
180
  appears in a view
176
181
 
177
- `IF EXISTS` was added in MySQL 8.0.24. Safe to emit unconditionally
178
- — older MySQL/MariaDB versions will reject this DDL syntax, but
179
- identifier quoting + IF EXISTS is the modern standard and matches
180
- Postgres' behavior. Consumers on MySQL <8.0.24 should pin
181
- masterrecord to <1.0.8 or use raw _execute() for drop-column
182
- migrations.
182
+ No `IF EXISTS`: MySQL has never supported it on DROP COLUMN (that is
183
+ MariaDB syntax), and emitting it made every drop-column migration fail
184
+ with ER_PARSE_ERROR — silently, when the caller swallowed the error.
185
+ schema.dropColumn() probes the live schema first and skips a column
186
+ that is already gone, so drops stay idempotent without the clause.
183
187
  */
184
- return `ALTER TABLE \`${table.tableName}\` DROP COLUMN IF EXISTS \`${table.name}\``;
188
+ return `ALTER TABLE \`${table.tableName}\` DROP COLUMN \`${table.name}\``;
185
189
  }
186
190
 
187
191
  insertInto(name, table){
@@ -234,7 +238,11 @@ class migrationMySQLQuery {
234
238
 
235
239
 
236
240
  dropTable(name){
237
- return `DROP TABLE \`${name}\``
241
+ // IF EXISTS keeps dropTable idempotent — consistent with createTable's
242
+ // `IF NOT EXISTS` and dropColumn's skip-if-gone, and matching the Postgres
243
+ // builder. A migration that DROPs a legacy table which never existed on a
244
+ // fresh install is then a no-op instead of a hard failure.
245
+ return `DROP TABLE IF EXISTS \`${name}\``
238
246
  }
239
247
 
240
248
  renameTable(table){
@@ -95,13 +95,17 @@ class migrationPostgresQuery {
95
95
  case "decimal":
96
96
  return "DECIMAL"
97
97
  case "datetime":
98
- return "TIMESTAMP"
99
98
  case "timestamp":
100
- return "TIMESTAMP"
101
99
  case "date":
102
- return "DATE"
103
100
  case "time":
104
- return "TIME"
101
+ // Match the SQLite engine, which stores every temporal type as
102
+ // TEXT "for cross-engine portability": masterrecord apps write
103
+ // epoch-millis / ISO strings into these columns (entity get/set
104
+ // hooks like `db.get((v) => v || Date.now())`), which native
105
+ // TIME/TIMESTAMP/DATE columns reject at INSERT
106
+ // ("column is of type time without time zone but expression is
107
+ // of type bigint"). TEXT keeps the engines interchangeable.
108
+ return "TEXT"
105
109
  case "boolean":
106
110
  case "bool":
107
111
  return "BOOLEAN" // PostgreSQL native boolean type
@@ -130,9 +134,14 @@ class migrationPostgresQuery {
130
134
  if(table){
131
135
  // PostgreSQL uses different syntax for ALTER COLUMN
132
136
  // ALTER TABLE table_name ALTER COLUMN column_name TYPE new_type;
133
- const colName = table.table.name;
137
+ // buildUpObject exposes column entries FLAT ({...columnDef, tableName});
138
+ // older callers pass a nested { table: columnDef, tableName } shape.
139
+ // Accept both — the nested access crashed generated CatchUp
140
+ // migrations with "Cannot read properties of undefined ('name')".
141
+ const col = table.table || table;
142
+ const colName = col.name;
134
143
  const tableName = table.tableName;
135
- const type = this.typeManager(table.table.type);
144
+ const type = this.typeManager(col.type);
136
145
 
137
146
  // Build ALTER statements - PostgreSQL requires separate statements for different changes
138
147
  const statements = [];
@@ -141,19 +150,19 @@ class migrationPostgresQuery {
141
150
  statements.push(`ALTER TABLE "${tableName}" ALTER COLUMN "${colName}" TYPE ${type}`);
142
151
 
143
152
  // Change nullability
144
- if(table.table.nullable === false){
153
+ if(col.nullable === false){
145
154
  statements.push(`ALTER TABLE "${tableName}" ALTER COLUMN "${colName}" SET NOT NULL`);
146
- } else if(table.table.nullable === true){
155
+ } else if(col.nullable === true){
147
156
  statements.push(`ALTER TABLE "${tableName}" ALTER COLUMN "${colName}" DROP NOT NULL`);
148
157
  }
149
158
 
150
159
  // Change default
151
- if(table.table.default !== undefined && table.table.default !== null){
152
- let def = table.table.default;
153
- if(table.table.type === 'boolean'){
160
+ if(col.default !== undefined && col.default !== null){
161
+ let def = col.default;
162
+ if(col.type === 'boolean'){
154
163
  def = (def === true || def === 'true') ? 'TRUE' : 'FALSE';
155
164
  statements.push(`ALTER TABLE "${tableName}" ALTER COLUMN "${colName}" SET DEFAULT ${def}`);
156
- } else if(table.table.type === 'integer' || table.table.type === 'float'){
165
+ } else if(col.type === 'integer' || col.type === 'float'){
157
166
  statements.push(`ALTER TABLE "${tableName}" ALTER COLUMN "${colName}" SET DEFAULT ${def}`);
158
167
  } else {
159
168
  const esc = String(def).replace(/'/g, "''");
@@ -214,7 +214,11 @@ class migrationSQLiteQuery {
214
214
 
215
215
 
216
216
  dropTable(name){
217
- return `DROP TABLE ${name}`
217
+ // IF EXISTS keeps dropTable idempotent — consistent with createTable's
218
+ // `IF NOT EXISTS` and dropColumn's skip-if-gone, and matching the Postgres
219
+ // builder. A migration that DROPs a legacy table which never existed on a
220
+ // fresh install is then a no-op instead of a hard failure.
221
+ return `DROP TABLE IF EXISTS ${name}`
218
222
  }
219
223
 
220
224
  renameTable(table){
@@ -54,12 +54,22 @@ export default ${this.name};
54
54
  }
55
55
  }
56
56
 
57
+ // A column statement needs a column name to produce valid DDL. When the
58
+ // diff can't resolve one (e.g. a phantom column from a metadata key), the
59
+ // spec is `{tableName}` with no `name` — emitting it would bake a malformed
60
+ // no-op like `addColumn({"tableName":"X"})`. Refuse to emit those.
61
+ #isEmittableColumnSpec(spec){
62
+ return !!(spec && typeof spec === 'object'
63
+ && spec.name !== undefined && spec.name !== null && spec.name !== '');
64
+ }
65
+
57
66
  // Bake the resolved column spec inline so the migration is self-contained
58
67
  // and replays deterministically on every database — independent of the
59
68
  // committed snapshot's state at apply time. (Previously emitted
60
69
  // `table.<col>`, re-derived from a live diff, which silently no-op'd when
61
70
  // the snapshot was already ahead of the target DB.)
62
71
  addColumn(type, spec){
72
+ if(!this.#isEmittableColumnSpec(spec)){ return; }
63
73
  const stmt = ` await this.addColumn(${JSON.stringify(spec)});`;
64
74
  if(type === "up"){ this.#up += os.EOL + stmt; }
65
75
  else{ this.#down += os.EOL + stmt; }
@@ -75,6 +85,7 @@ export default ${this.name};
75
85
  }
76
86
 
77
87
  dropColumn(type, spec){
88
+ if(!this.#isEmittableColumnSpec(spec)){ return; }
78
89
  const stmt = ` await this.dropColumn(${JSON.stringify(spec)});`;
79
90
  if(type === "up"){ this.#up += os.EOL + stmt; }
80
91
  else{ this.#down += os.EOL + stmt; }
@@ -91,9 +91,25 @@ class Migrations{
91
91
  let deletedColumn = null;
92
92
  if(item.new && item.old){
93
93
  Object.keys(item.old).forEach(function (key) {
94
+ // Only real column objects carry a `.name`. Metadata keys
95
+ // like `__name` are plain strings; reading `.name` off them
96
+ // yields undefined, which used to be pushed as a phantom
97
+ // deleted column — making hasChanges() spuriously true and
98
+ // baking a malformed `addColumn({"tableName":"X"})` no-op
99
+ // into the generated migration's down(). Skip non-columns.
100
+ // (This guard mirrors #findNewColumns, which already had it.)
101
+ if(typeof item.old[key] !== "object" || item.old[key] === null){
102
+ return;
103
+ }
94
104
  const value = item.old[key].name;
105
+ if(value === undefined || value === null || value === ''){
106
+ return;
107
+ }
95
108
  deletedColumn = null;
96
109
  Object.keys(item.new).forEach(function (newKey) {
110
+ if(typeof item.new[newKey] !== "object" || item.new[newKey] === null){
111
+ return;
112
+ }
97
113
  const newValue = item.new[newKey].name;
98
114
  if(value === newValue){
99
115
  deletedColumn = value;
@@ -295,18 +295,21 @@ class schema{
295
295
  }
296
296
  if(table){
297
297
  if(this.fullTable){
298
- // SQLite doesn't support `IF EXISTS` on DROP COLUMN, so
299
- // emulate it here: probe getTableInfo and bail out if the
300
- // column is already gone. Postgres + MySQL emit the
301
- // `IF EXISTS` clause directly in their DDL.
302
- if(this.context.isSQLite){
298
+ // Neither SQLite nor MySQL supports `IF EXISTS` on DROP COLUMN
299
+ // (MySQL never has — that is MariaDB syntax), so emulate it for
300
+ // both: probe the live schema and bail out if the column is
301
+ // already gone. Only Postgres emits the clause in its DDL.
302
+ if(this.context.isSQLite || this.context.isMySQL){
303
303
  if (typeof this.context._SQLEngine.getTableInfo === 'function') {
304
304
  const cols = await this.context._SQLEngine.getTableInfo(table.tableName);
305
- const exists = Array.isArray(cols) && cols.some(c => c && (c.name === table.name));
305
+ const exists = Array.isArray(cols) && cols.some(c => c && (c.name === table.name || c.COLUMN_NAME === table.name));
306
306
  if (!exists) {
307
307
  return;
308
308
  }
309
309
  }
310
+ }
311
+
312
+ if(this.context.isSQLite){
310
313
  var queryBuilder = new sqliteQuery();
311
314
  var query = queryBuilder.dropColumn(table);
312
315
  await this.context._execute(query);
@@ -411,11 +414,16 @@ class schema{
411
414
  if(col.type === 'hasOne' || col.type === 'hasMany' || col.type === 'hasManyThrough') continue;
412
415
  const colName = (col.relationshipType === 'belongsTo' && col.foreignKey) ? col.foreignKey : col.name;
413
416
  if(!existingNames.has(colName)){
414
- // add column
417
+ // add column — carry the WHOLE definition, not just the
418
+ // name/type. Dropping `nullable`/`unique`/`default` here
419
+ // made every synced column NOT NULL (columnMapping treats a
420
+ // missing `nullable` as false), so a later insert that left
421
+ // the column empty failed against a column the entity had
422
+ // declared optional.
415
423
  const newCol = {
424
+ ...col,
416
425
  tableName: tableName,
417
- name: colName,
418
- type: col.type
426
+ name: colName
419
427
  };
420
428
  // MySQL path uses addColum with realDataType
421
429
  if(this.context.isSQLite){
@@ -527,26 +535,98 @@ class schema{
527
535
  }
528
536
  }
529
537
 
538
+ if(this.context.isPostgres){
539
+ // Reconcile nullability and defaults, the way the MySQL branch
540
+ // above does. Without this a column that was created NOT NULL by
541
+ // an older sync stayed NOT NULL forever, even though the entity
542
+ // declared it optional.
543
+ const byName = {};
544
+ for(const row of existing){ byName[row.name] = row; }
545
+ for(const d of desiredCols){
546
+ const row = byName[d.name];
547
+ if(!row) continue;
548
+ if(d.col.primary) continue; // never touch the key
549
+ const desiredNotNull = d.col.nullable === false;
550
+ const existingNullable = String(row.is_nullable || '').toUpperCase() === 'YES';
551
+ if(desiredNotNull && existingNullable){
552
+ // Only safe when no row would violate it; Postgres tells us
553
+ // by failing, and a failure here must not abort the deploy.
554
+ try {
555
+ await this.context._execute(`ALTER TABLE "${tableName}" ALTER COLUMN "${d.name}" SET NOT NULL`);
556
+ } catch (e) {
557
+ if(process.env.MR_SILENT_MIGRATIONS !== 'true'){
558
+ console.log(`[masterrecord:sync] could not set NOT NULL on ${tableName}.${d.name}: ${e.message}`);
559
+ }
560
+ }
561
+ } else if(!desiredNotNull && !existingNullable){
562
+ await this.context._execute(`ALTER TABLE "${tableName}" ALTER COLUMN "${d.name}" DROP NOT NULL`);
563
+ }
564
+ }
565
+ }
566
+
530
567
  if(needRebuildSQLite()){
531
- var queryBuilder = new sqliteQuery();
532
- // rename old table
533
- const rename = queryBuilder.renameTable({ tableName, newName: "_temp_alter_column_update" });
534
- await this.context._execute(rename);
535
- // create new with desired schema
536
- const create = queryBuilder.createTable(table);
537
- await this.context._execute(create);
538
- // compute common columns
539
- const oldInfo = await engine.getTableInfo(tableName.replace(/.*/, '_temp_alter_column_update')) || await engine.getTableInfo("_temp_alter_column_update");
540
- const oldNames = new Set((oldInfo || existing).map(r => r.name));
541
- const newNames = desiredCols.map(d => d.name);
542
- const common = newNames.filter(n => oldNames.has(n));
543
- if(common.length > 0){
544
- const cols = common.join(',');
545
- const insert = `INSERT INTO ${tableName} (${cols}) SELECT ${cols} FROM _temp_alter_column_update`;
546
- await this.context._execute(insert);
547
- }
548
- const drop = queryBuilder.dropTable("_temp_alter_column_update");
549
- await this.context._execute(drop);
568
+ var queryBuilder = new sqliteQuery();
569
+ const TEMP = "_temp_alter_column_update";
570
+
571
+ // A rebuild is rename -> create -> copy -> drop. Every step after the
572
+ // rename is a step where the table's contents live only in TEMP, so a
573
+ // failure there used to leave the original renamed away and the new
574
+ // table empty. Anything that goes wrong now puts the original back.
575
+ const leftovers = await engine.getTableInfo(TEMP);
576
+ if(leftovers && leftovers.length){
577
+ // A previous run died mid-rebuild. Its data is the real data.
578
+ await this.context._execute(queryBuilder.dropTable(tableName));
579
+ await this.context._execute(`ALTER TABLE ${TEMP} RENAME TO ${tableName}`);
580
+ }
581
+
582
+ // Foreign keys must be off for the duration. The rebuild drops the
583
+ // renamed original, and a child table with ON DELETE CASCADE takes
584
+ // that as its parent disappearing — rebuilding Post silently emptied
585
+ // Kudos, Poll, PollOption, PollVote, PostComment and PostLike.
586
+ // SQLite's own "making other kinds of table schema changes" recipe
587
+ // prescribes exactly this.
588
+ let fkWasOn = false;
589
+ try {
590
+ const fk = await engine.query('PRAGMA foreign_keys');
591
+ fkWasOn = !!(fk && fk[0] && (fk[0].foreign_keys === 1 || fk[0].foreign_keys === true));
592
+ } catch { /* pragma unavailable — treat as off */ }
593
+ if(fkWasOn) await this.context._execute('PRAGMA foreign_keys = OFF');
594
+
595
+ await this.context._execute(queryBuilder.renameTable({ tableName, newName: TEMP }));
596
+ try {
597
+ await this.context._execute(queryBuilder.createTable(table));
598
+
599
+ const oldInfo = await engine.getTableInfo(TEMP);
600
+ const oldNames = new Set((oldInfo || existing).map(r => r.name));
601
+ const common = desiredCols.filter(d => oldNames.has(d.name));
602
+ if(common.length > 0){
603
+ // A column that is NOT NULL now may hold NULLs in rows written
604
+ // before it was required. Copying those verbatim fails the
605
+ // constraint and costs the whole table, so they take the
606
+ // column's default — or a typed zero value when it has none.
607
+ const cols = common.map(d => d.name).join(',');
608
+ const selects = common.map(d => {
609
+ if(d.col.nullable !== false) return d.name;
610
+ let fallback = d.col.default;
611
+ if(fallback == null){
612
+ const t = String(d.col.type || '').toLowerCase();
613
+ fallback = (t === 'integer' || t === 'float' || t === 'decimal' || t === 'boolean') ? 0 : "''";
614
+ } else if(typeof fallback === 'string'){
615
+ fallback = `'${fallback.replace(/'/g, "''")}'`;
616
+ }
617
+ return `COALESCE(${d.name}, ${fallback})`;
618
+ }).join(',');
619
+ await this.context._execute(`INSERT INTO ${tableName} (${cols}) SELECT ${selects} FROM ${TEMP}`);
620
+ }
621
+ await this.context._execute(queryBuilder.dropTable(TEMP));
622
+ } catch(err) {
623
+ // Put the table back exactly as it was, then report.
624
+ try { await this.context._execute(queryBuilder.dropTable(tableName)); } catch { /* never created */ }
625
+ await this.context._execute(`ALTER TABLE ${TEMP} RENAME TO ${tableName}`);
626
+ throw err;
627
+ } finally {
628
+ if(fkWasOn) await this.context._execute('PRAGMA foreign_keys = ON');
629
+ }
550
630
  }
551
631
  }
552
632