masterrecord 1.2.10 → 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 CHANGED
@@ -1,5 +1,78 @@
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
+
41
+ ## v1.3.0 — full builder type set + inline `env()` config
42
+
43
+ **Added — builder convenience type methods.** Every column type the engines'
44
+ DDL mappers already supported but the entity builder didn't expose now has a
45
+ method: `date()`, `datetime()`, `timestamp()`, `float()`, `decimal()`, `bigint()`,
46
+ `json()`, `uuid()`, `binary()`. Previously only `string/text/integer/time/boolean`
47
+ had methods and everything else required the generic `.type('…')`. Each resolves to
48
+ a valid SQL column type on SQLite, MySQL, and Postgres (verified end-to-end).
49
+
50
+ **Fixed — `context.env()` inline configuration object.** `env()` is documented (its
51
+ JSDoc `@example` and the README) to accept an inline config object —
52
+ `this.env({ type: 'sqlite', connection: './db/' })` — but it always treated its
53
+ argument as a folder path and threw `The "path" argument must be of type string` for
54
+ objects. `env()` now branches: an object is used directly as the config; a string
55
+ still resolves to `env.<NODE_ENV>.json` (keyed by context class name). No change to
56
+ the file-path behavior.
57
+
58
+ **Docs.** README + MIGRATIONS_GUIDE corrected: entity fields are builder **methods**
59
+ (`id(db){ db.integer().primary().auto(); }`), not constructor object-literals (the
60
+ schema builder reads prototype methods and ignores `this.x = {…}` properties); env
61
+ JSON files are keyed by the context class name; the context file is named after the
62
+ context class so the migration CLI (`enable-migrations AppContext`) can resolve it.
63
+
64
+ Tests: `test/builder-type-methods.test.js`, `test/env-inline-config.test.js`.
65
+
66
+ ## Tooling — cross-engine integration tests + CI (no package change)
67
+
68
+ Closes the long-standing verification caveat ("executed on SQLite; MySQL/Postgres verified by code-reading"). Each engine's `bulkInsert` is structurally different (SQLite loops single inserts; MySQL builds one multi-row `VALUES` + `insertId`; Postgres multi-row `VALUES … RETURNING`), so "green on SQLite" does not prove "green on MySQL/Postgres".
69
+
70
+ - **`test/integration/cross-engine.test.js`** — runs the real write/DDL paths against a live server: batch/single `.set()` parity (1.2.10), multi-row `bulkInsert` + auto-PK retrieval, and an executed `alterColumn` type change (1.2.9). Gated on `MR_TEST_MYSQL_URL` / `MR_TEST_PG_URL`; unset → skipped, so the default `npm test` stays SQLite-only and offline.
71
+ - **`.github/workflows/test.yml`** — CI matrix (Node 20/22) with `mysql:8` + `postgres:16` service containers wired to those env vars, so every push executes all three engines. Runs lint + the full suite.
72
+ - **`docker-compose.test.yml`** — spin the same databases up locally to run the integration suite on your machine.
73
+
74
+ None of this ships in the npm tarball (`test/`, `.github/`, compose file are outside the `files` allowlist) — it's repo tooling only, so no version bump.
75
+
3
76
  ## v1.2.10 — batch/single insert parity (.set() setters, defaults, timestamps, relationships)
4
77
 
5
78
  **Bug:** masterrecord had two INSERT write paths that didn't agree. A **single** insert (1 entity) routed through `insertManager`, which applies `.set()` setters, default values, auto timestamps, `belongsTo` FK resolution and validation. A **batch** insert (≥2 entities) called `engine.bulkInsert(entities)` **directly**, bypassing `insertManager` entirely. So saving ≥2 entities at once handed the raw, un-transformed model values straight to the engine — e.g. a field whose `.set()` maps a label to an int (`"operator"→2`) reached an INTEGER column as the string `"operator"`, the engine's type validator threw, and the whole batch **fell back to slow per-row inserts**. Correct data landed (via the fallback), but it was noisy and defeated the batch optimization. The batch path also **silently dropped child-relationship rows** (`hasMany`/`hasOne`/`hasManyThrough`), which only the per-entity path inserts.
@@ -93,11 +93,63 @@ class EntityModel {
93
93
  return this;
94
94
  }
95
95
 
96
+ // Date/time columns. All resolve to TEXT on SQLite, native types on
97
+ // MySQL/Postgres. Store ISO-8601 strings (or epoch numbers) in them.
98
+ date(){
99
+ this.obj.type = "date";
100
+ return this;
101
+ }
102
+
103
+ datetime(){
104
+ this.obj.type = "datetime";
105
+ return this;
106
+ }
107
+
108
+ timestamp(){
109
+ this.obj.type = "timestamp";
110
+ return this;
111
+ }
112
+
96
113
  boolean(){
97
114
  this.obj.type = "boolean";
98
115
  return this;
99
116
  }
100
117
 
118
+ // Numeric columns beyond integer: REAL on SQLite, native on MySQL/Postgres.
119
+ float(){
120
+ this.obj.type = "float";
121
+ return this;
122
+ }
123
+
124
+ decimal(){
125
+ this.obj.type = "decimal";
126
+ return this;
127
+ }
128
+
129
+ bigint(){
130
+ this.obj.type = "bigint";
131
+ return this;
132
+ }
133
+
134
+ // Stored as TEXT/JSON depending on engine. Pair with .get()/.set() (or a
135
+ // transformer) to (de)serialize objects automatically.
136
+ json(){
137
+ this.obj.type = "json";
138
+ return this;
139
+ }
140
+
141
+ // Universally-unique identifier column (TEXT on SQLite).
142
+ uuid(){
143
+ this.obj.type = "uuid";
144
+ return this;
145
+ }
146
+
147
+ // Raw binary column (BLOB).
148
+ binary(){
149
+ this.obj.type = "binary";
150
+ return this;
151
+ }
152
+
101
153
  // maxLength(amount){
102
154
  // this.obj.maxLength = amount;
103
155
  // return this;
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 || '.');
@@ -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
@@ -759,76 +759,91 @@ class context {
759
759
  }
760
760
  const contextName = this.__name;
761
761
 
762
- // Try multiple base roots for robustness
763
- const candidateRoots = [process.cwd(), appRoot.path, __dirname];
764
- let file = null;
765
- const searchErrors = [];
766
-
767
- // Performance: Use for...of instead of index-based loop (more readable, same speed)
768
- for (const candidateRoot of candidateRoots) {
769
- try {
770
- file = this.__findSettings(candidateRoot, rootFolderLocationOrConfig, envType);
771
- if (file) break;
772
- } catch (error) {
773
- searchErrors.push(`${candidateRoot}: ${error.message}`);
774
- }
775
- }
776
-
777
- if (!file && searchErrors.length > 0) {
778
- console.log('[Context] Config search errors:', searchErrors.join('; '));
779
- }
780
- // If still not found and an absolute path was provided, try directly
781
- if (!file && path.isAbsolute(rootFolderLocationOrConfig)) {
782
- const directFolder = rootFolderLocationOrConfig;
783
- const envFileA = path.join(directFolder, `env.${envType}.json`);
784
- const envFileB = path.join(directFolder, `${envType}.json`);
785
- const picked = fs.existsSync(envFileA) ? envFileA : (fs.existsSync(envFileB) ? envFileB : null);
786
-
787
- if (picked) {
788
- // Smart root folder detection for plugin paths
789
- // If the env file is in a bb-plugins/<plugin-name>/config/environments/ structure,
790
- // we should set rootFolder to the project root, not the plugin's config folder
791
- let detectedRoot = path.dirname(path.dirname(picked));
792
-
793
- // Check if we're in a bb-plugins structure
794
- const pickedParts = picked.split(path.sep);
795
- const pluginsIndex = pickedParts.findIndex(part => part === 'bb-plugins');
796
-
797
- if (pluginsIndex !== -1 && pluginsIndex + 3 < pickedParts.length) {
798
- // We're in bb-plugins/<plugin-name>/config/environments/...
799
- // Set rootFolder to the project root (parent of bb-plugins)
800
- const projectRootParts = pickedParts.slice(0, pluginsIndex);
801
- detectedRoot = projectRootParts.join(path.sep) || path.sep;
762
+ // The config can be supplied two ways:
763
+ // 1. An inline config object: this.env({ type: 'sqlite', connection: './db/' })
764
+ // 2. A folder path to load env.<NODE_ENV>.json (keyed by context name):
765
+ // this.env('config/environments')
766
+ let options;
767
+ let rootFolder;
768
+
769
+ if (rootFolderLocationOrConfig && typeof rootFolderLocationOrConfig === 'object') {
770
+ // (1) Inline configuration — use it directly, no file lookup.
771
+ options = rootFolderLocationOrConfig;
772
+ rootFolder = process.cwd();
773
+ } else {
774
+ // (2) Folder path — locate and read env.<NODE_ENV>.json.
775
+ // Try multiple base roots for robustness
776
+ const candidateRoots = [process.cwd(), appRoot.path, __dirname];
777
+ let file = null;
778
+ const searchErrors = [];
779
+
780
+ // Performance: Use for...of instead of index-based loop (more readable, same speed)
781
+ for (const candidateRoot of candidateRoots) {
782
+ try {
783
+ file = this.__findSettings(candidateRoot, rootFolderLocationOrConfig, envType);
784
+ if (file) break;
785
+ } catch (error) {
786
+ searchErrors.push(`${candidateRoot}: ${error.message}`);
802
787
  }
788
+ }
803
789
 
804
- file = { file: picked, rootFolder: detectedRoot };
790
+ if (!file && searchErrors.length > 0) {
791
+ console.log('[Context] Config search errors:', searchErrors.join('; '));
805
792
  }
806
- }
793
+ // If still not found and an absolute path was provided, try directly
794
+ if (!file && path.isAbsolute(rootFolderLocationOrConfig)) {
795
+ const directFolder = rootFolderLocationOrConfig;
796
+ const envFileA = path.join(directFolder, `env.${envType}.json`);
797
+ const envFileB = path.join(directFolder, `${envType}.json`);
798
+ const picked = fs.existsSync(envFileA) ? envFileA : (fs.existsSync(envFileB) ? envFileB : null);
799
+
800
+ if (picked) {
801
+ // Smart root folder detection for plugin paths
802
+ // If the env file is in a bb-plugins/<plugin-name>/config/environments/ structure,
803
+ // we should set rootFolder to the project root, not the plugin's config folder
804
+ let detectedRoot = path.dirname(path.dirname(picked));
805
+
806
+ // Check if we're in a bb-plugins structure
807
+ const pickedParts = picked.split(path.sep);
808
+ const pluginsIndex = pickedParts.findIndex(part => part === 'bb-plugins');
809
+
810
+ if (pluginsIndex !== -1 && pluginsIndex + 3 < pickedParts.length) {
811
+ // We're in bb-plugins/<plugin-name>/config/environments/...
812
+ // Set rootFolder to the project root (parent of bb-plugins)
813
+ const projectRootParts = pickedParts.slice(0, pluginsIndex);
814
+ detectedRoot = projectRootParts.join(path.sep) || path.sep;
815
+ }
807
816
 
808
- if (!file) {
809
- throw new ConfigurationError(
810
- `Environment configuration not found for '${envType}'`,
811
- {
812
- searchPath: rootFolderLocationOrConfig,
813
- environment: envType,
814
- attemptedRoots: candidateRoots
817
+ file = { file: picked, rootFolder: detectedRoot };
815
818
  }
816
- );
817
- }
819
+ }
818
820
 
819
- // Always use absolute file path to avoid module root ambiguity on global installs/Windows
820
- const settingsPath = path.isAbsolute(file.file) ? file.file : path.resolve(file.rootFolder, file.file);
821
- const settings = JSON.parse(fs.readFileSync(settingsPath, 'utf8'));
822
- const options = settings[contextName];
821
+ if (!file) {
822
+ throw new ConfigurationError(
823
+ `Environment configuration not found for '${envType}'`,
824
+ {
825
+ searchPath: rootFolderLocationOrConfig,
826
+ environment: envType,
827
+ attemptedRoots: candidateRoots
828
+ }
829
+ );
830
+ }
823
831
 
824
- if (!options || typeof options !== 'object') {
825
- throw new ConfigurationError(
826
- `Configuration missing settings for context '${contextName}'`,
827
- {
828
- configFile: settingsPath,
829
- availableContexts: Object.keys(settings)
830
- }
831
- );
832
+ // Always use absolute file path to avoid module root ambiguity on global installs/Windows
833
+ const settingsPath = path.isAbsolute(file.file) ? file.file : path.resolve(file.rootFolder, file.file);
834
+ const settings = JSON.parse(fs.readFileSync(settingsPath, 'utf8'));
835
+ options = settings[contextName];
836
+ rootFolder = file.rootFolder;
837
+
838
+ if (!options || typeof options !== 'object') {
839
+ throw new ConfigurationError(
840
+ `Configuration missing settings for context '${contextName}'`,
841
+ {
842
+ configFile: settingsPath,
843
+ availableContexts: Object.keys(settings)
844
+ }
845
+ );
846
+ }
832
847
  }
833
848
 
834
849
  const type = String(options.type || '').toLowerCase();
@@ -849,7 +864,7 @@ class context {
849
864
  this.isPostgres = false;
850
865
 
851
866
  // Resolve database path using extracted method
852
- const dbPath = this._resolveDatabasePath(options.connection, file.rootFolder, contextName);
867
+ const dbPath = this._resolveDatabasePath(options.connection, rootFolder, contextName);
853
868
 
854
869
  // Ensure database directory exists
855
870
  const dbDir = path.dirname(dbPath);
@@ -30,7 +30,9 @@ MasterRecord migrations let you:
30
30
  ### 1. Set up your context
31
31
 
32
32
  ```javascript
33
- // app/models/context.js
33
+ // app/models/AppContext.js
34
+ // Name the file after the context class so `masterrecord enable-migrations AppContext`
35
+ // can find it (the CLI resolves the context by file name: *AppContext.js).
34
36
  import context from 'masterrecord/context';
35
37
  import User from './User.js';
36
38
  import Post from './Post.js';
@@ -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.2.10",
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
- // 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
 
package/readme.md CHANGED
@@ -234,7 +234,9 @@ await db.saveChanges(); // ✅ Batch save
234
234
  ### 1. Create a Context
235
235
 
236
236
  ```javascript
237
- // app/models/context.js
237
+ // app/models/AppContext.js
238
+ // Name the file after the context class so the `masterrecord` migration CLI can
239
+ // resolve it: `masterrecord enable-migrations AppContext` looks for *AppContext.js.
238
240
  import context from 'masterrecord/context';
239
241
  import User from './User.js';
240
242
  import Post from './Post.js';
@@ -266,14 +268,13 @@ export default AppContext;
266
268
 
267
269
  ```javascript
268
270
  // app/models/User.js
271
+ // Each field is a METHOD that receives the schema builder (db).
269
272
  class User {
270
- constructor() {
271
- this.id = { type: 'integer', primary: true, auto: true };
272
- this.name = { type: 'string', nullable: false };
273
- this.email = { type: 'string', nullable: false, unique: true };
274
- this.age = { type: 'integer', nullable: true };
275
- this.created_at = { type: 'timestamp', default: 'CURRENT_TIMESTAMP' };
276
- }
273
+ id(db) { db.integer().primary().auto(); }
274
+ name(db) { db.string().notNullable(); }
275
+ email(db) { db.string().notNullable().unique(); }
276
+ age(db) { db.integer(); } // nullable by default
277
+ created_at(db) { db.datetime(); }
277
278
  }
278
279
 
279
280
  export default User;
@@ -295,7 +296,7 @@ masterrecord update-database AppContext
295
296
  ### 4. Query Your Data
296
297
 
297
298
  ```javascript
298
- import AppContext from './app/models/context.js';
299
+ import AppContext from './app/models/AppContext.js';
299
300
  const db = new AppContext();
300
301
 
301
302
  // Create (Active Record style)
@@ -398,17 +399,20 @@ await db.saveChanges(); // SQLite now has async API wrapper
398
399
 
399
400
  ### Environment Files
400
401
 
401
- Store configurations in JSON files:
402
+ Store configurations in JSON files **keyed by the context class name** (so one file
403
+ can hold settings for multiple contexts):
402
404
 
403
405
  ```json
404
406
  // config/environments/env.development.json
405
407
  {
406
- "type": "postgres",
407
- "host": "localhost",
408
- "port": 5432,
409
- "database": "myapp_dev",
410
- "user": "postgres",
411
- "password": "dev_password"
408
+ "AppContext": {
409
+ "type": "postgres",
410
+ "host": "localhost",
411
+ "port": 5432,
412
+ "database": "myapp_dev",
413
+ "user": "postgres",
414
+ "password": "dev_password"
415
+ }
412
416
  }
413
417
  ```
414
418
 
@@ -433,44 +437,32 @@ node app.js
433
437
 
434
438
  ### Basic Entity
435
439
 
440
+ Each field is a method on the class that receives the schema builder (`db`) and
441
+ chains type + modifiers:
442
+
436
443
  ```javascript
437
444
  class User {
438
- constructor() {
439
- // Primary key with auto-increment
440
- this.id = {
441
- type: 'integer',
442
- primary: true,
443
- auto: true
444
- };
445
+ // Primary key with auto-increment
446
+ id(db) { db.integer().primary().auto(); }
445
447
 
446
- // Required string field
447
- this.name = {
448
- type: 'string',
449
- nullable: false
450
- };
448
+ // Required string field
449
+ name(db) { db.string().notNullable(); }
451
450
 
452
- // Optional field with default
453
- this.status = {
454
- type: 'string',
455
- nullable: true,
456
- default: 'active'
457
- };
451
+ // Optional field with a default value
452
+ status(db) { db.string().default('active'); }
458
453
 
459
- // Unique constraint
460
- this.email = {
461
- type: 'string',
462
- unique: true
463
- };
454
+ // Unique constraint
455
+ email(db) { db.string().unique(); }
464
456
 
465
- // Timestamp
466
- this.created_at = {
467
- type: 'timestamp',
468
- default: 'CURRENT_TIMESTAMP'
469
- };
470
- }
457
+ // Timestamp (stored as TEXT on SQLite; set it in app code or a beforeSave hook)
458
+ created_at(db) { db.datetime(); }
471
459
  }
472
460
  ```
473
461
 
462
+ > **Note:** fields are *methods*, not assigned object literals. MasterRecord reads
463
+ > the class's prototype methods to build the schema; plain `this.x = {...}`
464
+ > properties in the constructor are ignored.
465
+
474
466
  ### Field Types
475
467
 
476
468
  | MasterRecord Type | PostgreSQL | MySQL | SQLite |
@@ -493,34 +485,24 @@ class User {
493
485
 
494
486
  ### Relationships
495
487
 
488
+ Relationships are declared with the `hasMany` / `hasOne` / `belongsTo` builder
489
+ methods. `belongsTo('User')` automatically creates the `user_id` foreign-key column.
490
+
496
491
  ```javascript
497
492
  class User {
498
- constructor() {
499
- this.id = { type: 'integer', primary: true, auto: true };
500
- this.name = { type: 'string' };
501
-
502
- // One-to-many: User has many Posts
503
- this.Posts = {
504
- type: 'hasMany',
505
- model: 'Post',
506
- foreignKey: 'user_id'
507
- };
508
- }
493
+ id(db) { db.integer().primary().auto(); }
494
+ name(db) { db.string(); }
495
+
496
+ // One-to-many: User has many Posts (foreign key inferred as user_id on Post)
497
+ Posts(db) { db.hasMany('Post'); }
509
498
  }
510
499
 
511
500
  class Post {
512
- constructor() {
513
- this.id = { type: 'integer', primary: true, auto: true };
514
- this.title = { type: 'string' };
515
- this.user_id = { type: 'integer' };
516
-
517
- // Many-to-one: Post belongs to User
518
- this.User = {
519
- type: 'belongsTo',
520
- model: 'User',
521
- foreignKey: 'user_id'
522
- };
523
- }
501
+ id(db) { db.integer().primary().auto(); }
502
+ title(db) { db.string(); }
503
+
504
+ // Many-to-one: Post belongs to a User (creates the user_id column)
505
+ User(db) { db.belongsTo('User'); }
524
506
  }
525
507
  ```
526
508
 
@@ -528,23 +510,18 @@ class Post {
528
510
 
529
511
  Store complex JavaScript types in simple database columns:
530
512
 
513
+ Use `.set(fn)` to transform a value on its way **into** the database and `.get(fn)`
514
+ to transform it on the way **out**:
515
+
531
516
  ```javascript
532
517
  class User {
533
- constructor() {
534
- this.id = { type: 'integer', primary: true, auto: true };
535
-
536
- // Store arrays as JSON strings
537
- this.tags = {
538
- type: 'string',
539
- transform: {
540
- toDatabase: (value) => {
541
- return Array.isArray(value) ? JSON.stringify(value) : value;
542
- },
543
- fromDatabase: (value) => {
544
- return value ? JSON.parse(value) : [];
545
- }
546
- }
547
- };
518
+ id(db) { db.integer().primary().auto(); }
519
+
520
+ // Store arrays as JSON strings transparently
521
+ tags(db) {
522
+ db.string()
523
+ .set((value) => (Array.isArray(value) ? JSON.stringify(value) : value))
524
+ .get((value) => (value ? JSON.parse(value) : []));
548
525
  }
549
526
  }
550
527
 
@@ -922,26 +899,20 @@ await db.saveChanges();
922
899
 
923
900
  ```javascript
924
901
  class Post {
925
- constructor() {
926
- this.id = { type: 'integer', primary: true, auto: true };
927
-
928
- // Store array as JSON
929
- this.tags = {
930
- type: 'string',
931
- transform: {
932
- toDatabase: (v) => Array.isArray(v) ? JSON.stringify(v) : v,
933
- fromDatabase: (v) => v ? JSON.parse(v) : []
934
- }
935
- };
902
+ id(db) { db.integer().primary().auto(); }
936
903
 
937
- // PostgreSQL JSONB (native JSON support)
938
- this.metadata = {
939
- type: 'jsonb', // PostgreSQL only
940
- transform: {
941
- toDatabase: (v) => JSON.stringify(v || {}),
942
- fromDatabase: (v) => typeof v === 'string' ? JSON.parse(v) : v
943
- }
944
- };
904
+ // Store array as JSON in a TEXT column
905
+ tags(db) {
906
+ db.string()
907
+ .set((v) => (Array.isArray(v) ? JSON.stringify(v) : v))
908
+ .get((v) => (v ? JSON.parse(v) : []));
909
+ }
910
+
911
+ // Native JSON column (JSON/JSONB on Postgres & MySQL, TEXT on SQLite)
912
+ metadata(db) {
913
+ db.json()
914
+ .set((v) => JSON.stringify(v || {}))
915
+ .get((v) => (typeof v === 'string' ? JSON.parse(v) : v));
945
916
  }
946
917
  }
947
918
  ```
@@ -1575,17 +1546,10 @@ If your entity has cascade delete rules, they will be applied automatically:
1575
1546
 
1576
1547
  ```javascript
1577
1548
  class User {
1578
- constructor() {
1579
- this.id = { type: 'integer', primary: true, auto: true };
1580
-
1581
- // Posts will be deleted when user is deleted
1582
- this.Posts = {
1583
- type: 'hasMany',
1584
- model: 'Post',
1585
- foreignKey: 'user_id',
1586
- cascade: true // Enable cascade delete
1587
- };
1588
- }
1549
+ id(db) { db.integer().primary().auto(); }
1550
+
1551
+ // hasMany cascades by default — call .stopCascadeOnDelete() to opt out
1552
+ Posts(db) { db.hasMany('Post'); }
1589
1553
  }
1590
1554
 
1591
1555
  const user = await db.User.findById(1);
@@ -1749,25 +1713,18 @@ Add lifecycle hooks to your entity definitions to execute logic before/after dat
1749
1713
  import bcrypt from 'bcrypt';
1750
1714
 
1751
1715
  class User {
1752
- constructor() {
1753
- this.id = { type: 'integer', primary: true, auto: true };
1754
- this.email = { type: 'string' };
1755
- this.password = { type: 'string' };
1756
- this.created_at = { type: 'timestamp' };
1757
- this.updated_at = { type: 'timestamp' };
1758
- this.role = { type: 'string' };
1759
- }
1716
+ id(db) { db.integer().primary().auto(); }
1717
+ email(db) { db.string(); }
1718
+ password(db) { db.string(); }
1719
+ created_at(db) { db.datetime(); }
1720
+ updated_at(db) { db.datetime(); }
1721
+ role(db) { db.string(); }
1760
1722
 
1761
- // Hash password before saving
1723
+ // Hash the password (when changed) and stamp timestamps before saving.
1762
1724
  beforeSave() {
1763
- // Only hash if password was changed
1764
1725
  if (this.__dirtyFields.includes('password')) {
1765
1726
  this.password = bcrypt.hashSync(this.password, 10);
1766
1727
  }
1767
- }
1768
-
1769
- // Set timestamps automatically
1770
- beforeSave() {
1771
1728
  if (this.__state === 'insert') {
1772
1729
  this.created_at = new Date();
1773
1730
  }
@@ -3110,7 +3067,7 @@ schema.bulkSeed(tableName, dataArray)
3110
3067
  ### Complete CRUD Example
3111
3068
 
3112
3069
  ```javascript
3113
- import AppContext from './app/models/context.js';
3070
+ import AppContext from './app/models/AppContext.js';
3114
3071
 
3115
3072
  async function demo() {
3116
3073
  const db = new AppContext();