masterrecord 1.0.8 → 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/Migrations/migrationMySQLQuery.js +33 -0
- package/Migrations/migrationPostgresQuery.js +98 -0
- package/Migrations/migrationSQLiteQuery.js +53 -0
- package/Migrations/schema.js +58 -0
- package/QueryLanguage/queryMethods.js +47 -0
- package/QueryLanguage/queryScript.js +5 -0
- package/SQLLiteEngine.js +43 -1
- 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/mySQLEngine.js +46 -0
- package/package.json +1 -1
- package/postgresEngine.js +50 -1
- package/readme.md +47 -12
- package/test/full-text-search.test.js +340 -0
- 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>;`.
|
|
@@ -281,6 +281,39 @@ class migrationMySQLQuery {
|
|
|
281
281
|
return `DROP INDEX \`${indexInfo.indexName}\` ON \`${indexInfo.tableName}\``;
|
|
282
282
|
}
|
|
283
283
|
|
|
284
|
+
_ftsIndexName(tableName, indexName) {
|
|
285
|
+
return indexName || `idx_${tableName.toLowerCase()}_fts`;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/**
|
|
289
|
+
* Build the DDL that adds a MySQL FULLTEXT index to a table. MySQL
|
|
290
|
+
* maintains the index automatically — no triggers needed. Requires
|
|
291
|
+
* MySQL 5.6+ (InnoDB) or any MyISAM table.
|
|
292
|
+
*
|
|
293
|
+
* @param {object} info
|
|
294
|
+
* @param {string} info.tableName
|
|
295
|
+
* @param {string[]} info.columns
|
|
296
|
+
* @param {string} [info.indexName]
|
|
297
|
+
* @returns {string[]}
|
|
298
|
+
*/
|
|
299
|
+
createFullTextIndex(info){
|
|
300
|
+
const idxName = this._ftsIndexName(info.tableName, info.indexName);
|
|
301
|
+
const cols = info.columns.map(c => `\`${c}\``).join(', ');
|
|
302
|
+
return [
|
|
303
|
+
`ALTER TABLE \`${info.tableName}\` ADD FULLTEXT INDEX \`${idxName}\` (${cols})`,
|
|
304
|
+
];
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/**
|
|
308
|
+
* Drop the FULLTEXT index created by createFullTextIndex.
|
|
309
|
+
*/
|
|
310
|
+
dropFullTextIndex(info){
|
|
311
|
+
const idxName = this._ftsIndexName(info.tableName, info.indexName);
|
|
312
|
+
return [
|
|
313
|
+
`ALTER TABLE \`${info.tableName}\` DROP INDEX \`${idxName}\``,
|
|
314
|
+
];
|
|
315
|
+
}
|
|
316
|
+
|
|
284
317
|
/**
|
|
285
318
|
* SEED DATA METHODS
|
|
286
319
|
* Support for inserting seed data during migrations
|
|
@@ -263,6 +263,104 @@ class migrationPostgresQuery {
|
|
|
263
263
|
return `DROP INDEX IF EXISTS "${indexInfo.indexName}"`;
|
|
264
264
|
}
|
|
265
265
|
|
|
266
|
+
/**
|
|
267
|
+
* Default name for the tsvector column added by createFullTextIndex.
|
|
268
|
+
*/
|
|
269
|
+
_ftsColumnName() { return '__tsv'; }
|
|
270
|
+
|
|
271
|
+
/**
|
|
272
|
+
* Default name for the GIN index added by createFullTextIndex.
|
|
273
|
+
*/
|
|
274
|
+
_ftsIndexName(tableName, indexName) {
|
|
275
|
+
return indexName || `idx_${tableName.toLowerCase()}_fts`;
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/**
|
|
279
|
+
* Default name for the trigger function maintained by createFullTextIndex.
|
|
280
|
+
*/
|
|
281
|
+
_ftsTriggerFunctionName(tableName) {
|
|
282
|
+
return `${tableName.toLowerCase()}_tsv_update`;
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/**
|
|
286
|
+
* Default name for the trigger maintained by createFullTextIndex.
|
|
287
|
+
*/
|
|
288
|
+
_ftsTriggerName(tableName) {
|
|
289
|
+
return `${tableName.toLowerCase()}_tsv_trigger`;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* Build the DDL statements that create a Postgres tsvector full-text
|
|
294
|
+
* index on a table. The strategy:
|
|
295
|
+
* 1. Add a tsvector column (`__tsv` by default).
|
|
296
|
+
* 2. Backfill it from existing rows using to_tsvector('english', ...).
|
|
297
|
+
* 3. Create a GIN index on the column.
|
|
298
|
+
* 4. Create a BEFORE INSERT/UPDATE trigger that keeps __tsv in sync.
|
|
299
|
+
*
|
|
300
|
+
* @param {object} info
|
|
301
|
+
* @param {string} info.tableName
|
|
302
|
+
* @param {string[]} info.columns - Source columns to concatenate into the tsvector.
|
|
303
|
+
* @param {string} [info.indexName] - Override the GIN index name.
|
|
304
|
+
* @param {string} [info.config='english'] - Postgres text-search config.
|
|
305
|
+
* @returns {string[]} Ordered list of DDL statements.
|
|
306
|
+
*/
|
|
307
|
+
createFullTextIndex(info){
|
|
308
|
+
const cfg = info.config || 'english';
|
|
309
|
+
const tsvCol = this._ftsColumnName();
|
|
310
|
+
const idxName = this._ftsIndexName(info.tableName, info.indexName);
|
|
311
|
+
const fnName = this._ftsTriggerFunctionName(info.tableName);
|
|
312
|
+
const trgName = this._ftsTriggerName(info.tableName);
|
|
313
|
+
|
|
314
|
+
// Concat for the existing-rows UPDATE (qualified by the column owner row).
|
|
315
|
+
const concatTable = info.columns
|
|
316
|
+
.map(c => `coalesce("${c}", '')`)
|
|
317
|
+
.join(` || ' ' || `);
|
|
318
|
+
|
|
319
|
+
// Concat for the trigger body — references NEW.<col>.
|
|
320
|
+
const concatNew = info.columns
|
|
321
|
+
.map(c => `coalesce(NEW."${c}", '')`)
|
|
322
|
+
.join(` || ' ' || `);
|
|
323
|
+
|
|
324
|
+
return [
|
|
325
|
+
// 1. Add the tsvector column if it doesn't exist
|
|
326
|
+
`ALTER TABLE "${info.tableName}" ADD COLUMN IF NOT EXISTS "${tsvCol}" tsvector`,
|
|
327
|
+
// 2. Backfill existing rows
|
|
328
|
+
`UPDATE "${info.tableName}" SET "${tsvCol}" = to_tsvector('${cfg}', ${concatTable})`,
|
|
329
|
+
// 3. GIN index for fast @@ matching
|
|
330
|
+
`CREATE INDEX IF NOT EXISTS "${idxName}" ON "${info.tableName}" USING GIN ("${tsvCol}")`,
|
|
331
|
+
// 4. Trigger function — $masterrecord$ dollar-quoted to avoid
|
|
332
|
+
// collision with any user-supplied content in column defaults.
|
|
333
|
+
`CREATE OR REPLACE FUNCTION "${fnName}"() RETURNS trigger AS $masterrecord$
|
|
334
|
+
BEGIN
|
|
335
|
+
NEW."${tsvCol}" := to_tsvector('${cfg}', ${concatNew});
|
|
336
|
+
RETURN NEW;
|
|
337
|
+
END
|
|
338
|
+
$masterrecord$ LANGUAGE plpgsql`,
|
|
339
|
+
// 5. Trigger — drop and recreate so config changes apply on re-run.
|
|
340
|
+
`DROP TRIGGER IF EXISTS "${trgName}" ON "${info.tableName}"`,
|
|
341
|
+
`CREATE TRIGGER "${trgName}" BEFORE INSERT OR UPDATE ON "${info.tableName}"
|
|
342
|
+
FOR EACH ROW EXECUTE FUNCTION "${fnName}"()`,
|
|
343
|
+
];
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/**
|
|
347
|
+
* Drop the trigger, function, index, and tsvector column created by
|
|
348
|
+
* createFullTextIndex.
|
|
349
|
+
*/
|
|
350
|
+
dropFullTextIndex(info){
|
|
351
|
+
const tsvCol = this._ftsColumnName();
|
|
352
|
+
const idxName = this._ftsIndexName(info.tableName, info.indexName);
|
|
353
|
+
const fnName = this._ftsTriggerFunctionName(info.tableName);
|
|
354
|
+
const trgName = this._ftsTriggerName(info.tableName);
|
|
355
|
+
|
|
356
|
+
return [
|
|
357
|
+
`DROP TRIGGER IF EXISTS "${trgName}" ON "${info.tableName}"`,
|
|
358
|
+
`DROP FUNCTION IF EXISTS "${fnName}"()`,
|
|
359
|
+
`DROP INDEX IF EXISTS "${idxName}"`,
|
|
360
|
+
`ALTER TABLE "${info.tableName}" DROP COLUMN IF EXISTS "${tsvCol}"`,
|
|
361
|
+
];
|
|
362
|
+
}
|
|
363
|
+
|
|
266
364
|
/**
|
|
267
365
|
* SEED DATA METHODS
|
|
268
366
|
* Support for inserting seed data during migrations
|
|
@@ -235,6 +235,59 @@ class migrationSQLiteQuery {
|
|
|
235
235
|
return `DROP INDEX IF EXISTS ${indexInfo.indexName}`;
|
|
236
236
|
}
|
|
237
237
|
|
|
238
|
+
/**
|
|
239
|
+
* Build the DDL statements that create an FTS5 full-text index on a
|
|
240
|
+
* SQLite table. The strategy is "external content" mode (the FTS5
|
|
241
|
+
* virtual table mirrors columns from the source table without
|
|
242
|
+
* duplicating storage), plus AFTER INSERT/UPDATE/DELETE triggers that
|
|
243
|
+
* keep the FTS5 table in sync with the source table.
|
|
244
|
+
*
|
|
245
|
+
* @param {object} info
|
|
246
|
+
* @param {string} info.tableName - Source table.
|
|
247
|
+
* @param {string[]} info.columns - Columns to index (in order).
|
|
248
|
+
* @param {string} [info.ftsTableName] - Override FTS table name.
|
|
249
|
+
* Defaults to `<tableName>_fts`.
|
|
250
|
+
* @returns {string[]} Ordered list of DDL statements to execute.
|
|
251
|
+
*/
|
|
252
|
+
createFullTextIndex(info){
|
|
253
|
+
const ftsTable = info.ftsTableName || `${info.tableName}_fts`;
|
|
254
|
+
const cols = info.columns.join(', ');
|
|
255
|
+
const insertCols = info.columns.map(c => `[${c}]`).join(', ');
|
|
256
|
+
const newCols = info.columns.map(c => `new.[${c}]`).join(', ');
|
|
257
|
+
const oldCols = info.columns.map(c => `old.[${c}]`).join(', ');
|
|
258
|
+
|
|
259
|
+
return [
|
|
260
|
+
// External-content FTS5 virtual table — rowid maps to source PK 'id'.
|
|
261
|
+
`CREATE VIRTUAL TABLE IF NOT EXISTS [${ftsTable}] USING fts5(${cols}, content=[${info.tableName}], content_rowid=id)`,
|
|
262
|
+
|
|
263
|
+
// Sync triggers
|
|
264
|
+
`CREATE TRIGGER IF NOT EXISTS [${info.tableName}_ai] AFTER INSERT ON [${info.tableName}] BEGIN
|
|
265
|
+
INSERT INTO [${ftsTable}](rowid, ${cols}) VALUES (new.id, ${newCols});
|
|
266
|
+
END`,
|
|
267
|
+
`CREATE TRIGGER IF NOT EXISTS [${info.tableName}_ad] AFTER DELETE ON [${info.tableName}] BEGIN
|
|
268
|
+
INSERT INTO [${ftsTable}]([${ftsTable}], rowid, ${cols}) VALUES('delete', old.id, ${oldCols});
|
|
269
|
+
END`,
|
|
270
|
+
`CREATE TRIGGER IF NOT EXISTS [${info.tableName}_au] AFTER UPDATE ON [${info.tableName}] BEGIN
|
|
271
|
+
INSERT INTO [${ftsTable}]([${ftsTable}], rowid, ${cols}) VALUES('delete', old.id, ${oldCols});
|
|
272
|
+
INSERT INTO [${ftsTable}](rowid, ${cols}) VALUES (new.id, ${newCols});
|
|
273
|
+
END`,
|
|
274
|
+
];
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/**
|
|
278
|
+
* Drop the FTS5 virtual table and the sync triggers created by
|
|
279
|
+
* createFullTextIndex.
|
|
280
|
+
*/
|
|
281
|
+
dropFullTextIndex(info){
|
|
282
|
+
const ftsTable = info.ftsTableName || `${info.tableName}_fts`;
|
|
283
|
+
return [
|
|
284
|
+
`DROP TRIGGER IF EXISTS [${info.tableName}_au]`,
|
|
285
|
+
`DROP TRIGGER IF EXISTS [${info.tableName}_ad]`,
|
|
286
|
+
`DROP TRIGGER IF EXISTS [${info.tableName}_ai]`,
|
|
287
|
+
`DROP TABLE IF EXISTS [${ftsTable}]`,
|
|
288
|
+
];
|
|
289
|
+
}
|
|
290
|
+
|
|
238
291
|
/**
|
|
239
292
|
* SEED DATA METHODS
|
|
240
293
|
* Support for inserting seed data during migrations
|
package/Migrations/schema.js
CHANGED
|
@@ -674,6 +674,64 @@ class schema{
|
|
|
674
674
|
}
|
|
675
675
|
}
|
|
676
676
|
|
|
677
|
+
/**
|
|
678
|
+
* Create a full-text search index on a table. The engine determines
|
|
679
|
+
* the underlying implementation:
|
|
680
|
+
*
|
|
681
|
+
* SQLite → FTS5 external-content virtual table + sync triggers
|
|
682
|
+
* Postgres → tsvector column + GIN index + maintenance trigger
|
|
683
|
+
* MySQL → FULLTEXT INDEX on the named columns
|
|
684
|
+
*
|
|
685
|
+
* Use the matching runtime API (e.g. `ctx.MemoryDoc.search(...)`) to
|
|
686
|
+
* query the index.
|
|
687
|
+
*
|
|
688
|
+
* @param {object} info
|
|
689
|
+
* @param {string} info.tableName
|
|
690
|
+
* @param {string[]} info.columns - Columns to index, in order.
|
|
691
|
+
* @param {string} [info.indexName] - Optional name override.
|
|
692
|
+
* @param {string} [info.config] - Postgres-only text search config ('english' default).
|
|
693
|
+
*
|
|
694
|
+
* @example
|
|
695
|
+
* await this.createFullTextIndex({
|
|
696
|
+
* tableName: 'MemoryDoc',
|
|
697
|
+
* columns: ['title', 'body'],
|
|
698
|
+
* });
|
|
699
|
+
*/
|
|
700
|
+
async createFullTextIndex(info){
|
|
701
|
+
if(!info || !info.tableName || !Array.isArray(info.columns) || info.columns.length === 0){
|
|
702
|
+
throw new Error('createFullTextIndex requires { tableName, columns: [...] }');
|
|
703
|
+
}
|
|
704
|
+
let builder;
|
|
705
|
+
if(this.context.isSQLite){ builder = new sqliteQuery(); }
|
|
706
|
+
else if(this.context.isMySQL){ builder = new sqlquery(); }
|
|
707
|
+
else if(this.context.isPostgres){ builder = new postgresQuery(); }
|
|
708
|
+
else { throw new Error('createFullTextIndex: unsupported database engine'); }
|
|
709
|
+
|
|
710
|
+
const statements = builder.createFullTextIndex(info);
|
|
711
|
+
for(const stmt of statements){
|
|
712
|
+
await this.context._execute(stmt);
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
/**
|
|
717
|
+
* Drop the full-text search index created by createFullTextIndex.
|
|
718
|
+
*/
|
|
719
|
+
async dropFullTextIndex(info){
|
|
720
|
+
if(!info || !info.tableName){
|
|
721
|
+
throw new Error('dropFullTextIndex requires { tableName }');
|
|
722
|
+
}
|
|
723
|
+
let builder;
|
|
724
|
+
if(this.context.isSQLite){ builder = new sqliteQuery(); }
|
|
725
|
+
else if(this.context.isMySQL){ builder = new sqlquery(); }
|
|
726
|
+
else if(this.context.isPostgres){ builder = new postgresQuery(); }
|
|
727
|
+
else { throw new Error('dropFullTextIndex: unsupported database engine'); }
|
|
728
|
+
|
|
729
|
+
const statements = builder.dropFullTextIndex(info);
|
|
730
|
+
for(const stmt of statements){
|
|
731
|
+
await this.context._execute(stmt);
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
|
|
677
735
|
async seed(tableName, rows){
|
|
678
736
|
if(!tableName || !rows){ return; }
|
|
679
737
|
const items = Array.isArray(rows) ? rows : [rows];
|
|
@@ -150,6 +150,53 @@ class queryMethods{
|
|
|
150
150
|
return this;
|
|
151
151
|
}
|
|
152
152
|
|
|
153
|
+
/**
|
|
154
|
+
* Full-text search across one or more columns.
|
|
155
|
+
*
|
|
156
|
+
* The schema must already have a full-text index created in a migration
|
|
157
|
+
* via `schema.createFullTextIndex({ tableName, columns })`. The runtime
|
|
158
|
+
* search uses FTS5 MATCH on SQLite, tsvector @@ on Postgres, and
|
|
159
|
+
* MATCH AGAINST on MySQL. Each row gets a `__rank` field for ordering.
|
|
160
|
+
*
|
|
161
|
+
* Composes with .where(), .take(), .skip(), .orderBy(). If no .orderBy()
|
|
162
|
+
* is chained, results come back ordered by rank descending.
|
|
163
|
+
*
|
|
164
|
+
* @param {object|string} opts - Either { in: [columns], query: 'terms' }
|
|
165
|
+
* or a bare string (which searches every column declared in the
|
|
166
|
+
* nearest createFullTextIndex — caller is responsible for matching).
|
|
167
|
+
* @param {string[]} [opts.in] - Columns to search. Required.
|
|
168
|
+
* @param {string} [opts.query] - Search terms.
|
|
169
|
+
*
|
|
170
|
+
* @example
|
|
171
|
+
* await ctx.MemoryDoc
|
|
172
|
+
* .search({ in: ['title', 'body'], query: 'auth login' })
|
|
173
|
+
* .where(d => d.workspace_id == ctx.$$, wid)
|
|
174
|
+
* .take(10)
|
|
175
|
+
* .toList();
|
|
176
|
+
*/
|
|
177
|
+
search(opts){
|
|
178
|
+
let columns, query;
|
|
179
|
+
if (typeof opts === 'string') {
|
|
180
|
+
// Bare string form requires the caller to declare columns elsewhere;
|
|
181
|
+
// we currently require explicit `in:` to keep the API honest.
|
|
182
|
+
throw new Error('search() requires { in: [columns], query: \'terms\' }. Bare-string form is reserved for a future declarative API.');
|
|
183
|
+
} else if (opts && typeof opts === 'object') {
|
|
184
|
+
columns = opts.in;
|
|
185
|
+
query = opts.query;
|
|
186
|
+
}
|
|
187
|
+
if (!Array.isArray(columns) || columns.length === 0) {
|
|
188
|
+
throw new Error('search() requires `in: [columns]` to be a non-empty array');
|
|
189
|
+
}
|
|
190
|
+
if (typeof query !== 'string' || query.length === 0) {
|
|
191
|
+
throw new Error('search() requires `query` to be a non-empty string');
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
// Stash the config on the script; engine buildQuery turns this into
|
|
195
|
+
// the right FTS predicate at SQL-generation time.
|
|
196
|
+
this.__queryObject.script.search = { columns: columns.slice(), query };
|
|
197
|
+
return this;
|
|
198
|
+
}
|
|
199
|
+
|
|
153
200
|
take(number){
|
|
154
201
|
this.__queryObject.script.take = number;
|
|
155
202
|
return this;
|
|
@@ -31,6 +31,10 @@ class queryScript{
|
|
|
31
31
|
skip: 0,
|
|
32
32
|
orderBy : false,
|
|
33
33
|
orderByDesc : false,
|
|
34
|
+
// Full-text search config: { columns: [...], query: '...' } when set.
|
|
35
|
+
// Engine-specific buildQuery() turns this into FTS5 MATCH, tsvector @@,
|
|
36
|
+
// or MATCH AGAINST and adds a __rank column.
|
|
37
|
+
search : false,
|
|
34
38
|
parentName : "",
|
|
35
39
|
parameters: null // Will hold QueryParameters instance
|
|
36
40
|
};
|
|
@@ -50,6 +54,7 @@ class queryScript{
|
|
|
50
54
|
skip: 0,
|
|
51
55
|
orderBy : false,
|
|
52
56
|
orderByDesc : false,
|
|
57
|
+
search : false,
|
|
53
58
|
parentName : "",
|
|
54
59
|
parameters: this.parameters
|
|
55
60
|
};
|
package/SQLLiteEngine.js
CHANGED
|
@@ -271,15 +271,57 @@ class SQLLiteEngine {
|
|
|
271
271
|
queryObject.skip = this.buildSkip(query);
|
|
272
272
|
queryObject.orderBy = this.buildOrderBy(query, entity);
|
|
273
273
|
|
|
274
|
+
// FTS5 full-text search bolted on top of the assembled query.
|
|
275
|
+
// The FTS5 virtual table is joined by rowid==id; we add a `__rank`
|
|
276
|
+
// column, a MATCH predicate against the search query, and default
|
|
277
|
+
// to ordering by rank if the user didn't chain their own .orderBy().
|
|
278
|
+
const fts = this._buildSearch(query, entity);
|
|
279
|
+
if (fts) {
|
|
280
|
+
queryObject.select = queryObject.select.replace(/\s*$/, `, ${fts.rankSelect} `);
|
|
281
|
+
queryObject.from = `${queryObject.from} ${fts.join}`;
|
|
282
|
+
if (queryObject.where && queryObject.where.trim().length > 0) {
|
|
283
|
+
queryObject.where = `${queryObject.where} AND ${fts.predicate}`;
|
|
284
|
+
} else {
|
|
285
|
+
queryObject.where = `WHERE ${fts.predicate}`;
|
|
286
|
+
}
|
|
287
|
+
if (!queryObject.orderBy || queryObject.orderBy.trim().length === 0) {
|
|
288
|
+
queryObject.orderBy = fts.defaultOrder;
|
|
289
|
+
}
|
|
290
|
+
}
|
|
274
291
|
|
|
275
292
|
var queryString = `${queryObject.select} ${queryObject.count} ${queryObject.from} ${queryObject.include} ${queryObject.where} ${queryObject.and} ${queryObject.orderBy} ${queryObject.take} ${queryObject.skip}`;
|
|
276
|
-
return {
|
|
293
|
+
return {
|
|
277
294
|
query : queryString,
|
|
278
295
|
entity : this.getEntity(entity.__name, query.entityMap)
|
|
279
296
|
}
|
|
280
297
|
|
|
281
298
|
}
|
|
282
299
|
|
|
300
|
+
/**
|
|
301
|
+
* Build the FTS5 plumbing fragments for the current query if a
|
|
302
|
+
* `.search()` clause was chained. Returns null if not.
|
|
303
|
+
*/
|
|
304
|
+
_buildSearch(query, entity){
|
|
305
|
+
if (!query.search) return null;
|
|
306
|
+
const alias = this.getEntity(query.parentName || entity.__name, query.entityMap);
|
|
307
|
+
const ftsTable = `${entity.__name}_fts`;
|
|
308
|
+
// FTS5's MATCH operator does not work with bracket-quoted aliases —
|
|
309
|
+
// `[_fts] MATCH ?` errors with `no such column: _fts`. We must use
|
|
310
|
+
// the FTS5 table name (or an unbracketed alias) directly in MATCH.
|
|
311
|
+
// Aliasing the FTS5 table also breaks MATCH; reference the table by
|
|
312
|
+
// its real name throughout the JOIN and WHERE.
|
|
313
|
+
const placeholder = query.parameters
|
|
314
|
+
? query.parameters.addParam(query.search.query, 'sqlite')
|
|
315
|
+
: '?';
|
|
316
|
+
return {
|
|
317
|
+
rankSelect: `${ftsTable}.rank AS __rank`,
|
|
318
|
+
join: `JOIN ${ftsTable} ON ${ftsTable}.rowid = ${alias}.id`,
|
|
319
|
+
predicate: `${ftsTable} MATCH ${placeholder}`,
|
|
320
|
+
// FTS5 rank is bm25; lower = more relevant. ASC gives best-first.
|
|
321
|
+
defaultOrder: `ORDER BY ${ftsTable}.rank`,
|
|
322
|
+
};
|
|
323
|
+
}
|
|
324
|
+
|
|
283
325
|
buildOrderBy(query, entity){
|
|
284
326
|
// ORDER BY column1, column2, ... ASC|DESC;
|
|
285
327
|
var $that = this;
|