masterrecord 1.2.9 → 1.3.0
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 +47 -0
- package/Entity/entityModel.js +52 -0
- package/context.js +171 -82
- package/docs/MIGRATIONS_GUIDE.md +3 -1
- package/insertManager.js +63 -36
- package/package.json +1 -1
- package/readme.md +85 -128
package/CHANGES.md
CHANGED
|
@@ -1,5 +1,52 @@
|
|
|
1
1
|
# MasterRecord Changelog
|
|
2
2
|
|
|
3
|
+
## v1.3.0 — full builder type set + inline `env()` config
|
|
4
|
+
|
|
5
|
+
**Added — builder convenience type methods.** Every column type the engines'
|
|
6
|
+
DDL mappers already supported but the entity builder didn't expose now has a
|
|
7
|
+
method: `date()`, `datetime()`, `timestamp()`, `float()`, `decimal()`, `bigint()`,
|
|
8
|
+
`json()`, `uuid()`, `binary()`. Previously only `string/text/integer/time/boolean`
|
|
9
|
+
had methods and everything else required the generic `.type('…')`. Each resolves to
|
|
10
|
+
a valid SQL column type on SQLite, MySQL, and Postgres (verified end-to-end).
|
|
11
|
+
|
|
12
|
+
**Fixed — `context.env()` inline configuration object.** `env()` is documented (its
|
|
13
|
+
JSDoc `@example` and the README) to accept an inline config object —
|
|
14
|
+
`this.env({ type: 'sqlite', connection: './db/' })` — but it always treated its
|
|
15
|
+
argument as a folder path and threw `The "path" argument must be of type string` for
|
|
16
|
+
objects. `env()` now branches: an object is used directly as the config; a string
|
|
17
|
+
still resolves to `env.<NODE_ENV>.json` (keyed by context class name). No change to
|
|
18
|
+
the file-path behavior.
|
|
19
|
+
|
|
20
|
+
**Docs.** README + MIGRATIONS_GUIDE corrected: entity fields are builder **methods**
|
|
21
|
+
(`id(db){ db.integer().primary().auto(); }`), not constructor object-literals (the
|
|
22
|
+
schema builder reads prototype methods and ignores `this.x = {…}` properties); env
|
|
23
|
+
JSON files are keyed by the context class name; the context file is named after the
|
|
24
|
+
context class so the migration CLI (`enable-migrations AppContext`) can resolve it.
|
|
25
|
+
|
|
26
|
+
Tests: `test/builder-type-methods.test.js`, `test/env-inline-config.test.js`.
|
|
27
|
+
|
|
28
|
+
## Tooling — cross-engine integration tests + CI (no package change)
|
|
29
|
+
|
|
30
|
+
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".
|
|
31
|
+
|
|
32
|
+
- **`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.
|
|
33
|
+
- **`.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.
|
|
34
|
+
- **`docker-compose.test.yml`** — spin the same databases up locally to run the integration suite on your machine.
|
|
35
|
+
|
|
36
|
+
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.
|
|
37
|
+
|
|
38
|
+
## v1.2.10 — batch/single insert parity (.set() setters, defaults, timestamps, relationships)
|
|
39
|
+
|
|
40
|
+
**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.
|
|
41
|
+
|
|
42
|
+
**Fix (engine-agnostic — applies to SQLite/MySQL/Postgres):**
|
|
43
|
+
- `insertManager` now exposes **`prepareInsertModel(entity)`** — the exact `clearAllProto → validateEntity (normalize: .set/defaults/timestamps) → belongsToInsert` pipeline that `runQueries` uses, minus the execute. `runQueries` was refactored to call it, so single and batch share **one** normalization source of truth.
|
|
44
|
+
- The context **batch path now runs every entity through `prepareInsertModel`** before building the bulk INSERT, so the fast path produces byte-for-byte identical column values to the single path (and inserts the clean, *set-once* model — no double transform).
|
|
45
|
+
- Entities carrying **assigned child-relationship data** are detected (`_batchEntityHasChildren`, own-keys only so no lazy getter is triggered) and routed through the full single-insert path so their children are inserted instead of dropped. The remaining flat entities still get one fast batched insert.
|
|
46
|
+
- The existing fallback-to-per-row-on-error safety net is preserved.
|
|
47
|
+
|
|
48
|
+
New test: `test/batch-insert-set-transform.test.js` — batch applies `.set()` and uses the fast path (no fallback), single/batch store identical values, `prepareInsertModel` returns a clean set-once model, and the child-routing predicate. Full suite **641/641, 0 lint errors**. Verified executing on SQLite; the fix lives in engine-agnostic code (`context.js` + `insertManager.js`), so all three engines share it.
|
|
49
|
+
|
|
3
50
|
## v1.2.9 — alterColumn type changes (SQLite rebuild + affinity-aware no-op)
|
|
4
51
|
|
|
5
52
|
**Bug:** `alterColumn` on SQLite emitted invalid SQL (`near ")"`). SQLite has no `ALTER`/`MODIFY COLUMN`, and `schema.alterColumn`'s builder path was handed an empty/missing table schema, producing `CREATE TABLE x ()`. Additionally, `string→text` is a no-op on SQLite (both TEXT affinity) yet it still attempted a rebuild.
|
package/Entity/entityModel.js
CHANGED
|
@@ -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/context.js
CHANGED
|
@@ -759,76 +759,91 @@ class context {
|
|
|
759
759
|
}
|
|
760
760
|
const contextName = this.__name;
|
|
761
761
|
|
|
762
|
-
//
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
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
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
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,
|
|
867
|
+
const dbPath = this._resolveDatabasePath(options.connection, rootFolder, contextName);
|
|
853
868
|
|
|
854
869
|
// Ensure database directory exists
|
|
855
870
|
const dbDir = path.dirname(dbPath);
|
|
@@ -1700,6 +1715,41 @@ class context {
|
|
|
1700
1715
|
}
|
|
1701
1716
|
}
|
|
1702
1717
|
|
|
1718
|
+
/**
|
|
1719
|
+
* Detect whether a tracked entity carries child-relationship data
|
|
1720
|
+
* (hasMany / hasOne / hasManyThrough) that was explicitly assigned by the
|
|
1721
|
+
* caller. Such entities can't be expressed as a single flat row, so the
|
|
1722
|
+
* batch-insert path routes them through the full single-insert path (which
|
|
1723
|
+
* inserts the children too) instead of the flat bulk path.
|
|
1724
|
+
*
|
|
1725
|
+
* Only OWN enumerable keys are inspected so we never trigger a lazy
|
|
1726
|
+
* relationship getter (those live on the prototype) — an unset relationship
|
|
1727
|
+
* accessor is correctly treated as "no children".
|
|
1728
|
+
*
|
|
1729
|
+
* @private
|
|
1730
|
+
* @param {object} entity - Tracked entity
|
|
1731
|
+
* @returns {boolean} True if the entity has assigned child-relationship data
|
|
1732
|
+
*/
|
|
1733
|
+
_batchEntityHasChildren(entity) {
|
|
1734
|
+
const modelEntity = entity.__entity;
|
|
1735
|
+
if (!modelEntity) {
|
|
1736
|
+
return false;
|
|
1737
|
+
}
|
|
1738
|
+
for (const key of Object.keys(entity)) {
|
|
1739
|
+
const def = modelEntity[key];
|
|
1740
|
+
if (!def) {
|
|
1741
|
+
continue;
|
|
1742
|
+
}
|
|
1743
|
+
if (def.type === 'hasMany' || def.type === 'hasOne' || def.type === 'hasManyThrough') {
|
|
1744
|
+
const value = entity[key];
|
|
1745
|
+
if (value !== undefined && value !== null && typeof value === 'object') {
|
|
1746
|
+
return true;
|
|
1747
|
+
}
|
|
1748
|
+
}
|
|
1749
|
+
}
|
|
1750
|
+
return false;
|
|
1751
|
+
}
|
|
1752
|
+
|
|
1703
1753
|
/**
|
|
1704
1754
|
* Process batch insert operations
|
|
1705
1755
|
*
|
|
@@ -1719,28 +1769,67 @@ class context {
|
|
|
1719
1769
|
const insert = new insertManager(this._SQLEngine, this._isModelValid, this.__entities);
|
|
1720
1770
|
await insert.init(entities[0]);
|
|
1721
1771
|
} else {
|
|
1722
|
-
// Batch insert
|
|
1723
|
-
|
|
1724
|
-
|
|
1772
|
+
// Batch insert. Two write paths used to disagree: the single-insert
|
|
1773
|
+
// path runs each entity through insertManager (which applies .set()
|
|
1774
|
+
// setters, default values, auto timestamps, belongsTo FK resolution
|
|
1775
|
+
// and validation), while the batch path handed RAW model values
|
|
1776
|
+
// straight to the engine. So a label that a .set() maps to an int
|
|
1777
|
+
// (e.g. "operator" -> 2) reached an INTEGER column as a string, the
|
|
1778
|
+
// whole batch threw, and it fell back to slow per-row inserts —
|
|
1779
|
+
// defeating the batch optimization. We now run every batched entity
|
|
1780
|
+
// through the SAME normalization pipeline before building the bulk
|
|
1781
|
+
// INSERT, so the fast path produces identical column values.
|
|
1782
|
+
//
|
|
1783
|
+
// Entities carrying child-relationship data (hasMany / hasOne /
|
|
1784
|
+
// hasManyThrough) cannot be expressed as a single flat row, so they
|
|
1785
|
+
// go through the full single-insert path which inserts their children
|
|
1786
|
+
// too — otherwise the flat bulk path would silently drop them.
|
|
1787
|
+
const relationalEntities = [];
|
|
1788
|
+
const flatEntities = [];
|
|
1789
|
+
for (const entity of entities) {
|
|
1790
|
+
if (this._batchEntityHasChildren(entity)) {
|
|
1791
|
+
relationalEntities.push(entity);
|
|
1792
|
+
} else {
|
|
1793
|
+
flatEntities.push(entity);
|
|
1794
|
+
}
|
|
1795
|
+
}
|
|
1725
1796
|
|
|
1726
|
-
|
|
1727
|
-
|
|
1728
|
-
|
|
1729
|
-
|
|
1797
|
+
// Children-bearing entities: full single path (row + children).
|
|
1798
|
+
for (const entity of relationalEntities) {
|
|
1799
|
+
const insert = new insertManager(this._SQLEngine, this._isModelValid, this.__entities);
|
|
1800
|
+
await insert.init(entity);
|
|
1801
|
+
}
|
|
1802
|
+
|
|
1803
|
+
// Flat entities: normalize each, then one fast batched insert.
|
|
1804
|
+
if (flatEntities.length > 0) {
|
|
1805
|
+
try {
|
|
1806
|
+
const manager = new insertManager(this._SQLEngine, this._isModelValid, this.__entities);
|
|
1807
|
+
const preparedModels = [];
|
|
1808
|
+
for (const entity of flatEntities) {
|
|
1809
|
+
preparedModels.push(await manager.prepareInsertModel(entity));
|
|
1810
|
+
}
|
|
1730
1811
|
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
|
|
1734
|
-
|
|
1812
|
+
const results = await this._SQLEngine.bulkInsert(preparedModels);
|
|
1813
|
+
|
|
1814
|
+
// Set auto-increment IDs back on the original tracked entities
|
|
1815
|
+
for (let i = 0; i < flatEntities.length; i++) {
|
|
1816
|
+
const entity = flatEntities[i];
|
|
1817
|
+
const result = results[i];
|
|
1818
|
+
|
|
1819
|
+
if (result && result.id) {
|
|
1820
|
+
const primaryKey = tools.getPrimaryKeyObject(entity.__entity);
|
|
1821
|
+
if (entity.__entity[primaryKey]?.auto === true) {
|
|
1822
|
+
entity[primaryKey] = result.id;
|
|
1823
|
+
}
|
|
1735
1824
|
}
|
|
1736
1825
|
}
|
|
1737
|
-
}
|
|
1738
|
-
|
|
1739
|
-
|
|
1740
|
-
|
|
1741
|
-
|
|
1742
|
-
|
|
1743
|
-
|
|
1826
|
+
} catch (error) {
|
|
1827
|
+
console.error('[Context] Bulk insert failed, falling back to individual inserts:', error.message);
|
|
1828
|
+
// Fallback to individual inserts
|
|
1829
|
+
for (const entity of flatEntities) {
|
|
1830
|
+
const insert = new insertManager(this._SQLEngine, this._isModelValid, this.__entities);
|
|
1831
|
+
await insert.init(entity);
|
|
1832
|
+
}
|
|
1744
1833
|
}
|
|
1745
1834
|
}
|
|
1746
1835
|
}
|
package/docs/MIGRATIONS_GUIDE.md
CHANGED
|
@@ -30,7 +30,9 @@ MasterRecord migrations let you:
|
|
|
30
30
|
### 1. Set up your context
|
|
31
31
|
|
|
32
32
|
```javascript
|
|
33
|
-
// app/models/
|
|
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';
|
package/insertManager.js
CHANGED
|
@@ -81,51 +81,74 @@ class InsertManager {
|
|
|
81
81
|
* @throws {InsertManagerError} If validation fails or relationships are invalid
|
|
82
82
|
*/
|
|
83
83
|
async runQueries(currentModel) {
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
84
|
+
const modelEntity = currentModel.__entity;
|
|
85
|
+
|
|
86
|
+
// Build the clean, normalized insert model (applies .set setters, defaults,
|
|
87
|
+
// auto timestamps and resolves belongsTo FKs). Throws if validation fails.
|
|
88
|
+
const cleanCurrentModel = await this.prepareInsertModel(currentModel);
|
|
89
|
+
|
|
90
|
+
const SQL = await this._SQLEngine.insert(cleanCurrentModel);
|
|
91
|
+
const primaryKey = tools.getPrimaryKeyObject(currentModel.__entity);
|
|
92
|
+
|
|
93
|
+
// use returned insert id directly; avoid redundant post-insert SELECT
|
|
94
|
+
if (currentModel.__entity[primaryKey].auto === true) {
|
|
95
|
+
currentModel[primaryKey] = SQL.id;
|
|
88
96
|
}
|
|
89
97
|
|
|
90
|
-
const
|
|
91
|
-
|
|
98
|
+
const proto = Object.getPrototypeOf(currentModel);
|
|
99
|
+
const props = Object.getOwnPropertyNames(proto);
|
|
100
|
+
const cleanPropList = tools.returnEntityList(props, modelEntity);
|
|
101
|
+
const modelKeys = Object.keys(currentModel);
|
|
102
|
+
const mergedArray = [...new Set(modelKeys.concat(cleanPropList))];
|
|
92
103
|
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
// use returned insert id directly; avoid redundant post-insert SELECT
|
|
101
|
-
if (currentModel.__entity[primaryKey].auto === true) {
|
|
102
|
-
currentModel[primaryKey] = SQL.id;
|
|
104
|
+
// loop through model properties
|
|
105
|
+
for (const property of mergedArray) {
|
|
106
|
+
const propertyModel = currentModel[property];
|
|
107
|
+
const entityProperty = modelEntity[property] ? modelEntity[property] : {};
|
|
108
|
+
|
|
109
|
+
if (entityProperty.type === RELATIONSHIP_TYPES.HAS_ONE) {
|
|
110
|
+
await this._processHasOneRelationship(propertyModel, entityProperty, property, currentModel, SQL);
|
|
103
111
|
}
|
|
104
112
|
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
const modelKeys = Object.keys(currentModel);
|
|
109
|
-
const mergedArray = [...new Set(modelKeys.concat(cleanPropList))];
|
|
113
|
+
if (entityProperty.type === RELATIONSHIP_TYPES.HAS_MANY) {
|
|
114
|
+
await this._processArrayRelationship(propertyModel, entityProperty, property, currentModel, SQL, RELATIONSHIP_TYPES.HAS_MANY);
|
|
115
|
+
}
|
|
110
116
|
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
117
|
+
if (entityProperty.type === RELATIONSHIP_TYPES.HAS_MANY_THROUGH) {
|
|
118
|
+
await this._processArrayRelationship(propertyModel, entityProperty, property, currentModel, SQL, RELATIONSHIP_TYPES.HAS_MANY_THROUGH);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
}
|
|
115
122
|
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
123
|
+
/**
|
|
124
|
+
* Prepare a tracked entity for an INSERT *without* executing it.
|
|
125
|
+
*
|
|
126
|
+
* Resets validation state, builds a clean (prototype-free) model, runs the
|
|
127
|
+
* full normalization the single-insert path depends on — legacy .set()
|
|
128
|
+
* setters, default values, auto timestamps — and resolves belongsTo foreign
|
|
129
|
+
* keys. Returns the clean model ready to hand to the engine.
|
|
130
|
+
*
|
|
131
|
+
* Shared by {@link runQueries} (single insert) and the context batch-insert
|
|
132
|
+
* path so both produce byte-for-byte identical column values. Before this was
|
|
133
|
+
* extracted, the batch path bypassed this entirely: a label that a .set() maps
|
|
134
|
+
* to an int reached an INTEGER column as a raw string, the whole batch threw,
|
|
135
|
+
* and it silently fell back to slow per-row inserts.
|
|
136
|
+
*
|
|
137
|
+
* @param {object} currentModel - Tracked entity to insert
|
|
138
|
+
* @returns {Promise<object>} Clean, normalized model for the engine
|
|
139
|
+
* @throws {InsertManagerError} If the entity fails validation
|
|
140
|
+
*/
|
|
141
|
+
async prepareInsertModel(currentModel) {
|
|
142
|
+
// Reset validation state for this operation to avoid stale errors
|
|
143
|
+
if (this._errorModel) {
|
|
144
|
+
this._errorModel.isValid = true;
|
|
145
|
+
this._errorModel.errors = [];
|
|
146
|
+
}
|
|
119
147
|
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
}
|
|
148
|
+
const cleanCurrentModel = tools.clearAllProto(currentModel);
|
|
149
|
+
this.validateEntity(cleanCurrentModel, currentModel, currentModel.__entity);
|
|
123
150
|
|
|
124
|
-
|
|
125
|
-
await this._processArrayRelationship(propertyModel, entityProperty, property, currentModel, SQL, RELATIONSHIP_TYPES.HAS_MANY_THROUGH);
|
|
126
|
-
}
|
|
127
|
-
}
|
|
128
|
-
} else {
|
|
151
|
+
if (!this._errorModel.isValid) {
|
|
129
152
|
const messages = this._errorModel.errors;
|
|
130
153
|
const combinedError = messages.join('; and ');
|
|
131
154
|
throw new InsertManagerError(combinedError, {
|
|
@@ -133,6 +156,10 @@ class InsertManager {
|
|
|
133
156
|
entity: currentModel.__entity ? currentModel.__entity.__name : 'unknown'
|
|
134
157
|
});
|
|
135
158
|
}
|
|
159
|
+
|
|
160
|
+
// TODO: if you try to add belongs to you must have a tag added first. if you dont throw error
|
|
161
|
+
await this.belongsToInsert(currentModel, currentModel.__entity);
|
|
162
|
+
return cleanCurrentModel;
|
|
136
163
|
}
|
|
137
164
|
|
|
138
165
|
/**
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "masterrecord",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.3.0",
|
|
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",
|
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/
|
|
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
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
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/
|
|
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
|
-
"
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
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
|
-
|
|
439
|
-
|
|
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
|
-
|
|
447
|
-
|
|
448
|
-
type: 'string',
|
|
449
|
-
nullable: false
|
|
450
|
-
};
|
|
448
|
+
// Required string field
|
|
449
|
+
name(db) { db.string().notNullable(); }
|
|
451
450
|
|
|
452
|
-
|
|
453
|
-
|
|
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
|
-
|
|
460
|
-
|
|
461
|
-
type: 'string',
|
|
462
|
-
unique: true
|
|
463
|
-
};
|
|
454
|
+
// Unique constraint
|
|
455
|
+
email(db) { db.string().unique(); }
|
|
464
456
|
|
|
465
|
-
|
|
466
|
-
|
|
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
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
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
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
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
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
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
|
-
|
|
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
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
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
|
-
|
|
1579
|
-
|
|
1580
|
-
|
|
1581
|
-
|
|
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
|
-
|
|
1753
|
-
|
|
1754
|
-
|
|
1755
|
-
|
|
1756
|
-
|
|
1757
|
-
|
|
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/
|
|
3070
|
+
import AppContext from './app/models/AppContext.js';
|
|
3114
3071
|
|
|
3115
3072
|
async function demo() {
|
|
3116
3073
|
const db = new AppContext();
|