Open History to see the last commit
1import { InvalidPersistedCollectionConfigError } from '@tanstack/db-sqlite-persistence-core'
2import type { SQLiteDriver } from '@tanstack/db-sqlite-persistence-core'
3
4type OpSQLiteExecuteFn = (
5 sql: string,
6 params?: ReadonlyArray<unknown>,
7) => unknown | Promise<unknown>
8
9type OpSQLiteRowListLike = {
10 length?: unknown
11 item?: unknown
12 _array?: unknown
13}
14
15const WRITE_RESULT_KEYS = new Set([
16 `rowsAffected`,
17 `changes`,
18 `insertId`,
19 `lastInsertRowId`,
20])
21
22const STATEMENT_RESULT_KEYS = new Set([
23 ...WRITE_RESULT_KEYS,
24 `rows`,
25 `resultRows`,
26 `rawRows`,
27 `columnNames`,
28 `results`,
29 `metadata`,
30])
31
32export type OpSQLiteDatabaseLike = {
33 execute?: OpSQLiteExecuteFn
34 executeAsync?: OpSQLiteExecuteFn
35 executeRaw?: OpSQLiteExecuteFn
36 execAsync?: OpSQLiteExecuteFn
37 close?: () => Promise<void> | void
38}
39
40export type OpSQLiteArrayResultMode = `rows` | `statement-results`
41
42type OpSQLiteResultOptions = {
43 /**
44 * Declares how to interpret a bare array when its first entry could be either
45 * a data row or a statement-result envelope. Published op-sqlite methods
46 * return object envelopes and do not need this option.
47 */
48 arrayResultMode?: OpSQLiteArrayResultMode
49}
50
51type OpSQLiteExistingDatabaseOptions = OpSQLiteResultOptions & {
52 database: OpSQLiteDatabaseLike
53}
54
55type OpSQLiteOpenDatabaseOptions = OpSQLiteResultOptions & {
56 openDatabase: () => OpSQLiteDatabaseLike
57}
58
59export type OpSQLiteDriverOptions =
60 | OpSQLiteExistingDatabaseOptions
61 | OpSQLiteOpenDatabaseOptions
62
63type TransactionContextStore = {
64 transactionDriver: SQLiteDriver
65}
66
67type AsyncLocalStorageLike<TStore> = {
68 getStore: () => TStore | undefined
69 run: <TResult>(store: TStore, callback: () => TResult) => TResult
70}
71
72type AsyncLocalStorageCtor = new <TStore>() => AsyncLocalStorageLike<TStore>
73
74type DatabaseExecutionState = {
75 queue: Promise<void>
76 nextSavepointId: number
77 transactionContextStoragePromise: Promise<AsyncLocalStorageLike<TransactionContextStore> | null> | null
78}
79
80const databaseExecutionStates = new WeakMap<
81 OpSQLiteDatabaseLike,
82 DatabaseExecutionState
83>()
84
85function getDatabaseExecutionState(
86 database: OpSQLiteDatabaseLike,
87): DatabaseExecutionState {
88 const existing = databaseExecutionStates.get(database)
89 if (existing) {
90 return existing
91 }
92
93 const state: DatabaseExecutionState = {
94 queue: Promise.resolve(),
95 nextSavepointId: 1,
96 transactionContextStoragePromise: null,
97 }
98 databaseExecutionStates.set(database, state)
99 return state
100}
101
102let asyncLocalStorageCtorPromise: Promise<AsyncLocalStorageCtor | null> | null =
103 null
104
105function canAttemptNodeAsyncLocalStorageLoad(): boolean {
106 if (typeof process === `undefined`) {
107 return false
108 }
109 // In React Native, process is polyfilled but process.versions may not exist
110 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
111 return typeof process.versions?.node === `string`
112}
113
114function getNodeAsyncHooksSpecifier(): string {
115 const moduleName = `async_hooks`
116 return `node:${moduleName}`
117}
118
119async function resolveAsyncLocalStorageCtor(): Promise<AsyncLocalStorageCtor | null> {
120 if (asyncLocalStorageCtorPromise) {
121 return asyncLocalStorageCtorPromise
122 }
123
124 asyncLocalStorageCtorPromise = (async () => {
125 if (!canAttemptNodeAsyncLocalStorageLoad()) {
126 return null
127 }
128
129 try {
130 // Use Function constructor to hide the dynamic import from React Native
131 // bundlers — Metro rejects non-literal dynamic import() at transform time.
132 // On React Native this code path is never reached (guarded above).
133 const importFn = new Function(`s`, `return import(s)`) as (
134 specifier: string,
135 ) => Promise<{
136 AsyncLocalStorage?: AsyncLocalStorageCtor
137 }>
138 const asyncHooksModule = await importFn(getNodeAsyncHooksSpecifier())
139
140 return typeof asyncHooksModule.AsyncLocalStorage === `function`
141 ? asyncHooksModule.AsyncLocalStorage
142 : null
143 } catch {
144 return null
145 }
146 })()
147
148 return asyncLocalStorageCtorPromise
149}
150
151function isObjectRecord(value: unknown): value is Record<string, unknown> {
152 return typeof value === `object` && value !== null
153}
154
155function hasOwnKey(value: Record<string, unknown>, key: string): boolean {
156 return Object.prototype.hasOwnProperty.call(value, key)
157}
158
159function rejectInheritedCarrierKeys(
160 value: Record<string, unknown>,
161 sql: string,
162): void {
163 for (const key of [
164 `rows`,
165 `resultRows`,
166 `rawRows`,
167 `columnNames`,
168 `results`,
169 ]) {
170 if (!hasOwnKey(value, key) && key in value) {
171 unsupportedQueryResult(sql, `inherited ${key} carrier`)
172 }
173 }
174}
175
176function hasWriteResultMarker(value: Record<string, unknown>): boolean {
177 for (const key of WRITE_RESULT_KEYS) {
178 if (hasOwnKey(value, key)) {
179 return true
180 }
181 }
182 return false
183}
184
185function isWriteResultEnvelope(value: Record<string, unknown>): boolean {
186 return (
187 hasWriteResultMarker(value) &&
188 Object.keys(value).every((key) => WRITE_RESULT_KEYS.has(key))
189 )
190}
191
192function unsupportedQueryResult(sql: string, details?: string): never {
193 throw new InvalidPersistedCollectionConfigError(
194 `Unsupported op-sqlite query result shape for SQL "${sql}"${
195 details ? `: ${details}` : ``
196 }`,
197 )
198}
199
200function isValidRowList(
201 rowsObject: OpSQLiteRowListLike,
202): rowsObject is OpSQLiteRowListLike & {
203 length: number
204 item: (index: number) => unknown
205} {
206 return (
207 typeof rowsObject.length === `number` &&
208 Number.isSafeInteger(rowsObject.length) &&
209 rowsObject.length >= 0 &&
210 typeof rowsObject.item === `function`
211 )
212}
213
214function toRowArray(rowsValue: unknown): Array<unknown> | null {
215 if (Array.isArray(rowsValue)) {
216 return rowsValue
217 }
218
219 if (!isObjectRecord(rowsValue)) {
220 return null
221 }
222
223 const rowsObject = rowsValue as OpSQLiteRowListLike
224 if (Array.isArray(rowsObject._array)) {
225 return rowsObject._array
226 }
227
228 if (isValidRowList(rowsObject)) {
229 const rows: Array<unknown> = []
230 for (let index = 0; index < rowsObject.length; index++) {
231 rows.push(rowsObject.item(index))
232 }
233 return rows
234 }
235
236 return null
237}
238
239function isRowCarrier(rowsValue: unknown): boolean {
240 if (Array.isArray(rowsValue)) {
241 return true
242 }
243
244 if (!isObjectRecord(rowsValue)) {
245 return false
246 }
247
248 const rowsObject = rowsValue as OpSQLiteRowListLike
249 return Array.isArray(rowsObject._array) || isValidRowList(rowsObject)
250}
251
252function isStatementResultEnvelope(value: Record<string, unknown>): boolean {
253 if (!Object.keys(value).every((key) => STATEMENT_RESULT_KEYS.has(key))) {
254 return false
255 }
256
257 // Bare arrays are also a supported row carrier. A legitimate row can contain
258 // only write-marker aliases, so markers alone cannot prove that an array is a
259 // statement wrapper; wrappers need an actual row structure.
260 const hasRowCarrier =
261 isRowCarrier(value.rows) ||
262 isRowCarrier(value.resultRows) ||
263 Array.isArray(value.results)
264 const hasStructuralCarrier =
265 hasRowCarrier ||
266 Array.isArray(value.rawRows) ||
267 Array.isArray(value.columnNames)
268
269 return (
270 hasRowCarrier ||
271 (hasWriteResultMarker(value) && hasStructuralCarrier) ||
272 (Array.isArray(value.rawRows) && Array.isArray(value.columnNames))
273 )
274}
275
276function decodeColumnarRows(
277 value: Record<string, unknown>,
278 sql: string,
279): Array<Record<string, unknown>> | null {
280 const hasRawRows = hasOwnKey(value, `rawRows`)
281 const hasColumnNames = hasOwnKey(value, `columnNames`)
282 if (!hasRawRows && !hasColumnNames) {
283 return null
284 }
285
286 if (!hasRawRows || !hasColumnNames) {
287 unsupportedQueryResult(
288 sql,
289 `columnar results require both rawRows and columnNames`,
290 )
291 }
292 const rawRows = value.rawRows
293 const columnNames = value.columnNames
294 if (
295 !Array.isArray(rawRows) ||
296 !Array.isArray(columnNames) ||
297 !columnNames.every((columnName) => typeof columnName === `string`)
298 ) {
299 unsupportedQueryResult(sql, `invalid columnar row or column metadata`)
300 }
301
302 if (rawRows.length > 0 && columnNames.length === 0) {
303 unsupportedQueryResult(
304 sql,
305 `nonempty columnar results require at least one column name`,
306 )
307 }
308
309 return rawRows.map((rawRow) => {
310 if (!Array.isArray(rawRow) || rawRow.length !== columnNames.length) {
311 unsupportedQueryResult(
312 sql,
313 `columnar row width does not match columnNames`,
314 )
315 }
316
317 const row: Record<string, unknown> = {}
318 for (let index = 0; index < columnNames.length; index++) {
319 const columnName = columnNames[index]!
320 if (columnName === `__proto__`) {
321 Object.defineProperty(row, columnName, {
322 configurable: true,
323 enumerable: true,
324 value: rawRow[index],
325 writable: true,
326 })
327 } else {
328 row[columnName] = rawRow[index]
329 }
330 }
331 return row
332 })
333}
334
335function rejectPositionalRows(
336 rows: Array<unknown>,
337 sql: string,
338): Array<unknown> {
339 if (rows.some((row) => Array.isArray(row))) {
340 unsupportedQueryResult(sql, `positional rows require column metadata`)
341 }
342 return rows
343}
344
345function extractRowsFromStatementResult(
346 record: Record<string, unknown>,
347 sql: string,
348 allowResultsWrapper: boolean,
349): Array<unknown> {
350 rejectInheritedCarrierKeys(record, sql)
351 const rowCarrierKeys = [`rows`, `resultRows`].filter((key) =>
352 hasOwnKey(record, key),
353 )
354 const rowCarrierKey = rowCarrierKeys[0]
355 if (
356 rowCarrierKeys.length > 1 ||
357 (rowCarrierKeys.length > 0 &&
358 (hasOwnKey(record, `results`) ||
359 (rowCarrierKey === `resultRows` && hasOwnKey(record, `rawRows`))))
360 ) {
361 unsupportedQueryResult(sql, `query result contains conflicting carriers`)
362 }
363
364 if (rowCarrierKeys.length === 1) {
365 const rows = toRowArray(record[rowCarrierKey!])
366 if (!rows) {
367 unsupportedQueryResult(sql, `invalid ${rowCarrierKey} carrier`)
368 }
369 return rejectPositionalRows(rows, sql)
370 }
371
372 if (
373 (hasOwnKey(record, `rawRows`) || hasOwnKey(record, `columnNames`)) &&
374 hasOwnKey(record, `results`)
375 ) {
376 unsupportedQueryResult(sql, `query result contains conflicting carriers`)
377 }
378
379 const columnarRows = decodeColumnarRows(record, sql)
380 if (columnarRows) {
381 return columnarRows
382 }
383
384 if (hasOwnKey(record, `results`)) {
385 if (!allowResultsWrapper) {
386 unsupportedQueryResult(sql, `unsupported nested results depth`)
387 }
388 const nestedResults = record.results
389 if (
390 !Array.isArray(nestedResults) ||
391 nestedResults.length !== 1 ||
392 !isObjectRecord(nestedResults[0])
393 ) {
394 unsupportedQueryResult(sql, `invalid nested results carrier`)
395 }
396 return extractRowsFromStatementResult(nestedResults[0], sql, false)
397 }
398
399 if (isWriteResultEnvelope(record)) {
400 return []
401 }
402
403 return unsupportedQueryResult(sql)
404}
405
406function extractRowsFromExecuteResult(
407 result: unknown,
408 sql: string,
409 arrayResultMode?: OpSQLiteArrayResultMode,
410): Array<unknown> {
411 if (result == null) {
412 return unsupportedQueryResult(sql)
413 }
414
415 if (Array.isArray(result)) {
416 if (result.length === 0) {
417 if (arrayResultMode === `statement-results`) {
418 return unsupportedQueryResult(
419 sql,
420 `statement-result arrays must contain exactly one result`,
421 )
422 }
423 return []
424 }
425
426 if (arrayResultMode === `rows`) {
427 return rejectPositionalRows(result, sql)
428 }
429
430 const firstEntry = result[0]
431 const isStructuralStatementResult =
432 isObjectRecord(firstEntry) && isStatementResultEnvelope(firstEntry)
433 if (arrayResultMode === `statement-results`) {
434 if (!isObjectRecord(firstEntry)) {
435 return unsupportedQueryResult(
436 sql,
437 `statement-results mode requires an object statement envelope`,
438 )
439 }
440 if (result.length !== 1) {
441 return unsupportedQueryResult(
442 sql,
443 `statement-result arrays must contain exactly one result`,
444 )
445 }
446 return extractRowsFromStatementResult(firstEntry, sql, false)
447 }
448
449 if (isStructuralStatementResult) {
450 return unsupportedQueryResult(
451 sql,
452 `ambiguous bare result array; set arrayResultMode to "rows" or "statement-results"`,
453 )
454 }
455
456 return rejectPositionalRows(result, sql)
457 }
458
459 if (isObjectRecord(result)) {
460 return extractRowsFromStatementResult(result, sql, true)
461 }
462
463 return unsupportedQueryResult(sql)
464}
465
466function hasExistingDatabase(
467 options: OpSQLiteDriverOptions,
468): options is OpSQLiteExistingDatabaseOptions {
469 return `database` in options
470}
471
472function assertTransactionCallbackHasDriverArg(
473 fn: (transactionDriver: SQLiteDriver) => Promise<unknown>,
474): void {
475 if (fn.length > 0) {
476 return
477 }
478
479 throw new InvalidPersistedCollectionConfigError(
480 `SQLiteDriver.transaction callback must accept the transaction driver argument`,
481 )
482}
483
484function resolveExecuteMethod(
485 database: OpSQLiteDatabaseLike,
486): OpSQLiteExecuteFn {
487 const executeCandidates: Array<unknown> = [
488 database.executeAsync,
489 database.execute,
490 database.executeRaw,
491 database.execAsync,
492 ]
493 const executeMethod = executeCandidates.find(
494 (candidate) => typeof candidate === `function`,
495 )
496
497 if (typeof executeMethod !== `function`) {
498 throw new InvalidPersistedCollectionConfigError(
499 `op-sqlite database object must provide execute/executeAsync/executeRaw/execAsync`,
500 )
501 }
502
503 return executeMethod as OpSQLiteExecuteFn
504}
505
506export class OpSQLiteDriver implements SQLiteDriver {
507 private readonly database: OpSQLiteDatabaseLike
508 private readonly executeMethod: OpSQLiteExecuteFn
509 private readonly arrayResultMode: OpSQLiteArrayResultMode | undefined
510 private readonly ownsDatabase: boolean
511 private readonly executionState: DatabaseExecutionState
512
513 constructor(options: OpSQLiteDriverOptions) {
514 if (hasExistingDatabase(options)) {
515 this.database = options.database
516 this.ownsDatabase = false
517 } else {
518 this.database = options.openDatabase()
519 this.ownsDatabase = true
520 }
521
522 this.executeMethod = resolveExecuteMethod(this.database)
523 this.arrayResultMode = options.arrayResultMode
524 this.executionState = getDatabaseExecutionState(this.database)
525 }
526
527 async exec(sql: string): Promise<void> {
528 const activeTransactionDriver = await this.getActiveTransactionDriver()
529 if (activeTransactionDriver) {
530 await activeTransactionDriver.exec(sql)
531 return
532 }
533
534 await this.enqueue(async () => {
535 await this.execute(sql)
536 })
537 }
538
539 async query<T>(
540 sql: string,
541 params: ReadonlyArray<unknown> = [],
542 ): Promise<ReadonlyArray<T>> {
543 const activeTransactionDriver = await this.getActiveTransactionDriver()
544 if (activeTransactionDriver) {
545 return activeTransactionDriver.query<T>(sql, params)
546 }
547
548 return this.enqueue(async () => {
549 const result = await this.execute(sql, params)
550 return extractRowsFromExecuteResult(
551 result,
552 sql,
553 this.arrayResultMode,
554 ) as ReadonlyArray<T>
555 })
556 }
557
558 async run(sql: string, params: ReadonlyArray<unknown> = []): Promise<void> {
559 const activeTransactionDriver = await this.getActiveTransactionDriver()
560 if (activeTransactionDriver) {
561 await activeTransactionDriver.run(sql, params)
562 return
563 }
564
565 await this.enqueue(async () => {
566 await this.execute(sql, params)
567 })
568 }
569
570 async transaction<T>(
571 fn: (transactionDriver: SQLiteDriver) => Promise<T>,
572 ): Promise<T> {
573 assertTransactionCallbackHasDriverArg(fn)
574
575 const activeTransactionDriver = await this.getActiveTransactionDriver()
576 if (activeTransactionDriver) {
577 return activeTransactionDriver.transaction(fn)
578 }
579
580 return this.transactionWithDriver((transactionDriver) =>
581 fn(transactionDriver),
582 )
583 }
584
585 async transactionWithDriver<T>(
586 fn: (transactionDriver: SQLiteDriver) => Promise<T>,
587 ): Promise<T> {
588 const activeTransactionDriver = await this.getActiveTransactionDriver()
589 if (
590 activeTransactionDriver &&
591 typeof activeTransactionDriver.transactionWithDriver === `function`
592 ) {
593 return activeTransactionDriver.transactionWithDriver(fn)
594 }
595
596 return this.enqueue(async () => {
597 await this.execute(`BEGIN IMMEDIATE`)
598 const transactionDriver = this.createTransactionDriver()
599 try {
600 const result = await this.runWithTransactionContext(
601 transactionDriver,
602 async () => fn(transactionDriver),
603 )
604 await this.execute(`COMMIT`)
605 return result
606 } catch (error) {
607 try {
608 await this.execute(`ROLLBACK`)
609 } catch {
610 // Keep the original transaction failure as the primary error.
611 }
612 throw error
613 }
614 })
615 }
616
617 async close(): Promise<void> {
618 if (!this.ownsDatabase || typeof this.database.close !== `function`) {
619 return
620 }
621
622 await Promise.resolve(this.database.close())
623 }
624
625 getDatabase(): OpSQLiteDatabaseLike {
626 return this.database
627 }
628
629 private async execute(
630 sql: string,
631 params: ReadonlyArray<unknown> = [],
632 ): Promise<unknown> {
633 const normalizedParams =
634 params.length > 0
635 ? [...params]
636 : (undefined as ReadonlyArray<unknown> | undefined)
637 const result = this.executeMethod.call(this.database, sql, normalizedParams)
638 return Promise.resolve(result)
639 }
640
641 private enqueue<T>(operation: () => Promise<T>): Promise<T> {
642 const queuedOperation = this.executionState.queue.then(operation, operation)
643 this.executionState.queue = queuedOperation.then(
644 () => undefined,
645 () => undefined,
646 )
647 return queuedOperation
648 }
649
650 private async getTransactionContextStorage(): Promise<AsyncLocalStorageLike<TransactionContextStore> | null> {
651 if (this.executionState.transactionContextStoragePromise) {
652 return this.executionState.transactionContextStoragePromise
653 }
654
655 this.executionState.transactionContextStoragePromise = (async () => {
656 const asyncLocalStorageCtor = await resolveAsyncLocalStorageCtor()
657 if (!asyncLocalStorageCtor) {
658 return null
659 }
660
661 return new asyncLocalStorageCtor<TransactionContextStore>()
662 })()
663
664 return this.executionState.transactionContextStoragePromise
665 }
666
667 private async getActiveTransactionDriver(): Promise<SQLiteDriver | null> {
668 const transactionContextStorage = await this.getTransactionContextStorage()
669 const store = transactionContextStorage?.getStore()
670 return store?.transactionDriver ?? null
671 }
672
673 private async runWithTransactionContext<TResult>(
674 transactionDriver: SQLiteDriver,
675 callback: () => Promise<TResult>,
676 ): Promise<TResult> {
677 const transactionContextStorage = await this.getTransactionContextStorage()
678 if (!transactionContextStorage) {
679 return callback()
680 }
681
682 return transactionContextStorage.run({ transactionDriver }, callback)
683 }
684
685 private createTransactionDriver(): SQLiteDriver {
686 const transactionDriver: SQLiteDriver = {
687 exec: async (sql) => {
688 await this.execute(sql)
689 },
690 query: async <T>(
691 sql: string,
692 params: ReadonlyArray<unknown> = [],
693 ): Promise<ReadonlyArray<T>> => {
694 const result = await this.execute(sql, params)
695 return extractRowsFromExecuteResult(
696 result,
697 sql,
698 this.arrayResultMode,
699 ) as ReadonlyArray<T>
700 },
701 run: async (sql, params = []) => {
702 await this.execute(sql, params)
703 },
704 transaction: async <T>(
705 fn: (transactionDriver: SQLiteDriver) => Promise<T>,
706 ): Promise<T> => {
707 assertTransactionCallbackHasDriverArg(fn)
708 return this.runNestedTransaction(transactionDriver, async (driver) => {
709 return fn(driver)
710 })
711 },
712 transactionWithDriver: async <T>(
713 fn: (transactionDriver: SQLiteDriver) => Promise<T>,
714 ): Promise<T> => this.runNestedTransaction(transactionDriver, fn),
715 }
716
717 return transactionDriver
718 }
719
720 private async runNestedTransaction<T>(
721 transactionDriver: SQLiteDriver,
722 fn: (transactionDriver: SQLiteDriver) => Promise<T>,
723 ): Promise<T> {
724 const savepointName = `tsdb_sp_${this.executionState.nextSavepointId}`
725 this.executionState.nextSavepointId++
726 await this.execute(`SAVEPOINT ${savepointName}`)
727
728 try {
729 const result = await fn(transactionDriver)
730 await this.execute(`RELEASE SAVEPOINT ${savepointName}`)
731 return result
732 } catch (error) {
733 await this.execute(`ROLLBACK TO SAVEPOINT ${savepointName}`)
734 await this.execute(`RELEASE SAVEPOINT ${savepointName}`)
735 throw error
736 }
737 }
738}
739
740export function createOpSQLiteDriver(
741 options: OpSQLiteDriverOptions,
742): OpSQLiteDriver {
743 return new OpSQLiteDriver(options)
744}