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,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
+ });
@@ -1,138 +0,0 @@
1
- # Future Improvements for MasterRecord
2
-
3
- ## Metadata Property Handling
4
-
5
- ### Context
6
- The `.index()` bug fix (commit 6e774a7) introduced a blacklist approach to skip metadata properties during schema processing. While this solves the immediate problem, there are architectural improvements to consider for future versions.
7
-
8
- ### Current Solution (v0.3.33)
9
- ```javascript
10
- for (var key in table) {
11
- // Skip metadata properties (indexes, __compositeIndexes, __name, etc.)
12
- if(key === 'indexes' || key.startsWith('__')){
13
- continue;
14
- }
15
- // ... process columns
16
- }
17
- ```
18
-
19
- **Status:** ✅ Shipped - Works well, well-tested, solves the problem
20
-
21
- ### Future Considerations
22
-
23
- #### 1. Document the Metadata Convention
24
- **Priority:** Medium
25
- **Effort:** Low
26
-
27
- Add clear documentation explaining that properties starting with `__` are reserved for internal metadata and will be skipped during schema processing. This should be documented in:
28
- - README.md (Entity Model section)
29
- - Code comments in `entityModel.js`
30
- - Migration guide if breaking changes are made
31
-
32
- **Example documentation:**
33
- ```markdown
34
- ## Reserved Property Names
35
- - Properties starting with `__` (double underscore) are reserved for internal metadata
36
- - `indexes` property is reserved for index definitions
37
- - These properties are automatically skipped during table creation
38
- ```
39
-
40
- #### 2. Whitelist Approach (Long-term)
41
- **Priority:** Low
42
- **Effort:** Medium
43
- **Breaking Change:** Potentially
44
-
45
- Instead of blacklisting specific properties, consider only processing properties that are actually column definitions.
46
-
47
- **Pros:**
48
- - More robust if new metadata properties are added
49
- - Explicit about what gets processed
50
- - Self-documenting code
51
-
52
- **Cons:**
53
- - Requires careful design to not break existing functionality
54
- - More complex validation logic
55
- - Could impact performance
56
-
57
- **Example approach:**
58
- ```javascript
59
- for (var key in table) {
60
- if(typeof table[key] !== "object") continue;
61
-
62
- var col = table[key];
63
-
64
- // Only process objects that have column-like properties
65
- if(!col.name || !col.type) continue;
66
-
67
- // Skip relationship types
68
- if(col.type === 'hasOne' || col.type === 'hasMany' || col.type === 'hasManyThrough'){
69
- continue;
70
- }
71
-
72
- queryVar += `${this.#columnMapping(col)}, `;
73
- }
74
- ```
75
-
76
- #### 3. Use JavaScript Symbols for Metadata (v1.0+)
77
- **Priority:** Low
78
- **Effort:** High
79
- **Breaking Change:** Yes
80
-
81
- For future major versions, consider using JavaScript Symbols for all internal metadata. Symbols don't appear in `for...in` loops or `Object.keys()`, eliminating this entire class of bugs.
82
-
83
- **Benefits:**
84
- - Metadata becomes truly invisible to iteration
85
- - No special-case filtering needed
86
- - Cleaner separation of concerns
87
- - More idiomatic JavaScript
88
-
89
- **Migration path:**
90
- ```javascript
91
- // Current (v0.x)
92
- table.__name = 'Users';
93
- table.indexes = ['idx_name'];
94
-
95
- // Future (v1.0+)
96
- const META_NAME = Symbol('name');
97
- const META_INDEXES = Symbol('indexes');
98
-
99
- table[META_NAME] = 'Users';
100
- table[META_INDEXES] = ['idx_name'];
101
- ```
102
-
103
- **Challenges:**
104
- - Requires refactoring all metadata access
105
- - Breaks existing code that accesses `__name`, `__compositeIndexes`, etc.
106
- - Would need comprehensive migration guide
107
- - Testing burden is significant
108
-
109
- **When to consider:**
110
- - During a major version bump (v1.0)
111
- - When other breaking changes are planned
112
- - After gathering user feedback on current metadata usage patterns
113
-
114
- ---
115
-
116
- ## Implementation Notes
117
-
118
- ### Current Fix is Good to Ship ✅
119
- The blacklist approach (`indexes` and `__*` properties) is:
120
- - Practical and solves the immediate problem
121
- - Well-tested (5 comprehensive tests)
122
- - Easy to understand and maintain
123
- - Not over-engineered
124
-
125
- ### Recommendation
126
- 1. **Ship the current fix** (already committed)
127
- 2. **Add documentation** about the `__` convention in next minor release
128
- 3. **Track whitelist approach** as a potential v0.4+ enhancement
129
- 4. **Consider Symbols** only for v1.0 major version
130
-
131
- ---
132
-
133
- ## Related Issues
134
- - Index bug fix: commit 6e774a7
135
- - Test suite: `test/index-bug-fix-test.js`
136
-
137
- ## Feedback Credit
138
- These suggestions came from code review feedback on the index bug fix implementation.