Open History to see the last commit
1import { LogLevels, sanitizeSQL } from '@powersync/common'
2import { LoadSubsetOperationAbortedError } from '@tanstack/db'
3import DebugModule from 'debug'
4import { PendingOperationStore } from './PendingOperationStore'
5import { asPowerSyncRecord, mapOperationToPowerSync } from './helpers'
6import type { CommonPowerSyncDatabase, LockContext } from '@powersync/common'
7import type { PendingMutation, Transaction } from '@tanstack/db'
8import type { PendingOperation } from './PendingOperationStore'
9import type {
10 EnhancedPowerSyncCollectionConfig,
11 PowerSyncCollectionMeta,
12} from './definitions'
13
14const debug = DebugModule.debug(`ts/db:powersync`)
15
16export type TransactorOptions = {
17 database: CommonPowerSyncDatabase
18}
19
20/**
21 * Applies mutations to the PowerSync database. This method is called automatically by the collection's
22 * insert, update, and delete operations. You typically don't need to call this directly unless you
23 * have special transaction requirements.
24 *
25 * @example
26 * ```typescript
27 * // Create a collection
28 * const collection = createCollection(
29 * powerSyncCollectionOptions<Document>({
30 * database: db,
31 * table: APP_SCHEMA.props.documents,
32 * })
33 * )
34 *
35 * const addTx = createTransaction({
36 * autoCommit: false,
37 * mutationFn: async ({ transaction }) => {
38 * await new PowerSyncTransactor({ database: db }).applyTransaction(transaction)
39 * },
40 * })
41 *
42 * addTx.mutate(() => {
43 * for (let i = 0; i < 5; i++) {
44 * collection.insert({ id: randomUUID(), name: `tx-${i}` })
45 * }
46 * })
47 *
48 * await addTx.commit()
49 * await addTx.isPersisted.promise
50 * ```
51 *
52 * @param transaction - The transaction containing mutations to apply
53 * @returns A promise that resolves when the mutations have been persisted to PowerSync
54 */
55export class PowerSyncTransactor {
56 database: CommonPowerSyncDatabase
57 pendingOperationStore: PendingOperationStore
58
59 constructor(options: TransactorOptions) {
60 this.database = options.database
61 this.pendingOperationStore = PendingOperationStore.GLOBAL
62 }
63
64 /**
65 * Persists a {@link Transaction} to the PowerSync SQLite database.
66 */
67 async applyTransaction(transaction: Transaction<any>) {
68 const { mutations } = transaction
69
70 if (mutations.length == 0) {
71 return
72 }
73 /**
74 * The transaction might contain operations for different collections.
75 * We can do some optimizations for single-collection transactions.
76 */
77 const collectionsById = new Map<
78 string,
79 PendingMutation<any>[`collection`]
80 >()
81 const lastCollectionMutationIndexes = new Map<string, number>()
82 for (const [index, mutation] of mutations.entries()) {
83 const collectionId = mutation.collection.id
84 if (!collectionsById.has(collectionId)) {
85 collectionsById.set(collectionId, mutation.collection)
86 }
87 const changesDatabase =
88 mutation.type != `update` ||
89 Object.keys(mutation.changes).some((key) => key != `id`) ||
90 (typeof mutation.metadata != `undefined` &&
91 this.getMutationCollectionMeta(mutation).metadataIsTracked)
92 if (changesDatabase) {
93 lastCollectionMutationIndexes.set(collectionId, index)
94 }
95 }
96
97 // Check all the observers are ready before taking a lock
98 await Promise.all(
99 Array.from(collectionsById.values()).map(async (collection) => {
100 if (collection.isReady()) {
101 return
102 }
103 // Observe this session without starting new demand from mutationFn.
104 // Cleanup and startup failure must settle the wait before taking a lock.
105 await new Promise<void>((resolve, reject) => {
106 const check = () => {
107 if (collection.isReady()) {
108 unsubscribe()
109 resolve()
110 } else if (
111 collection.status === `error` ||
112 collection.status === `cleaned-up`
113 ) {
114 unsubscribe()
115 reject(
116 collection.status === `error`
117 ? (collection._lifecycle.getSyncError() ??
118 new Error(`Collection failed before readiness`))
119 : new LoadSubsetOperationAbortedError(),
120 )
121 }
122 }
123 const unsubscribe = collection.on(`status:change`, check)
124 check()
125 })
126 }),
127 )
128
129 // Persist to PowerSync
130 const { whenComplete } = await this.database.writeTransaction(
131 async (tx) => {
132 const pendingOperations: Array<PendingOperation | null> = []
133
134 for (const [index, mutation] of mutations.entries()) {
135 /**
136 * Each collection processes events independently. We need to make sure the
137 * last operation for each collection has been observed.
138 */
139 const shouldWait =
140 index == lastCollectionMutationIndexes.get(mutation.collection.id)
141 switch (mutation.type) {
142 case `insert`:
143 pendingOperations.push(
144 await this.handleInsert(mutation, tx, shouldWait),
145 )
146 break
147 case `update`:
148 pendingOperations.push(
149 await this.handleUpdate(mutation, tx, shouldWait),
150 )
151 break
152 case `delete`:
153 pendingOperations.push(
154 await this.handleDelete(mutation, tx, shouldWait),
155 )
156 break
157 }
158 }
159
160 /**
161 * Return a promise from the writeTransaction, without awaiting it.
162 * This promise will resolve once the entire transaction has been
163 * observed via the diff triggers.
164 * We return without awaiting in order to free the write lock.
165 */
166 return {
167 whenComplete: Promise.all(
168 pendingOperations
169 .filter((op) => !!op)
170 .map((op) => this.pendingOperationStore.waitFor(op)),
171 ),
172 }
173 },
174 )
175
176 // Wait for the change to be observed via the diff trigger
177 await whenComplete
178 }
179
180 protected async handleInsert(
181 mutation: PendingMutation<any>,
182 context: LockContext,
183 waitForCompletion: boolean = false,
184 ): Promise<PendingOperation | null> {
185 debug(`insert`, mutation)
186
187 return this.handleOperationWithCompletion(
188 mutation,
189 context,
190 waitForCompletion,
191 // eslint-disable-next-line no-shadow
192 async (tableName, mutation, serializeValue) => {
193 const values = serializeValue(mutation.modified)
194 const keys = Object.keys(values).map((key) => sanitizeSQL`${key}`)
195 const queryParameters = Object.values(values)
196
197 const metadataValue = this.processMutationMetadata(mutation)
198 if (metadataValue != null) {
199 keys.push(`_metadata`)
200 queryParameters.push(metadataValue)
201 }
202
203 await context.execute(
204 `
205 INSERT into ${tableName}
206 (${keys.join(`, `)})
207 VALUES
208 (${keys.map((_) => `?`).join(`, `)})
209 `,
210 queryParameters,
211 )
212 },
213 )
214 }
215
216 protected async handleUpdate(
217 mutation: PendingMutation<any>,
218 context: LockContext,
219 waitForCompletion: boolean = false,
220 ): Promise<PendingOperation | null> {
221 debug(`update`, mutation)
222
223 return this.handleOperationWithCompletion(
224 mutation,
225 context,
226 waitForCompletion,
227 // eslint-disable-next-line no-shadow
228 async (tableName, mutation, serializeValue) => {
229 const { id: _id, ...changes } = mutation.changes
230 const values = serializeValue(changes)
231 const keys = Object.keys(values).map((key) => sanitizeSQL`${key}`)
232 const queryParameters = Object.values(values)
233
234 const metadataValue = this.processMutationMetadata(mutation)
235 if (metadataValue != null) {
236 keys.push(`_metadata`)
237 queryParameters.push(metadataValue)
238 }
239
240 if (keys.length == 0) {
241 return false
242 }
243
244 await context.execute(
245 `
246 UPDATE ${tableName}
247 SET ${keys.map((key) => `${key} = ?`).join(`, `)}
248 WHERE id = ?
249 `,
250 [...queryParameters, asPowerSyncRecord(mutation.original).id],
251 )
252
253 return
254 },
255 )
256 }
257
258 protected async handleDelete(
259 mutation: PendingMutation<any>,
260 context: LockContext,
261 waitForCompletion: boolean = false,
262 ): Promise<PendingOperation | null> {
263 debug(`update`, mutation)
264
265 return this.handleOperationWithCompletion(
266 mutation,
267 context,
268 waitForCompletion,
269 // eslint-disable-next-line no-shadow
270 async (tableName, mutation) => {
271 const metadataValue = this.processMutationMetadata(mutation)
272 if (metadataValue != null) {
273 /**
274 * Delete operations with metadata require a different approach to handle metadata.
275 * This will delete the record.
276 */
277 await context.execute(
278 `
279 UPDATE ${tableName} SET _deleted = TRUE, _metadata = ? WHERE id = ?
280 `,
281 [metadataValue, asPowerSyncRecord(mutation.original).id],
282 )
283 } else {
284 await context.execute(
285 `
286 DELETE FROM ${tableName} WHERE id = ?
287 `,
288 [asPowerSyncRecord(mutation.original).id],
289 )
290 }
291 },
292 )
293 }
294
295 /**
296 * Helper function which wraps a persistence operation by:
297 * - Fetching the mutation's collection's SQLite table details
298 * - Executing the mutation
299 * - Returning the last pending diff operation if required
300 */
301 protected async handleOperationWithCompletion(
302 mutation: PendingMutation<any>,
303 context: LockContext,
304 waitForCompletion: boolean,
305 handler: (
306 tableName: string,
307 mutation: PendingMutation<any>,
308 serializeValue: (value: any) => Record<string, unknown>,
309 ) => Promise<void | false>,
310 ): Promise<PendingOperation | null> {
311 const { tableName, trackedTableName, serializeValue } =
312 this.getMutationCollectionMeta(mutation)
313
314 const executed = await handler(
315 sanitizeSQL`${tableName}`,
316 mutation,
317 serializeValue,
318 )
319
320 if (executed === false) {
321 return null
322 }
323
324 if (!waitForCompletion) {
325 return null
326 }
327
328 // Need to get the operation in order to wait for it
329 const diffOperation = await context.get<{ id: string; timestamp: string }>(
330 sanitizeSQL`SELECT id, timestamp FROM ${trackedTableName} ORDER BY operation_id DESC LIMIT 1`,
331 )
332 return {
333 tableName,
334 id: diffOperation.id,
335 operation: mapOperationToPowerSync(mutation.type),
336 timestamp: diffOperation.timestamp,
337 }
338 }
339
340 protected getMutationCollectionMeta(
341 mutation: PendingMutation<any>,
342 ): PowerSyncCollectionMeta<any> {
343 if (
344 typeof (mutation.collection.config as any).utils?.getMeta != `function`
345 ) {
346 throw new Error(`Collection is not a PowerSync collection.`)
347 }
348 return (
349 mutation.collection
350 .config as unknown as EnhancedPowerSyncCollectionConfig<any>
351 ).utils.getMeta()
352 }
353
354 /**
355 * Processes collection mutation metadata for persistence to the database.
356 * We only support storing string metadata.
357 * @returns null if no metadata should be stored.
358 */
359 protected processMutationMetadata(
360 mutation: PendingMutation<any>,
361 ): string | null {
362 const { metadataIsTracked } = this.getMutationCollectionMeta(mutation)
363 if (!metadataIsTracked) {
364 // If it's not supported, we don't store metadata.
365 if (typeof mutation.metadata != `undefined`) {
366 // Log a warning if metadata is provided but not tracked.
367 this.database.logger.log({
368 level: LogLevels.warn,
369 message: `Metadata provided for collection ${mutation.collection.id} but the PowerSync table does not track metadata. The PowerSync table should be configured with trackMetadata: true.`,
370 error: mutation.metadata,
371 })
372 }
373 return null
374 } else if (typeof mutation.metadata == `undefined`) {
375 return null
376 } else if (typeof mutation.metadata == `string`) {
377 return mutation.metadata
378 } else {
379 return JSON.stringify(mutation.metadata)
380 }
381 }
382}