masterrecord 1.3.2 → 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.
@@ -1,445 +0,0 @@
1
- # Detached Entity Problem - Solutions
2
-
3
- ## The Problem
4
-
5
- ```javascript
6
- // Controller loads task
7
- const task = await this._taskService.getTask(taskId);
8
-
9
- // Service receives task and modifies it
10
- task.status = 'completed';
11
-
12
- // Try to save - BUT IT DOESN'T WORK! ❌
13
- this._qaContext.saveChanges(); // Task change NOT saved
14
-
15
- // Why? The task is "detached" - not tracked by _qaContext
16
- ```
17
-
18
- **Root Cause:** The task was loaded in a different context (`taskService`) and is now **detached** from the current context (`_qaContext`). MasterRecord's change tracking doesn't see the modification.
19
-
20
- ---
21
-
22
- ## How Other ORMs Solve This
23
-
24
- ### Entity Framework (.NET)
25
- ```csharp
26
- // Solution 1: Attach
27
- context.Attach(task);
28
- context.Entry(task).State = EntityState.Modified;
29
- context.SaveChanges();
30
-
31
- // Solution 2: Update (simpler)
32
- context.Update(task);
33
- context.SaveChanges();
34
- ```
35
-
36
- ### Hibernate (Java)
37
- ```java
38
- // Solution: Merge
39
- session.merge(task);
40
- session.flush();
41
- ```
42
-
43
- ### Active Record (Rails)
44
- ```ruby
45
- # No problem - entities have .save()
46
- task.status = 'completed'
47
- task.save
48
- ```
49
-
50
- ### Sequelize (Node.js)
51
- ```javascript
52
- // No problem - entities have .save()
53
- task.status = 'completed';
54
- await task.save();
55
- ```
56
-
57
- ---
58
-
59
- ## MasterRecord Solutions
60
-
61
- ### Solution 1: **attach()** Method (Recommended)
62
-
63
- Like Entity Framework's `Update()`:
64
-
65
- ```javascript
66
- // Your original code (BROKEN)
67
- const task = await this._taskService.getTask(taskId);
68
- task.status = 'completed';
69
- this._qaContext.saveChanges(); // ❌ Doesn't work
70
-
71
- // FIX: Attach the detached entity
72
- const task = await this._taskService.getTask(taskId);
73
- task.status = 'completed';
74
- this._qaContext.attach(task); // ✅ Mark as modified
75
- await this._qaContext.saveChanges(); // ✅ Now it works!
76
- ```
77
-
78
- ### Solution 2: **Specific Field Changes**
79
-
80
- Only mark specific fields as dirty:
81
-
82
- ```javascript
83
- const task = await this._taskService.getTask(taskId);
84
-
85
- // Attach with specific changes
86
- this._qaContext.attach(task, {
87
- status: 'completed',
88
- completed_at: new Date()
89
- });
90
-
91
- await this._qaContext.saveChanges();
92
- ```
93
-
94
- ### Solution 3: **attachAll()** for Multiple Entities
95
-
96
- ```javascript
97
- const tasks = await this._taskService.getTasks();
98
-
99
- // Modify all tasks
100
- tasks.forEach(task => {
101
- task.status = 'completed';
102
- });
103
-
104
- // Attach all at once
105
- this._qaContext.attachAll(tasks);
106
- await this._qaContext.saveChanges();
107
- ```
108
-
109
- ### Solution 4: **update()** Helper
110
-
111
- Update by primary key without loading first:
112
-
113
- ```javascript
114
- // No need to load task first
115
- await this._qaContext.update('Task', taskId, {
116
- status: 'completed',
117
- completed_at: new Date()
118
- });
119
-
120
- await this._qaContext.saveChanges();
121
- ```
122
-
123
- ---
124
-
125
- ## Complete Example: Your Annotation Service
126
-
127
- ### Before (BROKEN) ❌
128
-
129
- ```javascript
130
- class AnnotationService {
131
- constructor() {
132
- this._qaContext = new QAContext();
133
- this._taskService = new TaskService();
134
- }
135
-
136
- async createAnnotation(taskId, data) {
137
- // Load task from different service
138
- const task = await this._taskService.getTask(taskId);
139
-
140
- // Create annotation
141
- const annotation = this._qaContext.Annotation.new();
142
- annotation.task_id = taskId;
143
- annotation.data = data;
144
- this._qaContext.Annotation.add(annotation);
145
-
146
- // Modify task - BUT NOT TRACKED! ❌
147
- task.status = 'completed';
148
-
149
- // Only annotation is saved, task change is ignored ❌
150
- await this._qaContext.saveChanges();
151
-
152
- return annotation;
153
- }
154
- }
155
- ```
156
-
157
- ### After (FIXED) ✅
158
-
159
- **Option A: Use attach()**
160
-
161
- ```javascript
162
- class AnnotationService {
163
- constructor() {
164
- this._qaContext = new QAContext();
165
- this._taskService = new TaskService();
166
- }
167
-
168
- async createAnnotation(taskId, data) {
169
- // Load task from different service
170
- const task = await this._taskService.getTask(taskId);
171
-
172
- // Create annotation
173
- const annotation = this._qaContext.Annotation.new();
174
- annotation.task_id = taskId;
175
- annotation.data = data;
176
- this._qaContext.Annotation.add(annotation);
177
-
178
- // Modify task
179
- task.status = 'completed';
180
-
181
- // FIX: Attach detached task ✅
182
- this._qaContext.attach(task);
183
-
184
- // Both annotation and task are saved ✅
185
- await this._qaContext.saveChanges();
186
-
187
- return annotation;
188
- }
189
- }
190
- ```
191
-
192
- **Option B: Use attach() with specific fields**
193
-
194
- ```javascript
195
- async createAnnotation(taskId, data) {
196
- const task = await this._taskService.getTask(taskId);
197
-
198
- // Create annotation
199
- const annotation = this._qaContext.Annotation.new();
200
- annotation.task_id = taskId;
201
- annotation.data = data;
202
- this._qaContext.Annotation.add(annotation);
203
-
204
- // Attach with specific changes ✅
205
- this._qaContext.attach(task, {
206
- status: 'completed',
207
- completed_at: new Date()
208
- });
209
-
210
- await this._qaContext.saveChanges();
211
- return annotation;
212
- }
213
- ```
214
-
215
- **Option C: Use update() helper**
216
-
217
- ```javascript
218
- async createAnnotation(taskId, data) {
219
- // No need to load task first
220
-
221
- // Create annotation
222
- const annotation = this._qaContext.Annotation.new();
223
- annotation.task_id = taskId;
224
- annotation.data = data;
225
- this._qaContext.Annotation.add(annotation);
226
-
227
- // Update task by ID ✅
228
- await this._qaContext.update('Task', taskId, {
229
- status: 'completed',
230
- completed_at: new Date()
231
- });
232
-
233
- await this._qaContext.saveChanges();
234
- return annotation;
235
- }
236
- ```
237
-
238
- ---
239
-
240
- ## Best Practices
241
-
242
- ### ✅ DO: Use One Context Per Request
243
-
244
- ```javascript
245
- // Express middleware
246
- app.use((req, res, next) => {
247
- req.db = new AppContext(); // One context per request
248
- res.on('finish', () => req.db.endRequest());
249
- next();
250
- });
251
-
252
- // Service uses the request context
253
- class AnnotationService {
254
- async createAnnotation(db, taskId, data) {
255
- // Use passed-in context
256
- const task = db.Task.findById(taskId); // Loaded in same context ✅
257
- task.status = 'completed'; // Already tracked ✅
258
-
259
- const annotation = db.Annotation.new();
260
- annotation.task_id = taskId;
261
- db.Annotation.add(annotation);
262
-
263
- await db.saveChanges(); // Both changes saved ✅
264
- return annotation;
265
- }
266
- }
267
-
268
- // Controller
269
- app.post('/annotations', async (req, res) => {
270
- const annotationService = new AnnotationService();
271
- const annotation = await annotationService.createAnnotation(
272
- req.db, // Pass request context ✅
273
- req.body.taskId,
274
- req.body.data
275
- );
276
- res.json(annotation);
277
- });
278
- ```
279
-
280
- ### ✅ DO: Load in Same Context
281
-
282
- ```javascript
283
- // ❌ BAD: Different contexts
284
- const taskService = new TaskService(); // Has own context
285
- const qaContext = new QAContext(); // Different context
286
- const task = await taskService.getTask(taskId); // Loaded in taskService context
287
- task.status = 'completed';
288
- qaContext.saveChanges(); // Doesn't see change ❌
289
-
290
- // ✅ GOOD: Same context
291
- const db = new AppContext();
292
- const task = db.Task.findById(taskId); // Loaded in db context
293
- task.status = 'completed'; // Already tracked
294
- await db.saveChanges(); // Change saved ✅
295
- ```
296
-
297
- ### ✅ DO: Use attach() for Detached Entities
298
-
299
- ```javascript
300
- // When you must use entities from different contexts
301
- const task = await externalService.getTask(taskId); // Detached
302
- task.status = 'completed';
303
- db.attach(task); // Re-attach ✅
304
- await db.saveChanges();
305
- ```
306
-
307
- ### ❌ DON'T: Modify Detached Entities Without Attaching
308
-
309
- ```javascript
310
- // ❌ BAD
311
- const task = await someService.getTask(taskId);
312
- task.status = 'completed';
313
- db.saveChanges(); // Won't work!
314
-
315
- // ✅ GOOD
316
- const task = await someService.getTask(taskId);
317
- task.status = 'completed';
318
- db.attach(task); // Attach first!
319
- await db.saveChanges();
320
- ```
321
-
322
- ---
323
-
324
- ## Comparison Table
325
-
326
- | ORM | Method | Example |
327
- |-----|--------|---------|
328
- | **Entity Framework** | `context.Update(entity)` | `context.Update(task);` |
329
- | **Hibernate** | `session.merge(entity)` | `session.merge(task);` |
330
- | **Active Record** | `entity.save()` | `task.save` |
331
- | **Sequelize** | `entity.save()` | `await task.save()` |
332
- | **MasterRecord** | `context.attach(entity)` | `db.attach(task);` |
333
-
334
- ---
335
-
336
- ## API Reference
337
-
338
- ### attach(entity, changes?)
339
-
340
- Attach a detached entity and mark as modified.
341
-
342
- **Parameters:**
343
- - `entity` - The detached entity
344
- - `changes` (optional) - Object with specific field changes
345
-
346
- **Returns:** The attached entity
347
-
348
- **Example:**
349
- ```javascript
350
- // Attach entire entity
351
- db.attach(task);
352
-
353
- // Attach with specific changes
354
- db.attach(task, { status: 'completed' });
355
- ```
356
-
357
- ### attachAll(entities)
358
-
359
- Attach multiple entities at once.
360
-
361
- **Parameters:**
362
- - `entities` - Array of detached entities
363
-
364
- **Returns:** Array of attached entities
365
-
366
- **Example:**
367
- ```javascript
368
- const tasks = await getTasks();
369
- tasks.forEach(t => t.status = 'completed');
370
- db.attachAll(tasks);
371
- await db.saveChanges();
372
- ```
373
-
374
- ### update(entityName, primaryKey, changes)
375
-
376
- Update entity by primary key without loading.
377
-
378
- **Parameters:**
379
- - `entityName` - Name of entity (e.g., 'Task')
380
- - `primaryKey` - Primary key value
381
- - `changes` - Object with field changes
382
-
383
- **Returns:** The attached entity
384
-
385
- **Example:**
386
- ```javascript
387
- await db.update('Task', taskId, {
388
- status: 'completed',
389
- completed_at: new Date()
390
- });
391
- await db.saveChanges();
392
- ```
393
-
394
- ---
395
-
396
- ## Troubleshooting
397
-
398
- ### Changes not saving?
399
-
400
- **Check:**
401
- 1. Is entity tracked? `console.log(db.__trackedEntities.includes(entity))`
402
- 2. Is entity state correct? `console.log(entity.__state)` (should be "modified")
403
- 3. Are dirty fields marked? `console.log(entity.__dirtyFields)`
404
-
405
- **Fix:**
406
- ```javascript
407
- // If not tracked, attach it
408
- if (!db.__trackedEntities.includes(entity)) {
409
- db.attach(entity);
410
- }
411
- ```
412
-
413
- ### "Entity must have __entity metadata" error?
414
-
415
- **Cause:** Entity wasn't loaded through MasterRecord
416
-
417
- **Fix:**
418
- ```javascript
419
- // ❌ BAD: Plain object
420
- const task = { id: 1, status: 'completed' };
421
- db.attach(task); // Error!
422
-
423
- // ✅ GOOD: Load through MasterRecord
424
- const task = db.Task.findById(1);
425
- task.status = 'completed';
426
- db.attach(task); // Works!
427
- ```
428
-
429
- ---
430
-
431
- ## Summary
432
-
433
- **The detached entity problem** happens when:
434
- 1. Entity loaded in one context
435
- 2. Passed to different context/service
436
- 3. Modified
437
- 4. saveChanges() called but doesn't see modification
438
-
439
- **Solutions:**
440
- 1. ✅ Use **`attach()`** to re-attach detached entities (like Entity Framework)
441
- 2. ✅ Use **same context** throughout request (best practice)
442
- 3. ✅ Pass context to services instead of creating multiple contexts
443
- 4. ✅ Use **`update()`** helper for simple updates
444
-
445
- **MasterRecord now handles this like Entity Framework!** 🎉
@@ -1,219 +0,0 @@
1
- # Full-Text Search
2
-
3
- > Available since **v1.1.0**.
4
-
5
- MasterRecord ships a portable full-text search API that runs on top of each engine's native FTS implementation:
6
-
7
- | Engine | Implementation |
8
- | ---------- | --------------------------------------------------------------- |
9
- | SQLite | FTS5 external-content virtual table + AFTER INSERT/UPDATE/DELETE triggers |
10
- | PostgreSQL | `tsvector` column + GIN index + maintenance trigger |
11
- | MySQL | `FULLTEXT INDEX` |
12
-
13
- Your migration and query code stays the same across all three. The setup details, the rank algorithm (BM25 vs `ts_rank` vs MySQL relevance), and the query-syntax details (FTS5's `NEAR`, Postgres `&|<->`, MySQL natural-language mode) all live inside MasterRecord.
14
-
15
- ---
16
-
17
- ## Why not just use `.like()`?
18
-
19
- `LIKE` does a literal substring match without ranking, stemming, or tokenization. For "the user typed a few words, show the best matches first" you want FTS. Here's the practical difference:
20
-
21
- | Need | `.like()` | `.search()` |
22
- | --------------------------------------------------- | ----------- | ----------- |
23
- | Find rows containing this exact substring | ✅ | ✅ |
24
- | Prefix match (`auth*`) | ✅ (`auth%`) | ✅ |
25
- | Match `authentication` when searching `auth` | ❌ | ✅ |
26
- | Match `auth login` regardless of word order | ❌ | ✅ |
27
- | Rank results by relevance | ❌ | ✅ |
28
- | Fast on large tables | ❌ (scan) | ✅ (index) |
29
-
30
- If you want simple substring filtering, stay with `.like()`. If you want a search box, use `.search()`.
31
-
32
- ---
33
-
34
- ## Setup — in a migration
35
-
36
- Declare the index alongside `createTable`:
37
-
38
- ```js
39
- import masterrecord from 'masterrecord';
40
-
41
- class AddMemoryDocFts extends masterrecord.schema {
42
- async up(table) {
43
- await this.init(table);
44
- await this.createTable(table.MemoryDoc);
45
- await this.createFullTextIndex({
46
- tableName: 'MemoryDoc',
47
- columns: ['title', 'body'],
48
- });
49
- }
50
-
51
- async down(table) {
52
- await this.init(table);
53
- await this.dropFullTextIndex({ tableName: 'MemoryDoc' });
54
- await this.dropTable(table.MemoryDoc);
55
- }
56
- }
57
-
58
- export default AddMemoryDocFts;
59
- ```
60
-
61
- ### `createFullTextIndex(info)`
62
-
63
- | Option | Type | Required | Description |
64
- | ------------ | -------- | -------- | ------------------------------------------------------------------------------------------ |
65
- | `tableName` | string | yes | Source table. |
66
- | `columns` | string[] | yes | Columns to index, in order. |
67
- | `indexName` | string | no | Override the generated index name (`idx_<table>_fts` by default). |
68
- | `config` | string | no | Postgres-only `to_tsvector` config (defaults to `'english'`). Ignored on SQLite and MySQL. |
69
-
70
- Per-engine effect:
71
-
72
- - **SQLite** — creates `<TableName>_fts` virtual table with `content=<TableName>, content_rowid=id`, plus AFTER INSERT/UPDATE/DELETE sync triggers. The FTS table mirrors the source automatically.
73
- - **Postgres** — adds a `__tsv tsvector` column, backfills it from existing rows, creates a GIN index, and installs a BEFORE INSERT/UPDATE trigger that keeps `__tsv` in sync with the listed columns.
74
- - **MySQL** — `ALTER TABLE … ADD FULLTEXT INDEX (col1, col2)`. MySQL maintains the index automatically; no triggers needed.
75
-
76
- ### `dropFullTextIndex(info)`
77
-
78
- | Option | Type | Required | Description |
79
- | ----------- | ------ | -------- | -------------------------------------------- |
80
- | `tableName` | string | yes | Source table. |
81
- | `indexName` | string | no | Override if you set a custom name on create. |
82
-
83
- Reverses everything `createFullTextIndex` did. Safe to re-run on missing infrastructure (`IF EXISTS` clauses everywhere).
84
-
85
- ---
86
-
87
- ## Querying — at runtime
88
-
89
- ```js
90
- const docs = await ctx.MemoryDoc
91
- .search({ in: ['title', 'body'], query: 'auth login' })
92
- .toList();
93
-
94
- // Each row exposes a __rank field
95
- for (const d of docs) {
96
- console.log(d.__rank, d.title);
97
- }
98
- ```
99
-
100
- ### `.search(opts)`
101
-
102
- | Option | Type | Required | Description |
103
- | ------- | -------- | -------- | ----------------------------------------------------------------------- |
104
- | `in` | string[] | yes | Columns to search. Must be a subset of what `createFullTextIndex` indexed. |
105
- | `query` | string | yes | Search terms. Engine-specific syntax (see below). |
106
-
107
- Returns a chainable query builder, just like `.where()`. Each returned row gets a `__rank` field; results are ordered by rank descending by default.
108
-
109
- ### Composition
110
-
111
- `.search()` composes with `.where()`, `.take()`, `.skip()`, `.orderBy()`. The search predicate ANDs with `.where()` conditions:
112
-
113
- ```js
114
- // Workspace-scoped FTS, paginated, top 10
115
- const page = await ctx.MemoryDoc
116
- .search({ in: ['title', 'body'], query: 'auth login' })
117
- .where(d => d.workspace_id == ctx.$$, workspaceId)
118
- .take(10)
119
- .skip(20)
120
- .toList();
121
- ```
122
-
123
- If you chain your own `.orderBy()`, it replaces the default rank ordering:
124
-
125
- ```js
126
- // Most-recently-updated first, regardless of rank
127
- const docs = await ctx.MemoryDoc
128
- .search({ in: ['title', 'body'], query: 'auth' })
129
- .orderByDescending(d => d.updated_at)
130
- .toList();
131
- ```
132
-
133
- ---
134
-
135
- ## Engine-specific query syntax
136
-
137
- The `query` string is passed through to the engine's native FTS operator, so syntax differs:
138
-
139
- | Engine | Operator | Common syntax |
140
- | ---------- | ----------------------------------------------- | ---------------------------------------------------- |
141
- | SQLite | `MATCH 'terms'` | `auth*` (prefix), `auth NEAR login`, `"exact phrase"` |
142
- | PostgreSQL | `@@ plainto_tsquery('terms')` | Plain words. For operators use `to_tsquery` syntax: `auth & login`, `auth | login` |
143
- | MySQL | `MATCH(...) AGAINST(? IN NATURAL LANGUAGE MODE)` | Plain words. `+auth -login`, `"exact phrase"` in boolean mode (default is NLM) |
144
-
145
- > **The ranking *score* and exact ordering will differ across engines** — BM25 is not the same as `ts_rank` is not the same as MySQL relevance. Within a single engine the ordering is stable and meaningful; across engines it's best-effort.
146
-
147
- If your app's correctness depends on matching specific tokens or operator semantics, pick an engine and stay on it.
148
-
149
- ---
150
-
151
- ## Reading rank
152
-
153
- Every row returned from a `.search()` query has a `__rank` field added:
154
-
155
- ```js
156
- const rows = await ctx.MemoryDoc
157
- .search({ in: ['title', 'body'], query: 'auth' })
158
- .toList();
159
- console.log(rows[0].__rank); // numeric
160
- ```
161
-
162
- The scale differs per engine — Postgres and MySQL return positive values where higher means more relevant; SQLite's BM25 returns negative values where lower (more negative) means more relevant. **You should not compare rank values across engines.** Within a single query they're consistent for sorting.
163
-
164
- ---
165
-
166
- ## Patterns
167
-
168
- ### Auto-complete / search-as-you-type
169
-
170
- Use a prefix query — supported on SQLite (`auth*`) and Postgres (`auth:*` with `to_tsquery`; with `plainto_tsquery` it's plain stemming). MySQL natural-language mode doesn't do prefix matching; switch to boolean mode if you need it.
171
-
172
- For broadly portable behavior with `plainto_tsquery` semantics, just pass the prefix:
173
-
174
- ```js
175
- ctx.MemoryDoc.search({ in: ['title'], query: 'auth' }).take(10).toList();
176
- ```
177
-
178
- ### Scoped search
179
-
180
- Combine `.search()` with `.where()` on a tenant column:
181
-
182
- ```js
183
- ctx.MemoryDoc
184
- .search({ in: ['title', 'body'], query })
185
- .where(d => d.workspace_id == ctx.$$, workspaceId)
186
- .toList();
187
- ```
188
-
189
- ### Pagination
190
-
191
- `.search()` + `.skip().take()` work together. Rank is stable per query, so paging is safe as long as the underlying data doesn't change between requests.
192
-
193
- ### Returning rank to the UI
194
-
195
- `__rank` is a regular column on the result row. Serialize it as you would any field:
196
-
197
- ```js
198
- const results = await ctx.MemoryDoc.search({ in: ['title', 'body'], query }).toList();
199
- return results.map(d => ({ id: d.id, title: d.title, score: d.__rank }));
200
- ```
201
-
202
- ---
203
-
204
- ## Caveats
205
-
206
- - **The columns passed to `.search({ in: [...] })` must be a subset of what `createFullTextIndex({ columns: [...] })` declared.** If you index `[title, body]` and search `in: ['summary']`, the engine will reject the query (SQLite/Postgres) or return nothing (MySQL).
207
- - **MySQL FULLTEXT requires InnoDB ≥ 5.6** (or MyISAM). Older versions need a different table engine.
208
- - **Postgres requires a `to_tsvector`-compatible config.** Default is `'english'`. Pass `config: 'simple'` for no stemming, or any other Postgres config you've configured.
209
- - **Don't search before populating.** On SQLite the FTS table is filled by INSERT triggers — rows that exist before `createFullTextIndex` are NOT indexed unless you re-insert them. On Postgres, the migration backfills the `tsvector` column automatically. On MySQL, FULLTEXT indexes existing rows when the index is created.
210
-
211
- ---
212
-
213
- ## When NOT to use this
214
-
215
- Both runtime search and the schema setup add complexity. Skip them if:
216
-
217
- - You only need substring matching → use `.like()`.
218
- - Your dataset is tiny and a full table scan is fine.
219
- - You need cross-language or fuzzy matching beyond what BM25/`ts_rank` provide — reach for a dedicated search engine (Meilisearch, Elastic, Typesense) and integrate it as a separate service.