masterrecord 1.3.3 → 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.
- package/Entity/entityTrackerModel.js +202 -149
- package/Migrations/cli.js +152 -36
- package/Migrations/migrationMySQLQuery.js +21 -13
- package/Migrations/migrationPostgresQuery.js +21 -12
- package/Migrations/migrationSQLiteQuery.js +5 -1
- package/Migrations/migrationTemplate.js +11 -0
- package/Migrations/migrations.js +16 -0
- package/Migrations/schema.js +108 -28
- package/QueryLanguage/queryMethods.js +34 -5
- package/SQLLiteEngine.js +67 -10
- package/Tools.js +76 -0
- package/context.js +345 -63
- package/mySQLEngine.js +0 -0
- package/package.json +11 -14
- package/postgresEngine.js +97 -10
- package/readme.md +61 -11
- package/CHANGES.md +0 -421
- package/docs/ACTIVE_RECORD_PATTERN.md +0 -477
- package/docs/DETACHED_ENTITIES_GUIDE.md +0 -445
- package/docs/FULL_TEXT_SEARCH.md +0 -219
- package/docs/INCLUDES_CLARIFICATION.md +0 -202
- package/docs/METHODS_REFERENCE.md +0 -199
- package/docs/MIGRATIONS_GUIDE.md +0 -508
- package/docs/POSTGRESQL_SETUP.md +0 -441
- package/docs/QUERY_CACHING_GUIDE.md +0 -446
- package/docs/TROUBLESHOOTING.md +0 -348
- package/docs/belongsTo-relationships.md +0 -222
|
@@ -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
|
-
|
|
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
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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(
|
|
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(
|
|
153
|
+
if(col.nullable === false){
|
|
145
154
|
statements.push(`ALTER TABLE "${tableName}" ALTER COLUMN "${colName}" SET NOT NULL`);
|
|
146
|
-
} else if(
|
|
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(
|
|
152
|
-
let def =
|
|
153
|
-
if(
|
|
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(
|
|
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
|
-
|
|
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; }
|
package/Migrations/migrations.js
CHANGED
|
@@ -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;
|
package/Migrations/schema.js
CHANGED
|
@@ -295,18 +295,21 @@ class schema{
|
|
|
295
295
|
}
|
|
296
296
|
if(table){
|
|
297
297
|
if(this.fullTable){
|
|
298
|
-
// SQLite
|
|
299
|
-
//
|
|
300
|
-
//
|
|
301
|
-
//
|
|
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
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
//
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
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
|
}
|
|
@@ -572,8 +595,14 @@ class queryMethods{
|
|
|
572
595
|
throw new Error('No database type configured. Ensure context.env() or context.useMySql()/useSqlite() has been called and awaited.');
|
|
573
596
|
}
|
|
574
597
|
|
|
575
|
-
// Store in cache
|
|
576
|
-
|
|
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) {
|
|
577
606
|
this.__context._queryCache.set(cacheKey, result, tableName);
|
|
578
607
|
}
|
|
579
608
|
|
package/SQLLiteEngine.js
CHANGED
|
@@ -136,8 +136,12 @@ class SQLLiteEngine {
|
|
|
136
136
|
}
|
|
137
137
|
return Promise.resolve(null);
|
|
138
138
|
} catch (err) {
|
|
139
|
-
|
|
140
|
-
|
|
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
|
-
|
|
213
|
-
|
|
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
|
-
|
|
240
|
-
|
|
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
|
-
|
|
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 "";
|
|
@@ -379,13 +394,25 @@ class SQLLiteEngine {
|
|
|
379
394
|
// "no upper bound") so the OFFSET is valid SQL instead of a syntax
|
|
380
395
|
// error. Now that .toList() no longer injects a default LIMIT 1000,
|
|
381
396
|
// this is the path a bare .skip() takes.
|
|
382
|
-
|
|
397
|
+
const skip = this._safeRowCount(query.skip, 'skip');
|
|
398
|
+
return query.take ? `OFFSET ${skip}` : `LIMIT -1 OFFSET ${skip}`;
|
|
383
399
|
}
|
|
384
400
|
else{
|
|
385
401
|
return "";
|
|
386
402
|
}
|
|
387
403
|
}
|
|
388
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
|
+
|
|
389
416
|
buildAnd(query, mainQuery){
|
|
390
417
|
// loop through the AND
|
|
391
418
|
// loop update ther where .expr
|
|
@@ -423,14 +450,16 @@ class SQLLiteEngine {
|
|
|
423
450
|
}
|
|
424
451
|
}
|
|
425
452
|
if(item.expressions[exp].arg === "null"){
|
|
453
|
+
tools.assertSafeOperator(item.expressions[exp].func);
|
|
426
454
|
expressions.push(`${entity}.${field} ${item.expressions[exp].func} ${item.expressions[exp].arg}`);
|
|
427
455
|
}else{
|
|
428
456
|
// Check if arg is a parameterized placeholder
|
|
429
457
|
const isPlaceholder = (item.expressions[exp].arg === '?' || /^\$\d+$/.test(item.expressions[exp].arg));
|
|
458
|
+
tools.assertSafeOperator(item.expressions[exp].func);
|
|
430
459
|
if(isPlaceholder){
|
|
431
460
|
expressions.push(`${entity}.${field} ${item.expressions[exp].func} ${item.expressions[exp].arg}`);
|
|
432
461
|
}else{
|
|
433
|
-
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)}'`);
|
|
434
463
|
}
|
|
435
464
|
}
|
|
436
465
|
}
|
|
@@ -490,18 +519,22 @@ class SQLLiteEngine {
|
|
|
490
519
|
if(arg === "null"){
|
|
491
520
|
if(func === "=") func = "is";
|
|
492
521
|
if(func === "!=") func = "is not";
|
|
522
|
+
tools.assertSafeOperator(func);
|
|
493
523
|
return `${ent}.${field} ${func} ${arg}`;
|
|
494
524
|
}
|
|
495
525
|
if(func === "IN"){
|
|
496
526
|
return `${ent}.${field} ${func} ${arg}`;
|
|
497
527
|
}
|
|
528
|
+
tools.assertSafeOperator(func);
|
|
498
529
|
// Check if arg is a parameterized placeholder (? for MySQL/SQLite, $1/$2/etc for Postgres)
|
|
499
530
|
const isPlaceholder = (arg === '?' || /^\$\d+$/.test(arg));
|
|
500
531
|
if(isPlaceholder){
|
|
501
532
|
// Don't quote placeholders - they must remain as bare ? or $1
|
|
502
533
|
return `${ent}.${field} ${func} ${arg}`;
|
|
503
534
|
}
|
|
504
|
-
|
|
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)}'`;
|
|
505
538
|
}
|
|
506
539
|
|
|
507
540
|
const pieces = [];
|
|
@@ -738,6 +771,30 @@ class SQLLiteEngine {
|
|
|
738
771
|
);
|
|
739
772
|
}
|
|
740
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
|
+
|
|
741
798
|
_buildSQLEqualTo(model){
|
|
742
799
|
const $that = this;
|
|
743
800
|
let argument = null;
|