masterrecord 1.0.6 → 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.
Files changed (59) hide show
  1. package/.claude/settings.local.json +4 -1
  2. package/Migrations/migrationMySQLQuery.js +8 -1
  3. package/Migrations/migrationPostgresQuery.js +5 -2
  4. package/Migrations/migrationSQLiteQuery.js +6 -5
  5. package/Migrations/schema.js +14 -4
  6. package/QueryLanguage/queryMethods.js +8 -0
  7. package/QueryLanguage/queryScript.js +18 -8
  8. package/SQLLiteEngine.js +17 -7
  9. package/context.js +34 -7
  10. package/mySQLEngine.js +23 -7
  11. package/package.json +1 -1
  12. package/postgresEngine.js +155 -35
  13. package/test/count-no-from-audit.test.js +1 -1
  14. package/test/ctx-dollar-placeholder.test.js +142 -0
  15. package/test/drop-column-idempotent.test.js +181 -0
  16. package/test/postgres-camelcase-quoting.test.js +249 -0
  17. package/test/query-builder-parity.test.js +2 -2
  18. package/test/fixtures/broad-audit/config/environments/env.audit.json +0 -1
  19. package/test/fixtures/broad-audit/db/auditctx.sqlite +0 -0
  20. package/test/fixtures/count-chained-where/config/environments/env.countchained.json +0 -1
  21. package/test/fixtures/count-chained-where/db/countctx.sqlite +0 -0
  22. package/test/fixtures/count-no-from/config/environments/env.countfrom.json +0 -1
  23. package/test/fixtures/count-no-from/db/countfromctx.sqlite +0 -0
  24. package/test/fixtures/edge-cases-audit/config/environments/env.edgeaudit.json +0 -1
  25. package/test/fixtures/edge-cases-audit/db/edgectx.sqlite +0 -0
  26. package/test/fixtures/multi-migration-N4bUYy/app/models/db/migrations/1700000001000_CreateAuthor_migration.js +0 -14
  27. package/test/fixtures/multi-migration-N4bUYy/app/models/db/migrations/1700000002000_CreateBook_migration.js +0 -14
  28. package/test/fixtures/multi-migration-N4bUYy/app/models/db/migrations/1700000003000_CreateReview_migration.js +0 -14
  29. package/test/fixtures/multi-migration-N4bUYy/app/models/db/migrations/multimigctx_contextSnapShot.json +0 -96
  30. package/test/fixtures/multi-migration-N4bUYy/app/models/multimigctx.js +0 -26
  31. package/test/fixtures/multi-migration-N4bUYy/config/environments/env.multimig.json +0 -1
  32. package/test/fixtures/multi-migration-N4bUYy/db/multimigctx.sqlite +0 -0
  33. package/test/fixtures/multi-migration-N4bUYy/package.json +0 -1
  34. package/test/fixtures/multi-migration-Qu42ZE/app/models/db/migrations/1700000001000_CreateAuthor_migration.js +0 -14
  35. package/test/fixtures/multi-migration-Qu42ZE/app/models/db/migrations/1700000002000_CreateBook_migration.js +0 -14
  36. package/test/fixtures/multi-migration-Qu42ZE/app/models/db/migrations/1700000003000_CreateReview_migration.js +0 -14
  37. package/test/fixtures/multi-migration-Qu42ZE/app/models/db/migrations/multimigctx_contextSnapShot.json +0 -96
  38. package/test/fixtures/multi-migration-Qu42ZE/app/models/multimigctx.js +0 -26
  39. package/test/fixtures/multi-migration-Qu42ZE/config/environments/env.multimig.json +0 -1
  40. package/test/fixtures/multi-migration-Qu42ZE/db/multimigctx.sqlite +0 -0
  41. package/test/fixtures/multi-migration-Qu42ZE/package.json +0 -1
  42. package/test/fixtures/multi-migration-xDfXbJ/app/models/db/migrations/1700000001000_CreateAuthor_migration.js +0 -14
  43. package/test/fixtures/multi-migration-xDfXbJ/app/models/db/migrations/1700000002000_CreateBook_migration.js +0 -14
  44. package/test/fixtures/multi-migration-xDfXbJ/app/models/db/migrations/1700000003000_CreateReview_migration.js +0 -14
  45. package/test/fixtures/multi-migration-xDfXbJ/app/models/db/migrations/multimigctx_contextSnapShot.json +0 -104
  46. package/test/fixtures/multi-migration-xDfXbJ/app/models/multimigctx.js +0 -26
  47. package/test/fixtures/multi-migration-xDfXbJ/config/environments/env.multimig.json +0 -1
  48. package/test/fixtures/multi-migration-xDfXbJ/db/multimigctx.sqlite +0 -0
  49. package/test/fixtures/multi-migration-xDfXbJ/package.json +0 -1
  50. package/test/fixtures/new-setter-large-string/config/environments/env.newsetter.json +0 -1
  51. package/test/fixtures/new-setter-large-string/db/newsettercontext.sqlite +0 -0
  52. package/test/fixtures/query-builder-parity/config/environments/env.parity.json +0 -1
  53. package/test/fixtures/query-builder-parity/db/parityctx.sqlite +0 -0
  54. package/test/fixtures/setter-and-update-drop/config/environments/env.setterdrop.json +0 -1
  55. package/test/fixtures/setter-and-update-drop/db/setdropctx.sqlite +0 -0
  56. package/test/fixtures/sqlite-lifecycle/config/environments/env.test.json +0 -1
  57. package/test/fixtures/sqlite-lifecycle/db/lifecyclecontext.sqlite +0 -0
  58. package/test/fixtures/text-types/config/environments/env.texttypes.json +0 -1
  59. package/test/fixtures/text-types/db/textctx.sqlite +0 -0
@@ -1,7 +1,10 @@
1
1
  {
2
2
  "permissions": {
3
3
  "allow": [
4
- "Bash(node --test --test-timeout=20000 test/text-types.test.js)"
4
+ "Bash(node --test --test-timeout=20000 test/text-types.test.js)",
5
+ "Bash(node --check /Users/alexanderrich/Documents/development/opensourceHQ/MasterController/MasterActionFilters.js)",
6
+ "Bash(node --test test/action-filters-mixin.test.js)",
7
+ "Bash(npm test *)"
5
8
  ]
6
9
  }
7
10
  }
@@ -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
  }
@@ -297,6 +297,14 @@ class queryMethods{
297
297
  }
298
298
 
299
299
  __validateAndCollectParameters(str, args, methodName){
300
+ // Normalize `<ident>.$$` (e.g. `ctx.$$`, `this.$$`) to bare `$$` so
301
+ // TypeScript/ESLint-clean lambdas like `(u) => u.id == ctx.$$` work
302
+ // identically to `'u => u.id == $$'`. The lambda is never evaluated
303
+ // at runtime — only stringified — so the property path doesn't matter.
304
+ // Note: `$$$$` in a String.prototype.replace replacement string means
305
+ // a literal `$$` (each `$$` escapes to a single `$`).
306
+ str = str.replace(/[A-Za-z_$][\w$]*\.\$\$/g, '$$$$');
307
+
300
308
  // Count placeholders - support both $$ (standard) and $ (backwards compatibility)
301
309
  // Match $$ first to avoid double-counting, then match remaining single $
302
310
  let placeholderCount = 0;
@@ -202,10 +202,16 @@ class queryScript{
202
202
 
203
203
  // look and grab all fields
204
204
  buildFields(text, desc){
205
- var match = text.match(/^([\w\d$_]+?)\s*=>((?:\{\sreturn\s)?[\s\S]*(?:\})?)/);
205
+ // Accept both `p => body` and `(p) => body` (and `(p, ...) => body`).
206
+ // JS Function.prototype.toString() preserves the parenthesized form
207
+ // for arrow functions, so when users pass a real lambda we receive
208
+ // `(p) => p.name == ...` — the previous regex only matched bare
209
+ // identifiers and silently mis-parsed parens as the entity name,
210
+ // producing SQL like `SELECT (.id, (.name FROM Plugin AS (`.
211
+ var match = text.match(/^\s*(?:\(\s*([\w\d$_]+)[^)]*\)|([\w\d$_]+))\s*=>((?:\{\sreturn\s)?[\s\S]*(?:\})?)/);
206
212
  if(match){
207
- const entity = match[1];
208
- let exprStr = match[2];
213
+ const entity = match[1] || match[2];
214
+ let exprStr = match[3];
209
215
  const fields = [];
210
216
 
211
217
  exprStr.replace(new RegExp(entity + "\\.([\\w_]+)", "g"), function (_, field) {
@@ -465,13 +471,17 @@ class queryScript{
465
471
  }
466
472
 
467
473
  getEntity(str){
468
- // Prefer parsing the lambda parameter (e.g., 'uc' in 'uc => uc.user_id == $$')
469
- const m = str.match(/^\s*([\w\d$_]+?)\s*=>/);
470
- if(m && m[1]){
471
- return m[1];
474
+ // Prefer parsing the lambda parameter. Accept both bare-arg and
475
+ // parenthesized-arg forms — JS `.toString()` preserves parens.
476
+ // uc => uc.user_id == $$
477
+ // (uc) => uc.user_id == $$
478
+ // (uc, idx) => ...
479
+ const m = str.match(/^\s*(?:\(\s*([\w\d$_]+)[^)]*\)|([\w\d$_]+))\s*=>/);
480
+ if(m){
481
+ return m[1] || m[2];
472
482
  }
473
483
  // Fallback to previous behavior: first non-space char
474
- var clean = str.replace(/\s/g, '');
484
+ var clean = str.replace(/\s/g, '');
475
485
  return clean.substring(0, 1);
476
486
  }
477
487
 
package/SQLLiteEngine.js CHANGED
@@ -102,11 +102,11 @@ class SQLLiteEngine {
102
102
  /**
103
103
  * Batch delete multiple entities using WHERE IN
104
104
  */
105
- async bulkDelete(tableName, ids) {
105
+ async bulkDelete(tableName, ids, primaryKey = 'id') {
106
106
  if (!ids || ids.length === 0) return Promise.resolve();
107
107
 
108
108
  const placeholders = ids.map(() => '?').join(', ');
109
- const query = `DELETE FROM [${tableName}] WHERE id IN (${placeholders})`;
109
+ const query = `DELETE FROM [${tableName}] WHERE [${primaryKey}] IN (${placeholders})`;
110
110
  return Promise.resolve(this._runWithParams(query, ids));
111
111
  }
112
112
 
@@ -345,10 +345,15 @@ class SQLLiteEngine {
345
345
  var item = itemEntity[query.parentName][table];
346
346
  const expressions = [];
347
347
  for (let exp in item.expressions) {
348
- var field = tools.capitalizeFirstLetter(item.expressions[exp].field);
349
- if(mainQuery[field]){
350
- if(mainQuery[field].isNavigational){
351
- entity = $that.getEntity(field, query.entityMap);
348
+ // Use the field name verbatim for SQL emission; only
349
+ // use the capitalized form for the navigational
350
+ // relationship lookup (those are PascalCase keys).
351
+ const originalField = item.expressions[exp].field;
352
+ const capitalized = tools.capitalizeFirstLetter(originalField);
353
+ var field = originalField;
354
+ if(mainQuery[capitalized]){
355
+ if(mainQuery[capitalized].isNavigational){
356
+ entity = $that.getEntity(capitalized, query.entityMap);
352
357
  field = item.fields[1];
353
358
  }
354
359
  }
@@ -398,7 +403,12 @@ class SQLLiteEngine {
398
403
  var exprs = item.expressions || [];
399
404
 
400
405
  function exprToSql(expr){
401
- var field = expr.field.toLowerCase();
406
+ // Preserve case for column emission. SQLite identifier matching
407
+ // is case-insensitive so the old `.toLowerCase()` worked in
408
+ // practice, but it would have hidden a bug if SQLite were ever
409
+ // configured with strict case-sensitive identifiers, and it
410
+ // produced inconsistent SQL output across engines.
411
+ var field = expr.field;
402
412
  var ent = entityAlias;
403
413
  if(mainQuery[field]){
404
414
  if(mainQuery[field].isNavigational){
package/context.js CHANGED
@@ -240,6 +240,29 @@ class context {
240
240
  this._queryCache = context._sharedQueryCache;
241
241
  }
242
242
 
243
+ /**
244
+ * Parameter placeholder accessor for TypeScript / ESLint-clean queries.
245
+ *
246
+ * Bare `$$` in a lambda body is a free identifier that fails static
247
+ * analysis. Accessing `ctx.$$` (or `this.$$` from inside a context method)
248
+ * is a valid property reference, so editors and type checkers won't flag it.
249
+ *
250
+ * The getter just returns the string `'$$'`. The lambda is never evaluated
251
+ * at runtime — `.where()` / `.orderBy()` / `.and()` stringify it and treat
252
+ * any `<ident>.$$` token (or bare `$$`) as a parameter placeholder.
253
+ *
254
+ * @example
255
+ * // Bare $$ — works, but ESLint/TS flag it
256
+ * await ctx.User.where('u => u.id == $$', 42).single();
257
+ *
258
+ * @example
259
+ * // ctx.$$ — same behavior, ESLint/TS-clean
260
+ * await ctx.User.where(u => u.id == ctx.$$, 42).single();
261
+ */
262
+ get $$() {
263
+ return '$$';
264
+ }
265
+
243
266
  /**
244
267
  * Ensure the database engine is initialized and ready for queries.
245
268
  *
@@ -1792,24 +1815,28 @@ class context {
1792
1815
  const deleteObject = new deleteManager(this._SQLEngine, this.__entities);
1793
1816
  await deleteObject.init(entities[0]);
1794
1817
  } else {
1795
- // Batch delete - group by table for efficiency
1796
- const deletesByTable = new Map(); // Use Map instead of object for better performance
1818
+ // Batch delete - group by (table, primaryKey) for efficiency. The
1819
+ // primary-key column is part of the grouping key so a context with
1820
+ // entities that have different PK column names still produces one
1821
+ // bulkDelete call per (table, PK) pair.
1822
+ const deletesByTable = new Map(); // Map<`${table}::${pk}`, { tableName, primaryKey, ids: [] }>
1797
1823
 
1798
1824
  for (const entity of entities) {
1799
1825
  const tableName = entity.__entity.__name;
1800
1826
  const primaryKey = tools.getPrimaryKeyObject(entity.__entity);
1801
1827
  const id = entity[primaryKey];
1828
+ const groupKey = `${tableName}::${primaryKey}`;
1802
1829
 
1803
- if (!deletesByTable.has(tableName)) {
1804
- deletesByTable.set(tableName, []);
1830
+ if (!deletesByTable.has(groupKey)) {
1831
+ deletesByTable.set(groupKey, { tableName, primaryKey, ids: [] });
1805
1832
  }
1806
- deletesByTable.get(tableName).push(id);
1833
+ deletesByTable.get(groupKey).ids.push(id);
1807
1834
  }
1808
1835
 
1809
1836
  try {
1810
1837
  // Performance: Use for...of with Map entries
1811
- for (const [tableName, ids] of deletesByTable.entries()) {
1812
- await this._SQLEngine.bulkDelete(tableName, ids);
1838
+ for (const { tableName, primaryKey, ids } of deletesByTable.values()) {
1839
+ await this._SQLEngine.bulkDelete(tableName, ids, primaryKey);
1813
1840
  }
1814
1841
  } catch (error) {
1815
1842
  console.error('[Context] Bulk delete failed, falling back to individual deletes:', error.message);
package/mySQLEngine.js CHANGED
@@ -117,13 +117,18 @@ class MySQLEngine {
117
117
  }
118
118
 
119
119
  /**
120
- * Batch delete using WHERE IN
120
+ * Batch delete using WHERE IN.
121
+ * @param {string} tableName
122
+ * @param {Array} ids
123
+ * @param {string} [primaryKey='id'] - Primary-key column name. Defaults to
124
+ * 'id' for back-compat, but callers should pass the entity's actual PK
125
+ * to support custom primary-key names.
121
126
  */
122
- async bulkDelete(tableName, ids) {
127
+ async bulkDelete(tableName, ids, primaryKey = 'id') {
123
128
  if (!ids || ids.length === 0) return;
124
129
 
125
130
  const placeholders = ids.map(() => '?').join(', ');
126
- const query = `DELETE FROM \`${tableName}\` WHERE id IN (${placeholders})`;
131
+ const query = `DELETE FROM \`${tableName}\` WHERE \`${primaryKey}\` IN (${placeholders})`;
127
132
  return await this._runWithParams(query, ids);
128
133
  }
129
134
 
@@ -347,9 +352,17 @@ class MySQLEngine {
347
352
  const item = itemEntity[query.parentName][table];
348
353
  const expressions = [];
349
354
  for (const exp in item.expressions) {
350
- let field = tools.capitalizeFirstLetter(item.expressions[exp].field);
351
- if (mainQuery[field] && mainQuery[field].isNavigational) {
352
- entity = $that.getEntity(field, query.entityMap);
355
+ // Use the field name verbatim for SQL emission. With
356
+ // backtick quoting, MySQL on case-sensitive filesystems
357
+ // (Linux defaults) wouldn't match a column named `stage`
358
+ // if we emit `\`Stage\``. Only use the capitalized form
359
+ // for the navigational-relationship lookup since those
360
+ // are stored as PascalCase keys on the entity.
361
+ const originalField = item.expressions[exp].field;
362
+ const capitalized = tools.capitalizeFirstLetter(originalField);
363
+ let field = originalField;
364
+ if (mainQuery[capitalized] && mainQuery[capitalized].isNavigational) {
365
+ entity = $that.getEntity(capitalized, query.entityMap);
353
366
  field = item.fields[1];
354
367
  }
355
368
 
@@ -464,7 +477,10 @@ class MySQLEngine {
464
477
  const exprs = item.expressions || [];
465
478
 
466
479
  function exprToSql(expr) {
467
- let field = expr.field.toLowerCase();
480
+ // Preserve case for column-name emission — `.toLowerCase()` used
481
+ // to turn `updatedAt` into `updatedat`, which doesn't match a
482
+ // case-sensitive backtick-quoted column on Linux MySQL.
483
+ let field = expr.field;
468
484
  let ent = entityAlias;
469
485
  if (mainQuery[field]) {
470
486
  if (mainQuery[field].isNavigational) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "masterrecord",
3
- "version": "1.0.006",
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",