@g9tm/lynxcontrols-sqlite 1.4.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.
Files changed (111) hide show
  1. package/README.md +12 -0
  2. package/contract/cases.json +463 -0
  3. package/dist/.tsbuildinfo +1 -0
  4. package/dist/codecs/codecs.d.ts +68 -0
  5. package/dist/codecs/codecs.d.ts.map +1 -0
  6. package/dist/codecs/codecs.js +201 -0
  7. package/dist/codecs/codecs.js.map +1 -0
  8. package/dist/contract/run-contract.d.ts +94 -0
  9. package/dist/contract/run-contract.d.ts.map +1 -0
  10. package/dist/contract/run-contract.js +159 -0
  11. package/dist/contract/run-contract.js.map +1 -0
  12. package/dist/driver/types.d.ts +87 -0
  13. package/dist/driver/types.d.ts.map +1 -0
  14. package/dist/driver/types.js +14 -0
  15. package/dist/driver/types.js.map +1 -0
  16. package/dist/errors.d.ts +39 -0
  17. package/dist/errors.d.ts.map +1 -0
  18. package/dist/errors.js +57 -0
  19. package/dist/errors.js.map +1 -0
  20. package/dist/index.d.ts +25 -0
  21. package/dist/index.d.ts.map +1 -0
  22. package/dist/index.js +22 -0
  23. package/dist/query/builders.d.ts +216 -0
  24. package/dist/query/builders.d.ts.map +1 -0
  25. package/dist/query/builders.js +490 -0
  26. package/dist/query/builders.js.map +1 -0
  27. package/dist/query/compile.d.ts +42 -0
  28. package/dist/query/compile.d.ts.map +1 -0
  29. package/dist/query/compile.js +307 -0
  30. package/dist/query/compile.js.map +1 -0
  31. package/dist/query/expr.d.ts +201 -0
  32. package/dist/query/expr.d.ts.map +1 -0
  33. package/dist/query/expr.js +247 -0
  34. package/dist/query/expr.js.map +1 -0
  35. package/dist/repo/audit.d.ts +19 -0
  36. package/dist/repo/audit.d.ts.map +1 -0
  37. package/dist/repo/audit.js +36 -0
  38. package/dist/repo/audit.js.map +1 -0
  39. package/dist/repo/repository.d.ts +233 -0
  40. package/dist/repo/repository.d.ts.map +1 -0
  41. package/dist/repo/repository.js +715 -0
  42. package/dist/repo/repository.js.map +1 -0
  43. package/dist/schema/columns.d.ts +115 -0
  44. package/dist/schema/columns.d.ts.map +1 -0
  45. package/dist/schema/columns.js +112 -0
  46. package/dist/schema/columns.js.map +1 -0
  47. package/dist/schema/entity.d.ts +135 -0
  48. package/dist/schema/entity.d.ts.map +1 -0
  49. package/dist/schema/entity.js +227 -0
  50. package/dist/schema/entity.js.map +1 -0
  51. package/dist/schema/policies.d.ts +89 -0
  52. package/dist/schema/policies.d.ts.map +1 -0
  53. package/dist/schema/policies.js +54 -0
  54. package/dist/schema/policies.js.map +1 -0
  55. package/dist/session/ambient.d.ts +32 -0
  56. package/dist/session/ambient.d.ts.map +1 -0
  57. package/dist/session/ambient.js +28 -0
  58. package/dist/session/ambient.js.map +1 -0
  59. package/dist/session/cache.d.ts +62 -0
  60. package/dist/session/cache.d.ts.map +1 -0
  61. package/dist/session/cache.js +239 -0
  62. package/dist/session/cache.js.map +1 -0
  63. package/dist/session/database.d.ts +221 -0
  64. package/dist/session/database.d.ts.map +1 -0
  65. package/dist/session/database.js +430 -0
  66. package/dist/session/database.js.map +1 -0
  67. package/dist/session/locator.d.ts +33 -0
  68. package/dist/session/locator.d.ts.map +1 -0
  69. package/dist/session/locator.js +39 -0
  70. package/dist/session/locator.js.map +1 -0
  71. package/dist/session/migrations.d.ts +75 -0
  72. package/dist/session/migrations.d.ts.map +1 -0
  73. package/dist/session/migrations.js +88 -0
  74. package/dist/session/migrations.js.map +1 -0
  75. package/dist/session/mutex.d.ts +7 -0
  76. package/dist/session/mutex.d.ts.map +1 -0
  77. package/dist/session/mutex.js +27 -0
  78. package/dist/session/mutex.js.map +1 -0
  79. package/dist/session/rows.d.ts +17 -0
  80. package/dist/session/rows.d.ts.map +1 -0
  81. package/dist/session/rows.js +52 -0
  82. package/dist/session/rows.js.map +1 -0
  83. package/dist/session/schema-setup.d.ts +21 -0
  84. package/dist/session/schema-setup.d.ts.map +1 -0
  85. package/dist/session/schema-setup.js +227 -0
  86. package/dist/session/schema-setup.js.map +1 -0
  87. package/dist/session/scope.d.ts +117 -0
  88. package/dist/session/scope.d.ts.map +1 -0
  89. package/dist/session/scope.js +233 -0
  90. package/dist/session/scope.js.map +1 -0
  91. package/dist/session/write-hooks.d.ts +84 -0
  92. package/dist/session/write-hooks.d.ts.map +1 -0
  93. package/dist/session/write-hooks.js +55 -0
  94. package/dist/session/write-hooks.js.map +1 -0
  95. package/dist/values/ids.d.ts +46 -0
  96. package/dist/values/ids.d.ts.map +1 -0
  97. package/dist/values/ids.js +84 -0
  98. package/dist/values/ids.js.map +1 -0
  99. package/dist/values/int64.d.ts +33 -0
  100. package/dist/values/int64.d.ts.map +1 -0
  101. package/dist/values/int64.js +105 -0
  102. package/dist/values/int64.js.map +1 -0
  103. package/dist/values/local-date-time.d.ts +61 -0
  104. package/dist/values/local-date-time.d.ts.map +1 -0
  105. package/dist/values/local-date-time.js +122 -0
  106. package/dist/values/local-date-time.js.map +1 -0
  107. package/dist/values/sql-value.d.ts +36 -0
  108. package/dist/values/sql-value.d.ts.map +1 -0
  109. package/dist/values/sql-value.js +70 -0
  110. package/dist/values/sql-value.js.map +1 -0
  111. package/package.json +27 -0
@@ -0,0 +1,430 @@
1
+ import { G9LogLevel, createSystemClock, g9RuntimeTimers } from "@g9tm/lynxcontrols-foundation";
2
+ import { G9SqliteError, isG9SqliteError } from "../errors.js";
3
+ import { G9Sql } from "../query/builders.js";
4
+ import { encodeParam } from "../query/compile.js";
5
+ import { createSystemAuditClock, g9NoCurrentUser } from "./ambient.js";
6
+ import { G9CacheRegistry } from "./cache.js";
7
+ import { sortMigrations } from "./migrations.js";
8
+ import { G9AsyncLock } from "./mutex.js";
9
+ import { decodeShaped } from "./rows.js";
10
+ import { runSchemaSetup } from "./schema-setup.js";
11
+ function _define_property(obj, key, value) {
12
+ if (key in obj) Object.defineProperty(obj, key, {
13
+ value: value,
14
+ enumerable: true,
15
+ configurable: true,
16
+ writable: true
17
+ });
18
+ else obj[key] = value;
19
+ return obj;
20
+ }
21
+ const defaultTimers = g9RuntimeTimers;
22
+ function resolveOptions(options) {
23
+ var _ref, _ref1, _options_entities, _options_initializers, _options_clock, _options_currentUser, _options_idCase, _options_dateTimeProfile, _options_durability, _ref2, _options_migrations, _options_initializers1, _options_interceptors, _options_timers, _options_timeSource;
24
+ var _options_busy, _options_busy1, _options_busy2;
25
+ if (!(null == options ? void 0 : options.driver) || !options.locator) throw new G9SqliteError('misuse', 'createG9Sqlite needs a driver and a locator.');
26
+ const retries = null != (_ref = null == (_options_busy = options.busy) ? void 0 : _options_busy.retries) ? _ref : 4;
27
+ const delay = null != (_ref1 = null == (_options_busy1 = options.busy) ? void 0 : _options_busy1.initialDelayMs) ? _ref1 : 180;
28
+ if (!Number.isSafeInteger(retries) || retries < 0) throw new G9SqliteError('misuse', 'busy.retries must be ≥ 0.');
29
+ if (!Number.isFinite(delay) || delay < 0) throw new G9SqliteError('misuse', 'busy.initialDelayMs must be ≥ 0.');
30
+ const entities = Object.values(null != (_options_entities = options.entities) ? _options_entities : {});
31
+ for (const e of entities)if (!e || 'object' != typeof e || !Array.isArray(e.columns)) throw new G9SqliteError('misuse', "entities must hold descriptors from defineEntity().");
32
+ const tables = new Map();
33
+ for (const e of entities){
34
+ const other = tables.get(e.table.toLowerCase());
35
+ if (other && other !== e) throw new G9SqliteError('misuse', `Entities '${other.name}' and '${e.name}' both map table '${e.table}'.`);
36
+ tables.set(e.table.toLowerCase(), e);
37
+ }
38
+ const names = new Set();
39
+ for (const i of null != (_options_initializers = options.initializers) ? _options_initializers : []){
40
+ if (names.has(i.name)) throw new G9SqliteError('misuse', `Two initializers are named '${i.name}'.`);
41
+ names.add(i.name);
42
+ }
43
+ return Object.freeze({
44
+ driver: options.driver,
45
+ locator: options.locator,
46
+ create: true === options.create,
47
+ readOnly: true === options.readOnly,
48
+ clock: null != (_options_clock = options.clock) ? _options_clock : createSystemAuditClock(),
49
+ currentUser: null != (_options_currentUser = options.currentUser) ? _options_currentUser : g9NoCurrentUser,
50
+ codec: Object.freeze({
51
+ idCase: null != (_options_idCase = options.idCase) ? _options_idCase : 'lower',
52
+ dateTimeProfile: null != (_options_dateTimeProfile = options.dateTimeProfile) ? _options_dateTimeProfile : 'provider'
53
+ }),
54
+ durability: null != (_options_durability = options.durability) ? _options_durability : 'full',
55
+ pragmas: Object.freeze({
56
+ journalMode: 'wal',
57
+ tempStore: 'memory',
58
+ cacheSize: -8000,
59
+ ...options.connection,
60
+ busyTimeoutMs: null != (_ref2 = null == (_options_busy2 = options.busy) ? void 0 : _options_busy2.timeoutMs) ? _ref2 : 5000
61
+ }),
62
+ busyRetries: retries,
63
+ busyInitialDelayMs: delay,
64
+ migrations: sortMigrations(null != (_options_migrations = options.migrations) ? _options_migrations : []),
65
+ initializers: Object.freeze([
66
+ ...null != (_options_initializers1 = options.initializers) ? _options_initializers1 : []
67
+ ]),
68
+ interceptors: Object.freeze([
69
+ ...null != (_options_interceptors = options.interceptors) ? _options_interceptors : []
70
+ ]),
71
+ entities: Object.freeze(entities),
72
+ cultureKey: options.cultureKey,
73
+ maxInListParameters: options.maxInListParameters,
74
+ timers: null != (_options_timers = options.timers) ? _options_timers : defaultTimers,
75
+ timeSource: null != (_options_timeSource = options.timeSource) ? _options_timeSource : createSystemClock(),
76
+ diagnostics: options.diagnostics
77
+ });
78
+ }
79
+ class G9SqliteDatabase {
80
+ get generation() {
81
+ return this.generationValue;
82
+ }
83
+ get databasePath() {
84
+ return this.options.locator.getDatabasePath();
85
+ }
86
+ get activeDatabasePath() {
87
+ var _ref;
88
+ var _this_connection;
89
+ return null != (_ref = null == (_this_connection = this.connection) ? void 0 : _this_connection.path) ? _ref : null;
90
+ }
91
+ get hasActiveDatabase() {
92
+ try {
93
+ const path = this.options.locator.getDatabasePath();
94
+ return 'string' == typeof path && '' !== path.trim();
95
+ } catch {
96
+ return false;
97
+ }
98
+ }
99
+ buildOptions() {
100
+ return {
101
+ codec: this.options.codec,
102
+ ...this.options.cultureKey ? {
103
+ defaultCulture: this.options.cultureKey
104
+ } : {},
105
+ ...void 0 !== this.options.maxInListParameters ? {
106
+ maxInListParameters: this.options.maxInListParameters
107
+ } : {}
108
+ };
109
+ }
110
+ report(message, error) {
111
+ const d = this.options.diagnostics;
112
+ if (d) d.log({
113
+ level: G9LogLevel.Warning,
114
+ message,
115
+ source: 'g9-sqlite',
116
+ error
117
+ });
118
+ }
119
+ async capabilities() {
120
+ if (!this.capabilitiesValue) this.capabilitiesValue = await this.options.driver.capabilities();
121
+ return this.capabilitiesValue;
122
+ }
123
+ ensureOpen() {
124
+ if (this.closed) throw new G9SqliteError('misuse', 'The database is closed.');
125
+ }
126
+ async connect() {
127
+ this.ensureOpen();
128
+ const path = this.options.locator.getDatabasePath();
129
+ const current = this.connection;
130
+ if (current && current.path.toLowerCase() === path.toLowerCase()) return current;
131
+ if (current) {
132
+ this.connection = null;
133
+ await this.options.driver.close(current.token).catch((error)=>this.report('close failed', error));
134
+ this.generationValue++;
135
+ this.caches.resetAll();
136
+ }
137
+ const token = await this.options.driver.open({
138
+ path,
139
+ create: this.options.create,
140
+ readOnly: this.options.readOnly,
141
+ durability: this.options.durability,
142
+ pragmas: this.options.pragmas
143
+ });
144
+ const connection = {
145
+ token,
146
+ path,
147
+ generation: this.generationValue
148
+ };
149
+ this.connection = connection;
150
+ try {
151
+ for(let attempt = 0;; attempt++)try {
152
+ await runSchemaSetup(this, token);
153
+ break;
154
+ } catch (error) {
155
+ if (!isG9SqliteError(error, 'busy') || attempt >= this.options.busyRetries) throw error;
156
+ await this.sleep(this.options.busyInitialDelayMs * 2 ** attempt);
157
+ }
158
+ } catch (error) {
159
+ this.connection = null;
160
+ await this.options.driver.close(token).catch(()=>void 0);
161
+ throw error;
162
+ }
163
+ return connection;
164
+ }
165
+ async migrate() {
166
+ await this.withLock(async ()=>void 0);
167
+ }
168
+ async withLock(work, signal) {
169
+ this.ensureOpen();
170
+ const generation = this.generationValue;
171
+ const release = await this.lock.acquire();
172
+ try {
173
+ if (null == signal ? void 0 : signal.aborted) throw new G9SqliteError('cancelled', 'Cancelled while waiting for the database.');
174
+ if (generation !== this.generationValue) throw new G9SqliteError('cancelled', 'The database was switched (user change) while this call waited.');
175
+ return await work(await this.connect());
176
+ } finally{
177
+ release();
178
+ }
179
+ }
180
+ async runRead(statements, options = {}) {
181
+ return this.withLock(async (connection)=>{
182
+ const runOptions = {};
183
+ if (void 0 !== options.maxRows) runOptions.maxRows = options.maxRows;
184
+ if (options.signal) runOptions.signal = options.signal;
185
+ const results = await this.options.driver.run(connection.token, statements, runOptions);
186
+ if (connection.generation !== this.generationValue) throw new G9SqliteError('cancelled', 'The database was switched while this read ran; its rows are discarded.');
187
+ return results;
188
+ }, options.signal);
189
+ }
190
+ async unit(parent, needsTransaction, work, options = {}) {
191
+ var _options_retries;
192
+ if (parent) return this.joinUnit(parent, work, options.signal);
193
+ const retries = null != (_options_retries = options.retries) ? _options_retries : this.options.busyRetries;
194
+ let attempt = 0;
195
+ for(;;)try {
196
+ return await this.unitOnce(needsTransaction, work, options);
197
+ } catch (error) {
198
+ var _options_signal;
199
+ if (!isG9SqliteError(error, 'busy') || attempt >= retries || (null == (_options_signal = options.signal) ? void 0 : _options_signal.aborted)) throw error;
200
+ const delay = this.options.busyInitialDelayMs * 2 ** attempt;
201
+ attempt++;
202
+ await this.sleep(delay, options.signal);
203
+ }
204
+ }
205
+ sleep(ms, signal) {
206
+ return new Promise((resolve, reject)=>{
207
+ const onAbort = ()=>{
208
+ this.options.timers.clearTimeout(handle);
209
+ reject(new G9SqliteError('cancelled', 'Cancelled during busy back-off.'));
210
+ };
211
+ const handle = this.options.timers.setTimeout(()=>{
212
+ null == signal || signal.removeEventListener('abort', onAbort);
213
+ resolve();
214
+ }, ms);
215
+ null == signal || signal.addEventListener('abort', onAbort, {
216
+ once: true
217
+ });
218
+ });
219
+ }
220
+ async joinUnit(parent, work, signal) {
221
+ if (parent.finished) throw new G9SqliteError('misuse', 'The transaction is already finished.');
222
+ const uow = {
223
+ db: this,
224
+ tx: parent.token,
225
+ txState: parent,
226
+ signal,
227
+ run: (statements)=>this.runInTx(parent, statements, void 0, signal),
228
+ onCommit: (cb)=>parent.commitCallbacks.push(cb)
229
+ };
230
+ return work(uow);
231
+ }
232
+ async runInTx(tx, statements, maxRows, signal) {
233
+ if (tx.finished) throw new G9SqliteError('misuse', 'The transaction is already finished.');
234
+ if (tx.generation !== this.generationValue) throw new G9SqliteError('cancelled', 'The database was switched; this transaction can no longer run.');
235
+ const runOptions = {
236
+ tx: tx.token
237
+ };
238
+ if (void 0 !== maxRows) runOptions.maxRows = maxRows;
239
+ if (signal) runOptions.signal = signal;
240
+ return this.options.driver.run(tx.session, statements, runOptions);
241
+ }
242
+ async unitOnce(needsTransaction, work, options) {
243
+ const callbacks = [];
244
+ const result = await this.withLock(async (connection)=>{
245
+ var _options_mode;
246
+ if (!needsTransaction) {
247
+ const uow = {
248
+ db: this,
249
+ tx: null,
250
+ txState: null,
251
+ signal: options.signal,
252
+ run: (statements)=>this.options.driver.run(connection.token, statements, {
253
+ atomic: true,
254
+ ...options.signal ? {
255
+ signal: options.signal
256
+ } : {}
257
+ }),
258
+ onCommit: (cb)=>callbacks.push(cb)
259
+ };
260
+ return work(uow);
261
+ }
262
+ const tx = await this.beginTx(connection, null != (_options_mode = options.mode) ? _options_mode : 'immediate');
263
+ try {
264
+ const value = await this.joinUnit(tx, work, options.signal);
265
+ await this.commitTx(tx);
266
+ callbacks.push(...tx.commitCallbacks);
267
+ return value;
268
+ } catch (error) {
269
+ await this.rollbackTx(tx);
270
+ throw error;
271
+ }
272
+ }, options.signal);
273
+ await this.runCommitCallbacks(callbacks);
274
+ return result;
275
+ }
276
+ async beginTx(connection, mode) {
277
+ const token = await this.options.driver.begin(connection.token, mode);
278
+ return {
279
+ token,
280
+ session: connection.token,
281
+ generation: connection.generation,
282
+ commitCallbacks: [],
283
+ savepoints: 0,
284
+ finished: false
285
+ };
286
+ }
287
+ async commitTx(tx) {
288
+ try {
289
+ await this.options.driver.commit(tx.token);
290
+ } catch (error) {
291
+ if (isG9SqliteError(error, 'outcome-unknown')) tx.finished = true;
292
+ throw error;
293
+ }
294
+ tx.finished = true;
295
+ }
296
+ async rollbackTx(tx) {
297
+ if (tx.finished) return;
298
+ tx.finished = true;
299
+ await this.options.driver.rollback(tx.token).catch((error)=>this.report('rollback failed', error));
300
+ }
301
+ async runCommitCallbacks(callbacks) {
302
+ for (const cb of callbacks)try {
303
+ await cb();
304
+ } catch (error) {
305
+ this.report('post-commit callback failed (the write is committed)', error);
306
+ }
307
+ }
308
+ async openTransaction(options = {}) {
309
+ this.ensureOpen();
310
+ const generation = this.generationValue;
311
+ const release = await this.lock.acquire();
312
+ try {
313
+ var _options_mode;
314
+ if (generation !== this.generationValue) throw new G9SqliteError('cancelled', 'The database was switched while the transaction waited.');
315
+ const connection = await this.connect();
316
+ const tx = await this.beginTx(connection, null != (_options_mode = options.mode) ? _options_mode : 'immediate');
317
+ return {
318
+ tx,
319
+ release
320
+ };
321
+ } catch (error) {
322
+ release();
323
+ throw error;
324
+ }
325
+ }
326
+ async switchDatabase() {
327
+ this.generationValue++;
328
+ const acquiring = this.lock.acquire();
329
+ this.caches.resetAll();
330
+ const release = await acquiring;
331
+ try {
332
+ const current = this.connection;
333
+ this.connection = null;
334
+ if (current) await this.options.driver.close(current.token);
335
+ } finally{
336
+ release();
337
+ }
338
+ }
339
+ async closeConnection() {
340
+ const release = await this.lock.acquire();
341
+ try {
342
+ const current = this.connection;
343
+ this.connection = null;
344
+ if (current) await this.options.driver.close(current.token);
345
+ } finally{
346
+ release();
347
+ }
348
+ }
349
+ async checkpointWal() {
350
+ if (!this.connection) return;
351
+ await this.withLock((c)=>this.options.driver.run(c.token, [
352
+ {
353
+ sql: 'PRAGMA wal_checkpoint(TRUNCATE)',
354
+ params: []
355
+ }
356
+ ]));
357
+ }
358
+ async close() {
359
+ var _this_unsubscribeLocator, _this;
360
+ if (this.closed) return;
361
+ null == (_this_unsubscribeLocator = (_this = this).unsubscribeLocator) || _this_unsubscribeLocator.call(_this);
362
+ this.caches.dispose();
363
+ await this.closeConnection();
364
+ this.closed = true;
365
+ this.changeListeners.clear();
366
+ }
367
+ onChange(listener) {
368
+ this.changeListeners.add(listener);
369
+ return ()=>this.changeListeners.delete(listener);
370
+ }
371
+ publishChange(event) {
372
+ this.caches.invalidateTable(event.table);
373
+ this.emitChange(event);
374
+ }
375
+ emitChange(event) {
376
+ for (const listener of Array.from(this.changeListeners))try {
377
+ listener(event);
378
+ } catch (error) {
379
+ this.report('change listener failed', error);
380
+ }
381
+ }
382
+ notifyExternalChange(change) {
383
+ for (const table of change.tables)this.publishChange({
384
+ table,
385
+ entity: null,
386
+ kind: 'external',
387
+ rowCount: -1
388
+ });
389
+ }
390
+ encodeRaw(params) {
391
+ return params.map((p)=>encodeParam(p, void 0, this.options.codec));
392
+ }
393
+ async loadEntityRowsForCache(entity, maxRows) {
394
+ const builder = G9Sql.select(entity);
395
+ if (this.options.cultureKey) builder.withCulture();
396
+ const { statement, shape } = builder.compile(this.buildOptions());
397
+ try {
398
+ const [result] = await this.runRead([
399
+ statement
400
+ ], {
401
+ maxRows
402
+ });
403
+ return decodeShaped(shape, result, this.options.codec);
404
+ } catch (error) {
405
+ if (error instanceof G9SqliteError && /no such table/i.test(error.message)) return [];
406
+ throw error;
407
+ }
408
+ }
409
+ constructor(options){
410
+ var _this_options_locator_onDatabasePathChanged, _this_options_locator;
411
+ _define_property(this, "options", void 0);
412
+ _define_property(this, "lock", new G9AsyncLock());
413
+ _define_property(this, "caches", void 0);
414
+ _define_property(this, "connection", null);
415
+ _define_property(this, "generationValue", 0);
416
+ _define_property(this, "capabilitiesValue", null);
417
+ _define_property(this, "unsubscribeLocator", void 0);
418
+ _define_property(this, "changeListeners", new Set());
419
+ _define_property(this, "closed", false);
420
+ this.options = resolveOptions(options);
421
+ this.caches = new G9CacheRegistry(this);
422
+ this.unsubscribeLocator = null == (_this_options_locator_onDatabasePathChanged = (_this_options_locator = this.options.locator).onDatabasePathChanged) ? void 0 : _this_options_locator_onDatabasePathChanged.call(_this_options_locator, ()=>{
423
+ this.switchDatabase().catch((error)=>this.report('locator switch failed', error));
424
+ });
425
+ for (const entity of this.options.entities)if (entity.cachePolicy) this.caches.defineEntityCache(entity, entity.cachePolicy);
426
+ }
427
+ }
428
+ export { G9SqliteDatabase };
429
+
430
+ //# sourceMappingURL=database.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session/database.js","sources":["../../src/session/database.ts"],"sourcesContent":["import {\n createSystemClock,\n type G9AbortSignal,\n type G9Clock,\n type G9Diagnostics,\n G9LogLevel,\n type G9Timers,\n g9RuntimeTimers,\n} from '@g9tm/lynxcontrols-foundation';\nimport type { G9CodecContext } from '../codecs/codecs';\nimport type {\n G9ConnectionPragmas,\n G9DriverCapabilities,\n G9DriverStatement,\n G9Durability,\n G9RunOptions,\n G9SessionToken,\n G9SqliteDriver,\n G9SqlResult,\n G9TxToken,\n} from '../driver/types';\nimport { G9SqliteError, isG9SqliteError } from '../errors';\nimport { type G9BuildOptions, G9Sql } from '../query/builders';\nimport { encodeParam } from '../query/compile';\nimport type { G9EntityDescriptor } from '../schema/entity';\nimport type { G9IdCase } from '../values/ids';\nimport type { G9DateTimeWriteProfile } from '../values/local-date-time';\nimport { createSystemAuditClock, type G9AuditClock, type G9CurrentUserProvider, g9NoCurrentUser } from './ambient';\nimport { G9CacheRegistry } from './cache';\nimport type { G9DatabaseLocator } from './locator';\nimport { type G9Initializer, type G9Migration, sortMigrations } from './migrations';\nimport { G9AsyncLock } from './mutex';\nimport { decodeShaped } from './rows';\nimport { runSchemaSetup } from './schema-setup';\nimport type { G9ChangeEvent, G9SqliteInterceptor } from './write-hooks';\n\n/** Bounded retry around whole transactions when SQLite reports `busy` (MAUI `UseBusyRetry`, N10). */\nexport interface G9BusyOptions {\n /** `PRAGMA busy_timeout` applied on every open (SQLite's own wait). Default 5000. */\n readonly timeoutMs?: number;\n /** Extra attempts of a whole transaction after `busy` (MAUI default 4). 0 disables. */\n readonly retries?: number;\n /** First back-off delay; doubles per attempt (MAUI default 180). */\n readonly initialDelayMs?: number;\n}\n\n/** Options of {@link createG9Sqlite} (MAUI `G9SqliteOptions` / `AddG9Sqlite` builder). */\nexport interface G9SqliteOptions {\n readonly driver: G9SqliteDriver;\n /** MAUI `DatabaseLocator`. */\n readonly locator: G9DatabaseLocator;\n /** Create a missing database file. Default `false`: opening a missing file fails (`not-found`), never blank. */\n readonly create?: boolean;\n readonly readOnly?: boolean;\n /** MAUI `Clock`: \"now\" for audit columns. Default UTC. */\n readonly clock?: G9AuditClock;\n /** MAUI `CurrentUser`. Default nobody. */\n readonly currentUser?: G9CurrentUserProvider;\n /** MAUI `CanonicalIdCase`. Default `'lower'`. Fixed for the life of this database object. */\n readonly idCase?: G9IdCase;\n /** How date/times are written. Default the MAUI provider format. */\n readonly dateTimeProfile?: G9DateTimeWriteProfile;\n /** D13: `full` (default) or `normal`. */\n readonly durability?: G9Durability;\n /** Connection tuning applied on every open. Default WAL, temp_store MEMORY, 8 MiB cache, no mmap. */\n readonly connection?: Omit<G9ConnectionPragmas, 'busyTimeoutMs'>;\n /** MAUI `BusyRetryAttempts` / `BusyRetryInitialDelayMs` plus the busy timeout. */\n readonly busy?: G9BusyOptions;\n /** MAUI `Migrations` (N01). */\n readonly migrations?: readonly G9Migration[];\n /** MAUI `Initializers` (N02). */\n readonly initializers?: readonly G9Initializer[];\n /** MAUI `Interceptors` (N03), in registration order. */\n readonly interceptors?: readonly G9SqliteInterceptor[];\n /** MAUI `Entities` (N04): validated now; their indexes are created on open and their caches defined. */\n readonly entities?: Readonly<Record<string, G9EntityDescriptor>>;\n /** Culture key for localized columns when a query calls `withCulture()` without one (`'En'`, `'Fa'`). */\n readonly cultureKey?: () => string;\n /** IN-list placeholder budget (default 16 000). */\n readonly maxInListParameters?: number;\n /** Timers for cache debounce and retry back-off (tests pass fake ones). */\n readonly timers?: G9Timers;\n /** Monotonic time for cache TTL. */\n readonly timeSource?: G9Clock;\n /** Where post-commit hook failures and cache refresh failures are reported. */\n readonly diagnostics?: G9Diagnostics;\n}\n\n/** Resolved, frozen options. */\nexport interface G9ResolvedSqliteOptions {\n readonly driver: G9SqliteDriver;\n readonly locator: G9DatabaseLocator;\n readonly create: boolean;\n readonly readOnly: boolean;\n readonly clock: G9AuditClock;\n readonly currentUser: G9CurrentUserProvider;\n readonly codec: G9CodecContext;\n readonly durability: G9Durability;\n readonly pragmas: G9ConnectionPragmas;\n readonly busyRetries: number;\n readonly busyInitialDelayMs: number;\n readonly migrations: readonly G9Migration[];\n readonly initializers: readonly G9Initializer[];\n readonly interceptors: readonly G9SqliteInterceptor[];\n readonly entities: readonly G9EntityDescriptor[];\n readonly cultureKey: (() => string) | undefined;\n readonly maxInListParameters: number | undefined;\n readonly timers: G9Timers;\n readonly timeSource: G9Clock;\n readonly diagnostics: G9Diagnostics | undefined;\n}\n\n// Busy-retry delays use the runtime timers (bundle-scope identifiers in Lynx, not `globalThis` properties).\nconst defaultTimers: G9Timers = g9RuntimeTimers;\n\nfunction resolveOptions(options: G9SqliteOptions): G9ResolvedSqliteOptions {\n if (!options?.driver || !options.locator) {\n throw new G9SqliteError('misuse', 'createG9Sqlite needs a driver and a locator.');\n }\n const retries = options.busy?.retries ?? 4;\n const delay = options.busy?.initialDelayMs ?? 180;\n if (!Number.isSafeInteger(retries) || retries < 0) throw new G9SqliteError('misuse', 'busy.retries must be ≥ 0.');\n if (!Number.isFinite(delay) || delay < 0) throw new G9SqliteError('misuse', 'busy.initialDelayMs must be ≥ 0.');\n const entities = Object.values(options.entities ?? {});\n for (const e of entities) {\n if (!e || typeof e !== 'object' || !Array.isArray(e.columns)) {\n throw new G9SqliteError('misuse', 'entities must hold descriptors from defineEntity().');\n }\n }\n const tables = new Map<string, G9EntityDescriptor>();\n for (const e of entities) {\n const other = tables.get(e.table.toLowerCase());\n if (other && other !== e) {\n throw new G9SqliteError('misuse', `Entities '${other.name}' and '${e.name}' both map table '${e.table}'.`);\n }\n tables.set(e.table.toLowerCase(), e);\n }\n const names = new Set<string>();\n for (const i of options.initializers ?? []) {\n if (names.has(i.name)) throw new G9SqliteError('misuse', `Two initializers are named '${i.name}'.`);\n names.add(i.name);\n }\n return Object.freeze({\n driver: options.driver,\n locator: options.locator,\n create: options.create === true,\n readOnly: options.readOnly === true,\n clock: options.clock ?? createSystemAuditClock(),\n currentUser: options.currentUser ?? g9NoCurrentUser,\n codec: Object.freeze({ idCase: options.idCase ?? 'lower', dateTimeProfile: options.dateTimeProfile ?? 'provider' }),\n durability: options.durability ?? 'full',\n pragmas: Object.freeze({\n journalMode: 'wal' as const,\n tempStore: 'memory' as const,\n cacheSize: -8000,\n ...options.connection,\n busyTimeoutMs: options.busy?.timeoutMs ?? 5000,\n }),\n busyRetries: retries,\n busyInitialDelayMs: delay,\n migrations: sortMigrations(options.migrations ?? []),\n initializers: Object.freeze([...(options.initializers ?? [])]),\n interceptors: Object.freeze([...(options.interceptors ?? [])]),\n entities: Object.freeze(entities),\n cultureKey: options.cultureKey,\n maxInListParameters: options.maxInListParameters,\n timers: options.timers ?? defaultTimers,\n timeSource: options.timeSource ?? createSystemClock(),\n diagnostics: options.diagnostics,\n });\n}\n\ninterface Connection {\n readonly token: G9SessionToken;\n readonly path: string;\n readonly generation: number;\n}\n\n/** @internal A unit of work: statements run inside one transaction (or one atomic batch) and commit together. */\nexport interface G9UnitOfWork {\n readonly db: G9SqliteDatabase;\n /** The transaction token, or `null` for a single atomic batch. */\n readonly tx: G9TxToken | null;\n /** The transaction state (for scopes opened inside the unit), or `null`. */\n readonly txState: TxState | null;\n run(statements: readonly G9DriverStatement[]): Promise<G9SqlResult[]>;\n /** Runs after the commit (never after a rollback). */\n onCommit(callback: () => void | Promise<void>): void;\n readonly signal: G9AbortSignal | undefined;\n}\n\ninterface TxState {\n readonly token: G9TxToken;\n readonly session: G9SessionToken;\n readonly generation: number;\n readonly commitCallbacks: (() => void | Promise<void>)[];\n savepoints: number;\n finished: boolean;\n}\n\n/** Options of a transaction. */\nexport interface G9TransactionOptions {\n /** `immediate` (default) takes the write lock at begin, so a busy conflict surfaces before any work. */\n readonly mode?: 'deferred' | 'immediate';\n readonly signal?: G9AbortSignal;\n /** Override the database's busy retry count for this transaction. */\n readonly retries?: number;\n}\n\n/**\n * The session layer (MAUI `G9SqliteConnectionProvider` + repository plumbing): owns the connection, the user/path\n * generation, the write lock, transactions, caches and change notifications. One writer connection serialises all\n * work in FIFO order; a transaction holds it for its whole duration.\n */\nexport class G9SqliteDatabase {\n /** @internal */ readonly options: G9ResolvedSqliteOptions;\n /** @internal */ readonly lock = new G9AsyncLock();\n /** @internal */ readonly caches: G9CacheRegistry;\n private connection: Connection | null = null;\n private generationValue = 0;\n private capabilitiesValue: G9DriverCapabilities | null = null;\n private readonly unsubscribeLocator: (() => void) | undefined;\n private readonly changeListeners = new Set<(event: G9ChangeEvent) => void>();\n private closed = false;\n\n constructor(options: G9SqliteOptions) {\n this.options = resolveOptions(options);\n this.caches = new G9CacheRegistry(this);\n this.unsubscribeLocator = this.options.locator.onDatabasePathChanged?.(() => {\n void this.switchDatabase().catch((error) => this.report('locator switch failed', error));\n });\n for (const entity of this.options.entities) {\n if (entity.cachePolicy) this.caches.defineEntityCache(entity, entity.cachePolicy);\n }\n }\n\n /** Bumped by every user/path switch; work noted under an older generation is cancelled or discarded. */\n get generation(): number {\n return this.generationValue;\n }\n\n /** MAUI `DatabasePath`: what the locator answers now. */\n get databasePath(): string {\n return this.options.locator.getDatabasePath();\n }\n\n /** MAUI `ActiveDatabasePath`: the path of the open connection, or `null`. */\n get activeDatabasePath(): string | null {\n return this.connection?.path ?? null;\n }\n\n /** MAUI `HasActiveDatabase`: whether the locator can currently answer. */\n get hasActiveDatabase(): boolean {\n try {\n const path = this.options.locator.getDatabasePath();\n return typeof path === 'string' && path.trim() !== '';\n } catch {\n return false;\n }\n }\n\n /** @internal Build options for compiling queries against this database. */\n buildOptions(): G9BuildOptions {\n return {\n codec: this.options.codec,\n ...(this.options.cultureKey ? { defaultCulture: this.options.cultureKey } : {}),\n ...(this.options.maxInListParameters !== undefined\n ? { maxInListParameters: this.options.maxInListParameters }\n : {}),\n };\n }\n\n /** @internal Reports a non-fatal failure (post-commit hook, cache refresh) to diagnostics. */\n report(message: string, error: unknown): void {\n const d = this.options.diagnostics;\n if (d) d.log({ level: G9LogLevel.Warning, message, source: 'g9-sqlite', error });\n }\n\n /** Driver capabilities (negotiated once). */\n async capabilities(): Promise<G9DriverCapabilities> {\n if (!this.capabilitiesValue) this.capabilitiesValue = await this.options.driver.capabilities();\n return this.capabilitiesValue;\n }\n\n private ensureOpen(): void {\n if (this.closed) throw new G9SqliteError('misuse', 'The database is closed.');\n }\n\n /** @internal Resolves the connection for the current path; caller holds the lock. */\n async connect(): Promise<Connection> {\n this.ensureOpen();\n const path = this.options.locator.getDatabasePath();\n const current = this.connection;\n if (current && current.path.toLowerCase() === path.toLowerCase()) return current;\n if (current) {\n // The locator changed its answer without raising the event: same consequence as a switch.\n this.connection = null;\n await this.options.driver.close(current.token).catch((error) => this.report('close failed', error));\n this.generationValue++;\n this.caches.resetAll();\n }\n const token = await this.options.driver.open({\n path,\n create: this.options.create,\n readOnly: this.options.readOnly,\n durability: this.options.durability,\n pragmas: this.options.pragmas,\n });\n const connection: Connection = { token, path, generation: this.generationValue };\n this.connection = connection;\n try {\n // Every open: migrations (a one-query fast path once applied), index DDL, initializers. Each step re-checks\n // under the write lock, so the whole setup is retried on `busy` (another opener is migrating).\n for (let attempt = 0; ; attempt++) {\n try {\n await runSchemaSetup(this, token);\n break;\n } catch (error) {\n if (!isG9SqliteError(error, 'busy') || attempt >= this.options.busyRetries) throw error;\n await this.sleep(this.options.busyInitialDelayMs * 2 ** attempt);\n }\n }\n } catch (error) {\n // A failed migration leaves the database unusable for this open; close so the next call retries.\n this.connection = null;\n await this.options.driver.close(token).catch(() => undefined);\n throw error;\n }\n return connection;\n }\n\n /**\n * MAUI `SqliteMigrationRunner.RunAsync`: opens the connection now, which applies pending migrations, declared\n * indexes and initializers (otherwise that happens on the first call). Rejects with the migration's error.\n */\n async migrate(): Promise<void> {\n await this.withLock(async () => undefined);\n }\n\n /** @internal Runs work while holding the connection lock. */\n async withLock<T>(work: (connection: Connection) => Promise<T>, signal?: G9AbortSignal): Promise<T> {\n this.ensureOpen();\n const generation = this.generationValue;\n const release = await this.lock.acquire();\n try {\n if (signal?.aborted) throw new G9SqliteError('cancelled', 'Cancelled while waiting for the database.');\n if (generation !== this.generationValue) {\n throw new G9SqliteError('cancelled', 'The database was switched (user change) while this call waited.');\n }\n return await work(await this.connect());\n } finally {\n release();\n }\n }\n\n /** @internal A read (or any single batch) outside a transaction; discarded if the user switched meanwhile. */\n async runRead(\n statements: readonly G9DriverStatement[],\n options: { maxRows?: number; signal?: G9AbortSignal } = {},\n ): Promise<G9SqlResult[]> {\n return this.withLock(async (connection) => {\n const runOptions: { -readonly [K in keyof G9RunOptions]: G9RunOptions[K] } = {};\n if (options.maxRows !== undefined) runOptions.maxRows = options.maxRows;\n if (options.signal) runOptions.signal = options.signal;\n const results = await this.options.driver.run(connection.token, statements, runOptions);\n if (connection.generation !== this.generationValue) {\n throw new G9SqliteError('cancelled', 'The database was switched while this read ran; its rows are discarded.');\n }\n return results;\n }, options.signal);\n }\n\n /**\n * @internal Runs a unit of work. Inside an open transaction (`parent`), it joins it. Otherwise it takes the lock\n * and either runs one atomic batch (`needsTransaction` false: one bridge call) or a full immediate transaction,\n * retrying the whole unit on `busy`. Commit callbacks run after the lock is released.\n */\n async unit<T>(\n parent: TxState | null,\n needsTransaction: boolean,\n work: (uow: G9UnitOfWork) => Promise<T>,\n options: G9TransactionOptions = {},\n ): Promise<T> {\n if (parent) return this.joinUnit(parent, work, options.signal);\n const retries = options.retries ?? this.options.busyRetries;\n let attempt = 0;\n for (;;) {\n try {\n return await this.unitOnce(needsTransaction, work, options);\n } catch (error) {\n if (!isG9SqliteError(error, 'busy') || attempt >= retries || options.signal?.aborted) throw error;\n const delay = this.options.busyInitialDelayMs * 2 ** attempt;\n attempt++;\n await this.sleep(delay, options.signal);\n }\n }\n }\n\n /** @internal */\n sleep(ms: number, signal?: G9AbortSignal): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n const onAbort = () => {\n this.options.timers.clearTimeout(handle);\n reject(new G9SqliteError('cancelled', 'Cancelled during busy back-off.'));\n };\n const handle = this.options.timers.setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n }\n\n private async joinUnit<T>(\n parent: TxState,\n work: (uow: G9UnitOfWork) => Promise<T>,\n signal: G9AbortSignal | undefined,\n ): Promise<T> {\n if (parent.finished) throw new G9SqliteError('misuse', 'The transaction is already finished.');\n const uow: G9UnitOfWork = {\n db: this,\n tx: parent.token,\n txState: parent,\n signal,\n run: (statements) => this.runInTx(parent, statements, undefined, signal),\n onCommit: (cb) => parent.commitCallbacks.push(cb),\n };\n return work(uow);\n }\n\n /** @internal */\n async runInTx(\n tx: TxState,\n statements: readonly G9DriverStatement[],\n maxRows: number | undefined,\n signal: G9AbortSignal | undefined,\n ): Promise<G9SqlResult[]> {\n if (tx.finished) throw new G9SqliteError('misuse', 'The transaction is already finished.');\n if (tx.generation !== this.generationValue) {\n throw new G9SqliteError('cancelled', 'The database was switched; this transaction can no longer run.');\n }\n const runOptions: { -readonly [K in keyof G9RunOptions]: G9RunOptions[K] } = { tx: tx.token };\n if (maxRows !== undefined) runOptions.maxRows = maxRows;\n if (signal) runOptions.signal = signal;\n return this.options.driver.run(tx.session, statements, runOptions);\n }\n\n private async unitOnce<T>(\n needsTransaction: boolean,\n work: (uow: G9UnitOfWork) => Promise<T>,\n options: G9TransactionOptions,\n ): Promise<T> {\n const callbacks: (() => void | Promise<void>)[] = [];\n const result = await this.withLock(async (connection) => {\n if (!needsTransaction) {\n // One atomic batch: every caller of a non-transactional unit runs exactly one `run`.\n const uow: G9UnitOfWork = {\n db: this,\n tx: null,\n txState: null,\n signal: options.signal,\n run: (statements) =>\n this.options.driver.run(connection.token, statements, {\n atomic: true,\n ...(options.signal ? { signal: options.signal } : {}),\n }),\n onCommit: (cb) => callbacks.push(cb),\n };\n return work(uow);\n }\n const tx = await this.beginTx(connection, options.mode ?? 'immediate');\n try {\n const value = await this.joinUnit(tx, work, options.signal);\n await this.commitTx(tx);\n callbacks.push(...tx.commitCallbacks);\n return value;\n } catch (error) {\n await this.rollbackTx(tx);\n throw error;\n }\n }, options.signal);\n await this.runCommitCallbacks(callbacks);\n return result;\n }\n\n /** @internal */\n async beginTx(connection: Connection, mode: 'deferred' | 'immediate'): Promise<TxState> {\n const token = await this.options.driver.begin(connection.token, mode);\n return {\n token,\n session: connection.token,\n generation: connection.generation,\n commitCallbacks: [],\n savepoints: 0,\n finished: false,\n };\n }\n\n /** @internal */\n async commitTx(tx: TxState): Promise<void> {\n try {\n await this.options.driver.commit(tx.token);\n } catch (error) {\n // A busy COMMIT leaves the transaction open (the caller rolls back). An unknown outcome is final.\n if (isG9SqliteError(error, 'outcome-unknown')) tx.finished = true;\n throw error;\n }\n tx.finished = true;\n }\n\n /** @internal */\n async rollbackTx(tx: TxState): Promise<void> {\n if (tx.finished) return;\n tx.finished = true;\n await this.options.driver.rollback(tx.token).catch((error) => this.report('rollback failed', error));\n }\n\n /** @internal Commit callbacks: cache invalidation, post-commit hooks, change events. Failures are reported. */\n async runCommitCallbacks(callbacks: readonly (() => void | Promise<void>)[]): Promise<void> {\n for (const cb of callbacks) {\n try {\n await cb();\n } catch (error) {\n this.report('post-commit callback failed (the write is committed)', error);\n }\n }\n }\n\n /** @internal Explicit transaction: holds the lock until commit/rollback. */\n async openTransaction(options: G9TransactionOptions = {}): Promise<{ tx: TxState; release: () => void }> {\n this.ensureOpen();\n const generation = this.generationValue;\n const release = await this.lock.acquire();\n try {\n if (generation !== this.generationValue) {\n throw new G9SqliteError('cancelled', 'The database was switched while the transaction waited.');\n }\n const connection = await this.connect();\n const tx = await this.beginTx(connection, options.mode ?? 'immediate');\n return { tx, release };\n } catch (error) {\n release();\n throw error;\n }\n }\n\n /**\n * MAUI `SwitchDatabaseAsync` / `DatabasePathChanged`: bumps the generation (queued work of the old user is\n * cancelled, rows a running read returns are discarded), resets every cache synchronously, then closes the\n * connection once the current holder finishes. The next call opens whatever the locator answers.\n */\n async switchDatabase(): Promise<void> {\n this.generationValue++;\n // Queued before any work a cache-reset listener starts, so that work opens the new database.\n const acquiring = this.lock.acquire();\n this.caches.resetAll();\n const release = await acquiring;\n try {\n const current = this.connection;\n this.connection = null;\n if (current) await this.options.driver.close(current.token);\n } finally {\n release();\n }\n }\n\n /** MAUI `CloseCurrentConnectionAsync`: closes the connection without switching users. */\n async closeConnection(): Promise<void> {\n const release = await this.lock.acquire();\n try {\n const current = this.connection;\n this.connection = null;\n if (current) await this.options.driver.close(current.token);\n } finally {\n release();\n }\n }\n\n /** MAUI `CheckpointWalAsync`: `PRAGMA wal_checkpoint(TRUNCATE)` on the open connection (no-op when none). */\n async checkpointWal(): Promise<void> {\n if (!this.connection) return;\n await this.withLock((c) =>\n this.options.driver.run(c.token, [{ sql: 'PRAGMA wal_checkpoint(TRUNCATE)', params: [] }]),\n );\n }\n\n /** Disposes: unsubscribes the locator, stops caches, closes the connection. Later calls fail with `misuse`. */\n async close(): Promise<void> {\n if (this.closed) return;\n this.unsubscribeLocator?.();\n this.caches.dispose();\n await this.closeConnection();\n this.closed = true;\n this.changeListeners.clear();\n }\n\n /** Subscribes to committed changes (one event per committed write); returns the unsubscribe function. */\n onChange(listener: (event: G9ChangeEvent) => void): () => void {\n this.changeListeners.add(listener);\n return () => this.changeListeners.delete(listener);\n }\n\n /** @internal Publishes a committed change: caches first, then listeners. */\n publishChange(event: G9ChangeEvent): void {\n this.caches.invalidateTable(event.table);\n this.emitChange(event);\n }\n\n /** @internal Tells change listeners (after caches and post-commit hooks). */\n emitChange(event: G9ChangeEvent): void {\n for (const listener of Array.from(this.changeListeners)) {\n try {\n listener(event);\n } catch (error) {\n this.report('change listener failed', error);\n }\n }\n }\n\n /**\n * Tells caches and listeners that something else wrote to these tables (a sync engine on the same file, another\n * connection). Caches of those tables (and DTO caches over them) refresh.\n */\n notifyExternalChange(change: { readonly tables: readonly string[] }): void {\n for (const table of change.tables) this.publishChange({ table, entity: null, kind: 'external', rowCount: -1 });\n }\n\n /** @internal Encodes raw parameters (no codecs, MAUI `NormalizeParam`). */\n encodeRaw(params: readonly unknown[]): G9DriverStatement['params'] {\n return params.map((p) => encodeParam(p, undefined, this.options.codec));\n }\n\n /** @internal Loads an entity cache: managed SELECT (filters, soft delete), localized when a culture is set. */\n async loadEntityRowsForCache<T>(entity: G9EntityDescriptor, maxRows: number): Promise<T[]> {\n const builder = G9Sql.select(entity);\n if (this.options.cultureKey) builder.withCulture();\n const { statement, shape } = builder.compile(this.buildOptions());\n try {\n const [result] = await this.runRead([statement], { maxRows });\n return decodeShaped<T>(shape, result as G9SqlResult, this.options.codec);\n } catch (error) {\n if (error instanceof G9SqliteError && /no such table/i.test(error.message)) return [];\n throw error;\n }\n }\n}\n\nexport type { TxState as G9TxState };\n"],"names":["defaultTimers","g9RuntimeTimers","resolveOptions","options","_options_entities","_options_initializers","_options_clock","_options_currentUser","_options_idCase","_options_dateTimeProfile","_options_durability","_options_migrations","_options_initializers1","_options_interceptors","_options_timers","_options_timeSource","_options_busy","_options_busy1","_options_busy2","G9SqliteError","retries","delay","Number","entities","Object","e","Array","tables","Map","other","names","Set","i","createSystemAuditClock","g9NoCurrentUser","sortMigrations","createSystemClock","G9SqliteDatabase","_this_connection","path","undefined","message","error","d","G9LogLevel","current","token","connection","attempt","runSchemaSetup","isG9SqliteError","work","signal","generation","release","statements","runOptions","results","parent","needsTransaction","_options_retries","_options_signal","ms","Promise","resolve","reject","onAbort","handle","uow","cb","tx","maxRows","callbacks","result","_options_mode","value","mode","acquiring","c","_this","listener","event","change","table","params","p","encodeParam","entity","builder","G9Sql","statement","shape","decodeShaped","_this_options_locator","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AAIA,iBAAiBvB,iBAAiB,iBAAiB,IAAI,CAACuB,MAAM,OAAO,GAAG,OAAO,EAAE;YACrF,MAAMA;QACR;IACF;IAnaA,YAAYvC,OAAwB,CAAE;YAGV0F,6CAAAA;QAbX,uBAAS,WAAT;QACA,uBAAS,QAAO,IAAIC;QACpB,uBAAS,UAAT;QACjB,uBAAQ,cAAgC;QACxC,uBAAQ,mBAAkB;QAC1B,uBAAQ,qBAAiD;QACzD,uBAAiB,sBAAjB;QACA,uBAAiB,mBAAkB,IAAI/D;QACvC,uBAAQ,UAAS;QAGf,IAAI,CAAC,OAAO,GAAG7B,eAAeC;QAC9B,IAAI,CAAC,MAAM,GAAG,IAAI4F,gBAAgB,IAAI;QACtC,IAAI,CAAC,kBAAkB,GAAG,QAAAF,CAAAA,8CAAAA,AAAAA,CAAAA,wBAAAA,IAAI,CAAC,OAAO,CAAC,OAAO,AAAD,EAAE,qBAAqB,AAAD,IAAzCA,KAAAA,IAAAA,4CAAAA,IAAAA,CAAAA,uBAA6C;YAChE,IAAI,CAAC,cAAc,GAAG,KAAK,CAAC,CAACnD,QAAU,IAAI,CAAC,MAAM,CAAC,yBAAyBA;QACnF;QACA,KAAK,MAAM6C,UAAU,IAAI,CAAC,OAAO,CAAC,QAAQ,CACxC,IAAIA,OAAO,WAAW,EAAE,IAAI,CAAC,MAAM,CAAC,iBAAiB,CAACA,QAAQA,OAAO,WAAW;IAEpF;AA2ZF"}
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Decides which database file is open and says when the answer changes (MAUI `IG9SqliteDatabaseLocator`). Read on
3
+ * every connection acquisition, so it must be cheap; returning a different path closes the old connection, resets
4
+ * every cache and opens the new file.
5
+ */
6
+ export interface G9DatabaseLocator {
7
+ getDatabasePath(): string;
8
+ /** MAUI `DatabasePathChanged`: subscribe; returns the unsubscribe function. */
9
+ onDatabasePathChanged?(listener: () => void): () => void;
10
+ }
11
+ /** MAUI `G9SingleFileDatabaseLocator`: one file at a fixed path. The right default for a single-user app. */
12
+ export declare function singleFileDatabaseLocator(path: string): G9DatabaseLocator;
13
+ /** Characters .NET's `Path.GetInvalidFileNameChars()` reports on Android/iOS/macOS (MAUI's targets). */
14
+ export declare const g9UnixInvalidFileNameChars = "\0/";
15
+ /** The Windows set (control characters are always removed too). */
16
+ export declare const g9WindowsInvalidFileNameChars = "\0/\\:*?\"<>|";
17
+ /** A per-user locator (MAUI `G9PerUserDatabaseLocator`) with its `notifyUserChanged`. */
18
+ export interface G9PerUserDatabaseLocator extends G9DatabaseLocator {
19
+ /** Call after the active user changes, so the database swaps the connection and drops every cache. */
20
+ notifyUserChanged(): void;
21
+ }
22
+ /**
23
+ * MAUI `G9PerUserDatabaseLocator`: `<root>/users/<userId>/<fileName>`. ⚠ The directory name is the raw user id with
24
+ * invalid file-name characters removed, exactly as MAUI derived it: changing the id form orphans existing
25
+ * directories. Throws (`misuse`) when no user is active, so nothing silently opens a shared file.
26
+ */
27
+ export declare function perUserDatabaseLocator(options: {
28
+ readonly root: string;
29
+ readonly userId: () => string | null;
30
+ readonly fileName?: string;
31
+ readonly invalidFileNameChars?: string;
32
+ }): G9PerUserDatabaseLocator;
33
+ //# sourceMappingURL=locator.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"locator.d.ts","sourceRoot":"","sources":["../../src/session/locator.ts"],"names":[],"mappings":"AAEA;;;;GAIG;AACH,MAAM,WAAW,iBAAiB;IAChC,eAAe,IAAI,MAAM,CAAC;IAC1B,+EAA+E;IAC/E,qBAAqB,CAAC,CAAC,QAAQ,EAAE,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC;CAC1D;AAED,6GAA6G;AAC7G,wBAAgB,yBAAyB,CAAC,IAAI,EAAE,MAAM,GAAG,iBAAiB,CAGzE;AAED,wGAAwG;AACxG,eAAO,MAAM,0BAA0B,QAAY,CAAC;AACpD,mEAAmE;AACnE,eAAO,MAAM,6BAA6B,kBAAqB,CAAC;AAEhE,yFAAyF;AACzF,MAAM,WAAW,wBAAyB,SAAQ,iBAAiB;IACjE,sGAAsG;IACtG,iBAAiB,IAAI,IAAI,CAAC;CAC3B;AAED;;;;GAIG;AACH,wBAAgB,sBAAsB,CAAC,OAAO,EAAE;IAC9C,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,MAAM,EAAE,MAAM,MAAM,GAAG,IAAI,CAAC;IACrC,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,oBAAoB,CAAC,EAAE,MAAM,CAAC;CACxC,GAAG,wBAAwB,CA6B3B"}
@@ -0,0 +1,39 @@
1
+ import { G9SqliteError } from "../errors.js";
2
+ function singleFileDatabaseLocator(path) {
3
+ if ('string' != typeof path || '' === path.trim()) throw new G9SqliteError('misuse', 'The database path is empty.');
4
+ return Object.freeze({
5
+ getDatabasePath: ()=>path,
6
+ onDatabasePathChanged: ()=>()=>void 0
7
+ });
8
+ }
9
+ const g9UnixInvalidFileNameChars = '\u0000/';
10
+ const g9WindowsInvalidFileNameChars = '\u0000/\\:*?"<>|';
11
+ function perUserDatabaseLocator(options) {
12
+ var _options_invalidFileNameChars, _options_fileName;
13
+ const listeners = new Set();
14
+ const invalid = null != (_options_invalidFileNameChars = options.invalidFileNameChars) ? _options_invalidFileNameChars : g9UnixInvalidFileNameChars;
15
+ const fileName = null != (_options_fileName = options.fileName) ? _options_fileName : 'g9.db';
16
+ const root = options.root.replace(/[\\/]+$/, '');
17
+ return {
18
+ getDatabasePath () {
19
+ const userId = options.userId();
20
+ if (null == userId || '' === userId.trim()) throw new G9SqliteError('misuse', 'perUserDatabaseLocator has no active user. Activate the user before any repository opens a connection.');
21
+ let safe = '';
22
+ for (const ch of userId){
23
+ const code = ch.charCodeAt(0);
24
+ if (invalid.indexOf(ch) < 0 && !(invalid !== g9UnixInvalidFileNameChars && code < 32)) safe += ch;
25
+ }
26
+ return `${root}/users/${safe}/${fileName}`;
27
+ },
28
+ onDatabasePathChanged (listener) {
29
+ listeners.add(listener);
30
+ return ()=>listeners.delete(listener);
31
+ },
32
+ notifyUserChanged () {
33
+ for (const listener of Array.from(listeners))listener();
34
+ }
35
+ };
36
+ }
37
+ export { g9UnixInvalidFileNameChars, g9WindowsInvalidFileNameChars, perUserDatabaseLocator, singleFileDatabaseLocator };
38
+
39
+ //# sourceMappingURL=locator.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session/locator.js","sources":["../../src/session/locator.ts"],"sourcesContent":["import { G9SqliteError } from '../errors';\n\n/**\n * Decides which database file is open and says when the answer changes (MAUI `IG9SqliteDatabaseLocator`). Read on\n * every connection acquisition, so it must be cheap; returning a different path closes the old connection, resets\n * every cache and opens the new file.\n */\nexport interface G9DatabaseLocator {\n getDatabasePath(): string;\n /** MAUI `DatabasePathChanged`: subscribe; returns the unsubscribe function. */\n onDatabasePathChanged?(listener: () => void): () => void;\n}\n\n/** MAUI `G9SingleFileDatabaseLocator`: one file at a fixed path. The right default for a single-user app. */\nexport function singleFileDatabaseLocator(path: string): G9DatabaseLocator {\n if (typeof path !== 'string' || path.trim() === '') throw new G9SqliteError('misuse', 'The database path is empty.');\n return Object.freeze({ getDatabasePath: () => path, onDatabasePathChanged: () => () => undefined });\n}\n\n/** Characters .NET's `Path.GetInvalidFileNameChars()` reports on Android/iOS/macOS (MAUI's targets). */\nexport const g9UnixInvalidFileNameChars = '\\u0000/';\n/** The Windows set (control characters are always removed too). */\nexport const g9WindowsInvalidFileNameChars = '\\u0000/\\\\:*?\"<>|';\n\n/** A per-user locator (MAUI `G9PerUserDatabaseLocator`) with its `notifyUserChanged`. */\nexport interface G9PerUserDatabaseLocator extends G9DatabaseLocator {\n /** Call after the active user changes, so the database swaps the connection and drops every cache. */\n notifyUserChanged(): void;\n}\n\n/**\n * MAUI `G9PerUserDatabaseLocator`: `<root>/users/<userId>/<fileName>`. ⚠ The directory name is the raw user id with\n * invalid file-name characters removed, exactly as MAUI derived it: changing the id form orphans existing\n * directories. Throws (`misuse`) when no user is active, so nothing silently opens a shared file.\n */\nexport function perUserDatabaseLocator(options: {\n readonly root: string;\n readonly userId: () => string | null;\n readonly fileName?: string;\n readonly invalidFileNameChars?: string;\n}): G9PerUserDatabaseLocator {\n const listeners = new Set<() => void>();\n const invalid = options.invalidFileNameChars ?? g9UnixInvalidFileNameChars;\n const fileName = options.fileName ?? 'g9.db';\n const root = options.root.replace(/[\\\\/]+$/, '');\n return {\n getDatabasePath() {\n const userId = options.userId();\n if (userId === null || userId === undefined || userId.trim() === '') {\n throw new G9SqliteError(\n 'misuse',\n 'perUserDatabaseLocator has no active user. Activate the user before any repository opens a connection.',\n );\n }\n let safe = '';\n for (const ch of userId) {\n const code = ch.charCodeAt(0);\n if (invalid.indexOf(ch) < 0 && !(invalid !== g9UnixInvalidFileNameChars && code < 32)) safe += ch;\n }\n return `${root}/users/${safe}/${fileName}`;\n },\n onDatabasePathChanged(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n notifyUserChanged() {\n for (const listener of Array.from(listeners)) listener();\n },\n };\n}\n"],"names":["singleFileDatabaseLocator","path","G9SqliteError","Object","undefined","g9UnixInvalidFileNameChars","g9WindowsInvalidFileNameChars","perUserDatabaseLocator","options","_options_invalidFileNameChars","_options_fileName","listeners","Set","invalid","fileName","root","userId","safe","ch","code","listener","Array"],"mappings":";AAcO,SAASA,0BAA0BC,IAAY;IACpD,IAAI,AAAgB,YAAhB,OAAOA,QAAqBA,AAAgB,OAAhBA,KAAK,IAAI,IAAW,MAAM,IAAIC,cAAc,UAAU;IACtF,OAAOC,OAAO,MAAM,CAAC;QAAE,iBAAiB,IAAMF;QAAM,uBAAuB,IAAM,IAAMG;IAAU;AACnG;AAGO,MAAMC,6BAA6B;AAEnC,MAAMC,gCAAgC;AAatC,SAASC,uBAAuBC,OAKtC;QAEiBC,+BACCC;IAFjB,MAAMC,YAAY,IAAIC;IACtB,MAAMC,UAAU,QAAAJ,CAAAA,gCAAAA,QAAQ,oBAAoB,AAAD,IAA3BA,gCAAgCJ;IAChD,MAAMS,WAAW,QAAAJ,CAAAA,oBAAAA,QAAQ,QAAQ,AAAD,IAAfA,oBAAoB;IACrC,MAAMK,OAAOP,QAAQ,IAAI,CAAC,OAAO,CAAC,WAAW;IAC7C,OAAO;QACL;YACE,MAAMQ,SAASR,QAAQ,MAAM;YAC7B,IAAIQ,QAAAA,UAA2CA,AAAkB,OAAlBA,OAAO,IAAI,IACxD,MAAM,IAAId,cACR,UACA;YAGJ,IAAIe,OAAO;YACX,KAAK,MAAMC,MAAMF,OAAQ;gBACvB,MAAMG,OAAOD,GAAG,UAAU,CAAC;gBAC3B,IAAIL,QAAQ,OAAO,CAACK,MAAM,KAAK,CAAEL,CAAAA,YAAYR,8BAA8Bc,OAAO,EAAC,GAAIF,QAAQC;YACjG;YACA,OAAO,GAAGH,KAAK,OAAO,EAAEE,KAAK,CAAC,EAAEH,UAAU;QAC5C;QACA,uBAAsBM,QAAQ;YAC5BT,UAAU,GAAG,CAACS;YACd,OAAO,IAAMT,UAAU,MAAM,CAACS;QAChC;QACA;YACE,KAAK,MAAMA,YAAYC,MAAM,IAAI,CAACV,WAAYS;QAChD;IACF;AACF"}