@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 +3 -2
- package/src/connection.test.ts +654 -0
- package/src/connection.ts +253 -0
- package/src/index.test.ts +673 -0
- package/src/index.ts +164 -0
- package/src/migration-conformance.test.ts +171 -0
- package/src/migration-conformance.ts +281 -0
- package/src/node-sqlite.test.ts +195 -0
- package/src/node-sqlite.ts +205 -0
- package/src/operation-queue.test.ts +68 -0
- package/src/operation-queue.ts +42 -0
- package/src/queued-database.ts +86 -0
- package/src/statements.ts +328 -0
- package/src/testing.ts +7 -0
|
@@ -0,0 +1,673 @@
|
|
|
1
|
+
import type { JsonValue } from '@baukit/data-contracts';
|
|
2
|
+
import type { ContractTestRecord } from '@baukit/data-contracts/vitest';
|
|
3
|
+
import {
|
|
4
|
+
describeKeyValueContract,
|
|
5
|
+
describeRecordStoreContract,
|
|
6
|
+
describeSchemaMetadataContract,
|
|
7
|
+
describeScopedPersistenceContract,
|
|
8
|
+
describeTransactionalStorageContract,
|
|
9
|
+
} from '@baukit/data-contracts/vitest';
|
|
10
|
+
import type { SQLiteDatabase } from 'expo-sqlite';
|
|
11
|
+
import { afterEach, describe, expect, it } from 'vitest';
|
|
12
|
+
|
|
13
|
+
import { ExpoSqliteStore, SqliteRecordStore } from './index.js';
|
|
14
|
+
|
|
15
|
+
interface FakeRow {
|
|
16
|
+
readonly namespace: string;
|
|
17
|
+
readonly id: string;
|
|
18
|
+
payload: string;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
interface FakeState {
|
|
22
|
+
readonly records: Map<string, FakeRow>;
|
|
23
|
+
readonly keyValues: Map<string, string>;
|
|
24
|
+
readonly schemaMetadata: Map<string, { readonly name: string; readonly version: number }>;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
type ConnectionRole = 'root' | 'transaction';
|
|
28
|
+
|
|
29
|
+
interface Signal {
|
|
30
|
+
readonly promise: Promise<void>;
|
|
31
|
+
readonly resolve: () => void;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
interface Pause {
|
|
35
|
+
readonly started: Promise<void>;
|
|
36
|
+
release(): void;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function signal(): Signal {
|
|
40
|
+
let resolve = (): void => undefined;
|
|
41
|
+
const promise = new Promise<void>((done) => {
|
|
42
|
+
resolve = done;
|
|
43
|
+
});
|
|
44
|
+
return { promise, resolve };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function flush(): Promise<void> {
|
|
48
|
+
return new Promise((resolve) => {
|
|
49
|
+
setImmediate(resolve);
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function emptyState(): FakeState {
|
|
54
|
+
return {
|
|
55
|
+
records: new Map(),
|
|
56
|
+
keyValues: new Map(),
|
|
57
|
+
schemaMetadata: new Map(),
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function copyState(state: FakeState): FakeState {
|
|
62
|
+
return {
|
|
63
|
+
records: new Map([...state.records].map(([key, value]) => [key, { ...value }])),
|
|
64
|
+
keyValues: new Map(state.keyValues),
|
|
65
|
+
schemaMetadata: new Map([...state.schemaMetadata].map(([key, value]) => [key, { ...value }])),
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function replaceState(target: FakeState, source: FakeState): void {
|
|
70
|
+
target.records.clear();
|
|
71
|
+
target.keyValues.clear();
|
|
72
|
+
target.schemaMetadata.clear();
|
|
73
|
+
for (const [key, value] of source.records) target.records.set(key, value);
|
|
74
|
+
for (const [key, value] of source.keyValues) target.keyValues.set(key, value);
|
|
75
|
+
for (const [key, value] of source.schemaMetadata) target.schemaMetadata.set(key, value);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function databaseLocked(): Error {
|
|
79
|
+
return new Error('database is locked');
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* One SQLite file shared by every fake connection opened on it. Like real SQLite without a busy
|
|
84
|
+
* timeout, a statement on a root connection fails while another connection holds an exclusive
|
|
85
|
+
* transaction, and a transaction cannot begin while a root statement is in flight.
|
|
86
|
+
*/
|
|
87
|
+
class FakeSqliteFile {
|
|
88
|
+
public readonly state = emptyState();
|
|
89
|
+
public statementAttempts = 0;
|
|
90
|
+
private rootStatements = 0;
|
|
91
|
+
private transactionOpen = false;
|
|
92
|
+
private readonly pauses: { readonly started: () => void; readonly gate: Promise<void> }[] = [];
|
|
93
|
+
private readonly failures: unknown[] = [];
|
|
94
|
+
|
|
95
|
+
public pauseNextStatement(): Pause {
|
|
96
|
+
const started = signal();
|
|
97
|
+
const gate = signal();
|
|
98
|
+
this.pauses.push({ started: started.resolve, gate: gate.promise });
|
|
99
|
+
return { started: started.promise, release: gate.resolve };
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
public failNextStatement(cause: unknown): void {
|
|
103
|
+
this.failures.push(cause);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
public async runStatement<TResult>(
|
|
107
|
+
role: ConnectionRole,
|
|
108
|
+
execute: () => TResult,
|
|
109
|
+
): Promise<TResult> {
|
|
110
|
+
this.statementAttempts += 1;
|
|
111
|
+
this.acquire(role);
|
|
112
|
+
try {
|
|
113
|
+
await this.pauseOrYield();
|
|
114
|
+
if (this.failures.length > 0) {
|
|
115
|
+
throw this.failures.shift();
|
|
116
|
+
}
|
|
117
|
+
return execute();
|
|
118
|
+
} finally {
|
|
119
|
+
this.release(role);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
public beginTransaction(): void {
|
|
124
|
+
if (this.transactionOpen || this.rootStatements > 0) {
|
|
125
|
+
throw databaseLocked();
|
|
126
|
+
}
|
|
127
|
+
this.transactionOpen = true;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
public endTransaction(): void {
|
|
131
|
+
this.transactionOpen = false;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
private acquire(role: ConnectionRole): void {
|
|
135
|
+
if (role === 'transaction') return;
|
|
136
|
+
if (this.transactionOpen) {
|
|
137
|
+
throw databaseLocked();
|
|
138
|
+
}
|
|
139
|
+
this.rootStatements += 1;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
private release(role: ConnectionRole): void {
|
|
143
|
+
if (role === 'root') this.rootStatements -= 1;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
private async pauseOrYield(): Promise<void> {
|
|
147
|
+
const pause = this.pauses.shift();
|
|
148
|
+
if (pause === undefined) {
|
|
149
|
+
await Promise.resolve();
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
pause.started();
|
|
153
|
+
await pause.gate;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
class FakeSQLiteConnection {
|
|
158
|
+
public constructor(
|
|
159
|
+
public readonly file: FakeSqliteFile,
|
|
160
|
+
private readonly role: ConnectionRole,
|
|
161
|
+
private readonly state: FakeState,
|
|
162
|
+
) {}
|
|
163
|
+
|
|
164
|
+
public execAsync(source: string): Promise<void> {
|
|
165
|
+
return this.file.runStatement(this.role, () => {
|
|
166
|
+
if (!source.startsWith('CREATE TABLE')) {
|
|
167
|
+
throw new Error('Unexpected fake SQLite statement.');
|
|
168
|
+
}
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
public runAsync(source: string, ...params: unknown[]): Promise<unknown> {
|
|
173
|
+
return this.file.runStatement(this.role, () => {
|
|
174
|
+
this.apply(source, params);
|
|
175
|
+
return {};
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
public getFirstAsync<T>(source: string, ...params: unknown[]): Promise<T | null> {
|
|
180
|
+
return this.file.runStatement(this.role, () => this.first(source, params) as T | null);
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
public getAllAsync<T>(_source: string, ...params: unknown[]): Promise<T[]> {
|
|
184
|
+
const namespace = params[0] as string;
|
|
185
|
+
const afterId = params[1] as string;
|
|
186
|
+
const limit = params[2] as number;
|
|
187
|
+
return this.file.runStatement(this.role, () =>
|
|
188
|
+
[...this.state.records.values()]
|
|
189
|
+
.filter((row) => row.namespace === namespace && row.id > afterId)
|
|
190
|
+
.sort((left, right) => (left.id < right.id ? -1 : left.id > right.id ? 1 : 0))
|
|
191
|
+
.slice(0, limit)
|
|
192
|
+
.map((row) => ({ id: row.id, payload: row.payload }) as T),
|
|
193
|
+
);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
private apply(source: string, params: unknown[]): void {
|
|
197
|
+
const namespace = params[0] as string;
|
|
198
|
+
if (source.startsWith('INSERT INTO baukit_records')) {
|
|
199
|
+
const id = params[1] as string;
|
|
200
|
+
this.state.records.set(`${namespace}\0${id}`, {
|
|
201
|
+
namespace,
|
|
202
|
+
id,
|
|
203
|
+
payload: params[2] as string,
|
|
204
|
+
});
|
|
205
|
+
} else if (source.startsWith('DELETE FROM baukit_records')) {
|
|
206
|
+
this.state.records.delete(`${namespace}\0${params[1] as string}`);
|
|
207
|
+
} else if (source.startsWith('INSERT INTO baukit_key_values')) {
|
|
208
|
+
this.state.keyValues.set(`${namespace}\0${params[1] as string}`, params[2] as string);
|
|
209
|
+
} else if (source === 'DELETE FROM baukit_key_values WHERE namespace = ?') {
|
|
210
|
+
this.deleteKeyValues(`${namespace}\0`);
|
|
211
|
+
} else if (source.includes('substr(CAST(key AS BLOB)')) {
|
|
212
|
+
this.deleteKeyValues(`${namespace}\0${params[2] as string}`);
|
|
213
|
+
} else if (source.startsWith('DELETE FROM baukit_key_values')) {
|
|
214
|
+
this.state.keyValues.delete(`${namespace}\0${params[1] as string}`);
|
|
215
|
+
} else if (source.startsWith('INSERT INTO baukit_schema_metadata')) {
|
|
216
|
+
this.state.schemaMetadata.set(namespace, {
|
|
217
|
+
name: params[1] as string,
|
|
218
|
+
version: params[2] as number,
|
|
219
|
+
});
|
|
220
|
+
} else {
|
|
221
|
+
throw new Error(`Unexpected fake SQLite statement: ${source}`);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
private deleteKeyValues(prefix: string): void {
|
|
226
|
+
for (const key of [...this.state.keyValues.keys()]) {
|
|
227
|
+
if (key.startsWith(prefix)) {
|
|
228
|
+
this.state.keyValues.delete(key);
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
private first(source: string, params: unknown[]): unknown {
|
|
234
|
+
const namespace = params[0] as string;
|
|
235
|
+
if (source.includes('FROM baukit_records')) {
|
|
236
|
+
const row = this.state.records.get(`${namespace}\0${params[1] as string}`);
|
|
237
|
+
return row === undefined ? null : { id: row.id, payload: row.payload };
|
|
238
|
+
}
|
|
239
|
+
if (source.includes('FROM baukit_key_values')) {
|
|
240
|
+
const payload = this.state.keyValues.get(`${namespace}\0${params[1] as string}`);
|
|
241
|
+
return payload === undefined ? null : { payload };
|
|
242
|
+
}
|
|
243
|
+
if (source.includes('FROM baukit_schema_metadata')) {
|
|
244
|
+
return this.state.schemaMetadata.get(namespace) ?? null;
|
|
245
|
+
}
|
|
246
|
+
throw new Error(`Unexpected fake SQLite statement: ${source}`);
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
let fakePathSequence = 0;
|
|
251
|
+
|
|
252
|
+
function uniquePath(): string {
|
|
253
|
+
fakePathSequence += 1;
|
|
254
|
+
return `/fake/database-${String(fakePathSequence)}.db`;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
class FakeSQLiteDatabase extends FakeSQLiteConnection {
|
|
258
|
+
public closeCount = 0;
|
|
259
|
+
private closeFailure: Error | undefined;
|
|
260
|
+
|
|
261
|
+
public constructor(
|
|
262
|
+
file: FakeSqliteFile = new FakeSqliteFile(),
|
|
263
|
+
public readonly databasePath: string = uniquePath(),
|
|
264
|
+
) {
|
|
265
|
+
super(file, 'root', file.state);
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
public get rows(): Map<string, FakeRow> {
|
|
269
|
+
return this.file.state.records;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
public async withExclusiveTransactionAsync(
|
|
273
|
+
task: (transaction: FakeSQLiteConnection) => Promise<void>,
|
|
274
|
+
): Promise<void> {
|
|
275
|
+
this.file.beginTransaction();
|
|
276
|
+
try {
|
|
277
|
+
const pending = copyState(this.file.state);
|
|
278
|
+
await task(new FakeSQLiteConnection(this.file, 'transaction', pending));
|
|
279
|
+
replaceState(this.file.state, pending);
|
|
280
|
+
} finally {
|
|
281
|
+
this.file.endTransaction();
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
public failClose(cause: Error): void {
|
|
286
|
+
this.closeFailure = cause;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
public closeAsync(): Promise<void> {
|
|
290
|
+
this.closeCount += 1;
|
|
291
|
+
return this.closeFailure === undefined ? Promise.resolve() : Promise.reject(this.closeFailure);
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
function sqlite(database: FakeSQLiteDatabase): SQLiteDatabase {
|
|
296
|
+
return database as unknown as SQLiteDatabase;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
async function makeRecordStore(): Promise<SqliteRecordStore<ContractTestRecord>> {
|
|
300
|
+
const store = new SqliteRecordStore<ContractTestRecord>(
|
|
301
|
+
sqlite(new FakeSQLiteDatabase()),
|
|
302
|
+
'contract',
|
|
303
|
+
);
|
|
304
|
+
await store.initialize();
|
|
305
|
+
return store;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
const compositeStores: ExpoSqliteStore<ContractTestRecord>[] = [];
|
|
309
|
+
|
|
310
|
+
async function openCompositeStore(
|
|
311
|
+
database: FakeSQLiteDatabase = new FakeSQLiteDatabase(),
|
|
312
|
+
namespace = 'contract',
|
|
313
|
+
closeDatabase = false,
|
|
314
|
+
): Promise<ExpoSqliteStore<ContractTestRecord>> {
|
|
315
|
+
const store = new ExpoSqliteStore<ContractTestRecord>(sqlite(database), namespace, {
|
|
316
|
+
closeDatabase,
|
|
317
|
+
});
|
|
318
|
+
await store.initialize();
|
|
319
|
+
compositeStores.push(store);
|
|
320
|
+
return store;
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
function makeCompositeStore(): Promise<ExpoSqliteStore<ContractTestRecord>> {
|
|
324
|
+
return openCompositeStore();
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
afterEach(async () => {
|
|
328
|
+
await Promise.allSettled(compositeStores.splice(0).map((store) => store.close()));
|
|
329
|
+
});
|
|
330
|
+
|
|
331
|
+
describeRecordStoreContract(makeRecordStore);
|
|
332
|
+
describeKeyValueContract(async () => (await makeCompositeStore()).keyValues);
|
|
333
|
+
describeSchemaMetadataContract(async () => (await makeCompositeStore()).schemaMetadata);
|
|
334
|
+
describeTransactionalStorageContract(makeCompositeStore);
|
|
335
|
+
describeScopedPersistenceContract(() => {
|
|
336
|
+
const files = new Map<string, FakeSqliteFile>();
|
|
337
|
+
return {
|
|
338
|
+
open: (storeName) => {
|
|
339
|
+
let file = files.get(storeName);
|
|
340
|
+
if (file === undefined) {
|
|
341
|
+
file = new FakeSqliteFile();
|
|
342
|
+
files.set(storeName, file);
|
|
343
|
+
}
|
|
344
|
+
return openCompositeStore(new FakeSQLiteDatabase(file, `/fake/${storeName}.db`));
|
|
345
|
+
},
|
|
346
|
+
};
|
|
347
|
+
});
|
|
348
|
+
|
|
349
|
+
describe('SQLite adapters', () => {
|
|
350
|
+
it('isolates records in separate namespaces sharing a database', async () => {
|
|
351
|
+
const database = new FakeSQLiteDatabase();
|
|
352
|
+
const first = new SqliteRecordStore<ContractTestRecord>(sqlite(database), 'first');
|
|
353
|
+
const second = new SqliteRecordStore<ContractTestRecord>(sqlite(database), 'second');
|
|
354
|
+
await first.initialize();
|
|
355
|
+
await first.put({ id: 'same', label: 'first', payload: 1 });
|
|
356
|
+
await second.put({ id: 'same', label: 'second', payload: 2 });
|
|
357
|
+
await expect(first.get('same')).resolves.toMatchObject({ label: 'first' });
|
|
358
|
+
await expect(second.get('same')).resolves.toMatchObject({ label: 'second' });
|
|
359
|
+
});
|
|
360
|
+
|
|
361
|
+
it('does not include malformed private payload content in errors', async () => {
|
|
362
|
+
const database = new FakeSQLiteDatabase();
|
|
363
|
+
database.rows.set('private\0record', {
|
|
364
|
+
namespace: 'private',
|
|
365
|
+
id: 'record',
|
|
366
|
+
payload: 'private journal content {',
|
|
367
|
+
});
|
|
368
|
+
const store = new SqliteRecordStore<ContractTestRecord>(sqlite(database), 'private');
|
|
369
|
+
let caught: unknown;
|
|
370
|
+
try {
|
|
371
|
+
await store.get('record');
|
|
372
|
+
} catch (cause) {
|
|
373
|
+
caught = cause;
|
|
374
|
+
}
|
|
375
|
+
expect(caught).toBeInstanceOf(TypeError);
|
|
376
|
+
expect((caught as Error).message).toBe('The local database contains an invalid record.');
|
|
377
|
+
expect((caught as Error).message).not.toContain('journal');
|
|
378
|
+
});
|
|
379
|
+
|
|
380
|
+
it('round-trips JSON key/value shapes in the fake native harness', async () => {
|
|
381
|
+
const store = await makeCompositeStore();
|
|
382
|
+
const value: JsonValue = { nested: [true, null, 'value'] };
|
|
383
|
+
await store.keyValues.set('json', value);
|
|
384
|
+
await expect(store.keyValues.get('json')).resolves.toEqual(value);
|
|
385
|
+
});
|
|
386
|
+
});
|
|
387
|
+
|
|
388
|
+
const RECORD: ContractTestRecord = { id: 'record', label: 'queued', payload: 1 };
|
|
389
|
+
|
|
390
|
+
type Store = ExpoSqliteStore<ContractTestRecord>;
|
|
391
|
+
|
|
392
|
+
const ROOT_OPERATIONS: readonly (readonly [string, (store: Store) => Promise<unknown>])[] = [
|
|
393
|
+
['record write', (store) => store.records.put(RECORD)],
|
|
394
|
+
['record read', (store) => store.records.get(RECORD.id)],
|
|
395
|
+
['record list', (store) => store.records.list()],
|
|
396
|
+
['key/value write', (store) => store.keyValues.set('key', 'value')],
|
|
397
|
+
['key/value read', (store) => store.keyValues.get('key')],
|
|
398
|
+
[
|
|
399
|
+
'schema metadata write',
|
|
400
|
+
(store) => store.schemaMetadata.setSchemaMeta({ name: 's', version: 1 }),
|
|
401
|
+
],
|
|
402
|
+
['schema metadata read', (store) => store.schemaMetadata.getSchemaMeta()],
|
|
403
|
+
];
|
|
404
|
+
|
|
405
|
+
interface HeldTransaction {
|
|
406
|
+
readonly done: Promise<void>;
|
|
407
|
+
release(): void;
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
async function holdTransaction(store: Store): Promise<HeldTransaction> {
|
|
411
|
+
const entered = signal();
|
|
412
|
+
const gate = signal();
|
|
413
|
+
const done = store.withTransaction(async (transaction) => {
|
|
414
|
+
await transaction.keyValues.set('held', true);
|
|
415
|
+
entered.resolve();
|
|
416
|
+
await gate.promise;
|
|
417
|
+
});
|
|
418
|
+
await entered.promise;
|
|
419
|
+
return { done, release: gate.resolve };
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
function track(operation: Promise<unknown>): { readonly settled: () => boolean } {
|
|
423
|
+
let settled = false;
|
|
424
|
+
void operation.then(
|
|
425
|
+
() => {
|
|
426
|
+
settled = true;
|
|
427
|
+
},
|
|
428
|
+
() => {
|
|
429
|
+
settled = true;
|
|
430
|
+
},
|
|
431
|
+
);
|
|
432
|
+
return { settled: () => settled };
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
describe('ExpoSqliteStore operation serialization', () => {
|
|
436
|
+
it.each(ROOT_OPERATIONS)(
|
|
437
|
+
'starts a transaction only after an active %s finishes',
|
|
438
|
+
async (_name, operation) => {
|
|
439
|
+
const database = new FakeSQLiteDatabase();
|
|
440
|
+
const store = await openCompositeStore(database);
|
|
441
|
+
const pause = database.file.pauseNextStatement();
|
|
442
|
+
const root = operation(store);
|
|
443
|
+
await pause.started;
|
|
444
|
+
|
|
445
|
+
let transactionStarted = false;
|
|
446
|
+
const transaction = store.withTransaction(async (context) => {
|
|
447
|
+
transactionStarted = true;
|
|
448
|
+
await context.keyValues.set('after', 'root');
|
|
449
|
+
});
|
|
450
|
+
await flush();
|
|
451
|
+
const startedEarly = transactionStarted;
|
|
452
|
+
pause.release();
|
|
453
|
+
|
|
454
|
+
await root;
|
|
455
|
+
await expect(transaction).resolves.toBeUndefined();
|
|
456
|
+
expect(startedEarly).toBe(false);
|
|
457
|
+
await expect(store.keyValues.get('after')).resolves.toBe('root');
|
|
458
|
+
},
|
|
459
|
+
);
|
|
460
|
+
|
|
461
|
+
it.each(ROOT_OPERATIONS)(
|
|
462
|
+
'runs a %s only after an active transaction commits',
|
|
463
|
+
async (_name, operation) => {
|
|
464
|
+
const store = await openCompositeStore();
|
|
465
|
+
const held = await holdTransaction(store);
|
|
466
|
+
|
|
467
|
+
const root = operation(store);
|
|
468
|
+
const progress = track(root);
|
|
469
|
+
await flush();
|
|
470
|
+
const settledEarly = progress.settled();
|
|
471
|
+
held.release();
|
|
472
|
+
|
|
473
|
+
await expect(held.done).resolves.toBeUndefined();
|
|
474
|
+
await root;
|
|
475
|
+
expect(settledEarly).toBe(false);
|
|
476
|
+
await expect(store.keyValues.get('held')).resolves.toBe(true);
|
|
477
|
+
},
|
|
478
|
+
);
|
|
479
|
+
|
|
480
|
+
it('orders initialize with a transaction that arrives first', async () => {
|
|
481
|
+
const database = new FakeSQLiteDatabase();
|
|
482
|
+
const store = await openCompositeStore(database);
|
|
483
|
+
const held = await holdTransaction(store);
|
|
484
|
+
const initialize = store.initialize();
|
|
485
|
+
const progress = track(initialize);
|
|
486
|
+
await flush();
|
|
487
|
+
expect(progress.settled()).toBe(false);
|
|
488
|
+
held.release();
|
|
489
|
+
await expect(initialize).resolves.toBeUndefined();
|
|
490
|
+
});
|
|
491
|
+
|
|
492
|
+
it('releases the queue after a rejected root operation', async () => {
|
|
493
|
+
const database = new FakeSQLiteDatabase();
|
|
494
|
+
const store = await openCompositeStore(database);
|
|
495
|
+
const failure = new Error('disk I/O error');
|
|
496
|
+
database.file.failNextStatement(failure);
|
|
497
|
+
|
|
498
|
+
const failed = store.records.get(RECORD.id);
|
|
499
|
+
const queued = store.records.put(RECORD);
|
|
500
|
+
|
|
501
|
+
await expect(failed).rejects.toBe(failure);
|
|
502
|
+
await expect(queued).resolves.toBeUndefined();
|
|
503
|
+
await expect(store.records.get(RECORD.id)).resolves.toEqual(RECORD);
|
|
504
|
+
});
|
|
505
|
+
|
|
506
|
+
it('rolls back a rejected transaction and releases the queue', async () => {
|
|
507
|
+
const store = await openCompositeStore();
|
|
508
|
+
const failed = store.withTransaction(async (transaction) => {
|
|
509
|
+
await transaction.records.put(RECORD);
|
|
510
|
+
throw new Error('rollback');
|
|
511
|
+
});
|
|
512
|
+
const queued = store.records.get(RECORD.id);
|
|
513
|
+
|
|
514
|
+
await expect(failed).rejects.toThrow('rollback');
|
|
515
|
+
await expect(queued).resolves.toBeUndefined();
|
|
516
|
+
await expect(store.records.put(RECORD)).resolves.toBeUndefined();
|
|
517
|
+
});
|
|
518
|
+
|
|
519
|
+
it('surfaces a lock error unchanged without retrying the statement', async () => {
|
|
520
|
+
const database = new FakeSQLiteDatabase();
|
|
521
|
+
const store = await openCompositeStore(database);
|
|
522
|
+
const locked = databaseLocked();
|
|
523
|
+
database.file.failNextStatement(locked);
|
|
524
|
+
const attemptsBefore = database.file.statementAttempts;
|
|
525
|
+
|
|
526
|
+
await expect(store.keyValues.set('key', 'value')).rejects.toBe(locked);
|
|
527
|
+
expect(database.file.statementAttempts - attemptsBefore).toBe(1);
|
|
528
|
+
await expect(store.keyValues.get('key')).resolves.toBeUndefined();
|
|
529
|
+
});
|
|
530
|
+
|
|
531
|
+
it('keeps nested transaction work on the transaction connection', async () => {
|
|
532
|
+
const store = await openCompositeStore();
|
|
533
|
+
const queuedBehind = store.keyValues.set('after', 'nested');
|
|
534
|
+
|
|
535
|
+
await store.withTransaction((transaction) =>
|
|
536
|
+
transaction.withTransaction(async (nested) => {
|
|
537
|
+
await nested.records.put(RECORD);
|
|
538
|
+
await nested.keyValues.set('nested', true);
|
|
539
|
+
await nested.schemaMetadata.setSchemaMeta({ name: 'nested', version: 2 });
|
|
540
|
+
return nested.withTransaction((deeper) => deeper.records.get(RECORD.id));
|
|
541
|
+
}),
|
|
542
|
+
);
|
|
543
|
+
|
|
544
|
+
await expect(queuedBehind).resolves.toBeUndefined();
|
|
545
|
+
await expect(store.records.get(RECORD.id)).resolves.toEqual(RECORD);
|
|
546
|
+
await expect(store.schemaMetadata.getSchemaMeta()).resolves.toEqual({
|
|
547
|
+
name: 'nested',
|
|
548
|
+
version: 2,
|
|
549
|
+
});
|
|
550
|
+
});
|
|
551
|
+
|
|
552
|
+
it('drains accepted work before closing and rejects later calls', async () => {
|
|
553
|
+
const database = new FakeSQLiteDatabase();
|
|
554
|
+
const store = await openCompositeStore(database, 'contract', true);
|
|
555
|
+
const pause = database.file.pauseNextStatement();
|
|
556
|
+
const write = store.records.put(RECORD);
|
|
557
|
+
await pause.started;
|
|
558
|
+
const acceptedTransaction = store.withTransaction((transaction) =>
|
|
559
|
+
transaction.keyValues.set('accepted', true),
|
|
560
|
+
);
|
|
561
|
+
|
|
562
|
+
const close = store.close();
|
|
563
|
+
const repeatedClose = store.close();
|
|
564
|
+
const progress = track(close);
|
|
565
|
+
await expect(store.records.get(RECORD.id)).rejects.toMatchObject({ code: 'storage_closed' });
|
|
566
|
+
await expect(store.withTransaction(() => undefined)).rejects.toMatchObject({
|
|
567
|
+
code: 'storage_closed',
|
|
568
|
+
});
|
|
569
|
+
await expect(store.initialize()).rejects.toMatchObject({ code: 'storage_closed' });
|
|
570
|
+
await flush();
|
|
571
|
+
const closedEarly = progress.settled();
|
|
572
|
+
pause.release();
|
|
573
|
+
|
|
574
|
+
await expect(write).resolves.toBeUndefined();
|
|
575
|
+
await expect(acceptedTransaction).resolves.toBeUndefined();
|
|
576
|
+
await expect(close).resolves.toBeUndefined();
|
|
577
|
+
expect(repeatedClose).toBe(close);
|
|
578
|
+
expect(closedEarly).toBe(false);
|
|
579
|
+
expect(database.closeCount).toBe(1);
|
|
580
|
+
expect(database.file.state.keyValues.get('contract\0accepted')).toBe('true');
|
|
581
|
+
await expect(store.keyValues.get('accepted')).rejects.toMatchObject({
|
|
582
|
+
code: 'storage_closed',
|
|
583
|
+
});
|
|
584
|
+
});
|
|
585
|
+
|
|
586
|
+
it('shares one failed close result and closes the database once', async () => {
|
|
587
|
+
const database = new FakeSQLiteDatabase();
|
|
588
|
+
const store = await openCompositeStore(database, 'contract', true);
|
|
589
|
+
const failure = new Error('close failed');
|
|
590
|
+
database.failClose(failure);
|
|
591
|
+
|
|
592
|
+
const close = store.close();
|
|
593
|
+
const repeatedClose = store.close();
|
|
594
|
+
|
|
595
|
+
expect(repeatedClose).toBe(close);
|
|
596
|
+
await expect(close).rejects.toBe(failure);
|
|
597
|
+
await expect(store.close()).rejects.toBe(failure);
|
|
598
|
+
expect(database.closeCount).toBe(1);
|
|
599
|
+
await expect(store.keyValues.get('key')).rejects.toMatchObject({ code: 'storage_closed' });
|
|
600
|
+
});
|
|
601
|
+
|
|
602
|
+
it('leaves a supplied database open unless the adapter owns it', async () => {
|
|
603
|
+
const database = new FakeSQLiteDatabase();
|
|
604
|
+
const store = await openCompositeStore(database);
|
|
605
|
+
await store.close();
|
|
606
|
+
expect(database.closeCount).toBe(0);
|
|
607
|
+
});
|
|
608
|
+
});
|
|
609
|
+
|
|
610
|
+
describe('shared database coordination', () => {
|
|
611
|
+
it('orders stores in different namespaces on one database handle', async () => {
|
|
612
|
+
const database = new FakeSQLiteDatabase();
|
|
613
|
+
const first = await openCompositeStore(database, 'first');
|
|
614
|
+
const second = await openCompositeStore(database, 'second');
|
|
615
|
+
const held = await holdTransaction(first);
|
|
616
|
+
|
|
617
|
+
const write = second.records.put(RECORD);
|
|
618
|
+
const progress = track(write);
|
|
619
|
+
await flush();
|
|
620
|
+
const settledEarly = progress.settled();
|
|
621
|
+
held.release();
|
|
622
|
+
|
|
623
|
+
await expect(write).resolves.toBeUndefined();
|
|
624
|
+
await expect(held.done).resolves.toBeUndefined();
|
|
625
|
+
expect(settledEarly).toBe(false);
|
|
626
|
+
});
|
|
627
|
+
|
|
628
|
+
it('orders stores on separate handles to the same database file', async () => {
|
|
629
|
+
const file = new FakeSqliteFile();
|
|
630
|
+
const first = await openCompositeStore(new FakeSQLiteDatabase(file, '/fake/shared.db'));
|
|
631
|
+
const second = await openCompositeStore(new FakeSQLiteDatabase(file, '/fake/shared.db'));
|
|
632
|
+
const held = await holdTransaction(first);
|
|
633
|
+
|
|
634
|
+
const read = second.keyValues.get('held');
|
|
635
|
+
const progress = track(read);
|
|
636
|
+
await flush();
|
|
637
|
+
const settledEarly = progress.settled();
|
|
638
|
+
held.release();
|
|
639
|
+
|
|
640
|
+
await expect(read).resolves.toBe(true);
|
|
641
|
+
expect(settledEarly).toBe(false);
|
|
642
|
+
});
|
|
643
|
+
|
|
644
|
+
it('orders a standalone record store with a transaction on the same database', async () => {
|
|
645
|
+
const database = new FakeSQLiteDatabase();
|
|
646
|
+
const store = await openCompositeStore(database);
|
|
647
|
+
const records = new SqliteRecordStore<ContractTestRecord>(sqlite(database), 'standalone');
|
|
648
|
+
await records.initialize();
|
|
649
|
+
const held = await holdTransaction(store);
|
|
650
|
+
|
|
651
|
+
const write = records.put(RECORD);
|
|
652
|
+
const progress = track(write);
|
|
653
|
+
await flush();
|
|
654
|
+
const settledEarly = progress.settled();
|
|
655
|
+
held.release();
|
|
656
|
+
|
|
657
|
+
await expect(write).resolves.toBeUndefined();
|
|
658
|
+
expect(settledEarly).toBe(false);
|
|
659
|
+
});
|
|
660
|
+
|
|
661
|
+
it('lets independent databases proceed while another holds a transaction', async () => {
|
|
662
|
+
const busy = await openCompositeStore(new FakeSQLiteDatabase());
|
|
663
|
+
const independent = await openCompositeStore(new FakeSQLiteDatabase());
|
|
664
|
+
const held = await holdTransaction(busy);
|
|
665
|
+
|
|
666
|
+
const write = independent.records.put(RECORD);
|
|
667
|
+
await expect(write).resolves.toBeUndefined();
|
|
668
|
+
await expect(independent.withTransaction(() => 'independent')).resolves.toBe('independent');
|
|
669
|
+
|
|
670
|
+
held.release();
|
|
671
|
+
await expect(held.done).resolves.toBeUndefined();
|
|
672
|
+
});
|
|
673
|
+
});
|