masterrecord 1.5.5 → 1.5.7
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 +633 -0
- package/Entity/entityTrackerModel.js +7 -1
- package/QueryLanguage/queryMethods.js +15 -0
- package/docs/ACTIVE_RECORD_PATTERN.md +477 -0
- package/docs/DETACHED_ENTITIES_GUIDE.md +453 -0
- package/docs/FULL_TEXT_SEARCH.md +219 -0
- package/docs/INCLUDES_CLARIFICATION.md +202 -0
- package/docs/METHODS_REFERENCE.md +199 -0
- package/docs/MIGRATIONS_GUIDE.md +532 -0
- package/docs/POSTGRESQL_SETUP.md +445 -0
- package/docs/QUERY_CACHING_GUIDE.md +446 -0
- package/docs/SECURITY.md +95 -0
- package/docs/TROUBLESHOOTING.md +348 -0
- package/docs/belongsTo-relationships.md +222 -0
- package/package.json +3 -1
|
@@ -0,0 +1,453 @@
|
|
|
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 - the task change is NOT written by this context ❌
|
|
13
|
+
this._qaContext.saveChanges(); // Task change not persisted here
|
|
14
|
+
|
|
15
|
+
// Why? The task is "detached" - it is tracked by a DIFFERENT context
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
**Root Cause:** The task was loaded in a different context (`taskService`) and is tracked there, not by the current context (`_qaContext`). `_qaContext.saveChanges()` only writes entities *it* tracks.
|
|
19
|
+
|
|
20
|
+
> **As of 1.4.3 this no longer fails silently.** `saveChanges()` now **warns
|
|
21
|
+
> loudly** when entities tracked by a *different* context instance have unsaved
|
|
22
|
+
> changes — naming them and pointing you to the fix (save on the owning context,
|
|
23
|
+
> use `entity.save()`, or re-track with `context.attach(entity)`). Freshly loaded,
|
|
24
|
+
> unmodified entities never trip the warning. If you *intentionally* run multiple
|
|
25
|
+
> concurrent contexts with independent pending changes, silence it with
|
|
26
|
+
> `MASTERRECORD_SILENCE_CROSS_CONTEXT=1`.
|
|
27
|
+
|
|
28
|
+
---
|
|
29
|
+
|
|
30
|
+
## How Other ORMs Solve This
|
|
31
|
+
|
|
32
|
+
### Entity Framework (.NET)
|
|
33
|
+
```csharp
|
|
34
|
+
// Solution 1: Attach
|
|
35
|
+
context.Attach(task);
|
|
36
|
+
context.Entry(task).State = EntityState.Modified;
|
|
37
|
+
context.SaveChanges();
|
|
38
|
+
|
|
39
|
+
// Solution 2: Update (simpler)
|
|
40
|
+
context.Update(task);
|
|
41
|
+
context.SaveChanges();
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
### Hibernate (Java)
|
|
45
|
+
```java
|
|
46
|
+
// Solution: Merge
|
|
47
|
+
session.merge(task);
|
|
48
|
+
session.flush();
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
### Active Record (Rails)
|
|
52
|
+
```ruby
|
|
53
|
+
# No problem - entities have .save()
|
|
54
|
+
task.status = 'completed'
|
|
55
|
+
task.save
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
### Sequelize (Node.js)
|
|
59
|
+
```javascript
|
|
60
|
+
// No problem - entities have .save()
|
|
61
|
+
task.status = 'completed';
|
|
62
|
+
await task.save();
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
---
|
|
66
|
+
|
|
67
|
+
## MasterRecord Solutions
|
|
68
|
+
|
|
69
|
+
### Solution 1: **attach()** Method (Recommended)
|
|
70
|
+
|
|
71
|
+
Like Entity Framework's `Update()`:
|
|
72
|
+
|
|
73
|
+
```javascript
|
|
74
|
+
// Your original code (BROKEN)
|
|
75
|
+
const task = await this._taskService.getTask(taskId);
|
|
76
|
+
task.status = 'completed';
|
|
77
|
+
this._qaContext.saveChanges(); // ❌ Doesn't work
|
|
78
|
+
|
|
79
|
+
// FIX: Attach the detached entity
|
|
80
|
+
const task = await this._taskService.getTask(taskId);
|
|
81
|
+
task.status = 'completed';
|
|
82
|
+
this._qaContext.attach(task); // ✅ Mark as modified
|
|
83
|
+
await this._qaContext.saveChanges(); // ✅ Now it works!
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
### Solution 2: **Specific Field Changes**
|
|
87
|
+
|
|
88
|
+
Only mark specific fields as dirty:
|
|
89
|
+
|
|
90
|
+
```javascript
|
|
91
|
+
const task = await this._taskService.getTask(taskId);
|
|
92
|
+
|
|
93
|
+
// Attach with specific changes
|
|
94
|
+
this._qaContext.attach(task, {
|
|
95
|
+
status: 'completed',
|
|
96
|
+
completed_at: new Date()
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
await this._qaContext.saveChanges();
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
### Solution 3: **attachAll()** for Multiple Entities
|
|
103
|
+
|
|
104
|
+
```javascript
|
|
105
|
+
const tasks = await this._taskService.getTasks();
|
|
106
|
+
|
|
107
|
+
// Modify all tasks
|
|
108
|
+
tasks.forEach(task => {
|
|
109
|
+
task.status = 'completed';
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
// Attach all at once
|
|
113
|
+
this._qaContext.attachAll(tasks);
|
|
114
|
+
await this._qaContext.saveChanges();
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
### Solution 4: **update()** Helper
|
|
118
|
+
|
|
119
|
+
Update by primary key without loading first:
|
|
120
|
+
|
|
121
|
+
```javascript
|
|
122
|
+
// No need to load task first
|
|
123
|
+
await this._qaContext.update('Task', taskId, {
|
|
124
|
+
status: 'completed',
|
|
125
|
+
completed_at: new Date()
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
await this._qaContext.saveChanges();
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
---
|
|
132
|
+
|
|
133
|
+
## Complete Example: Your Annotation Service
|
|
134
|
+
|
|
135
|
+
### Before (BROKEN) ❌
|
|
136
|
+
|
|
137
|
+
```javascript
|
|
138
|
+
class AnnotationService {
|
|
139
|
+
constructor() {
|
|
140
|
+
this._qaContext = new QAContext();
|
|
141
|
+
this._taskService = new TaskService();
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
async createAnnotation(taskId, data) {
|
|
145
|
+
// Load task from different service
|
|
146
|
+
const task = await this._taskService.getTask(taskId);
|
|
147
|
+
|
|
148
|
+
// Create annotation
|
|
149
|
+
const annotation = this._qaContext.Annotation.new();
|
|
150
|
+
annotation.task_id = taskId;
|
|
151
|
+
annotation.data = data;
|
|
152
|
+
this._qaContext.Annotation.add(annotation);
|
|
153
|
+
|
|
154
|
+
// Modify task - BUT NOT TRACKED! ❌
|
|
155
|
+
task.status = 'completed';
|
|
156
|
+
|
|
157
|
+
// Only annotation is saved, task change is ignored ❌
|
|
158
|
+
await this._qaContext.saveChanges();
|
|
159
|
+
|
|
160
|
+
return annotation;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
### After (FIXED) ✅
|
|
166
|
+
|
|
167
|
+
**Option A: Use attach()**
|
|
168
|
+
|
|
169
|
+
```javascript
|
|
170
|
+
class AnnotationService {
|
|
171
|
+
constructor() {
|
|
172
|
+
this._qaContext = new QAContext();
|
|
173
|
+
this._taskService = new TaskService();
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
async createAnnotation(taskId, data) {
|
|
177
|
+
// Load task from different service
|
|
178
|
+
const task = await this._taskService.getTask(taskId);
|
|
179
|
+
|
|
180
|
+
// Create annotation
|
|
181
|
+
const annotation = this._qaContext.Annotation.new();
|
|
182
|
+
annotation.task_id = taskId;
|
|
183
|
+
annotation.data = data;
|
|
184
|
+
this._qaContext.Annotation.add(annotation);
|
|
185
|
+
|
|
186
|
+
// Modify task
|
|
187
|
+
task.status = 'completed';
|
|
188
|
+
|
|
189
|
+
// FIX: Attach detached task ✅
|
|
190
|
+
this._qaContext.attach(task);
|
|
191
|
+
|
|
192
|
+
// Both annotation and task are saved ✅
|
|
193
|
+
await this._qaContext.saveChanges();
|
|
194
|
+
|
|
195
|
+
return annotation;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
**Option B: Use attach() with specific fields**
|
|
201
|
+
|
|
202
|
+
```javascript
|
|
203
|
+
async createAnnotation(taskId, data) {
|
|
204
|
+
const task = await this._taskService.getTask(taskId);
|
|
205
|
+
|
|
206
|
+
// Create annotation
|
|
207
|
+
const annotation = this._qaContext.Annotation.new();
|
|
208
|
+
annotation.task_id = taskId;
|
|
209
|
+
annotation.data = data;
|
|
210
|
+
this._qaContext.Annotation.add(annotation);
|
|
211
|
+
|
|
212
|
+
// Attach with specific changes ✅
|
|
213
|
+
this._qaContext.attach(task, {
|
|
214
|
+
status: 'completed',
|
|
215
|
+
completed_at: new Date()
|
|
216
|
+
});
|
|
217
|
+
|
|
218
|
+
await this._qaContext.saveChanges();
|
|
219
|
+
return annotation;
|
|
220
|
+
}
|
|
221
|
+
```
|
|
222
|
+
|
|
223
|
+
**Option C: Use update() helper**
|
|
224
|
+
|
|
225
|
+
```javascript
|
|
226
|
+
async createAnnotation(taskId, data) {
|
|
227
|
+
// No need to load task first
|
|
228
|
+
|
|
229
|
+
// Create annotation
|
|
230
|
+
const annotation = this._qaContext.Annotation.new();
|
|
231
|
+
annotation.task_id = taskId;
|
|
232
|
+
annotation.data = data;
|
|
233
|
+
this._qaContext.Annotation.add(annotation);
|
|
234
|
+
|
|
235
|
+
// Update task by ID ✅
|
|
236
|
+
await this._qaContext.update('Task', taskId, {
|
|
237
|
+
status: 'completed',
|
|
238
|
+
completed_at: new Date()
|
|
239
|
+
});
|
|
240
|
+
|
|
241
|
+
await this._qaContext.saveChanges();
|
|
242
|
+
return annotation;
|
|
243
|
+
}
|
|
244
|
+
```
|
|
245
|
+
|
|
246
|
+
---
|
|
247
|
+
|
|
248
|
+
## Best Practices
|
|
249
|
+
|
|
250
|
+
### ✅ DO: Use One Context Per Request
|
|
251
|
+
|
|
252
|
+
```javascript
|
|
253
|
+
// Express middleware
|
|
254
|
+
app.use((req, res, next) => {
|
|
255
|
+
req.db = new AppContext(); // One context per request
|
|
256
|
+
res.on('finish', () => req.db.endRequest());
|
|
257
|
+
next();
|
|
258
|
+
});
|
|
259
|
+
|
|
260
|
+
// Service uses the request context
|
|
261
|
+
class AnnotationService {
|
|
262
|
+
async createAnnotation(db, taskId, data) {
|
|
263
|
+
// Use passed-in context
|
|
264
|
+
const task = db.Task.findById(taskId); // Loaded in same context ✅
|
|
265
|
+
task.status = 'completed'; // Already tracked ✅
|
|
266
|
+
|
|
267
|
+
const annotation = db.Annotation.new();
|
|
268
|
+
annotation.task_id = taskId;
|
|
269
|
+
db.Annotation.add(annotation);
|
|
270
|
+
|
|
271
|
+
await db.saveChanges(); // Both changes saved ✅
|
|
272
|
+
return annotation;
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
// Controller
|
|
277
|
+
app.post('/annotations', async (req, res) => {
|
|
278
|
+
const annotationService = new AnnotationService();
|
|
279
|
+
const annotation = await annotationService.createAnnotation(
|
|
280
|
+
req.db, // Pass request context ✅
|
|
281
|
+
req.body.taskId,
|
|
282
|
+
req.body.data
|
|
283
|
+
);
|
|
284
|
+
res.json(annotation);
|
|
285
|
+
});
|
|
286
|
+
```
|
|
287
|
+
|
|
288
|
+
### ✅ DO: Load in Same Context
|
|
289
|
+
|
|
290
|
+
```javascript
|
|
291
|
+
// ❌ BAD: Different contexts
|
|
292
|
+
const taskService = new TaskService(); // Has own context
|
|
293
|
+
const qaContext = new QAContext(); // Different context
|
|
294
|
+
const task = await taskService.getTask(taskId); // Loaded in taskService context
|
|
295
|
+
task.status = 'completed';
|
|
296
|
+
qaContext.saveChanges(); // Doesn't see change ❌
|
|
297
|
+
|
|
298
|
+
// ✅ GOOD: Same context
|
|
299
|
+
const db = new AppContext();
|
|
300
|
+
const task = db.Task.findById(taskId); // Loaded in db context
|
|
301
|
+
task.status = 'completed'; // Already tracked
|
|
302
|
+
await db.saveChanges(); // Change saved ✅
|
|
303
|
+
```
|
|
304
|
+
|
|
305
|
+
### ✅ DO: Use attach() for Detached Entities
|
|
306
|
+
|
|
307
|
+
```javascript
|
|
308
|
+
// When you must use entities from different contexts
|
|
309
|
+
const task = await externalService.getTask(taskId); // Detached
|
|
310
|
+
task.status = 'completed';
|
|
311
|
+
db.attach(task); // Re-attach ✅
|
|
312
|
+
await db.saveChanges();
|
|
313
|
+
```
|
|
314
|
+
|
|
315
|
+
### ❌ DON'T: Modify Detached Entities Without Attaching
|
|
316
|
+
|
|
317
|
+
```javascript
|
|
318
|
+
// ❌ BAD
|
|
319
|
+
const task = await someService.getTask(taskId);
|
|
320
|
+
task.status = 'completed';
|
|
321
|
+
db.saveChanges(); // Won't work!
|
|
322
|
+
|
|
323
|
+
// ✅ GOOD
|
|
324
|
+
const task = await someService.getTask(taskId);
|
|
325
|
+
task.status = 'completed';
|
|
326
|
+
db.attach(task); // Attach first!
|
|
327
|
+
await db.saveChanges();
|
|
328
|
+
```
|
|
329
|
+
|
|
330
|
+
---
|
|
331
|
+
|
|
332
|
+
## Comparison Table
|
|
333
|
+
|
|
334
|
+
| ORM | Method | Example |
|
|
335
|
+
|-----|--------|---------|
|
|
336
|
+
| **Entity Framework** | `context.Update(entity)` | `context.Update(task);` |
|
|
337
|
+
| **Hibernate** | `session.merge(entity)` | `session.merge(task);` |
|
|
338
|
+
| **Active Record** | `entity.save()` | `task.save` |
|
|
339
|
+
| **Sequelize** | `entity.save()` | `await task.save()` |
|
|
340
|
+
| **MasterRecord** | `context.attach(entity)` | `db.attach(task);` |
|
|
341
|
+
|
|
342
|
+
---
|
|
343
|
+
|
|
344
|
+
## API Reference
|
|
345
|
+
|
|
346
|
+
### attach(entity, changes?)
|
|
347
|
+
|
|
348
|
+
Attach a detached entity and mark as modified.
|
|
349
|
+
|
|
350
|
+
**Parameters:**
|
|
351
|
+
- `entity` - The detached entity
|
|
352
|
+
- `changes` (optional) - Object with specific field changes
|
|
353
|
+
|
|
354
|
+
**Returns:** The attached entity
|
|
355
|
+
|
|
356
|
+
**Example:**
|
|
357
|
+
```javascript
|
|
358
|
+
// Attach entire entity
|
|
359
|
+
db.attach(task);
|
|
360
|
+
|
|
361
|
+
// Attach with specific changes
|
|
362
|
+
db.attach(task, { status: 'completed' });
|
|
363
|
+
```
|
|
364
|
+
|
|
365
|
+
### attachAll(entities)
|
|
366
|
+
|
|
367
|
+
Attach multiple entities at once.
|
|
368
|
+
|
|
369
|
+
**Parameters:**
|
|
370
|
+
- `entities` - Array of detached entities
|
|
371
|
+
|
|
372
|
+
**Returns:** Array of attached entities
|
|
373
|
+
|
|
374
|
+
**Example:**
|
|
375
|
+
```javascript
|
|
376
|
+
const tasks = await getTasks();
|
|
377
|
+
tasks.forEach(t => t.status = 'completed');
|
|
378
|
+
db.attachAll(tasks);
|
|
379
|
+
await db.saveChanges();
|
|
380
|
+
```
|
|
381
|
+
|
|
382
|
+
### update(entityName, primaryKey, changes)
|
|
383
|
+
|
|
384
|
+
Update entity by primary key without loading.
|
|
385
|
+
|
|
386
|
+
**Parameters:**
|
|
387
|
+
- `entityName` - Name of entity (e.g., 'Task')
|
|
388
|
+
- `primaryKey` - Primary key value
|
|
389
|
+
- `changes` - Object with field changes
|
|
390
|
+
|
|
391
|
+
**Returns:** The attached entity
|
|
392
|
+
|
|
393
|
+
**Example:**
|
|
394
|
+
```javascript
|
|
395
|
+
await db.update('Task', taskId, {
|
|
396
|
+
status: 'completed',
|
|
397
|
+
completed_at: new Date()
|
|
398
|
+
});
|
|
399
|
+
await db.saveChanges();
|
|
400
|
+
```
|
|
401
|
+
|
|
402
|
+
---
|
|
403
|
+
|
|
404
|
+
## Troubleshooting
|
|
405
|
+
|
|
406
|
+
### Changes not saving?
|
|
407
|
+
|
|
408
|
+
**Check:**
|
|
409
|
+
1. Is entity tracked? `console.log(db.__trackedEntities.includes(entity))`
|
|
410
|
+
2. Is entity state correct? `console.log(entity.__state)` (should be "modified")
|
|
411
|
+
3. Are dirty fields marked? `console.log(entity.__dirtyFields)`
|
|
412
|
+
|
|
413
|
+
**Fix:**
|
|
414
|
+
```javascript
|
|
415
|
+
// If not tracked, attach it
|
|
416
|
+
if (!db.__trackedEntities.includes(entity)) {
|
|
417
|
+
db.attach(entity);
|
|
418
|
+
}
|
|
419
|
+
```
|
|
420
|
+
|
|
421
|
+
### "Entity must have __entity metadata" error?
|
|
422
|
+
|
|
423
|
+
**Cause:** Entity wasn't loaded through MasterRecord
|
|
424
|
+
|
|
425
|
+
**Fix:**
|
|
426
|
+
```javascript
|
|
427
|
+
// ❌ BAD: Plain object
|
|
428
|
+
const task = { id: 1, status: 'completed' };
|
|
429
|
+
db.attach(task); // Error!
|
|
430
|
+
|
|
431
|
+
// ✅ GOOD: Load through MasterRecord
|
|
432
|
+
const task = db.Task.findById(1);
|
|
433
|
+
task.status = 'completed';
|
|
434
|
+
db.attach(task); // Works!
|
|
435
|
+
```
|
|
436
|
+
|
|
437
|
+
---
|
|
438
|
+
|
|
439
|
+
## Summary
|
|
440
|
+
|
|
441
|
+
**The detached entity problem** happens when:
|
|
442
|
+
1. Entity loaded in one context
|
|
443
|
+
2. Passed to different context/service
|
|
444
|
+
3. Modified
|
|
445
|
+
4. saveChanges() called but doesn't see modification
|
|
446
|
+
|
|
447
|
+
**Solutions:**
|
|
448
|
+
1. ✅ Use **`attach()`** to re-attach detached entities (like Entity Framework)
|
|
449
|
+
2. ✅ Use **same context** throughout request (best practice)
|
|
450
|
+
3. ✅ Pass context to services instead of creating multiple contexts
|
|
451
|
+
4. ✅ Use **`update()`** helper for simple updates
|
|
452
|
+
|
|
453
|
+
**MasterRecord now handles this like Entity Framework!** 🎉
|
|
@@ -0,0 +1,219 @@
|
|
|
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.
|