masterrecord 1.2.9 → 1.2.10

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,17 @@
1
1
  # MasterRecord Changelog
2
2
 
3
+ ## v1.2.10 — batch/single insert parity (.set() setters, defaults, timestamps, relationships)
4
+
5
+ **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.
6
+
7
+ **Fix (engine-agnostic — applies to SQLite/MySQL/Postgres):**
8
+ - `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.
9
+ - 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).
10
+ - 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.
11
+ - The existing fallback-to-per-row-on-error safety net is preserved.
12
+
13
+ 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.
14
+
3
15
  ## v1.2.9 — alterColumn type changes (SQLite rebuild + affinity-aware no-op)
4
16
 
5
17
  **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/context.js CHANGED
@@ -1700,6 +1700,41 @@ class context {
1700
1700
  }
1701
1701
  }
1702
1702
 
1703
+ /**
1704
+ * Detect whether a tracked entity carries child-relationship data
1705
+ * (hasMany / hasOne / hasManyThrough) that was explicitly assigned by the
1706
+ * caller. Such entities can't be expressed as a single flat row, so the
1707
+ * batch-insert path routes them through the full single-insert path (which
1708
+ * inserts the children too) instead of the flat bulk path.
1709
+ *
1710
+ * Only OWN enumerable keys are inspected so we never trigger a lazy
1711
+ * relationship getter (those live on the prototype) — an unset relationship
1712
+ * accessor is correctly treated as "no children".
1713
+ *
1714
+ * @private
1715
+ * @param {object} entity - Tracked entity
1716
+ * @returns {boolean} True if the entity has assigned child-relationship data
1717
+ */
1718
+ _batchEntityHasChildren(entity) {
1719
+ const modelEntity = entity.__entity;
1720
+ if (!modelEntity) {
1721
+ return false;
1722
+ }
1723
+ for (const key of Object.keys(entity)) {
1724
+ const def = modelEntity[key];
1725
+ if (!def) {
1726
+ continue;
1727
+ }
1728
+ if (def.type === 'hasMany' || def.type === 'hasOne' || def.type === 'hasManyThrough') {
1729
+ const value = entity[key];
1730
+ if (value !== undefined && value !== null && typeof value === 'object') {
1731
+ return true;
1732
+ }
1733
+ }
1734
+ }
1735
+ return false;
1736
+ }
1737
+
1703
1738
  /**
1704
1739
  * Process batch insert operations
1705
1740
  *
@@ -1719,28 +1754,67 @@ class context {
1719
1754
  const insert = new insertManager(this._SQLEngine, this._isModelValid, this.__entities);
1720
1755
  await insert.init(entities[0]);
1721
1756
  } else {
1722
- // Batch insert - 100x faster for multiple records
1723
- try {
1724
- const results = await this._SQLEngine.bulkInsert(entities);
1757
+ // Batch insert. Two write paths used to disagree: the single-insert
1758
+ // path runs each entity through insertManager (which applies .set()
1759
+ // setters, default values, auto timestamps, belongsTo FK resolution
1760
+ // and validation), while the batch path handed RAW model values
1761
+ // straight to the engine. So a label that a .set() maps to an int
1762
+ // (e.g. "operator" -> 2) reached an INTEGER column as a string, the
1763
+ // whole batch threw, and it fell back to slow per-row inserts —
1764
+ // defeating the batch optimization. We now run every batched entity
1765
+ // through the SAME normalization pipeline before building the bulk
1766
+ // INSERT, so the fast path produces identical column values.
1767
+ //
1768
+ // Entities carrying child-relationship data (hasMany / hasOne /
1769
+ // hasManyThrough) cannot be expressed as a single flat row, so they
1770
+ // go through the full single-insert path which inserts their children
1771
+ // too — otherwise the flat bulk path would silently drop them.
1772
+ const relationalEntities = [];
1773
+ const flatEntities = [];
1774
+ for (const entity of entities) {
1775
+ if (this._batchEntityHasChildren(entity)) {
1776
+ relationalEntities.push(entity);
1777
+ } else {
1778
+ flatEntities.push(entity);
1779
+ }
1780
+ }
1781
+
1782
+ // Children-bearing entities: full single path (row + children).
1783
+ for (const entity of relationalEntities) {
1784
+ const insert = new insertManager(this._SQLEngine, this._isModelValid, this.__entities);
1785
+ await insert.init(entity);
1786
+ }
1787
+
1788
+ // Flat entities: normalize each, then one fast batched insert.
1789
+ if (flatEntities.length > 0) {
1790
+ try {
1791
+ const manager = new insertManager(this._SQLEngine, this._isModelValid, this.__entities);
1792
+ const preparedModels = [];
1793
+ for (const entity of flatEntities) {
1794
+ preparedModels.push(await manager.prepareInsertModel(entity));
1795
+ }
1725
1796
 
1726
- // Set auto-increment IDs back on entities
1727
- for (let i = 0; i < entities.length; i++) {
1728
- const entity = entities[i];
1729
- const result = results[i];
1797
+ const results = await this._SQLEngine.bulkInsert(preparedModels);
1730
1798
 
1731
- if (result && result.id) {
1732
- const primaryKey = tools.getPrimaryKeyObject(entity.__entity);
1733
- if (entity.__entity[primaryKey]?.auto === true) {
1734
- entity[primaryKey] = result.id;
1799
+ // Set auto-increment IDs back on the original tracked entities
1800
+ for (let i = 0; i < flatEntities.length; i++) {
1801
+ const entity = flatEntities[i];
1802
+ const result = results[i];
1803
+
1804
+ if (result && result.id) {
1805
+ const primaryKey = tools.getPrimaryKeyObject(entity.__entity);
1806
+ if (entity.__entity[primaryKey]?.auto === true) {
1807
+ entity[primaryKey] = result.id;
1808
+ }
1735
1809
  }
1736
1810
  }
1737
- }
1738
- } catch (error) {
1739
- console.error('[Context] Bulk insert failed, falling back to individual inserts:', error.message);
1740
- // Fallback to individual inserts
1741
- for (const entity of entities) {
1742
- const insert = new insertManager(this._SQLEngine, this._isModelValid, this.__entities);
1743
- await insert.init(entity);
1811
+ } catch (error) {
1812
+ console.error('[Context] Bulk insert failed, falling back to individual inserts:', error.message);
1813
+ // Fallback to individual inserts
1814
+ for (const entity of flatEntities) {
1815
+ const insert = new insertManager(this._SQLEngine, this._isModelValid, this.__entities);
1816
+ await insert.init(entity);
1817
+ }
1744
1818
  }
1745
1819
  }
1746
1820
  }
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
- // Reset validation state for this operation to avoid stale errors
85
- if (this._errorModel) {
86
- this._errorModel.isValid = true;
87
- this._errorModel.errors = [];
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 cleanCurrentModel = tools.clearAllProto(currentModel);
91
- this.validateEntity(cleanCurrentModel, currentModel, currentModel.__entity);
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
- if (this._errorModel.isValid) {
94
- const modelEntity = currentModel.__entity;
95
- // TODO: if you try to add belongs to you must have a tag added first. if you dont throw error
96
- currentModel = await this.belongsToInsert(currentModel, modelEntity);
97
- const SQL = await this._SQLEngine.insert(cleanCurrentModel);
98
- const primaryKey = tools.getPrimaryKeyObject(currentModel.__entity);
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
- const proto = Object.getPrototypeOf(currentModel);
106
- const props = Object.getOwnPropertyNames(proto);
107
- const cleanPropList = tools.returnEntityList(props, modelEntity);
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
- // loop through model properties
112
- for (const property of mergedArray) {
113
- const propertyModel = currentModel[property];
114
- const entityProperty = modelEntity[property] ? modelEntity[property] : {};
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
- if (entityProperty.type === RELATIONSHIP_TYPES.HAS_ONE) {
117
- await this._processHasOneRelationship(propertyModel, entityProperty, property, currentModel, SQL);
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
- if (entityProperty.type === RELATIONSHIP_TYPES.HAS_MANY) {
121
- await this._processArrayRelationship(propertyModel, entityProperty, property, currentModel, SQL, RELATIONSHIP_TYPES.HAS_MANY);
122
- }
148
+ const cleanCurrentModel = tools.clearAllProto(currentModel);
149
+ this.validateEntity(cleanCurrentModel, currentModel, currentModel.__entity);
123
150
 
124
- if (entityProperty.type === RELATIONSHIP_TYPES.HAS_MANY_THROUGH) {
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.2.9",
3
+ "version": "1.2.10",
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",