masterrecord 1.0.7 → 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.
@@ -185,8 +185,15 @@ class migrationMySQLQuery {
185
185
  has unique constraint
186
186
  is indexed
187
187
  appears in a view
188
+
189
+ `IF EXISTS` was added in MySQL 8.0.24. Safe to emit unconditionally
190
+ — older MySQL/MariaDB versions will reject this DDL syntax, but
191
+ identifier quoting + IF EXISTS is the modern standard and matches
192
+ Postgres' behavior. Consumers on MySQL <8.0.24 should pin
193
+ masterrecord to <1.0.8 or use raw _execute() for drop-column
194
+ migrations.
188
195
  */
189
- return `ALTER TABLE \`${table.tableName}\` DROP COLUMN \`${table.name}\``;
196
+ return `ALTER TABLE \`${table.tableName}\` DROP COLUMN IF EXISTS \`${table.name}\``;
190
197
  }
191
198
 
192
199
  insertInto(name, table){
@@ -274,6 +281,39 @@ class migrationMySQLQuery {
274
281
  return `DROP INDEX \`${indexInfo.indexName}\` ON \`${indexInfo.tableName}\``;
275
282
  }
276
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
+
277
317
  /**
278
318
  * SEED DATA METHODS
279
319
  * Support for inserting seed data during migrations
@@ -186,9 +186,12 @@ class migrationPostgresQuery {
186
186
  dropColumn(table){
187
187
  /*
188
188
  PostgreSQL DROP COLUMN is more flexible than SQLite
189
- Can drop columns with constraints if CASCADE is used
189
+ Can drop columns with constraints if CASCADE is used.
190
+ `IF EXISTS` makes drop-column migrations idempotent: re-running a
191
+ migration after a failed/partial earlier run no longer errors with
192
+ `column "X" does not exist`.
190
193
  */
191
- return `ALTER TABLE "${table.tableName}" DROP COLUMN "${table.name}"`;
194
+ return `ALTER TABLE "${table.tableName}" DROP COLUMN IF EXISTS "${table.name}"`;
192
195
  }
193
196
 
194
197
  insertInto(name, table){
@@ -260,6 +263,104 @@ class migrationPostgresQuery {
260
263
  return `DROP INDEX IF EXISTS "${indexInfo.indexName}"`;
261
264
  }
262
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
+
263
364
  /**
264
365
  * SEED DATA METHODS
265
366
  * Support for inserting seed data during migrations
@@ -142,12 +142,13 @@ class migrationSQLiteQuery {
142
142
 
143
143
  dropColumn(table){
144
144
  /*
145
- COLUMNS CANNOT BE DROPPED - RULES
146
- has unique constraint
147
- is indexed
148
- appears in a view
145
+ SQLite added DROP COLUMN in 3.35 (2021). SQLite does NOT support
146
+ `IF EXISTS` on DROP COLUMN; idempotency is handled one level up
147
+ in schema.dropColumn() which checks via getTableInfo before
148
+ emitting this DDL. Square brackets quote the identifiers for
149
+ consistency with the rest of the SQLite engine output.
149
150
  */
150
- return `ALTER TABLE ${table.tableName} DROP COLUMN ${table.name}`
151
+ return `ALTER TABLE [${table.tableName}] DROP COLUMN [${table.name}]`
151
152
  }
152
153
 
153
154
  insertInto(name, table){
@@ -234,6 +235,59 @@ class migrationSQLiteQuery {
234
235
  return `DROP INDEX IF EXISTS ${indexInfo.indexName}`;
235
236
  }
236
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
+
237
291
  /**
238
292
  * SEED DATA METHODS
239
293
  * Support for inserting seed data during migrations
@@ -247,21 +247,31 @@ class schema{
247
247
  async dropColumn(table){
248
248
  if(table){
249
249
  if(this.fullTable){
250
- // drop column
250
+ // SQLite doesn't support `IF EXISTS` on DROP COLUMN, so
251
+ // emulate it here: probe getTableInfo and bail out if the
252
+ // column is already gone. Postgres + MySQL emit the
253
+ // `IF EXISTS` clause directly in their DDL.
251
254
  if(this.context.isSQLite){
252
- var queryBuilder = new sqliteQuery();
255
+ if (typeof this.context._SQLEngine.getTableInfo === 'function') {
256
+ const cols = await this.context._SQLEngine.getTableInfo(table.tableName);
257
+ const exists = Array.isArray(cols) && cols.some(c => c && (c.name === table.name));
258
+ if (!exists) {
259
+ return;
260
+ }
261
+ }
262
+ var queryBuilder = new sqliteQuery();
253
263
  var query = queryBuilder.dropColumn(table);
254
264
  await this.context._execute(query);
255
265
  }
256
266
 
257
267
  if(this.context.isMySQL){
258
- var queryBuilder = new sqlquery();
268
+ var queryBuilder = new sqlquery();
259
269
  var query = queryBuilder.dropColumn(table);
260
270
  await this.context._execute(query);
261
271
  }
262
272
 
263
273
  if(this.context.isPostgres){
264
- var queryBuilder = new postgresQuery();
274
+ var queryBuilder = new postgresQuery();
265
275
  var query = queryBuilder.dropColumn(table);
266
276
  await this.context._execute(query);
267
277
  }
@@ -664,6 +674,64 @@ class schema{
664
674
  }
665
675
  }
666
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
+
667
735
  async seed(tableName, rows){
668
736
  if(!tableName || !rows){ return; }
669
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.7",
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
@@ -290,6 +290,38 @@ class postgresEngine {
290
290
  }
291
291
  }
292
292
 
293
+ /**
294
+ * Introspection: Get column information for a table.
295
+ *
296
+ * Used by `schema.syncTable()` to diff the existing database schema
297
+ * against the entity definition so migrations can add only the
298
+ * missing columns. Without this method on Postgres, syncTable
299
+ * couldn't detect existing columns and re-ran migrations failed
300
+ * with `column "X" already exists`.
301
+ *
302
+ * Returns rows shaped like the SQLite/MySQL counterparts:
303
+ * { name, dflt_value, is_nullable, data_type }
304
+ */
305
+ async getTableInfo(tableName) {
306
+ try {
307
+ const sql = `
308
+ SELECT
309
+ column_name AS name,
310
+ column_default AS dflt_value,
311
+ is_nullable AS is_nullable,
312
+ data_type AS data_type
313
+ FROM information_schema.columns
314
+ WHERE table_schema = ANY(current_schemas(false))
315
+ AND table_name = $1
316
+ ORDER BY ordinal_position
317
+ `;
318
+ const result = await this._runWithParams(sql, [tableName]);
319
+ return (result && result.rows) ? result.rows : [];
320
+ } catch (_) {
321
+ return [];
322
+ }
323
+ }
324
+
293
325
  /**
294
326
  * Build complete SELECT query with parameters
295
327
  */
@@ -299,7 +331,28 @@ class postgresEngine {
299
331
 
300
332
  // Standard SQL clause order: SELECT ... FROM ... WHERE ... AND ... ORDER BY ... LIMIT ... OFFSET ...
301
333
  // The previous order placed LIMIT/OFFSET before ORDER BY, which Postgres rejects as a syntax error.
302
- const sql = `SELECT ${this.buildSelectString(query, entity)} ${this.buildFrom(query, entity)} ${this.buildWhere(query, entity)} ${this.buildAnd(query, entity)} ${this.buildOrderBy(query, entity)} ${this.buildLimit(query)} ${this.buildSkip(query)}`;
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)}`;
303
356
 
304
357
  return {
305
358
  query: sql,
@@ -307,6 +360,34 @@ class postgresEngine {
307
360
  };
308
361
  }
309
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
+
310
391
  /**
311
392
  * Build the column list after SELECT. If the user called `.select()`,
312
393
  * `query.select` is a cachedExpr object with `selectFields` (not a string)
@@ -0,0 +1,181 @@
1
+ /**
2
+ * Regression for two related 1.0.8 fixes:
3
+ *
4
+ * 1. postgresEngine was missing getTableInfo() — schema.syncTable() couldn't
5
+ * diff against the existing schema, so re-running migrations failed with
6
+ * `column "X" already exists`.
7
+ *
8
+ * 2. DROP COLUMN DDL was not idempotent — Postgres/MySQL didn't emit
9
+ * `IF EXISTS` and SQLite had no runtime guard, so re-running a
10
+ * drop-column migration after a failed/partial run errored with
11
+ * `column "X" does not exist`.
12
+ */
13
+
14
+ import { test } from 'node:test';
15
+ import assert from 'node:assert/strict';
16
+ import fs from 'node:fs';
17
+ import path from 'node:path';
18
+ import { fileURLToPath } from 'node:url';
19
+
20
+ process.env.master = 'dropcol';
21
+
22
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
23
+ const fixturesDir = path.join(__dirname, 'fixtures', 'drop-col');
24
+ const envDir = path.join(fixturesDir, 'config', 'environments');
25
+ const dbDir = path.join(fixturesDir, 'db');
26
+ const dbFile = path.join(dbDir, 'dropcolctx.sqlite');
27
+
28
+ fs.mkdirSync(envDir, { recursive: true });
29
+ fs.mkdirSync(dbDir, { recursive: true });
30
+ if (fs.existsSync(dbFile)) fs.rmSync(dbFile);
31
+
32
+ fs.writeFileSync(
33
+ path.join(envDir, 'env.dropcol.json'),
34
+ JSON.stringify({
35
+ DropColCtx: {
36
+ type: 'better-sqlite3',
37
+ connection: dbDir + path.sep,
38
+ },
39
+ })
40
+ );
41
+
42
+ const { default: context } = await import('../context.js');
43
+ const { default: schema } = await import('../Migrations/schema.js');
44
+ const { default: PostgresEngine } = await import('../postgresEngine.js');
45
+ const { default: MySQLEngine } = await import('../mySQLEngine.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
+
50
+ // ---- DDL string-level checks (no DB connection required) ----
51
+
52
+ test('Postgres dropColumn emits IF EXISTS with quoted identifiers', () => {
53
+ const q = new PostgresQuery();
54
+ const sql = q.dropColumn({ tableName: 'SchedulerLeader', name: 'staleField' });
55
+ assert.match(sql, /ALTER TABLE "SchedulerLeader" DROP COLUMN IF EXISTS "staleField"/);
56
+ });
57
+
58
+ test('MySQL dropColumn emits IF EXISTS with backtick quotes', () => {
59
+ const q = new MySQLQuery();
60
+ const sql = q.dropColumn({ tableName: 'User', name: 'legacyField' });
61
+ assert.match(sql, /ALTER TABLE `User` DROP COLUMN IF EXISTS `legacyField`/);
62
+ });
63
+
64
+ test('SQLite dropColumn quotes identifiers with square brackets', () => {
65
+ const q = new SQLiteQuery();
66
+ const sql = q.dropColumn({ tableName: 'User', name: 'legacyField' });
67
+ assert.match(sql, /ALTER TABLE \[User\] DROP COLUMN \[legacyField\]/);
68
+ // SQLite has no `IF EXISTS` on DROP COLUMN; the guard lives in schema.dropColumn().
69
+ assert.doesNotMatch(sql, /IF EXISTS/);
70
+ });
71
+
72
+ // ---- Postgres getTableInfo presence ----
73
+
74
+ test('Postgres engine exposes getTableInfo()', () => {
75
+ const engine = new PostgresEngine();
76
+ assert.equal(typeof engine.getTableInfo, 'function');
77
+ });
78
+
79
+ test('Postgres getTableInfo returns rows shaped like SQLite/MySQL counterparts', async () => {
80
+ const engine = new PostgresEngine();
81
+ // Stub _runWithParams so we can verify the SQL without a live Postgres.
82
+ let capturedSql;
83
+ let capturedParams;
84
+ engine._runWithParams = async (sql, params) => {
85
+ capturedSql = sql;
86
+ capturedParams = params;
87
+ return {
88
+ rows: [
89
+ { name: 'id', dflt_value: null, is_nullable: 'NO', data_type: 'integer' },
90
+ { name: 'createdAt', dflt_value: null, is_nullable: 'YES', data_type: 'timestamp without time zone' },
91
+ ],
92
+ };
93
+ };
94
+ const rows = await engine.getTableInfo('SchedulerLeader');
95
+ assert.match(capturedSql, /information_schema\.columns/);
96
+ assert.match(capturedSql, /table_name\s*=\s*\$1/);
97
+ assert.deepEqual(capturedParams, ['SchedulerLeader']);
98
+ assert.equal(rows.length, 2);
99
+ assert.equal(rows[0].name, 'id');
100
+ assert.equal(rows[1].name, 'createdAt');
101
+ // Field names mirror SQLite's PRAGMA table_info / MySQL's INFORMATION_SCHEMA query.
102
+ for (const key of ['name', 'dflt_value', 'is_nullable', 'data_type']) {
103
+ assert.ok(key in rows[0], `expected '${key}' in row`);
104
+ }
105
+ });
106
+
107
+ test('Postgres getTableInfo returns [] on error', async () => {
108
+ const engine = new PostgresEngine();
109
+ engine._runWithParams = async () => { throw new Error('boom'); };
110
+ assert.deepEqual(await engine.getTableInfo('Whatever'), []);
111
+ });
112
+
113
+ // ---- SQLite end-to-end: dropColumn twice in a row must not throw ----
114
+
115
+ class Widget {
116
+ id(db) { db.integer().primary().auto(); }
117
+ name(db) { db.string(); }
118
+ legacyField(db) { db.string(); }
119
+ }
120
+
121
+ class DropColCtx extends context {
122
+ constructor() {
123
+ super();
124
+ this.env(envDir);
125
+ this.dbset(Widget);
126
+ }
127
+ }
128
+
129
+ {
130
+ // Seed the schema using raw SQL so we don't depend on the rest of the
131
+ // migration pipeline for setup.
132
+ const ctx = new DropColCtx();
133
+ ctx._SQLEngine.db.exec(`
134
+ CREATE TABLE IF NOT EXISTS Widget (
135
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
136
+ name TEXT,
137
+ legacyField TEXT
138
+ );
139
+ `);
140
+ await ctx.close();
141
+ }
142
+
143
+ test('SQLite schema.dropColumn() is idempotent (re-running does not throw)', async () => {
144
+ const ctx = new DropColCtx();
145
+ const sch = new schema(DropColCtx);
146
+ await sch._ensureReady();
147
+ // schema.dropColumn() gates on `this.fullTable` being truthy as a "did
148
+ // init run" sentinel. Real migrations get a real tableObj here; tests
149
+ // just need a truthy value to pass the gate.
150
+ sch.fullTable = { __name: 'Widget' };
151
+
152
+ // Confirm the column exists initially.
153
+ const before = await ctx._SQLEngine.getTableInfo('Widget');
154
+ assert.ok(before.some(c => c.name === 'legacyField'), 'precondition: legacyField column exists');
155
+
156
+ // First drop: removes the column.
157
+ await sch.dropColumn({ tableName: 'Widget', name: 'legacyField' });
158
+ const afterFirst = await ctx._SQLEngine.getTableInfo('Widget');
159
+ assert.ok(!afterFirst.some(c => c.name === 'legacyField'), 'column was dropped');
160
+
161
+ // Second drop: must be a no-op, not an error. This is the regression
162
+ // that 1.0.8 fixes — without the runtime guard in schema.dropColumn(),
163
+ // SQLite would have thrown "no such column: legacyField".
164
+ await assert.doesNotReject(
165
+ sch.dropColumn({ tableName: 'Widget', name: 'legacyField' }),
166
+ 'second dropColumn must be idempotent'
167
+ );
168
+
169
+ await ctx.close();
170
+ });
171
+
172
+ test('SQLite schema.dropColumn() on a never-existed column is also a no-op', async () => {
173
+ const ctx = new DropColCtx();
174
+ const sch = new schema(DropColCtx);
175
+ await sch._ensureReady();
176
+ sch.fullTable = { __name: 'Widget' };
177
+ await assert.doesNotReject(
178
+ sch.dropColumn({ tableName: 'Widget', name: 'neverExisted' })
179
+ );
180
+ await ctx.close();
181
+ });
@@ -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
+ });