sqlite-zod-orm 3.8.0 → 3.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/database.ts CHANGED
@@ -1,50 +1,86 @@
1
1
  /**
2
2
  * database.ts — Main Database class for sqlite-zod-orm
3
3
  *
4
- * Orchestrates schema-driven table creation, CRUD, relationships,
5
- * query builders, and event handling.
4
+ * Slim orchestrator: initializes the schema, creates tables/triggers,
5
+ * and delegates CRUD, entity augmentation, and query building to
6
+ * focused modules.
6
7
  */
7
8
  import { Database as SqliteDatabase } from 'bun:sqlite';
8
9
  import { z } from 'zod';
9
- import { QueryBuilder } from './query-builder';
10
- import { executeProxyQuery, type ProxyQueryResult } from './proxy-query';
10
+ import { QueryBuilder, executeProxyQuery, createQueryBuilder, type ProxyQueryResult } from './query';
11
11
  import type {
12
12
  SchemaMap, DatabaseOptions, Relationship, RelationsConfig,
13
13
  EntityAccessor, TypedAccessors, TypedNavAccessors, AugmentedEntity, UpdateBuilder,
14
- ProxyColumns, InferSchema,
14
+ ProxyColumns, InferSchema, ChangeEvent,
15
15
  } from './types';
16
16
  import { asZodObject } from './types';
17
17
  import {
18
18
  parseRelationsConfig,
19
19
  getStorableFields,
20
- zodTypeToSqlType, transformForStorage, transformFromStorage,
20
+ zodTypeToSqlType,
21
21
  } from './schema';
22
+ import { transformFromStorage } from './schema';
23
+ import type { DatabaseContext } from './context';
24
+ import { buildWhereClause } from './helpers';
25
+ import { attachMethods } from './entity';
26
+ import {
27
+ insert, insertMany, update, upsert, deleteEntity,
28
+ getById, getOne, findMany, updateWhere, createUpdateBuilder,
29
+ } from './crud';
22
30
 
23
31
  // =============================================================================
24
32
  // Database Class
25
33
  // =============================================================================
26
34
 
35
+ type Listener = {
36
+ table: string;
37
+ event: ChangeEvent;
38
+ callback: (row: any) => void | Promise<void>;
39
+ };
40
+
27
41
  class _Database<Schemas extends SchemaMap> {
28
42
  private db: SqliteDatabase;
43
+ private _reactive: boolean;
29
44
  private schemas: Schemas;
30
45
  private relationships: Relationship[];
31
46
  private options: DatabaseOptions;
32
- private pollInterval: number;
33
47
 
34
- /** In-memory revision counter per table — same-process fast path.
35
- * Complements the trigger-based _satidb_changes table for cross-process detection. */
36
- private _revisions: Record<string, number> = {};
48
+ /** Shared context for extracted modules. */
49
+ private _ctx: DatabaseContext;
50
+
51
+ /** Registered change listeners. */
52
+ private _listeners: Listener[] = [];
53
+
54
+ /** Watermark: last processed change id from _changes table. */
55
+ private _changeWatermark: number = 0;
56
+
57
+ /** Global poll timer (single loop for all listeners). */
58
+ private _pollTimer: ReturnType<typeof setInterval> | null = null;
59
+
60
+ /** Poll interval in ms. */
61
+ private _pollInterval: number;
37
62
 
38
63
  constructor(dbFile: string, schemas: Schemas, options: DatabaseOptions = {}) {
39
64
  this.db = new SqliteDatabase(dbFile);
40
- this.db.run('PRAGMA journal_mode = WAL'); // WAL enables concurrent read + write
65
+ this.db.run('PRAGMA journal_mode = WAL');
41
66
  this.db.run('PRAGMA foreign_keys = ON');
42
67
  this.schemas = schemas;
43
68
  this.options = options;
44
- this.pollInterval = options.pollInterval ?? 500;
69
+ this._reactive = options.reactive !== false; // default true
70
+ this._pollInterval = options.pollInterval ?? 100;
45
71
  this.relationships = options.relations ? parseRelationsConfig(options.relations, schemas) : [];
72
+
73
+ // Build the context that extracted modules use
74
+ this._ctx = {
75
+ db: this.db,
76
+ schemas: this.schemas as SchemaMap,
77
+ relationships: this.relationships,
78
+ attachMethods: (name, entity) => attachMethods(this._ctx, name, entity),
79
+ buildWhereClause: (conds, prefix) => buildWhereClause(conds, prefix),
80
+ };
81
+
46
82
  this.initializeTables();
47
- this.initializeChangeTracking();
83
+ if (this._reactive) this.initializeChangeTracking();
48
84
  this.runMigrations();
49
85
  if (options.indexes) this.createIndexes(options.indexes);
50
86
 
@@ -52,84 +88,100 @@ class _Database<Schemas extends SchemaMap> {
52
88
  for (const entityName of Object.keys(schemas)) {
53
89
  const key = entityName as keyof Schemas;
54
90
  const accessor: EntityAccessor<Schemas[typeof key]> = {
55
- insert: (data) => this.insert(entityName, data),
91
+ insert: (data) => insert(this._ctx, entityName, data),
92
+ insertMany: (rows: any[]) => insertMany(this._ctx, entityName, rows),
56
93
  update: (idOrData: any, data?: any) => {
57
- if (typeof idOrData === 'number') return this.update(entityName, idOrData, data);
58
- return this._createUpdateBuilder(entityName, idOrData);
94
+ if (typeof idOrData === 'number') return update(this._ctx, entityName, idOrData, data);
95
+ return createUpdateBuilder(this._ctx, entityName, idOrData);
96
+ },
97
+ upsert: (conditions, data) => upsert(this._ctx, entityName, data, conditions),
98
+ delete: (id) => deleteEntity(this._ctx, entityName, id),
99
+ select: (...cols: string[]) => createQueryBuilder(this._ctx, entityName, cols),
100
+ on: (event: ChangeEvent, callback: (row: any) => void | Promise<void>) => {
101
+ return this._registerListener(entityName, event, callback);
59
102
  },
60
- upsert: (conditions, data) => this.upsert(entityName, data, conditions),
61
- delete: (id) => this.delete(entityName, id),
62
- select: (...cols: string[]) => this._createQueryBuilder(entityName, cols),
63
103
  _tableName: entityName,
64
104
  };
65
105
  (this as any)[key] = accessor;
66
106
  }
67
107
  }
68
108
 
69
- // ===========================================================================
109
+ // =========================================================================
70
110
  // Table Initialization & Migrations
71
- // ===========================================================================
111
+ // =========================================================================
72
112
 
73
113
  private initializeTables(): void {
74
114
  for (const [entityName, schema] of Object.entries(this.schemas)) {
75
115
  const storableFields = getStorableFields(schema);
76
- const columnDefs = storableFields.map(f => `${f.name} ${zodTypeToSqlType(f.type)}`);
116
+ const columnDefs = storableFields.map(f => `"${f.name}" ${zodTypeToSqlType(f.type)}`);
77
117
  const constraints: string[] = [];
78
118
 
79
- // Add FOREIGN KEY constraints for FK columns declared in the schema
80
119
  const belongsToRels = this.relationships.filter(
81
120
  rel => rel.type === 'belongs-to' && rel.from === entityName
82
121
  );
83
122
  for (const rel of belongsToRels) {
84
- constraints.push(`FOREIGN KEY (${rel.foreignKey}) REFERENCES ${rel.to}(id) ON DELETE SET NULL`);
123
+ constraints.push(`FOREIGN KEY ("${rel.foreignKey}") REFERENCES "${rel.to}"(id) ON DELETE SET NULL`);
85
124
  }
86
125
 
87
126
  const allCols = columnDefs.join(', ');
88
127
  const allConstraints = constraints.length > 0 ? ', ' + constraints.join(', ') : '';
89
- this.db.run(`CREATE TABLE IF NOT EXISTS ${entityName} (id INTEGER PRIMARY KEY AUTOINCREMENT, ${allCols}${allConstraints})`);
128
+ this.db.run(`CREATE TABLE IF NOT EXISTS "${entityName}" (id INTEGER PRIMARY KEY AUTOINCREMENT, ${allCols}${allConstraints})`);
90
129
  }
91
130
  }
92
131
 
93
132
  /**
94
133
  * Initialize per-table change tracking using triggers.
95
134
  *
96
- * Creates a `_satidb_changes` table with one row per user table and a monotonic `seq` counter.
97
- * INSERT/UPDATE/DELETE triggers on each user table auto-increment the seq.
98
- * This enables table-specific, cross-process change detection no PRAGMA data_version needed.
135
+ * Creates a `_changes` table that logs every insert/update/delete with
136
+ * the table name, operation, and affected row id. This enables
137
+ * row-level change detection for the `on()` API.
99
138
  */
100
139
  private initializeChangeTracking(): void {
101
- this.db.run(`CREATE TABLE IF NOT EXISTS _satidb_changes (
102
- tbl TEXT PRIMARY KEY,
103
- seq INTEGER NOT NULL DEFAULT 0
140
+ this.db.run(`CREATE TABLE IF NOT EXISTS "_changes" (
141
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
142
+ tbl TEXT NOT NULL,
143
+ op TEXT NOT NULL,
144
+ row_id INTEGER NOT NULL
104
145
  )`);
105
146
 
106
147
  for (const entityName of Object.keys(this.schemas)) {
107
- // Ensure a row exists for this table
108
- this.db.run(`INSERT OR IGNORE INTO _satidb_changes (tbl, seq) VALUES (?, 0)`, entityName);
109
-
110
- // Create triggers (idempotent via IF NOT EXISTS)
111
- for (const op of ['insert', 'update', 'delete'] as const) {
112
- const triggerName = `_satidb_${entityName}_${op}`;
113
- const event = op.toUpperCase();
114
- this.db.run(`CREATE TRIGGER IF NOT EXISTS ${triggerName}
115
- AFTER ${event} ON ${entityName}
116
- BEGIN
117
- UPDATE _satidb_changes SET seq = seq + 1 WHERE tbl = '${entityName}';
118
- END`);
119
- }
148
+ // INSERT trigger logs NEW.id
149
+ this.db.run(`CREATE TRIGGER IF NOT EXISTS "_trg_${entityName}_insert"
150
+ AFTER INSERT ON "${entityName}"
151
+ BEGIN
152
+ INSERT INTO "_changes" (tbl, op, row_id) VALUES ('${entityName}', 'insert', NEW.id);
153
+ END`);
154
+
155
+ // UPDATE trigger logs NEW.id (post-update row)
156
+ this.db.run(`CREATE TRIGGER IF NOT EXISTS "_trg_${entityName}_update"
157
+ AFTER UPDATE ON "${entityName}"
158
+ BEGIN
159
+ INSERT INTO "_changes" (tbl, op, row_id) VALUES ('${entityName}', 'update', NEW.id);
160
+ END`);
161
+
162
+ // DELETE trigger — logs OLD.id (row that was deleted)
163
+ this.db.run(`CREATE TRIGGER IF NOT EXISTS "_trg_${entityName}_delete"
164
+ AFTER DELETE ON "${entityName}"
165
+ BEGIN
166
+ INSERT INTO "_changes" (tbl, op, row_id) VALUES ('${entityName}', 'delete', OLD.id);
167
+ END`);
120
168
  }
169
+
170
+ // Initialize watermark to current max (skip replaying historical changes)
171
+ const row = this.db.query('SELECT MAX(id) as maxId FROM "_changes"').get() as any;
172
+ this._changeWatermark = row?.maxId ?? 0;
121
173
  }
122
174
 
123
175
  private runMigrations(): void {
124
176
  for (const [entityName, schema] of Object.entries(this.schemas)) {
125
- const existingColumns = this.db.query(`PRAGMA table_info(${entityName})`).all() as any[];
177
+ const existingColumns = this.db.query(`PRAGMA table_info("${entityName}")`).all() as any[];
126
178
  const existingNames = new Set(existingColumns.map(c => c.name));
127
179
 
128
180
  const storableFields = getStorableFields(schema);
129
181
  for (const field of storableFields) {
130
182
  if (!existingNames.has(field.name)) {
131
183
  const sqlType = zodTypeToSqlType(field.type);
132
- this.db.run(`ALTER TABLE ${entityName} ADD COLUMN ${field.name} ${sqlType}`);
184
+ this.db.run(`ALTER TABLE "${entityName}" ADD COLUMN "${field.name}" ${sqlType}`);
133
185
  }
134
186
  }
135
187
  }
@@ -140,388 +192,110 @@ class _Database<Schemas extends SchemaMap> {
140
192
  for (const def of indexDefs) {
141
193
  const cols = Array.isArray(def) ? def : [def];
142
194
  const idxName = `idx_${tableName}_${cols.join('_')}`;
143
- this.db.run(`CREATE INDEX IF NOT EXISTS ${idxName} ON ${tableName} (${cols.join(', ')})`);
195
+ this.db.run(`CREATE INDEX IF NOT EXISTS "${idxName}" ON "${tableName}" (${cols.map(c => `"${c}"`).join(', ')})`);
144
196
  }
145
197
  }
146
198
  }
147
199
 
148
- // ===========================================================================
149
- // Revision Tracking (trigger-based + in-memory fast path)
150
- // ===========================================================================
151
-
152
- /** Bump the in-memory revision counter. Called by our CRUD methods (same-process fast path). */
153
- private _bumpRevision(entityName: string): void {
154
- this._revisions[entityName] = (this._revisions[entityName] ?? 0) + 1;
155
- }
156
-
157
- /**
158
- * Get the change sequence for a table.
159
- *
160
- * Reads from `_satidb_changes` — a per-table seq counter bumped by triggers
161
- * on every INSERT/UPDATE/DELETE, regardless of which connection performed the write.
162
- *
163
- * Combined with the in-memory counter for instant same-process detection.
164
- */
165
- public _getRevision(entityName: string): string {
166
- const rev = this._revisions[entityName] ?? 0;
167
- const row = this.db.query('SELECT seq FROM _satidb_changes WHERE tbl = ?').get(entityName) as any;
168
- const seq = row?.seq ?? 0;
169
- return `${rev}:${seq}`;
170
- }
171
-
172
- // ===========================================================================
173
- // CRUD
174
- // ===========================================================================
175
-
176
- private insert<T extends Record<string, any>>(entityName: string, data: Omit<T, 'id'>): AugmentedEntity<any> {
177
- const schema = this.schemas[entityName]!;
178
- const validatedData = asZodObject(schema).passthrough().parse(data);
179
- const transformed = transformForStorage(validatedData);
180
- const columns = Object.keys(transformed);
181
-
182
- const sql = columns.length === 0
183
- ? `INSERT INTO ${entityName} DEFAULT VALUES`
184
- : `INSERT INTO ${entityName} (${columns.join(', ')}) VALUES (${columns.map(() => '?').join(', ')})`;
200
+ // =========================================================================
201
+ // Change Listeners — db.table.on('insert' | 'update' | 'delete', cb)
202
+ // =========================================================================
185
203
 
186
- const result = this.db.query(sql).run(...Object.values(transformed));
187
- const newEntity = this._getById(entityName, result.lastInsertRowid as number);
188
- if (!newEntity) throw new Error('Failed to retrieve entity after insertion');
189
-
190
- this._bumpRevision(entityName);
191
- return newEntity;
192
- }
193
-
194
- /** Internal: get a single entity by ID */
195
- private _getById(entityName: string, id: number): AugmentedEntity<any> | null {
196
- const row = this.db.query(`SELECT * FROM ${entityName} WHERE id = ?`).get(id) as any;
197
- if (!row) return null;
198
- return this._attachMethods(entityName, transformFromStorage(row, this.schemas[entityName]!));
199
- }
200
-
201
- /** Internal: get a single entity by conditions */
202
- private _getOne(entityName: string, conditions: Record<string, any>): AugmentedEntity<any> | null {
203
- const { clause, values } = this.buildWhereClause(conditions);
204
- const row = this.db.query(`SELECT * FROM ${entityName} ${clause} LIMIT 1`).get(...values) as any;
205
- if (!row) return null;
206
- return this._attachMethods(entityName, transformFromStorage(row, this.schemas[entityName]!));
207
- }
208
-
209
- /** Internal: find multiple entities by conditions */
210
- private _findMany(entityName: string, conditions: Record<string, any> = {}): AugmentedEntity<any>[] {
211
- const { clause, values } = this.buildWhereClause(conditions);
212
- const rows = this.db.query(`SELECT * FROM ${entityName} ${clause}`).all(...values);
213
- return rows.map((row: any) =>
214
- this._attachMethods(entityName, transformFromStorage(row, this.schemas[entityName]!))
215
- );
216
- }
217
-
218
- private update<T extends Record<string, any>>(entityName: string, id: number, data: Partial<Omit<T, 'id'>>): AugmentedEntity<any> | null {
219
- const schema = this.schemas[entityName]!;
220
- const validatedData = asZodObject(schema).partial().parse(data);
221
- const transformed = transformForStorage(validatedData);
222
- if (Object.keys(transformed).length === 0) return this._getById(entityName, id);
223
-
224
- const setClause = Object.keys(transformed).map(key => `${key} = ?`).join(', ');
225
- this.db.query(`UPDATE ${entityName} SET ${setClause} WHERE id = ?`).run(...Object.values(transformed), id);
226
-
227
- this._bumpRevision(entityName);
228
- const updatedEntity = this._getById(entityName, id);
229
- return updatedEntity;
230
- }
231
-
232
- private _updateWhere(entityName: string, data: Record<string, any>, conditions: Record<string, any>): number {
233
- const schema = this.schemas[entityName]!;
234
- const validatedData = asZodObject(schema).partial().parse(data);
235
- const transformed = transformForStorage(validatedData);
236
- if (Object.keys(transformed).length === 0) return 0;
237
-
238
- const { clause, values: whereValues } = this.buildWhereClause(conditions);
239
- if (!clause) throw new Error('update().where() requires at least one condition');
240
-
241
- const setCols = Object.keys(transformed);
242
- const setClause = setCols.map(key => `${key} = ?`).join(', ');
243
- const result = this.db.query(`UPDATE ${entityName} SET ${setClause} ${clause}`).run(
244
- ...setCols.map(key => transformed[key]),
245
- ...whereValues
246
- );
204
+ private _registerListener(table: string, event: ChangeEvent, callback: (row: any) => void | Promise<void>): () => void {
205
+ if (!this._reactive) {
206
+ throw new Error(
207
+ 'Change listeners are disabled. Set { reactive: true } (or omit it) in Database options to enable .on().'
208
+ );
209
+ }
247
210
 
248
- const affected = (result as any).changes ?? 0;
249
- if (affected > 0) this._bumpRevision(entityName);
250
- return affected;
251
- }
211
+ const listener: Listener = { table, event, callback };
212
+ this._listeners.push(listener);
213
+ this._startPolling();
252
214
 
253
- private _createUpdateBuilder(entityName: string, data: Record<string, any>): UpdateBuilder<any> {
254
- let _conditions: Record<string, any> = {};
255
- const builder: UpdateBuilder<any> = {
256
- where: (conditions) => { _conditions = { ..._conditions, ...conditions }; return builder; },
257
- exec: () => this._updateWhere(entityName, data, _conditions),
215
+ return () => {
216
+ const idx = this._listeners.indexOf(listener);
217
+ if (idx >= 0) this._listeners.splice(idx, 1);
218
+ if (this._listeners.length === 0) this._stopPolling();
258
219
  };
259
- return builder;
260
220
  }
261
221
 
262
- private upsert<T extends Record<string, any>>(entityName: string, data: any, conditions: any = {}): AugmentedEntity<any> {
263
- const hasId = data?.id && typeof data.id === 'number';
264
- const existing = hasId
265
- ? this._getById(entityName, data.id)
266
- : Object.keys(conditions ?? {}).length > 0
267
- ? this._getOne(entityName, conditions)
268
- : null;
269
-
270
- if (existing) {
271
- const updateData = { ...data };
272
- delete updateData.id;
273
- return this.update(entityName, existing.id, updateData) as AugmentedEntity<any>;
274
- }
275
- const insertData = { ...(conditions ?? {}), ...(data ?? {}) };
276
- delete insertData.id;
277
- return this.insert(entityName, insertData);
222
+ private _startPolling(): void {
223
+ if (this._pollTimer) return;
224
+ this._pollTimer = setInterval(() => this._processChanges(), this._pollInterval);
278
225
  }
279
226
 
280
- private delete(entityName: string, id: number): void {
281
- const entity = this._getById(entityName, id);
282
- if (entity) {
283
- this.db.query(`DELETE FROM ${entityName} WHERE id = ?`).run(id);
284
- this._bumpRevision(entityName);
227
+ private _stopPolling(): void {
228
+ if (this._pollTimer) {
229
+ clearInterval(this._pollTimer);
230
+ this._pollTimer = null;
285
231
  }
286
232
  }
287
233
 
288
- // ===========================================================================
289
- // Entity Methods
290
- // ===========================================================================
291
-
292
- private _attachMethods<T extends Record<string, any>>(
293
- entityName: string, entity: T
294
- ): AugmentedEntity<any> {
295
- const augmented = entity as any;
296
- augmented.update = (data: any) => this.update(entityName, entity.id, data);
297
- augmented.delete = () => this.delete(entityName, entity.id);
298
-
299
- // Attach lazy relationship navigation
300
- for (const rel of this.relationships) {
301
- if (rel.from === entityName && rel.type === 'belongs-to') {
302
- // book.author() lazy load parent via author_id FK
303
- augmented[rel.relationshipField] = () => {
304
- const fkValue = entity[rel.foreignKey];
305
- return fkValue ? this._getById(rel.to, fkValue) : null;
306
- };
307
- } else if (rel.from === entityName && rel.type === 'one-to-many') {
308
- // author.books() → lazy load children
309
- const belongsToRel = this.relationships.find(
310
- r => r.type === 'belongs-to' && r.from === rel.to && r.to === rel.from
311
- );
312
- if (belongsToRel) {
313
- const fk = belongsToRel.foreignKey;
314
- augmented[rel.relationshipField] = () => {
315
- return this._findMany(rel.to, { [fk]: entity.id });
316
- };
317
- }
318
- }
319
- }
320
-
321
- // Auto-persist proxy: setting a field auto-updates the DB row
322
- const storableFieldNames = new Set(getStorableFields(this.schemas[entityName]!).map(f => f.name));
323
- return new Proxy(augmented, {
324
- set: (target, prop: string, value) => {
325
- if (storableFieldNames.has(prop) && target[prop] !== value) {
326
- this.update(entityName, target.id, { [prop]: value });
327
- }
328
- target[prop] = value;
329
- return true;
330
- },
331
- get: (target, prop, receiver) => Reflect.get(target, prop, receiver),
332
- });
333
- }
234
+ /**
235
+ * Core change dispatch loop.
236
+ *
237
+ * Fast path: checks MAX(id) against watermark first — if equal,
238
+ * there are no new changes and we skip entirely (no row materialization).
239
+ * Only fetches actual change rows when something has changed.
240
+ */
241
+ private _processChanges(): void {
242
+ // Fast path: check if anything changed at all (single scalar, index-only)
243
+ const head = this.db.query('SELECT MAX(id) as m FROM "_changes"').get() as any;
244
+ const maxId: number = head?.m ?? 0;
245
+ if (maxId <= this._changeWatermark) return;
246
+
247
+ const changes = this.db.query(
248
+ 'SELECT id, tbl, op, row_id FROM "_changes" WHERE id > ? ORDER BY id'
249
+ ).all(this._changeWatermark) as { id: number; tbl: string; op: string; row_id: number }[];
250
+
251
+ for (const change of changes) {
252
+ const listeners = this._listeners.filter(
253
+ l => l.table === change.tbl && l.event === change.op
254
+ );
334
255
 
335
- // ===========================================================================
336
- // SQL Helpers
337
- // ===========================================================================
338
-
339
- private buildWhereClause(conditions: Record<string, any>, tablePrefix?: string): { clause: string; values: any[] } {
340
- const parts: string[] = [];
341
- const values: any[] = [];
342
-
343
- for (const key in conditions) {
344
- if (key.startsWith('$')) {
345
- if (key === '$or' && Array.isArray(conditions[key])) {
346
- const orBranches = conditions[key] as Record<string, any>[];
347
- const orParts: string[] = [];
348
- for (const branch of orBranches) {
349
- const sub = this.buildWhereClause(branch, tablePrefix);
350
- if (sub.clause) {
351
- orParts.push(`(${sub.clause.replace(/^WHERE /, '')})`);
352
- values.push(...sub.values);
256
+ if (listeners.length > 0) {
257
+ if (change.op === 'delete') {
258
+ // Row is gone — pass just the id
259
+ const payload = { id: change.row_id };
260
+ for (const l of listeners) {
261
+ try { l.callback(payload); } catch { /* listener error */ }
262
+ }
263
+ } else {
264
+ // insert or update re-fetch the current row
265
+ const row = getById(this._ctx, change.tbl, change.row_id);
266
+ if (row) {
267
+ for (const l of listeners) {
268
+ try { l.callback(row); } catch { /* listener error */ }
353
269
  }
354
270
  }
355
- if (orParts.length > 0) parts.push(`(${orParts.join(' OR ')})`);
356
271
  }
357
- continue;
358
272
  }
359
- const value = conditions[key];
360
- const fieldName = tablePrefix ? `${tablePrefix}.${key}` : key;
361
273
 
362
- if (typeof value === 'object' && value !== null && !Array.isArray(value) && !(value instanceof Date)) {
363
- const operator = Object.keys(value)[0];
364
- if (!operator?.startsWith('$')) {
365
- throw new Error(`Querying on nested object '${key}' not supported. Use operators like $gt.`);
366
- }
367
- const operand = value[operator];
368
-
369
- if (operator === '$in') {
370
- if (!Array.isArray(operand)) throw new Error(`$in for '${key}' requires an array`);
371
- if (operand.length === 0) { parts.push('1 = 0'); continue; }
372
- parts.push(`${fieldName} IN (${operand.map(() => '?').join(', ')})`);
373
- values.push(...operand.map((v: any) => transformForStorage({ v }).v));
374
- continue;
375
- }
376
-
377
- const sqlOp = ({ $gt: '>', $gte: '>=', $lt: '<', $lte: '<=', $ne: '!=' } as Record<string, string>)[operator];
378
- if (!sqlOp) throw new Error(`Unsupported operator '${operator}' on '${key}'`);
379
- parts.push(`${fieldName} ${sqlOp} ?`);
380
- values.push(transformForStorage({ operand }).operand);
381
- } else {
382
- parts.push(`${fieldName} = ?`);
383
- values.push(transformForStorage({ value }).value);
384
- }
274
+ this._changeWatermark = change.id;
385
275
  }
386
276
 
387
- return { clause: parts.length > 0 ? `WHERE ${parts.join(' AND ')}` : '', values };
277
+ // Clean up consumed changes
278
+ this.db.run('DELETE FROM "_changes" WHERE id <= ?', this._changeWatermark);
388
279
  }
389
280
 
390
- // ===========================================================================
281
+ // =========================================================================
391
282
  // Transactions
392
- // ===========================================================================
283
+ // =========================================================================
393
284
 
394
285
  public transaction<T>(callback: () => T): T {
395
- try {
396
- this.db.run('BEGIN TRANSACTION');
397
- const result = callback();
398
- this.db.run('COMMIT');
399
- return result;
400
- } catch (error) {
401
- this.db.run('ROLLBACK');
402
- throw new Error(`Transaction failed: ${(error as Error).message}`);
403
- }
286
+ return this.db.transaction(callback)();
404
287
  }
405
288
 
406
- // ===========================================================================
407
- // Query Builders
408
- // ===========================================================================
409
-
410
- private _createQueryBuilder(entityName: string, initialCols: string[]): QueryBuilder<any> {
411
- const schema = this.schemas[entityName]!;
412
-
413
- const executor = (sql: string, params: any[], raw: boolean): any[] => {
414
- const rows = this.db.query(sql).all(...params);
415
- if (raw) return rows;
416
- return rows.map((row: any) => this._attachMethods(entityName, transformFromStorage(row, schema)));
417
- };
418
-
419
- const singleExecutor = (sql: string, params: any[], raw: boolean): any | null => {
420
- const results = executor(sql, params, raw);
421
- return results.length > 0 ? results[0] : null;
422
- };
423
-
424
- const joinResolver = (fromTable: string, toTable: string): { fk: string; pk: string } | null => {
425
- const belongsTo = this.relationships.find(
426
- r => r.type === 'belongs-to' && r.from === fromTable && r.to === toTable
427
- );
428
- if (belongsTo) return { fk: belongsTo.foreignKey, pk: 'id' };
429
- const reverse = this.relationships.find(
430
- r => r.type === 'belongs-to' && r.from === toTable && r.to === fromTable
431
- );
432
- if (reverse) return { fk: 'id', pk: reverse.foreignKey };
433
- return null;
434
- };
435
-
436
- // Pass revision getter — allows .subscribe() to detect ALL changes
437
- const revisionGetter = () => this._getRevision(entityName);
438
-
439
- // Condition resolver: { author: aliceEntity } → { author_id: 1 }
440
- const conditionResolver = (conditions: Record<string, any>): Record<string, any> => {
441
- const resolved: Record<string, any> = {};
442
- for (const [key, value] of Object.entries(conditions)) {
443
- // Detect entity references: objects with `id` and `delete` (augmented entities)
444
- if (value && typeof value === 'object' && typeof value.id === 'number' && typeof value.delete === 'function') {
445
- // Find a belongs-to relationship: entityName has a FK named `key_id` pointing to another table
446
- const fkCol = key + '_id';
447
- const rel = this.relationships.find(
448
- r => r.type === 'belongs-to' && r.from === entityName && r.foreignKey === fkCol
449
- );
450
- if (rel) {
451
- resolved[fkCol] = value.id;
452
- } else {
453
- // Fallback: try any relationship that matches the key as the nav name
454
- const relByNav = this.relationships.find(
455
- r => r.type === 'belongs-to' && r.from === entityName && r.to === key + 's'
456
- ) || this.relationships.find(
457
- r => r.type === 'belongs-to' && r.from === entityName && r.to === key
458
- );
459
- if (relByNav) {
460
- resolved[relByNav.foreignKey] = value.id;
461
- } else {
462
- resolved[key] = value; // pass through
463
- }
464
- }
465
- } else {
466
- resolved[key] = value;
467
- }
468
- }
469
- return resolved;
470
- };
471
-
472
- // Eager loader: resolves .with('books') → batch load children
473
- const eagerLoader = (parentTable: string, relation: string, parentIds: number[]): { key: string; groups: Map<number, any[]> } | null => {
474
- // 1. Try one-to-many: parentTable has-many relation (e.g., authors → books)
475
- const hasMany = this.relationships.find(
476
- r => r.type === 'one-to-many' && r.from === parentTable && r.relationshipField === relation
477
- );
478
- if (hasMany) {
479
- // Find the belongs-to FK on the child table
480
- const belongsTo = this.relationships.find(
481
- r => r.type === 'belongs-to' && r.from === hasMany.to && r.to === parentTable
482
- );
483
- if (belongsTo) {
484
- const fk = belongsTo.foreignKey;
485
- const placeholders = parentIds.map(() => '?').join(', ');
486
- const childRows = this.db.query(
487
- `SELECT * FROM ${hasMany.to} WHERE ${fk} IN (${placeholders})`
488
- ).all(...parentIds) as any[];
489
-
490
- const groups = new Map<number, any[]>();
491
- const childSchema = this.schemas[hasMany.to]!;
492
- for (const rawRow of childRows) {
493
- const entity = this._attachMethods(
494
- hasMany.to,
495
- transformFromStorage(rawRow, childSchema)
496
- );
497
- const parentId = rawRow[fk] as number;
498
- if (!groups.has(parentId)) groups.set(parentId, []);
499
- groups.get(parentId)!.push(entity);
500
- }
501
- return { key: relation, groups };
502
- }
503
- }
504
-
505
- // 2. Try belongs-to: parentTable belongs-to relation (e.g., books → author)
506
- const belongsTo = this.relationships.find(
507
- r => r.type === 'belongs-to' && r.from === parentTable && r.relationshipField === relation
508
- );
509
- if (belongsTo) {
510
- // Load parent entities and map by id
511
- const fkValues = [...new Set(parentIds)];
512
- // Actually we need FK values from parent rows, not parent IDs
513
- // This case is trickier — skip for now, belongs-to is already handled by lazy nav
514
- return null;
515
- }
516
-
517
- return null;
518
- };
519
-
520
- const builder = new QueryBuilder(entityName, executor, singleExecutor, joinResolver, conditionResolver, revisionGetter, eagerLoader, this.pollInterval);
521
- if (initialCols.length > 0) builder.select(...initialCols);
522
- return builder;
289
+ /** Close the database: stops polling and releases the SQLite handle. */
290
+ public close(): void {
291
+ this._stopPolling();
292
+ this.db.close();
523
293
  }
524
294
 
295
+ // =========================================================================
296
+ // Proxy Query
297
+ // =========================================================================
298
+
525
299
  /** Proxy callback query for complex SQL-like JOINs */
526
300
  public query<T extends Record<string, any> = Record<string, any>>(
527
301
  callback: (ctx: { [K in keyof Schemas]: ProxyColumns<InferSchema<Schemas[K]>> }) => ProxyQueryResult