masterrecord 1.2.8 → 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,29 @@
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
+
15
+ ## v1.2.9 — alterColumn type changes (SQLite rebuild + affinity-aware no-op)
16
+
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.
18
+
19
+ **Fix:**
20
+ - **SQLite** `alterColumn` now reconciles the table to its entity definition via `syncTable`'s proven rebuild (rename → recreate with the new schema → copy common columns → drop old). It is a **no-op when the type is unchanged at SQLite's affinity level** (`string→text`, `int→bigint`), and performs a **data-preserving rebuild on a real change** (e.g. `integer→text`).
21
+ - **`needRebuildSQLite`** now compares the **resolved SQLite affinity** of the desired vs existing column type, catching *any* real type change. The previous check hardcoded only boolean/string/integer and missed most.
22
+ - **MySQL** (`MODIFY COLUMN`) and **Postgres** (`ALTER COLUMN … TYPE`) keep their native type-change DDL — verified to emit correct SQL.
23
+ - `alterColumn` now `await this._ensureReady()` (parity with the other schema methods) and throws a clear error if the entity schema can't be resolved on SQLite (instead of emitting broken DDL).
24
+
25
+ New test: `test/alter-column-type.test.js` — SQLite `string→text` no-op (data intact), SQLite `integer→text` rebuild (column becomes TEXT, rows preserved), and MySQL/Postgres SQL output. Verified executing on SQLite; MySQL/Postgres via SQL-string assertions (no live servers here). Full suite 613/613, 0 lint errors.
26
+
3
27
  ## v1.2.8 — batched-insert auto-increment PK handling
4
28
 
5
29
  **Bug:** the batched-insert path could fail with `Type mismatch for <Entity>.id: Expected integer, got function` for an unset auto-increment primary key, then fall back to individual inserts (which handled it). The INSERT builder (`_buildSQLInsertObjectParameterized`, shared by single + batch inserts) only skipped the auto-PK when its value was `undefined`/`null`. When the unset PK surfaced as its **schema-definition function** (`id(db){…}`, e.g. when the row is a class instance rather than a `.new()` data instance), the builder fell through to the type validator and threw.
@@ -67,6 +67,14 @@ class migrationSQLiteQuery {
67
67
  return `${colName} ${type}${nullName}${defaultClause}${unique}${primaryKey}${auto}`;
68
68
  }
69
69
 
70
+ // Public accessor for the resolved SQLite column type (affinity) of a
71
+ // masterrecord type. Used by schema.syncTable to decide whether a column's
72
+ // type actually changes at SQLite's affinity level — e.g. string and text
73
+ // both resolve to TEXT, so string -> text is a no-op (no rebuild needed).
74
+ resolveColumnType(type){
75
+ return this.#typeManager(type);
76
+ }
77
+
70
78
  #typeManager(type){
71
79
  switch(type) {
72
80
  case "string":
@@ -454,6 +454,7 @@ class schema{
454
454
 
455
455
  const needRebuildSQLite = () => {
456
456
  if(!this.context.isSQLite) return false;
457
+ const sqliteBuilder = new sqliteQuery();
457
458
  const byName = {};
458
459
  for(const row of existing){ byName[row.name] = row; }
459
460
  for(const d of desiredCols){
@@ -461,8 +462,6 @@ class schema{
461
462
  if(!row) continue;
462
463
  const notnull = row.notnull === 1;
463
464
  const desiredNotNull = d.col.nullable === false;
464
- const desiredType = d.col.type;
465
- const existingType = (row.type || '').toLowerCase();
466
465
  // compare default (normalize quotes)
467
466
  const exDefRaw = row.dflt_value == null ? null : String(row.dflt_value);
468
467
  let exDef = exDefRaw;
@@ -472,10 +471,16 @@ class schema{
472
471
  const dsDef = d.col.default == null ? null : String(d.col.default);
473
472
  if(desiredNotNull !== notnull) return true;
474
473
  if(exDef !== dsDef) return true;
475
- // rough type differences that require rebuild
476
- if((desiredType === 'boolean' && existingType !== 'integer') ||
477
- (desiredType === 'string' && existingType !== 'text') ||
478
- (desiredType === 'integer' && existingType !== 'integer')){
474
+ // Type change at SQLite's AFFINITY level. Compare the resolved
475
+ // SQLite type of the desired column to the existing column's
476
+ // declared type. This catches ANY real change (integer->text,
477
+ // float->text, …) — the previous hardcoded boolean/string/
478
+ // integer checks missed most — while treating same-affinity
479
+ // changes (string->text, both TEXT; int->bigint, both INTEGER)
480
+ // as a no-op so we don't rebuild unnecessarily.
481
+ const desiredResolved = sqliteBuilder.resolveColumnType(d.col.type).toUpperCase();
482
+ const existingResolved = String(row.type || '').toUpperCase();
483
+ if(existingResolved && desiredResolved !== existingResolved){
479
484
  return true;
480
485
  }
481
486
  }
@@ -582,16 +587,28 @@ class schema{
582
587
 
583
588
  //"dbo.People", "Location"
584
589
  async alterColumn(table){
590
+ await this._ensureReady();
585
591
  if(table){
586
592
  if(this.fullTable){
587
593
  if(this.context.isSQLite){
588
- var queryBuilder = new sqliteQuery();
589
- const tableSchema = (this._tableObj && this._tableObj[table.tableName]) || this.fullTable.new;
590
- const queryObj = queryBuilder.alterColumn(tableSchema, table);
591
- for (const key in queryObj) {
592
- var query = queryObj[key];
593
- await this.context._execute(query);
594
+ // SQLite has no ALTER/MODIFY COLUMN — a type change needs a
595
+ // full table rebuild (rename → recreate with new schema →
596
+ // copy common columns → drop old). Reconcile the table to
597
+ // its entity definition via syncTable, which performs that
598
+ // rebuild and is a no-op when the type is unchanged at
599
+ // SQLite's affinity level (e.g. string -> text, both TEXT).
600
+ // (The previous builder.alterColumn path emitted invalid
601
+ // SQL — "near )" — when handed an empty/missing schema.)
602
+ const entity = (this.context.__entities || []).find(e => e && e.__name === table.tableName)
603
+ || (this._tableObj && this._tableObj[table.tableName])
604
+ || (this.fullTable && this.fullTable[table.tableName]);
605
+ if (!entity || !entity.__name) {
606
+ throw new Error(
607
+ `masterrecord: alterColumn could not resolve the full schema for table '${table.tableName}' ` +
608
+ `to rebuild it on SQLite. Ensure the context registers this entity (dbset).`
609
+ );
594
610
  }
611
+ await this.syncTable(entity);
595
612
  }
596
613
 
597
614
  if(this.context.isMySQL){
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.8",
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",