masterrecord 1.0.8 → 1.1.0
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/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/mySQLEngine.js +46 -0
- package/package.json +1 -1
- package/postgresEngine.js +50 -1
- package/test/full-text-search.test.js +340 -0
|
@@ -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;
|
package/mySQLEngine.js
CHANGED
|
@@ -280,6 +280,23 @@ class MySQLEngine {
|
|
|
280
280
|
skip: this.buildSkip(query)
|
|
281
281
|
};
|
|
282
282
|
|
|
283
|
+
// MySQL FULLTEXT search bolted onto the assembled query: append
|
|
284
|
+
// MATCH(...) AGAINST(...) AS __rank to SELECT, the same expression
|
|
285
|
+
// into WHERE (or AND), and default to ORDER BY __rank DESC if the
|
|
286
|
+
// user didn't chain their own ordering.
|
|
287
|
+
const fts = this._buildSearch(query, entity);
|
|
288
|
+
if (fts) {
|
|
289
|
+
queryObject.select = queryObject.select.replace(/\s*$/, `, ${fts.rankSelect} `);
|
|
290
|
+
if (queryObject.where && queryObject.where.trim().length > 0) {
|
|
291
|
+
queryObject.where = `${queryObject.where} AND ${fts.predicate}`;
|
|
292
|
+
} else {
|
|
293
|
+
queryObject.where = `WHERE ${fts.predicate}`;
|
|
294
|
+
}
|
|
295
|
+
if (!queryObject.orderBy || queryObject.orderBy.trim().length === 0) {
|
|
296
|
+
queryObject.orderBy = fts.defaultOrder;
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
|
|
283
300
|
const queryString = `${queryObject.select} ${queryObject.from} ${queryObject.include} ${queryObject.where} ${queryObject.and} ${queryObject.orderBy} ${queryObject.take} ${queryObject.skip}`;
|
|
284
301
|
return {
|
|
285
302
|
query: queryString,
|
|
@@ -334,6 +351,35 @@ class MySQLEngine {
|
|
|
334
351
|
return "";
|
|
335
352
|
}
|
|
336
353
|
|
|
354
|
+
/**
|
|
355
|
+
* Build the MySQL FULLTEXT search plumbing for the current query if a
|
|
356
|
+
* `.search()` clause was chained. Returns null otherwise.
|
|
357
|
+
*
|
|
358
|
+
* MySQL emits `MATCH(col1, col2) AGAINST(? IN NATURAL LANGUAGE MODE)`.
|
|
359
|
+
* The MATCH expression appears twice: once in SELECT (aliased as
|
|
360
|
+
* __rank for ordering), once in WHERE. To keep parameter ordering
|
|
361
|
+
* consistent we bind the search term twice as separate parameters.
|
|
362
|
+
*/
|
|
363
|
+
_buildSearch(query, entity) {
|
|
364
|
+
if (!query.search) return null;
|
|
365
|
+
const alias = this.getEntity(query.parentName || entity.__name, query.entityMap);
|
|
366
|
+
const cols = query.search.columns.map(c => `${alias}.\`${c}\``).join(', ');
|
|
367
|
+
const phSelect = query.parameters
|
|
368
|
+
? query.parameters.addParam(query.search.query, 'mysql')
|
|
369
|
+
: '?';
|
|
370
|
+
const phWhere = query.parameters
|
|
371
|
+
? query.parameters.addParam(query.search.query, 'mysql')
|
|
372
|
+
: '?';
|
|
373
|
+
const matchSelect = `MATCH(${cols}) AGAINST(${phSelect} IN NATURAL LANGUAGE MODE)`;
|
|
374
|
+
const matchWhere = `MATCH(${cols}) AGAINST(${phWhere} IN NATURAL LANGUAGE MODE)`;
|
|
375
|
+
return {
|
|
376
|
+
rankSelect: `${matchSelect} AS __rank`,
|
|
377
|
+
predicate: matchWhere,
|
|
378
|
+
// MySQL relevance: higher = more relevant.
|
|
379
|
+
defaultOrder: `ORDER BY __rank DESC`,
|
|
380
|
+
};
|
|
381
|
+
}
|
|
382
|
+
|
|
337
383
|
/**
|
|
338
384
|
* Build chained AND clause from query.and (array of cachedExpr objects).
|
|
339
385
|
* Produces "AND <expr> AND <expr>" that appends to the WHERE clause.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "masterrecord",
|
|
3
|
-
"version": "1.0
|
|
3
|
+
"version": "1.1.0",
|
|
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/postgresEngine.js
CHANGED
|
@@ -331,7 +331,28 @@ class postgresEngine {
|
|
|
331
331
|
|
|
332
332
|
// Standard SQL clause order: SELECT ... FROM ... WHERE ... AND ... ORDER BY ... LIMIT ... OFFSET ...
|
|
333
333
|
// The previous order placed LIMIT/OFFSET before ORDER BY, which Postgres rejects as a syntax error.
|
|
334
|
-
|
|
334
|
+
let selectClause = this.buildSelectString(query, entity);
|
|
335
|
+
let whereClause = this.buildWhere(query, entity);
|
|
336
|
+
let orderByClause = this.buildOrderBy(query, entity);
|
|
337
|
+
|
|
338
|
+
// Postgres tsvector search bolted onto the assembled clauses.
|
|
339
|
+
// Adds ts_rank as __rank, the @@ predicate, and orders by rank DESC
|
|
340
|
+
// by default. Param binding happens via `_buildSearch` (it pushes
|
|
341
|
+
// the term into params and returns $N placeholders).
|
|
342
|
+
const fts = this._buildSearch(query, entity, params);
|
|
343
|
+
if (fts) {
|
|
344
|
+
selectClause = `${selectClause}, ${fts.rankSelect}`;
|
|
345
|
+
if (whereClause && whereClause.trim().length > 0) {
|
|
346
|
+
whereClause = `${whereClause} AND ${fts.predicate}`;
|
|
347
|
+
} else {
|
|
348
|
+
whereClause = `WHERE ${fts.predicate}`;
|
|
349
|
+
}
|
|
350
|
+
if (!orderByClause || orderByClause.trim().length === 0) {
|
|
351
|
+
orderByClause = fts.defaultOrder;
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
const sql = `SELECT ${selectClause} ${this.buildFrom(query, entity)} ${whereClause} ${this.buildAnd(query, entity)} ${orderByClause} ${this.buildLimit(query)} ${this.buildSkip(query)}`;
|
|
335
356
|
|
|
336
357
|
return {
|
|
337
358
|
query: sql,
|
|
@@ -339,6 +360,34 @@ class postgresEngine {
|
|
|
339
360
|
};
|
|
340
361
|
}
|
|
341
362
|
|
|
363
|
+
/**
|
|
364
|
+
* Build the Postgres tsvector search plumbing for the current query if
|
|
365
|
+
* a `.search()` clause was chained. Returns null otherwise.
|
|
366
|
+
*
|
|
367
|
+
* Pushes the search term onto the live params array (twice — once for
|
|
368
|
+
* SELECT, once for WHERE) and returns the corresponding $N placeholders
|
|
369
|
+
* inline. Caller is responsible for splicing the returned fragments
|
|
370
|
+
* into the right SELECT/WHERE/ORDER BY positions.
|
|
371
|
+
*/
|
|
372
|
+
_buildSearch(query, entity, params) {
|
|
373
|
+
if (!query.search) return null;
|
|
374
|
+
const alias = this.getEntity(query.parentName || entity.__name, query.entityMap);
|
|
375
|
+
const tsvCol = '__tsv'; // matches migrationPostgresQuery._ftsColumnName()
|
|
376
|
+
|
|
377
|
+
// Push the search term twice with sequential $N indices.
|
|
378
|
+
const baseIndex = params.length;
|
|
379
|
+
params.push(query.search.query);
|
|
380
|
+
params.push(query.search.query);
|
|
381
|
+
const phSelect = `$${baseIndex + 1}`;
|
|
382
|
+
const phWhere = `$${baseIndex + 2}`;
|
|
383
|
+
|
|
384
|
+
return {
|
|
385
|
+
rankSelect: `ts_rank(${alias}.${this._q(tsvCol)}, plainto_tsquery(${phSelect})) AS __rank`,
|
|
386
|
+
predicate: `${alias}.${this._q(tsvCol)} @@ plainto_tsquery(${phWhere})`,
|
|
387
|
+
defaultOrder: `ORDER BY __rank DESC`,
|
|
388
|
+
};
|
|
389
|
+
}
|
|
390
|
+
|
|
342
391
|
/**
|
|
343
392
|
* Build the column list after SELECT. If the user called `.select()`,
|
|
344
393
|
* `query.select` is a cachedExpr object with `selectFields` (not a string)
|
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Full-text search across all three engines (1.1.0).
|
|
3
|
+
*
|
|
4
|
+
* Schema-side: createFullTextIndex / dropFullTextIndex emit:
|
|
5
|
+
* - SQLite: FTS5 virtual table + AFTER INSERT/UPDATE/DELETE sync triggers
|
|
6
|
+
* - Postgres: tsvector column + GIN index + maintenance trigger
|
|
7
|
+
* - MySQL: ALTER TABLE ADD FULLTEXT INDEX
|
|
8
|
+
*
|
|
9
|
+
* Runtime: ctx.<Entity>.search({ in: [cols], query: 'term' }) emits the
|
|
10
|
+
* right SELECT for the engine and exposes a `__rank` column for ordering.
|
|
11
|
+
*
|
|
12
|
+
* SQLite end-to-end covers real ranking; MySQL/Postgres get string-output
|
|
13
|
+
* tests since we can't run them without live connections.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { test } from 'node:test';
|
|
17
|
+
import assert from 'node:assert/strict';
|
|
18
|
+
import fs from 'node:fs';
|
|
19
|
+
import path from 'node:path';
|
|
20
|
+
import { fileURLToPath } from 'node:url';
|
|
21
|
+
|
|
22
|
+
process.env.master = 'fts';
|
|
23
|
+
|
|
24
|
+
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
25
|
+
const fixturesDir = path.join(__dirname, 'fixtures', 'fts');
|
|
26
|
+
const envDir = path.join(fixturesDir, 'config', 'environments');
|
|
27
|
+
const dbDir = path.join(fixturesDir, 'db');
|
|
28
|
+
const dbFile = path.join(dbDir, 'ftsctx.sqlite');
|
|
29
|
+
|
|
30
|
+
fs.mkdirSync(envDir, { recursive: true });
|
|
31
|
+
fs.mkdirSync(dbDir, { recursive: true });
|
|
32
|
+
if (fs.existsSync(dbFile)) fs.rmSync(dbFile);
|
|
33
|
+
|
|
34
|
+
fs.writeFileSync(
|
|
35
|
+
path.join(envDir, 'env.fts.json'),
|
|
36
|
+
JSON.stringify({
|
|
37
|
+
FtsCtx: {
|
|
38
|
+
type: 'better-sqlite3',
|
|
39
|
+
connection: dbDir + path.sep,
|
|
40
|
+
},
|
|
41
|
+
})
|
|
42
|
+
);
|
|
43
|
+
|
|
44
|
+
const { default: context } = await import('../context.js');
|
|
45
|
+
const { default: schemaCls } = await import('../Migrations/schema.js');
|
|
46
|
+
const { default: SQLiteQuery } = await import('../Migrations/migrationSQLiteQuery.js');
|
|
47
|
+
const { default: MySQLQuery } = await import('../Migrations/migrationMySQLQuery.js');
|
|
48
|
+
const { default: PostgresQuery } = await import('../Migrations/migrationPostgresQuery.js');
|
|
49
|
+
const { default: SQLiteEngine } = await import('../SQLLiteEngine.js');
|
|
50
|
+
const { default: MySQLEngine } = await import('../mySQLEngine.js');
|
|
51
|
+
const { default: PostgresEngine } = await import('../postgresEngine.js');
|
|
52
|
+
|
|
53
|
+
// =====================================================================
|
|
54
|
+
// DDL string output — no DB required
|
|
55
|
+
// =====================================================================
|
|
56
|
+
|
|
57
|
+
test('SQLite createFullTextIndex emits FTS5 virtual table + sync triggers', () => {
|
|
58
|
+
const q = new SQLiteQuery();
|
|
59
|
+
const stmts = q.createFullTextIndex({
|
|
60
|
+
tableName: 'MemoryDoc',
|
|
61
|
+
columns: ['title', 'body'],
|
|
62
|
+
});
|
|
63
|
+
// Virtual table with external content
|
|
64
|
+
assert.match(stmts[0], /CREATE VIRTUAL TABLE IF NOT EXISTS \[MemoryDoc_fts\] USING fts5/);
|
|
65
|
+
assert.match(stmts[0], /title, body/);
|
|
66
|
+
assert.match(stmts[0], /content=\[MemoryDoc\]/);
|
|
67
|
+
assert.match(stmts[0], /content_rowid=id/);
|
|
68
|
+
// Three sync triggers (AFTER INSERT, DELETE, UPDATE)
|
|
69
|
+
assert.match(stmts[1], /AFTER INSERT ON \[MemoryDoc\]/);
|
|
70
|
+
assert.match(stmts[2], /AFTER DELETE ON \[MemoryDoc\]/);
|
|
71
|
+
assert.match(stmts[3], /AFTER UPDATE ON \[MemoryDoc\]/);
|
|
72
|
+
assert.equal(stmts.length, 4);
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
test('SQLite dropFullTextIndex drops triggers + virtual table in reverse order', () => {
|
|
76
|
+
const q = new SQLiteQuery();
|
|
77
|
+
const stmts = q.dropFullTextIndex({ tableName: 'MemoryDoc' });
|
|
78
|
+
assert.match(stmts[0], /DROP TRIGGER IF EXISTS \[MemoryDoc_au\]/);
|
|
79
|
+
assert.match(stmts[1], /DROP TRIGGER IF EXISTS \[MemoryDoc_ad\]/);
|
|
80
|
+
assert.match(stmts[2], /DROP TRIGGER IF EXISTS \[MemoryDoc_ai\]/);
|
|
81
|
+
assert.match(stmts[3], /DROP TABLE IF EXISTS \[MemoryDoc_fts\]/);
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
test('Postgres createFullTextIndex emits tsvector + GIN + trigger', () => {
|
|
85
|
+
const q = new PostgresQuery();
|
|
86
|
+
const stmts = q.createFullTextIndex({
|
|
87
|
+
tableName: 'MemoryDoc',
|
|
88
|
+
columns: ['title', 'body'],
|
|
89
|
+
});
|
|
90
|
+
// tsvector column
|
|
91
|
+
assert.match(stmts[0], /ALTER TABLE "MemoryDoc" ADD COLUMN IF NOT EXISTS "__tsv" tsvector/);
|
|
92
|
+
// Backfill
|
|
93
|
+
assert.match(stmts[1], /UPDATE "MemoryDoc" SET "__tsv" = to_tsvector\('english'/);
|
|
94
|
+
// GIN index
|
|
95
|
+
assert.match(stmts[2], /CREATE INDEX IF NOT EXISTS "idx_memorydoc_fts" ON "MemoryDoc" USING GIN \("__tsv"\)/);
|
|
96
|
+
// Trigger function exists and references NEW columns
|
|
97
|
+
assert.match(stmts[3], /CREATE OR REPLACE FUNCTION "memorydoc_tsv_update"/);
|
|
98
|
+
assert.match(stmts[3], /NEW\."title"/);
|
|
99
|
+
assert.match(stmts[3], /NEW\."body"/);
|
|
100
|
+
assert.match(stmts[3], /\$masterrecord\$/);
|
|
101
|
+
// DROP+CREATE trigger
|
|
102
|
+
assert.match(stmts[4], /DROP TRIGGER IF EXISTS "memorydoc_tsv_trigger" ON "MemoryDoc"/);
|
|
103
|
+
assert.match(stmts[5], /CREATE TRIGGER "memorydoc_tsv_trigger" BEFORE INSERT OR UPDATE ON "MemoryDoc"/);
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
test('Postgres dropFullTextIndex drops trigger, function, index, and column', () => {
|
|
107
|
+
const q = new PostgresQuery();
|
|
108
|
+
const stmts = q.dropFullTextIndex({ tableName: 'MemoryDoc' });
|
|
109
|
+
assert.match(stmts[0], /DROP TRIGGER IF EXISTS "memorydoc_tsv_trigger" ON "MemoryDoc"/);
|
|
110
|
+
assert.match(stmts[1], /DROP FUNCTION IF EXISTS "memorydoc_tsv_update"/);
|
|
111
|
+
assert.match(stmts[2], /DROP INDEX IF EXISTS "idx_memorydoc_fts"/);
|
|
112
|
+
assert.match(stmts[3], /ALTER TABLE "MemoryDoc" DROP COLUMN IF EXISTS "__tsv"/);
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
test('Postgres createFullTextIndex honors custom config (language)', () => {
|
|
116
|
+
const q = new PostgresQuery();
|
|
117
|
+
const stmts = q.createFullTextIndex({
|
|
118
|
+
tableName: 'Doc',
|
|
119
|
+
columns: ['body'],
|
|
120
|
+
config: 'spanish',
|
|
121
|
+
});
|
|
122
|
+
assert.match(stmts[1], /to_tsvector\('spanish'/);
|
|
123
|
+
assert.match(stmts[3], /to_tsvector\('spanish'/);
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
test('MySQL createFullTextIndex emits ALTER TABLE ADD FULLTEXT INDEX', () => {
|
|
127
|
+
const q = new MySQLQuery();
|
|
128
|
+
const stmts = q.createFullTextIndex({
|
|
129
|
+
tableName: 'MemoryDoc',
|
|
130
|
+
columns: ['title', 'body'],
|
|
131
|
+
});
|
|
132
|
+
assert.equal(stmts.length, 1);
|
|
133
|
+
assert.match(stmts[0], /ALTER TABLE `MemoryDoc` ADD FULLTEXT INDEX `idx_memorydoc_fts` \(`title`, `body`\)/);
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
test('MySQL dropFullTextIndex emits ALTER TABLE DROP INDEX', () => {
|
|
137
|
+
const q = new MySQLQuery();
|
|
138
|
+
const stmts = q.dropFullTextIndex({ tableName: 'MemoryDoc' });
|
|
139
|
+
assert.equal(stmts.length, 1);
|
|
140
|
+
assert.match(stmts[0], /ALTER TABLE `MemoryDoc` DROP INDEX `idx_memorydoc_fts`/);
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
// =====================================================================
|
|
144
|
+
// queryMethods.search() input validation
|
|
145
|
+
// =====================================================================
|
|
146
|
+
|
|
147
|
+
class MemoryDoc {
|
|
148
|
+
id(db) { db.integer().primary().auto(); }
|
|
149
|
+
title(db) { db.string(); }
|
|
150
|
+
body(db) { db.text(); }
|
|
151
|
+
workspaceId(db) { db.integer(); }
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
class FtsCtx extends context {
|
|
155
|
+
constructor() {
|
|
156
|
+
super();
|
|
157
|
+
this.env(envDir);
|
|
158
|
+
this.dbset(MemoryDoc);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
test('search() requires { in: [...], query: ... }', () => {
|
|
163
|
+
const ctx = new FtsCtx();
|
|
164
|
+
assert.throws(() => ctx.MemoryDoc.search('bare-string'), /requires \{ in/);
|
|
165
|
+
assert.throws(() => ctx.MemoryDoc.search({}), /requires `in:/);
|
|
166
|
+
assert.throws(() => ctx.MemoryDoc.search({ in: [] }), /non-empty array/);
|
|
167
|
+
assert.throws(() => ctx.MemoryDoc.search({ in: ['title'] }), /`query` to be a non-empty string/);
|
|
168
|
+
assert.throws(() => ctx.MemoryDoc.search({ in: ['title'], query: '' }), /non-empty string/);
|
|
169
|
+
ctx.close();
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
// =====================================================================
|
|
173
|
+
// SQLite end-to-end ranked search
|
|
174
|
+
// =====================================================================
|
|
175
|
+
|
|
176
|
+
{
|
|
177
|
+
// Seed the SQLite DB + FTS5 index via the real schema API.
|
|
178
|
+
const ctx = new FtsCtx();
|
|
179
|
+
ctx._SQLEngine.db.exec(`
|
|
180
|
+
CREATE TABLE IF NOT EXISTS MemoryDoc (
|
|
181
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
182
|
+
title TEXT,
|
|
183
|
+
body TEXT,
|
|
184
|
+
workspaceId INTEGER
|
|
185
|
+
);
|
|
186
|
+
`);
|
|
187
|
+
|
|
188
|
+
const sch = new schemaCls(FtsCtx);
|
|
189
|
+
await sch._ensureReady();
|
|
190
|
+
sch.fullTable = { __name: 'MemoryDoc' };
|
|
191
|
+
await sch.createFullTextIndex({ tableName: 'MemoryDoc', columns: ['title', 'body'] });
|
|
192
|
+
|
|
193
|
+
// Seed rows AFTER the FTS index so triggers populate the virtual table.
|
|
194
|
+
const insert = ctx._SQLEngine.db.prepare(
|
|
195
|
+
'INSERT INTO MemoryDoc (title, body, workspaceId) VALUES (?, ?, ?)'
|
|
196
|
+
);
|
|
197
|
+
insert.run('Authentication flow', 'user login session token', 1);
|
|
198
|
+
insert.run('Database migrations', 'schema changes postgres sqlite', 1);
|
|
199
|
+
insert.run('Login button styling', 'css button color hover', 1);
|
|
200
|
+
insert.run('Unrelated document', 'absolutely nothing matches here', 2);
|
|
201
|
+
|
|
202
|
+
await ctx.close();
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
test('SQLite search returns ranked results with __rank populated', async () => {
|
|
206
|
+
const ctx = new FtsCtx();
|
|
207
|
+
const rows = await ctx.MemoryDoc
|
|
208
|
+
.search({ in: ['title', 'body'], query: 'login' })
|
|
209
|
+
.toList();
|
|
210
|
+
assert.ok(rows.length >= 2, `expected at least 2 results, got ${rows.length}`);
|
|
211
|
+
// Top result must mention 'login' in title or body
|
|
212
|
+
const titles = rows.map(r => r.title);
|
|
213
|
+
assert.ok(titles.some(t => /login/i.test(t)));
|
|
214
|
+
// Every returned row exposes __rank
|
|
215
|
+
for (const r of rows) {
|
|
216
|
+
assert.equal(typeof r.__rank, 'number', `row ${r.id} missing __rank`);
|
|
217
|
+
}
|
|
218
|
+
await ctx.close();
|
|
219
|
+
});
|
|
220
|
+
|
|
221
|
+
test('SQLite search composes with .where() (workspace scoping)', async () => {
|
|
222
|
+
const ctx = new FtsCtx();
|
|
223
|
+
const rows = await ctx.MemoryDoc
|
|
224
|
+
.search({ in: ['title', 'body'], query: 'login' })
|
|
225
|
+
.where('d => d.workspaceId == $$', 1)
|
|
226
|
+
.toList();
|
|
227
|
+
assert.ok(rows.length >= 1);
|
|
228
|
+
for (const r of rows) {
|
|
229
|
+
assert.equal(r.workspaceId, 1, `row ${r.id} not scoped to workspace 1`);
|
|
230
|
+
}
|
|
231
|
+
await ctx.close();
|
|
232
|
+
});
|
|
233
|
+
|
|
234
|
+
test('SQLite search composes with .take() for pagination', async () => {
|
|
235
|
+
const ctx = new FtsCtx();
|
|
236
|
+
const rows = await ctx.MemoryDoc
|
|
237
|
+
.search({ in: ['title', 'body'], query: 'login' })
|
|
238
|
+
.take(1)
|
|
239
|
+
.toList();
|
|
240
|
+
assert.equal(rows.length, 1);
|
|
241
|
+
await ctx.close();
|
|
242
|
+
});
|
|
243
|
+
|
|
244
|
+
test('SQLite search returns empty for terms with no matches', async () => {
|
|
245
|
+
const ctx = new FtsCtx();
|
|
246
|
+
const rows = await ctx.MemoryDoc
|
|
247
|
+
.search({ in: ['title', 'body'], query: 'nonexistentword' })
|
|
248
|
+
.toList();
|
|
249
|
+
assert.equal(rows.length, 0);
|
|
250
|
+
await ctx.close();
|
|
251
|
+
});
|
|
252
|
+
|
|
253
|
+
// =====================================================================
|
|
254
|
+
// MySQL/Postgres SQL string output — no live DB needed
|
|
255
|
+
// =====================================================================
|
|
256
|
+
|
|
257
|
+
function buildScript(chainFn) {
|
|
258
|
+
const ctx = new FtsCtx();
|
|
259
|
+
const builder = chainFn(ctx);
|
|
260
|
+
// Mirror what `.toList()` does: bootstrap the entityMap when no prior
|
|
261
|
+
// .where()/.orderBy() chained call has touched it, otherwise buildFrom
|
|
262
|
+
// emits an empty alias and the assertions fail with `.col` (no alias).
|
|
263
|
+
if (builder.__queryObject.script.entityMap.length === 0) {
|
|
264
|
+
builder.__queryObject.skipClause(builder.__entity.__name);
|
|
265
|
+
}
|
|
266
|
+
const script = builder.__queryObject.script;
|
|
267
|
+
const entity = builder.__entity;
|
|
268
|
+
ctx.close();
|
|
269
|
+
return { script, entity };
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
test('MySQL search SQL contains MATCH(...) AGAINST(...) twice and ORDER BY __rank DESC', () => {
|
|
273
|
+
const { script, entity } = buildScript((ctx) =>
|
|
274
|
+
ctx.MemoryDoc.search({ in: ['title', 'body'], query: 'auth login' })
|
|
275
|
+
);
|
|
276
|
+
const engine = new MySQLEngine();
|
|
277
|
+
const out = engine.buildQuery(script, entity, {});
|
|
278
|
+
assert.match(out.query, /MATCH\(\w+\.`title`, \w+\.`body`\) AGAINST\(\? IN NATURAL LANGUAGE MODE\) AS __rank/);
|
|
279
|
+
assert.match(out.query, /WHERE MATCH\(\w+\.`title`, \w+\.`body`\) AGAINST\(\? IN NATURAL LANGUAGE MODE\)/);
|
|
280
|
+
assert.match(out.query, /ORDER BY __rank DESC/);
|
|
281
|
+
});
|
|
282
|
+
|
|
283
|
+
test('Postgres search SQL contains ts_rank, @@ predicate, and ORDER BY __rank DESC', () => {
|
|
284
|
+
const { script, entity } = buildScript((ctx) =>
|
|
285
|
+
ctx.MemoryDoc.search({ in: ['title', 'body'], query: 'auth login' })
|
|
286
|
+
);
|
|
287
|
+
const engine = new PostgresEngine();
|
|
288
|
+
const out = engine.buildQuery(script, entity, {});
|
|
289
|
+
assert.match(out.query, /ts_rank\(\w+\."__tsv", plainto_tsquery\(\$\d+\)\) AS __rank/);
|
|
290
|
+
assert.match(out.query, /WHERE \w+\."__tsv" @@ plainto_tsquery\(\$\d+\)/);
|
|
291
|
+
assert.match(out.query, /ORDER BY __rank DESC/);
|
|
292
|
+
// Search term bound twice (once for SELECT, once for WHERE)
|
|
293
|
+
assert.equal(out.params.length, 2);
|
|
294
|
+
assert.equal(out.params[0], 'auth login');
|
|
295
|
+
assert.equal(out.params[1], 'auth login');
|
|
296
|
+
});
|
|
297
|
+
|
|
298
|
+
test('Postgres search composes with prior .where() (parameter ordering preserved)', () => {
|
|
299
|
+
const { script, entity } = buildScript((ctx) =>
|
|
300
|
+
ctx.MemoryDoc
|
|
301
|
+
.where('d => d.workspaceId == $$', 42)
|
|
302
|
+
.search({ in: ['title', 'body'], query: 'login' })
|
|
303
|
+
);
|
|
304
|
+
const engine = new PostgresEngine();
|
|
305
|
+
const out = engine.buildQuery(script, entity, {});
|
|
306
|
+
// WHERE has the workspace predicate AND the @@ predicate
|
|
307
|
+
assert.match(out.query, /WHERE.*workspaceId.*AND.*@@/s);
|
|
308
|
+
// Params: workspace 42 first, then search term twice
|
|
309
|
+
assert.equal(out.params[0], 42);
|
|
310
|
+
assert.equal(out.params[1], 'login');
|
|
311
|
+
assert.equal(out.params[2], 'login');
|
|
312
|
+
});
|
|
313
|
+
|
|
314
|
+
test('MySQL search clauses appear in correct SQL order (WHERE before ORDER BY before LIMIT)', () => {
|
|
315
|
+
const { script, entity } = buildScript((ctx) =>
|
|
316
|
+
ctx.MemoryDoc.search({ in: ['title', 'body'], query: 'login' }).take(5)
|
|
317
|
+
);
|
|
318
|
+
const engine = new MySQLEngine();
|
|
319
|
+
const out = engine.buildQuery(script, entity, {});
|
|
320
|
+
const whereIdx = out.query.indexOf('WHERE');
|
|
321
|
+
const orderIdx = out.query.indexOf('ORDER BY');
|
|
322
|
+
const limitIdx = out.query.indexOf('LIMIT');
|
|
323
|
+
assert.ok(whereIdx >= 0 && whereIdx < orderIdx, 'WHERE before ORDER BY');
|
|
324
|
+
assert.ok(orderIdx < limitIdx, 'ORDER BY before LIMIT');
|
|
325
|
+
});
|
|
326
|
+
|
|
327
|
+
test('All engines: schema.createFullTextIndex throws if columns missing', async () => {
|
|
328
|
+
const ctx = new FtsCtx();
|
|
329
|
+
const sch = new schemaCls(FtsCtx);
|
|
330
|
+
await sch._ensureReady();
|
|
331
|
+
await assert.rejects(
|
|
332
|
+
sch.createFullTextIndex({ tableName: 'MemoryDoc' }),
|
|
333
|
+
/requires \{ tableName, columns/
|
|
334
|
+
);
|
|
335
|
+
await assert.rejects(
|
|
336
|
+
sch.createFullTextIndex({ columns: ['title'] }),
|
|
337
|
+
/requires \{ tableName, columns/
|
|
338
|
+
);
|
|
339
|
+
await ctx.close();
|
|
340
|
+
});
|