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.
package/logging.js ADDED
@@ -0,0 +1,109 @@
1
+ /**
2
+ * Central, pluggable logging — EF Core's LogTo()/ILogger integration with
3
+ * EF's default of NOT logging parameter values (EnableSensitiveDataLogging
4
+ * opts in).
5
+ *
6
+ * Defaults (all overridable via configureLogging() or env):
7
+ * logSql : false, or LOG_SQL=true — log every SQL command
8
+ * sensitiveData : false, or MR_SENSITIVE_LOGGING=true — show parameter values
9
+ * (otherwise each value is redacted to '?')
10
+ * slowQueryMs : 0 (off), or MR_SLOW_QUERY_MS=<n> — warn when a command
11
+ * exceeds n ms, even if logSql is off
12
+ * migrations : true unless MR_SILENT_MIGRATIONS=true — log migration DDL
13
+ * level : 'info' | 'debug' | 'warn' | 'error' (min level), default 'info'
14
+ * logger : { debug, info, warn, error } — default console
15
+ *
16
+ * Previously SQL (with parameter values) was printed whenever NODE_ENV was
17
+ * not 'production'. That leaked PII into dev logs and was noisy; like EF,
18
+ * nothing is logged now unless you ask, and values are redacted unless you
19
+ * opt in.
20
+ */
21
+ const LEVELS = { debug: 10, info: 20, warn: 30, error: 40, silent: 99 };
22
+
23
+ const state = {
24
+ logger: console,
25
+ level: 'info',
26
+ logSql: process.env.LOG_SQL === 'true',
27
+ sensitiveData: process.env.MR_SENSITIVE_LOGGING === 'true',
28
+ slowQueryMs: Number(process.env.MR_SLOW_QUERY_MS) > 0 ? Number(process.env.MR_SLOW_QUERY_MS) : 0,
29
+ migrations: process.env.MR_SILENT_MIGRATIONS !== 'true',
30
+ };
31
+
32
+ function configureLogging(options = {}) {
33
+ if (options.logger !== undefined) {
34
+ const l = options.logger;
35
+ if (l !== null && (typeof l !== 'object' && typeof l !== 'function')) {
36
+ throw new TypeError('masterrecord: configureLogging({ logger }) expects an object with debug/info/warn/error.');
37
+ }
38
+ state.logger = l || console;
39
+ }
40
+ if (options.level !== undefined) {
41
+ if (!(options.level in LEVELS)) throw new TypeError(`masterrecord: unknown log level ${JSON.stringify(options.level)}`);
42
+ state.level = options.level;
43
+ }
44
+ if (options.logSql !== undefined) state.logSql = !!options.logSql;
45
+ if (options.sensitiveData !== undefined) state.sensitiveData = !!options.sensitiveData;
46
+ if (options.slowQueryMs !== undefined) state.slowQueryMs = Number(options.slowQueryMs) > 0 ? Number(options.slowQueryMs) : 0;
47
+ if (options.migrations !== undefined) state.migrations = !!options.migrations;
48
+ return getLoggingConfig();
49
+ }
50
+
51
+ function getLoggingConfig() {
52
+ return { level: state.level, logSql: state.logSql, sensitiveData: state.sensitiveData, slowQueryMs: state.slowQueryMs, migrations: state.migrations };
53
+ }
54
+
55
+ function enabled(level) {
56
+ return (LEVELS[level] || 0) >= (LEVELS[state.level] || 0);
57
+ }
58
+
59
+ function emit(level, message, data) {
60
+ if (!enabled(level)) return;
61
+ const l = state.logger || console;
62
+ const fn = (typeof l[level] === 'function') ? l[level] : (typeof l.log === 'function' ? l.log : null);
63
+ if (!fn) return;
64
+ try { data === undefined ? fn.call(l, message) : fn.call(l, message, data); } catch (_) { /* never let logging break the ORM */ }
65
+ }
66
+
67
+ /** Parameter values are PII until proven otherwise — redact unless opted in. */
68
+ function redactParams(params) {
69
+ if (!params || params.length === 0) return params;
70
+ if (state.sensitiveData) return params;
71
+ return params.map(() => '?');
72
+ }
73
+
74
+ function compact(sql) {
75
+ return typeof sql === 'string' ? sql.replace(/\s+/g, ' ').trim() : sql;
76
+ }
77
+
78
+ /**
79
+ * Called by every engine for every command: { sql, params, durationMs, engine,
80
+ * error?, migration? }. Decides what to log based on config.
81
+ */
82
+ function logCommand(info) {
83
+ if (!info) return;
84
+ const { sql, params, durationMs, engine, error, migration } = info;
85
+ const ms = typeof durationMs === 'number' ? Math.round(durationMs * 100) / 100 : undefined;
86
+ const shown = redactParams(params);
87
+ const tag = migration ? '[masterrecord:migration]' : `[masterrecord:sql${engine ? ':' + engine : ''}]`;
88
+
89
+ if (error) {
90
+ emit('error', `${tag} FAILED (${ms}ms) ${compact(sql)}`, { params: shown, error: error.message });
91
+ return;
92
+ }
93
+ if (migration) {
94
+ if (state.migrations) emit('info', `${tag} ${compact(sql)}`, shown && shown.length ? { params: shown } : undefined);
95
+ return;
96
+ }
97
+ if (state.slowQueryMs > 0 && ms !== undefined && ms >= state.slowQueryMs) {
98
+ emit('warn', `${tag} SLOW ${ms}ms (threshold ${state.slowQueryMs}ms) ${compact(sql)}`, shown && shown.length ? { params: shown } : undefined);
99
+ if (!state.logSql) return;
100
+ }
101
+ if (state.logSql) {
102
+ emit('debug', `${tag} (${ms}ms) ${compact(sql)}`, shown && shown.length ? { params: shown } : undefined);
103
+ }
104
+ }
105
+
106
+ /** General-purpose logging for non-command messages (cache, migrations, warnings). */
107
+ function log(level, message, data) { emit(level, message, data); }
108
+
109
+ export { configureLogging, getLoggingConfig, logCommand, log, redactParams };
package/mySQLEngine.js CHANGED
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "masterrecord",
3
- "version": "1.5.17",
3
+ "version": "1.22.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",
@@ -28,7 +28,11 @@
28
28
  "./Migrations/schema": "./Migrations/schema.js",
29
29
  "./Migrations/migrations": "./Migrations/migrations.js",
30
30
  "./Migrations/migrationTemplate": "./Migrations/migrationTemplate.js",
31
- "./package.json": "./package.json"
31
+ "./package.json": "./package.json",
32
+ "./errors": "./errors.js",
33
+ "./sql": "./QueryLanguage/rawSql.js",
34
+ "./logging": "./logging.js",
35
+ "./resilience": "./resilience.js"
32
36
  },
33
37
  "bin": {
34
38
  "masterrecord": "Migrations/cli.js"
package/postgresEngine.js CHANGED
@@ -1,6 +1,7 @@
1
1
  // Version 0.1.0 - Complete PostgreSQL implementation with pg 8.16.3
2
2
  import tools from './Tools.js';
3
3
  import FieldTransformer from './Entity/fieldTransformer.js';
4
+ import { logCommand } from './logging.js';
4
5
  import pg from 'pg';
5
6
 
6
7
  const { Pool } = pg;
@@ -79,12 +80,111 @@ class postgresEngine {
79
80
 
80
81
  const t = this._q(query.tableName);
81
82
  const pk = this._q(query.primaryKey);
82
- const sqlQuery = `UPDATE ${t} SET ${query.arg.query} WHERE ${t}.${pk} = $${query.arg.params.length + 1}`;
83
- // Add primaryKeyValue to params array
83
+ // Optimistic concurrency: bump a rowVersion column atomically and add
84
+ // each concurrency token's ORIGINAL value to the WHERE (see SQLite
85
+ // engine). Positional parameters continue from the SET params.
86
+ let setSql = query.arg.query;
87
+ if (query.rowVersionColumn) {
88
+ const rv = this._q(query.rowVersionColumn);
89
+ setSql += `, ${rv} = ${rv} + 1`;
90
+ }
84
91
  const params = [...query.arg.params, query.primaryKeyValue];
92
+ let where = `${t}.${pk} = $${params.length}`;
93
+ for (const c of (query.concurrency || [])) {
94
+ if (c.value === null || c.value === undefined) { where += ` AND ${t}.${this._q(c.column)} IS NULL`; }
95
+ else { params.push(c.value); where += ` AND ${t}.${this._q(c.column)} = $${params.length}`; }
96
+ }
97
+ const sqlQuery = `UPDATE ${t} SET ${setSql} WHERE ${where}`;
85
98
  return await this._runWithParams(sqlQuery, params);
86
99
  }
87
100
 
101
+ // ---- Command observation (EF IDbCommandInterceptor / CommandExecuted) ----
102
+ addCommandObserver(fn){ (this.__commandObservers ||= new Set()).add(fn); }
103
+ removeCommandObserver(fn){ if (this.__commandObservers) this.__commandObservers.delete(fn); }
104
+ _notifyCommand(info){
105
+ logCommand(info);
106
+ if (!this.__commandObservers || this.__commandObservers.size === 0) return;
107
+ for (const fn of Array.from(this.__commandObservers)) {
108
+ try { fn(info); } catch (e) { console.error('[PostgreSQL] command observer threw:', e); }
109
+ }
110
+ }
111
+
112
+ /** Rows matched by the last UPDATE/DELETE (pg Result.rowCount). */
113
+ /** Connection probe (context.healthCheck()): never throws. */
114
+ async healthCheck(){
115
+ try {
116
+ if (!this.pool) return { healthy: false, error: 'Not connected' };
117
+ const res = await this._runWithParams('SELECT NOW() AS time, version() AS version', []);
118
+ const row = res && res.rows ? res.rows[0] : undefined;
119
+ return { healthy: true, serverTime: row ? row.time : undefined, version: row ? row.version : undefined, poolSize: this.pool.totalCount, idleCount: this.pool.idleCount, waitingCount: this.pool.waitingCount };
120
+ } catch (err) {
121
+ return { healthy: false, error: err.message };
122
+ }
123
+ }
124
+
125
+ affectedRows(result){
126
+ if (!result) return 0;
127
+ if (typeof result.rowCount === 'number') return result.rowCount;
128
+ return 0;
129
+ }
130
+
131
+ // ---- Set-based writes from a compiled query (EF ExecuteUpdate / ExecuteDelete) ----
132
+ // The compiled WHERE already holds $1..$n; SET parameters continue from n+1
133
+ // (Postgres placeholders are numbered, not positional, so text order is free).
134
+
135
+ async executeUpdate(query, entity, setters){
136
+ const alias = this.getEntity(entity.__name, query.entityMap) || entity.__name;
137
+ const whereSql = `${this.buildWhere(query, entity)} ${this.buildAnd(query, entity)}`.trim();
138
+ const whereParams = query.parameters ? query.parameters.getParams() : [];
139
+ const params = [...whereParams];
140
+ const setParts = [];
141
+ for (const s of setters) {
142
+ if (s.raw !== undefined) { setParts.push(`${this._q(s.column)} = ${s.raw}`); }
143
+ else { params.push(s.value); setParts.push(`${this._q(s.column)} = $${params.length}`); }
144
+ }
145
+ const sql = `UPDATE ${this._q(entity.__name)} AS ${alias} SET ${setParts.join(', ')} ${whereSql}`;
146
+ return this.affectedRows(await this._runWithParams(sql, params));
147
+ }
148
+
149
+ async executeDelete(query, entity){
150
+ const alias = this.getEntity(entity.__name, query.entityMap) || entity.__name;
151
+ const whereSql = `${this.buildWhere(query, entity)} ${this.buildAnd(query, entity)}`.trim();
152
+ const whereParams = query.parameters ? query.parameters.getParams() : [];
153
+ const sql = `DELETE FROM ${this._q(entity.__name)} AS ${alias} ${whereSql}`;
154
+ return this.affectedRows(await this._runWithParams(sql, whereParams));
155
+ }
156
+
157
+ /** Scalar aggregate over the query's rows (EF Sum/Average/Min/Max): fn in SUM|AVG|MIN|MAX. */
158
+ /** EF GroupBy + aggregates (see SQLite engine for the contract). Positional params continue after the WHERE's. */
159
+ async getGrouped(queryObject, entity, groups, aggs, having, orderBy){
160
+ const q = queryObject.script;
161
+ const alias = this.getEntity(entity.__name, q.entityMap) || entity.__name;
162
+ const qi = (n) => this._q(n);
163
+ const sel = [
164
+ ...groups.map(g => `${alias}.${qi(g.column)} AS ${qi(g.column)}`),
165
+ ...aggs.map(a => `${a.fn}(${a.column ? `${alias}.${qi(a.column)}` : '*'}) AS ${qi(a.alias)}`),
166
+ ].join(', ');
167
+ const params = q.parameters ? [...q.parameters.getParams()] : [];
168
+ let sql = `SELECT ${sel} ${this.buildFrom(q, entity)} ${this.buildWhere(q, entity)} ${this.buildAnd(q, entity)} GROUP BY ${groups.map(g => `${alias}.${qi(g.column)}`).join(', ')}`;
169
+ if (having && having.length) {
170
+ sql += ' HAVING ' + having.map(h => { params.push(h.value); return `${h.agg.fn}(${h.agg.column ? `${alias}.${qi(h.agg.column)}` : '*'}) ${h.op} $${params.length}`; }).join(' AND ');
171
+ }
172
+ sql += (orderBy && orderBy.length) ? ` ORDER BY ${orderBy.map(o => `${qi(o.name)}${o.desc ? ' DESC' : ' ASC'}`).join(', ')}` : ` ORDER BY ${groups.map(g => qi(g.column)).join(', ')}`;
173
+ sql += ` ${this.buildLimit(q)} ${this.buildSkip(q)}`;
174
+ const result = await this._runWithParams(sql, params);
175
+ return result && result.rows ? result.rows : [];
176
+ }
177
+
178
+ async getAggregate(queryObject, entity, fn, column){
179
+ const q = queryObject.script;
180
+ const alias = this.getEntity(entity.__name, q.entityMap) || entity.__name;
181
+ const sql = `SELECT ${fn}(${alias}.${this._q(column)}) AS value ${this.buildFrom(q, entity)} ${this.buildWhere(q, entity)} ${this.buildAnd(q, entity)}`;
182
+ const params = q.parameters ? q.parameters.getParams() : [];
183
+ const result = await this._runWithParams(sql, params);
184
+ const row = result && result.rows ? result.rows[0] : null;
185
+ return row ? row.value : null;
186
+ }
187
+
88
188
  /**
89
189
  * DELETE with parameterized query
90
190
  */
@@ -92,8 +192,14 @@ class postgresEngine {
92
192
  const sqlObject = this._buildDeleteObject(queryObject);
93
193
  const t = this._q(sqlObject.tableName);
94
194
  const pk = this._q(sqlObject.primaryKey);
95
- const sqlQuery = `DELETE FROM ${t} WHERE ${t}.${pk} = $1`;
96
- return await this._runWithParams(sqlQuery, [sqlObject.value]);
195
+ const params = [sqlObject.value];
196
+ let where = `${t}.${pk} = $1`;
197
+ for (const c of (queryObject.__concurrency || [])) {
198
+ if (c.value === null || c.value === undefined) { where += ` AND ${t}.${this._q(c.column)} IS NULL`; }
199
+ else { params.push(c.value); where += ` AND ${t}.${this._q(c.column)} = $${params.length}`; }
200
+ }
201
+ const sqlQuery = `DELETE FROM ${t} WHERE ${where}`;
202
+ return await this._runWithParams(sqlQuery, params);
97
203
  }
98
204
 
99
205
  /**
@@ -389,7 +495,7 @@ class postgresEngine {
389
495
  }
390
496
  }
391
497
 
392
- const sql = `SELECT ${selectClause} ${this.buildFrom(query, entity)} ${whereClause} ${this.buildAnd(query, entity)} ${orderByClause} ${this.buildLimit(query)} ${this.buildSkip(query)}`;
498
+ const sql = `SELECT ${query.distinct ? 'DISTINCT ' : ''}${selectClause} ${this.buildFrom(query, entity)} ${whereClause} ${this.buildAnd(query, entity)} ${orderByClause} ${this.buildLimit(query)} ${this.buildSkip(query)}`;
393
499
 
394
500
  return {
395
501
  query: sql,
@@ -677,8 +783,17 @@ class postgresEngine {
677
783
  for (const item in orderByEntity.selectFields) {
678
784
  fieldList.push(`${entityStr}.${this._q(orderByEntity.selectFields[item])}`);
679
785
  }
680
- if (fieldList.length === 0) return "";
681
- return `ORDER BY ${fieldList.join(', ')} ${orderByType}`;
786
+ let out = fieldList.length ? `ORDER BY ${fieldList.join(', ')} ${orderByType}` : "";
787
+ // thenBy / thenByDescending (EF ThenBy)
788
+ const thenBy = Array.isArray(query.thenBy) ? query.thenBy : [];
789
+ if (thenBy.length) {
790
+ const extra = thenBy.map(t => {
791
+ if (entity && !entity[t.field]) throw new Error(`Invalid ORDER BY field: ${t.field} not found in ${entity.__name || 'entity'}`);
792
+ return `${entityStr}.${this._q(t.field)} ${t.dir === 'DESC' ? 'DESC' : 'ASC'}`;
793
+ });
794
+ out = out ? `${out}, ${extra.join(', ')}` : `ORDER BY ${extra.join(', ')}`;
795
+ }
796
+ return out;
682
797
  }
683
798
 
684
799
  getEntity(name, list) {
@@ -698,7 +813,7 @@ class postgresEngine {
698
813
  const $that = this;
699
814
  const sqlParts = [];
700
815
  const params = [];
701
- const dirtyFields = model.__dirtyFields;
816
+ const dirtyFields = (model.__dirtyFields || []).filter(f => !(model.__entity[f] && model.__entity[f].computedSql)); // computed columns are never written
702
817
  let paramIndex = 1;
703
818
 
704
819
  for (const column in dirtyFields) {
@@ -711,7 +826,7 @@ class postgresEngine {
711
826
  // bypassing get() which may change the type (e.g. parseFloat)
712
827
  let persistedValue = model["_" + fieldName];
713
828
  if (persistedValue === undefined) {
714
- persistedValue = model[fieldName];
829
+ persistedValue = (model.__entity[fieldName] && model.__entity[fieldName].relationshipType === "belongsTo") ? tools.foreignKeyValue(model, fieldName) : model[fieldName];
715
830
  }
716
831
  const isEmptyString = (typeof persistedValue === 'string') && (persistedValue.trim() === '');
717
832
  if (persistedValue === undefined || persistedValue === null || isEmptyString) {
@@ -727,7 +842,7 @@ class postgresEngine {
727
842
  switch (type) {
728
843
  case "belongsTo": {
729
844
  const foreignKey = model.__entity[dirtyFields[column]].foreignKey;
730
- let fkValue = model[dirtyFields[column]];
845
+ let fkValue = tools.foreignKeyValue(model, dirtyFields[column]);
731
846
  // Apply toDatabase transformer
732
847
  try {
733
848
  fkValue = FieldTransformer.toDatabase(fkValue, model.__entity[dirtyFields[column]], model.__entity.__name, dirtyFields[column]);
@@ -740,9 +855,8 @@ class postgresEngine {
740
855
  throw new Error(`UPDATE failed: ${typeError.message}`);
741
856
  }
742
857
  fkValue = $that._convertValueForDatabase(fkValue, model.__entity[dirtyFields[column]].type);
743
- const fore = `_${dirtyFields[column]}`;
744
858
  sqlParts.push(`${$that._q(foreignKey)} = $${paramIndex++}`);
745
- params.push(model[fore]);
859
+ params.push(fkValue);
746
860
  break;
747
861
  }
748
862
 
@@ -861,15 +975,12 @@ class postgresEngine {
861
975
 
862
976
  for (const column in modelEntity) {
863
977
  if (column.indexOf("__") === -1) {
864
- let fieldColumn = fields[column];
865
-
866
- // 🔥 FIX: For belongsTo relationships, also check the foreignKey field name
867
- // Users can set either orgRole.User = obj OR orgRole.user_id = 2
868
- if ((fieldColumn === undefined || fieldColumn === null) &&
869
- modelEntity[column].relationshipType === "belongsTo" &&
870
- modelEntity[column].foreignKey) {
871
- fieldColumn = fields[modelEntity[column].foreignKey];
872
- }
978
+ if (modelEntity[column] && modelEntity[column].computedSql) continue; // computed column: DB-generated, never written
979
+ // belongsTo: persist the FK VALUE (assigned entity -> its PK, or
980
+ // the primitive / FK column), never the navigation getter.
981
+ let fieldColumn = (modelEntity[column] && modelEntity[column].relationshipType === "belongsTo")
982
+ ? tools.foreignKeyValue(fields, column)
983
+ : fields[column];
873
984
 
874
985
  // Auto-increment PKs are DB-assigned — never emit an unset one.
875
986
  // "Unset" surfaces as undefined/null (a .new() getter) or as the
@@ -1059,23 +1170,27 @@ class postgresEngine {
1059
1170
  // migrations are observable; runtime queries stay behind the
1060
1171
  // dev/LOG_SQL gate.
1061
1172
  const isMigration = opts.migration === true;
1062
- if (isMigration ? process.env.MR_SILENT_MIGRATIONS !== 'true'
1063
- : (process.env.LOG_SQL === 'true' || process.env.NODE_ENV !== 'production')) {
1064
- console.log(isMigration ? "[masterrecord:migration]" : "[SQL]", typeof query === 'string' ? query.replace(/\s+/g, ' ').trim() : query);
1065
- if (params && params.length) console.log(isMigration ? "[masterrecord:migration] params" : "[Params]", params);
1066
- }
1173
+ // Logging (redacted params, slow-query warnings, migration DDL) is
1174
+ // handled centrally by logging.js via _notifyCommand below.
1067
1175
 
1068
1176
  // Inside a transaction, reuse the transaction's client so every
1069
1177
  // statement is part of the same BEGIN..COMMIT unit (and don't
1070
1178
  // release it — endTransaction/errorTransaction owns its lifecycle).
1179
+ const start = process.hrtime.bigint();
1180
+ const done = (error) => this._notifyCommand({ sql: query, params, durationMs: Number(process.hrtime.bigint() - start) / 1e6, engine: 'postgres', migration: isMigration, ...(error ? { error } : {}) });
1071
1181
  if (this._txnClient) {
1072
- return await this._txnClient.query(query, params);
1182
+ try { const r = await this._txnClient.query(query, params); done(); return r; }
1183
+ catch (error) { done(error); throw error; }
1073
1184
  }
1074
1185
 
1075
1186
  const client = await this.pool.connect();
1076
1187
  try {
1077
1188
  const result = await client.query(query, params);
1189
+ done();
1078
1190
  return result;
1191
+ } catch (error) {
1192
+ done(error);
1193
+ throw error;
1079
1194
  } finally {
1080
1195
  client.release();
1081
1196
  }
package/resilience.js ADDED
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Connection resiliency — EF Core's execution strategy / EnableRetryOnFailure.
3
+ *
4
+ * Retries an operation on TRANSIENT database errors (deadlocks, lock
5
+ * timeouts, dropped connections, busy SQLite) with capped exponential backoff
6
+ * and jitter. Non-transient errors (constraint violations, syntax errors,
7
+ * concurrency conflicts) are never retried. Like EF, retries are NOT applied
8
+ * inside a user transaction — the transaction as a whole is the retry unit
9
+ * and must be re-run by the caller.
10
+ */
11
+
12
+ /** Error classifier per engine. Conservative: only well-known transient codes. */
13
+ function isTransientError(err, engine) {
14
+ if (!err) return false;
15
+ if (err.name === 'ConcurrencyError') return false;
16
+ const code = err.code || (err.original && err.original.code) || (err.cause && err.cause.code);
17
+ const errno = err.errno;
18
+ const msg = String(err.message || '');
19
+
20
+ // Network-level, any engine
21
+ if (['ECONNRESET', 'ECONNREFUSED', 'ETIMEDOUT', 'EPIPE', 'EAI_AGAIN', 'PROTOCOL_CONNECTION_LOST'].includes(code)) return true;
22
+
23
+ switch (engine) {
24
+ case 'sqlite':
25
+ return code === 'SQLITE_BUSY' || code === 'SQLITE_LOCKED' || code === 'SQLITE_BUSY_SNAPSHOT' || /SQLITE_BUSY|database is locked/i.test(msg);
26
+ case 'mysql':
27
+ return code === 'ER_LOCK_DEADLOCK' || errno === 1213
28
+ || code === 'ER_LOCK_WAIT_TIMEOUT' || errno === 1205
29
+ || code === 'ER_TOO_MANY_USER_CONNECTIONS' || errno === 1203
30
+ || code === 'ER_CON_COUNT_ERROR' || errno === 1040;
31
+ case 'postgres':
32
+ // serialization_failure, deadlock_detected, admin_shutdown, crash_shutdown,
33
+ // cannot_connect_now, and connection-exception class 08xxx
34
+ return ['40001', '40P01', '57P01', '57P02', '57P03'].includes(code) || /^08/.test(String(code || ''));
35
+ default:
36
+ return false;
37
+ }
38
+ }
39
+
40
+ const sleep = (ms) => new Promise(r => setTimeout(r, ms));
41
+
42
+ /**
43
+ * Run `fn` with retries on transient errors.
44
+ * @param {() => Promise<any>} fn
45
+ * @param {object} opts { maxRetries=3, maxDelayMs=2000, baseDelayMs=50, engine, onRetry }
46
+ */
47
+ async function withRetry(fn, opts = {}) {
48
+ const maxRetries = Number.isInteger(opts.maxRetries) && opts.maxRetries >= 0 ? opts.maxRetries : 3;
49
+ const maxDelayMs = Number(opts.maxDelayMs) > 0 ? Number(opts.maxDelayMs) : 2000;
50
+ const baseDelayMs = Number(opts.baseDelayMs) > 0 ? Number(opts.baseDelayMs) : 50;
51
+ let attempt = 0;
52
+ for (;;) {
53
+ try {
54
+ return await fn();
55
+ } catch (err) {
56
+ if (attempt >= maxRetries || !isTransientError(err, opts.engine)) throw err;
57
+ attempt++;
58
+ const exp = Math.min(maxDelayMs, baseDelayMs * Math.pow(2, attempt - 1));
59
+ const delay = Math.round(exp * (0.5 + Math.random() * 0.5)); // jitter
60
+ if (typeof opts.onRetry === 'function') {
61
+ try { opts.onRetry({ attempt, maxRetries, delayMs: delay, error: err }); } catch (_) { /* ignore */ }
62
+ }
63
+ await sleep(delay);
64
+ }
65
+ }
66
+ }
67
+
68
+ export { isTransientError, withRetry };