@baukit/data-contracts-expo-sqlite 0.7.1 → 0.7.3

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@baukit/data-contracts-expo-sqlite",
3
- "version": "0.7.1",
3
+ "version": "0.7.3",
4
4
  "description": "Expo SQLite implementation of the @baukit/data-contracts base storage contracts.",
5
5
  "license": "MIT",
6
6
  "author": "Patrick Koss",
@@ -35,6 +35,7 @@
35
35
  },
36
36
  "files": [
37
37
  "dist",
38
+ "src",
38
39
  "README.md",
39
40
  "LICENSE"
40
41
  ],
@@ -52,7 +53,7 @@
52
53
  "typescript": "6.0.3"
53
54
  },
54
55
  "peerDependencies": {
55
- "@baukit/data-contracts": "^0.7.1",
56
+ "@baukit/data-contracts": "^0.7.3",
56
57
  "expo-sqlite": "^57.0.3"
57
58
  }
58
59
  }
@@ -0,0 +1,654 @@
1
+ import { StorageError, type StoredRecord } from '@baukit/data-contracts';
2
+ import { afterEach, describe, expect, it } from 'vitest';
3
+
4
+ import { ExpoSqliteConnection, ExpoSqliteStore, type SqliteTransaction } from './index.js';
5
+ import {
6
+ NodeSqliteDatabase,
7
+ type SqliteMigrationConformanceAdapter,
8
+ type SqliteMigrationStep,
9
+ createSqliteMigrationConformanceTests,
10
+ } from './testing.js';
11
+
12
+ interface Signal {
13
+ readonly promise: Promise<void>;
14
+ readonly resolve: () => void;
15
+ }
16
+
17
+ interface LabelRow {
18
+ readonly label: string;
19
+ }
20
+
21
+ interface VersionRow {
22
+ readonly version: number | null;
23
+ }
24
+
25
+ interface CachedRecord extends StoredRecord {
26
+ readonly value: string;
27
+ }
28
+
29
+ /** The statements a root-transaction driver exposes, whether or not it queues them. */
30
+ interface RawDriver {
31
+ exec(source: string): Promise<unknown>;
32
+ run(source: string, ...params: string[]): Promise<unknown>;
33
+ transaction(work: (transaction: RawDriver) => Promise<void>): Promise<void>;
34
+ }
35
+
36
+ const CREATE_EVENTS = 'CREATE TABLE events (label TEXT NOT NULL)';
37
+ const INSERT_EVENT = 'INSERT INTO events (label) VALUES (?)';
38
+ const CREATE_FAMILY = `CREATE TABLE parents (id TEXT PRIMARY KEY NOT NULL);
39
+ CREATE TABLE children (
40
+ id TEXT PRIMARY KEY NOT NULL,
41
+ parent_id TEXT NOT NULL REFERENCES parents (id) ON DELETE CASCADE
42
+ );`;
43
+
44
+ const databases: NodeSqliteDatabase[] = [];
45
+
46
+ function openDatabase(): NodeSqliteDatabase {
47
+ const database = new NodeSqliteDatabase();
48
+ databases.push(database);
49
+ return database;
50
+ }
51
+
52
+ function signal(): Signal {
53
+ let resolve = (): void => undefined;
54
+ const promise = new Promise<void>((done) => {
55
+ resolve = done;
56
+ });
57
+ return { promise, resolve };
58
+ }
59
+
60
+ function flush(): Promise<void> {
61
+ return new Promise((resolve) => {
62
+ setImmediate(resolve);
63
+ });
64
+ }
65
+
66
+ async function labels(database: NodeSqliteDatabase): Promise<string[]> {
67
+ const rows = await database.getAllAsync<LabelRow>('SELECT label FROM events ORDER BY rowid');
68
+ return rows.map((row) => row.label);
69
+ }
70
+
71
+ /** Expo's `withTransactionAsync` shape: `BEGIN` on the root handle with no queue. */
72
+ function unqueuedRootTransactions(database: NodeSqliteDatabase): RawDriver {
73
+ const driver: RawDriver = {
74
+ exec: (source) => database.execAsync(source),
75
+ run: (source, ...params) => database.runAsync(source, ...params),
76
+ transaction: async (work) => {
77
+ await database.execAsync('BEGIN');
78
+ try {
79
+ await work(driver);
80
+ await database.execAsync('COMMIT');
81
+ } catch (cause) {
82
+ await database.execAsync('ROLLBACK');
83
+ throw cause;
84
+ }
85
+ },
86
+ };
87
+ return driver;
88
+ }
89
+
90
+ function queuedConnection(database: NodeSqliteDatabase): RawDriver {
91
+ const connection = new ExpoSqliteConnection(database);
92
+ return {
93
+ exec: (source) => connection.exec(source),
94
+ run: (source, ...params) => connection.run(source, ...params),
95
+ transaction: (work) =>
96
+ connection.transaction((transaction) =>
97
+ work({
98
+ exec: (source) => transaction.exec(source),
99
+ run: (source, ...params) => transaction.run(source, ...params),
100
+ transaction: (nested) => transaction.transaction(nested),
101
+ }),
102
+ ),
103
+ };
104
+ }
105
+
106
+ /**
107
+ * One caller's transaction writes a row and rolls back while another caller issues an
108
+ * unrelated root write. Returns the rows that survive.
109
+ */
110
+ async function rootWriteDuringRolledBackTransaction(
111
+ database: NodeSqliteDatabase,
112
+ driver: RawDriver,
113
+ ): Promise<string[]> {
114
+ await driver.exec(CREATE_EVENTS);
115
+ const entered = signal();
116
+ const release = signal();
117
+ const transaction = driver.transaction(async (context) => {
118
+ await context.run(INSERT_EVENT, 'transaction');
119
+ entered.resolve();
120
+ await release.promise;
121
+ throw new Error('roll back');
122
+ });
123
+ await entered.promise;
124
+ const root = driver.run(INSERT_EVENT, 'root');
125
+ await flush();
126
+ release.resolve();
127
+ await expect(transaction).rejects.toThrow('roll back');
128
+ await root;
129
+ return labels(database);
130
+ }
131
+
132
+ afterEach(async () => {
133
+ await Promise.allSettled(databases.splice(0).map((database) => database.closeAsync()));
134
+ });
135
+
136
+ describe('ExpoSqliteConnection', () => {
137
+ it('runs, reads, and binds parameters as Expo does', async () => {
138
+ const connection = new ExpoSqliteConnection(openDatabase());
139
+ await connection.exec('CREATE TABLE items (id INTEGER PRIMARY KEY, label TEXT, flag ANY)');
140
+ const inserted = await connection.run(
141
+ 'INSERT INTO items (label, flag) VALUES (?, ?)',
142
+ 'variadic',
143
+ true,
144
+ );
145
+ await connection.run('INSERT INTO items (label, flag) VALUES (?, ?)', ['array', null]);
146
+ await connection.run('INSERT INTO items (label, flag) VALUES ($label, $flag)', {
147
+ $label: 'named',
148
+ $flag: false,
149
+ });
150
+ expect(inserted).toEqual({ changes: 1, lastInsertRowId: 1 });
151
+ await expect(
152
+ connection.all<{ readonly label: string; readonly flag: number | null }>(
153
+ 'SELECT label, flag FROM items ORDER BY id',
154
+ ),
155
+ ).resolves.toEqual([
156
+ { label: 'variadic', flag: 1 },
157
+ { label: 'array', flag: null },
158
+ { label: 'named', flag: 0 },
159
+ ]);
160
+ await expect(
161
+ connection.get<LabelRow>('SELECT label FROM items WHERE id = ?', 3),
162
+ ).resolves.toEqual({ label: 'named' });
163
+ await expect(connection.get('SELECT label FROM items WHERE id = ?', 99)).resolves.toBe(
164
+ undefined,
165
+ );
166
+ });
167
+
168
+ it('keeps a root statement issued during a transaction out of that transaction', async () => {
169
+ const database = openDatabase();
170
+ await expect(
171
+ rootWriteDuringRolledBackTransaction(database, queuedConnection(database)),
172
+ ).resolves.toEqual(['root']);
173
+ });
174
+
175
+ it('shows the same case losing the root write when root transactions are not queued', async () => {
176
+ const database = openDatabase();
177
+ await expect(
178
+ rootWriteDuringRolledBackTransaction(database, unqueuedRootTransactions(database)),
179
+ ).resolves.toEqual([]);
180
+ });
181
+
182
+ it('commits every statement and returns the callback result', async () => {
183
+ const database = openDatabase();
184
+ const connection = new ExpoSqliteConnection(database);
185
+ await connection.exec(CREATE_EVENTS);
186
+ const result = await connection.transaction(async (transaction) => {
187
+ await transaction.run(INSERT_EVENT, 'first');
188
+ await transaction.run(INSERT_EVENT, 'second');
189
+ return transaction.all<LabelRow>('SELECT label FROM events ORDER BY rowid');
190
+ });
191
+ expect(result).toEqual([{ label: 'first' }, { label: 'second' }]);
192
+ await expect(labels(database)).resolves.toEqual(['first', 'second']);
193
+ });
194
+
195
+ it('rolls back every statement, including schema changes, and rethrows the failure', async () => {
196
+ const database = openDatabase();
197
+ const connection = new ExpoSqliteConnection(database);
198
+ await connection.exec(CREATE_EVENTS);
199
+ const failure = new Error('step failed');
200
+ await expect(
201
+ connection.transaction(async (transaction) => {
202
+ await transaction.run(INSERT_EVENT, 'lost');
203
+ await transaction.exec('CREATE TABLE partial (id TEXT); ALTER TABLE events ADD COLUMN x');
204
+ throw failure;
205
+ }),
206
+ ).rejects.toBe(failure);
207
+ await expect(labels(database)).resolves.toEqual([]);
208
+ await expect(
209
+ connection.get("SELECT name FROM sqlite_master WHERE name = 'partial'"),
210
+ ).resolves.toBe(undefined);
211
+ await expect(connection.all("SELECT name FROM pragma_table_info('events')")).resolves.toEqual([
212
+ { name: 'label' },
213
+ ]);
214
+ });
215
+
216
+ it('rolls back when the commit fails and passes the commit error on', async () => {
217
+ const database = openDatabase();
218
+ const connection = new ExpoSqliteConnection(database);
219
+ await connection.exec(`CREATE TABLE parents (id TEXT PRIMARY KEY NOT NULL);
220
+ CREATE TABLE children (
221
+ id TEXT PRIMARY KEY NOT NULL,
222
+ parent_id TEXT NOT NULL REFERENCES parents (id) DEFERRABLE INITIALLY DEFERRED
223
+ );`);
224
+ await expect(
225
+ connection.transaction((transaction) =>
226
+ transaction.run('INSERT INTO children (id, parent_id) VALUES (?, ?)', 'orphan', 'none'),
227
+ ),
228
+ ).rejects.toThrow('FOREIGN KEY constraint failed');
229
+ await expect(connection.all('SELECT id FROM children')).resolves.toEqual([]);
230
+ await expect(connection.run('INSERT INTO parents (id) VALUES (?)', 'next')).resolves.toEqual({
231
+ changes: 1,
232
+ lastInsertRowId: 1,
233
+ });
234
+ });
235
+
236
+ it('enforces foreign keys inside transactions', async () => {
237
+ const database = openDatabase();
238
+ const connection = new ExpoSqliteConnection(database);
239
+ await connection.exec(CREATE_FAMILY);
240
+ await expect(
241
+ connection.transaction((transaction) =>
242
+ transaction.run('INSERT INTO children (id, parent_id) VALUES (?, ?)', 'orphan', 'none'),
243
+ ),
244
+ ).rejects.toThrow('FOREIGN KEY constraint failed');
245
+ await connection.transaction(async (transaction) => {
246
+ await transaction.run('INSERT INTO parents (id) VALUES (?)', 'parent');
247
+ await transaction.run('INSERT INTO children (id, parent_id) VALUES (?, ?)', 'kid', 'parent');
248
+ await transaction.run('DELETE FROM parents WHERE id = ?', 'parent');
249
+ });
250
+ await expect(database.getAllAsync('SELECT id FROM children')).resolves.toEqual([]);
251
+ });
252
+
253
+ it('enables foreign keys before its first statement on the handle', async () => {
254
+ const database = openDatabase();
255
+ await expect(database.getFirstAsync('PRAGMA foreign_keys')).resolves.toEqual({
256
+ foreign_keys: 0,
257
+ });
258
+ const connection = new ExpoSqliteConnection(database);
259
+ await expect(connection.get('PRAGMA foreign_keys')).resolves.toEqual({ foreign_keys: 1 });
260
+ });
261
+
262
+ it('rejects statements on a transaction after it settles', async () => {
263
+ const connection = new ExpoSqliteConnection(openDatabase());
264
+ await connection.exec(CREATE_EVENTS);
265
+ let leaked: SqliteTransaction | undefined;
266
+ await connection.transaction((transaction) => {
267
+ leaked = transaction;
268
+ });
269
+ const error = await leaked?.run(INSERT_EVENT, 'late').catch((cause: unknown) => cause);
270
+ expect(error).toBeInstanceOf(StorageError);
271
+ expect(error).toMatchObject({ code: 'storage_closed' });
272
+ await expect(connection.all('SELECT label FROM events')).resolves.toEqual([]);
273
+ });
274
+
275
+ it('runs root statements and transactions one at a time in call order', async () => {
276
+ const connection = new ExpoSqliteConnection(openDatabase());
277
+ await connection.exec(CREATE_EVENTS);
278
+ const events: string[] = [];
279
+ const first = connection.transaction(async (transaction) => {
280
+ events.push('first:start');
281
+ await transaction.run(INSERT_EVENT, 'first');
282
+ await flush();
283
+ events.push('first:end');
284
+ });
285
+ const root = connection.run(INSERT_EVENT, 'root').then(() => {
286
+ events.push('root');
287
+ });
288
+ const second = connection.transaction(async (transaction) => {
289
+ events.push('second:start');
290
+ await transaction.run(INSERT_EVENT, 'second');
291
+ events.push('second:end');
292
+ });
293
+ await Promise.all([first, root, second]);
294
+ expect(events).toEqual(['first:start', 'first:end', 'root', 'second:start', 'second:end']);
295
+ });
296
+
297
+ it('releases the queue after a failed statement', async () => {
298
+ const connection = new ExpoSqliteConnection(openDatabase());
299
+ const failed = connection.exec('SELECT * FROM missing_table');
300
+ const next = connection.get<{ readonly one: number }>('SELECT 1 AS one');
301
+ await expect(failed).rejects.toThrow('no such table');
302
+ await expect(next).resolves.toEqual({ one: 1 });
303
+ });
304
+
305
+ it('shares the file queue with ExpoSqliteStore in both arrival orders', async () => {
306
+ const database = openDatabase();
307
+ const connection = new ExpoSqliteConnection(database);
308
+ const store = new ExpoSqliteStore<CachedRecord>(database, 'cache');
309
+ await store.initialize();
310
+ await connection.exec(CREATE_EVENTS);
311
+
312
+ const storeEntered = signal();
313
+ const storeRelease = signal();
314
+ const storeTransaction = store.withTransaction(async (context) => {
315
+ await context.records.put({ id: 'store', value: 'committed' });
316
+ storeEntered.resolve();
317
+ await storeRelease.promise;
318
+ });
319
+ await storeEntered.promise;
320
+ const rootWrite = connection.run(INSERT_EVENT, 'after store');
321
+ await flush();
322
+ storeRelease.resolve();
323
+ await Promise.all([storeTransaction, rootWrite]);
324
+
325
+ const connectionEntered = signal();
326
+ const connectionRelease = signal();
327
+ const connectionTransaction = connection.transaction(async (transaction) => {
328
+ await transaction.run(INSERT_EVENT, 'rolled back');
329
+ connectionEntered.resolve();
330
+ await connectionRelease.promise;
331
+ throw new Error('roll back');
332
+ });
333
+ await connectionEntered.promise;
334
+ const storeWrite = store.records.put({ id: 'root', value: 'kept' });
335
+ await flush();
336
+ connectionRelease.resolve();
337
+ await expect(connectionTransaction).rejects.toThrow('roll back');
338
+ await storeWrite;
339
+
340
+ await expect(labels(database)).resolves.toEqual(['after store']);
341
+ await expect(store.records.get('root')).resolves.toEqual({ id: 'root', value: 'kept' });
342
+ });
343
+
344
+ it('closes an owned handle once after accepted work and rejects later calls', async () => {
345
+ const database = new NodeSqliteDatabase();
346
+ const connection = new ExpoSqliteConnection(database, { closeDatabase: true });
347
+ await connection.exec(CREATE_EVENTS);
348
+ const accepted = connection.transaction((transaction) => transaction.run(INSERT_EVENT, 'x'));
349
+ const closed = connection.close();
350
+ expect(connection.close()).toBe(closed);
351
+ await expect(accepted).resolves.toMatchObject({ changes: 1 });
352
+ await closed;
353
+ await expect(connection.run(INSERT_EVENT, 'late')).rejects.toMatchObject({
354
+ code: 'storage_closed',
355
+ });
356
+ await expect(connection.transaction(() => undefined)).rejects.toMatchObject({
357
+ code: 'storage_closed',
358
+ });
359
+ await expect(database.execAsync('SELECT 1')).rejects.toThrow();
360
+ });
361
+
362
+ it('leaves an unowned handle open on close', async () => {
363
+ const database = openDatabase();
364
+ const connection = new ExpoSqliteConnection(database);
365
+ await connection.close();
366
+ await expect(database.getFirstAsync('SELECT 1 AS one')).resolves.toEqual({ one: 1 });
367
+ });
368
+ });
369
+
370
+ describe('ExpoSqliteConnection nested transactions', () => {
371
+ async function eventsConnection(): Promise<{
372
+ readonly database: NodeSqliteDatabase;
373
+ readonly connection: ExpoSqliteConnection;
374
+ }> {
375
+ const database = openDatabase();
376
+ const connection = new ExpoSqliteConnection(database);
377
+ await connection.exec(CREATE_EVENTS);
378
+ return { database, connection };
379
+ }
380
+
381
+ it('commits nested work with the enclosing transaction and returns its result', async () => {
382
+ const { database, connection } = await eventsConnection();
383
+ const result = await connection.transaction(async (transaction) => {
384
+ await transaction.run(INSERT_EVENT, 'outer');
385
+ const inner = await transaction.transaction(async (nested) => {
386
+ await nested.run(INSERT_EVENT, 'inner');
387
+ return nested.all<LabelRow>('SELECT label FROM events ORDER BY rowid');
388
+ });
389
+ await transaction.run(INSERT_EVENT, 'after');
390
+ return inner;
391
+ });
392
+ expect(result).toEqual([{ label: 'outer' }, { label: 'inner' }]);
393
+ await expect(labels(database)).resolves.toEqual(['outer', 'inner', 'after']);
394
+ });
395
+
396
+ it('rolls back only the nested work, schema changes included, when the caller catches it', async () => {
397
+ const { database, connection } = await eventsConnection();
398
+ const failure = new Error('inner failed');
399
+ await connection.transaction(async (transaction) => {
400
+ await transaction.run(INSERT_EVENT, 'outer');
401
+ await expect(
402
+ transaction.transaction(async (nested) => {
403
+ await nested.run(INSERT_EVENT, 'lost');
404
+ await nested.exec('CREATE TABLE partial (id TEXT); ALTER TABLE events ADD COLUMN x');
405
+ throw failure;
406
+ }),
407
+ ).rejects.toBe(failure);
408
+ await transaction.run(INSERT_EVENT, 'after');
409
+ });
410
+ await expect(labels(database)).resolves.toEqual(['outer', 'after']);
411
+ await expect(
412
+ connection.get("SELECT name FROM sqlite_master WHERE name = 'partial'"),
413
+ ).resolves.toBe(undefined);
414
+ await expect(connection.all("SELECT name FROM pragma_table_info('events')")).resolves.toEqual([
415
+ { name: 'label' },
416
+ ]);
417
+ });
418
+
419
+ it('rolls back the whole transaction when a nested failure is not caught', async () => {
420
+ const { database, connection } = await eventsConnection();
421
+ const failure = new Error('inner failed');
422
+ await expect(
423
+ connection.transaction(async (transaction) => {
424
+ await transaction.run(INSERT_EVENT, 'outer');
425
+ await transaction.transaction(async (nested) => {
426
+ await nested.run(INSERT_EVENT, 'inner');
427
+ throw failure;
428
+ });
429
+ }),
430
+ ).rejects.toBe(failure);
431
+ await expect(labels(database)).resolves.toEqual([]);
432
+ });
433
+
434
+ it('rolls back released nested work when the enclosing transaction fails', async () => {
435
+ const { database, connection } = await eventsConnection();
436
+ await expect(
437
+ connection.transaction(async (transaction) => {
438
+ await transaction.transaction((nested) => nested.run(INSERT_EVENT, 'released'));
439
+ throw new Error('outer failed');
440
+ }),
441
+ ).rejects.toThrow('outer failed');
442
+ await expect(labels(database)).resolves.toEqual([]);
443
+ });
444
+
445
+ it('nests several levels and runs sibling nested transactions one after another', async () => {
446
+ const { database, connection } = await eventsConnection();
447
+ await connection.transaction(async (transaction) => {
448
+ await transaction.transaction((first) => first.run(INSERT_EVENT, 'first sibling'));
449
+ await expect(
450
+ transaction.transaction(async (middle) => {
451
+ await middle.run(INSERT_EVENT, 'middle');
452
+ await middle.transaction((inner) => inner.run(INSERT_EVENT, 'innermost'));
453
+ throw new Error('middle failed');
454
+ }),
455
+ ).rejects.toThrow('middle failed');
456
+ await transaction.transaction(async (last) => {
457
+ await last.transaction((inner) => inner.run(INSERT_EVENT, 'last sibling'));
458
+ });
459
+ });
460
+ await expect(labels(database)).resolves.toEqual(['first sibling', 'last sibling']);
461
+ });
462
+
463
+ it('enforces foreign keys inside nested transactions', async () => {
464
+ const database = openDatabase();
465
+ const connection = new ExpoSqliteConnection(database);
466
+ await connection.exec(CREATE_FAMILY);
467
+ await connection.transaction(async (transaction) => {
468
+ await transaction.run('INSERT INTO parents (id) VALUES (?)', 'parent');
469
+ await expect(
470
+ transaction.transaction((nested) =>
471
+ nested.run('INSERT INTO children (id, parent_id) VALUES (?, ?)', 'orphan', 'none'),
472
+ ),
473
+ ).rejects.toThrow('FOREIGN KEY constraint failed');
474
+ await transaction.transaction((nested) =>
475
+ nested.run('INSERT INTO children (id, parent_id) VALUES (?, ?)', 'kid', 'parent'),
476
+ );
477
+ });
478
+ await expect(database.getAllAsync('SELECT id FROM children')).resolves.toEqual([{ id: 'kid' }]);
479
+ });
480
+
481
+ it('rejects work on an outer level while a nested transaction is open', async () => {
482
+ const { database, connection } = await eventsConnection();
483
+ await connection.transaction(async (transaction) => {
484
+ const entered = signal();
485
+ const release = signal();
486
+ const nested = transaction.transaction(async (inner) => {
487
+ await inner.run(INSERT_EVENT, 'inner');
488
+ entered.resolve();
489
+ await release.promise;
490
+ });
491
+ await entered.promise;
492
+ await expect(transaction.run(INSERT_EVENT, 'outer')).rejects.toThrow(TypeError);
493
+ await expect(transaction.transaction(() => undefined)).rejects.toThrow(
494
+ 'A nested SQLite transaction is open. Use the nested transaction until it settles.',
495
+ );
496
+ release.resolve();
497
+ await nested;
498
+ await transaction.run(INSERT_EVENT, 'outer after');
499
+ });
500
+ await expect(labels(database)).resolves.toEqual(['inner', 'outer after']);
501
+ });
502
+
503
+ it('rejects statements on a nested transaction after it settles', async () => {
504
+ const { connection } = await eventsConnection();
505
+ await connection.transaction(async (transaction) => {
506
+ let leaked: SqliteTransaction | undefined;
507
+ await transaction.transaction((nested) => {
508
+ leaked = nested;
509
+ });
510
+ await expect(leaked?.run(INSERT_EVENT, 'late')).rejects.toMatchObject({
511
+ code: 'storage_closed',
512
+ });
513
+ });
514
+ await expect(connection.all('SELECT label FROM events')).resolves.toEqual([]);
515
+ });
516
+
517
+ it('does not wait on the file queue that another caller is queued on', async () => {
518
+ const { database, connection } = await eventsConnection();
519
+ let root: Promise<unknown> | undefined;
520
+ await connection.transaction(async (transaction) => {
521
+ root = connection.run(INSERT_EVENT, 'other caller');
522
+ await flush();
523
+ await transaction.transaction((nested) => nested.run(INSERT_EVENT, 'nested'));
524
+ await expect(labels(database)).resolves.toEqual(['nested']);
525
+ });
526
+ await root;
527
+ await expect(labels(database)).resolves.toEqual(['nested', 'other caller']);
528
+ });
529
+
530
+ it('lets a helper that opens its own transaction run at the root or inside another one', async () => {
531
+ const { database, connection } = await eventsConnection();
532
+ const record = (
533
+ target: Pick<SqliteTransaction, 'transaction'>,
534
+ label: string,
535
+ ): Promise<unknown> =>
536
+ target.transaction(async (transaction) => {
537
+ await transaction.run(INSERT_EVENT, label);
538
+ if (label.startsWith('invalid')) {
539
+ throw new Error(`rejected ${label}`);
540
+ }
541
+ });
542
+ await record(connection, 'root');
543
+ await connection.transaction(async (transaction) => {
544
+ await record(transaction, 'composed');
545
+ await expect(record(transaction, 'invalid composed')).rejects.toThrow('rejected');
546
+ });
547
+ await expect(labels(database)).resolves.toEqual(['root', 'composed']);
548
+ });
549
+ });
550
+
551
+ const HISTORY_TABLE = `CREATE TABLE IF NOT EXISTS migration_history (
552
+ version INTEGER PRIMARY KEY NOT NULL,
553
+ name TEXT NOT NULL
554
+ )`;
555
+
556
+ async function assertNotNewer(
557
+ connection: ExpoSqliteConnection,
558
+ steps: readonly SqliteMigrationStep[],
559
+ ): Promise<void> {
560
+ const row = await connection.get<VersionRow>(
561
+ 'SELECT max(version) AS version FROM migration_history',
562
+ );
563
+ const known = Math.max(0, ...steps.map((step) => step.version));
564
+ if ((row?.version ?? 0) > known) {
565
+ throw new Error(`database version ${String(row?.version)} is newer than ${String(known)}`);
566
+ }
567
+ }
568
+
569
+ const connectionRunner: SqliteMigrationConformanceAdapter = {
570
+ migrate: async (database, steps) => {
571
+ const connection = new ExpoSqliteConnection(database);
572
+ await connection.exec(HISTORY_TABLE);
573
+ await assertNotNewer(connection, steps);
574
+ const rows = await connection.all<VersionRow>('SELECT version FROM migration_history');
575
+ const applied = new Set(rows.map((row) => row.version));
576
+ const pending = [...steps]
577
+ .sort((left, right) => left.version - right.version)
578
+ .filter((step) => !applied.has(step.version));
579
+ for (const step of pending) {
580
+ await connection.transaction(async (transaction) => {
581
+ await transaction.exec(step.sql);
582
+ await transaction.run(
583
+ 'INSERT INTO migration_history (version, name) VALUES (?, ?)',
584
+ step.version,
585
+ step.name,
586
+ );
587
+ });
588
+ }
589
+ },
590
+ };
591
+
592
+ describe('createSqliteMigrationConformanceTests with a history runner on ExpoSqliteConnection', () => {
593
+ for (const testCase of createSqliteMigrationConformanceTests(connectionRunner)) {
594
+ it(testCase.name, testCase.run);
595
+ }
596
+ });
597
+
598
+ /**
599
+ * Applies every pending step inside one transaction, each in its own nested transaction. A failed
600
+ * step rolls back alone; the steps before it commit and the failure is rethrown.
601
+ */
602
+ const savepointRunner: SqliteMigrationConformanceAdapter = {
603
+ migrate: async (database, steps) => {
604
+ const connection = new ExpoSqliteConnection(database);
605
+ await connection.exec(HISTORY_TABLE);
606
+ await assertNotNewer(connection, steps);
607
+ const rows = await connection.all<VersionRow>('SELECT version FROM migration_history');
608
+ const applied = new Set(rows.map((row) => row.version));
609
+ const pending = [...steps]
610
+ .sort((left, right) => left.version - right.version)
611
+ .filter((step) => !applied.has(step.version));
612
+ const failure = await connection.transaction(async (transaction) => {
613
+ for (const step of pending) {
614
+ try {
615
+ await transaction.transaction(async (nested) => {
616
+ await nested.exec(step.sql);
617
+ await nested.run(
618
+ 'INSERT INTO migration_history (version, name) VALUES (?, ?)',
619
+ step.version,
620
+ step.name,
621
+ );
622
+ });
623
+ } catch (cause) {
624
+ return cause instanceof Error ? cause : new Error(String(cause));
625
+ }
626
+ }
627
+ return undefined;
628
+ });
629
+ if (failure !== undefined) {
630
+ throw failure;
631
+ }
632
+ },
633
+ };
634
+
635
+ describe('createSqliteMigrationConformanceTests with one savepoint per step on ExpoSqliteConnection', () => {
636
+ for (const testCase of createSqliteMigrationConformanceTests(savepointRunner)) {
637
+ it(testCase.name, testCase.run);
638
+ }
639
+
640
+ it('keeps the steps before a failed one', async () => {
641
+ const database = openDatabase();
642
+ const steps: SqliteMigrationStep[] = [
643
+ { version: 1, name: 'events', sql: CREATE_EVENTS },
644
+ { version: 2, name: 'broken', sql: 'CREATE TABLE partial (id TEXT); SELECT * FROM missing' },
645
+ ];
646
+ await expect(savepointRunner.migrate(database, steps)).rejects.toThrow('no such table');
647
+ await expect(
648
+ database.getAllAsync('SELECT version FROM migration_history ORDER BY version'),
649
+ ).resolves.toEqual([{ version: 1 }]);
650
+ await expect(
651
+ database.getAllAsync("SELECT name FROM sqlite_master WHERE name IN ('events', 'partial')"),
652
+ ).resolves.toEqual([{ name: 'events' }]);
653
+ });
654
+ });