masterrecord 1.3.0 → 1.3.2

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 CHANGED
@@ -1,5 +1,58 @@
1
1
  # MasterRecord Changelog
2
2
 
3
+ ## v1.3.2 — migration CLI auto-creates a missing MySQL/Postgres database
4
+
5
+ **Bug (critical for first deploys):** `update-database` printed *"Instantiating Context (this will create the database if it doesn't exist)…"*, but it `await`ed the raw `context._initPromise` directly. When the target database didn't exist, that promise rejected with `Unknown database 'X'` (MySQL) / `database "X" does not exist` (Postgres), and the catch block merely reported failure and exited — it **never invoked the auto-create** (`_createDatabaseFromConfig` + retry) that lives in `schema._ensureReady()`. So a first-time deploy against an empty server failed with a confusing error despite the CLI claiming it would create the database. (Confirmed present through 1.3.1.)
6
+
7
+ **Fix:**
8
+ - New shared bootstrap `Migrations/contextInit.js` → `instantiateReadyContext(ContextCtor)` routes context construction through `schema._ensureReady()`, which auto-creates a missing MySQL/Postgres database and retries the connection. It marks the returned context `_ready` so later `_execute()`/`query()` calls don't re-await the now-settled (rejected) original init promise. SQLite is unaffected (the driver creates the file on open).
9
+ - `update-database`, `update-database-restart`, and `update-database-all` now use it. `update-database-restart`/`-all` additionally never awaited async MySQL/Postgres init at all — also fixed.
10
+
11
+ **Deep-dive findings (fixed in the same release):**
12
+ - `context.query()` blindly awaited `_initPromise`, so after the auto-create retry swapped in a live engine it could still re-throw the stale rejection. It now goes through `_ensureReady()` (short-circuits on `_ready`).
13
+ - `add-migration-all` constructed contexts **without** `MASTERRECORD_SCHEMA_ONLY`, unlike the single `add-migration` — so generating migrations for all contexts needlessly required a reachable database (and hit the missing-DB init path on MySQL/Postgres). Now schema-only, matching `add-migration`.
14
+ - Reviewed the remaining construction sites: `ensure-database` (dedicated create — correct), per-migration `new Migration(ContextCtor)` (each runs `schema._ensureReady()` internally — correct), and the rollback commands `update-database-down`/`-target` (auto-create is intentionally **not** applied — you can't roll back a database that was never created; `-down` already awaits init, `-target` never queries its bootstrap context).
15
+
16
+ New tests: `test/cli-context-init.test.js` (SQLite: bootstrap returns a ready, queryable context) and a gated `[engine] migration bootstrap AUTO-CREATES a missing database` integration test (drops a throwaway DB, bootstraps, asserts it was created and is queryable). Full suite green (0 fail); 0 lint errors. The live auto-create assertion runs in CI against the MySQL/Postgres service containers.
17
+
18
+ ## v1.3.1 — portable snapshots + heterogeneous batch inserts
19
+
20
+ **Fixed — Windows-generated migration snapshots broke Linux deploys (critical).**
21
+ `createSnapShot` stored `contextLocation` straight from `path.relative()`, which
22
+ emits backslashes on Windows. On Linux a backslash is a literal filename
23
+ character, so the CLI's `path.resolve()` built a bogus specifier and the ESM
24
+ import of the context died with `ERR_INVALID_MODULE_SPECIFIER` **before any
25
+ migration ran** — a backend container crash-looped at boot even with a fully
26
+ up-to-date database. Fix on both ends: `Migrations/pathUtils.js` gains
27
+ `toPosixPath()` (every `\` → `/`; forward slashes are valid on all platforms
28
+ Node supports, so Windows behavior is unchanged); the snapshot **writer**
29
+ normalizes `contextLocation` before serializing, and every CLI **read** site
30
+ normalizes on load — so already-committed backslash snapshots in user repos
31
+ work without regeneration.
32
+
33
+ **Fixed — `bulkInsert` built one INSERT from heterogeneous rows (MySQL +
34
+ Postgres).** The multi-row INSERT took its column list from the FIRST entity
35
+ but appended EACH entity's own placeholder group. Batched rows with different
36
+ populated field sets (the builder skips unset optional columns and auto-PKs)
37
+ produced a malformed statement — MySQL `ER_WRONG_VALUE_COUNT_ON_ROW` — and the
38
+ context silently fell back to slow per-row inserts on every such batch; worse,
39
+ rows whose column COUNT matched while the column SET differed would have landed
40
+ values in the wrong columns. Now rows are sub-grouped by identical column
41
+ signature and ONE multi-value INSERT is emitted per signature (no NULL-padding
42
+ to a column union — an omitted column keeps its DB-level `DEFAULT`, pinned by a
43
+ new integration test). Postgres `$n` placeholders renumber per statement, and
44
+ results map back to entities in their **original input order** — the contract
45
+ `context._processBatchInserts` relies on, which also fixes a latent id
46
+ misalignment when one batch spanned multiple tables. SQLite is unaffected (it
47
+ loops single inserts in a transaction).
48
+
49
+ **Tests.** Cross-engine integration tests now quote table identifiers per
50
+ engine (`user` is reserved in Postgres, and unquoted DDL case-folds to a
51
+ different relation than the engine's quoted writes), and every test body runs
52
+ in `try/finally` so `ctx.close()` always releases the pool — a failing test can
53
+ no longer hang the `node --test` runner. New `[engine] heterogeneous batch
54
+ stays on the bulk path` test pins the bulkInsert fix on both live engines.
55
+
3
56
  ## v1.3.0 — full builder type set + inline `env()` config
4
57
 
5
58
  **Added — builder convenience type methods.** Every column type the engines'
package/Migrations/cli.js CHANGED
@@ -9,8 +9,9 @@ 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
+ import { instantiateReadyContext } from './contextInit.js';
14
15
 
15
16
  const __filename = fileURLToPath(import.meta.url);
16
17
  const __dirname = path.dirname(__filename);
@@ -29,6 +30,21 @@ async function __loadUserModule(filePath) {
29
30
 
30
31
  const pkg = JSON.parse(fs.readFileSync(path.join(__dirname, '..', 'package.json'), 'utf8'));
31
32
 
33
+ // Snapshots written on Windows before 1.3.1 can contain backslash-relative
34
+ // paths (e.g. "..\\..\\userContext.js"). On POSIX a backslash is a literal
35
+ // filename character, so path.resolve() builds a bogus specifier and the
36
+ // dynamic import of the context dies with ERR_INVALID_MODULE_SPECIFIER
37
+ // before any migration runs. Normalize every path-bearing field on load so
38
+ // already-committed snapshots keep working without regeneration.
39
+ function __normalizeSnapshotPaths(snapshot){
40
+ if (snapshot && typeof snapshot === 'object') {
41
+ for (const key of ['contextLocation', 'migrationFolder', 'snapShotLocation']) {
42
+ if (typeof snapshot[key] === 'string') snapshot[key] = toPosixPath(snapshot[key]);
43
+ }
44
+ }
45
+ return snapshot;
46
+ }
47
+
32
48
  // Extract numeric timestamp from migration filename (e.g., 1737999999999_name_migration.js)
33
49
  function __getMigrationTimestamp(file){
34
50
  try{
@@ -189,7 +205,7 @@ program.option('-V', 'output the version');
189
205
  }
190
206
  let contextSnapshot;
191
207
  try{
192
- contextSnapshot = JSON.parse(fs.readFileSync(file, 'utf8'));
208
+ contextSnapshot = __normalizeSnapshotPaths(JSON.parse(fs.readFileSync(file, 'utf8')));
193
209
  }catch(_){
194
210
  console.log(`Error - Cannot read context snapshot at '${file}'.`);
195
211
  return;
@@ -295,7 +311,7 @@ program.option('-V', 'output the version');
295
311
  }
296
312
  let contextSnapshot = null;
297
313
  try{
298
- contextSnapshot = JSON.parse(fs.readFileSync(file, 'utf8'));
314
+ contextSnapshot = __normalizeSnapshotPaths(JSON.parse(fs.readFileSync(file, 'utf8')));
299
315
  }catch(_){
300
316
  console.log(`Error - Cannot read context snapshot at '${file}'.`);
301
317
  return;
@@ -402,7 +418,7 @@ program.option('-V', 'output the version');
402
418
 
403
419
  let contextSnapshot;
404
420
  try{
405
- contextSnapshot = JSON.parse(fs.readFileSync(file, 'utf8'));
421
+ contextSnapshot = __normalizeSnapshotPaths(JSON.parse(fs.readFileSync(file, 'utf8')));
406
422
  }catch(err){
407
423
  console.error(`\n❌ Error - Cannot load context snapshot`);
408
424
  console.error(`\nFile: ${file}`);
@@ -458,12 +474,12 @@ program.option('-V', 'output the version');
458
474
  console.log(`\n🔍 Instantiating Context (this will create the database if it doesn't exist)...`);
459
475
 
460
476
  try{
461
- contextInstance = new ContextCtor();
462
- // MySQL/Postgres initialize asynchronously — wait for the pool
463
- // before we can run any migration queries against it.
464
- if (contextInstance && contextInstance._initPromise) {
465
- await contextInstance._initPromise;
466
- }
477
+ // Route through the schema layer so a missing MySQL/Postgres
478
+ // database is AUTO-CREATED (and the connection retried) before any
479
+ // migration runs — honoring the message printed just above. Awaiting
480
+ // the raw _initPromise here used to just report "Unknown database"
481
+ // and exit without ever creating it.
482
+ contextInstance = await instantiateReadyContext(ContextCtor);
467
483
  }catch(err){
468
484
  console.error(`\n❌ Error - Failed to instantiate Context`);
469
485
  console.error(`\nContext file: ${contextAbs}`);
@@ -619,7 +635,7 @@ program.option('-V', 'output the version');
619
635
  }
620
636
  let contextSnapshot;
621
637
  try{
622
- contextSnapshot = JSON.parse(fs.readFileSync(file, 'utf8'));
638
+ contextSnapshot = __normalizeSnapshotPaths(JSON.parse(fs.readFileSync(file, 'utf8')));
623
639
  }catch(_){
624
640
  console.log(`Error - Cannot read context snapshot at '${file}'.`);
625
641
  return;
@@ -744,7 +760,7 @@ program.option('-V', 'output the version');
744
760
  }
745
761
  let contextSnapshot;
746
762
  try{
747
- contextSnapshot = JSON.parse(fs.readFileSync(file, 'utf8'));
763
+ contextSnapshot = __normalizeSnapshotPaths(JSON.parse(fs.readFileSync(file, 'utf8')));
748
764
  }catch(_){
749
765
  console.log(`Error - Cannot read context snapshot at '${file}'.`);
750
766
  return;
@@ -777,7 +793,9 @@ program.option('-V', 'output the version');
777
793
  }
778
794
  var contextInstance;
779
795
  try{
780
- contextInstance = new ContextCtor();
796
+ // Auto-create a missing MySQL/Postgres database (and await async
797
+ // init) via the schema layer before applying migrations.
798
+ contextInstance = await instantiateReadyContext(ContextCtor);
781
799
  }catch(err){
782
800
  console.error(`\n❌ Error - Failed to construct Context from '${contextAbs}'`);
783
801
  console.error(`\nThis usually happens when:`);
@@ -835,7 +853,7 @@ program.option('-V', 'output the version');
835
853
  }
836
854
  let contextSnapshot;
837
855
  try{
838
- contextSnapshot = JSON.parse(fs.readFileSync(file, 'utf8'));
856
+ contextSnapshot = __normalizeSnapshotPaths(JSON.parse(fs.readFileSync(file, 'utf8')));
839
857
  }catch(_){
840
858
  console.log(`Error - Cannot read context snapshot at '${file}'.`);
841
859
  return;
@@ -885,7 +903,7 @@ program.option('-V', 'output the version');
885
903
 
886
904
  let contextSnapshot;
887
905
  try{
888
- contextSnapshot = JSON.parse(fs.readFileSync(snapshotFile, 'utf8'));
906
+ contextSnapshot = __normalizeSnapshotPaths(JSON.parse(fs.readFileSync(snapshotFile, 'utf8')));
889
907
  }catch(_){
890
908
  console.log(`Error - Cannot read context snapshot at '${snapshotFile}'.`);
891
909
  return;
@@ -1000,7 +1018,7 @@ program.option('-V', 'output the version');
1000
1018
  try{
1001
1019
  const snapFile = path.resolve(executedLocation, snapRel);
1002
1020
  let cs;
1003
- try{ cs = JSON.parse(fs.readFileSync(snapFile, 'utf8')); }catch(_){ continue; }
1021
+ try{ cs = __normalizeSnapshotPaths(JSON.parse(fs.readFileSync(snapFile, 'utf8'))); }catch(_){ continue; }
1004
1022
  const snapDir = path.dirname(snapFile);
1005
1023
  const contextAbs = path.resolve(snapDir, cs.contextLocation || '');
1006
1024
  const migBase = path.resolve(snapDir, cs.migrationFolder || '.');
@@ -1015,9 +1033,16 @@ program.option('-V', 'output the version');
1015
1033
  }
1016
1034
  let contextInstance;
1017
1035
  try{
1036
+ // Generating a migration only needs entity metadata, not a live DB.
1037
+ // Schema-only mode skips connection/init — matching `add-migration`
1038
+ // (without it, add-migration-all needlessly required a reachable
1039
+ // database and would hit the missing-DB init path on MySQL/Postgres).
1040
+ process.env.MASTERRECORD_SCHEMA_ONLY = '1';
1018
1041
  contextInstance = new ContextCtor();
1042
+ delete process.env.MASTERRECORD_SCHEMA_ONLY;
1019
1043
  contextInstances.push(contextInstance);
1020
1044
  }catch(err){
1045
+ delete process.env.MASTERRECORD_SCHEMA_ONLY;
1021
1046
  console.error(`⚠️ Skipping ${path.basename(contextAbs)}: failed to construct Context`);
1022
1047
  console.error(` Details: ${err.message}`);
1023
1048
  continue;
@@ -1086,7 +1111,7 @@ program.option('-V', 'output the version');
1086
1111
  for(const snapRel of snapshotFiles){
1087
1112
  const snapFile = path.resolve(executedLocation, snapRel);
1088
1113
  let cs;
1089
- try{ cs = JSON.parse(fs.readFileSync(snapFile, 'utf8')); }catch(_){ continue; }
1114
+ try{ cs = __normalizeSnapshotPaths(JSON.parse(fs.readFileSync(snapFile, 'utf8'))); }catch(_){ continue; }
1090
1115
  const snapDir = path.dirname(snapFile);
1091
1116
  const contextAbs = path.resolve(snapDir, cs.contextLocation || '');
1092
1117
  let migBase = path.resolve(snapDir, cs.migrationFolder || '.');
@@ -1132,7 +1157,9 @@ program.option('-V', 'output the version');
1132
1157
  }
1133
1158
  var contextInstance;
1134
1159
  try{
1135
- contextInstance = new ContextCtor();
1160
+ // Auto-create a missing MySQL/Postgres database (and await async
1161
+ // init) via the schema layer before applying migrations.
1162
+ contextInstance = await instantiateReadyContext(ContextCtor);
1136
1163
  contextInstances.push(contextInstance);
1137
1164
  }catch(err){
1138
1165
  console.error(`⚠️ Skipping ${entry.ctxName}: failed to construct Context`);
@@ -0,0 +1,39 @@
1
+ // version 1.3.2 - ESM only
2
+ import schema from './schema.js';
3
+
4
+ /**
5
+ * Instantiate a user context and ensure its database is reachable for
6
+ * migrations, AUTO-CREATING a missing MySQL/Postgres database (and retrying the
7
+ * connection) via the schema layer — the same path `ensure-database` uses.
8
+ *
9
+ * Why this exists: the migration CLI used to await the raw
10
+ * `context._initPromise` directly. When the target database didn't exist yet,
11
+ * that promise rejected with "Unknown database 'X'" (MySQL) /
12
+ * `database "X" does not exist` (Postgres), and the CLI's catch block merely
13
+ * reported failure and exited — it never invoked the auto-create that lives in
14
+ * `schema._ensureReady()` (`_createDatabaseFromConfig` + retry). So the CLI's
15
+ * own message "this will create the database if it doesn't exist" was a lie for
16
+ * a first-time deploy against an empty server. Routing through
17
+ * `schema._ensureReady()` makes that promise real.
18
+ *
19
+ * SQLite is unaffected (the driver creates the file on open); for SQLite this
20
+ * is just a normal construct-and-connect.
21
+ *
22
+ * @param {Function} ContextCtor - The user's context class (constructor)
23
+ * @returns {Promise<object>} A ready context whose engine/pool is live
24
+ * @throws Propagates a genuine connection/config failure (not "db missing")
25
+ */
26
+ export async function instantiateReadyContext(ContextCtor) {
27
+ const initSchema = new schema(ContextCtor);
28
+ await initSchema._ensureReady();
29
+ const ctx = initSchema.context;
30
+ // After _ensureReady() the engine/pool is live — including the
31
+ // create-database-then-retry path, which swaps in a fresh engine/pool but
32
+ // leaves the original (now-settled, possibly rejected) _initPromise in
33
+ // place. Mark the context ready so later context._execute() calls
34
+ // short-circuit context._ensureReady() instead of re-awaiting that promise.
35
+ ctx._ready = true;
36
+ return ctx;
37
+ }
38
+
39
+ export default instantiateReadyContext;
@@ -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 directory (migrationsDirectory)
453
- const relContextLocation = path.relative(migrationsDirectory, snap.file);
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
 
@@ -70,4 +70,22 @@ function isInMigrationsDirectory(filePath) {
70
70
  return normalized.includes('/db/migrations') || normalized.includes('\\db\\migrations');
71
71
  }
72
72
 
73
- export { resolveMigrationsDirectory, isInMigrationsDirectory };
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/context.js CHANGED
@@ -2118,7 +2118,12 @@ class context {
2118
2118
  * await ctx.execute('UPDATE Step SET run_id = ? WHERE id = ?', ['run_x', 1]); // sqlite/mysql
2119
2119
  */
2120
2120
  async query(sql, params = []) {
2121
- if (this._initPromise) { await this._initPromise; } // MySQL/Postgres async init
2121
+ // Honor the readiness flag rather than blindly awaiting _initPromise:
2122
+ // after the migration auto-create path swaps in a live engine, the
2123
+ // original _initPromise may be settled-rejected, and re-awaiting it
2124
+ // would throw even though the connection is healthy. _ensureReady()
2125
+ // short-circuits on _ready and validates the engine.
2126
+ await this._ensureReady();
2122
2127
  if (!this._SQLEngine) {
2123
2128
  throw new DatabaseConnectionError(
2124
2129
  'Cannot run query: database engine not initialized. Ensure you have awaited env() before querying.',
@@ -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.0",
3
+ "version": "1.3.2",
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
- // Group by table name
124
- const byTable = {};
125
- for (const entity of entities) {
126
- const tableName = entity.__entity.__name;
127
- if (!byTable[tableName]) byTable[tableName] = [];
128
- byTable[tableName].push(entity);
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 tableName in byTable) {
133
- const tableEntities = byTable[tableName];
134
- const primaryKey = tools.getPrimaryKeyObject(tableEntities[0].__entity);
135
-
136
- // Build multi-value INSERT
137
- const first = this._buildSQLInsertObjectParameterized(tableEntities[0], tableEntities[0].__entity);
138
- const allParams = [...first.params];
139
- let paramIndex = first.params.length + 1;
140
- const valueGroups = [`(${first.placeholders})`];
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(...sqlObj.params);
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
- // PostgreSQL returns rows with the primary key values
154
- // Convert to consistent format: { id: value }
155
- for (const row of result.rows) {
156
- results.push({ id: row[primaryKey] });
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