masterrecord 1.5.17 → 1.22.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,41 @@
1
+ /**
2
+ * A trusted raw SQL fragment for set-based updates — the counterpart of
3
+ * EF Core's `SetProperty(b => b.Views, b => b.Views + 1)` (referencing the
4
+ * existing column value in the SET clause).
5
+ *
6
+ * await db.Blogs.where('b => b.rating < $$', 3).executeUpdate({
7
+ * views: sql`views + 1`, // raw fragment, inlined verbatim
8
+ * hidden: true, // plain value, parameterized
9
+ * });
10
+ *
11
+ * The fragment is inlined into the statement, so it is developer-owned SQL.
12
+ * To keep it injection-safe by construction, the tagged template REFUSES
13
+ * interpolations (`sql\`views + ${n}\`` throws) — pass dynamic values as
14
+ * ordinary setter values, which are parameterized.
15
+ */
16
+ class RawSql {
17
+ constructor(fragment) {
18
+ if (typeof fragment !== 'string' || fragment.trim() === '') {
19
+ throw new TypeError('masterrecord: sql() requires a non-empty SQL fragment string.');
20
+ }
21
+ this.__rawSql = fragment;
22
+ Object.freeze(this);
23
+ }
24
+ toString() { return this.__rawSql; }
25
+ }
26
+
27
+ function sql(strings, ...values) {
28
+ // sql('views + 1')
29
+ if (typeof strings === 'string') return new RawSql(strings);
30
+ // sql`views + 1` (tagged template, no interpolations)
31
+ if (values.length > 0) {
32
+ throw new TypeError(
33
+ 'masterrecord: sql`...` does not accept interpolated values (they would be inlined unparameterized). ' +
34
+ 'Put dynamic values in ordinary setter properties instead — those are sent as parameters.'
35
+ );
36
+ }
37
+ return new RawSql(Array.isArray(strings) ? strings.join('') : String(strings));
38
+ }
39
+
40
+ export { RawSql, sql };
41
+ export default sql;
package/SQLLiteEngine.js CHANGED
@@ -1,6 +1,7 @@
1
1
  // Version 0.0.23
2
2
  import tools from './Tools.js';
3
3
  import FieldTransformer from './Entity/fieldTransformer.js';
4
+ import { logCommand } from './logging.js';
4
5
 
5
6
  class SQLLiteEngine {
6
7
 
@@ -13,19 +14,113 @@ class SQLLiteEngine {
13
14
  throw new Error('UPDATE failed: Invalid parameterized query structure. Check entity definition.');
14
15
  }
15
16
 
16
- const sqlQuery = ` UPDATE [${query.tableName}]
17
- SET ${query.arg.sql}
18
- WHERE [${query.tableName}].[${query.primaryKey}] = ?`;
19
- // Add primaryKeyValue to params array
17
+ // Optimistic concurrency: a rowVersion column is bumped atomically in
18
+ // the same statement, and every concurrency token's ORIGINAL value is
19
+ // appended to the WHERE so a concurrently-modified row matches 0 rows
20
+ // (the caller checks affectedRows and throws ConcurrencyError).
21
+ const t = query.tableName;
22
+ let setSql = query.arg.sql;
23
+ if (query.rowVersionColumn) {
24
+ setSql += `, [${query.rowVersionColumn}] = [${query.rowVersionColumn}] + 1`;
25
+ }
20
26
  const params = [...query.arg.params, query.primaryKeyValue];
27
+ let where = `[${t}].[${query.primaryKey}] = ?`;
28
+ for (const c of (query.concurrency || [])) {
29
+ if (c.value === null || c.value === undefined) { where += ` AND [${t}].[${c.column}] IS NULL`; }
30
+ else { where += ` AND [${t}].[${c.column}] = ?`; params.push(c.value); }
31
+ }
32
+ const sqlQuery = ` UPDATE [${t}]
33
+ SET ${setSql}
34
+ WHERE ${where}`;
21
35
  return Promise.resolve(this._runWithParams(sqlQuery, params));
22
36
  }
23
37
 
24
38
  async delete(queryObject){
25
39
  const sqlObject = this._buildDeleteObject(queryObject);
26
40
  // Use parameterized query to prevent SQL injection
27
- const sqlQuery = `DELETE FROM [${sqlObject.tableName}] WHERE [${sqlObject.tableName}].[${sqlObject.primaryKey}] = ?`;
28
- return Promise.resolve(this._executeWithParams(sqlQuery, [sqlObject.value]));
41
+ const params = [sqlObject.value];
42
+ let where = `[${sqlObject.tableName}].[${sqlObject.primaryKey}] = ?`;
43
+ for (const c of (queryObject.__concurrency || [])) {
44
+ if (c.value === null || c.value === undefined) { where += ` AND [${sqlObject.tableName}].[${c.column}] IS NULL`; }
45
+ else { where += ` AND [${sqlObject.tableName}].[${c.column}] = ?`; params.push(c.value); }
46
+ }
47
+ const sqlQuery = `DELETE FROM [${sqlObject.tableName}] WHERE ${where}`;
48
+ return Promise.resolve(this._runWithParams(sqlQuery, params));
49
+ }
50
+
51
+ /** Connection probe (context.healthCheck()): never throws. */
52
+ async healthCheck(){
53
+ try {
54
+ if (!this.db) return { healthy: false, error: 'Not connected' };
55
+ const row = this.db.prepare('SELECT sqlite_version() AS version').get();
56
+ return { healthy: true, version: row ? row.version : undefined, open: this.db.open !== false, inTransaction: !!this.db.inTransaction };
57
+ } catch (err) {
58
+ return { healthy: false, error: err.message };
59
+ }
60
+ }
61
+
62
+ /** Rows matched by the last UPDATE/DELETE (driver-specific result shape). */
63
+ affectedRows(result){
64
+ if (!result) return 0;
65
+ if (typeof result.changes === 'number') return result.changes;
66
+ return 0;
67
+ }
68
+
69
+ // ---- Set-based writes from a compiled query (EF ExecuteUpdate / ExecuteDelete) ----
70
+ // Reuse the query's own compiled WHERE (same alias, same parameters) so the
71
+ // rows affected are exactly the rows the equivalent SELECT would return.
72
+
73
+ async executeUpdate(query, entity, setters){
74
+ const alias = this.getEntity(entity.__name, query.entityMap) || entity.__name;
75
+ const whereSql = `${this.buildWhere(query, entity)} ${this.buildAnd(query, entity)}`.trim();
76
+ const whereParams = query.parameters ? query.parameters.getParams() : [];
77
+ const setParts = [], setParams = [];
78
+ for (const s of setters) {
79
+ if (s.raw !== undefined) { setParts.push(`[${s.column}] = ${s.raw}`); }
80
+ else { setParts.push(`[${s.column}] = ?`); setParams.push(s.value); }
81
+ }
82
+ const sql = `UPDATE [${entity.__name}] AS ${alias} SET ${setParts.join(', ')} ${whereSql}`;
83
+ return this.affectedRows(this._runWithParams(sql, [...setParams, ...whereParams]));
84
+ }
85
+
86
+ async executeDelete(query, entity){
87
+ const alias = this.getEntity(entity.__name, query.entityMap) || entity.__name;
88
+ const whereSql = `${this.buildWhere(query, entity)} ${this.buildAnd(query, entity)}`.trim();
89
+ const whereParams = query.parameters ? query.parameters.getParams() : [];
90
+ const sql = `DELETE FROM [${entity.__name}] AS ${alias} ${whereSql}`;
91
+ return this.affectedRows(this._runWithParams(sql, whereParams));
92
+ }
93
+
94
+ /**
95
+ * EF GroupBy + aggregates: SELECT <groups>, <aggs> ... GROUP BY [HAVING] [ORDER BY] [LIMIT/OFFSET].
96
+ * groups: [{ column }], aggs: [{ alias, fn, column|null }], having: [{ agg, op, value }],
97
+ * orderBy: [{ name, desc }]. Identifiers are validated by the caller.
98
+ */
99
+ async getGrouped(queryObject, entity, groups, aggs, having, orderBy){
100
+ const q = queryObject.script;
101
+ const alias = this.getEntity(entity.__name, q.entityMap) || entity.__name;
102
+ const sel = [
103
+ ...groups.map(g => `${alias}.[${g.column}] AS [${g.column}]`),
104
+ ...aggs.map(a => `${a.fn}(${a.column ? `${alias}.[${a.column}]` : '*'}) AS [${a.alias}]`),
105
+ ].join(', ');
106
+ const params = q.parameters ? [...q.parameters.getParams()] : [];
107
+ let sql = `SELECT ${sel} ${this.buildFrom(q, entity)} ${this.buildWhere(q, entity)} ${this.buildAnd(q, entity)} GROUP BY ${groups.map(g => `${alias}.[${g.column}]`).join(', ')}`;
108
+ if (having && having.length) {
109
+ sql += ' HAVING ' + having.map(h => { params.push(h.value); return `${h.agg.fn}(${h.agg.column ? `${alias}.[${h.agg.column}]` : '*'}) ${h.op} ?`; }).join(' AND ');
110
+ }
111
+ sql += (orderBy && orderBy.length) ? ` ORDER BY ${orderBy.map(o => `[${o.name}]${o.desc ? ' DESC' : ' ASC'}`).join(', ')}` : ` ORDER BY ${groups.map(g => `[${g.column}]`).join(', ')}`;
112
+ sql += ` ${this.buildTake(q)} ${this.buildSkip(q)}`;
113
+ return this._observed(sql, params, () => this.db.prepare(sql).all(...this._bind(params)));
114
+ }
115
+
116
+ /** Scalar aggregate over the query's rows (EF Sum/Average/Min/Max): fn in SUM|AVG|MIN|MAX. */
117
+ async getAggregate(queryObject, entity, fn, column){
118
+ const q = queryObject.script;
119
+ const alias = this.getEntity(entity.__name, q.entityMap) || entity.__name;
120
+ const sql = `SELECT ${fn}(${alias}.[${column}]) AS value ${this.buildFrom(q, entity)} ${this.buildWhere(q, entity)} ${this.buildAnd(q, entity)}`;
121
+ const params = q.parameters ? q.parameters.getParams() : [];
122
+ const row = this._observed(sql, params, () => this.db.prepare(sql).get(...this._bind(params)));
123
+ return row ? row.value : null;
29
124
  }
30
125
 
31
126
  async insert(queryObject){
@@ -127,11 +222,7 @@ class SQLLiteEngine {
127
222
  if(queryString.query){
128
223
  // Get parameters from query script
129
224
  const params = query.parameters ? query.parameters.getParams() : [];
130
- if (process.env.LOG_SQL === 'true' || process.env.NODE_ENV !== 'production') {
131
- console.debug("[SQL]", queryString.query);
132
- console.debug("[Params]", params);
133
- }
134
- const queryReturn = this.db.prepare(queryString.query).get(...params);
225
+ const queryReturn = this._observed(queryString.query, params, () => this.db.prepare(queryString.query).get(...this._bind(params)));
135
226
  return Promise.resolve(queryReturn);
136
227
  }
137
228
  return Promise.resolve(null);
@@ -176,7 +267,10 @@ class SQLLiteEngine {
176
267
  // PRAGMA on a non-existent table returns an empty list (not an
177
268
  // error), so a genuinely-absent table is [] — only real failures
178
269
  // throw.
179
- const rows = this.db.prepare(`PRAGMA table_info(${tableName})`).all();
270
+ // table_xinfo (not table_info): it also lists GENERATED columns
271
+ // (hidden = 2 VIRTUAL / 3 STORED), which table_info omits — without
272
+ // it a computed() column would look missing on every schema sync.
273
+ const rows = this.db.prepare(`PRAGMA table_xinfo(${tableName})`).all();
180
274
  return rows || [];
181
275
  }catch(err){
182
276
  throw new Error(`masterrecord: could not read columns for table '${tableName}' (SQLite introspection failed): ${err.message}`);
@@ -204,11 +298,7 @@ class SQLLiteEngine {
204
298
  const queryCount = queryString.query
205
299
  // Get parameters from query script
206
300
  const params = query.parameters ? query.parameters.getParams() : [];
207
- if (process.env.LOG_SQL === 'true' || process.env.NODE_ENV !== 'production') {
208
- console.debug("[SQL]", queryCount);
209
- console.debug("[Params]", params);
210
- }
211
- const queryReturn = this.db.prepare(queryCount).get(...params);
301
+ const queryReturn = this._observed(queryCount, params, () => this.db.prepare(queryCount).get(...this._bind(params)));
212
302
  return Promise.resolve(queryReturn);
213
303
  }
214
304
  return Promise.resolve(null);
@@ -235,11 +325,7 @@ class SQLLiteEngine {
235
325
  if(selectQuery.query){
236
326
  // Get parameters from query script
237
327
  const params = query.parameters ? query.parameters.getParams() : [];
238
- if (process.env.LOG_SQL === 'true' || process.env.NODE_ENV !== 'production') {
239
- console.debug("[SQL]", selectQuery.query);
240
- console.debug("[Params]", params);
241
- }
242
- const queryReturn = this.db.prepare(selectQuery.query).all(...params);
328
+ const queryReturn = this._observed(selectQuery.query, params, () => this.db.prepare(selectQuery.query).all(...this._bind(params)));
243
329
  return Promise.resolve(queryReturn);
244
330
  }
245
331
  return Promise.resolve(null);
@@ -372,6 +458,17 @@ class SQLLiteEngine {
372
458
  strQuery = "ORDER BY";
373
459
  strQuery += ` ${fieldList.join(', ')} ${orderByType}`;
374
460
  }
461
+ // thenBy / thenByDescending (EF ThenBy): secondary sort keys, each with
462
+ // its own direction, appended after the primary ORDER BY.
463
+ const thenBy = Array.isArray(query.thenBy) ? query.thenBy : [];
464
+ if (thenBy.length) {
465
+ const entityAlias = this.getEntity(query.parentName, query.entityMap);
466
+ const extra = thenBy.map(t => {
467
+ if (entity && !entity[t.field]) throw new Error(`Invalid ORDER BY field: ${t.field} not found in ${entity.__name || 'entity'}`);
468
+ return `${entityAlias}.${t.field} ${t.dir === 'DESC' ? 'DESC' : 'ASC'}`;
469
+ });
470
+ strQuery = strQuery ? `${strQuery}, ${extra.join(', ')}` : `ORDER BY ${extra.join(', ')}`;
471
+ }
375
472
  return strQuery;
376
473
  }
377
474
 
@@ -616,7 +713,7 @@ class SQLLiteEngine {
616
713
 
617
714
  buildSelect(query, entity){
618
715
  // this means that there is a select statement
619
- const select = "SELECT";
716
+ const select = query.distinct ? "SELECT DISTINCT" : "SELECT";
620
717
  const arr = [];
621
718
  const $that = this;
622
719
  if(query.select){
@@ -798,7 +895,7 @@ class SQLLiteEngine {
798
895
  _buildSQLEqualTo(model){
799
896
  const $that = this;
800
897
  let argument = null;
801
- const dirtyFields = model.__dirtyFields;
898
+ const dirtyFields = (model.__dirtyFields || []).filter(f => !(model.__entity[f] && model.__entity[f].computedSql)); // computed columns are never written
802
899
 
803
900
  for (const column in dirtyFields) {
804
901
 
@@ -813,10 +910,10 @@ class SQLLiteEngine {
813
910
  persistedValue = model["_" + fieldName];
814
911
  break;
815
912
  case "belongsTo":
816
- persistedValue = model["_" + fieldName] !== undefined ? model["_" + fieldName] : model[fieldName];
913
+ persistedValue = tools.foreignKeyValue(model, fieldName);
817
914
  break;
818
915
  default:
819
- persistedValue = model[fieldName];
916
+ persistedValue = (model.__entity[fieldName] && model.__entity[fieldName].relationshipType === "belongsTo") ? tools.foreignKeyValue(model, fieldName) : model[fieldName];
820
917
  }
821
918
  const isEmptyString = (typeof persistedValue === 'string') && (persistedValue.trim() === '');
822
919
  if(persistedValue === undefined || persistedValue === null || isEmptyString){
@@ -833,7 +930,7 @@ class SQLLiteEngine {
833
930
  switch(type){
834
931
  case "belongsTo" : {
835
932
  const foreignKey = model.__entity[dirtyFields[column]].foreignKey;
836
- let fkValue = model[dirtyFields[column]];
933
+ let fkValue = tools.foreignKeyValue(model, dirtyFields[column]);
837
934
  // 🔥 NEW: Validate foreign key type
838
935
  try {
839
936
  fkValue = $that._validateAndCoerceFieldType(fkValue, model.__entity[dirtyFields[column]], model.__entity.__name, dirtyFields[column]);
@@ -921,7 +1018,7 @@ class SQLLiteEngine {
921
1018
  const $that = this;
922
1019
  const sqlParts = [];
923
1020
  const params = [];
924
- const dirtyFields = model.__dirtyFields;
1021
+ const dirtyFields = (model.__dirtyFields || []).filter(f => !(model.__entity[f] && model.__entity[f].computedSql)); // computed columns are never written
925
1022
 
926
1023
  for (const column in dirtyFields) {
927
1024
  // Validate non-nullable constraints on updates
@@ -932,7 +1029,7 @@ class SQLLiteEngine {
932
1029
  // bypassing get() which may change the type (e.g. parseFloat)
933
1030
  let persistedValue = model["_" + fieldName];
934
1031
  if(persistedValue === undefined){
935
- persistedValue = model[fieldName];
1032
+ persistedValue = (model.__entity[fieldName] && model.__entity[fieldName].relationshipType === "belongsTo") ? tools.foreignKeyValue(model, fieldName) : model[fieldName];
936
1033
  }
937
1034
  const isEmptyString = (typeof persistedValue === 'string') && (persistedValue.trim() === '');
938
1035
  if(persistedValue === undefined || persistedValue === null || isEmptyString){
@@ -950,7 +1047,7 @@ class SQLLiteEngine {
950
1047
  switch(type){
951
1048
  case "belongsTo": {
952
1049
  const foreignKey = model.__entity[dirtyFields[column]].foreignKey;
953
- let fkValue = model[dirtyFields[column]];
1050
+ let fkValue = tools.foreignKeyValue(model, dirtyFields[column]);
954
1051
 
955
1052
  // 🔥 Apply toDatabase transformer before validation
956
1053
  try {
@@ -964,9 +1061,8 @@ class SQLLiteEngine {
964
1061
  } catch(typeError) {
965
1062
  throw new Error(`UPDATE failed: ${typeError.message}`);
966
1063
  }
967
- var fore = `_${dirtyFields[column]}`;
968
1064
  sqlParts.push(`[${foreignKey}] = ?`);
969
- params.push(model[fore]);
1065
+ params.push(fkValue);
970
1066
  break;
971
1067
  }
972
1068
  case "integer":
@@ -1194,10 +1290,13 @@ class SQLLiteEngine {
1194
1290
  for (let column in modelEntity) {
1195
1291
  // column1 = value1, column2 = value2, ...
1196
1292
  if(column.indexOf("__") === -1 ){
1293
+ if (modelEntity[column] && modelEntity[column].computedSql) continue; // computed column: DB-generated, never written
1197
1294
  // call the get method if avlable
1198
1295
  let fieldColumn = "";
1199
1296
  // check if get function is avaliable if so use that
1200
- fieldColumn = fields[column];
1297
+ fieldColumn = (modelEntity[column] && modelEntity[column].relationshipType === "belongsTo")
1298
+ ? tools.foreignKeyValue(fields, column)
1299
+ : fields[column];
1201
1300
 
1202
1301
  if((fieldColumn !== undefined && fieldColumn !== null ) && typeof(fieldColumn) !== "object"){
1203
1302
  // 🔥 NEW: Validate and coerce field type before processing
@@ -1264,15 +1363,12 @@ class SQLLiteEngine {
1264
1363
  for (const column in modelEntity) {
1265
1364
  // Skip internal properties
1266
1365
  if(column.indexOf("__") === -1 ){
1267
- let fieldColumn = fields[column];
1268
-
1269
- // 🔥 FIX: For belongsTo relationships, also check the foreignKey field name
1270
- // Users can set either orgRole.User = obj OR orgRole.user_id = 2
1271
- if((fieldColumn === undefined || fieldColumn === null) &&
1272
- modelEntity[column].relationshipType === "belongsTo" &&
1273
- modelEntity[column].foreignKey) {
1274
- fieldColumn = fields[modelEntity[column].foreignKey];
1275
- }
1366
+ if (modelEntity[column] && modelEntity[column].computedSql) continue; // computed column: DB-generated, never written
1367
+ // belongsTo: persist the FK VALUE (assigned entity -> its PK, or
1368
+ // the primitive / FK column), never the navigation getter.
1369
+ let fieldColumn = (modelEntity[column] && modelEntity[column].relationshipType === "belongsTo")
1370
+ ? tools.foreignKeyValue(fields, column)
1371
+ : fields[column];
1276
1372
 
1277
1373
  // Auto-increment primary keys are assigned by the database, so
1278
1374
  // they must never be emitted in the INSERT unless the caller
@@ -1394,30 +1490,65 @@ class SQLLiteEngine {
1394
1490
  if (process.env.MR_SILENT_MIGRATIONS !== 'true') {
1395
1491
  console.log("[masterrecord:migration]", typeof query === 'string' ? query.replace(/\s+/g, ' ').trim() : query);
1396
1492
  }
1397
- return this.db.exec(query);
1493
+ return this._observed(query, [], () => this.db.exec(query));
1398
1494
  }
1399
1495
 
1400
1496
  _executeWithParams(query, params = []){
1401
- if (process.env.MR_SILENT_MIGRATIONS !== 'true') {
1402
- console.log("[masterrecord:migration]", typeof query === 'string' ? query.replace(/\s+/g, ' ').trim() : query);
1403
- if (params && params.length) console.log("[masterrecord:migration] params", params);
1404
- }
1405
- return this.db.prepare(query).run(...params);
1497
+ // Migration DDL: logged at info (unless MR_SILENT_MIGRATIONS) via logging.js
1498
+ return this._observed(query, params, () => this.db.prepare(query).run(...this._bind(params)), { migration: true });
1406
1499
  }
1407
1500
 
1408
1501
  _run(query){
1409
- if (process.env.LOG_SQL === 'true' || process.env.NODE_ENV !== 'production') {
1410
- console.debug("[SQL]", query);
1411
- }
1412
- return this.db.prepare(query).run();
1502
+ return this._observed(query, [], () => this.db.prepare(query).run());
1413
1503
  }
1414
1504
 
1415
1505
  _runWithParams(query, params = []){
1416
- if (process.env.LOG_SQL === 'true' || process.env.NODE_ENV !== 'production') {
1417
- console.debug("[SQL]", query);
1418
- console.debug("[Params]", params);
1506
+ return this._observed(query, params, () => this.db.prepare(query).run(...this._bind(params)));
1507
+ }
1508
+
1509
+ // ---- Command observation (EF IDbCommandInterceptor / CommandExecuted) ----
1510
+ // Every command is timed and reported to (a) the central logger (logging.js:
1511
+ // redacted params by default, slow-query warnings) and (b) any observers
1512
+ // registered by contexts sharing this engine ('command' event):
1513
+ // { sql, params, durationMs, engine: 'sqlite', error?, migration? }.
1514
+ addCommandObserver(fn){ (this.__commandObservers ||= new Set()).add(fn); }
1515
+ removeCommandObserver(fn){ if (this.__commandObservers) this.__commandObservers.delete(fn); }
1516
+ _notifyCommand(info){
1517
+ logCommand(info);
1518
+ if (!this.__commandObservers || this.__commandObservers.size === 0) return;
1519
+ for (const fn of Array.from(this.__commandObservers)) {
1520
+ try { fn(info); } catch (e) { console.error('[SQLite] command observer threw:', e); }
1521
+ }
1522
+ }
1523
+ /** Run `exec` (sync), time it, notify logger + observers; rethrows errors. */
1524
+ /**
1525
+ * Normalize bound parameters for better-sqlite3, which binds only numbers,
1526
+ * strings, bigints, buffers and null: booleans -> 1/0 (the engine stores
1527
+ * booleans as INTEGER), undefined -> null, Date -> ISO string. Applied at
1528
+ * every statement execution so `where('x => x.flag == $$', true)` and
1529
+ * boolean query filters work like on MySQL/Postgres.
1530
+ */
1531
+ _bind(params){
1532
+ if (!Array.isArray(params)) return [];
1533
+ return params.map(v => {
1534
+ if (v === true) return 1;
1535
+ if (v === false) return 0;
1536
+ if (v === undefined) return null;
1537
+ if (v instanceof Date) return v.toISOString();
1538
+ return v;
1539
+ });
1540
+ }
1541
+
1542
+ _observed(sql, params, exec, extra){
1543
+ const start = process.hrtime.bigint();
1544
+ try {
1545
+ const out = exec();
1546
+ this._notifyCommand({ sql, params, durationMs: Number(process.hrtime.bigint() - start) / 1e6, engine: 'sqlite', ...(extra || {}) });
1547
+ return out;
1548
+ } catch (error) {
1549
+ this._notifyCommand({ sql, params, durationMs: Number(process.hrtime.bigint() - start) / 1e6, engine: 'sqlite', error, ...(extra || {}) });
1550
+ throw error;
1419
1551
  }
1420
- return this.db.prepare(query).run(...params);
1421
1552
  }
1422
1553
 
1423
1554
  // Engine-agnostic raw query backing the public ctx.query()/ctx.execute().
@@ -1425,13 +1556,9 @@ class SQLLiteEngine {
1425
1556
  // RETURNING); for writes returns better-sqlite3's run info
1426
1557
  // ({ changes, lastInsertRowid }). `stmt.reader` tells the two apart.
1427
1558
  query(query, params = []){
1428
- if (process.env.LOG_SQL === 'true' || process.env.NODE_ENV !== 'production') {
1429
- console.debug("[SQL]", query);
1430
- if (params && params.length) console.debug("[Params]", params);
1431
- }
1432
1559
  const stmt = this.db.prepare(query);
1433
1560
  const args = Array.isArray(params) ? params : (params === undefined ? [] : [params]);
1434
- return stmt.reader ? stmt.all(...args) : stmt.run(...args);
1561
+ return this._observed(query, args, () => (stmt.reader ? stmt.all(...this._bind(args)) : stmt.run(...this._bind(args))));
1435
1562
  }
1436
1563
 
1437
1564
  setDB(db, type){
package/Tools.js CHANGED
@@ -57,6 +57,30 @@ class Tools{
57
57
  }
58
58
  }
59
59
 
60
+ /** All primary-key field names (EF HasKey(a, b)); [] when none. */
61
+ static primaryKeys(model){
62
+ const out = [];
63
+ if (!model) return out;
64
+ for (const key of Object.keys(model)) {
65
+ if (key.startsWith('__')) continue;
66
+ const f = model[key];
67
+ if (f && typeof f === 'object' && f.primary === true) out.push(key);
68
+ }
69
+ return out;
70
+ }
71
+
72
+ static isCompositeKey(model){
73
+ return Tools.primaryKeys(model).length > 1;
74
+ }
75
+
76
+ /** Key values of an entity as { field: value } (read without invoking navigation getters). */
77
+ static keyValues(entity){
78
+ const out = {};
79
+ if (!entity || !entity.__entity) return out;
80
+ for (const k of Tools.primaryKeys(entity.__entity)) out[k] = Tools.dataValue(entity, k);
81
+ return out;
82
+ }
83
+
60
84
  static findForeignTable(name, model){
61
85
  for (const key in model) {
62
86
  if (Object.prototype.hasOwnProperty.call(model, key)) {
@@ -126,6 +150,55 @@ class Tools{
126
150
 
127
151
  }
128
152
 
153
+ /**
154
+ * Read a field's stored value WITHOUT invoking a navigation getter:
155
+ * a plain data property (new Model() before tracking accessors exist),
156
+ * else the tracked backing slot `_<key>` on the prototype.
157
+ */
158
+ static dataValue(obj, key) {
159
+ if (!obj || typeof obj !== 'object') return undefined;
160
+ const d = Object.getOwnPropertyDescriptor(obj, key);
161
+ if (d && 'value' in d) return d.value;
162
+ const proto = Object.getPrototypeOf(obj);
163
+ if (proto && ('_' + key) in proto) return proto['_' + key];
164
+ return undefined;
165
+ }
166
+
167
+ /**
168
+ * The foreign-key VALUE to persist for a belongsTo field — the single place
169
+ * the engines read it for INSERT/UPDATE, so a loaded navigation entity (or
170
+ * an in-flight lazy-load Promise) can never leak into SQL.
171
+ *
172
+ * Resolution order (EF fix-up semantics):
173
+ * 1. the navigation slot: an assigned entity -> its primary key; an
174
+ * assigned primitive (`post.author = authorId`) -> itself; null -> null;
175
+ * 2. otherwise the FK column itself (`post.author_id`).
176
+ */
177
+ static foreignKeyValue(model, fieldName) {
178
+ if (!model || typeof model !== 'object') return undefined;
179
+ const def = model.__entity ? model.__entity[fieldName] : undefined;
180
+ const nav = Tools.dataValue(model, fieldName);
181
+ if (nav === null) return null;
182
+ if (nav !== undefined && typeof nav !== 'function' && !(typeof nav.then === 'function')) {
183
+ if (typeof nav === 'object') {
184
+ if (nav.__entity) {
185
+ const pk = Tools.getPrimaryKeyObject(nav.__entity);
186
+ const pkVal = pk ? Tools.dataValue(nav, pk) : undefined;
187
+ if (pkVal !== undefined) return pkVal;
188
+ } else if (!(nav instanceof Date)) {
189
+ return nav; // plain object: let the type validator report it
190
+ }
191
+ } else {
192
+ return nav;
193
+ }
194
+ }
195
+ if (def && def.foreignKey) {
196
+ const fk = Tools.dataValue(model, def.foreignKey);
197
+ if (fk !== undefined && (fk === null || (typeof fk !== 'object' && typeof fk !== 'function'))) return fk;
198
+ }
199
+ return undefined;
200
+ }
201
+
129
202
  static removePrimarykeyandVirtual(currentModel, modelEntity){
130
203
  const newCurrentModel = Object.create(currentModel);
131
204