masterrecord 1.1.1 → 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,49 @@
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
+
27
+ ## v1.1.2 — belongsTo FK type resolution + MySQL/SQLite type-map gaps
28
+
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.
30
+
31
+ **Fix:** after every `dbset()` call, walk every registered entity and re-resolve each `belongsTo` column's `type` from its parent's primary-key type. Order-independent (works whether parent or child is registered first), idempotent (running multiple times produces the same result), case-insensitive on the `foreignTable` lookup.
32
+
33
+ | Parent PK type | SQLite FK | MySQL FK | Postgres FK |
34
+ | -------------- | --------- | ------------ | ----------- |
35
+ | `string` | TEXT | VARCHAR(255) | VARCHAR(255) |
36
+ | `integer` | INTEGER | INTEGER | INTEGER |
37
+ | `bigint` | INTEGER | BIGINT | BIGINT |
38
+ | `uuid` | TEXT | VARCHAR(36) | UUID |
39
+
40
+ **Related cleanup in the migration type maps:**
41
+
42
+ - **MySQL** `typeManager` now handles `bigint`, `uuid`, `int`, `jsonb`, and falls back to `TEXT` for unknown types. Previously these emitted literal `undefined` into the DDL string (e.g. `` `run_id` undefined NOT NULL ``).
43
+ - **SQLite** `typeManager` now handles `bigint`, `uuid`, `int`, `float`, `decimal`, `binary`/`blob`, `json`/`jsonb`, `date`/`datetime`/`timestamp` explicitly (collapsing to the appropriate SQLite affinity). Same `TEXT` fallback as before.
44
+
45
+ 17 new tests cover the resolver across all four PK types, both `dbset()` orders, and every engine's emitted DDL.
46
+
3
47
  ## v1.1.1 — Documentation
4
48
 
5
49
  - Documented the v1.1.0 full-text search feature: new [`docs/FULL_TEXT_SEARCH.md`](docs/FULL_TEXT_SEARCH.md), README section, and `.search()` entry in [`docs/METHODS_REFERENCE.md`](docs/METHODS_REFERENCE.md).
@@ -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(){
@@ -89,52 +89,46 @@ class migrationMySQLQuery {
89
89
  switch(type) {
90
90
  case "string":
91
91
  return "VARCHAR(255)"
92
- break;
93
92
  case "text":
94
93
  return "TEXT"
95
- break;
96
94
  case "mediumtext":
97
95
  return "MEDIUMTEXT"
98
- break;
99
96
  case "longtext":
100
97
  return "LONGTEXT"
101
- break;
102
98
  case "float":
103
- return "fLOAT(24)"
104
- break;
99
+ return "FLOAT(24)"
105
100
  case "decimal":
106
101
  return "DECIMAL"
107
- break;
108
102
  case "datetime":
109
103
  return "DATETIME"
110
- break;
111
104
  case "timestamp":
112
105
  return "TIMESTAMP"
113
- break;
114
106
  case "date":
115
107
  return "DATE"
116
- break;
117
108
  case "time":
118
109
  return "TIME"
119
- break;
120
110
  case "boolean":
121
111
  return "TINYINT"
122
- break;
123
112
  case "integer":
113
+ case "int":
124
114
  return "INTEGER"
125
- break;
115
+ case "bigint":
116
+ return "BIGINT"
117
+ case "uuid":
118
+ // MySQL has no native UUID type; store as fixed-length string.
119
+ return "VARCHAR(36)"
126
120
  case "binary":
127
- return "BLOB"
128
- break;
129
121
  case "blob":
130
122
  return "BLOB"
131
- break;
132
123
  case "json":
124
+ case "jsonb":
133
125
  return "JSON"
134
- break;
135
- }
136
- // :string, :text, :integer, :float, :decimal, :datetime, :timestamp, :time, :date, :binary, :boolean
137
- }
126
+ default:
127
+ // Fallback so we never emit `undefined` for an unknown type
128
+ // (matches SQLite's and Postgres's lenient behavior).
129
+ return "TEXT"
130
+ }
131
+ }
138
132
 
139
133
  // table is the altered field
140
134
  alterColumn( table){
@@ -70,26 +70,32 @@ class migrationSQLiteQuery {
70
70
  #typeManager(type){
71
71
  switch(type) {
72
72
  case "string":
73
- return "TEXT"
74
- break;
75
73
  case "text":
76
74
  case "mediumtext":
77
75
  case "longtext":
78
- // SQLite TEXT is unlimited — MEDIUMTEXT/LONGTEXT collapse to TEXT
79
- // for cross-engine portability. (Previously "text" had no case
80
- // here at all, which produced "<colname> undefined NOT NULL"
81
- // SQL — accepted by SQLite's lax type affinity but still wrong.)
76
+ case "uuid":
77
+ // SQLite TEXT is unlimited; MEDIUMTEXT/LONGTEXT/UUID collapse to
78
+ // TEXT for cross-engine portability.
82
79
  return "TEXT"
83
- break;
84
80
  case "time":
81
+ case "date":
82
+ case "datetime":
83
+ case "timestamp":
85
84
  return "TEXT"
86
- break;
87
85
  case "boolean":
88
- return "INTEGER"
89
- break;
90
86
  case "integer":
87
+ case "int":
88
+ case "bigint":
91
89
  return "INTEGER"
92
- break;
90
+ case "float":
91
+ case "decimal":
92
+ return "REAL"
93
+ case "binary":
94
+ case "blob":
95
+ return "BLOB"
96
+ case "json":
97
+ case "jsonb":
98
+ return "TEXT"
93
99
  default:
94
100
  // Fallback for unknown types so we never emit `undefined`.
95
101
  return "TEXT"
@@ -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
  }
package/context.js CHANGED
@@ -1299,12 +1299,60 @@ class context {
1299
1299
  enumerable: true
1300
1300
  });
1301
1301
 
1302
+ // belongsTo() hardcodes type='integer' before the parent entity is known.
1303
+ // Now that another entity is registered, re-resolve every belongsTo FK
1304
+ // column's type from its parent's primary-key type. Idempotent.
1305
+ this.#resolveBelongsToTypes();
1306
+
1302
1307
  // Return chainable object with seed() method
1303
1308
  return {
1304
1309
  seed: (data) => this.#addSeedData(tableName, data)
1305
1310
  };
1306
1311
  }
1307
1312
 
1313
+ // Walk every registered entity. For each column with relationshipType ===
1314
+ // 'belongsTo', look up the parent entity by foreignTable name and copy the
1315
+ // parent's primary-key type onto the FK column. Without this, FKs to a
1316
+ // string/uuid/bigint PK end up declared INTEGER, which SQLite tolerates
1317
+ // (dynamic typing) but Postgres and MySQL reject.
1318
+ #resolveBelongsToTypes() {
1319
+ const entities = this.__entities;
1320
+ if (!entities || entities.length === 0) return;
1321
+
1322
+ // Case-insensitive lookup table — users may write
1323
+ // db.belongsTo('run') while the class is `Run`.
1324
+ const byName = {};
1325
+ for (const e of entities) {
1326
+ if (e && e.__name) {
1327
+ byName[e.__name.toLowerCase()] = e;
1328
+ }
1329
+ }
1330
+
1331
+ for (const entity of entities) {
1332
+ for (const key of Object.keys(entity)) {
1333
+ const col = entity[key];
1334
+ if (!col || typeof col !== 'object') continue;
1335
+ if (col.relationshipType !== 'belongsTo') continue;
1336
+ if (!col.foreignTable) continue;
1337
+
1338
+ const parent = byName[String(col.foreignTable).toLowerCase()];
1339
+ if (!parent) continue;
1340
+
1341
+ // Find the parent's primary-key column.
1342
+ for (const pKey of Object.keys(parent)) {
1343
+ const pCol = parent[pKey];
1344
+ if (!pCol || typeof pCol !== 'object') continue;
1345
+ if (pCol.primary === true && pCol.type) {
1346
+ if (col.type !== pCol.type) {
1347
+ col.type = pCol.type;
1348
+ }
1349
+ break;
1350
+ }
1351
+ }
1352
+ }
1353
+ }
1354
+ }
1355
+
1308
1356
  /**
1309
1357
  * Define a composite index on an entity (Option C - Context-level)
1310
1358
  * @param {Function|string} model - Entity class or table name
@@ -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
 
@@ -172,6 +175,35 @@ Even though `chat_id` is never explicitly defined as a field, it's accessible be
172
175
  2. `entityTrackerModel.build()` creates properties for all columns from the result
173
176
  3. The `belongsTo` relationship doesn't prevent the foreign key from being accessible
174
177
 
178
+ ## Foreign Key Column Type
179
+
180
+ > Behavior since **v1.1.2**.
181
+
182
+ The foreign-key column's SQL type is **automatically resolved from the parent entity's primary-key type**. You do not declare a type on the FK; it inherits from the parent.
183
+
184
+ ```javascript
185
+ class Run {
186
+ id(db) { db.string().primary(); } // PK is VARCHAR(255)
187
+ name(db) { db.string(); }
188
+ }
189
+
190
+ class Step {
191
+ id(db) { db.integer().primary().auto(); }
192
+ Run(db) { db.belongsTo('Run').notNullable(); } // run_id is VARCHAR(255), not INTEGER
193
+ }
194
+ ```
195
+
196
+ This matters across engines:
197
+
198
+ | Parent PK type | SQLite `run_id` | MySQL `run_id` | Postgres `run_id` |
199
+ | -------------- | --------------- | ----------------- | ----------------- |
200
+ | `string` | TEXT | VARCHAR(255) | VARCHAR(255) |
201
+ | `integer` | INTEGER | INTEGER | INTEGER |
202
+ | `bigint` | INTEGER | BIGINT | BIGINT |
203
+ | `uuid` | TEXT | VARCHAR(36) | UUID |
204
+
205
+ Before v1.1.2, every belongsTo FK was declared INTEGER regardless of the parent's PK type. SQLite tolerated the mismatch (dynamic typing), but Postgres and MySQL rejected inserts of string IDs into INTEGER columns. The resolver is order-independent: register child and parent entities in either order via `dbset()`.
206
+
175
207
  ## Summary
176
208
 
177
209
  | Operation | Property to Use | Example |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "masterrecord",
3
- "version": "1.1.1",
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
+ });
@@ -0,0 +1,253 @@
1
+ /**
2
+ * belongsTo FK type resolution (1.1.2).
3
+ *
4
+ * Bug: belongsTo() hardcoded type='integer' on the FK column at entity-
5
+ * definition time, before the parent entity was known. If the parent's PK
6
+ * was string/bigint/uuid, the FK column was still declared INTEGER. SQLite
7
+ * accepted the mismatch (dynamic typing); Postgres and MySQL rejected it.
8
+ *
9
+ * Fix: after each dbset() call, walk every entity and re-resolve every
10
+ * belongsTo column's `type` from its parent's primary-key type. Order-
11
+ * independent, idempotent.
12
+ *
13
+ * Notes for future maintenance:
14
+ * - EntityModelBuilder only sees own-prototype methods. Test entity classes
15
+ * must declare their fields directly (no `extends`) or the build silently
16
+ * produces an empty entity with no PK and the resolver has nothing to copy.
17
+ * - bigint/uuid go through EntityModel.type('bigint') because EntityModel
18
+ * doesn't have dedicated bigint()/uuid() field-setter methods.
19
+ */
20
+
21
+ import { test } from 'node:test';
22
+ import assert from 'node:assert/strict';
23
+ import fs from 'node:fs';
24
+ import path from 'node:path';
25
+ import { fileURLToPath } from 'node:url';
26
+
27
+ process.env.master = 'fktypes';
28
+
29
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
30
+ const fixturesDir = path.join(__dirname, 'fixtures', 'belongs-to-fk-type');
31
+ const envDir = path.join(fixturesDir, 'config', 'environments');
32
+ const dbDir = path.join(fixturesDir, 'db');
33
+ fs.mkdirSync(envDir, { recursive: true });
34
+ fs.mkdirSync(dbDir, { recursive: true });
35
+
36
+ fs.writeFileSync(
37
+ path.join(envDir, 'env.fktypes.json'),
38
+ JSON.stringify({
39
+ StringPkCtx: { type: 'better-sqlite3', connection: dbDir + path.sep },
40
+ IntPkCtx: { type: 'better-sqlite3', connection: dbDir + path.sep },
41
+ OutOfOrderCtx: { type: 'better-sqlite3', connection: dbDir + path.sep },
42
+ BigintPkCtx: { type: 'better-sqlite3', connection: dbDir + path.sep },
43
+ UuidPkCtx: { type: 'better-sqlite3', connection: dbDir + path.sep },
44
+ })
45
+ );
46
+
47
+ const { default: context } = await import('../context.js');
48
+ const { default: SQLiteQuery } = await import('../Migrations/migrationSQLiteQuery.js');
49
+ const { default: MySQLQuery } = await import('../Migrations/migrationMySQLQuery.js');
50
+ const { default: PostgresQuery } = await import('../Migrations/migrationPostgresQuery.js');
51
+
52
+ // =====================================================================
53
+ // Resolver behavior (per parent PK type)
54
+ // =====================================================================
55
+
56
+ test('belongsTo FK type resolves from string PK on parent', () => {
57
+ class Run {
58
+ id(db) { db.string().primary(); }
59
+ name(db) { db.string(); }
60
+ }
61
+ class Step {
62
+ id(db) { db.integer().primary().auto(); }
63
+ name(db) { db.string(); }
64
+ Run(db) { db.belongsTo('Run').notNullable(); }
65
+ }
66
+ class StringPkCtx extends context {
67
+ constructor() {
68
+ super();
69
+ this.env(envDir);
70
+ this.dbset(Run);
71
+ this.dbset(Step);
72
+ }
73
+ }
74
+ const ctx = new StringPkCtx();
75
+ const stepEntity = ctx.__entities.find(e => e.__name === 'Step');
76
+ const fk = stepEntity.Run;
77
+ assert.equal(fk.relationshipType, 'belongsTo');
78
+ assert.equal(fk.foreignKey, 'run_id');
79
+ assert.equal(fk.type, 'string', 'FK type should match parent string PK');
80
+ });
81
+
82
+ test('belongsTo FK type stays integer when parent PK is integer', () => {
83
+ class Run {
84
+ id(db) { db.integer().primary().auto(); }
85
+ name(db) { db.string(); }
86
+ }
87
+ class Step {
88
+ id(db) { db.integer().primary().auto(); }
89
+ Run(db) { db.belongsTo('Run').notNullable(); }
90
+ }
91
+ class IntPkCtx extends context {
92
+ constructor() {
93
+ super();
94
+ this.env(envDir);
95
+ this.dbset(Run);
96
+ this.dbset(Step);
97
+ }
98
+ }
99
+ const ctx = new IntPkCtx();
100
+ const stepEntity = ctx.__entities.find(e => e.__name === 'Step');
101
+ assert.equal(stepEntity.Run.type, 'integer');
102
+ });
103
+
104
+ test('belongsTo FK type resolves regardless of dbset() order', () => {
105
+ class Run {
106
+ id(db) { db.string().primary(); }
107
+ name(db) { db.string(); }
108
+ }
109
+ class Step {
110
+ id(db) { db.integer().primary().auto(); }
111
+ Run(db) { db.belongsTo('Run').notNullable(); }
112
+ }
113
+ class OutOfOrderCtx extends context {
114
+ constructor() {
115
+ super();
116
+ this.env(envDir);
117
+ this.dbset(Step); // child first
118
+ this.dbset(Run); // parent second
119
+ }
120
+ }
121
+ const ctx = new OutOfOrderCtx();
122
+ const stepEntity = ctx.__entities.find(e => e.__name === 'Step');
123
+ assert.equal(stepEntity.Run.type, 'string', 'resolution must be order-independent');
124
+ });
125
+
126
+ test('belongsTo FK type resolves for bigint parent PK', () => {
127
+ class Run {
128
+ id(db) { db.type('bigint').primary().auto(); }
129
+ name(db) { db.string(); }
130
+ }
131
+ class Step {
132
+ id(db) { db.integer().primary().auto(); }
133
+ Run(db) { db.belongsTo('Run').notNullable(); }
134
+ }
135
+ class BigintPkCtx extends context {
136
+ constructor() {
137
+ super();
138
+ this.env(envDir);
139
+ this.dbset(Run);
140
+ this.dbset(Step);
141
+ }
142
+ }
143
+ const ctx = new BigintPkCtx();
144
+ const stepEntity = ctx.__entities.find(e => e.__name === 'Step');
145
+ assert.equal(stepEntity.Run.type, 'bigint');
146
+ });
147
+
148
+ test('belongsTo FK type resolves for uuid parent PK', () => {
149
+ class Run {
150
+ id(db) { db.type('uuid').primary(); }
151
+ name(db) { db.string(); }
152
+ }
153
+ class Step {
154
+ id(db) { db.integer().primary().auto(); }
155
+ Run(db) { db.belongsTo('Run').notNullable(); }
156
+ }
157
+ class UuidPkCtx extends context {
158
+ constructor() {
159
+ super();
160
+ this.env(envDir);
161
+ this.dbset(Run);
162
+ this.dbset(Step);
163
+ }
164
+ }
165
+ const ctx = new UuidPkCtx();
166
+ const stepEntity = ctx.__entities.find(e => e.__name === 'Step');
167
+ assert.equal(stepEntity.Run.type, 'uuid');
168
+ });
169
+
170
+ // =====================================================================
171
+ // Migration DDL output — verify each engine emits a matching SQL type.
172
+ // Bypasses context; feeds a minimal table-like object straight to the
173
+ // migration query builders. Shape mirrors what the resolver produces.
174
+ // =====================================================================
175
+
176
+ function stepTableWith(fkType) {
177
+ return {
178
+ __name: 'Step',
179
+ id: { name: 'id', type: 'integer', primary: true, auto: true },
180
+ name: { name: 'name', type: 'string' },
181
+ Run: {
182
+ name: 'Run',
183
+ type: fkType,
184
+ relationshipType: 'belongsTo',
185
+ foreignTable: 'Run',
186
+ foreignKey: 'run_id',
187
+ nullable: false,
188
+ },
189
+ };
190
+ }
191
+
192
+ test('Postgres createTable emits VARCHAR(255) for FK to string PK', () => {
193
+ const sql = new PostgresQuery().createTable(stepTableWith('string'));
194
+ assert.match(sql, /"run_id"\s+VARCHAR\(255\)/, sql);
195
+ assert.doesNotMatch(sql, /"run_id"\s+INTEGER/);
196
+ });
197
+
198
+ test('Postgres createTable emits INTEGER for FK to integer PK', () => {
199
+ const sql = new PostgresQuery().createTable(stepTableWith('integer'));
200
+ assert.match(sql, /"run_id"\s+INTEGER/, sql);
201
+ });
202
+
203
+ test('Postgres createTable emits BIGINT for FK to bigint PK', () => {
204
+ const sql = new PostgresQuery().createTable(stepTableWith('bigint'));
205
+ assert.match(sql, /"run_id"\s+BIGINT/, sql);
206
+ });
207
+
208
+ test('Postgres createTable emits UUID for FK to uuid PK', () => {
209
+ const sql = new PostgresQuery().createTable(stepTableWith('uuid'));
210
+ assert.match(sql, /"run_id"\s+UUID/, sql);
211
+ });
212
+
213
+ test('MySQL createTable emits VARCHAR(255) for FK to string PK', () => {
214
+ const sql = new MySQLQuery().createTable(stepTableWith('string'));
215
+ assert.match(sql, /`run_id`\s+VARCHAR\(255\)/, sql);
216
+ });
217
+
218
+ test('MySQL createTable emits BIGINT for FK to bigint PK', () => {
219
+ const sql = new MySQLQuery().createTable(stepTableWith('bigint'));
220
+ assert.match(sql, /`run_id`\s+BIGINT/, sql);
221
+ });
222
+
223
+ test('MySQL createTable emits VARCHAR(36) for FK to uuid PK', () => {
224
+ const sql = new MySQLQuery().createTable(stepTableWith('uuid'));
225
+ assert.match(sql, /`run_id`\s+VARCHAR\(36\)/, sql);
226
+ });
227
+
228
+ test('MySQL createTable never emits "undefined" for any FK type', () => {
229
+ for (const t of ['string', 'integer', 'bigint', 'uuid', 'text']) {
230
+ const sql = new MySQLQuery().createTable(stepTableWith(t));
231
+ assert.doesNotMatch(sql, /undefined/, `MySQL ${t}: ${sql}`);
232
+ }
233
+ });
234
+
235
+ test('SQLite createTable emits TEXT for FK to string PK', () => {
236
+ const sql = new SQLiteQuery().createTable(stepTableWith('string'));
237
+ assert.match(sql, /\[?run_id\]?\s+TEXT/i, sql);
238
+ });
239
+
240
+ test('SQLite createTable emits INTEGER for FK to integer PK', () => {
241
+ const sql = new SQLiteQuery().createTable(stepTableWith('integer'));
242
+ assert.match(sql, /\[?run_id\]?\s+INTEGER/i, sql);
243
+ });
244
+
245
+ test('SQLite createTable emits INTEGER for FK to bigint PK', () => {
246
+ const sql = new SQLiteQuery().createTable(stepTableWith('bigint'));
247
+ assert.match(sql, /\[?run_id\]?\s+INTEGER/i, sql);
248
+ });
249
+
250
+ test('SQLite createTable emits TEXT for FK to uuid PK', () => {
251
+ const sql = new SQLiteQuery().createTable(stepTableWith('uuid'));
252
+ assert.match(sql, /\[?run_id\]?\s+TEXT/i, sql);
253
+ });