masterrecord 1.3.0 → 1.3.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/CHANGES.md +38 -0
- package/Migrations/cli.js +25 -10
- package/Migrations/migrations.js +8 -3
- package/Migrations/pathUtils.js +19 -1
- package/docs/TROUBLESHOOTING.md +25 -0
- package/mySQLEngine.js +0 -0
- package/package.json +2 -2
- package/postgresEngine.js +39 -26
package/CHANGES.md
CHANGED
|
@@ -1,5 +1,43 @@
|
|
|
1
1
|
# MasterRecord Changelog
|
|
2
2
|
|
|
3
|
+
## v1.3.1 — portable snapshots + heterogeneous batch inserts
|
|
4
|
+
|
|
5
|
+
**Fixed — Windows-generated migration snapshots broke Linux deploys (critical).**
|
|
6
|
+
`createSnapShot` stored `contextLocation` straight from `path.relative()`, which
|
|
7
|
+
emits backslashes on Windows. On Linux a backslash is a literal filename
|
|
8
|
+
character, so the CLI's `path.resolve()` built a bogus specifier and the ESM
|
|
9
|
+
import of the context died with `ERR_INVALID_MODULE_SPECIFIER` **before any
|
|
10
|
+
migration ran** — a backend container crash-looped at boot even with a fully
|
|
11
|
+
up-to-date database. Fix on both ends: `Migrations/pathUtils.js` gains
|
|
12
|
+
`toPosixPath()` (every `\` → `/`; forward slashes are valid on all platforms
|
|
13
|
+
Node supports, so Windows behavior is unchanged); the snapshot **writer**
|
|
14
|
+
normalizes `contextLocation` before serializing, and every CLI **read** site
|
|
15
|
+
normalizes on load — so already-committed backslash snapshots in user repos
|
|
16
|
+
work without regeneration.
|
|
17
|
+
|
|
18
|
+
**Fixed — `bulkInsert` built one INSERT from heterogeneous rows (MySQL +
|
|
19
|
+
Postgres).** The multi-row INSERT took its column list from the FIRST entity
|
|
20
|
+
but appended EACH entity's own placeholder group. Batched rows with different
|
|
21
|
+
populated field sets (the builder skips unset optional columns and auto-PKs)
|
|
22
|
+
produced a malformed statement — MySQL `ER_WRONG_VALUE_COUNT_ON_ROW` — and the
|
|
23
|
+
context silently fell back to slow per-row inserts on every such batch; worse,
|
|
24
|
+
rows whose column COUNT matched while the column SET differed would have landed
|
|
25
|
+
values in the wrong columns. Now rows are sub-grouped by identical column
|
|
26
|
+
signature and ONE multi-value INSERT is emitted per signature (no NULL-padding
|
|
27
|
+
to a column union — an omitted column keeps its DB-level `DEFAULT`, pinned by a
|
|
28
|
+
new integration test). Postgres `$n` placeholders renumber per statement, and
|
|
29
|
+
results map back to entities in their **original input order** — the contract
|
|
30
|
+
`context._processBatchInserts` relies on, which also fixes a latent id
|
|
31
|
+
misalignment when one batch spanned multiple tables. SQLite is unaffected (it
|
|
32
|
+
loops single inserts in a transaction).
|
|
33
|
+
|
|
34
|
+
**Tests.** Cross-engine integration tests now quote table identifiers per
|
|
35
|
+
engine (`user` is reserved in Postgres, and unquoted DDL case-folds to a
|
|
36
|
+
different relation than the engine's quoted writes), and every test body runs
|
|
37
|
+
in `try/finally` so `ctx.close()` always releases the pool — a failing test can
|
|
38
|
+
no longer hang the `node --test` runner. New `[engine] heterogeneous batch
|
|
39
|
+
stays on the bulk path` test pins the bulkInsert fix on both live engines.
|
|
40
|
+
|
|
3
41
|
## v1.3.0 — full builder type set + inline `env()` config
|
|
4
42
|
|
|
5
43
|
**Added — builder convenience type methods.** Every column type the engines'
|
package/Migrations/cli.js
CHANGED
|
@@ -9,7 +9,7 @@ import fs from 'node:fs';
|
|
|
9
9
|
import path from 'node:path';
|
|
10
10
|
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
11
11
|
import { globSync } from 'glob';
|
|
12
|
-
import { resolveMigrationsDirectory } from './pathUtils.js';
|
|
12
|
+
import { resolveMigrationsDirectory, toPosixPath } from './pathUtils.js';
|
|
13
13
|
import Migration from './migrations.js';
|
|
14
14
|
|
|
15
15
|
const __filename = fileURLToPath(import.meta.url);
|
|
@@ -29,6 +29,21 @@ async function __loadUserModule(filePath) {
|
|
|
29
29
|
|
|
30
30
|
const pkg = JSON.parse(fs.readFileSync(path.join(__dirname, '..', 'package.json'), 'utf8'));
|
|
31
31
|
|
|
32
|
+
// Snapshots written on Windows before 1.3.1 can contain backslash-relative
|
|
33
|
+
// paths (e.g. "..\\..\\userContext.js"). On POSIX a backslash is a literal
|
|
34
|
+
// filename character, so path.resolve() builds a bogus specifier and the
|
|
35
|
+
// dynamic import of the context dies with ERR_INVALID_MODULE_SPECIFIER
|
|
36
|
+
// before any migration runs. Normalize every path-bearing field on load so
|
|
37
|
+
// already-committed snapshots keep working without regeneration.
|
|
38
|
+
function __normalizeSnapshotPaths(snapshot){
|
|
39
|
+
if (snapshot && typeof snapshot === 'object') {
|
|
40
|
+
for (const key of ['contextLocation', 'migrationFolder', 'snapShotLocation']) {
|
|
41
|
+
if (typeof snapshot[key] === 'string') snapshot[key] = toPosixPath(snapshot[key]);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
return snapshot;
|
|
45
|
+
}
|
|
46
|
+
|
|
32
47
|
// Extract numeric timestamp from migration filename (e.g., 1737999999999_name_migration.js)
|
|
33
48
|
function __getMigrationTimestamp(file){
|
|
34
49
|
try{
|
|
@@ -189,7 +204,7 @@ program.option('-V', 'output the version');
|
|
|
189
204
|
}
|
|
190
205
|
let contextSnapshot;
|
|
191
206
|
try{
|
|
192
|
-
contextSnapshot = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
207
|
+
contextSnapshot = __normalizeSnapshotPaths(JSON.parse(fs.readFileSync(file, 'utf8')));
|
|
193
208
|
}catch(_){
|
|
194
209
|
console.log(`Error - Cannot read context snapshot at '${file}'.`);
|
|
195
210
|
return;
|
|
@@ -295,7 +310,7 @@ program.option('-V', 'output the version');
|
|
|
295
310
|
}
|
|
296
311
|
let contextSnapshot = null;
|
|
297
312
|
try{
|
|
298
|
-
contextSnapshot = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
313
|
+
contextSnapshot = __normalizeSnapshotPaths(JSON.parse(fs.readFileSync(file, 'utf8')));
|
|
299
314
|
}catch(_){
|
|
300
315
|
console.log(`Error - Cannot read context snapshot at '${file}'.`);
|
|
301
316
|
return;
|
|
@@ -402,7 +417,7 @@ program.option('-V', 'output the version');
|
|
|
402
417
|
|
|
403
418
|
let contextSnapshot;
|
|
404
419
|
try{
|
|
405
|
-
contextSnapshot = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
420
|
+
contextSnapshot = __normalizeSnapshotPaths(JSON.parse(fs.readFileSync(file, 'utf8')));
|
|
406
421
|
}catch(err){
|
|
407
422
|
console.error(`\n❌ Error - Cannot load context snapshot`);
|
|
408
423
|
console.error(`\nFile: ${file}`);
|
|
@@ -619,7 +634,7 @@ program.option('-V', 'output the version');
|
|
|
619
634
|
}
|
|
620
635
|
let contextSnapshot;
|
|
621
636
|
try{
|
|
622
|
-
contextSnapshot = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
637
|
+
contextSnapshot = __normalizeSnapshotPaths(JSON.parse(fs.readFileSync(file, 'utf8')));
|
|
623
638
|
}catch(_){
|
|
624
639
|
console.log(`Error - Cannot read context snapshot at '${file}'.`);
|
|
625
640
|
return;
|
|
@@ -744,7 +759,7 @@ program.option('-V', 'output the version');
|
|
|
744
759
|
}
|
|
745
760
|
let contextSnapshot;
|
|
746
761
|
try{
|
|
747
|
-
contextSnapshot = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
762
|
+
contextSnapshot = __normalizeSnapshotPaths(JSON.parse(fs.readFileSync(file, 'utf8')));
|
|
748
763
|
}catch(_){
|
|
749
764
|
console.log(`Error - Cannot read context snapshot at '${file}'.`);
|
|
750
765
|
return;
|
|
@@ -835,7 +850,7 @@ program.option('-V', 'output the version');
|
|
|
835
850
|
}
|
|
836
851
|
let contextSnapshot;
|
|
837
852
|
try{
|
|
838
|
-
contextSnapshot = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
853
|
+
contextSnapshot = __normalizeSnapshotPaths(JSON.parse(fs.readFileSync(file, 'utf8')));
|
|
839
854
|
}catch(_){
|
|
840
855
|
console.log(`Error - Cannot read context snapshot at '${file}'.`);
|
|
841
856
|
return;
|
|
@@ -885,7 +900,7 @@ program.option('-V', 'output the version');
|
|
|
885
900
|
|
|
886
901
|
let contextSnapshot;
|
|
887
902
|
try{
|
|
888
|
-
contextSnapshot = JSON.parse(fs.readFileSync(snapshotFile, 'utf8'));
|
|
903
|
+
contextSnapshot = __normalizeSnapshotPaths(JSON.parse(fs.readFileSync(snapshotFile, 'utf8')));
|
|
889
904
|
}catch(_){
|
|
890
905
|
console.log(`Error - Cannot read context snapshot at '${snapshotFile}'.`);
|
|
891
906
|
return;
|
|
@@ -1000,7 +1015,7 @@ program.option('-V', 'output the version');
|
|
|
1000
1015
|
try{
|
|
1001
1016
|
const snapFile = path.resolve(executedLocation, snapRel);
|
|
1002
1017
|
let cs;
|
|
1003
|
-
try{ cs = JSON.parse(fs.readFileSync(snapFile, 'utf8')); }catch(_){ continue; }
|
|
1018
|
+
try{ cs = __normalizeSnapshotPaths(JSON.parse(fs.readFileSync(snapFile, 'utf8'))); }catch(_){ continue; }
|
|
1004
1019
|
const snapDir = path.dirname(snapFile);
|
|
1005
1020
|
const contextAbs = path.resolve(snapDir, cs.contextLocation || '');
|
|
1006
1021
|
const migBase = path.resolve(snapDir, cs.migrationFolder || '.');
|
|
@@ -1086,7 +1101,7 @@ program.option('-V', 'output the version');
|
|
|
1086
1101
|
for(const snapRel of snapshotFiles){
|
|
1087
1102
|
const snapFile = path.resolve(executedLocation, snapRel);
|
|
1088
1103
|
let cs;
|
|
1089
|
-
try{ cs = JSON.parse(fs.readFileSync(snapFile, 'utf8')); }catch(_){ continue; }
|
|
1104
|
+
try{ cs = __normalizeSnapshotPaths(JSON.parse(fs.readFileSync(snapFile, 'utf8'))); }catch(_){ continue; }
|
|
1090
1105
|
const snapDir = path.dirname(snapFile);
|
|
1091
1106
|
const contextAbs = path.resolve(snapDir, cs.contextLocation || '');
|
|
1092
1107
|
let migBase = path.resolve(snapDir, cs.migrationFolder || '.');
|
package/Migrations/migrations.js
CHANGED
|
@@ -7,7 +7,7 @@ import { pathToFileURL } from 'node:url';
|
|
|
7
7
|
import * as diff from 'deep-object-diff';
|
|
8
8
|
import { globSync } from 'glob';
|
|
9
9
|
import MigrationTemplate from './migrationTemplate.js';
|
|
10
|
-
import { resolveMigrationsDirectory } from './pathUtils.js';
|
|
10
|
+
import { resolveMigrationsDirectory, toPosixPath } from './pathUtils.js';
|
|
11
11
|
|
|
12
12
|
// https://blog.tekspace.io/code-first-multiple-db-context-migration/
|
|
13
13
|
|
|
@@ -449,8 +449,13 @@ class Migrations{
|
|
|
449
449
|
|
|
450
450
|
const snapshotPath = path.join(migrationsDirectory, `${snap.contextFileName}_contextSnapShot.json`);
|
|
451
451
|
|
|
452
|
-
// Store relative paths (portable): values are relative to the snapshot file
|
|
453
|
-
|
|
452
|
+
// Store relative paths (portable): values are relative to the snapshot file
|
|
453
|
+
// directory (migrationsDirectory). path.relative() emits backslashes on
|
|
454
|
+
// Windows, which are literal characters on POSIX — normalize to forward
|
|
455
|
+
// slashes so a snapshot generated on Windows deploys cleanly on Linux.
|
|
456
|
+
// (migrationFolder is the literal '.' and snapShotLocation a basename, so
|
|
457
|
+
// neither can carry a separator today.)
|
|
458
|
+
const relContextLocation = toPosixPath(path.relative(migrationsDirectory, snap.file));
|
|
454
459
|
const relMigrationFolder = '.'; // the snapshot sits inside migrationsDirectory
|
|
455
460
|
const relSnapshotLocation = path.basename(snapshotPath);
|
|
456
461
|
|
package/Migrations/pathUtils.js
CHANGED
|
@@ -70,4 +70,22 @@ function isInMigrationsDirectory(filePath) {
|
|
|
70
70
|
return normalized.includes('/db/migrations') || normalized.includes('\\db\\migrations');
|
|
71
71
|
}
|
|
72
72
|
|
|
73
|
-
|
|
73
|
+
/**
|
|
74
|
+
* Convert a path to POSIX separators (every backslash → forward slash).
|
|
75
|
+
*
|
|
76
|
+
* Snapshot files store RELATIVE paths that must work on every platform.
|
|
77
|
+
* `path.relative()` emits backslashes on Windows; on Linux a backslash is a
|
|
78
|
+
* literal filename character, so resolving such a value produces a bogus
|
|
79
|
+
* specifier and the dynamic `import()` of the context dies with
|
|
80
|
+
* ERR_INVALID_MODULE_SPECIFIER before any migration runs. Forward slashes
|
|
81
|
+
* are valid path separators on every platform Node supports (including
|
|
82
|
+
* Windows), so normalizing is always safe.
|
|
83
|
+
*
|
|
84
|
+
* @param {string} p - Path that may contain backslash separators
|
|
85
|
+
* @returns {string} The same path with forward slashes only
|
|
86
|
+
*/
|
|
87
|
+
function toPosixPath(p) {
|
|
88
|
+
return typeof p === 'string' ? p.replace(/\\/g, '/') : p;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export { resolveMigrationsDirectory, isInMigrationsDirectory, toPosixPath };
|
package/docs/TROUBLESHOOTING.md
CHANGED
|
@@ -321,3 +321,28 @@ await ctx.execute('UPDATE "User" SET name = ? WHERE id = ?', ['Alice', id]);
|
|
|
321
321
|
```
|
|
322
322
|
|
|
323
323
|
Better still, prefer the ORM (`ctx.User.where(u => u.id == $$, id).single()`), which is portable by construction. On a non-SQLite engine, `ctx.db.prepare()` now throws a descriptive error pointing you to `ctx.query()`.
|
|
324
|
+
|
|
325
|
+
## `ERR_INVALID_MODULE_SPECIFIER` on Linux after generating migrations on Windows
|
|
326
|
+
|
|
327
|
+
A migration snapshot generated on Windows before **1.3.1** stored `contextLocation`
|
|
328
|
+
with backslashes (e.g. `"..\\..\\AppContext.js"`). On Linux a backslash is a literal
|
|
329
|
+
filename character, so the CLI's `path.resolve()` built a bogus module specifier and
|
|
330
|
+
the ESM import of the context failed **before any migration ran** — a deploy could
|
|
331
|
+
crash-loop at boot even with a fully up-to-date database.
|
|
332
|
+
|
|
333
|
+
**Fix:** upgrade to `masterrecord@1.3.1`. The snapshot writer now stores POSIX
|
|
334
|
+
separators, and every CLI read site normalizes on load — so already-committed
|
|
335
|
+
backslash snapshots keep working without regeneration.
|
|
336
|
+
|
|
337
|
+
## "Bulk insert failed, falling back to individual inserts" in the logs
|
|
338
|
+
|
|
339
|
+
Before **1.3.1**, saving a batch whose rows populated *different* column sets (some
|
|
340
|
+
rows leave optional fields unset, and auto-PKs are always skipped) emitted one
|
|
341
|
+
multi-row INSERT built from the FIRST row's column list — malformed for the rest
|
|
342
|
+
(MySQL `ER_WRONG_VALUE_COUNT_ON_ROW`) — and the context silently fell back to slow
|
|
343
|
+
per-row inserts. Rows whose column COUNT matched but column SET differed could even
|
|
344
|
+
land values in the wrong columns.
|
|
345
|
+
|
|
346
|
+
**Fix:** upgrade to `masterrecord@1.3.1`. Heterogeneous batches are sub-grouped by
|
|
347
|
+
column signature, one multi-value INSERT per signature, omitted columns keep their
|
|
348
|
+
database `DEFAULT`, and ids map back to entities in their original input order.
|
package/mySQLEngine.js
CHANGED
|
Binary file
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "masterrecord",
|
|
3
|
-
"version": "1.3.
|
|
3
|
+
"version": "1.3.1",
|
|
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",
|
|
@@ -49,7 +49,7 @@
|
|
|
49
49
|
"node": ">=20.0.0"
|
|
50
50
|
},
|
|
51
51
|
"scripts": {
|
|
52
|
-
"test": "node --test test/ Migrations/pathUtils.test.js",
|
|
52
|
+
"test": "node --test test/*.test.js test/integration/*.test.js Migrations/pathUtils.test.js",
|
|
53
53
|
"lint": "eslint . --fix",
|
|
54
54
|
"lint:check": "eslint ."
|
|
55
55
|
},
|
package/postgresEngine.js
CHANGED
|
@@ -120,40 +120,53 @@ class postgresEngine {
|
|
|
120
120
|
async bulkInsert(entities) {
|
|
121
121
|
if (!entities || entities.length === 0) return [];
|
|
122
122
|
|
|
123
|
-
//
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
123
|
+
// Build each row's SQL object up front, keeping its ORIGINAL index so
|
|
124
|
+
// the returned array aligns with the input order — the contract
|
|
125
|
+
// context._processBatchInserts relies on when writing ids back.
|
|
126
|
+
const rows = entities.map((entity, index) => ({
|
|
127
|
+
index,
|
|
128
|
+
entity,
|
|
129
|
+
sql: this._buildSQLInsertObjectParameterized(entity, entity.__entity),
|
|
130
|
+
}));
|
|
131
|
+
|
|
132
|
+
// One multi-value INSERT can only serve rows that share the SAME
|
|
133
|
+
// column list. The builder skips unset optional columns and auto PKs,
|
|
134
|
+
// so a batch can be heterogeneous; reusing the first row's columns for
|
|
135
|
+
// every row produced malformed statements (or, when the counts
|
|
136
|
+
// happened to match, values landing in the wrong columns). Sub-group
|
|
137
|
+
// by table + exact column signature and emit one statement per group.
|
|
138
|
+
// No NULL-padding to a column union — that would override DB-level
|
|
139
|
+
// column defaults.
|
|
140
|
+
const groups = new Map();
|
|
141
|
+
for (const row of rows) {
|
|
142
|
+
const key = `${row.sql.tableName} ${row.sql.columns}`;
|
|
143
|
+
if (!groups.has(key)) groups.set(key, []);
|
|
144
|
+
groups.get(key).push(row);
|
|
129
145
|
}
|
|
130
146
|
|
|
131
|
-
const results =
|
|
132
|
-
for (const
|
|
133
|
-
const
|
|
134
|
-
const primaryKey = tools.getPrimaryKeyObject(
|
|
135
|
-
|
|
136
|
-
//
|
|
137
|
-
const
|
|
138
|
-
const allParams = [
|
|
139
|
-
let paramIndex =
|
|
140
|
-
const
|
|
141
|
-
|
|
142
|
-
for (let i = 1; i < tableEntities.length; i++) {
|
|
143
|
-
const sqlObj = this._buildSQLInsertObjectParameterized(tableEntities[i], tableEntities[i].__entity);
|
|
144
|
-
// Renumber placeholders
|
|
145
|
-
const placeholders = sqlObj.params.map(() => `$${paramIndex++}`).join(', ');
|
|
147
|
+
const results = new Array(entities.length);
|
|
148
|
+
for (const group of groups.values()) {
|
|
149
|
+
const first = group[0].sql;
|
|
150
|
+
const primaryKey = tools.getPrimaryKeyObject(group[0].entity.__entity);
|
|
151
|
+
|
|
152
|
+
// Renumber $n placeholders per statement (each group restarts at $1).
|
|
153
|
+
const valueGroups = [];
|
|
154
|
+
const allParams = [];
|
|
155
|
+
let paramIndex = 1;
|
|
156
|
+
for (const row of group) {
|
|
157
|
+
const placeholders = row.sql.params.map(() => `$${paramIndex++}`).join(', ');
|
|
146
158
|
valueGroups.push(`(${placeholders})`);
|
|
147
|
-
allParams.push(...
|
|
159
|
+
allParams.push(...row.sql.params);
|
|
148
160
|
}
|
|
149
161
|
|
|
150
162
|
const query = `INSERT INTO ${this._q(first.tableName)} (${first.columns}) VALUES ${valueGroups.join(', ')} RETURNING ${this._q(primaryKey)}`;
|
|
151
163
|
const result = await this._runWithParams(query, allParams);
|
|
152
164
|
|
|
153
|
-
//
|
|
154
|
-
//
|
|
155
|
-
for (
|
|
156
|
-
|
|
165
|
+
// RETURNING preserves the VALUES order within a single statement,
|
|
166
|
+
// so row k of the result belongs to group[k].
|
|
167
|
+
for (let i = 0; i < group.length; i++) {
|
|
168
|
+
const row = result.rows[i];
|
|
169
|
+
results[group[i].index] = { id: row ? row[primaryKey] : undefined };
|
|
157
170
|
}
|
|
158
171
|
}
|
|
159
172
|
|