masterrecord 1.1.2 → 1.1.3

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.1.3 — belongsTo FK column setter on both `.new()` and loaded entities
4
+
5
+ **Bug:** `belongsTo('Run')` declares a navigation property `Run` and an implicit FK column `run_id`. Two assignment paths existed but only one worked reliably:
6
+
7
+ | Path | Worked before? | Why |
8
+ | ----------------------------------- | -------------- | --------------------------------------------------- |
9
+ | `step.Run = id` (any entity) | ✅ | Setter installed by relationship-models pass |
10
+ | `step.run_id = id` (new entity) | ⚠️ partial | Value reached INSERT via fallback, but wasn't tracked as dirty |
11
+ | `step.run_id = id` (loaded entity) | ❌ **crash** | Tracker setter dereferenced `__entity['run_id'].set` — undefined → TypeError |
12
+
13
+ The loaded-entity crash forced users into the raw-SQL escape hatch on `context.db` to update FKs.
14
+
15
+ **Fix:**
16
+ - `QueryLanguage/queryMethods.js` `.new()` — for each `belongsTo` field, also install a setter on the FK column name (e.g. `run_id`). Both `step.Run = id` and `step.run_id = id` now produce identical tracked state.
17
+ - `Entity/entityTrackerModel.js` `build()` — when the DB-row iterator builds a setter for a column that has no `__entity` entry (the FK column case), guard the `.set` access and canonicalize the dirty-field name to the navigation property's name so the engine UPDATE/INSERT builders' existing belongsTo path picks it up.
18
+
19
+ Setting the FK column on a loaded entity now correctly emits an UPDATE; setting it on a `.new()` entity correctly marks the field dirty so subsequent saves include it.
20
+
21
+ 3 new tests in `test/belongs-to-fk-setter.test.js` cover the three paths above.
22
+
23
+ ### Known limitation: columns added by a migration after the class is loaded
24
+
25
+ If a migration adds a column but the entity class file isn't reloaded (Node's import cache is process-lifetime), assignments to the new field on `.new()` instances won't be tracked because `__entity` was built from the stale class. There's no fix possible from inside the library — restart the process after editing the model class. As a stopgap, use `context.db` to run raw SQL.
26
+
3
27
  ## v1.1.2 — belongsTo FK type resolution + MySQL/SQLite type-map gaps
4
28
 
5
29
  **Bug:** `belongsTo()` hardcoded the FK column type to `integer` at entity-definition time, before the parent entity was registered. If the parent's PK was `string` / `bigint` / `uuid`, the FK was still emitted as `INTEGER`. SQLite accepted the mismatch silently (dynamic typing); Postgres and MySQL rejected inserts of string IDs into integer columns.
@@ -20,6 +20,18 @@ class EntityTrackerModel {
20
20
  modelClass.__context = context;
21
21
  this.buildRelationshipModels(modelClass, currentEntity, dataModel);
22
22
 
23
+ // Pre-compute belongsTo navName lookup for FK column names that
24
+ // appear in the DB row but not as a top-level key in `__entity`
25
+ // (e.g. row has `run_id`; __entity has `Run` with foreignKey:
26
+ // 'run_id' but no separate `run_id` declaration).
27
+ const fkToNavName = {};
28
+ for (const k of Object.keys(currentEntity)) {
29
+ const def = currentEntity[k];
30
+ if (def && def.relationshipType === 'belongsTo' && def.foreignKey) {
31
+ fkToNavName[def.foreignKey] = k;
32
+ }
33
+ }
34
+
23
35
  // loop through data model fields
24
36
  for (const [modelField, modelFieldValue] of modelFields) {
25
37
 
@@ -108,23 +120,52 @@ class EntityTrackerModel {
108
120
  }
109
121
 
110
122
  modelClass.__state = "modified";
123
+
124
+ // belongsTo FK columns appear in the DB row but not as
125
+ // a top-level key in `__entity` (the entity defines
126
+ // the navigation property `Run` with foreignKey:
127
+ // 'run_id'; there's no separate 'run_id' field). The
128
+ // engine UPDATE/INSERT builders detect belongsTo by
129
+ // looking up __entity[<dirtyField>]; pushing 'run_id'
130
+ // would crash on `__entity['run_id'].type`. Translate
131
+ // the dirty field to the navigation name and mirror
132
+ // the value into both backing fields so existing
133
+ // belongsTo handling (which reads `_<navName>`) and
134
+ // FK-name reads (which read `_<modelField>`) both
135
+ // return the new value.
136
+ const navNameForFk = (!currentEntity[modelField] && fkToNavName[modelField])
137
+ ? fkToNavName[modelField]
138
+ : null;
139
+ const dirtyName = navNameForFk || modelField;
140
+
111
141
  // Deduplicate: setting the same field twice used to push
112
142
  // the name twice, producing duplicate assignments in the
113
143
  // UPDATE SET clause (`SET col = ?, col = ?`) which is a
114
144
  // hard error in Postgres and may silently take-last in
115
145
  // MySQL/SQLite.
116
- if (!modelClass.__dirtyFields.includes(modelField)) {
117
- modelClass.__dirtyFields.push(modelField);
146
+ if (!modelClass.__dirtyFields.includes(dirtyName)) {
147
+ modelClass.__dirtyFields.push(dirtyName);
118
148
  }
119
149
  // ensure this entity is tracked on any modification
120
150
  if(modelClass.__context && typeof modelClass.__context.__track === 'function'){
121
151
  modelClass.__context.__track(modelClass);
122
152
  }
123
- if(typeof currentEntity[modelField].set === "function"){
124
- this["__proto__"]["_" + modelField] = currentEntity[modelField].set(value);
153
+ // Guard against currentEntity[modelField] being
154
+ // undefined (the FK column case described above).
155
+ const fieldDefForSet = currentEntity[modelField];
156
+ let storedValue;
157
+ if(fieldDefForSet && typeof fieldDefForSet.set === "function"){
158
+ storedValue = fieldDefForSet.set(value);
125
159
  }else{
126
- // Then it will add name to dirty fields
127
- this["__proto__"]["_" + modelField] = value;
160
+ storedValue = value;
161
+ }
162
+ this["__proto__"]["_" + modelField] = storedValue;
163
+ if (navNameForFk) {
164
+ // Mirror into the nav-property backing so the
165
+ // engine UPDATE builders (which read
166
+ // `_<dirtyField>` for belongsTo) find the new
167
+ // value.
168
+ this["__proto__"]["_" + navNameForFk] = storedValue;
128
169
  }
129
170
  },
130
171
  get:function(){
@@ -701,6 +701,60 @@ class queryMethods{
701
701
  return this.__proto__["_" + fname];
702
702
  }
703
703
  });
704
+
705
+ // belongsTo declares a navigation property (e.g. `Run`)
706
+ // and an implicit foreign-key column (e.g. `run_id`).
707
+ // The loop above installs a setter for `Run`. Also
708
+ // install one on the FK column name so user code can
709
+ // do `step.run_id = 'xyz'` instead of being forced
710
+ // into `step.Run = 'xyz'`.
711
+ //
712
+ // Both paths must produce identical state: push the
713
+ // *navigation* name to `__dirtyFields` and store the
714
+ // value at `_<navName>`. The engine INSERT/UPDATE
715
+ // builders detect belongsTo by looking up that name
716
+ // in `__entity`; if we pushed the FK column name
717
+ // instead, the builder would crash on
718
+ // `__entity['run_id']` (no such key) when computing
719
+ // the SQL column type.
720
+ if (fieldDef && fieldDef.relationshipType === 'belongsTo' && fieldDef.foreignKey) {
721
+ const fkName = fieldDef.foreignKey;
722
+ const navName = fname;
723
+ // Don't clobber an explicit column declaration:
724
+ // some entities declare `run_id(db) { db.string() }`
725
+ // alongside `Run(db) { db.belongsTo('Run') }`. If
726
+ // that's the case, the explicit setter has already
727
+ // been installed by this loop on its own iteration.
728
+ if (!Object.prototype.hasOwnProperty.call(newEntity, fkName)) {
729
+ Object.defineProperty(newEntity, fkName, {
730
+ enumerable: true,
731
+ configurable: true,
732
+ set: function(value) {
733
+ this.__proto__["_" + navName] = value;
734
+ if (!this.__dirtyFields.includes(navName)) {
735
+ this.__dirtyFields.push(navName);
736
+ }
737
+ if (this.__state === 'track') {
738
+ this.__state = 'modified';
739
+ }
740
+ if (this.__context && typeof this.__context.__track === 'function') {
741
+ this.__context.__track(this);
742
+ }
743
+ },
744
+ get: function() {
745
+ // Prefer the nav-property backing
746
+ // (most recently assigned). Fall back
747
+ // to the FK-column backing populated
748
+ // by DB hydration in
749
+ // entityTrackerModel.build().
750
+ const navVal = this.__proto__["_" + navName];
751
+ return navVal !== undefined
752
+ ? navVal
753
+ : this.__proto__["_" + fkName];
754
+ }
755
+ });
756
+ }
757
+ }
704
758
  })(fieldName, field);
705
759
  }
706
760
  }
@@ -268,3 +268,41 @@ console.log(user.Auth.password_hash); // Wrong! This is navigation property
268
268
  - **Add debug logging** to catch Promise objects being treated as entities
269
269
 
270
270
  This pattern is consistent throughout MasterRecord and applies to all relationship types: `hasOne`, `hasMany`, `belongsTo`, and `hasManyThrough`.
271
+
272
+ ---
273
+
274
+ ## "Cannot read properties of undefined (reading 'set')" on FK assignment
275
+
276
+ If you see this error setting a foreign-key column on a loaded entity:
277
+
278
+ ```javascript
279
+ const step = await ctx.Step.findById(1);
280
+ step.run_id = 'run_beta'; // ← TypeError before v1.1.3
281
+ await step.save();
282
+ ```
283
+
284
+ **Cause:** before v1.1.3, the entity tracker's setter dereferenced `__entity['run_id'].set` without a null guard. The `belongsTo('Run')` definition only registers the navigation property `Run` (with `foreignKey: 'run_id'`) — there is no `run_id` field on `__entity`, so `__entity['run_id']` is `undefined` and accessing `.set` on it threw.
285
+
286
+ **Fix:** upgrade to **v1.1.3 or later**. Both `step.Run = id` and `step.run_id = id` are now safe and produce identical persisted state.
287
+
288
+ If you can't upgrade, the workaround is to use the navigation property: `step.Run = id`, or to drop to raw SQL via `ctx.db`.
289
+
290
+ ---
291
+
292
+ ## A column added by migration isn't seen by `.new()` until I restart Node
293
+
294
+ If you add a column via a migration, update the entity class to declare it, and assignments to the new field still don't track:
295
+
296
+ ```javascript
297
+ // 1. Migration adds `step.created_at`
298
+ // 2. You add `created_at(db) { db.string(); }` to Step.js
299
+ // 3. Without restarting Node:
300
+ const step = ctx.Step.new();
301
+ step.created_at = String(Date.now()); // ← stored as a plain JS prop, INSERT misses it
302
+ ```
303
+
304
+ **Cause:** Node ESM module cache is process-lifetime. The context built `__entity` from the Step class *as it was when the process started*. Editing Step.js doesn't update the in-memory class — and therefore doesn't update `__entity`.
305
+
306
+ **Fix:** restart the Node process. There is no library-level fix; this is how Node module loading works.
307
+
308
+ Until restart, the workaround is to set the field via raw SQL through `ctx.db` (e.g. `ctx.db.prepare('INSERT INTO Step (...) VALUES (...)').run(...)`) — or, for fields that exist in the DB but not the class definition, lazy-load the entity (which iterates the DB row's actual columns and creates setters for them on the instance, even if the class doesn't declare them).
@@ -41,18 +41,23 @@ console.log(chunk.Document); // Accesses the relationship (object or ID)
41
41
 
42
42
  ### Pattern 1: INSERT Operations (Setting Foreign Keys)
43
43
 
44
- When **creating new records**, use the **relationship property name**:
44
+ Both the relationship property name and the foreign-key column name work (since **v1.1.3** — before that, only the relationship property reliably tracked the assignment).
45
45
 
46
46
  ```javascript
47
- const chunk = new DocumentChunk();
47
+ // Option A — relationship property name (always worked)
48
+ const chunk = context.DocumentChunk.new();
48
49
  chunk.content = "Sample content";
49
- chunk.Document = documentId; // ✅ CORRECT - Use relationship property for INSERT
50
+ chunk.Document = documentId;
51
+ await chunk.save();
50
52
 
51
- context.DocumentChunk.add(chunk);
52
- context.saveChanges();
53
+ // Option B — foreign-key column name (fixed in v1.1.3)
54
+ const chunk = context.DocumentChunk.new();
55
+ chunk.content = "Sample content";
56
+ chunk.document_id = documentId;
57
+ await chunk.save();
53
58
  ```
54
59
 
55
- **Why?** The `belongsTo` setter (entityTrackerModel.js:98-105) triggers dirty field tracking and marks the model as modified when you set the relationship property.
60
+ Both paths produce identical state internally — the FK setter aliases to the relationship property's tracking. Pick whichever feels more natural for your call site. Useful when you only have the ID handy and don't want the noise of "set the relationship property" semantics for what is effectively a scalar assignment.
56
61
 
57
62
  ### Pattern 2: READ Operations (Accessing Foreign Keys)
58
63
 
@@ -77,19 +82,17 @@ if (chunk.document_id === targetId) {
77
82
 
78
83
  ### Pattern 3: UPDATE Operations
79
84
 
80
- For updates, you can use either property:
85
+ For updates, both properties are equivalent (since **v1.1.3**):
81
86
 
82
87
  ```javascript
83
- // Using relationship property (preferred for consistency)
88
+ // Using relationship property
84
89
  chunk.Document = newDocumentId;
85
90
 
86
- // Using foreign key directly (also works)
91
+ // Using foreign key directly
87
92
  chunk.document_id = newDocumentId;
88
93
  ```
89
94
 
90
- Both will work because:
91
- - Setting `chunk.Document` triggers the relationship setter (line 98-105)
92
- - Setting `chunk.document_id` directly modifies the underlying value
95
+ Both push the same canonical name (`Document`) to `__dirtyFields` and store the value where the engine UPDATE builders read it. Before v1.1.3, `chunk.document_id = newDocumentId` on a loaded entity crashed with `Cannot read properties of undefined (reading 'set')` because the tracker's setter dereferenced `__entity['document_id'].set` — and `__entity` only has the relationship property `Document`, not a separate `document_id` field. That forced users into the `context.db` raw-SQL escape hatch for UPDATE-by-FK.
93
96
 
94
97
  ## Code References
95
98
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "masterrecord",
3
- "version": "1.1.2",
3
+ "version": "1.1.3",
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",
@@ -0,0 +1,154 @@
1
+ /**
2
+ * belongsTo FK column setter on `.new()` entities.
3
+ *
4
+ * Bug: `belongsTo('Run')` declares a navigation property `Run` and an
5
+ * implicit foreign-key column `run_id`. `.new()` walks the entity
6
+ * definition and creates a setter for `Run`, but NOT for `run_id` (the
7
+ * FK column doesn't appear as a top-level field in `__entity`).
8
+ *
9
+ * Effect: `step.run_id = 'run_xyz'` lands as a plain JS property — the
10
+ * tracker never sees it, the INSERT builder never picks it up, the row
11
+ * goes in without the FK. Users were forced to either use the
12
+ * navigation setter (`step.Run = id`) or drop to raw SQL.
13
+ *
14
+ * Fix: when defining `.new()` setters, for each `belongsTo` column,
15
+ * also define a setter on the foreignKey field name that stores the
16
+ * value and marks the FK as dirty.
17
+ */
18
+
19
+ import { test } from 'node:test';
20
+ import assert from 'node:assert/strict';
21
+ import fs from 'node:fs';
22
+ import path from 'node:path';
23
+ import { fileURLToPath } from 'node:url';
24
+
25
+ process.env.master = 'fk-setter';
26
+
27
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
28
+ const fixturesDir = path.join(__dirname, 'fixtures', 'belongs-to-fk-setter');
29
+ const envDir = path.join(fixturesDir, 'config', 'environments');
30
+ const dbDir = path.join(fixturesDir, 'db');
31
+ fs.mkdirSync(envDir, { recursive: true });
32
+ fs.mkdirSync(dbDir, { recursive: true });
33
+
34
+ fs.writeFileSync(
35
+ path.join(envDir, 'env.fk-setter.json'),
36
+ JSON.stringify({
37
+ FkSetterCtx: { type: 'better-sqlite3', connection: dbDir + path.sep },
38
+ })
39
+ );
40
+
41
+ const { default: context } = await import('../context.js');
42
+
43
+ class Run {
44
+ id(db) { db.string().primary(); }
45
+ name(db) { db.string(); }
46
+ }
47
+
48
+ class Step {
49
+ id(db) { db.integer().primary().auto(); }
50
+ name(db) { db.string(); }
51
+ Run(db) { db.belongsTo('Run').notNullable(); }
52
+ }
53
+
54
+ class FkSetterCtx extends context {
55
+ constructor() {
56
+ super();
57
+ this.env(envDir);
58
+ this.dbset(Run);
59
+ this.dbset(Step);
60
+ }
61
+ }
62
+
63
+ test('.new() entity has a setter for the belongsTo foreignKey column', () => {
64
+ const ctx = new FkSetterCtx();
65
+ const step = ctx.Step.new();
66
+
67
+ // The navigation property setter has always worked
68
+ step.Run = 'run_abc';
69
+ assert.equal(step.Run, 'run_abc');
70
+
71
+ // The FK column setter is what was broken
72
+ step.run_id = 'run_xyz';
73
+ assert.equal(step.run_id, 'run_xyz', 'run_id should be readable');
74
+ // The assignment must be tracked. Internally we canonicalize to the
75
+ // navigation-property name ('Run') so the engine UPDATE/INSERT
76
+ // builders' existing belongsTo handling picks it up. Either name in
77
+ // __dirtyFields is acceptable; what matters is that the entity is
78
+ // marked as having a pending change.
79
+ const dirtyHas = step.__dirtyFields.includes('Run') ||
80
+ step.__dirtyFields.includes('run_id');
81
+ assert.ok(
82
+ dirtyHas,
83
+ `FK assignment must be marked dirty, got: ${JSON.stringify(step.__dirtyFields)}`
84
+ );
85
+ });
86
+
87
+ test('loaded entity allows reassigning run_id and persists the UPDATE', async () => {
88
+ const ctx = new FkSetterCtx();
89
+ ctx._SQLEngine.db.exec(`
90
+ CREATE TABLE IF NOT EXISTS Run (
91
+ id TEXT PRIMARY KEY,
92
+ name TEXT
93
+ );
94
+ CREATE TABLE IF NOT EXISTS Step (
95
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
96
+ name TEXT,
97
+ run_id TEXT NOT NULL
98
+ );
99
+ DELETE FROM Step;
100
+ DELETE FROM Run;
101
+ INSERT INTO Run (id, name) VALUES ('run_alpha', 'first');
102
+ INSERT INTO Run (id, name) VALUES ('run_beta', 'second');
103
+ INSERT INTO Step (id, name, run_id) VALUES (1, 'step 1', 'run_alpha');
104
+ `);
105
+
106
+ const step = await ctx.Step.where(s => s.id == $$, 1).single();
107
+ assert.equal(step.run_id, 'run_alpha', 'loaded step has the FK');
108
+
109
+ // Reassign the FK. Pre-fix this throws because the tracker setter
110
+ // does `currentEntity[modelField].set` without a null guard — and
111
+ // currentEntity has no 'run_id' key (only 'Run' with foreignKey).
112
+ step.run_id = 'run_beta';
113
+ assert.equal(step.run_id, 'run_beta');
114
+ const dirtyHas = step.__dirtyFields.includes('Run') ||
115
+ step.__dirtyFields.includes('run_id');
116
+ assert.ok(dirtyHas, `dirty fields: ${JSON.stringify(step.__dirtyFields)}`);
117
+
118
+ await ctx.saveChanges();
119
+
120
+ const after = ctx._SQLEngine.db.prepare('SELECT run_id FROM Step WHERE id = 1').get();
121
+ assert.equal(after.run_id, 'run_beta');
122
+
123
+ await ctx.close();
124
+ });
125
+
126
+ test('.new() then setting run_id ends up in SQLite INSERT', async () => {
127
+ const ctx = new FkSetterCtx();
128
+ ctx._SQLEngine.db.exec(`
129
+ CREATE TABLE IF NOT EXISTS Run (
130
+ id TEXT PRIMARY KEY,
131
+ name TEXT
132
+ );
133
+ CREATE TABLE IF NOT EXISTS Step (
134
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
135
+ name TEXT,
136
+ run_id TEXT NOT NULL
137
+ );
138
+ DELETE FROM Step;
139
+ DELETE FROM Run;
140
+ INSERT INTO Run (id, name) VALUES ('run_abc', 'first');
141
+ `);
142
+
143
+ const step = ctx.Step.new();
144
+ step.name = 'step 1';
145
+ step.run_id = 'run_abc'; // ← this is the case the bug forbade
146
+ await ctx.saveChanges();
147
+
148
+ const rows = ctx._SQLEngine.db.prepare('SELECT * FROM Step').all();
149
+ assert.equal(rows.length, 1);
150
+ assert.equal(rows[0].run_id, 'run_abc');
151
+ assert.equal(rows[0].name, 'step 1');
152
+
153
+ await ctx.close();
154
+ });