masterrecord 1.0.8 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,219 @@
1
+ # Full-Text Search
2
+
3
+ > Available since **v1.1.0**.
4
+
5
+ MasterRecord ships a portable full-text search API that runs on top of each engine's native FTS implementation:
6
+
7
+ | Engine | Implementation |
8
+ | ---------- | --------------------------------------------------------------- |
9
+ | SQLite | FTS5 external-content virtual table + AFTER INSERT/UPDATE/DELETE triggers |
10
+ | PostgreSQL | `tsvector` column + GIN index + maintenance trigger |
11
+ | MySQL | `FULLTEXT INDEX` |
12
+
13
+ Your migration and query code stays the same across all three. The setup details, the rank algorithm (BM25 vs `ts_rank` vs MySQL relevance), and the query-syntax details (FTS5's `NEAR`, Postgres `&|<->`, MySQL natural-language mode) all live inside MasterRecord.
14
+
15
+ ---
16
+
17
+ ## Why not just use `.like()`?
18
+
19
+ `LIKE` does a literal substring match without ranking, stemming, or tokenization. For "the user typed a few words, show the best matches first" you want FTS. Here's the practical difference:
20
+
21
+ | Need | `.like()` | `.search()` |
22
+ | --------------------------------------------------- | ----------- | ----------- |
23
+ | Find rows containing this exact substring | ✅ | ✅ |
24
+ | Prefix match (`auth*`) | ✅ (`auth%`) | ✅ |
25
+ | Match `authentication` when searching `auth` | ❌ | ✅ |
26
+ | Match `auth login` regardless of word order | ❌ | ✅ |
27
+ | Rank results by relevance | ❌ | ✅ |
28
+ | Fast on large tables | ❌ (scan) | ✅ (index) |
29
+
30
+ If you want simple substring filtering, stay with `.like()`. If you want a search box, use `.search()`.
31
+
32
+ ---
33
+
34
+ ## Setup — in a migration
35
+
36
+ Declare the index alongside `createTable`:
37
+
38
+ ```js
39
+ import masterrecord from 'masterrecord';
40
+
41
+ class AddMemoryDocFts extends masterrecord.schema {
42
+ async up(table) {
43
+ await this.init(table);
44
+ await this.createTable(table.MemoryDoc);
45
+ await this.createFullTextIndex({
46
+ tableName: 'MemoryDoc',
47
+ columns: ['title', 'body'],
48
+ });
49
+ }
50
+
51
+ async down(table) {
52
+ await this.init(table);
53
+ await this.dropFullTextIndex({ tableName: 'MemoryDoc' });
54
+ await this.dropTable(table.MemoryDoc);
55
+ }
56
+ }
57
+
58
+ export default AddMemoryDocFts;
59
+ ```
60
+
61
+ ### `createFullTextIndex(info)`
62
+
63
+ | Option | Type | Required | Description |
64
+ | ------------ | -------- | -------- | ------------------------------------------------------------------------------------------ |
65
+ | `tableName` | string | yes | Source table. |
66
+ | `columns` | string[] | yes | Columns to index, in order. |
67
+ | `indexName` | string | no | Override the generated index name (`idx_<table>_fts` by default). |
68
+ | `config` | string | no | Postgres-only `to_tsvector` config (defaults to `'english'`). Ignored on SQLite and MySQL. |
69
+
70
+ Per-engine effect:
71
+
72
+ - **SQLite** — creates `<TableName>_fts` virtual table with `content=<TableName>, content_rowid=id`, plus AFTER INSERT/UPDATE/DELETE sync triggers. The FTS table mirrors the source automatically.
73
+ - **Postgres** — adds a `__tsv tsvector` column, backfills it from existing rows, creates a GIN index, and installs a BEFORE INSERT/UPDATE trigger that keeps `__tsv` in sync with the listed columns.
74
+ - **MySQL** — `ALTER TABLE … ADD FULLTEXT INDEX (col1, col2)`. MySQL maintains the index automatically; no triggers needed.
75
+
76
+ ### `dropFullTextIndex(info)`
77
+
78
+ | Option | Type | Required | Description |
79
+ | ----------- | ------ | -------- | -------------------------------------------- |
80
+ | `tableName` | string | yes | Source table. |
81
+ | `indexName` | string | no | Override if you set a custom name on create. |
82
+
83
+ Reverses everything `createFullTextIndex` did. Safe to re-run on missing infrastructure (`IF EXISTS` clauses everywhere).
84
+
85
+ ---
86
+
87
+ ## Querying — at runtime
88
+
89
+ ```js
90
+ const docs = await ctx.MemoryDoc
91
+ .search({ in: ['title', 'body'], query: 'auth login' })
92
+ .toList();
93
+
94
+ // Each row exposes a __rank field
95
+ for (const d of docs) {
96
+ console.log(d.__rank, d.title);
97
+ }
98
+ ```
99
+
100
+ ### `.search(opts)`
101
+
102
+ | Option | Type | Required | Description |
103
+ | ------- | -------- | -------- | ----------------------------------------------------------------------- |
104
+ | `in` | string[] | yes | Columns to search. Must be a subset of what `createFullTextIndex` indexed. |
105
+ | `query` | string | yes | Search terms. Engine-specific syntax (see below). |
106
+
107
+ Returns a chainable query builder, just like `.where()`. Each returned row gets a `__rank` field; results are ordered by rank descending by default.
108
+
109
+ ### Composition
110
+
111
+ `.search()` composes with `.where()`, `.take()`, `.skip()`, `.orderBy()`. The search predicate ANDs with `.where()` conditions:
112
+
113
+ ```js
114
+ // Workspace-scoped FTS, paginated, top 10
115
+ const page = await ctx.MemoryDoc
116
+ .search({ in: ['title', 'body'], query: 'auth login' })
117
+ .where(d => d.workspace_id == ctx.$$, workspaceId)
118
+ .take(10)
119
+ .skip(20)
120
+ .toList();
121
+ ```
122
+
123
+ If you chain your own `.orderBy()`, it replaces the default rank ordering:
124
+
125
+ ```js
126
+ // Most-recently-updated first, regardless of rank
127
+ const docs = await ctx.MemoryDoc
128
+ .search({ in: ['title', 'body'], query: 'auth' })
129
+ .orderByDescending(d => d.updated_at)
130
+ .toList();
131
+ ```
132
+
133
+ ---
134
+
135
+ ## Engine-specific query syntax
136
+
137
+ The `query` string is passed through to the engine's native FTS operator, so syntax differs:
138
+
139
+ | Engine | Operator | Common syntax |
140
+ | ---------- | ----------------------------------------------- | ---------------------------------------------------- |
141
+ | SQLite | `MATCH 'terms'` | `auth*` (prefix), `auth NEAR login`, `"exact phrase"` |
142
+ | PostgreSQL | `@@ plainto_tsquery('terms')` | Plain words. For operators use `to_tsquery` syntax: `auth & login`, `auth | login` |
143
+ | MySQL | `MATCH(...) AGAINST(? IN NATURAL LANGUAGE MODE)` | Plain words. `+auth -login`, `"exact phrase"` in boolean mode (default is NLM) |
144
+
145
+ > **The ranking *score* and exact ordering will differ across engines** — BM25 is not the same as `ts_rank` is not the same as MySQL relevance. Within a single engine the ordering is stable and meaningful; across engines it's best-effort.
146
+
147
+ If your app's correctness depends on matching specific tokens or operator semantics, pick an engine and stay on it.
148
+
149
+ ---
150
+
151
+ ## Reading rank
152
+
153
+ Every row returned from a `.search()` query has a `__rank` field added:
154
+
155
+ ```js
156
+ const rows = await ctx.MemoryDoc
157
+ .search({ in: ['title', 'body'], query: 'auth' })
158
+ .toList();
159
+ console.log(rows[0].__rank); // numeric
160
+ ```
161
+
162
+ The scale differs per engine — Postgres and MySQL return positive values where higher means more relevant; SQLite's BM25 returns negative values where lower (more negative) means more relevant. **You should not compare rank values across engines.** Within a single query they're consistent for sorting.
163
+
164
+ ---
165
+
166
+ ## Patterns
167
+
168
+ ### Auto-complete / search-as-you-type
169
+
170
+ Use a prefix query — supported on SQLite (`auth*`) and Postgres (`auth:*` with `to_tsquery`; with `plainto_tsquery` it's plain stemming). MySQL natural-language mode doesn't do prefix matching; switch to boolean mode if you need it.
171
+
172
+ For broadly portable behavior with `plainto_tsquery` semantics, just pass the prefix:
173
+
174
+ ```js
175
+ ctx.MemoryDoc.search({ in: ['title'], query: 'auth' }).take(10).toList();
176
+ ```
177
+
178
+ ### Scoped search
179
+
180
+ Combine `.search()` with `.where()` on a tenant column:
181
+
182
+ ```js
183
+ ctx.MemoryDoc
184
+ .search({ in: ['title', 'body'], query })
185
+ .where(d => d.workspace_id == ctx.$$, workspaceId)
186
+ .toList();
187
+ ```
188
+
189
+ ### Pagination
190
+
191
+ `.search()` + `.skip().take()` work together. Rank is stable per query, so paging is safe as long as the underlying data doesn't change between requests.
192
+
193
+ ### Returning rank to the UI
194
+
195
+ `__rank` is a regular column on the result row. Serialize it as you would any field:
196
+
197
+ ```js
198
+ const results = await ctx.MemoryDoc.search({ in: ['title', 'body'], query }).toList();
199
+ return results.map(d => ({ id: d.id, title: d.title, score: d.__rank }));
200
+ ```
201
+
202
+ ---
203
+
204
+ ## Caveats
205
+
206
+ - **The columns passed to `.search({ in: [...] })` must be a subset of what `createFullTextIndex({ columns: [...] })` declared.** If you index `[title, body]` and search `in: ['summary']`, the engine will reject the query (SQLite/Postgres) or return nothing (MySQL).
207
+ - **MySQL FULLTEXT requires InnoDB ≥ 5.6** (or MyISAM). Older versions need a different table engine.
208
+ - **Postgres requires a `to_tsvector`-compatible config.** Default is `'english'`. Pass `config: 'simple'` for no stemming, or any other Postgres config you've configured.
209
+ - **Don't search before populating.** On SQLite the FTS table is filled by INSERT triggers — rows that exist before `createFullTextIndex` are NOT indexed unless you re-insert them. On Postgres, the migration backfills the `tsvector` column automatically. On MySQL, FULLTEXT indexes existing rows when the index is created.
210
+
211
+ ---
212
+
213
+ ## When NOT to use this
214
+
215
+ Both runtime search and the schema setup add complexity. Skip them if:
216
+
217
+ - You only need substring matching → use `.like()`.
218
+ - Your dataset is tiny and a full table scan is fine.
219
+ - You need cross-language or fuzzy matching beyond what BM25/`ts_rank` provide — reach for a dedicated search engine (Meilisearch, Elastic, Typesense) and integrate it as a separate service.
@@ -53,6 +53,7 @@ context.User.where(u => $$.includes(u.id), [1, 2, 3]).toList();
53
53
  | `.orderByDescending(lambda)` | Sort descending | `.orderByDescending(u => u.created_at)` |
54
54
  | `.take(n)` | Limit results | `.take(10)` |
55
55
  | `.skip(n)` | Offset results | `.skip(20)` |
56
+ | `.search({ in, query })` | Full-text search (see [FULL_TEXT_SEARCH.md](FULL_TEXT_SEARCH.md)) | `context.MemoryDoc.search({ in: ['title','body'], query: 'auth login' })` |
56
57
  | `.toList()` | Execute and return array | `.where(...).toList()` |
57
58
  | `.single()` | Execute and return one | `.where(...).single()` |
58
59
  | `.first()` | Execute and return first | `.where(...).first()` |
@@ -124,6 +125,20 @@ const activeUsers = context.User
124
125
  .toList();
125
126
  ```
126
127
 
128
+ ### Full-Text Search
129
+
130
+ ```javascript
131
+ // Requires a migration with createFullTextIndex(); see docs/FULL_TEXT_SEARCH.md
132
+ const docs = await context.MemoryDoc
133
+ .search({ in: ['title', 'body'], query: 'auth login' })
134
+ .where(d => d.workspace_id == $$, workspaceId)
135
+ .take(10)
136
+ .toList();
137
+
138
+ // Each row has a __rank field (engine-specific scale)
139
+ docs.forEach(d => console.log(d.__rank, d.title));
140
+ ```
141
+
127
142
  ---
128
143
 
129
144
  ## Why Your LLM Might Be Confused
@@ -186,6 +186,41 @@ class MakeAgeRequired extends masterrecord.schema {
186
186
  export default MakeAgeRequired;
187
187
  ```
188
188
 
189
+ ### Full-text search indexes
190
+
191
+ Create and drop portable FTS indexes. Each engine emits its native equivalent — FTS5 virtual table + triggers on SQLite, `tsvector` column + GIN index + maintenance trigger on PostgreSQL, `FULLTEXT INDEX` on MySQL.
192
+
193
+ ```javascript
194
+ import masterrecord from 'masterrecord';
195
+
196
+ class AddMemoryDocFts extends masterrecord.schema {
197
+ async up(table) {
198
+ await this.init(table);
199
+ await this.createTable(table.MemoryDoc);
200
+ await this.createFullTextIndex({
201
+ tableName: 'MemoryDoc',
202
+ columns: ['title', 'body'],
203
+ });
204
+ }
205
+
206
+ async down(table) {
207
+ await this.init(table);
208
+ await this.dropFullTextIndex({ tableName: 'MemoryDoc' });
209
+ await this.dropTable(table.MemoryDoc);
210
+ }
211
+ }
212
+
213
+ export default AddMemoryDocFts;
214
+ ```
215
+
216
+ `createFullTextIndex(info)` accepts:
217
+ - `tableName` (string, required)
218
+ - `columns` (string[], required) — columns to index
219
+ - `indexName` (string, optional) — overrides the generated name (`idx_<table>_fts`)
220
+ - `config` (string, optional) — Postgres-only `to_tsvector` config (defaults to `'english'`)
221
+
222
+ Runtime querying uses the matching `.search({ in, query })` dbset method — see [FULL_TEXT_SEARCH.md](FULL_TEXT_SEARCH.md) for engine-specific query syntax and ranking caveats.
223
+
189
224
  ### Renaming columns
190
225
 
191
226
  ```javascript
@@ -344,10 +344,10 @@ node test/postgresIntegrationTest.js
344
344
 
345
345
  ## Version Compatibility
346
346
 
347
- - **MasterRecord**: 0.3.0+
348
- - **pg (node-postgres)**: 8.16.3+
347
+ - **MasterRecord**: 1.0+ (ESM-only)
348
+ - **pg (node-postgres)**: 8.17+
349
349
  - **PostgreSQL Server**: 9.6+ (tested with 12+, 13+, 14+)
350
- - **Node.js**: 20+ (ESM-only package)
350
+ - **Node.js**: 20+
351
351
 
352
352
  ## Complete Example
353
353
 
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.8",
3
+ "version": "1.1.1",
4
4
  "description": "An Object-relational mapping for the Master framework. Master Record connects classes to relational database tables to establish a database with almost zero-configuration ",
5
5
  "type": "module",
6
6
  "main": "./MasterRecord.js",
package/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
- 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)}`;
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)
package/readme.md CHANGED
@@ -17,6 +17,7 @@
17
17
  🔹 **Lifecycle Hooks** - `beforeSave`, `afterSave`, `beforeDelete`, `afterDelete` hooks
18
18
  🔹 **Business Validation** - Built-in validators (required, email, length, pattern, custom)
19
19
  🔹 **Bulk Operations** - Efficient `bulkCreate`, `bulkUpdate`, `bulkDelete` APIs
20
+ 🔹 **Full-Text Search** - Portable `.search()` API on top of SQLite FTS5, Postgres `tsvector`, and MySQL `FULLTEXT`
20
21
  🔹 **Query Result Caching** - Production-grade in-memory and Redis caching with automatic invalidation
21
22
  🔹 **Migration System** - CLI-driven migrations with rollback support
22
23
  🔹 **SQL Injection Protection** - Automatic parameterized queries throughout
@@ -40,6 +41,7 @@
40
41
  - [Database Configuration](#database-configuration)
41
42
  - [Entity Definitions](#entity-definitions)
42
43
  - [Querying](#querying)
44
+ - [Full-Text Search](#full-text-search)
43
45
  - [Entity Serialization](#entity-serialization)
44
46
  - [.toObject()](#toobjectoptions)
45
47
  - [.toJSON()](#tojson)
@@ -706,6 +708,50 @@ const matching = await db.User
706
708
  .toList();
707
709
  ```
708
710
 
711
+ ## Full-Text Search
712
+
713
+ Portable full-text search that runs on each engine's native FTS implementation: FTS5 on SQLite, `tsvector` + GIN on PostgreSQL, `FULLTEXT INDEX` on MySQL. Use it when `LIKE` isn't enough — when you want stemming, tokenization, multi-word queries, and ranking.
714
+
715
+ ### Set up the index in a migration
716
+
717
+ ```javascript
718
+ import masterrecord from 'masterrecord';
719
+
720
+ class AddMemoryDocFts extends masterrecord.schema {
721
+ async up(table) {
722
+ await this.init(table);
723
+ await this.createTable(table.MemoryDoc);
724
+ await this.createFullTextIndex({
725
+ tableName: 'MemoryDoc',
726
+ columns: ['title', 'body'],
727
+ });
728
+ }
729
+
730
+ async down(table) {
731
+ await this.init(table);
732
+ await this.dropFullTextIndex({ tableName: 'MemoryDoc' });
733
+ await this.dropTable(table.MemoryDoc);
734
+ }
735
+ }
736
+
737
+ export default AddMemoryDocFts;
738
+ ```
739
+
740
+ ### Query
741
+
742
+ ```javascript
743
+ const docs = await db.MemoryDoc
744
+ .search({ in: ['title', 'body'], query: 'auth login' })
745
+ .where(d => d.workspace_id == $$, workspaceId)
746
+ .take(10)
747
+ .toList();
748
+
749
+ // Each row has a __rank field; default ordering is rank descending.
750
+ for (const d of docs) console.log(d.__rank, d.title);
751
+ ```
752
+
753
+ `.search()` composes with `.where()`, `.take()`, `.skip()`, and `.orderBy()`. Engine-specific query syntax (FTS5's `NEAR` / prefix, Postgres `to_tsquery` operators, MySQL boolean mode), ranking semantics, and engine caveats are documented in [docs/FULL_TEXT_SEARCH.md](./docs/FULL_TEXT_SEARCH.md).
754
+
709
755
  ## Migrations
710
756
 
711
757
  ### CLI Commands
@@ -3377,15 +3423,4 @@ user.name = null; // Error if name is { nullable: false }
3377
3423
 
3378
3424
  ## Changelog
3379
3425
 
3380
- ### Version 0.3.49 (2026-02-21) - FIX: Duplicate Index Creation for New Tables
3381
-
3382
- #### Bug Fixed: `createIndex` called twice for new tables during `update-database`
3383
- - **FIXED**: When running `update-database` with a new table that has indexes, the indexes were created twice — once by `createTable()` in schema.js (which iterates column `.index()` definitions and `__compositeIndexes`), and again by explicit `createIndex()`/`createCompositeIndex()` calls in the generated migration file
3384
- - **Symptom**: MySQL error `Duplicate key name 'idx_...'` during InitialCreate migrations
3385
- - **Root Cause**: `migrations.js` `#findNewIndexes()` and `#findNewCompositeIndexes()` added index operations for ALL tables, including brand new ones where `createTable()` already handles them
3386
- - **Solution**: Skip index generation in migration template for new tables (`item.newTables.length > 0`). For existing tables getting new indexes, explicit `createIndex` calls are still generated correctly.
3387
-
3388
- #### Files Modified
3389
- 1. **`Migrations/migrations.js`** - Skip `newIndexes` and `newCompositeIndexes` for new tables in `#findNewIndexes()` and `#findNewCompositeIndexes()`
3390
- 2. **`test/v0.3.34-bug-fixes-test.js`** - Updated tests to verify correct behavior + added tests for adding indexes to existing tables
3391
- 3. **`package.json`** - Updated to v0.3.49
3426
+ See [CHANGES.md](./CHANGES.md) for the full version history.