Open History to see the last commit
1import { InvalidPersistedCollectionConfigError } from '@tanstack/db-sqlite-persistence-core'
2import type { SQLiteDriver } from '@tanstack/db-sqlite-persistence-core'
3import type {
4 SQLiteBindParams,
5 SQLiteBindValue,
6 SQLiteRunResult,
7} from 'expo-sqlite'
8
9export type ExpoSQLiteBindParams = SQLiteBindParams
10
11export type ExpoSQLiteRunResult = SQLiteRunResult
12
13export type ExpoSQLiteQueryable = {
14 execAsync: (sql: string) => Promise<void>
15 getAllAsync: {
16 <T>(sql: string, params: SQLiteBindParams): Promise<ReadonlyArray<T>>
17 <T>(sql: string): Promise<ReadonlyArray<T>>
18 }
19 runAsync: {
20 (sql: string, params: SQLiteBindParams): Promise<SQLiteRunResult>
21 (sql: string): Promise<SQLiteRunResult>
22 }
23}
24
25export type ExpoSQLiteTransaction = ExpoSQLiteQueryable
26
27export type ExpoSQLiteDatabaseLike = ExpoSQLiteQueryable & {
28 withExclusiveTransactionAsync: (
29 task: (transaction: ExpoSQLiteTransaction) => Promise<void>,
30 ) => Promise<void>
31 closeAsync?: () => Promise<void>
32}
33
34type ExpoSQLiteExistingDatabaseOptions = {
35 database: ExpoSQLiteDatabaseLike
36}
37
38type ExpoSQLiteOpenDatabaseOptions = {
39 openDatabase: () => Promise<ExpoSQLiteDatabaseLike> | ExpoSQLiteDatabaseLike
40}
41
42export type ExpoSQLiteDriverOptions =
43 ExpoSQLiteExistingDatabaseOptions | ExpoSQLiteOpenDatabaseOptions
44
45function hasExistingDatabase(
46 options: ExpoSQLiteDriverOptions,
47): options is ExpoSQLiteExistingDatabaseOptions {
48 return `database` in options
49}
50
51function assertTransactionCallbackHasDriverArg(
52 fn: (transactionDriver: SQLiteDriver) => Promise<unknown>,
53): void {
54 if (fn.length > 0) {
55 return
56 }
57
58 throw new InvalidPersistedCollectionConfigError(
59 `SQLiteDriver.transaction callback must accept the transaction driver argument`,
60 )
61}
62
63function isExpoSQLiteDatabaseLike(
64 value: unknown,
65): value is ExpoSQLiteDatabaseLike {
66 return (
67 typeof value === `object` &&
68 value !== null &&
69 typeof (value as ExpoSQLiteDatabaseLike).execAsync === `function` &&
70 typeof (value as ExpoSQLiteDatabaseLike).getAllAsync === `function` &&
71 typeof (value as ExpoSQLiteDatabaseLike).runAsync === `function` &&
72 typeof (value as ExpoSQLiteDatabaseLike).withExclusiveTransactionAsync ===
73 `function`
74 )
75}
76
77export class ExpoSQLiteDriver implements SQLiteDriver {
78 private readonly databasePromise: Promise<ExpoSQLiteDatabaseLike>
79 private readonly ownsDatabase: boolean
80 private queue: Promise<void> = Promise.resolve()
81 private nextSavepointId = 1
82
83 constructor(options: ExpoSQLiteDriverOptions) {
84 if (hasExistingDatabase(options)) {
85 if (!isExpoSQLiteDatabaseLike(options.database)) {
86 throw new InvalidPersistedCollectionConfigError(
87 `Expo SQLite database must provide execAsync/getAllAsync/runAsync/withExclusiveTransactionAsync`,
88 )
89 }
90
91 this.databasePromise = Promise.resolve(options.database)
92 this.ownsDatabase = false
93 return
94 }
95
96 this.databasePromise = Promise.resolve(options.openDatabase()).then(
97 (database) => {
98 if (!isExpoSQLiteDatabaseLike(database)) {
99 throw new InvalidPersistedCollectionConfigError(
100 `Expo SQLite openDatabase() must resolve a database with execAsync/getAllAsync/runAsync/withExclusiveTransactionAsync`,
101 )
102 }
103
104 return database
105 },
106 )
107 this.ownsDatabase = true
108 }
109
110 async exec(sql: string): Promise<void> {
111 await this.enqueue(async () => {
112 const database = await this.getDatabase()
113 await database.execAsync(sql)
114 })
115 }
116
117 async query<T>(
118 sql: string,
119 params: ReadonlyArray<unknown> = [],
120 ): Promise<ReadonlyArray<T>> {
121 return this.enqueue(async () => {
122 const database = await this.getDatabase()
123 return database.getAllAsync<T>(sql, normalizeParams(params))
124 })
125 }
126
127 async run(sql: string, params: ReadonlyArray<unknown> = []): Promise<void> {
128 await this.enqueue(async () => {
129 const database = await this.getDatabase()
130 await database.runAsync(sql, normalizeParams(params))
131 })
132 }
133
134 async transaction<T>(
135 fn: (transactionDriver: SQLiteDriver) => Promise<T>,
136 ): Promise<T> {
137 assertTransactionCallbackHasDriverArg(fn)
138 return this.transactionWithDriver(fn)
139 }
140
141 async transactionWithDriver<T>(
142 fn: (transactionDriver: SQLiteDriver) => Promise<T>,
143 ): Promise<T> {
144 return this.enqueue(async () => {
145 const database = await this.getDatabase()
146 let result: T | undefined
147 await database.withExclusiveTransactionAsync(async (transaction) => {
148 const transactionDriver = this.createTransactionDriver(transaction)
149 result = await fn(transactionDriver)
150 })
151 return result as T
152 })
153 }
154
155 async close(): Promise<void> {
156 const database = await this.getDatabase()
157 if (!this.ownsDatabase || typeof database.closeAsync !== `function`) {
158 return
159 }
160
161 await database.closeAsync()
162 }
163
164 async getDatabase(): Promise<ExpoSQLiteDatabaseLike> {
165 return this.databasePromise
166 }
167
168 private enqueue<T>(operation: () => Promise<T>): Promise<T> {
169 const queuedOperation = this.queue.then(operation, operation)
170 this.queue = queuedOperation.then(
171 () => undefined,
172 () => undefined,
173 )
174 return queuedOperation
175 }
176
177 private createTransactionDriver(
178 transaction: ExpoSQLiteTransaction,
179 ): SQLiteDriver {
180 const transactionDriver: SQLiteDriver = {
181 exec: async (sql) => {
182 await transaction.execAsync(sql)
183 },
184 query: async <T>(
185 sql: string,
186 params: ReadonlyArray<unknown> = [],
187 ): Promise<ReadonlyArray<T>> => {
188 return transaction.getAllAsync<T>(sql, normalizeParams(params))
189 },
190 run: async (sql: string, params: ReadonlyArray<unknown> = []) => {
191 await transaction.runAsync(sql, normalizeParams(params))
192 },
193 transaction: async <T>(
194 fn: (nestedTransactionDriver: SQLiteDriver) => Promise<T>,
195 ): Promise<T> => {
196 assertTransactionCallbackHasDriverArg(fn)
197 return this.runNestedTransaction(transaction, transactionDriver, fn)
198 },
199 transactionWithDriver: async <T>(
200 fn: (nestedTransactionDriver: SQLiteDriver) => Promise<T>,
201 ): Promise<T> =>
202 this.runNestedTransaction(transaction, transactionDriver, fn),
203 }
204
205 return transactionDriver
206 }
207
208 private async runNestedTransaction<T>(
209 transaction: ExpoSQLiteTransaction,
210 transactionDriver: SQLiteDriver,
211 fn: (transactionDriver: SQLiteDriver) => Promise<T>,
212 ): Promise<T> {
213 const savepointName = `tsdb_sp_${this.nextSavepointId}`
214 this.nextSavepointId++
215 await transaction.execAsync(`SAVEPOINT ${savepointName}`)
216
217 try {
218 const result = await fn(transactionDriver)
219 await transaction.execAsync(`RELEASE SAVEPOINT ${savepointName}`)
220 return result
221 } catch (error) {
222 await transaction.execAsync(`ROLLBACK TO SAVEPOINT ${savepointName}`)
223 await transaction.execAsync(`RELEASE SAVEPOINT ${savepointName}`)
224 throw error
225 }
226 }
227}
228
229function normalizeParams(params: ReadonlyArray<unknown>): SQLiteBindParams {
230 return params.map((value) => {
231 if (
232 value === null ||
233 typeof value === `string` ||
234 typeof value === `number` ||
235 typeof value === `boolean` ||
236 value instanceof Uint8Array
237 ) {
238 return value satisfies SQLiteBindValue
239 }
240
241 throw new TypeError(
242 `Expo SQLite bind parameters must be strings, numbers, booleans, null, or Uint8Array values`,
243 )
244 })
245}
246
247export function createExpoSQLiteDriver(
248 options: ExpoSQLiteDriverOptions,
249): ExpoSQLiteDriver {
250 return new ExpoSQLiteDriver(options)
251}