masterrecord 1.5.17 → 1.22.1

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
@@ -152,6 +152,82 @@ async function __removeMigrationApplied(ctx, migrationName){
152
152
  }
153
153
  }
154
154
 
155
+ /** Applied migrations with timestamps: [{ migration_name, applied_at }] (EF `migrations list`). */
156
+ async function __getAppliedMigrationRows(ctx){
157
+ const engine = ctx._SQLEngine;
158
+ try {
159
+ if (ctx.isSQLite) {
160
+ return engine.db.prepare(`SELECT migration_name, applied_at FROM [${__MIGRATIONS_TABLE__}] ORDER BY applied_at`).all();
161
+ } else if (ctx.isMySQL) {
162
+ return await engine._runWithParams(`SELECT migration_name, applied_at FROM \`${__MIGRATIONS_TABLE__}\` ORDER BY applied_at`, []);
163
+ } else if (ctx.isPostgres) {
164
+ const r = await engine._runWithParams(`SELECT migration_name, applied_at FROM "${__MIGRATIONS_TABLE__}" ORDER BY applied_at`, []);
165
+ return r && r.rows ? r.rows : [];
166
+ }
167
+ } catch (_) { /* table may not exist yet */ }
168
+ return [];
169
+ }
170
+
171
+ /**
172
+ * Apply ONE migration step atomically (EF Core: each migration runs in its own
173
+ * transaction). The migration's DDL/DML and its tracking-table row commit or
174
+ * roll back together, so a failure can never leave a half-applied schema that
175
+ * is (or isn't) recorded.
176
+ * - PostgreSQL: transactional DDL -> BEGIN ... COMMIT.
177
+ * - SQLite: transactional DDL too, but `PRAGMA foreign_keys` is a no-op inside
178
+ * a transaction and the table-rebuild path relies on toggling it, so FK
179
+ * enforcement is switched off BEFORE the transaction and restored after
180
+ * (exactly what EF does for SQLite rebuilds).
181
+ * - MySQL: DDL implicitly commits, so a migration cannot be made atomic there
182
+ * (EF documents the same limitation); statements run directly.
183
+ * Runs on the migration's own context (it shares the engine/connection with
184
+ * `contextInstance`), so the tracking row is written inside the same transaction.
185
+ */
186
+ async function __applyMigrationStep(contextInstance, instance, tableObj, migrationName, direction = 'up'){
187
+ const ctx = (instance && instance.context) ? instance.context : contextInstance;
188
+ const run = async () => {
189
+ if (direction === 'down') await instance.down(tableObj); else await instance.up(tableObj);
190
+ if (typeof instance.finalize === 'function') await instance.finalize();
191
+ if (direction === 'down') await __removeMigrationApplied(ctx, migrationName);
192
+ else await __recordMigrationApplied(ctx, migrationName);
193
+ };
194
+ if (ctx.isMySQL || typeof ctx.transaction !== 'function') { await run(); return 'autocommit'; }
195
+
196
+ let fkWasOn = false;
197
+ if (ctx.isSQLite) {
198
+ await ctx._ensureReady();
199
+ try { fkWasOn = ctx._SQLEngine.db.pragma('foreign_keys', { simple: true }) === 1; } catch (_) { /* older driver */ }
200
+ if (fkWasOn) { try { ctx._SQLEngine.db.pragma('foreign_keys = OFF'); } catch (_) { /* ignore */ } }
201
+ }
202
+ try {
203
+ await ctx.transaction(run);
204
+ return 'transaction';
205
+ } finally {
206
+ if (ctx.isSQLite && fkWasOn) { try { ctx._SQLEngine.db.pragma('foreign_keys = ON'); } catch (_) { /* ignore */ } }
207
+ }
208
+ }
209
+
210
+ /** Resolve everything a migration command needs for a context (snapshot, files, constructor). */
211
+ async function __resolveMigrationPlan(contextFileName){
212
+ const executedLocation = process.cwd();
213
+ contextFileName = String(contextFileName).toLowerCase();
214
+ const files = globSync(`**/*${contextFileName}_contextSnapShot.json`, { cwd: executedLocation, dot: true, windowsPathsNoEscape: true, nocase: true });
215
+ const file = files && files[0] ? path.resolve(executedLocation, files[0]) : null;
216
+ if (!file) {
217
+ throw new Error(`Cannot find Context snapshot '${contextFileName}_contextSnapShot.json' in '${executedLocation}'. Run 'masterrecord enable-migrations ${contextFileName}' first.`);
218
+ }
219
+ const contextSnapshot = __normalizeSnapshotPaths(JSON.parse(fs.readFileSync(file, 'utf8')));
220
+ const snapDir = path.dirname(file);
221
+ const contextAbs = path.resolve(snapDir, contextSnapshot.contextLocation || '');
222
+ let migBase = path.resolve(snapDir, contextSnapshot.migrationFolder || '.');
223
+ if (!fs.existsSync(migBase)) migBase = snapDir;
224
+ const migrationFiles = globSync(`**/*_migration.js`, { cwd: migBase, dot: true, windowsPathsNoEscape: true }) || [];
225
+ const mFiles = migrationFiles.map(f => path.resolve(migBase, f))
226
+ .sort((a, b) => __getMigrationTimestamp(a) - __getMigrationTimestamp(b));
227
+ const ContextCtor = await __loadUserModule(contextAbs);
228
+ return { executedLocation, contextFileName, file, contextSnapshot, contextAbs, migBase, mFiles, ContextCtor };
229
+ }
230
+
155
231
  // Helper to cleanup context and exit
156
232
  async function __cleanupAndExit(contextInstance, exitCode = 0) {
157
233
  try {
@@ -177,6 +253,15 @@ program
177
253
  // Support legacy '-V' as an alias to print version
178
254
  program.option('-V', 'output the version');
179
255
 
256
+ // EF `--connection`: override the env-file connection for this run with a JSON
257
+ // config (optionally keyed by context name), e.g.
258
+ // masterrecord update-database AppContext --connection '{"type":"sqlite","connection":"./tmp/"}'
259
+ program.option('--connection <json>', 'JSON connection config that overrides the environment file for this run');
260
+ program.hook('preAction', () => {
261
+ const opts = program.opts();
262
+ if (opts.connection) process.env.MASTERRECORD_CONNECTION_OVERRIDE = String(opts.connection);
263
+ });
264
+
180
265
  // Instructions : to run command you must go to main project folder is located and run the command using the context file name.
181
266
  program
182
267
  .command('enable-migrations <contextFileName>')
@@ -594,9 +679,10 @@ program.option('-V', 'output the version');
594
679
  try {
595
680
  const MigrationCtor = await __loadUserModule(mFile);
596
681
  const instance = new MigrationCtor(ContextCtor);
597
- await instance.up(tableObj);
598
- await __recordMigrationApplied(contextInstance, migrationName);
599
- console.log(` ✓ applied`);
682
+ // Atomic: DDL + tracking row commit/roll back together (EF: one
683
+ // transaction per migration; MySQL DDL autocommits — see helper).
684
+ const mode = await __applyMigrationStep(contextInstance, instance, tableObj, migrationName, 'up');
685
+ console.log(` ✓ applied${mode === 'transaction' ? ' (transactional)' : ''}`);
600
686
  } catch (err) {
601
687
  console.error(`\n❌ Error - Migration '${migrationName}' failed during execution`);
602
688
  console.error(`\nDetails: ${err.message}`);
@@ -616,7 +702,8 @@ program.option('-V', 'output the version');
616
702
  context : contextInstance,
617
703
  contextEntities : cleanEntities,
618
704
  contextSeedData: contextInstance.__contextSeedData || {},
619
- contextFileName: contextFileName
705
+ contextFileName: contextFileName,
706
+ latestMigration: mFiles.length ? path.basename(mFiles[mFiles.length - 1]) : null
620
707
  }
621
708
 
622
709
  migration.createSnapShot(snap);
@@ -745,6 +832,7 @@ program.option('-V', 'output the version');
745
832
  const migInstance = new MigCtor(ContextCtor);
746
833
  if(typeof migInstance.down === 'function'){
747
834
  await migInstance.down(tableObj);
835
+ if (typeof migInstance.finalize === 'function') await migInstance.finalize();
748
836
  await __removeMigrationApplied(contextInstance, rollbackName);
749
837
  }else{
750
838
  console.log(`Warning - Migration '${rollbackName}' has no down method; skipping.`);
@@ -847,6 +935,7 @@ program.option('-V', 'output the version');
847
935
  const newMigrationProjectInstance = new migrationProjectFile(ContextCtor);
848
936
  const tableObj = migration.buildUpObject(contextSnapshot.schema, cleanEntities);
849
937
  await newMigrationProjectInstance.up(tableObj);
938
+ if (typeof newMigrationProjectInstance.finalize === 'function') await newMigrationProjectInstance.finalize();
850
939
  }
851
940
  const snap = {
852
941
  file : contextAbs,
@@ -868,6 +957,163 @@ program.option('-V', 'output the version');
868
957
  });
869
958
 
870
959
 
960
+ // EF `dotnet ef migrations list`: applied (with timestamps) vs pending.
961
+ program
962
+ .command('migrations-status <contextFileName>')
963
+ .alias('ms')
964
+ .description('Show applied and pending migrations for a context against the database')
965
+ .action(async function(contextFileName){
966
+ let contextInstance = null;
967
+ try {
968
+ const plan = await __resolveMigrationPlan(contextFileName);
969
+ contextInstance = await instantiateReadyContext(plan.ContextCtor);
970
+ const rows = await __getAppliedMigrationRows(contextInstance);
971
+ const appliedMap = new Map(rows.map(r => [r.migration_name, r.applied_at]));
972
+ const names = plan.mFiles.map(f => path.basename(f));
973
+ const pending = names.filter(n => !appliedMap.has(n));
974
+ const orphans = [...appliedMap.keys()].filter(n => !names.includes(n));
975
+ console.log(`Context: ${plan.contextFileName}`);
976
+ console.log(`Migrations folder: ${plan.migBase}`);
977
+ console.log(`\nApplied (${appliedMap.size}):`);
978
+ for (const n of names) if (appliedMap.has(n)) console.log(` ✓ ${n} ${appliedMap.get(n)}`);
979
+ for (const n of orphans) console.log(` ✓ ${n} ${appliedMap.get(n)} [recorded, file missing]`);
980
+ console.log(`\nPending (${pending.length}):`);
981
+ for (const n of pending) console.log(` • ${n}`);
982
+ if (plan.contextSnapshot.latestMigration) console.log(`\nSnapshot latest migration: ${plan.contextSnapshot.latestMigration}`);
983
+ await __cleanupAndExit(contextInstance, 0);
984
+ } catch (e) {
985
+ console.error(`❌ migrations-status failed: ${e.message}`);
986
+ await __cleanupAndExit(contextInstance, 1);
987
+ }
988
+ });
989
+
990
+ // EF `dotnet ef migrations remove`: delete the LATEST migration file. Like EF
991
+ // it refuses when that migration has been applied to the database, unless
992
+ // `--force`, which reverts it (down, in its own transaction) first. The
993
+ // snapshot needs no rewrite for a pending migration: masterrecord's snapshot
994
+ // reflects the APPLIED database state (it is updated by update-database).
995
+ program
996
+ .command('remove-migration <contextFileName>')
997
+ .alias('rm')
998
+ .option('-f, --force', 'revert the migration if it has been applied, then remove it')
999
+ .description('Remove the latest migration file (EF: migrations remove); refuses an applied migration unless --force')
1000
+ .action(async function(contextFileName, cmdOpts){
1001
+ let contextInstance = null;
1002
+ try {
1003
+ const plan = await __resolveMigrationPlan(contextFileName);
1004
+ if (!plan.mFiles.length) {
1005
+ console.log(`No migration files found in ${plan.migBase}.`);
1006
+ process.exit(0);
1007
+ }
1008
+ const latest = plan.mFiles[plan.mFiles.length - 1];
1009
+ const name = path.basename(latest);
1010
+ contextInstance = await instantiateReadyContext(plan.ContextCtor);
1011
+ const rows = await __getAppliedMigrationRows(contextInstance);
1012
+ const appliedNames = new Set(rows.map(r => r.migration_name));
1013
+ if (appliedNames.has(name)) {
1014
+ if (!(cmdOpts && cmdOpts.force)) {
1015
+ console.error(`❌ Migration '${name}' has been applied to the database. Revert it first with 'masterrecord update-database-down ${plan.contextFileName}', or pass --force to revert and remove it.`);
1016
+ await __cleanupAndExit(contextInstance, 1);
1017
+ return;
1018
+ }
1019
+ // --force: revert (down) atomically, then remove.
1020
+ const migration = new Migration();
1021
+ const cleanEntities = migration.cleanEntities(contextInstance.__entities);
1022
+ const tableObj = migration.buildUpObject(plan.contextSnapshot.schema, cleanEntities);
1023
+ const MigCtor = await __loadUserModule(latest);
1024
+ const instance = new MigCtor(plan.ContextCtor);
1025
+ if (typeof instance.down !== 'function') throw new Error(`Migration '${name}' has no down() method; cannot revert it.`);
1026
+ const mode = await __applyMigrationStep(contextInstance, instance, tableObj, name, 'down');
1027
+ console.log(`↩ Reverted '${name}' (${mode})`);
1028
+ try { if (instance.context && instance.context !== contextInstance && typeof instance.context.close === 'function') await instance.context.close(); } catch (_) { /* best-effort */ }
1029
+ // Snapshot follows the applied state: previous applied migration becomes the latest.
1030
+ const remaining = plan.mFiles.filter(f => path.basename(f) !== name && appliedNames.has(path.basename(f)));
1031
+ migration.createSnapShot({
1032
+ file: plan.contextAbs, executedLocation: plan.executedLocation, context: contextInstance,
1033
+ contextEntities: cleanEntities,
1034
+ contextSeedData: contextInstance.__contextSeedData || {},
1035
+ contextSeedConfig: contextInstance.__contextSeedConfig || {},
1036
+ contextFileName: plan.contextFileName,
1037
+ latestMigration: remaining.length ? path.basename(remaining[remaining.length - 1]) : null,
1038
+ });
1039
+ }
1040
+ fs.unlinkSync(latest);
1041
+ console.log(`✓ Removed migration '${name}'`);
1042
+ await __cleanupAndExit(contextInstance, 0);
1043
+ } catch (e) {
1044
+ console.error(`❌ remove-migration failed: ${e.message}`);
1045
+ await __cleanupAndExit(contextInstance, 1);
1046
+ }
1047
+ });
1048
+
1049
+ // EF `dotnet ef migrations script`: the SQL for pending migrations, NOT applied.
1050
+ program
1051
+ .command('script <contextFileName>')
1052
+ .option('-o, --output <file>', 'write the SQL to a file instead of stdout')
1053
+ .description('Generate the SQL for pending migrations without applying them (for DBA review)')
1054
+ .action(async function(contextFileName, cmdOpts){
1055
+ let contextInstance = null;
1056
+ try {
1057
+ const plan = await __resolveMigrationPlan(contextFileName);
1058
+ contextInstance = await instantiateReadyContext(plan.ContextCtor);
1059
+ const applied = await __getAppliedMigrations(contextInstance);
1060
+ const pending = plan.mFiles.filter(f => !applied.has(path.basename(f)));
1061
+ const migration = new Migration();
1062
+ const cleanEntities = migration.cleanEntities(contextInstance.__entities);
1063
+ const tableObj = migration.buildUpObject(plan.contextSnapshot.schema, cleanEntities);
1064
+ const lines = [
1065
+ `-- masterrecord migration script for '${plan.contextFileName}'`,
1066
+ `-- generated ${new Date().toISOString()} — ${pending.length} pending migration(s). This script was NOT applied.`,
1067
+ `-- Introspection (table/column checks) ran against the live database; statements below are what update-database would execute.`,
1068
+ '',
1069
+ ];
1070
+ const fmt = (q, p) => {
1071
+ const s = String(q).replace(/\s+/g, ' ').trim().replace(/;$/, '');
1072
+ return (p && p.length) ? `${s}; -- params: ${JSON.stringify(p)}` : `${s};`;
1073
+ };
1074
+ for (const mFile of pending) {
1075
+ const name = path.basename(mFile);
1076
+ const MigrationCtor = await __loadUserModule(mFile);
1077
+ const instance = new MigrationCtor(plan.ContextCtor);
1078
+ const mctx = instance.context || contextInstance;
1079
+ const captured = [];
1080
+ // Capture instead of execute: schema.js issues all DDL/DML through
1081
+ // context._execute; engine-level introspection (tableExists/getTableInfo)
1082
+ // is untouched so the plan reflects the real database state.
1083
+ const patch = (c) => {
1084
+ const orig = c._execute;
1085
+ c._execute = (q, p) => { captured.push(fmt(q, p)); return Promise.resolve({ changes: 0, rowCount: 0, affectedRows: 0 }); };
1086
+ return () => { c._execute = orig; };
1087
+ };
1088
+ const restores = [patch(mctx)];
1089
+ if (mctx !== contextInstance) restores.push(patch(contextInstance));
1090
+ try {
1091
+ await instance.up(tableObj);
1092
+ if (typeof instance.finalize === 'function') await instance.finalize();
1093
+ await __recordMigrationApplied(mctx, name); // captured, not executed
1094
+ } finally {
1095
+ for (const r of restores) r();
1096
+ }
1097
+ lines.push(`-- Migration: ${name}`);
1098
+ lines.push(...captured);
1099
+ lines.push('');
1100
+ try { if (mctx !== contextInstance && typeof mctx.close === 'function') await mctx.close(); } catch (_) { /* best-effort */ }
1101
+ }
1102
+ const out = lines.join('\n');
1103
+ if (cmdOpts && cmdOpts.output) {
1104
+ const target = path.resolve(cmdOpts.output);
1105
+ fs.writeFileSync(target, out, 'utf8');
1106
+ console.log(`✓ SQL script for ${pending.length} pending migration(s) written to ${target}`);
1107
+ } else {
1108
+ process.stdout.write(out + '\n');
1109
+ }
1110
+ await __cleanupAndExit(contextInstance, 0);
1111
+ } catch (e) {
1112
+ console.error(`❌ script failed: ${e.message}`);
1113
+ await __cleanupAndExit(contextInstance, 1);
1114
+ }
1115
+ });
1116
+
871
1117
  program
872
1118
  .command('get-migrations <contextFileName>')
873
1119
  .alias('gm')
@@ -1004,6 +1250,7 @@ program.option('-V', 'output the version');
1004
1250
  const migInstance = new MigCtor(ContextCtor);
1005
1251
  if(typeof migInstance.down === 'function'){
1006
1252
  await migInstance.down(tableObj);
1253
+ if (typeof migInstance.finalize === 'function') await migInstance.finalize();
1007
1254
  } else {
1008
1255
  console.log(`Warning - Migration '${path.basename(migFile)}' has no down method; skipping.`);
1009
1256
  }
@@ -1234,8 +1481,7 @@ program.option('-V', 'output the version');
1234
1481
  try {
1235
1482
  const MigrationCtor = await __loadUserModule(mFile);
1236
1483
  const inst = new MigrationCtor(ContextCtor);
1237
- await inst.up(tableObj);
1238
- await __recordMigrationApplied(contextInstance, migrationName);
1484
+ await __applyMigrationStep(contextInstance, inst, tableObj, migrationName, 'up');
1239
1485
  appliedCount++;
1240
1486
  // Release the migration's own context (opened by its schema
1241
1487
  // constructor) so connections don't accumulate across the batch.
@@ -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
  }