masterrecord 1.3.2 → 1.5.5

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.
@@ -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
 
@@ -4,6 +4,23 @@ import entityTrackerModel from '../Entity/entityTrackerModel.js';
4
4
  import tools from '../Tools.js';
5
5
  import queryScript from './queryScript.js';
6
6
 
7
+ // Security: `.take()`/`.skip()` values are interpolated directly into
8
+ // LIMIT/OFFSET (these clauses cannot be parameterized on SQLite/MySQL/Postgres).
9
+ // Pagination values are the single most common place an application forwards
10
+ // raw user input (e.g. `?page=`, `?limit=`), so a non-numeric value here is a
11
+ // direct SQL-injection vector. Coerce to a safe, non-negative integer and throw
12
+ // loudly on anything else rather than letting it reach the SQL string.
13
+ function validateRowCount(value, method){
14
+ if(value === null || value === undefined){
15
+ return 0; // treated as "not set"
16
+ }
17
+ const n = typeof value === 'number' ? value : Number(value);
18
+ if(!Number.isInteger(n) || n < 0 || !Number.isSafeInteger(n)){
19
+ throw new Error(`.${method}() requires a non-negative integer, received: ${JSON.stringify(value)}`);
20
+ }
21
+ return n;
22
+ }
23
+
7
24
  class queryMethods{
8
25
 
9
26
  constructor(entity, context) {
@@ -198,12 +215,12 @@ class queryMethods{
198
215
  }
199
216
 
200
217
  take(number){
201
- this.__queryObject.script.take = number;
218
+ this.__queryObject.script.take = validateRowCount(number, 'take');
202
219
  return this;
203
220
  }
204
221
 
205
222
  skip(number){
206
- this.__queryObject.script.skip = number;
223
+ this.__queryObject.script.skip = validateRowCount(number, 'skip');
207
224
  return this;
208
225
  }
209
226
 
@@ -522,7 +539,13 @@ class queryMethods{
522
539
  throw new Error('No database type configured. Ensure context.env() or context.useMySql()/useSqlite() has been called and awaited.');
523
540
  }
524
541
 
525
- // Store in cache
542
+ // Store in cache — but never cache a "not found" (null) result. A
543
+ // negative result is poisoned the instant any concurrent writer inserts
544
+ // the matching row: a reader that filled the cache with the pre-commit
545
+ // empty would keep serving it (the writer's invalidateTable ran before
546
+ // this set, or on a different context instance's cache entirely). This
547
+ // is the "claimed idempotency key reads back empty" bug — re-run the
548
+ // cheap lookup against the database instead of trusting a cached miss.
526
549
  if (this.__useCache && result) {
527
550
  this.__context._queryCache.set(cacheKey, result, tableName);
528
551
  }
@@ -534,9 +557,6 @@ class queryMethods{
534
557
  async toList(){
535
558
  if(this.__queryObject.script.entityMap.length === 0){
536
559
  this.__queryObject.skipClause( this.__entity.__name);
537
- if(!this.__queryObject.script.take || this.__queryObject.script.take === 0){
538
- this.__queryObject.script.take = 1000;
539
- }
540
560
  }
541
561
 
542
562
  // Generate cache key
@@ -575,8 +595,14 @@ class queryMethods{
575
595
  throw new Error('No database type configured. Ensure context.env() or context.useMySql()/useSqlite() has been called and awaited.');
576
596
  }
577
597
 
578
- // Store in cache
579
- if (this.__useCache && result) {
598
+ // Store in cache — but NOT an empty result set. An empty array is
599
+ // truthy, so the old `&& result` guard cached `[]`, which is negative
600
+ // caching: the moment a concurrent writer inserts a matching row the
601
+ // cached `[]` is stale, yet a reader that filled it just before the
602
+ // writer's commit (or on a different context instance, whose cache the
603
+ // writer's invalidateTable never touches) keeps serving empty. Skipping
604
+ // empty sets means a "no rows yet" lookup always re-checks the database.
605
+ if (this.__useCache && result && result.length > 0) {
580
606
  this.__context._queryCache.set(cacheKey, result, tableName);
581
607
  }
582
608
 
package/SQLLiteEngine.js CHANGED
@@ -136,8 +136,12 @@ class SQLLiteEngine {
136
136
  }
137
137
  return Promise.resolve(null);
138
138
  } catch (err) {
139
- console.error(err);
140
- return Promise.resolve(null);
139
+ // Loud failure: never swallow a query error into a silent null.
140
+ // A missing table (the classic "SQLite dev worked, MySQL broke"
141
+ // drift) becomes a clear, actionable error naming the table.
142
+ const missing = tools.missingTableError(err);
143
+ if (missing) { throw missing; }
144
+ throw err;
141
145
  }
142
146
  }
143
147
 
@@ -209,8 +213,12 @@ class SQLLiteEngine {
209
213
  }
210
214
  return Promise.resolve(null);
211
215
  } catch (err) {
212
- console.error(err);
213
- return Promise.resolve(null);
216
+ // Loud failure: never swallow a query error into a silent null.
217
+ // A missing table (the classic "SQLite dev worked, MySQL broke"
218
+ // drift) becomes a clear, actionable error naming the table.
219
+ const missing = tools.missingTableError(err);
220
+ if (missing) { throw missing; }
221
+ throw err;
214
222
  }
215
223
  }
216
224
 
@@ -236,8 +244,12 @@ class SQLLiteEngine {
236
244
  }
237
245
  return Promise.resolve(null);
238
246
  } catch (err) {
239
- console.error(err);
240
- return Promise.resolve(null);
247
+ // Loud failure: never swallow a query error into a silent null.
248
+ // A missing table (the classic "SQLite dev worked, MySQL broke"
249
+ // drift) becomes a clear, actionable error naming the table.
250
+ const missing = tools.missingTableError(err);
251
+ if (missing) { throw missing; }
252
+ throw err;
241
253
  }
242
254
  }
243
255
 
@@ -365,7 +377,10 @@ class SQLLiteEngine {
365
377
 
366
378
  buildTake(query){
367
379
  if(query.take){
368
- return `LIMIT ${query.take}`
380
+ // Defense-in-depth: coerce to an integer at the SQL boundary. The
381
+ // `.take()` setter already validates, but LIMIT cannot be
382
+ // parameterized, so we never interpolate anything but a number.
383
+ return `LIMIT ${this._safeRowCount(query.take, 'take')}`
369
384
  }
370
385
  else{
371
386
  return "";
@@ -374,13 +389,30 @@ class SQLLiteEngine {
374
389
 
375
390
  buildSkip(query){
376
391
  if(query.skip){
377
- return `OFFSET ${query.skip}`
392
+ // SQLite requires a LIMIT before OFFSET. When the caller paginated
393
+ // with .skip() but no .take(), emit `LIMIT -1` (SQLite's documented
394
+ // "no upper bound") so the OFFSET is valid SQL instead of a syntax
395
+ // error. Now that .toList() no longer injects a default LIMIT 1000,
396
+ // this is the path a bare .skip() takes.
397
+ const skip = this._safeRowCount(query.skip, 'skip');
398
+ return query.take ? `OFFSET ${skip}` : `LIMIT -1 OFFSET ${skip}`;
378
399
  }
379
400
  else{
380
401
  return "";
381
402
  }
382
403
  }
383
404
 
405
+ // Coerce a LIMIT/OFFSET value to a non-negative integer or throw. OFFSET
406
+ // and LIMIT are not parameterizable, so this is the last line of defense
407
+ // against a non-numeric (injection) value reaching the SQL string.
408
+ _safeRowCount(value, label){
409
+ const n = typeof value === 'number' ? value : Number(value);
410
+ if(!Number.isInteger(n) || n < 0 || !Number.isSafeInteger(n)){
411
+ throw new Error(`Invalid ${label} value for LIMIT/OFFSET: ${JSON.stringify(value)} (expected a non-negative integer)`);
412
+ }
413
+ return n;
414
+ }
415
+
384
416
  buildAnd(query, mainQuery){
385
417
  // loop through the AND
386
418
  // loop update ther where .expr
@@ -418,14 +450,16 @@ class SQLLiteEngine {
418
450
  }
419
451
  }
420
452
  if(item.expressions[exp].arg === "null"){
453
+ tools.assertSafeOperator(item.expressions[exp].func);
421
454
  expressions.push(`${entity}.${field} ${item.expressions[exp].func} ${item.expressions[exp].arg}`);
422
455
  }else{
423
456
  // Check if arg is a parameterized placeholder
424
457
  const isPlaceholder = (item.expressions[exp].arg === '?' || /^\$\d+$/.test(item.expressions[exp].arg));
458
+ tools.assertSafeOperator(item.expressions[exp].func);
425
459
  if(isPlaceholder){
426
460
  expressions.push(`${entity}.${field} ${item.expressions[exp].func} ${item.expressions[exp].arg}`);
427
461
  }else{
428
- expressions.push(`${entity}.${field} ${item.expressions[exp].func} '${item.expressions[exp].arg}'`);
462
+ expressions.push(`${entity}.${field} ${item.expressions[exp].func} '${tools.escapeSqlLiteral(item.expressions[exp].arg)}'`);
429
463
  }
430
464
  }
431
465
  }
@@ -485,18 +519,22 @@ class SQLLiteEngine {
485
519
  if(arg === "null"){
486
520
  if(func === "=") func = "is";
487
521
  if(func === "!=") func = "is not";
522
+ tools.assertSafeOperator(func);
488
523
  return `${ent}.${field} ${func} ${arg}`;
489
524
  }
490
525
  if(func === "IN"){
491
526
  return `${ent}.${field} ${func} ${arg}`;
492
527
  }
528
+ tools.assertSafeOperator(func);
493
529
  // Check if arg is a parameterized placeholder (? for MySQL/SQLite, $1/$2/etc for Postgres)
494
530
  const isPlaceholder = (arg === '?' || /^\$\d+$/.test(arg));
495
531
  if(isPlaceholder){
496
532
  // Don't quote placeholders - they must remain as bare ? or $1
497
533
  return `${ent}.${field} ${func} ${arg}`;
498
534
  }
499
- return `${ent}.${field} ${func} '${arg}'`;
535
+ // Literal (inline lambda constant). Escape the single quote so a
536
+ // value containing `'` can't break out of the string literal.
537
+ return `${ent}.${field} ${func} '${tools.escapeSqlLiteral(arg)}'`;
500
538
  }
501
539
 
502
540
  const pieces = [];
@@ -733,6 +771,30 @@ class SQLLiteEngine {
733
771
  );
734
772
  }
735
773
 
774
+ // True while a transaction is open. Used by saveChanges' batch fallbacks
775
+ // to decide whether to protect a bulk attempt with a SAVEPOINT.
776
+ inTransaction(){
777
+ return !!(this.db && this.db.inTransaction);
778
+ }
779
+
780
+ // Nested-rollback primitives so a failed bulk write can be undone without
781
+ // aborting the whole enclosing transaction. `name` is an internally
782
+ // generated identifier (`mr_sp_<n>`), never user input.
783
+ async savepoint(name){
784
+ return Promise.resolve(this.db.prepare(`SAVEPOINT ${name}`).run());
785
+ }
786
+
787
+ async releaseSavepoint(name){
788
+ return Promise.resolve(this.db.prepare(`RELEASE SAVEPOINT ${name}`).run());
789
+ }
790
+
791
+ async rollbackToSavepoint(name){
792
+ // ROLLBACK TO leaves the savepoint defined; RELEASE removes it so the
793
+ // savepoint stack doesn't grow across repeated fallbacks.
794
+ this.db.prepare(`ROLLBACK TO SAVEPOINT ${name}`).run();
795
+ return Promise.resolve(this.db.prepare(`RELEASE SAVEPOINT ${name}`).run());
796
+ }
797
+
736
798
  _buildSQLEqualTo(model){
737
799
  const $that = this;
738
800
  let argument = null;