masterrecord 1.0.7 → 1.0.8

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.
@@ -185,8 +185,15 @@ class migrationMySQLQuery {
185
185
  has unique constraint
186
186
  is indexed
187
187
  appears in a view
188
+
189
+ `IF EXISTS` was added in MySQL 8.0.24. Safe to emit unconditionally
190
+ — older MySQL/MariaDB versions will reject this DDL syntax, but
191
+ identifier quoting + IF EXISTS is the modern standard and matches
192
+ Postgres' behavior. Consumers on MySQL <8.0.24 should pin
193
+ masterrecord to <1.0.8 or use raw _execute() for drop-column
194
+ migrations.
188
195
  */
189
- return `ALTER TABLE \`${table.tableName}\` DROP COLUMN \`${table.name}\``;
196
+ return `ALTER TABLE \`${table.tableName}\` DROP COLUMN IF EXISTS \`${table.name}\``;
190
197
  }
191
198
 
192
199
  insertInto(name, table){
@@ -186,9 +186,12 @@ class migrationPostgresQuery {
186
186
  dropColumn(table){
187
187
  /*
188
188
  PostgreSQL DROP COLUMN is more flexible than SQLite
189
- Can drop columns with constraints if CASCADE is used
189
+ Can drop columns with constraints if CASCADE is used.
190
+ `IF EXISTS` makes drop-column migrations idempotent: re-running a
191
+ migration after a failed/partial earlier run no longer errors with
192
+ `column "X" does not exist`.
190
193
  */
191
- return `ALTER TABLE "${table.tableName}" DROP COLUMN "${table.name}"`;
194
+ return `ALTER TABLE "${table.tableName}" DROP COLUMN IF EXISTS "${table.name}"`;
192
195
  }
193
196
 
194
197
  insertInto(name, table){
@@ -142,12 +142,13 @@ class migrationSQLiteQuery {
142
142
 
143
143
  dropColumn(table){
144
144
  /*
145
- COLUMNS CANNOT BE DROPPED - RULES
146
- has unique constraint
147
- is indexed
148
- appears in a view
145
+ SQLite added DROP COLUMN in 3.35 (2021). SQLite does NOT support
146
+ `IF EXISTS` on DROP COLUMN; idempotency is handled one level up
147
+ in schema.dropColumn() which checks via getTableInfo before
148
+ emitting this DDL. Square brackets quote the identifiers for
149
+ consistency with the rest of the SQLite engine output.
149
150
  */
150
- return `ALTER TABLE ${table.tableName} DROP COLUMN ${table.name}`
151
+ return `ALTER TABLE [${table.tableName}] DROP COLUMN [${table.name}]`
151
152
  }
152
153
 
153
154
  insertInto(name, table){
@@ -247,21 +247,31 @@ class schema{
247
247
  async dropColumn(table){
248
248
  if(table){
249
249
  if(this.fullTable){
250
- // drop column
250
+ // SQLite doesn't support `IF EXISTS` on DROP COLUMN, so
251
+ // emulate it here: probe getTableInfo and bail out if the
252
+ // column is already gone. Postgres + MySQL emit the
253
+ // `IF EXISTS` clause directly in their DDL.
251
254
  if(this.context.isSQLite){
252
- var queryBuilder = new sqliteQuery();
255
+ if (typeof this.context._SQLEngine.getTableInfo === 'function') {
256
+ const cols = await this.context._SQLEngine.getTableInfo(table.tableName);
257
+ const exists = Array.isArray(cols) && cols.some(c => c && (c.name === table.name));
258
+ if (!exists) {
259
+ return;
260
+ }
261
+ }
262
+ var queryBuilder = new sqliteQuery();
253
263
  var query = queryBuilder.dropColumn(table);
254
264
  await this.context._execute(query);
255
265
  }
256
266
 
257
267
  if(this.context.isMySQL){
258
- var queryBuilder = new sqlquery();
268
+ var queryBuilder = new sqlquery();
259
269
  var query = queryBuilder.dropColumn(table);
260
270
  await this.context._execute(query);
261
271
  }
262
272
 
263
273
  if(this.context.isPostgres){
264
- var queryBuilder = new postgresQuery();
274
+ var queryBuilder = new postgresQuery();
265
275
  var query = queryBuilder.dropColumn(table);
266
276
  await this.context._execute(query);
267
277
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "masterrecord",
3
- "version": "1.0.7",
3
+ "version": "1.0.8",
4
4
  "description": "An Object-relational mapping for the Master framework. Master Record connects classes to relational database tables to establish a database with almost zero-configuration ",
5
5
  "type": "module",
6
6
  "main": "./MasterRecord.js",
package/postgresEngine.js CHANGED
@@ -290,6 +290,38 @@ class postgresEngine {
290
290
  }
291
291
  }
292
292
 
293
+ /**
294
+ * Introspection: Get column information for a table.
295
+ *
296
+ * Used by `schema.syncTable()` to diff the existing database schema
297
+ * against the entity definition so migrations can add only the
298
+ * missing columns. Without this method on Postgres, syncTable
299
+ * couldn't detect existing columns and re-ran migrations failed
300
+ * with `column "X" already exists`.
301
+ *
302
+ * Returns rows shaped like the SQLite/MySQL counterparts:
303
+ * { name, dflt_value, is_nullable, data_type }
304
+ */
305
+ async getTableInfo(tableName) {
306
+ try {
307
+ const sql = `
308
+ SELECT
309
+ column_name AS name,
310
+ column_default AS dflt_value,
311
+ is_nullable AS is_nullable,
312
+ data_type AS data_type
313
+ FROM information_schema.columns
314
+ WHERE table_schema = ANY(current_schemas(false))
315
+ AND table_name = $1
316
+ ORDER BY ordinal_position
317
+ `;
318
+ const result = await this._runWithParams(sql, [tableName]);
319
+ return (result && result.rows) ? result.rows : [];
320
+ } catch (_) {
321
+ return [];
322
+ }
323
+ }
324
+
293
325
  /**
294
326
  * Build complete SELECT query with parameters
295
327
  */
@@ -0,0 +1,181 @@
1
+ /**
2
+ * Regression for two related 1.0.8 fixes:
3
+ *
4
+ * 1. postgresEngine was missing getTableInfo() — schema.syncTable() couldn't
5
+ * diff against the existing schema, so re-running migrations failed with
6
+ * `column "X" already exists`.
7
+ *
8
+ * 2. DROP COLUMN DDL was not idempotent — Postgres/MySQL didn't emit
9
+ * `IF EXISTS` and SQLite had no runtime guard, so re-running a
10
+ * drop-column migration after a failed/partial run errored with
11
+ * `column "X" does not exist`.
12
+ */
13
+
14
+ import { test } from 'node:test';
15
+ import assert from 'node:assert/strict';
16
+ import fs from 'node:fs';
17
+ import path from 'node:path';
18
+ import { fileURLToPath } from 'node:url';
19
+
20
+ process.env.master = 'dropcol';
21
+
22
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
23
+ const fixturesDir = path.join(__dirname, 'fixtures', 'drop-col');
24
+ const envDir = path.join(fixturesDir, 'config', 'environments');
25
+ const dbDir = path.join(fixturesDir, 'db');
26
+ const dbFile = path.join(dbDir, 'dropcolctx.sqlite');
27
+
28
+ fs.mkdirSync(envDir, { recursive: true });
29
+ fs.mkdirSync(dbDir, { recursive: true });
30
+ if (fs.existsSync(dbFile)) fs.rmSync(dbFile);
31
+
32
+ fs.writeFileSync(
33
+ path.join(envDir, 'env.dropcol.json'),
34
+ JSON.stringify({
35
+ DropColCtx: {
36
+ type: 'better-sqlite3',
37
+ connection: dbDir + path.sep,
38
+ },
39
+ })
40
+ );
41
+
42
+ const { default: context } = await import('../context.js');
43
+ const { default: schema } = await import('../Migrations/schema.js');
44
+ const { default: PostgresEngine } = await import('../postgresEngine.js');
45
+ const { default: MySQLEngine } = await import('../mySQLEngine.js');
46
+ const { default: SQLiteQuery } = await import('../Migrations/migrationSQLiteQuery.js');
47
+ const { default: MySQLQuery } = await import('../Migrations/migrationMySQLQuery.js');
48
+ const { default: PostgresQuery } = await import('../Migrations/migrationPostgresQuery.js');
49
+
50
+ // ---- DDL string-level checks (no DB connection required) ----
51
+
52
+ test('Postgres dropColumn emits IF EXISTS with quoted identifiers', () => {
53
+ const q = new PostgresQuery();
54
+ const sql = q.dropColumn({ tableName: 'SchedulerLeader', name: 'staleField' });
55
+ assert.match(sql, /ALTER TABLE "SchedulerLeader" DROP COLUMN IF EXISTS "staleField"/);
56
+ });
57
+
58
+ test('MySQL dropColumn emits IF EXISTS with backtick quotes', () => {
59
+ const q = new MySQLQuery();
60
+ const sql = q.dropColumn({ tableName: 'User', name: 'legacyField' });
61
+ assert.match(sql, /ALTER TABLE `User` DROP COLUMN IF EXISTS `legacyField`/);
62
+ });
63
+
64
+ test('SQLite dropColumn quotes identifiers with square brackets', () => {
65
+ const q = new SQLiteQuery();
66
+ const sql = q.dropColumn({ tableName: 'User', name: 'legacyField' });
67
+ assert.match(sql, /ALTER TABLE \[User\] DROP COLUMN \[legacyField\]/);
68
+ // SQLite has no `IF EXISTS` on DROP COLUMN; the guard lives in schema.dropColumn().
69
+ assert.doesNotMatch(sql, /IF EXISTS/);
70
+ });
71
+
72
+ // ---- Postgres getTableInfo presence ----
73
+
74
+ test('Postgres engine exposes getTableInfo()', () => {
75
+ const engine = new PostgresEngine();
76
+ assert.equal(typeof engine.getTableInfo, 'function');
77
+ });
78
+
79
+ test('Postgres getTableInfo returns rows shaped like SQLite/MySQL counterparts', async () => {
80
+ const engine = new PostgresEngine();
81
+ // Stub _runWithParams so we can verify the SQL without a live Postgres.
82
+ let capturedSql;
83
+ let capturedParams;
84
+ engine._runWithParams = async (sql, params) => {
85
+ capturedSql = sql;
86
+ capturedParams = params;
87
+ return {
88
+ rows: [
89
+ { name: 'id', dflt_value: null, is_nullable: 'NO', data_type: 'integer' },
90
+ { name: 'createdAt', dflt_value: null, is_nullable: 'YES', data_type: 'timestamp without time zone' },
91
+ ],
92
+ };
93
+ };
94
+ const rows = await engine.getTableInfo('SchedulerLeader');
95
+ assert.match(capturedSql, /information_schema\.columns/);
96
+ assert.match(capturedSql, /table_name\s*=\s*\$1/);
97
+ assert.deepEqual(capturedParams, ['SchedulerLeader']);
98
+ assert.equal(rows.length, 2);
99
+ assert.equal(rows[0].name, 'id');
100
+ assert.equal(rows[1].name, 'createdAt');
101
+ // Field names mirror SQLite's PRAGMA table_info / MySQL's INFORMATION_SCHEMA query.
102
+ for (const key of ['name', 'dflt_value', 'is_nullable', 'data_type']) {
103
+ assert.ok(key in rows[0], `expected '${key}' in row`);
104
+ }
105
+ });
106
+
107
+ test('Postgres getTableInfo returns [] on error', async () => {
108
+ const engine = new PostgresEngine();
109
+ engine._runWithParams = async () => { throw new Error('boom'); };
110
+ assert.deepEqual(await engine.getTableInfo('Whatever'), []);
111
+ });
112
+
113
+ // ---- SQLite end-to-end: dropColumn twice in a row must not throw ----
114
+
115
+ class Widget {
116
+ id(db) { db.integer().primary().auto(); }
117
+ name(db) { db.string(); }
118
+ legacyField(db) { db.string(); }
119
+ }
120
+
121
+ class DropColCtx extends context {
122
+ constructor() {
123
+ super();
124
+ this.env(envDir);
125
+ this.dbset(Widget);
126
+ }
127
+ }
128
+
129
+ {
130
+ // Seed the schema using raw SQL so we don't depend on the rest of the
131
+ // migration pipeline for setup.
132
+ const ctx = new DropColCtx();
133
+ ctx._SQLEngine.db.exec(`
134
+ CREATE TABLE IF NOT EXISTS Widget (
135
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
136
+ name TEXT,
137
+ legacyField TEXT
138
+ );
139
+ `);
140
+ await ctx.close();
141
+ }
142
+
143
+ test('SQLite schema.dropColumn() is idempotent (re-running does not throw)', async () => {
144
+ const ctx = new DropColCtx();
145
+ const sch = new schema(DropColCtx);
146
+ await sch._ensureReady();
147
+ // schema.dropColumn() gates on `this.fullTable` being truthy as a "did
148
+ // init run" sentinel. Real migrations get a real tableObj here; tests
149
+ // just need a truthy value to pass the gate.
150
+ sch.fullTable = { __name: 'Widget' };
151
+
152
+ // Confirm the column exists initially.
153
+ const before = await ctx._SQLEngine.getTableInfo('Widget');
154
+ assert.ok(before.some(c => c.name === 'legacyField'), 'precondition: legacyField column exists');
155
+
156
+ // First drop: removes the column.
157
+ await sch.dropColumn({ tableName: 'Widget', name: 'legacyField' });
158
+ const afterFirst = await ctx._SQLEngine.getTableInfo('Widget');
159
+ assert.ok(!afterFirst.some(c => c.name === 'legacyField'), 'column was dropped');
160
+
161
+ // Second drop: must be a no-op, not an error. This is the regression
162
+ // that 1.0.8 fixes — without the runtime guard in schema.dropColumn(),
163
+ // SQLite would have thrown "no such column: legacyField".
164
+ await assert.doesNotReject(
165
+ sch.dropColumn({ tableName: 'Widget', name: 'legacyField' }),
166
+ 'second dropColumn must be idempotent'
167
+ );
168
+
169
+ await ctx.close();
170
+ });
171
+
172
+ test('SQLite schema.dropColumn() on a never-existed column is also a no-op', async () => {
173
+ const ctx = new DropColCtx();
174
+ const sch = new schema(DropColCtx);
175
+ await sch._ensureReady();
176
+ sch.fullTable = { __name: 'Widget' };
177
+ await assert.doesNotReject(
178
+ sch.dropColumn({ tableName: 'Widget', name: 'neverExisted' })
179
+ );
180
+ await ctx.close();
181
+ });