masterrecord 1.3.3 → 1.5.5
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/Entity/entityTrackerModel.js +202 -149
- package/Migrations/cli.js +152 -36
- package/Migrations/migrationMySQLQuery.js +21 -13
- package/Migrations/migrationPostgresQuery.js +21 -12
- package/Migrations/migrationSQLiteQuery.js +5 -1
- package/Migrations/migrationTemplate.js +11 -0
- package/Migrations/migrations.js +16 -0
- package/Migrations/schema.js +108 -28
- package/QueryLanguage/queryMethods.js +34 -5
- package/SQLLiteEngine.js +67 -10
- package/Tools.js +76 -0
- package/context.js +345 -63
- package/mySQLEngine.js +0 -0
- package/package.json +11 -14
- package/postgresEngine.js +97 -10
- package/readme.md +61 -11
- package/CHANGES.md +0 -421
- package/docs/ACTIVE_RECORD_PATTERN.md +0 -477
- package/docs/DETACHED_ENTITIES_GUIDE.md +0 -445
- package/docs/FULL_TEXT_SEARCH.md +0 -219
- package/docs/INCLUDES_CLARIFICATION.md +0 -202
- package/docs/METHODS_REFERENCE.md +0 -199
- package/docs/MIGRATIONS_GUIDE.md +0 -508
- package/docs/POSTGRESQL_SETUP.md +0 -441
- package/docs/QUERY_CACHING_GUIDE.md +0 -446
- package/docs/TROUBLESHOOTING.md +0 -348
- package/docs/belongsTo-relationships.md +0 -222
package/docs/TROUBLESHOOTING.md
DELETED
|
@@ -1,348 +0,0 @@
|
|
|
1
|
-
# MasterRecord Troubleshooting Guide
|
|
2
|
-
|
|
3
|
-
This guide covers common issues and potential pitfalls when using MasterRecord.
|
|
4
|
-
|
|
5
|
-
## Navigation Properties vs Regular Properties
|
|
6
|
-
|
|
7
|
-
### Understanding the Difference
|
|
8
|
-
|
|
9
|
-
MasterRecord provides **two different ways** to access related entities, and mixing them causes bugs.
|
|
10
|
-
|
|
11
|
-
#### 1. Navigation Properties (Lazy Loading)
|
|
12
|
-
|
|
13
|
-
When you access a related entity using a **capital letter that matches the entity name**, MasterRecord treats it as a navigation property with lazy loading:
|
|
14
|
-
|
|
15
|
-
```javascript
|
|
16
|
-
// Accessing with capital letter triggers lazy loading
|
|
17
|
-
const auth = await user.Auth; // Executes a database query
|
|
18
|
-
```
|
|
19
|
-
|
|
20
|
-
**How it works:**
|
|
21
|
-
- MasterRecord looks up the entity definition in your context
|
|
22
|
-
- Executes a SQL query to load the related record
|
|
23
|
-
- Returns a **Promise** that must be awaited
|
|
24
|
-
- Defined in your entity's relationship configuration (hasOne, hasMany, belongsTo)
|
|
25
|
-
|
|
26
|
-
#### 2. Regular Properties (Direct Access)
|
|
27
|
-
|
|
28
|
-
When you manually attach an object to an entity as a regular property, you access it directly:
|
|
29
|
-
|
|
30
|
-
```javascript
|
|
31
|
-
// Attach as regular property (any case except navigation property name)
|
|
32
|
-
user.auth = someAuthObject; // lowercase
|
|
33
|
-
|
|
34
|
-
// Access directly - no query, just returns the object
|
|
35
|
-
console.log(user.auth.password_hash); // Immediate access
|
|
36
|
-
```
|
|
37
|
-
|
|
38
|
-
### Common Bug: Mixing Both Approaches
|
|
39
|
-
|
|
40
|
-
**❌ THIS CAUSES BUGS:**
|
|
41
|
-
|
|
42
|
-
```javascript
|
|
43
|
-
// In authService.js - attaching as regular property (lowercase)
|
|
44
|
-
async findAuthByEmail(email, context) {
|
|
45
|
-
var user = await context.User
|
|
46
|
-
.where(r => r.email.toLowerCase() == $$, email.toLowerCase())
|
|
47
|
-
.single();
|
|
48
|
-
|
|
49
|
-
var auth = await context.Auth
|
|
50
|
-
.where(a => a.user_id == $$, user.id)
|
|
51
|
-
.single();
|
|
52
|
-
|
|
53
|
-
// Attaching as lowercase regular property
|
|
54
|
-
user.auth = auth;
|
|
55
|
-
return user;
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
// In credentialsController.js - accessing as navigation property (capital)
|
|
59
|
-
async login(req) {
|
|
60
|
-
var authObj = await req.authService.authenticate(email, password, req.userContext);
|
|
61
|
-
|
|
62
|
-
// ❌ BUG: Accessing as capital triggers navigation property!
|
|
63
|
-
authObj.user.Auth.temp_access_token = refreshToken; // Returns Promise, not auth object!
|
|
64
|
-
req.userContext.saveChanges(); // Doesn't save - Promise isn't resolved
|
|
65
|
-
}
|
|
66
|
-
```
|
|
67
|
-
|
|
68
|
-
**What happens:**
|
|
69
|
-
1. `findAuthByEmail()` attaches auth as `user.auth` (lowercase regular property)
|
|
70
|
-
2. `credentialsController` tries to access `user.Auth` (capital navigation property)
|
|
71
|
-
3. MasterRecord sees the capital letter and thinks "navigation property!"
|
|
72
|
-
4. It executes a lazy loading query and returns a Promise
|
|
73
|
-
5. The Promise isn't awaited, so you get `undefined` or the Promise object itself
|
|
74
|
-
6. Your data doesn't save, properties return undefined, bcrypt fails with "Illegal arguments"
|
|
75
|
-
|
|
76
|
-
### Solutions
|
|
77
|
-
|
|
78
|
-
#### Option 1: Use Regular Properties (Recommended when entity already loaded)
|
|
79
|
-
|
|
80
|
-
**✅ CORRECT:**
|
|
81
|
-
|
|
82
|
-
```javascript
|
|
83
|
-
// Attach as lowercase regular property
|
|
84
|
-
user.auth = auth;
|
|
85
|
-
|
|
86
|
-
// Access as lowercase regular property
|
|
87
|
-
authObj.user.auth.temp_access_token = refreshToken;
|
|
88
|
-
authObj.user.auth.login_counter = authObj.user.auth.login_counter + 1;
|
|
89
|
-
req.userContext.saveChanges();
|
|
90
|
-
```
|
|
91
|
-
|
|
92
|
-
**Benefits:**
|
|
93
|
-
- ✅ No extra database queries
|
|
94
|
-
- ✅ Synchronous access
|
|
95
|
-
- ✅ More performant
|
|
96
|
-
|
|
97
|
-
**Use when:**
|
|
98
|
-
- You've already loaded the related entity with an explicit query
|
|
99
|
-
- You want direct access without database overhead
|
|
100
|
-
- You need synchronous property access
|
|
101
|
-
|
|
102
|
-
#### Option 2: Use Navigation Properties with Await (When you want lazy loading)
|
|
103
|
-
|
|
104
|
-
**✅ CORRECT:**
|
|
105
|
-
|
|
106
|
-
```javascript
|
|
107
|
-
// Access navigation property with await
|
|
108
|
-
const auth = await authObj.user.Auth; // Must await!
|
|
109
|
-
auth.temp_access_token = refreshToken;
|
|
110
|
-
auth.login_counter = auth.login_counter + 1;
|
|
111
|
-
req.userContext.saveChanges();
|
|
112
|
-
```
|
|
113
|
-
|
|
114
|
-
**Benefits:**
|
|
115
|
-
- ✅ Automatic loading of related entities
|
|
116
|
-
- ✅ Works without manual queries
|
|
117
|
-
|
|
118
|
-
**Drawbacks:**
|
|
119
|
-
- ❌ Extra database query (even if you already loaded it)
|
|
120
|
-
- ❌ Must remember to await
|
|
121
|
-
- ❌ Async only
|
|
122
|
-
|
|
123
|
-
**Use when:**
|
|
124
|
-
- You want lazy loading behavior
|
|
125
|
-
- You haven't already loaded the related entity
|
|
126
|
-
- You're okay with the extra database query
|
|
127
|
-
|
|
128
|
-
### Best Practice: Be Consistent
|
|
129
|
-
|
|
130
|
-
The key is **consistency** - pick one approach per relationship and stick with it:
|
|
131
|
-
|
|
132
|
-
```javascript
|
|
133
|
-
// Good: Explicit loading + regular properties
|
|
134
|
-
async findAuthByEmail(email, context) {
|
|
135
|
-
const user = await context.User.where(r => r.email == $$, email).single();
|
|
136
|
-
const auth = await context.Auth.where(a => a.user_id == $$, user.id).single();
|
|
137
|
-
user.auth = auth; // lowercase
|
|
138
|
-
return user;
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
// Access consistently with lowercase
|
|
142
|
-
authObj.user.auth.temp_access_token = refreshToken; // lowercase
|
|
143
|
-
```
|
|
144
|
-
|
|
145
|
-
OR
|
|
146
|
-
|
|
147
|
-
```javascript
|
|
148
|
-
// Good: Let navigation properties do the work
|
|
149
|
-
async findAuthByEmail(email, context) {
|
|
150
|
-
const user = await context.User.where(r => r.email == $$, email).single();
|
|
151
|
-
// Don't manually load auth - let navigation property handle it
|
|
152
|
-
return user;
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
// Access with await
|
|
156
|
-
const auth = await authObj.user.Auth; // capital + await
|
|
157
|
-
auth.temp_access_token = refreshToken;
|
|
158
|
-
```
|
|
159
|
-
|
|
160
|
-
### Real-World Example: Authentication Bug
|
|
161
|
-
|
|
162
|
-
This bug was found in a production authentication system where login succeeded but immediately redirected back to the login page.
|
|
163
|
-
|
|
164
|
-
**The Problem:**
|
|
165
|
-
```javascript
|
|
166
|
-
// authService.js - Line 306
|
|
167
|
-
user.auth = auth; // Attaching as lowercase
|
|
168
|
-
|
|
169
|
-
// credentialsController.js - Line 287-288
|
|
170
|
-
authObj.user.Auth.temp_access_token = refreshToken; // ❌ Accessing as capital!
|
|
171
|
-
req.userContext.saveChanges();
|
|
172
|
-
```
|
|
173
|
-
|
|
174
|
-
**What happened:**
|
|
175
|
-
1. JWT token was generated correctly
|
|
176
|
-
2. `authObj.user.Auth.temp_access_token = refreshToken` didn't actually save the token
|
|
177
|
-
3. It set the property on a Promise object instead of the auth entity
|
|
178
|
-
4. Database query `WHERE temp_access_token = ?` returned no results
|
|
179
|
-
5. `currentUser()` check failed
|
|
180
|
-
6. User was redirected back to login
|
|
181
|
-
|
|
182
|
-
**The Fix:**
|
|
183
|
-
```javascript
|
|
184
|
-
// credentialsController.js - Line 287-288
|
|
185
|
-
authObj.user.auth.temp_access_token = refreshToken; // ✅ lowercase matches attachment
|
|
186
|
-
authObj.user.auth.login_counter = authObj.user.auth.login_counter + 1;
|
|
187
|
-
req.userContext.saveChanges(); // Now it actually saves!
|
|
188
|
-
```
|
|
189
|
-
|
|
190
|
-
### Debugging Tips
|
|
191
|
-
|
|
192
|
-
If you're seeing any of these symptoms:
|
|
193
|
-
- Properties returning `undefined` when you know they exist in the database
|
|
194
|
-
- `bcrypt.compareSync()` failing with "Illegal arguments: string, undefined"
|
|
195
|
-
- Data not saving when you call `saveChanges()`
|
|
196
|
-
- `[object Promise]` appearing in logs instead of actual values
|
|
197
|
-
- Queries executing successfully but entities seem empty
|
|
198
|
-
|
|
199
|
-
**Check for navigation property mismatches:**
|
|
200
|
-
|
|
201
|
-
1. Add debug logging:
|
|
202
|
-
```javascript
|
|
203
|
-
console.log('Type of user.Auth:', typeof user.Auth);
|
|
204
|
-
console.log('Is Promise?', user.Auth instanceof Promise);
|
|
205
|
-
console.log('Value:', user.Auth);
|
|
206
|
-
```
|
|
207
|
-
|
|
208
|
-
2. Look for:
|
|
209
|
-
- Capital letter access (`user.Auth`, `auth.User`) without `await`
|
|
210
|
-
- Mixing lowercase attachment with capital access
|
|
211
|
-
- Accessing navigation properties in non-async contexts
|
|
212
|
-
|
|
213
|
-
3. Fix by:
|
|
214
|
-
- Making access match attachment (both lowercase)
|
|
215
|
-
- OR using `await` with capital navigation properties
|
|
216
|
-
- OR explicitly loading entities instead of relying on lazy loading
|
|
217
|
-
|
|
218
|
-
### Additional Examples
|
|
219
|
-
|
|
220
|
-
#### Creating New Entities with Relationships
|
|
221
|
-
|
|
222
|
-
When creating new entities, you can use capital letters during construction:
|
|
223
|
-
|
|
224
|
-
```javascript
|
|
225
|
-
// ✅ This is fine - entity not yet persisted
|
|
226
|
-
var user = new userEntity();
|
|
227
|
-
var auth = new authEntity();
|
|
228
|
-
user.Auth = auth; // Capital is OK here
|
|
229
|
-
auth.password_hash = bcrypt.hashSync(password, salt);
|
|
230
|
-
context.User.add(user);
|
|
231
|
-
await context.saveChanges();
|
|
232
|
-
|
|
233
|
-
// ❌ After saveChanges, use regular property or reload
|
|
234
|
-
// Store reference to avoid navigation property
|
|
235
|
-
auth.temp_access_token = refreshToken; // Use stored reference
|
|
236
|
-
await context.saveChanges();
|
|
237
|
-
|
|
238
|
-
// ❌ DON'T DO THIS after saveChanges:
|
|
239
|
-
user.Auth.temp_access_token = refreshToken; // Triggers navigation property!
|
|
240
|
-
```
|
|
241
|
-
|
|
242
|
-
#### Working with Loaded Entities
|
|
243
|
-
|
|
244
|
-
```javascript
|
|
245
|
-
// Load user from database
|
|
246
|
-
const user = await context.User.where(r => r.id == $$, userId).single();
|
|
247
|
-
|
|
248
|
-
// ✅ Option 1: Explicitly load and attach
|
|
249
|
-
const auth = await context.Auth.where(a => a.user_id == $$, user.id).single();
|
|
250
|
-
user.auth = auth; // lowercase
|
|
251
|
-
console.log(user.auth.password_hash); // Direct access
|
|
252
|
-
|
|
253
|
-
// ✅ Option 2: Use navigation property with await
|
|
254
|
-
const auth = await user.Auth; // capital + await
|
|
255
|
-
console.log(auth.password_hash);
|
|
256
|
-
|
|
257
|
-
// ❌ DON'T MIX:
|
|
258
|
-
user.auth = await context.Auth.where(a => a.user_id == $$, user.id).single();
|
|
259
|
-
console.log(user.Auth.password_hash); // Wrong! This is navigation property
|
|
260
|
-
```
|
|
261
|
-
|
|
262
|
-
## Summary
|
|
263
|
-
|
|
264
|
-
- **Navigation properties** (capital letter) = lazy loading = returns Promise = must await
|
|
265
|
-
- **Regular properties** (lowercase or any non-entity name) = direct access = immediate value
|
|
266
|
-
- **Never mix them** - be consistent in how you attach and access related entities
|
|
267
|
-
- **When in doubt**, explicitly load entities and use lowercase regular properties
|
|
268
|
-
- **Add debug logging** to catch Promise objects being treated as entities
|
|
269
|
-
|
|
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 the engine-agnostic raw escape hatch — `await ctx.execute('INSERT INTO Step (...) VALUES (?, ?)', [...])` (works on every engine) — 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).
|
|
309
|
-
|
|
310
|
-
---
|
|
311
|
-
|
|
312
|
-
## `TypeError: ctx.db.prepare is not a function` (MySQL / Postgres)
|
|
313
|
-
|
|
314
|
-
`ctx.db` is the **raw, engine-specific driver**. On SQLite it's a better-sqlite3 database (which has `.prepare()/.get()/.run()/.all()`); on MySQL it's a mysql2 pool and on Postgres a pg pool — neither has `.prepare()`. Code written against `ctx.db.prepare(...)` therefore works on SQLite and throws on MySQL/Postgres.
|
|
315
|
-
|
|
316
|
-
**Fix:** use the engine-agnostic raw-SQL escape hatch (since v1.2.7):
|
|
317
|
-
|
|
318
|
-
```javascript
|
|
319
|
-
const rows = await ctx.query('SELECT * FROM "User" WHERE id = $1', [id]); // returns rows, all engines
|
|
320
|
-
await ctx.execute('UPDATE "User" SET name = ? WHERE id = ?', ['Alice', id]);
|
|
321
|
-
```
|
|
322
|
-
|
|
323
|
-
Better still, prefer the ORM (`ctx.User.where(u => u.id == $$, id).single()`), which is portable by construction. On a non-SQLite engine, `ctx.db.prepare()` now throws a descriptive error pointing you to `ctx.query()`.
|
|
324
|
-
|
|
325
|
-
## `ERR_INVALID_MODULE_SPECIFIER` on Linux after generating migrations on Windows
|
|
326
|
-
|
|
327
|
-
A migration snapshot generated on Windows before **1.3.1** stored `contextLocation`
|
|
328
|
-
with backslashes (e.g. `"..\\..\\AppContext.js"`). On Linux a backslash is a literal
|
|
329
|
-
filename character, so the CLI's `path.resolve()` built a bogus module specifier and
|
|
330
|
-
the ESM import of the context failed **before any migration ran** — a deploy could
|
|
331
|
-
crash-loop at boot even with a fully up-to-date database.
|
|
332
|
-
|
|
333
|
-
**Fix:** upgrade to `masterrecord@1.3.1`. The snapshot writer now stores POSIX
|
|
334
|
-
separators, and every CLI read site normalizes on load — so already-committed
|
|
335
|
-
backslash snapshots keep working without regeneration.
|
|
336
|
-
|
|
337
|
-
## "Bulk insert failed, falling back to individual inserts" in the logs
|
|
338
|
-
|
|
339
|
-
Before **1.3.1**, saving a batch whose rows populated *different* column sets (some
|
|
340
|
-
rows leave optional fields unset, and auto-PKs are always skipped) emitted one
|
|
341
|
-
multi-row INSERT built from the FIRST row's column list — malformed for the rest
|
|
342
|
-
(MySQL `ER_WRONG_VALUE_COUNT_ON_ROW`) — and the context silently fell back to slow
|
|
343
|
-
per-row inserts. Rows whose column COUNT matched but column SET differed could even
|
|
344
|
-
land values in the wrong columns.
|
|
345
|
-
|
|
346
|
-
**Fix:** upgrade to `masterrecord@1.3.1`. Heterogeneous batches are sub-grouped by
|
|
347
|
-
column signature, one multi-value INSERT per signature, omitted columns keep their
|
|
348
|
-
database `DEFAULT`, and ids map back to entities in their original input order.
|
|
@@ -1,222 +0,0 @@
|
|
|
1
|
-
# belongsTo Relationships in MasterRecord
|
|
2
|
-
|
|
3
|
-
## Overview
|
|
4
|
-
|
|
5
|
-
When you define a `belongsTo` relationship in MasterRecord, the ORM creates **two separate properties** on your model instances:
|
|
6
|
-
|
|
7
|
-
1. **The foreign key field** (e.g., `document_id`) - the actual database column value
|
|
8
|
-
2. **The relationship property** (e.g., `Document`) - for accessing/setting the related object or ID
|
|
9
|
-
|
|
10
|
-
## How belongsTo Works Internally
|
|
11
|
-
|
|
12
|
-
### Entity Definition
|
|
13
|
-
|
|
14
|
-
```javascript
|
|
15
|
-
// DocumentChunk entity
|
|
16
|
-
DocumentChunk(db) {
|
|
17
|
-
db.integer("id").primary().notNull().autoIncrement();
|
|
18
|
-
db.string("content");
|
|
19
|
-
db.belongsTo("Document", "document_id"); // Creates both Document and document_id properties
|
|
20
|
-
}
|
|
21
|
-
```
|
|
22
|
-
|
|
23
|
-
The `belongsTo("Document", "document_id")` call:
|
|
24
|
-
- **Does NOT** create a separate `document_id` field definition
|
|
25
|
-
- Tells MasterRecord that `document_id` is a foreign key to the `Document` entity
|
|
26
|
-
- Creates a relationship property named `Document`
|
|
27
|
-
|
|
28
|
-
### Model Instance Properties
|
|
29
|
-
|
|
30
|
-
When you query records or create new instances, **both properties are available**:
|
|
31
|
-
|
|
32
|
-
```javascript
|
|
33
|
-
const chunk = context.DocumentChunk.where("r => r.id == 1").single();
|
|
34
|
-
|
|
35
|
-
// Both of these work:
|
|
36
|
-
console.log(chunk.document_id); // Accesses the foreign key value (e.g., 5)
|
|
37
|
-
console.log(chunk.Document); // Accesses the relationship (object or ID)
|
|
38
|
-
```
|
|
39
|
-
|
|
40
|
-
## Usage Patterns
|
|
41
|
-
|
|
42
|
-
### Pattern 1: INSERT Operations (Setting Foreign Keys)
|
|
43
|
-
|
|
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
|
-
|
|
46
|
-
```javascript
|
|
47
|
-
// Option A — relationship property name (always worked)
|
|
48
|
-
const chunk = context.DocumentChunk.new();
|
|
49
|
-
chunk.content = "Sample content";
|
|
50
|
-
chunk.Document = documentId;
|
|
51
|
-
await chunk.save();
|
|
52
|
-
|
|
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();
|
|
58
|
-
```
|
|
59
|
-
|
|
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.
|
|
61
|
-
|
|
62
|
-
### Pattern 2: READ Operations (Accessing Foreign Keys)
|
|
63
|
-
|
|
64
|
-
When **reading or filtering records**, use the **foreign key field name**:
|
|
65
|
-
|
|
66
|
-
```javascript
|
|
67
|
-
// ✅ CORRECT - Use foreign key for filtering
|
|
68
|
-
const chunks = context.DocumentChunk
|
|
69
|
-
.where(`r => r.document_id == ${docId}`)
|
|
70
|
-
.toList();
|
|
71
|
-
|
|
72
|
-
// ✅ CORRECT - Use foreign key in JavaScript filters
|
|
73
|
-
const filtered = allChunks.filter(c => documentIds.includes(c.document_id));
|
|
74
|
-
|
|
75
|
-
// ✅ CORRECT - Access foreign key value directly
|
|
76
|
-
if (chunk.document_id === targetId) {
|
|
77
|
-
// ...
|
|
78
|
-
}
|
|
79
|
-
```
|
|
80
|
-
|
|
81
|
-
**Why?** When records are loaded from the database, the raw column data includes `document_id`. The `build` method (entityTrackerModel.js:21-59) creates getters/setters for all non-relationship fields from the database result.
|
|
82
|
-
|
|
83
|
-
### Pattern 3: UPDATE Operations
|
|
84
|
-
|
|
85
|
-
For updates, both properties are equivalent (since **v1.1.3**):
|
|
86
|
-
|
|
87
|
-
```javascript
|
|
88
|
-
// Using relationship property
|
|
89
|
-
chunk.Document = newDocumentId;
|
|
90
|
-
|
|
91
|
-
// Using foreign key directly
|
|
92
|
-
chunk.document_id = newDocumentId;
|
|
93
|
-
```
|
|
94
|
-
|
|
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.
|
|
96
|
-
|
|
97
|
-
## Code References
|
|
98
|
-
|
|
99
|
-
The behavior is implemented in `/Entity/entityTrackerModel.js`:
|
|
100
|
-
|
|
101
|
-
### Creating Non-Relationship Properties (lines 21-59)
|
|
102
|
-
|
|
103
|
-
```javascript
|
|
104
|
-
for (const [modelField, modelFieldValue] of modelFields) {
|
|
105
|
-
if(!$that._isRelationship(currentEntity[modelField])){
|
|
106
|
-
// Creates getter/setter for document_id (from database column)
|
|
107
|
-
modelClass["__proto__"]["_" + modelField] = modelFieldValue;
|
|
108
|
-
Object.defineProperty(modelClass, modelField, {
|
|
109
|
-
set: function(value) {
|
|
110
|
-
modelClass.__state = "modified";
|
|
111
|
-
modelClass.__dirtyFields.push(modelField);
|
|
112
|
-
this["__proto__"]["_" + modelField] = value;
|
|
113
|
-
},
|
|
114
|
-
get: function() {
|
|
115
|
-
return this["__proto__"]["_" + modelField];
|
|
116
|
-
}
|
|
117
|
-
});
|
|
118
|
-
}
|
|
119
|
-
}
|
|
120
|
-
```
|
|
121
|
-
|
|
122
|
-
This loop processes fields from the database result (like `document_id`) and makes them accessible as properties.
|
|
123
|
-
|
|
124
|
-
### Creating Relationship Properties (lines 89-149)
|
|
125
|
-
|
|
126
|
-
```javascript
|
|
127
|
-
if($that._isRelationship(currentEntity[entityField])){
|
|
128
|
-
// Creates getter/setter for Document (relationship property)
|
|
129
|
-
Object.defineProperty(modelClass, entityField, {
|
|
130
|
-
set: function(value) {
|
|
131
|
-
if(typeof value === "string" || typeof value === "number" ||
|
|
132
|
-
typeof value === "boolean" || typeof value === "bigint") {
|
|
133
|
-
modelClass.__state = "modified";
|
|
134
|
-
modelClass.__dirtyFields.push(entityField);
|
|
135
|
-
modelClass.__context.__track(modelClass);
|
|
136
|
-
}
|
|
137
|
-
this["__proto__"]["_" + entityField] = value;
|
|
138
|
-
},
|
|
139
|
-
get: function() {
|
|
140
|
-
// Complex getter logic for lazy loading, etc.
|
|
141
|
-
return this["__proto__"]["_" + entityField];
|
|
142
|
-
}
|
|
143
|
-
});
|
|
144
|
-
|
|
145
|
-
if(currentEntity[entityField].relationshipType === "belongsTo"){
|
|
146
|
-
// Initialize relationship value from database result
|
|
147
|
-
if(currentModel[entityField]){
|
|
148
|
-
modelClass[entityField] = currentModel[entityField];
|
|
149
|
-
}
|
|
150
|
-
}
|
|
151
|
-
}
|
|
152
|
-
```
|
|
153
|
-
|
|
154
|
-
This creates the `Document` property for relationship access.
|
|
155
|
-
|
|
156
|
-
## Real-World Example from bookbag-ce
|
|
157
|
-
|
|
158
|
-
In `bookbag-ce`, the `UserChat` entity demonstrates this pattern:
|
|
159
|
-
|
|
160
|
-
```javascript
|
|
161
|
-
// Entity definition
|
|
162
|
-
UserChat(db) {
|
|
163
|
-
db.integer("id").primary().notNull().autoIncrement();
|
|
164
|
-
db.belongsTo("Chat", "chat_id"); // Only defines relationship, not chat_id field
|
|
165
|
-
}
|
|
166
|
-
|
|
167
|
-
// Controller usage (chatController.js:66)
|
|
168
|
-
const messages = context.UserChat
|
|
169
|
-
.where(`r => r.chat_id == ${chatId}`) // ✅ Uses foreign key for filtering
|
|
170
|
-
.toList();
|
|
171
|
-
```
|
|
172
|
-
|
|
173
|
-
Even though `chat_id` is never explicitly defined as a field, it's accessible because:
|
|
174
|
-
1. The database returns `chat_id` as a column
|
|
175
|
-
2. `entityTrackerModel.build()` creates properties for all columns from the result
|
|
176
|
-
3. The `belongsTo` relationship doesn't prevent the foreign key from being accessible
|
|
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
|
-
|
|
207
|
-
## Summary
|
|
208
|
-
|
|
209
|
-
| Operation | Property to Use | Example |
|
|
210
|
-
|-----------|----------------|---------|
|
|
211
|
-
| **INSERT** (setting FK) | Relationship property | `chunk.Document = docId` |
|
|
212
|
-
| **READ** (accessing FK) | Foreign key field | `chunk.document_id` |
|
|
213
|
-
| **FILTER** (where clauses) | Foreign key field | `r.document_id == 5` |
|
|
214
|
-
| **UPDATE** (changing FK) | Either (prefer relationship) | `chunk.Document = newId` |
|
|
215
|
-
|
|
216
|
-
## Key Takeaways
|
|
217
|
-
|
|
218
|
-
1. **belongsTo creates TWO properties**, not one
|
|
219
|
-
2. The **foreign key column** (`document_id`) is automatically available from database results
|
|
220
|
-
3. The **relationship property** (`Document`) is created by the ORM for setting relationships
|
|
221
|
-
4. **Use the relationship property for INSERT**, foreign key field for READ/FILTER
|
|
222
|
-
5. Both properties reference the same underlying foreign key value in the database
|