@powersync/common 0.0.0-dev-20260503073249 → 0.0.0-dev-20260630141119

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