masterrecord 1.1.0 → 1.1.1
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 +58 -197
- package/docs/FULL_TEXT_SEARCH.md +219 -0
- package/docs/METHODS_REFERENCE.md +15 -0
- package/docs/MIGRATIONS_GUIDE.md +35 -0
- package/docs/POSTGRESQL_SETUP.md +3 -3
- package/package.json +1 -1
- package/readme.md +47 -12
- package/.github/FUTURE_IMPROVEMENTS.md +0 -138
- package/FOREIGN_KEY_STRING_FIX.md +0 -288
- package/GLOBAL_REGISTRY_VERIFICATION.md +0 -375
package/CHANGES.md
CHANGED
|
@@ -1,199 +1,60 @@
|
|
|
1
1
|
# MasterRecord Changelog
|
|
2
2
|
|
|
3
|
-
## v1.
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
-
|
|
14
|
-
-
|
|
15
|
-
-
|
|
16
|
-
-
|
|
17
|
-
-
|
|
18
|
-
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
##
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
console.log('[Context] Config search errors:', searchErrors.join('; '));
|
|
62
|
-
```
|
|
63
|
-
|
|
64
|
-
### 4. ✅ Input Validation
|
|
65
|
-
**Issue:** No validation on dbset() - crashes and SQL injection risk
|
|
66
|
-
**Fix:** Validate model and table name
|
|
67
|
-
```javascript
|
|
68
|
-
if(!model) throw new Error('dbset() requires a valid model');
|
|
69
|
-
if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(tableName)){
|
|
70
|
-
throw new Error(`Invalid table name: ${tableName}`);
|
|
71
|
-
}
|
|
72
|
-
```
|
|
73
|
-
|
|
74
|
-
### 5. ✅ Code Style
|
|
75
|
-
**Issue:** Mixed var/const/let
|
|
76
|
-
**Fix:** Use const/let consistently (FAANG standard)
|
|
77
|
-
|
|
78
|
-
## Performance Improvements
|
|
79
|
-
- Entity tracking: O(n) → O(1) [100x faster]
|
|
80
|
-
- ID generation: Zero collision risk
|
|
81
|
-
- Better error messages for debugging
|
|
82
|
-
|
|
83
|
-
## Breaking Changes
|
|
84
|
-
**PostgreSQL users:** Must now await the `env()` method
|
|
85
|
-
```javascript
|
|
86
|
-
// OLD:
|
|
87
|
-
ctx.env('./config');
|
|
88
|
-
|
|
89
|
-
// NEW:
|
|
90
|
-
await ctx.env('./config');
|
|
91
|
-
```
|
|
92
|
-
|
|
93
|
-
## Files Updated
|
|
94
|
-
- ✅ context.js v1.0.0 (critical bug fixes + performance)
|
|
95
|
-
- ✅ deleteManager.js v1.0.0 (error handling + code quality)
|
|
96
|
-
|
|
97
|
-
## Additional Files
|
|
98
|
-
- .eslintrc.js (FAANG linting rules)
|
|
99
|
-
- .prettierrc.js (code formatting)
|
|
100
|
-
|
|
101
|
-
---
|
|
102
|
-
|
|
103
|
-
## DeleteManager.js Improvements
|
|
104
|
-
|
|
105
|
-
### Critical Fixes Applied
|
|
106
|
-
|
|
107
|
-
#### 1. ✅ Proper Error Handling
|
|
108
|
-
**Issue:** Threw string instead of Error object
|
|
109
|
-
**Fix:** Now throws Error objects with context
|
|
110
|
-
```javascript
|
|
111
|
-
// OLD:
|
|
112
|
-
throw "No relationship record found - please set hasOne or hasMany to nullable."
|
|
113
|
-
|
|
114
|
-
// NEW:
|
|
115
|
-
throw new Error(
|
|
116
|
-
`Cannot delete ${entity.__entity.__name}: ` +
|
|
117
|
-
`required relationship '${property}' is null. ` +
|
|
118
|
-
`Set nullable: true if this is intentional.`
|
|
119
|
-
);
|
|
120
|
-
```
|
|
121
|
-
|
|
122
|
-
#### 2. ✅ Input Validation
|
|
123
|
-
**Issue:** No validation on currentModel parameter
|
|
124
|
-
**Fix:** Validates inputs before processing
|
|
125
|
-
```javascript
|
|
126
|
-
if (!currentModel) {
|
|
127
|
-
throw new Error('DeleteManager.init() requires a valid model');
|
|
128
|
-
}
|
|
129
|
-
if (!entity.__entity) {
|
|
130
|
-
throw new Error('Entity missing __entity metadata');
|
|
131
|
-
}
|
|
132
|
-
```
|
|
133
|
-
|
|
134
|
-
#### 3. ✅ Null Safety
|
|
135
|
-
**Issue:** Didn't handle null entities in arrays
|
|
136
|
-
**Fix:** Warns and skips null entities safely
|
|
137
|
-
```javascript
|
|
138
|
-
if (!entity) {
|
|
139
|
-
console.warn(`DeleteManager: Skipping null entity at index ${i}`);
|
|
140
|
-
continue;
|
|
141
|
-
}
|
|
142
|
-
```
|
|
143
|
-
|
|
144
|
-
#### 4. ✅ Code Quality Refactoring
|
|
145
|
-
**Issue:** Duplicate code for single entity vs array handling
|
|
146
|
-
**Fix:** Extracted into focused methods
|
|
147
|
-
```javascript
|
|
148
|
-
// Now split into clear, testable methods:
|
|
149
|
-
_deleteSingleEntity(entity) // Handle one entity
|
|
150
|
-
_deleteMultipleEntities(entities) // Handle array
|
|
151
|
-
_isRelationshipType(type) // Type checking helper
|
|
152
|
-
```
|
|
153
|
-
|
|
154
|
-
#### 5. ✅ Constants for Relationship Types
|
|
155
|
-
**Issue:** Magic strings ("hasOne", "hasMany") throughout code
|
|
156
|
-
**Fix:** Constants at module level
|
|
157
|
-
```javascript
|
|
158
|
-
const RELATIONSHIP_TYPES = {
|
|
159
|
-
HAS_ONE: 'hasOne',
|
|
160
|
-
HAS_MANY: 'hasMany',
|
|
161
|
-
HAS_MANY_THROUGH: 'hasManyThrough'
|
|
162
|
-
};
|
|
163
|
-
```
|
|
164
|
-
|
|
165
|
-
### Code Quality Improvements
|
|
166
|
-
- Comprehensive JSDoc documentation
|
|
167
|
-
- Modern JavaScript (const/let, no var)
|
|
168
|
-
- Removed unused `$that = this` pattern
|
|
169
|
-
- Better error messages with context
|
|
170
|
-
- Reduced cyclomatic complexity
|
|
171
|
-
|
|
172
|
-
### Example Usage
|
|
173
|
-
```javascript
|
|
174
|
-
// Clear error messages guide developers
|
|
175
|
-
const user = db.User.findById(1);
|
|
176
|
-
|
|
177
|
-
try {
|
|
178
|
-
db.User.remove(user);
|
|
179
|
-
db.saveChanges();
|
|
180
|
-
} catch (error) {
|
|
181
|
-
console.error(error.message);
|
|
182
|
-
// "Cannot delete User: required relationship 'Profile' is null.
|
|
183
|
-
// Set nullable: true if this is intentional."
|
|
184
|
-
}
|
|
185
|
-
```
|
|
186
|
-
|
|
187
|
-
---
|
|
188
|
-
|
|
189
|
-
## Context.js Improvements (Previously Applied)
|
|
190
|
-
|
|
191
|
-
## Next Steps
|
|
192
|
-
1. Update PostgreSQL initialization calls to use `await`
|
|
193
|
-
2. Run `npm install --save-dev eslint prettier`
|
|
194
|
-
3. Run `npm run lint` to check for any remaining issues
|
|
195
|
-
4. Test thoroughly before deploying
|
|
196
|
-
|
|
197
|
-
## Grade
|
|
198
|
-
**Before:** C+ (Needs Improvement)
|
|
199
|
-
**After:** A (Production Ready)
|
|
3
|
+
## v1.1.1 — Documentation
|
|
4
|
+
|
|
5
|
+
- 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).
|
|
6
|
+
- Documented `createFullTextIndex` / `dropFullTextIndex` in [`docs/MIGRATIONS_GUIDE.md`](docs/MIGRATIONS_GUIDE.md).
|
|
7
|
+
- Removed stale per-bug postmortem markdown files (kept their fixes; deleted the writeups).
|
|
8
|
+
|
|
9
|
+
## v1.1.0 — Portable Full-Text Search
|
|
10
|
+
|
|
11
|
+
A single API that targets each engine's native FTS implementation.
|
|
12
|
+
|
|
13
|
+
- **Migrations** — `createFullTextIndex({ tableName, columns, indexName?, config? })` and `dropFullTextIndex({ tableName, indexName? })`:
|
|
14
|
+
- **SQLite** — FTS5 external-content virtual table + AFTER INSERT/UPDATE/DELETE triggers
|
|
15
|
+
- **PostgreSQL** — `tsvector` column + GIN index + maintenance trigger (`config` controls `to_tsvector` config, default `'english'`)
|
|
16
|
+
- **MySQL** — `ALTER TABLE … ADD FULLTEXT INDEX`
|
|
17
|
+
- **Runtime** — `.search({ in: [columns], query: 'terms' })` fluent method on any dbset. Composes with `.where()`, `.take()`, `.skip()`, `.orderBy()`. Each result row has a `__rank` field; default ordering is rank descending.
|
|
18
|
+
- 17 new tests cover DDL output per engine, generated SQL strings, and an end-to-end SQLite ranking test.
|
|
19
|
+
|
|
20
|
+
## v1.0.8 — Idempotent dropColumn + Postgres getTableInfo
|
|
21
|
+
|
|
22
|
+
- `dropColumn` is now idempotent across all engines (uses `IF EXISTS` where supported; no-op when the column is already gone).
|
|
23
|
+
- PostgreSQL: implemented `getTableInfo()` against `information_schema.columns` so introspection-driven migrations work.
|
|
24
|
+
|
|
25
|
+
## v1.0.7 — Postgres identifier quoting + cross-engine cleanup
|
|
26
|
+
|
|
27
|
+
- PostgreSQL: all generated DDL and DML now quotes identifiers (`"camelCase"`, `"updatedAt"`, etc.) so mixed-case entity and column names work. Previously these were lowercased silently by Postgres, breaking queries.
|
|
28
|
+
- Removed accidental case transformations from `buildWhere` / `buildAnd` in the SQLite, MySQL, and Postgres engines — field names are now used as declared.
|
|
29
|
+
- MySQL: `bulkDelete` honors the entity's actual primary key column instead of hard-coding `id`.
|
|
30
|
+
|
|
31
|
+
## v1.0.x — Bug fixes
|
|
32
|
+
|
|
33
|
+
- `.new()` setter with `transform.toDatabase`: object-valued fields were silently dropped on save. Now applied via the field transformer.
|
|
34
|
+
- Nested-array property assignment no longer corrupts adjacent fields.
|
|
35
|
+
- SQLite engine: absolute paths in `connection` were being concatenated with the project root, producing `/abs//abs/path`. Now passed through unchanged.
|
|
36
|
+
- Query builder parity: `ORDER BY`, `LIMIT`, `OFFSET`, `AND`, and `COUNT` are emitted consistently across all three engines. Previously each engine had a different subset of dropped clauses depending on the call path.
|
|
37
|
+
- CLI `update-database`: now applies every pending migration via a tracking table, not just the latest file.
|
|
38
|
+
|
|
39
|
+
## v1.0.0 — ESM only
|
|
40
|
+
|
|
41
|
+
**BREAKING:** Pure ESM. Requires **Node.js 20+** and `"type": "module"` in the host project's `package.json`. No CommonJS build.
|
|
42
|
+
|
|
43
|
+
- All sources moved from `require` / `module.exports` to `import` / `export default`.
|
|
44
|
+
- Static import of `better-sqlite3` in `context.js` (no more runtime `require(sqlName)`).
|
|
45
|
+
- Environment config files and migration snapshot files load via `fs.readFileSync` + `JSON.parse` instead of `require()` — `context.env()` stays synchronous.
|
|
46
|
+
- User-authored migration files load via `await import(pathToFileURL(file).href)`. The CJS `Module.prototype.require` aliasing hook is gone; host projects must install `masterrecord` as a local dependency.
|
|
47
|
+
- `Migrations/migrationTemplate.js` emits ESM migrations only.
|
|
48
|
+
- `context.js` exports the default class plus named error classes (`ContextError`, `ConfigurationError`, `DatabaseConnectionError`, `EntityValidationError`).
|
|
49
|
+
- `Cache/QueryCache.js` cleanup timer is `.unref()`'d so it no longer keeps the event loop alive.
|
|
50
|
+
- Lint / format configs migrated to flat ESM (`eslint.config.js`, `prettier.config.js`).
|
|
51
|
+
- Test suite rewritten on `node --test`.
|
|
52
|
+
|
|
53
|
+
### Upgrading
|
|
54
|
+
|
|
55
|
+
1. Node 20 or newer.
|
|
56
|
+
2. `"type": "module"` in your `package.json`.
|
|
57
|
+
3. `require('masterrecord/…')` → `import X from 'masterrecord/…'`.
|
|
58
|
+
4. `module.exports = MyContext` → `export default MyContext`.
|
|
59
|
+
5. Add `.js` extensions to all relative imports (ESM requires explicit extensions).
|
|
60
|
+
6. Regenerate migration files (or update the top/bottom): `import masterrecord from 'masterrecord';` … `export default <Name>;`.
|
|
@@ -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.
|
|
@@ -53,6 +53,7 @@ context.User.where(u => $$.includes(u.id), [1, 2, 3]).toList();
|
|
|
53
53
|
| `.orderByDescending(lambda)` | Sort descending | `.orderByDescending(u => u.created_at)` |
|
|
54
54
|
| `.take(n)` | Limit results | `.take(10)` |
|
|
55
55
|
| `.skip(n)` | Offset results | `.skip(20)` |
|
|
56
|
+
| `.search({ in, query })` | Full-text search (see [FULL_TEXT_SEARCH.md](FULL_TEXT_SEARCH.md)) | `context.MemoryDoc.search({ in: ['title','body'], query: 'auth login' })` |
|
|
56
57
|
| `.toList()` | Execute and return array | `.where(...).toList()` |
|
|
57
58
|
| `.single()` | Execute and return one | `.where(...).single()` |
|
|
58
59
|
| `.first()` | Execute and return first | `.where(...).first()` |
|
|
@@ -124,6 +125,20 @@ const activeUsers = context.User
|
|
|
124
125
|
.toList();
|
|
125
126
|
```
|
|
126
127
|
|
|
128
|
+
### Full-Text Search
|
|
129
|
+
|
|
130
|
+
```javascript
|
|
131
|
+
// Requires a migration with createFullTextIndex(); see docs/FULL_TEXT_SEARCH.md
|
|
132
|
+
const docs = await context.MemoryDoc
|
|
133
|
+
.search({ in: ['title', 'body'], query: 'auth login' })
|
|
134
|
+
.where(d => d.workspace_id == $$, workspaceId)
|
|
135
|
+
.take(10)
|
|
136
|
+
.toList();
|
|
137
|
+
|
|
138
|
+
// Each row has a __rank field (engine-specific scale)
|
|
139
|
+
docs.forEach(d => console.log(d.__rank, d.title));
|
|
140
|
+
```
|
|
141
|
+
|
|
127
142
|
---
|
|
128
143
|
|
|
129
144
|
## Why Your LLM Might Be Confused
|
package/docs/MIGRATIONS_GUIDE.md
CHANGED
|
@@ -186,6 +186,41 @@ class MakeAgeRequired extends masterrecord.schema {
|
|
|
186
186
|
export default MakeAgeRequired;
|
|
187
187
|
```
|
|
188
188
|
|
|
189
|
+
### Full-text search indexes
|
|
190
|
+
|
|
191
|
+
Create and drop portable FTS indexes. Each engine emits its native equivalent — FTS5 virtual table + triggers on SQLite, `tsvector` column + GIN index + maintenance trigger on PostgreSQL, `FULLTEXT INDEX` on MySQL.
|
|
192
|
+
|
|
193
|
+
```javascript
|
|
194
|
+
import masterrecord from 'masterrecord';
|
|
195
|
+
|
|
196
|
+
class AddMemoryDocFts extends masterrecord.schema {
|
|
197
|
+
async up(table) {
|
|
198
|
+
await this.init(table);
|
|
199
|
+
await this.createTable(table.MemoryDoc);
|
|
200
|
+
await this.createFullTextIndex({
|
|
201
|
+
tableName: 'MemoryDoc',
|
|
202
|
+
columns: ['title', 'body'],
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
async down(table) {
|
|
207
|
+
await this.init(table);
|
|
208
|
+
await this.dropFullTextIndex({ tableName: 'MemoryDoc' });
|
|
209
|
+
await this.dropTable(table.MemoryDoc);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
export default AddMemoryDocFts;
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
`createFullTextIndex(info)` accepts:
|
|
217
|
+
- `tableName` (string, required)
|
|
218
|
+
- `columns` (string[], required) — columns to index
|
|
219
|
+
- `indexName` (string, optional) — overrides the generated name (`idx_<table>_fts`)
|
|
220
|
+
- `config` (string, optional) — Postgres-only `to_tsvector` config (defaults to `'english'`)
|
|
221
|
+
|
|
222
|
+
Runtime querying uses the matching `.search({ in, query })` dbset method — see [FULL_TEXT_SEARCH.md](FULL_TEXT_SEARCH.md) for engine-specific query syntax and ranking caveats.
|
|
223
|
+
|
|
189
224
|
### Renaming columns
|
|
190
225
|
|
|
191
226
|
```javascript
|
package/docs/POSTGRESQL_SETUP.md
CHANGED
|
@@ -344,10 +344,10 @@ node test/postgresIntegrationTest.js
|
|
|
344
344
|
|
|
345
345
|
## Version Compatibility
|
|
346
346
|
|
|
347
|
-
- **MasterRecord**:
|
|
348
|
-
- **pg (node-postgres)**: 8.
|
|
347
|
+
- **MasterRecord**: 1.0+ (ESM-only)
|
|
348
|
+
- **pg (node-postgres)**: 8.17+
|
|
349
349
|
- **PostgreSQL Server**: 9.6+ (tested with 12+, 13+, 14+)
|
|
350
|
-
- **Node.js**: 20+
|
|
350
|
+
- **Node.js**: 20+
|
|
351
351
|
|
|
352
352
|
## Complete Example
|
|
353
353
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "masterrecord",
|
|
3
|
-
"version": "1.1.
|
|
3
|
+
"version": "1.1.1",
|
|
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",
|
package/readme.md
CHANGED
|
@@ -17,6 +17,7 @@
|
|
|
17
17
|
🔹 **Lifecycle Hooks** - `beforeSave`, `afterSave`, `beforeDelete`, `afterDelete` hooks
|
|
18
18
|
🔹 **Business Validation** - Built-in validators (required, email, length, pattern, custom)
|
|
19
19
|
🔹 **Bulk Operations** - Efficient `bulkCreate`, `bulkUpdate`, `bulkDelete` APIs
|
|
20
|
+
🔹 **Full-Text Search** - Portable `.search()` API on top of SQLite FTS5, Postgres `tsvector`, and MySQL `FULLTEXT`
|
|
20
21
|
🔹 **Query Result Caching** - Production-grade in-memory and Redis caching with automatic invalidation
|
|
21
22
|
🔹 **Migration System** - CLI-driven migrations with rollback support
|
|
22
23
|
🔹 **SQL Injection Protection** - Automatic parameterized queries throughout
|
|
@@ -40,6 +41,7 @@
|
|
|
40
41
|
- [Database Configuration](#database-configuration)
|
|
41
42
|
- [Entity Definitions](#entity-definitions)
|
|
42
43
|
- [Querying](#querying)
|
|
44
|
+
- [Full-Text Search](#full-text-search)
|
|
43
45
|
- [Entity Serialization](#entity-serialization)
|
|
44
46
|
- [.toObject()](#toobjectoptions)
|
|
45
47
|
- [.toJSON()](#tojson)
|
|
@@ -706,6 +708,50 @@ const matching = await db.User
|
|
|
706
708
|
.toList();
|
|
707
709
|
```
|
|
708
710
|
|
|
711
|
+
## Full-Text Search
|
|
712
|
+
|
|
713
|
+
Portable full-text search that runs on each engine's native FTS implementation: FTS5 on SQLite, `tsvector` + GIN on PostgreSQL, `FULLTEXT INDEX` on MySQL. Use it when `LIKE` isn't enough — when you want stemming, tokenization, multi-word queries, and ranking.
|
|
714
|
+
|
|
715
|
+
### Set up the index in a migration
|
|
716
|
+
|
|
717
|
+
```javascript
|
|
718
|
+
import masterrecord from 'masterrecord';
|
|
719
|
+
|
|
720
|
+
class AddMemoryDocFts extends masterrecord.schema {
|
|
721
|
+
async up(table) {
|
|
722
|
+
await this.init(table);
|
|
723
|
+
await this.createTable(table.MemoryDoc);
|
|
724
|
+
await this.createFullTextIndex({
|
|
725
|
+
tableName: 'MemoryDoc',
|
|
726
|
+
columns: ['title', 'body'],
|
|
727
|
+
});
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
async down(table) {
|
|
731
|
+
await this.init(table);
|
|
732
|
+
await this.dropFullTextIndex({ tableName: 'MemoryDoc' });
|
|
733
|
+
await this.dropTable(table.MemoryDoc);
|
|
734
|
+
}
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
export default AddMemoryDocFts;
|
|
738
|
+
```
|
|
739
|
+
|
|
740
|
+
### Query
|
|
741
|
+
|
|
742
|
+
```javascript
|
|
743
|
+
const docs = await db.MemoryDoc
|
|
744
|
+
.search({ in: ['title', 'body'], query: 'auth login' })
|
|
745
|
+
.where(d => d.workspace_id == $$, workspaceId)
|
|
746
|
+
.take(10)
|
|
747
|
+
.toList();
|
|
748
|
+
|
|
749
|
+
// Each row has a __rank field; default ordering is rank descending.
|
|
750
|
+
for (const d of docs) console.log(d.__rank, d.title);
|
|
751
|
+
```
|
|
752
|
+
|
|
753
|
+
`.search()` composes with `.where()`, `.take()`, `.skip()`, and `.orderBy()`. Engine-specific query syntax (FTS5's `NEAR` / prefix, Postgres `to_tsquery` operators, MySQL boolean mode), ranking semantics, and engine caveats are documented in [docs/FULL_TEXT_SEARCH.md](./docs/FULL_TEXT_SEARCH.md).
|
|
754
|
+
|
|
709
755
|
## Migrations
|
|
710
756
|
|
|
711
757
|
### CLI Commands
|
|
@@ -3377,15 +3423,4 @@ user.name = null; // Error if name is { nullable: false }
|
|
|
3377
3423
|
|
|
3378
3424
|
## Changelog
|
|
3379
3425
|
|
|
3380
|
-
|
|
3381
|
-
|
|
3382
|
-
#### Bug Fixed: `createIndex` called twice for new tables during `update-database`
|
|
3383
|
-
- **FIXED**: When running `update-database` with a new table that has indexes, the indexes were created twice — once by `createTable()` in schema.js (which iterates column `.index()` definitions and `__compositeIndexes`), and again by explicit `createIndex()`/`createCompositeIndex()` calls in the generated migration file
|
|
3384
|
-
- **Symptom**: MySQL error `Duplicate key name 'idx_...'` during InitialCreate migrations
|
|
3385
|
-
- **Root Cause**: `migrations.js` `#findNewIndexes()` and `#findNewCompositeIndexes()` added index operations for ALL tables, including brand new ones where `createTable()` already handles them
|
|
3386
|
-
- **Solution**: Skip index generation in migration template for new tables (`item.newTables.length > 0`). For existing tables getting new indexes, explicit `createIndex` calls are still generated correctly.
|
|
3387
|
-
|
|
3388
|
-
#### Files Modified
|
|
3389
|
-
1. **`Migrations/migrations.js`** - Skip `newIndexes` and `newCompositeIndexes` for new tables in `#findNewIndexes()` and `#findNewCompositeIndexes()`
|
|
3390
|
-
2. **`test/v0.3.34-bug-fixes-test.js`** - Updated tests to verify correct behavior + added tests for adding indexes to existing tables
|
|
3391
|
-
3. **`package.json`** - Updated to v0.3.49
|
|
3426
|
+
See [CHANGES.md](./CHANGES.md) for the full version history.
|