@powersync/shared-internals 0.0.0-tmp.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 (153) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +5 -0
  3. package/dist/bundle.cjs +11787 -0
  4. package/dist/bundle.cjs.map +1 -0
  5. package/dist/bundle.mjs +11757 -0
  6. package/dist/bundle.mjs.map +1 -0
  7. package/dist/bundle.node.cjs +9418 -0
  8. package/dist/bundle.node.cjs.map +1 -0
  9. package/dist/bundle.node.mjs +9388 -0
  10. package/dist/bundle.node.mjs.map +1 -0
  11. package/dist/index.d.cts +1159 -0
  12. package/dist/websockets.mjs +7558 -0
  13. package/dist/websockets.mjs.map +1 -0
  14. package/dist/websockets.node.mjs +5189 -0
  15. package/dist/websockets.node.mjs.map +1 -0
  16. package/legacy/sync_protocol.d.ts +103 -0
  17. package/lib/client/BasePowerSyncDatabase.d.ts +147 -0
  18. package/lib/client/BasePowerSyncDatabase.js +622 -0
  19. package/lib/client/BasePowerSyncDatabase.js.map +1 -0
  20. package/lib/client/ConnectionManager.d.ts +116 -0
  21. package/lib/client/ConnectionManager.js +306 -0
  22. package/lib/client/ConnectionManager.js.map +1 -0
  23. package/lib/client/CustomQuery.d.ts +21 -0
  24. package/lib/client/CustomQuery.js +43 -0
  25. package/lib/client/CustomQuery.js.map +1 -0
  26. package/lib/client/sync/bucket/BucketStorageAdapter.d.ts +42 -0
  27. package/lib/client/sync/bucket/BucketStorageAdapter.js +23 -0
  28. package/lib/client/sync/bucket/BucketStorageAdapter.js.map +1 -0
  29. package/lib/client/sync/bucket/CrudEntry.d.ts +46 -0
  30. package/lib/client/sync/bucket/CrudEntry.js +60 -0
  31. package/lib/client/sync/bucket/CrudEntry.js.map +1 -0
  32. package/lib/client/sync/bucket/SqliteBucketStorage.d.ts +33 -0
  33. package/lib/client/sync/bucket/SqliteBucketStorage.js +166 -0
  34. package/lib/client/sync/bucket/SqliteBucketStorage.js.map +1 -0
  35. package/lib/client/sync/options.d.ts +9 -0
  36. package/lib/client/sync/options.js +16 -0
  37. package/lib/client/sync/options.js.map +1 -0
  38. package/lib/client/sync/stream/AbstractRemote.d.ts +125 -0
  39. package/lib/client/sync/stream/AbstractRemote.js +265 -0
  40. package/lib/client/sync/stream/AbstractRemote.js.map +1 -0
  41. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.d.ts +138 -0
  42. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js +611 -0
  43. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js.map +1 -0
  44. package/lib/client/sync/stream/WebSocketSupport.d.ts +26 -0
  45. package/lib/client/sync/stream/WebSocketSupport.js +198 -0
  46. package/lib/client/sync/stream/WebSocketSupport.js.map +1 -0
  47. package/lib/client/sync/stream/WebsocketClientTransport.d.ts +15 -0
  48. package/lib/client/sync/stream/WebsocketClientTransport.js +62 -0
  49. package/lib/client/sync/stream/WebsocketClientTransport.js.map +1 -0
  50. package/lib/client/sync/stream/core-instruction.d.ts +75 -0
  51. package/lib/client/sync/stream/core-instruction.js +4 -0
  52. package/lib/client/sync/stream/core-instruction.js.map +1 -0
  53. package/lib/client/triggers/MemoryTriggerClaimManager.d.ts +6 -0
  54. package/lib/client/triggers/MemoryTriggerClaimManager.js +21 -0
  55. package/lib/client/triggers/MemoryTriggerClaimManager.js.map +1 -0
  56. package/lib/client/triggers/TriggerManagerImpl.d.ts +68 -0
  57. package/lib/client/triggers/TriggerManagerImpl.js +415 -0
  58. package/lib/client/triggers/TriggerManagerImpl.js.map +1 -0
  59. package/lib/client/watched/AbstractQueryProcessor.d.ts +68 -0
  60. package/lib/client/watched/AbstractQueryProcessor.js +155 -0
  61. package/lib/client/watched/AbstractQueryProcessor.js.map +1 -0
  62. package/lib/client/watched/DifferentialQueryProcessor.d.ts +50 -0
  63. package/lib/client/watched/DifferentialQueryProcessor.js +174 -0
  64. package/lib/client/watched/DifferentialQueryProcessor.js.map +1 -0
  65. package/lib/client/watched/OnChangeQueryProcessor.d.ts +22 -0
  66. package/lib/client/watched/OnChangeQueryProcessor.js +80 -0
  67. package/lib/client/watched/OnChangeQueryProcessor.js.map +1 -0
  68. package/lib/client/watched/WatchedQuery.d.ts +9 -0
  69. package/lib/client/watched/WatchedQuery.js +12 -0
  70. package/lib/client/watched/WatchedQuery.js.map +1 -0
  71. package/lib/constants.d.ts +5 -0
  72. package/lib/constants.js +6 -0
  73. package/lib/constants.js.map +1 -0
  74. package/lib/db/ConnectionClosedError.d.ts +12 -0
  75. package/lib/db/ConnectionClosedError.js +23 -0
  76. package/lib/db/ConnectionClosedError.js.map +1 -0
  77. package/lib/db/crud/SyncProgress.d.ts +10 -0
  78. package/lib/db/crud/SyncProgress.js +33 -0
  79. package/lib/db/crud/SyncProgress.js.map +1 -0
  80. package/lib/db/crud/SyncStatus.d.ts +48 -0
  81. package/lib/db/crud/SyncStatus.js +178 -0
  82. package/lib/db/crud/SyncStatus.js.map +1 -0
  83. package/lib/db/openDatabase.d.ts +7 -0
  84. package/lib/db/openDatabase.js +22 -0
  85. package/lib/db/openDatabase.js.map +1 -0
  86. package/lib/index.d.ts +22 -0
  87. package/lib/index.js +22 -0
  88. package/lib/index.js.map +1 -0
  89. package/lib/utils/AbortOperation.d.ts +11 -0
  90. package/lib/utils/AbortOperation.js +21 -0
  91. package/lib/utils/AbortOperation.js.map +1 -0
  92. package/lib/utils/ControlledExecutor.d.ts +31 -0
  93. package/lib/utils/ControlledExecutor.js +54 -0
  94. package/lib/utils/ControlledExecutor.js.map +1 -0
  95. package/lib/utils/MetaBaseObserver.d.ts +11 -0
  96. package/lib/utils/MetaBaseObserver.js +51 -0
  97. package/lib/utils/MetaBaseObserver.js.map +1 -0
  98. package/lib/utils/async.d.ts +46 -0
  99. package/lib/utils/async.js +147 -0
  100. package/lib/utils/async.js.map +1 -0
  101. package/lib/utils/compatibility.d.ts +8 -0
  102. package/lib/utils/compatibility.js +9 -0
  103. package/lib/utils/compatibility.js.map +1 -0
  104. package/lib/utils/mutex.d.ts +42 -0
  105. package/lib/utils/mutex.js +150 -0
  106. package/lib/utils/mutex.js.map +1 -0
  107. package/lib/utils/parseQuery.d.ts +12 -0
  108. package/lib/utils/parseQuery.js +20 -0
  109. package/lib/utils/parseQuery.js.map +1 -0
  110. package/lib/utils/queue.d.ts +16 -0
  111. package/lib/utils/queue.js +42 -0
  112. package/lib/utils/queue.js.map +1 -0
  113. package/lib/utils/stream_transform.d.ts +41 -0
  114. package/lib/utils/stream_transform.js +211 -0
  115. package/lib/utils/stream_transform.js.map +1 -0
  116. package/lib/version.d.ts +1 -0
  117. package/lib/version.js +4 -0
  118. package/lib/version.js.map +1 -0
  119. package/package.json +65 -0
  120. package/src/client/BasePowerSyncDatabase.ts +853 -0
  121. package/src/client/ConnectionManager.ts +419 -0
  122. package/src/client/CustomQuery.ts +60 -0
  123. package/src/client/sync/bucket/BucketStorageAdapter.ts +51 -0
  124. package/src/client/sync/bucket/CrudEntry.ts +116 -0
  125. package/src/client/sync/bucket/SqliteBucketStorage.ts +213 -0
  126. package/src/client/sync/options.ts +24 -0
  127. package/src/client/sync/stream/AbstractRemote.ts +369 -0
  128. package/src/client/sync/stream/AbstractStreamingSyncImplementation.ts +795 -0
  129. package/src/client/sync/stream/WebSocketSupport.ts +259 -0
  130. package/src/client/sync/stream/WebsocketClientTransport.ts +82 -0
  131. package/src/client/sync/stream/core-instruction.ts +78 -0
  132. package/src/client/triggers/MemoryTriggerClaimManager.ts +25 -0
  133. package/src/client/triggers/TriggerManagerImpl.ts +538 -0
  134. package/src/client/watched/AbstractQueryProcessor.ts +231 -0
  135. package/src/client/watched/DifferentialQueryProcessor.ts +226 -0
  136. package/src/client/watched/OnChangeQueryProcessor.ts +108 -0
  137. package/src/client/watched/WatchedQuery.ts +14 -0
  138. package/src/constants.ts +6 -0
  139. package/src/db/ConnectionClosedError.ts +25 -0
  140. package/src/db/crud/SyncProgress.ts +39 -0
  141. package/src/db/crud/SyncStatus.ts +234 -0
  142. package/src/db/openDatabase.ts +23 -0
  143. package/src/index.ts +24 -0
  144. package/src/utils/AbortOperation.ts +19 -0
  145. package/src/utils/ControlledExecutor.ts +78 -0
  146. package/src/utils/MetaBaseObserver.ts +65 -0
  147. package/src/utils/async.ts +185 -0
  148. package/src/utils/compatibility.ts +9 -0
  149. package/src/utils/mutex.ts +186 -0
  150. package/src/utils/parseQuery.ts +31 -0
  151. package/src/utils/queue.ts +48 -0
  152. package/src/utils/stream_transform.ts +260 -0
  153. package/src/version.ts +3 -0
@@ -0,0 +1,538 @@
1
+ import type { BasePowerSyncDatabase } from '../BasePowerSyncDatabase.js';
2
+ import { DEFAULT_WATCH_THROTTLE_MS } from '../watched/WatchedQuery.js';
3
+ import {
4
+ CreateDiffTriggerOptions,
5
+ DiffTriggerOperation,
6
+ LockContext,
7
+ LogLevels,
8
+ Schema,
9
+ TrackDiffOptions,
10
+ TriggerManager,
11
+ TriggerRemoveCallback,
12
+ TriggerRemoveCallbackOptions,
13
+ WithDiffOptions
14
+ } from '@powersync/common';
15
+
16
+ /**
17
+ * @experimental
18
+ * @internal
19
+ */
20
+ export interface TriggerManagerConfig {
21
+ claimManager: TriggerClaimManager;
22
+ }
23
+
24
+ /**
25
+ * @experimental
26
+ * Manages claims on persisted SQLite triggers and destination tables to enable proper cleanup
27
+ * when they are no longer actively in use.
28
+ *
29
+ * When using persisted triggers (especially for OPFS multi-tab scenarios), we need a reliable way to determine which resources are still actively in use across different connections/tabs so stale resources can be safely cleaned up without interfering with active triggers.
30
+ *
31
+ * A cleanup process runs
32
+ * on database creation (and every 2 minutes) that:
33
+ * 1. Queries for existing managed persisted resources
34
+ * 2. Checks with the claim manager if any consumer is actively using those resources
35
+ * 3. Deletes unused resources
36
+ */
37
+
38
+ export interface TriggerClaimManager {
39
+ /**
40
+ * Obtains or marks a claim on a certain identifier.
41
+ * @returns a callback to release the claim.
42
+ */
43
+ obtainClaim: (identifier: string) => Promise<() => Promise<void>>;
44
+ /**
45
+ * Checks if a claim is present for an identifier.
46
+ */
47
+ checkClaim: (identifier: string) => Promise<boolean>;
48
+ }
49
+
50
+ export type TriggerManagerImplOptions = TriggerManagerConfig & {
51
+ db: BasePowerSyncDatabase;
52
+ schema: Schema;
53
+ };
54
+
55
+ export type TriggerManagerImplConfiguration = {
56
+ useStorageByDefault: boolean;
57
+ };
58
+
59
+ export const DEFAULT_TRIGGER_MANAGER_CONFIGURATION: TriggerManagerImplConfiguration = {
60
+ useStorageByDefault: false
61
+ };
62
+
63
+ /**
64
+ * A record of persisted table/trigger information.
65
+ * This is used for fail-safe cleanup.
66
+ */
67
+ type TrackedTableRecord = {
68
+ /**
69
+ * The id of the trigger. This is used in the SQLite trigger name
70
+ */
71
+ id: string;
72
+ /**
73
+ * The destination table name for the trigger
74
+ */
75
+ table: string;
76
+ /**
77
+ * Array of actual trigger names found for this table/id combo
78
+ */
79
+ triggerNames: string[];
80
+ };
81
+
82
+ const TRIGGER_CLEANUP_INTERVAL_MS = 120_000; // 2 minutes
83
+
84
+ /**
85
+ * @internal
86
+ * @experimental
87
+ */
88
+ export class TriggerManagerImpl implements TriggerManager {
89
+ protected schema: Schema;
90
+
91
+ protected defaultConfig: TriggerManagerImplConfiguration;
92
+ protected cleanupTimeout: ReturnType<typeof setTimeout> | null;
93
+ protected isDisposed: boolean;
94
+
95
+ constructor(protected options: TriggerManagerImplOptions) {
96
+ this.schema = options.schema;
97
+ options.db.registerListener({
98
+ schemaChanged: (schema) => {
99
+ this.schema = schema;
100
+ }
101
+ });
102
+ this.isDisposed = false;
103
+
104
+ /**
105
+ * Configure a cleanup to run on an interval.
106
+ * The interval is configured using setTimeout to take the async
107
+ * execution time of the callback into account.
108
+ */
109
+ this.defaultConfig = DEFAULT_TRIGGER_MANAGER_CONFIGURATION;
110
+ const cleanupCallback = async () => {
111
+ this.cleanupTimeout = null;
112
+ if (this.isDisposed) {
113
+ return;
114
+ }
115
+ try {
116
+ await this.cleanupResources();
117
+ } catch (error) {
118
+ this.db.logger.log({
119
+ level: LogLevels.error,
120
+ error,
121
+ message: `Caught error while attempting to cleanup triggers`
122
+ });
123
+ } finally {
124
+ // if not closed, set another timeout
125
+ if (this.isDisposed) {
126
+ return;
127
+ }
128
+ this.cleanupTimeout = setTimeout(cleanupCallback, TRIGGER_CLEANUP_INTERVAL_MS);
129
+ }
130
+ };
131
+ this.cleanupTimeout = setTimeout(cleanupCallback, TRIGGER_CLEANUP_INTERVAL_MS);
132
+ }
133
+
134
+ protected get db() {
135
+ return this.options.db;
136
+ }
137
+
138
+ protected async getUUID(ctx?: LockContext) {
139
+ const { id: uuid } = await (ctx ?? this.db).get<{ id: string }>(/* sql */ `
140
+ SELECT
141
+ uuid () as id
142
+ `);
143
+
144
+ // Replace dashes with underscores for SQLite table/trigger name compatibility
145
+ return uuid.replace(/-/g, '_');
146
+ }
147
+
148
+ protected async removeTriggers(tx: LockContext, triggerIds: string[]) {
149
+ for (const triggerId of triggerIds) {
150
+ await tx.execute(/* sql */ `DROP TRIGGER IF EXISTS ${triggerId}; `);
151
+ }
152
+ }
153
+
154
+ dispose() {
155
+ this.isDisposed = true;
156
+ if (this.cleanupTimeout) {
157
+ clearTimeout(this.cleanupTimeout);
158
+ }
159
+ }
160
+
161
+ /**
162
+ * Updates default config settings for platform specific use-cases.
163
+ */
164
+ updateDefaults(config: TriggerManagerImplConfiguration) {
165
+ this.defaultConfig = {
166
+ ...this.defaultConfig,
167
+ ...config
168
+ };
169
+ }
170
+
171
+ protected generateTriggerName(operation: DiffTriggerOperation, destinationTable: string, triggerId: string) {
172
+ return `__ps_temp_trigger_${operation.toLowerCase()}__${destinationTable}__${triggerId}`;
173
+ }
174
+
175
+ /**
176
+ * Cleanup any SQLite triggers or tables that are no longer in use.
177
+ */
178
+ async cleanupResources() {
179
+ // we use the database here since cleanupResources is called during the PowerSyncDatabase initialization
180
+ await this.db.database.writeLock(async (ctx) => {
181
+ /**
182
+ * Note: We only cleanup persisted triggers. These are tracked in the sqlite_master table.
183
+ * temporary triggers will not be affected by this.
184
+ * Query all triggers that match our naming pattern
185
+ */
186
+ const triggers = await ctx.getAll<{ name: string }>(/* sql */ `
187
+ SELECT
188
+ name
189
+ FROM
190
+ sqlite_master
191
+ WHERE
192
+ type = 'trigger'
193
+ AND name LIKE '__ps_temp_trigger_%'
194
+ `);
195
+
196
+ /** Use regex to extract table names and IDs from trigger names
197
+ * Trigger naming convention: __ps_temp_trigger_<operation>__<destination_table>__<id>
198
+ */
199
+ const triggerPattern = /^__ps_temp_trigger_(?:insert|update|delete)__(.+)__([a-f0-9_]{36})$/i;
200
+ const trackedItems = new Map<string, TrackedTableRecord>();
201
+
202
+ for (const trigger of triggers) {
203
+ const match = trigger.name.match(triggerPattern);
204
+ if (match) {
205
+ const [, table, id] = match;
206
+ // Collect all trigger names for each id combo
207
+ const existing = trackedItems.get(id);
208
+ if (existing) {
209
+ existing.triggerNames.push(trigger.name);
210
+ } else {
211
+ trackedItems.set(id, { table, id, triggerNames: [trigger.name] });
212
+ }
213
+ }
214
+ }
215
+
216
+ for (const trackedItem of trackedItems.values()) {
217
+ // check if there is anything holding on to this item
218
+ const hasClaim = await this.options.claimManager.checkClaim(trackedItem.id);
219
+ if (hasClaim) {
220
+ // This does not require cleanup
221
+ continue;
222
+ }
223
+
224
+ this.db.logger.log({
225
+ level: LogLevels.debug,
226
+ message: `Clearing resources for trigger ${trackedItem.id} with table ${trackedItem.table}`
227
+ });
228
+
229
+ // We need to delete the triggers and table
230
+ for (const triggerName of trackedItem.triggerNames) {
231
+ await ctx.execute(`DROP TRIGGER IF EXISTS ${triggerName}`);
232
+ }
233
+ await ctx.execute(`DROP TABLE IF EXISTS ${trackedItem.table}`);
234
+ }
235
+ });
236
+ }
237
+
238
+ async createDiffTrigger(options: CreateDiffTriggerOptions) {
239
+ await this.db.waitForReady();
240
+ const {
241
+ source,
242
+ destination,
243
+ columns,
244
+ when,
245
+ hooks,
246
+ setupContext,
247
+ // Fall back to the provided default if not given on this level
248
+ useStorage = this.defaultConfig.useStorageByDefault
249
+ } = options;
250
+ const operations = Object.keys(when) as DiffTriggerOperation[];
251
+ if (operations.length == 0) {
252
+ throw new Error('At least one WHEN operation must be specified for the trigger.');
253
+ }
254
+
255
+ /**
256
+ * The clause to use when executing
257
+ * CREATE ${tableTriggerTypeClause} TABLE
258
+ * OR
259
+ * CREATE ${tableTriggerTypeClause} TRIGGER
260
+ */
261
+ const tableTriggerTypeClause = !useStorage ? 'TEMP' : '';
262
+
263
+ const whenClauses = Object.fromEntries(
264
+ Object.entries(when).map(([operation, filter]) => [operation, `WHEN ${filter}`])
265
+ );
266
+
267
+ /**
268
+ * Allow specifying the View name as the source.
269
+ * We can lookup the internal table name from the schema.
270
+ */
271
+ const sourceDefinition = this.schema.tables.find((table) => table.viewName == source);
272
+ if (!sourceDefinition) {
273
+ throw new Error(`Source table or view "${source}" not found in the schema.`);
274
+ }
275
+
276
+ const replicatedColumns = columns ?? sourceDefinition.columns.map((col) => col.name);
277
+
278
+ const internalSource = sourceDefinition.internalName;
279
+ const triggerIds: string[] = [];
280
+
281
+ const id = await this.getUUID(setupContext);
282
+
283
+ const releaseStorageClaim = useStorage ? await this.options.claimManager.obtainClaim(id) : null;
284
+
285
+ /**
286
+ * We default to replicating all columns if no columns array is provided.
287
+ */
288
+ const jsonFragment = (source: 'NEW' | 'OLD' = 'NEW') => {
289
+ if (columns == null) {
290
+ // Track all columns
291
+ return `${source}.data`;
292
+ } else if (columns.length == 0) {
293
+ // Don't track any columns except for the id
294
+ return `'{}'`;
295
+ } else {
296
+ // Filter the data by the replicated columns
297
+ return `json_object(${replicatedColumns.map((col) => `'${col}', json_extract(${source}.data, '$.${col}')`).join(', ')})`;
298
+ }
299
+ };
300
+
301
+ const disposeWarningListener = this.db.registerListener({
302
+ schemaChanged: () => {
303
+ this.db.logger.log({
304
+ level: LogLevels.warn,
305
+ message: `The PowerSync schema has changed while previously configured triggers are still operational. This might cause unexpected results.`
306
+ });
307
+ }
308
+ });
309
+
310
+ /**
311
+ * Declare the cleanup function early since if any of the init steps fail,
312
+ * we need to ensure we can cleanup the created resources.
313
+ * We unfortunately cannot rely on transaction rollback.
314
+ */
315
+ const cleanup = async (options?: TriggerRemoveCallbackOptions) => {
316
+ const { context } = options ?? {};
317
+ disposeWarningListener();
318
+ const doCleanup = async (tx: LockContext) => {
319
+ await this.removeTriggers(tx, triggerIds);
320
+ await tx.execute(`DROP TABLE IF EXISTS ${destination};`);
321
+ await releaseStorageClaim?.();
322
+ };
323
+ if (context) {
324
+ await doCleanup(context);
325
+ } else {
326
+ await this.db.writeLock(doCleanup);
327
+ }
328
+ };
329
+
330
+ const setup = async (tx: LockContext) => {
331
+ // Allow user code to execute in this lock context before the trigger is created.
332
+ await hooks?.beforeCreate?.(tx);
333
+ await tx.execute(/* sql */ `
334
+ CREATE ${tableTriggerTypeClause} TABLE ${destination} (
335
+ operation_id INTEGER PRIMARY KEY AUTOINCREMENT,
336
+ id TEXT,
337
+ operation TEXT,
338
+ timestamp TEXT,
339
+ value TEXT,
340
+ previous_value TEXT
341
+ )
342
+ `);
343
+
344
+ if (operations.includes(DiffTriggerOperation.INSERT)) {
345
+ const insertTriggerId = this.generateTriggerName(DiffTriggerOperation.INSERT, destination, id);
346
+ triggerIds.push(insertTriggerId);
347
+
348
+ await tx.execute(/* sql */ `
349
+ CREATE ${tableTriggerTypeClause} TRIGGER ${insertTriggerId} AFTER INSERT ON ${internalSource} ${whenClauses[
350
+ DiffTriggerOperation.INSERT
351
+ ]} BEGIN
352
+ INSERT INTO
353
+ ${destination} (id, operation, timestamp, value)
354
+ VALUES
355
+ (
356
+ NEW.id,
357
+ 'INSERT',
358
+ strftime ('%Y-%m-%dT%H:%M:%fZ', 'now'),
359
+ ${jsonFragment('NEW')}
360
+ );
361
+
362
+ END
363
+ `);
364
+ }
365
+
366
+ if (operations.includes(DiffTriggerOperation.UPDATE)) {
367
+ const updateTriggerId = this.generateTriggerName(DiffTriggerOperation.UPDATE, destination, id);
368
+ triggerIds.push(updateTriggerId);
369
+
370
+ await tx.execute(/* sql */ `
371
+ CREATE ${tableTriggerTypeClause} TRIGGER ${updateTriggerId} AFTER
372
+ UPDATE ON ${internalSource} ${whenClauses[DiffTriggerOperation.UPDATE]} BEGIN
373
+ INSERT INTO
374
+ ${destination} (id, operation, timestamp, value, previous_value)
375
+ VALUES
376
+ (
377
+ NEW.id,
378
+ 'UPDATE',
379
+ strftime ('%Y-%m-%dT%H:%M:%fZ', 'now'),
380
+ ${jsonFragment('NEW')},
381
+ ${jsonFragment('OLD')}
382
+ );
383
+
384
+ END;
385
+ `);
386
+ }
387
+
388
+ if (operations.includes(DiffTriggerOperation.DELETE)) {
389
+ const deleteTriggerId = this.generateTriggerName(DiffTriggerOperation.DELETE, destination, id);
390
+ triggerIds.push(deleteTriggerId);
391
+
392
+ // Create delete trigger for basic JSON
393
+ await tx.execute(/* sql */ `
394
+ CREATE ${tableTriggerTypeClause} TRIGGER ${deleteTriggerId} AFTER DELETE ON ${internalSource} ${whenClauses[
395
+ DiffTriggerOperation.DELETE
396
+ ]} BEGIN
397
+ INSERT INTO
398
+ ${destination} (id, operation, timestamp, value)
399
+ VALUES
400
+ (
401
+ OLD.id,
402
+ 'DELETE',
403
+ strftime ('%Y-%m-%dT%H:%M:%fZ', 'now'),
404
+ ${jsonFragment('OLD')}
405
+ );
406
+
407
+ END;
408
+ `);
409
+ }
410
+ };
411
+
412
+ try {
413
+ if (setupContext) {
414
+ await setup(setupContext);
415
+ } else {
416
+ await this.db.writeLock(setup);
417
+ }
418
+ return cleanup;
419
+ } catch (error) {
420
+ try {
421
+ await cleanup(setupContext ? { context: setupContext } : undefined);
422
+ } catch (cleanupError) {
423
+ throw new AggregateError([error, cleanupError], 'Error during operation and cleanup');
424
+ }
425
+ throw error;
426
+ }
427
+ }
428
+
429
+ async trackTableDiff(options: TrackDiffOptions): Promise<TriggerRemoveCallback> {
430
+ const { source, when, columns, hooks, throttleMs = DEFAULT_WATCH_THROTTLE_MS } = options;
431
+
432
+ await this.db.waitForReady();
433
+
434
+ /**
435
+ * Allow specifying the View name as the source.
436
+ * We can lookup the internal table name from the schema.
437
+ */
438
+ const sourceDefinition = this.schema.tables.find((table) => table.viewName == source);
439
+ if (!sourceDefinition) {
440
+ throw new Error(`Source table or view "${source}" not found in the schema.`);
441
+ }
442
+
443
+ // The columns to present in the onChange context methods.
444
+ // If no array is provided, we use all columns from the source table.
445
+ const contextColumns = columns ?? sourceDefinition.columns.map((col) => col.name);
446
+
447
+ const id = await this.getUUID();
448
+ const destination = `__ps_temp_track_${source}_${id}`;
449
+
450
+ // register an onChange before the trigger is created
451
+ const abortController = new AbortController();
452
+ const abortOnChange = () => abortController.abort();
453
+ this.db.onChange(
454
+ {
455
+ // Note that the onChange events here have their execution scheduled.
456
+ // Callbacks are throttled and are sequential.
457
+ onChange: async () => {
458
+ if (abortController.signal.aborted) return;
459
+
460
+ // Run the handler in a write lock to keep the state of the
461
+ // destination table consistent.
462
+ await this.db.writeTransaction(async (tx) => {
463
+ const callbackResult = await options.onChange({
464
+ context: tx,
465
+ destinationTable: destination,
466
+ withDiff: async <T>(query: string, params: any, options?: WithDiffOptions) => {
467
+ // Wrap the query to expose the destination table
468
+ const operationIdSelect = options?.castOperationIdAsText
469
+ ? 'id, operation, CAST(operation_id AS TEXT) as operation_id, timestamp, value, previous_value'
470
+ : '*';
471
+ const wrappedQuery = /* sql */ `
472
+ WITH
473
+ DIFF AS (
474
+ SELECT
475
+ ${operationIdSelect}
476
+ FROM
477
+ ${destination}
478
+ ORDER BY
479
+ operation_id ASC
480
+ ) ${query}
481
+ `;
482
+ return tx.getAll<T>(wrappedQuery, params);
483
+ },
484
+ withExtractedDiff: async <T>(query: string, params: any) => {
485
+ // Wrap the query to expose the destination table
486
+ const wrappedQuery = /* sql */ `
487
+ WITH
488
+ DIFF AS (
489
+ SELECT
490
+ id,
491
+ ${contextColumns.length > 0
492
+ ? `${contextColumns.map((col) => `json_extract(value, '$.${col}') as ${col}`).join(', ')},`
493
+ : ''} operation_id as __operation_id,
494
+ operation as __operation,
495
+ timestamp as __timestamp,
496
+ previous_value as __previous_value
497
+ FROM
498
+ ${destination}
499
+ ORDER BY
500
+ __operation_id ASC
501
+ ) ${query}
502
+ `;
503
+ return tx.getAll<T>(wrappedQuery, params);
504
+ }
505
+ });
506
+
507
+ // Clear the destination table after processing
508
+ await tx.execute(/* sql */ `DELETE FROM ${destination};`);
509
+ return callbackResult;
510
+ });
511
+ }
512
+ },
513
+ { tables: [destination], signal: abortController.signal, throttleMs }
514
+ );
515
+
516
+ try {
517
+ const removeTrigger = await this.createDiffTrigger({
518
+ source,
519
+ destination,
520
+ columns: contextColumns,
521
+ when,
522
+ hooks
523
+ });
524
+
525
+ return async () => {
526
+ abortOnChange();
527
+ await removeTrigger();
528
+ };
529
+ } catch (error) {
530
+ try {
531
+ abortOnChange();
532
+ } catch (cleanupError) {
533
+ throw new AggregateError([error, cleanupError], 'Error during operation and cleanup');
534
+ }
535
+ throw error;
536
+ }
537
+ }
538
+ }