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.
@@ -0,0 +1,86 @@
1
+ /**
2
+ * Shared DDL fragments for Entity Framework Core-style column modeling, used by
3
+ * the SQLite / MySQL / Postgres migration query builders so all three engines
4
+ * render identically-structured clauses:
5
+ *
6
+ * EF masterrecord DDL
7
+ * HasDefaultValueSql -> db.defaultSql(sql) -> DEFAULT <expr>
8
+ * HasComputedColumnSql -> db.computed(sql, {stored}) -> GENERATED ALWAYS AS (<expr>) STORED|VIRTUAL
9
+ * HasCheckConstraint -> db.check(sql, name) -> [CONSTRAINT name] CHECK (<expr>)
10
+ */
11
+
12
+ // Defaults that may appear bare; any other expression is parenthesized
13
+ // (SQLite and MySQL require it, Postgres accepts it). MySQL additionally
14
+ // requires even CURRENT_TIMESTAMP to be parenthesized on TEXT/BLOB/JSON
15
+ // columns (expression defaults, 8.0.13+) — and masterrecord maps every
16
+ // temporal type to TEXT — so on MySQL only literals stay bare.
17
+ const LITERAL_DEFAULT = /^(NULL|TRUE|FALSE|-?\d+(\.\d+)?|'(?:[^']|'')*')$/i;
18
+ const BARE_DEFAULT = /^(CURRENT_TIMESTAMP|CURRENT_DATE|CURRENT_TIME)$/i;
19
+
20
+ /** @param {'sqlite'|'mysql'|'postgres'} [engine] */
21
+ export function defaultSqlClause(col, engine) {
22
+ if (!col || col.defaultSql === undefined || col.defaultSql === null || col.defaultSql === '') return '';
23
+ const sql = String(col.defaultSql).trim();
24
+ const bare = LITERAL_DEFAULT.test(sql)
25
+ || (engine !== 'mysql' && BARE_DEFAULT.test(sql))
26
+ || (sql.startsWith('(') && sql.endsWith(')'));
27
+ return bare ? ` DEFAULT ${sql}` : ` DEFAULT (${sql})`;
28
+ }
29
+
30
+ /** @param {'sqlite'|'mysql'|'postgres'} engine Postgres supports STORED only. */
31
+ export function computedClause(col, engine) {
32
+ if (!col || !col.computedSql) return '';
33
+ const stored = engine === 'postgres' ? true : col.computedStored !== false;
34
+ return ` GENERATED ALWAYS AS (${col.computedSql}) ${stored ? 'STORED' : 'VIRTUAL'}`;
35
+ }
36
+
37
+ /** @param {(name:string)=>string} [quote] identifier quoting for the constraint name */
38
+ export function checkClause(col, quote) {
39
+ if (!col || !col.check) return '';
40
+ const name = col.checkName ? ` CONSTRAINT ${quote ? quote(col.checkName) : col.checkName}` : '';
41
+ return `${name} CHECK (${col.check})`;
42
+ }
43
+
44
+ /** Reject contradictory modeling options up front, with the column named. */
45
+ export function assertDdlOptions(col) {
46
+ if (!col || !col.computedSql) return;
47
+ if (col.default !== undefined && col.default !== null) throw new Error(`masterrecord: column '${col.name}' cannot have both computed() and default().`);
48
+ if (col.defaultSql !== undefined && col.defaultSql !== null) throw new Error(`masterrecord: column '${col.name}' cannot have both computed() and defaultSql().`);
49
+ if (col.primary) throw new Error(`masterrecord: computed column '${col.name}' cannot be the primary key.`);
50
+ if (col.auto) throw new Error(`masterrecord: computed column '${col.name}' cannot be auto-increment.`);
51
+ }
52
+
53
+ /**
54
+ * Primary-key DB column names of an entity definition. More than one means a
55
+ * composite key (EF HasKey(a, b)): the builders then emit a table-level
56
+ * `PRIMARY KEY (a, b)` and no inline PRIMARY KEY / auto-increment.
57
+ */
58
+ export function primaryKeyColumns(table) {
59
+ const out = [];
60
+ for (const key of Object.keys(table || {})) {
61
+ if (key.startsWith('__') || key === 'indexes') continue;
62
+ const col = table[key];
63
+ if (!col || typeof col !== 'object' || col.primary !== true) continue;
64
+ if (col.type === 'hasOne' || col.type === 'hasMany' || col.type === 'hasManyThrough') continue;
65
+ out.push((col.relationshipType === 'belongsTo' && col.foreignKey) ? col.foreignKey : (col.name || key));
66
+ }
67
+ return out;
68
+ }
69
+
70
+ export function compositePrimaryKeyClause(table, quote) {
71
+ const cols = primaryKeyColumns(table);
72
+ if (cols.length < 2) return '';
73
+ for (const key of Object.keys(table)) {
74
+ const col = table[key];
75
+ if (col && typeof col === 'object' && col.primary === true && col.auto) {
76
+ throw new Error(`masterrecord: composite key on '${table.__name}' cannot include the auto-increment column '${col.name || key}' (EF: identity columns are not part of composite keys).`);
77
+ }
78
+ }
79
+ const q = quote || ((n) => n);
80
+ return `PRIMARY KEY (${cols.map(q).join(', ')})`;
81
+ }
82
+
83
+ /** True when the column's value is produced by the database (never written by the ORM). */
84
+ export function isComputedColumn(col) {
85
+ return !!(col && typeof col === 'object' && col.computedSql);
86
+ }
@@ -1,3 +1,4 @@
1
+ import { defaultSqlClause, computedClause, checkClause, assertDdlOptions, compositePrimaryKeyClause } from "./ddlClauses.js";
1
2
 
2
3
  // verison 0.0.4
3
4
  class migrationMySQLQuery {
@@ -21,7 +22,7 @@ class migrationMySQLQuery {
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 changes then call rename column
@@ -38,10 +39,11 @@ class migrationMySQLQuery {
38
39
  */
39
40
  // name TEXT NOT NULL,
40
41
 
41
- const auto = table.auto ? " AUTO_INCREMENT":"";
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) ? " AUTO_INCREMENT":"";
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 tableName = table.name;
47
49
  if(table.relationshipType === 'belongsTo' && table.foreignKey){
@@ -63,7 +65,13 @@ class migrationMySQLQuery {
63
65
  }
64
66
  }
65
67
 
66
- return `\`${tableName}\` ${type}${nullName}${defaultValue}${unique}${primaryKey}${auto}`;
68
+ assertDdlOptions(table);
69
+ const q = (n) => '`' + String(n).replace(/`/g, '``') + '`';
70
+ if (table.computedSql) {
71
+ // DB-generated: no default / PK / autoincrement; the ORM never writes it.
72
+ return `${q(tableName)} ${type}${computedClause(table, 'mysql')}${nullName}${unique}${checkClause(table, q)}`;
73
+ }
74
+ return `${q(tableName)} ${type}${nullName}${defaultValue || defaultSqlClause(table, 'mysql')}${checkClause(table, q)}${unique}${primaryKey}${auto}`;
67
75
  }
68
76
 
69
77
  boolType(type){
@@ -196,6 +204,7 @@ class migrationMySQLQuery {
196
204
  createTable(table){
197
205
 
198
206
  let queryVar = "";
207
+ const compositePk = compositePrimaryKeyClause(table, (n) => '`' + String(n).replace(/`/g, '``') + '`');
199
208
  //console.log("Dsfdsfdsf---------", table)
200
209
  for (const key in table) {
201
210
  // Skip metadata properties (indexes, __compositeIndexes, __name, etc.)
@@ -213,10 +222,11 @@ class migrationMySQLQuery {
213
222
  continue;
214
223
  }
215
224
 
216
- queryVar += `${this.#columnMapping(col)}, `;
225
+ queryVar += `${this.#columnMapping(col, !!compositePk)}, `;
217
226
  }
218
227
  }
219
228
  }
229
+ if (compositePk) queryVar += `${compositePk}, `; // EF HasKey(a, b)
220
230
 
221
231
  const completeQuery = `CREATE TABLE IF NOT EXISTS \`${table.__name}\` (${queryVar.replace(/,\s*$/, "")});`;
222
232
  return completeQuery;
@@ -253,6 +263,15 @@ class migrationMySQLQuery {
253
263
  return `ALTER TABLE \`${table.tableName}\` RENAME COLUMN \`${table.name}\` TO \`${table.newName}\``
254
264
  }
255
265
 
266
+ /** FOREIGN KEY constraint added after both tables exist (MySQL auto-indexes the FK column). */
267
+ addForeignKey(fk){
268
+ return `ALTER TABLE \`${fk.tableName}\` ADD CONSTRAINT \`${fk.name}\` FOREIGN KEY (\`${fk.column}\`) REFERENCES \`${fk.refTable}\` (\`${fk.refColumn}\`) ON DELETE ${fk.onDelete || 'CASCADE'}`;
269
+ }
270
+
271
+ dropForeignKey(fk){
272
+ return `ALTER TABLE \`${fk.tableName}\` DROP FOREIGN KEY \`${fk.name}\``;
273
+ }
274
+
256
275
  createIndex(indexInfo){
257
276
  // MySQL has no partial/filtered indexes — fail loudly rather than
258
277
  // silently emit a non-filtered index (which would enforce the wrong
@@ -1,3 +1,4 @@
1
+ import { defaultSqlClause, computedClause, checkClause, assertDdlOptions, compositePrimaryKeyClause } from "./ddlClauses.js";
1
2
  // Version 1.0.0 - PostgreSQL migration query builder
2
3
  class migrationPostgresQuery {
3
4
 
@@ -20,7 +21,7 @@ class migrationPostgresQuery {
20
21
  return columnList.join(',');
21
22
  }
22
23
 
23
- #columnMapping(table){
24
+ #columnMapping(table, suppressPk = false){
24
25
  /*
25
26
  var mapping = {
26
27
  "name": "id", // if this changes then call rename column
@@ -37,17 +38,18 @@ class migrationPostgresQuery {
37
38
 
38
39
  // PostgreSQL uses SERIAL for auto-increment, not separate AUTO_INCREMENT keyword
39
40
  let auto = "";
40
- let primaryKey = table.primary ? " PRIMARY KEY" : "";
41
- const nullName = table.nullable ? "" : " NOT NULL";
42
- const unique = table.unique ? " UNIQUE" : "";
41
+ // suppressPk: part of a composite key -> emitted as a table-level PRIMARY KEY (a, b)
42
+ let primaryKey = (table.primary && !suppressPk) ? " PRIMARY KEY" : "";
43
+ const nullName = (table.nullable && !(table.primary && suppressPk)) ? "" : " NOT NULL";
44
+ const unique = (table.unique && !(table.primary && suppressPk)) ? " UNIQUE" : ""; // primary() implies unique; a composite key is unique as a whole
43
45
 
44
46
  // For PostgreSQL, if auto-increment primary key, use SERIAL or BIGSERIAL
45
47
  let type;
46
- if(table.auto && table.primary && (table.type === 'integer' || table.type === 'int')){
48
+ if(table.auto && table.primary && !suppressPk && (table.type === 'integer' || table.type === 'int')){
47
49
  type = "SERIAL"; // Auto-incrementing integer
48
50
  auto = "";
49
51
  primaryKey = " PRIMARY KEY";
50
- } else if(table.auto && table.primary && table.type === 'bigint'){
52
+ } else if(table.auto && table.primary && !suppressPk && table.type === 'bigint'){
51
53
  type = "BIGSERIAL";
52
54
  auto = "";
53
55
  primaryKey = " PRIMARY KEY";
@@ -77,7 +79,13 @@ class migrationPostgresQuery {
77
79
  }
78
80
  }
79
81
 
80
- return `"${tableName}" ${type}${nullName}${defaultValue}${unique}${primaryKey}${auto}`;
82
+ assertDdlOptions(table);
83
+ const q = (n) => '"' + String(n).replace(/"/g, '""') + '"';
84
+ if (table.computedSql) {
85
+ // DB-generated (Postgres: STORED only); no default / PK / serial.
86
+ return `${q(tableName)} ${type}${computedClause(table, 'postgres')}${nullName}${unique}${checkClause(table, q)}`;
87
+ }
88
+ return `${q(tableName)} ${type}${nullName}${defaultValue || defaultSqlClause(table, 'postgres')}${checkClause(table, q)}${unique}${primaryKey}${auto}`;
81
89
  }
82
90
 
83
91
  typeManager(type){
@@ -170,6 +178,11 @@ class migrationPostgresQuery {
170
178
  }
171
179
  }
172
180
 
181
+ // Default EXPRESSION (EF HasDefaultValueSql)
182
+ if ((col.default === undefined || col.default === null) && col.defaultSql) {
183
+ statements.push(`ALTER TABLE "${tableName}" ALTER COLUMN "${colName}" SET${defaultSqlClause(col, 'postgres')}`);
184
+ }
185
+
173
186
  // Return array of statements or join them with semicolons
174
187
  return statements.join('; ');
175
188
  }
@@ -210,6 +223,7 @@ class migrationPostgresQuery {
210
223
 
211
224
  createTable(table){
212
225
  let queryVar = "";
226
+ const compositePk = compositePrimaryKeyClause(table, (n) => '"' + String(n).replace(/"/g, '""') + '"');
213
227
 
214
228
  for (const key in table) {
215
229
  // Skip metadata properties (indexes, __compositeIndexes, __name, etc.)
@@ -227,10 +241,11 @@ class migrationPostgresQuery {
227
241
  continue;
228
242
  }
229
243
 
230
- queryVar += `${this.#columnMapping(col)}, `;
244
+ queryVar += `${this.#columnMapping(col, !!compositePk)}, `;
231
245
  }
232
246
  }
233
247
  }
248
+ if (compositePk) queryVar += `${compositePk}, `; // EF HasKey(a, b)
234
249
 
235
250
  const completeQuery = `CREATE TABLE IF NOT EXISTS "${table.__name}" (${queryVar.replace(/,\s*$/, "")});`;
236
251
  return completeQuery;
@@ -240,6 +255,15 @@ class migrationPostgresQuery {
240
255
  return `DROP TABLE IF EXISTS "${name}"`;
241
256
  }
242
257
 
258
+ /** FOREIGN KEY constraint added after both tables exist. */
259
+ addForeignKey(fk){
260
+ return `ALTER TABLE "${fk.tableName}" ADD CONSTRAINT "${fk.name}" FOREIGN KEY ("${fk.column}") REFERENCES "${fk.refTable}" ("${fk.refColumn}") ON DELETE ${fk.onDelete || 'CASCADE'}`;
261
+ }
262
+
263
+ dropForeignKey(fk){
264
+ return `ALTER TABLE "${fk.tableName}" DROP CONSTRAINT IF EXISTS "${fk.name}"`;
265
+ }
266
+
243
267
  renameTable(table){
244
268
  return `ALTER TABLE "${table.tableName}" RENAME TO "${table.newName}"`;
245
269
  }
@@ -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