Open History to see the last commit
1import { mkdtempSync, rmSync } from 'node:fs'
2import { tmpdir } from 'node:os'
3import { join } from 'node:path'
4import { afterEach, expect, it } from 'vitest'
5import { ExpoSQLiteDriver } from '../src/expo-sqlite-driver'
6import { InvalidPersistedCollectionConfigError } from '../../db-sqlite-persistence-core/src'
7import { createExpoSQLiteTestDatabase } from './helpers/expo-sqlite-test-db'
8import type {
9 ExpoSQLiteDatabaseLike,
10 ExpoSQLiteTransaction,
11} from '../src/expo-sqlite-driver'
12
13const activeCleanupFns: Array<() => void | Promise<void>> = []
14
15afterEach(async () => {
16 while (activeCleanupFns.length > 0) {
17 const cleanupFn = activeCleanupFns.pop()
18 await Promise.resolve(cleanupFn?.())
19 }
20})
21
22function createTempSqlitePath(): string {
23 const tempDirectory = mkdtempSync(join(tmpdir(), `db-expo-sqlite-test-`))
24 const dbPath = join(tempDirectory, `state.sqlite`)
25 activeCleanupFns.push(() => {
26 rmSync(tempDirectory, { recursive: true, force: true })
27 })
28 return dbPath
29}
30
31it(`reads query rows through getAllAsync`, async () => {
32 const dbPath = createTempSqlitePath()
33 const database = createExpoSQLiteTestDatabase({ filename: dbPath })
34 activeCleanupFns.push(() => database.closeAsync())
35
36 const driver = new ExpoSQLiteDriver({ database })
37 await driver.exec(
38 `CREATE TABLE todos (id TEXT PRIMARY KEY, title TEXT NOT NULL, score INTEGER NOT NULL)`,
39 )
40 await driver.run(`INSERT INTO todos (id, title, score) VALUES (?, ?, ?)`, [
41 `1`,
42 `From expo test`,
43 7,
44 ])
45
46 const rows = await driver.query<{
47 id: string
48 title: string
49 score: number
50 }>(`SELECT id, title, score FROM todos ORDER BY id ASC`)
51 expect(rows).toEqual([
52 {
53 id: `1`,
54 title: `From expo test`,
55 score: 7,
56 },
57 ])
58})
59
60it(`rolls back exclusive transaction on failure`, async () => {
61 const dbPath = createTempSqlitePath()
62 const database = createExpoSQLiteTestDatabase({ filename: dbPath })
63 activeCleanupFns.push(() => database.closeAsync())
64
65 const driver = new ExpoSQLiteDriver({ database })
66 await driver.exec(
67 `CREATE TABLE tx_test (id TEXT PRIMARY KEY, title TEXT NOT NULL)`,
68 )
69
70 await expect(
71 driver.transactionWithDriver(async (transactionDriver) => {
72 await transactionDriver.run(
73 `INSERT INTO tx_test (id, title) VALUES (?, ?)`,
74 [`1`, `First`],
75 )
76 await transactionDriver.run(
77 `INSERT INTO tx_test (missing_column) VALUES (?)`,
78 [`x`],
79 )
80 }),
81 ).rejects.toThrow()
82
83 const rows = await driver.query<{ count: number }>(
84 `SELECT COUNT(*) AS count FROM tx_test`,
85 )
86 expect(rows[0]?.count).toBe(0)
87})
88
89it(`supports nested savepoint rollback without losing outer transaction`, async () => {
90 const dbPath = createTempSqlitePath()
91 const database = createExpoSQLiteTestDatabase({ filename: dbPath })
92 activeCleanupFns.push(() => database.closeAsync())
93
94 const driver = new ExpoSQLiteDriver({ database })
95 await driver.exec(
96 `CREATE TABLE nested_tx_test (id TEXT PRIMARY KEY, title TEXT NOT NULL)`,
97 )
98
99 await driver.transactionWithDriver(async (outerTransactionDriver) => {
100 await outerTransactionDriver.run(
101 `INSERT INTO nested_tx_test (id, title) VALUES (?, ?)`,
102 [`1`, `Outer before`],
103 )
104
105 await expect(
106 outerTransactionDriver.transaction(async (innerTransactionDriver) => {
107 await innerTransactionDriver.run(
108 `INSERT INTO nested_tx_test (id, title) VALUES (?, ?)`,
109 [`2`, `Inner failing`],
110 )
111 throw new Error(`nested-failure`)
112 }),
113 ).rejects.toThrow(`nested-failure`)
114
115 await outerTransactionDriver.run(
116 `INSERT INTO nested_tx_test (id, title) VALUES (?, ?)`,
117 [`3`, `Outer after`],
118 )
119 })
120
121 const rows = await driver.query<{ id: string; title: string }>(
122 `SELECT id, title FROM nested_tx_test ORDER BY id ASC`,
123 )
124 expect(rows).toEqual([
125 { id: `1`, title: `Outer before` },
126 { id: `3`, title: `Outer after` },
127 ])
128})
129
130it(`supports transaction callbacks that use provided transaction driver`, async () => {
131 const dbPath = createTempSqlitePath()
132 const database = createExpoSQLiteTestDatabase({ filename: dbPath })
133 activeCleanupFns.push(() => database.closeAsync())
134
135 const driver = new ExpoSQLiteDriver({ database })
136 await driver.exec(`CREATE TABLE closure_tx_test (value INTEGER NOT NULL)`)
137
138 let resolveHold: (() => void) | undefined
139 const hold = new Promise<void>((resolve) => {
140 resolveHold = resolve
141 })
142 let resolveEntered: (() => void) | undefined
143 const entered = new Promise<void>((resolve) => {
144 resolveEntered = resolve
145 })
146
147 const txPromise = driver.transaction(async (transactionDriver) => {
148 if (!resolveEntered) {
149 throw new Error(`transaction entry signal missing`)
150 }
151 resolveEntered()
152 await transactionDriver.run(
153 `INSERT INTO closure_tx_test (value) VALUES (?)`,
154 [1],
155 )
156 await hold
157 await transactionDriver.run(
158 `INSERT INTO closure_tx_test (value) VALUES (?)`,
159 [2],
160 )
161 })
162
163 await entered
164
165 let outsideResolved = false
166 const outsidePromise = driver
167 .run(`INSERT INTO closure_tx_test (value) VALUES (?)`, [3])
168 .then(() => {
169 outsideResolved = true
170 })
171
172 await Promise.resolve()
173 expect(outsideResolved).toBe(false)
174
175 if (!resolveHold) {
176 throw new Error(`transaction hold signal missing`)
177 }
178 resolveHold()
179
180 await Promise.all([txPromise, outsidePromise])
181
182 const rows = await driver.query<{ value: number }>(
183 `SELECT value FROM closure_tx_test ORDER BY value ASC`,
184 )
185 expect(rows.map((row) => row.value)).toEqual([1, 2, 3])
186})
187
188it(`throws when transaction callback omits transaction driver argument`, async () => {
189 const dbPath = createTempSqlitePath()
190 const database = createExpoSQLiteTestDatabase({ filename: dbPath })
191 activeCleanupFns.push(() => database.closeAsync())
192
193 const driver = new ExpoSQLiteDriver({ database })
194
195 await expect(
196 driver.transaction((() => Promise.resolve(undefined)) as never),
197 ).rejects.toThrow(`transaction driver argument`)
198})
199
200/**
201 * Runtime checkpoint for the paired type assertion: `transaction<T>` resolves
202 * to the callback's value after Expo's void-returning exclusive transaction
203 * boundary settles. This test does not claim an intermediate publication or
204 * independently recheck commit and rollback behavior.
205 */
206it(`returns callback values when Expo's transaction boundary returns void`, async () => {
207 const transaction: ExpoSQLiteTransaction = {
208 execAsync: () => Promise.resolve(),
209 getAllAsync: <T>() => Promise.resolve([] as Array<T>),
210 runAsync: () =>
211 Promise.resolve({
212 changes: 0,
213 lastInsertRowId: 0,
214 }),
215 }
216 const database: ExpoSQLiteDatabaseLike = {
217 ...transaction,
218 withExclusiveTransactionAsync: async (task) => {
219 await task(transaction)
220 },
221 }
222 const driver = new ExpoSQLiteDriver({ database })
223
224 await expect(
225 driver.transaction((transactionDriver) => {
226 void transactionDriver
227 return Promise.resolve({ status: `committed` as const })
228 }),
229 ).resolves.toEqual({ status: `committed` })
230})
231
232it(`rejects values outside Expo's SQLite bind domain`, async () => {
233 const transaction: ExpoSQLiteTransaction = {
234 execAsync: () => Promise.resolve(),
235 getAllAsync: <T>() => Promise.resolve([] as Array<T>),
236 runAsync: () =>
237 Promise.resolve({
238 changes: 0,
239 lastInsertRowId: 0,
240 }),
241 }
242 const database: ExpoSQLiteDatabaseLike = {
243 ...transaction,
244 withExclusiveTransactionAsync: async (task) => {
245 await task(transaction)
246 },
247 }
248 const driver = new ExpoSQLiteDriver({ database })
249
250 await expect(driver.run(`SELECT ?`, [{ unsupported: true }])).rejects.toThrow(
251 `Expo SQLite bind parameters`,
252 )
253})
254
255it(`throws config error when expo database methods are missing`, () => {
256 expect(() => new ExpoSQLiteDriver({ database: {} as never })).toThrowError(
257 InvalidPersistedCollectionConfigError,
258 )
259})