@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,195 @@
|
|
|
1
|
+
import { existsSync, mkdtempSync, rmSync } from 'node:fs';
|
|
2
|
+
import { tmpdir } from 'node:os';
|
|
3
|
+
import { dirname, join } from 'node:path';
|
|
4
|
+
|
|
5
|
+
import type { ContractTestRecord } from '@baukit/data-contracts/vitest';
|
|
6
|
+
import {
|
|
7
|
+
describeKeyValueContract,
|
|
8
|
+
describeRecordStoreContract,
|
|
9
|
+
describeSchemaMetadataContract,
|
|
10
|
+
describeScopedPersistenceContract,
|
|
11
|
+
describeTransactionalStorageContract,
|
|
12
|
+
} from '@baukit/data-contracts/vitest';
|
|
13
|
+
import { afterEach, describe, expect, it } from 'vitest';
|
|
14
|
+
|
|
15
|
+
import { ExpoSqliteStore } from './index.js';
|
|
16
|
+
import { NodeSqliteDatabase } from './testing.js';
|
|
17
|
+
|
|
18
|
+
interface ValueRow {
|
|
19
|
+
readonly value: unknown;
|
|
20
|
+
readonly kind: string;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const databases: NodeSqliteDatabase[] = [];
|
|
24
|
+
const directories: string[] = [];
|
|
25
|
+
const stores: ExpoSqliteStore<ContractTestRecord>[] = [];
|
|
26
|
+
|
|
27
|
+
function openDatabase(path?: string): NodeSqliteDatabase {
|
|
28
|
+
const database = new NodeSqliteDatabase(path);
|
|
29
|
+
databases.push(database);
|
|
30
|
+
return database;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function temporaryDirectory(): string {
|
|
34
|
+
const directory = mkdtempSync(join(tmpdir(), 'baukit-node-sqlite-test-'));
|
|
35
|
+
directories.push(directory);
|
|
36
|
+
return directory;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
async function openValuesTable(): Promise<NodeSqliteDatabase> {
|
|
40
|
+
const database = openDatabase();
|
|
41
|
+
await database.execAsync('CREATE TABLE value_table (value ANY) STRICT');
|
|
42
|
+
return database;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
async function storedValue(database: NodeSqliteDatabase): Promise<ValueRow | null> {
|
|
46
|
+
return database.getFirstAsync<ValueRow>(
|
|
47
|
+
'SELECT value, typeof(value) AS kind FROM value_table ORDER BY rowid DESC LIMIT 1',
|
|
48
|
+
);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
async function openStore(
|
|
52
|
+
database: NodeSqliteDatabase,
|
|
53
|
+
): Promise<ExpoSqliteStore<ContractTestRecord>> {
|
|
54
|
+
const store = new ExpoSqliteStore<ContractTestRecord>(database, 'contract', {
|
|
55
|
+
closeDatabase: true,
|
|
56
|
+
});
|
|
57
|
+
await store.initialize();
|
|
58
|
+
stores.push(store);
|
|
59
|
+
return store;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
afterEach(async () => {
|
|
63
|
+
await Promise.allSettled(stores.splice(0).map((store) => store.close()));
|
|
64
|
+
await Promise.allSettled(databases.splice(0).map((database) => database.closeAsync()));
|
|
65
|
+
for (const directory of directories.splice(0)) {
|
|
66
|
+
rmSync(directory, { recursive: true, force: true });
|
|
67
|
+
}
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
describe('NodeSqliteDatabase', () => {
|
|
71
|
+
it('binds variadic, array, and prefixed named parameters', async () => {
|
|
72
|
+
const database = await openValuesTable();
|
|
73
|
+
await database.runAsync('INSERT INTO value_table (value) VALUES (?)', 'variadic');
|
|
74
|
+
await database.runAsync('INSERT INTO value_table (value) VALUES (?)', ['array']);
|
|
75
|
+
await database.runAsync('INSERT INTO value_table (value) VALUES ($value)', { $value: 'named' });
|
|
76
|
+
const rows = await database.getAllAsync<{ readonly value: string }>(
|
|
77
|
+
'SELECT value FROM value_table ORDER BY rowid',
|
|
78
|
+
);
|
|
79
|
+
expect(rows).toEqual([{ value: 'variadic' }, { value: 'array' }, { value: 'named' }]);
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
it('stores booleans and integral numbers as integers, as the native module does', async () => {
|
|
83
|
+
const database = await openValuesTable();
|
|
84
|
+
await database.runAsync('INSERT INTO value_table (value) VALUES (?)', true);
|
|
85
|
+
await expect(storedValue(database)).resolves.toEqual({ value: 1, kind: 'integer' });
|
|
86
|
+
await database.runAsync('INSERT INTO value_table (value) VALUES (?)', 42);
|
|
87
|
+
await expect(storedValue(database)).resolves.toEqual({ value: 42, kind: 'integer' });
|
|
88
|
+
await database.runAsync('INSERT INTO value_table (value) VALUES (?)', 1.5);
|
|
89
|
+
await expect(storedValue(database)).resolves.toEqual({ value: 1.5, kind: 'real' });
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
it('binds undefined as NULL and a single blob as one value', async () => {
|
|
93
|
+
const database = await openValuesTable();
|
|
94
|
+
// @ts-expect-error expo-sqlite's types forbid undefined, but untyped callers can still pass it.
|
|
95
|
+
await database.runAsync('INSERT INTO value_table (value) VALUES (?)', [undefined]);
|
|
96
|
+
await expect(storedValue(database)).resolves.toEqual({ value: null, kind: 'null' });
|
|
97
|
+
await database.runAsync('INSERT INTO value_table (value) VALUES (?)', new Uint8Array([1, 2]));
|
|
98
|
+
await expect(storedValue(database)).resolves.toEqual({
|
|
99
|
+
value: new Uint8Array([1, 2]),
|
|
100
|
+
kind: 'blob',
|
|
101
|
+
});
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
it('requires the prefix on named parameters', async () => {
|
|
105
|
+
const database = await openValuesTable();
|
|
106
|
+
await expect(
|
|
107
|
+
database.runAsync('INSERT INTO value_table (value) VALUES ($value)', { value: 'bare' }),
|
|
108
|
+
).rejects.toThrow();
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
it('returns plain row objects, null for no row, and the run result', async () => {
|
|
112
|
+
const database = await openValuesTable();
|
|
113
|
+
const result = await database.runAsync('INSERT INTO value_table (value) VALUES (?)', 'row');
|
|
114
|
+
expect(result).toEqual({ changes: 1, lastInsertRowId: 1 });
|
|
115
|
+
const row = await database.getFirstAsync('SELECT value FROM value_table');
|
|
116
|
+
expect(Object.getPrototypeOf(row)).toBe(Object.prototype);
|
|
117
|
+
await expect(
|
|
118
|
+
database.getFirstAsync('SELECT value FROM value_table WHERE value = ?', 'absent'),
|
|
119
|
+
).resolves.toBeNull();
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
it('commits an exclusive transaction on a second connection to the same file', async () => {
|
|
123
|
+
const database = await openValuesTable();
|
|
124
|
+
await database.withExclusiveTransactionAsync(async (transaction) => {
|
|
125
|
+
await transaction.runAsync('INSERT INTO value_table (value) VALUES (?)', 'committed');
|
|
126
|
+
});
|
|
127
|
+
await expect(storedValue(database)).resolves.toMatchObject({ value: 'committed' });
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
it('rolls back an exclusive transaction when its task throws', async () => {
|
|
131
|
+
const database = await openValuesTable();
|
|
132
|
+
const failure = new Error('task failed');
|
|
133
|
+
await expect(
|
|
134
|
+
database.withExclusiveTransactionAsync(async (transaction) => {
|
|
135
|
+
await transaction.runAsync('INSERT INTO value_table (value) VALUES (?)', 'discarded');
|
|
136
|
+
throw failure;
|
|
137
|
+
}),
|
|
138
|
+
).rejects.toBe(failure);
|
|
139
|
+
await expect(storedValue(database)).resolves.toBeNull();
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
it('fails a root write that overlaps an open exclusive transaction', async () => {
|
|
143
|
+
const database = await openValuesTable();
|
|
144
|
+
await database.withExclusiveTransactionAsync(async (transaction) => {
|
|
145
|
+
await transaction.runAsync('INSERT INTO value_table (value) VALUES (?)', 'inside');
|
|
146
|
+
await expect(
|
|
147
|
+
database.runAsync('INSERT INTO value_table (value) VALUES (?)', 'outside'),
|
|
148
|
+
).rejects.toThrow('database is locked');
|
|
149
|
+
});
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
it('leaves foreign keys off, including on transaction connections', async () => {
|
|
153
|
+
const database = openDatabase();
|
|
154
|
+
await database.execAsync(`CREATE TABLE parent (id TEXT PRIMARY KEY);
|
|
155
|
+
CREATE TABLE child (id TEXT PRIMARY KEY, parent_id TEXT REFERENCES parent(id));
|
|
156
|
+
PRAGMA foreign_keys = ON;`);
|
|
157
|
+
await database.withExclusiveTransactionAsync(async (transaction) => {
|
|
158
|
+
await transaction.runAsync('INSERT INTO child (id, parent_id) VALUES (?, ?)', 'a', 'none');
|
|
159
|
+
});
|
|
160
|
+
await expect(
|
|
161
|
+
database.runAsync('INSERT INTO child (id, parent_id) VALUES (?, ?)', 'b', 'none'),
|
|
162
|
+
).rejects.toThrow('FOREIGN KEY constraint failed');
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
it('rejects an in-memory path', () => {
|
|
166
|
+
expect(() => new NodeSqliteDatabase(':memory:')).toThrow(TypeError);
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
it('deletes its temporary file on close and keeps a caller-owned file', async () => {
|
|
170
|
+
const owned = new NodeSqliteDatabase();
|
|
171
|
+
await owned.closeAsync();
|
|
172
|
+
expect(existsSync(dirname(owned.databasePath))).toBe(false);
|
|
173
|
+
|
|
174
|
+
const path = join(temporaryDirectory(), 'kept.sqlite');
|
|
175
|
+
const kept = new NodeSqliteDatabase(path);
|
|
176
|
+
await kept.closeAsync();
|
|
177
|
+
expect(existsSync(path)).toBe(true);
|
|
178
|
+
});
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
describe('ExpoSqliteStore on NodeSqliteDatabase', () => {
|
|
182
|
+
const makeStore = (): Promise<ExpoSqliteStore<ContractTestRecord>> =>
|
|
183
|
+
openStore(new NodeSqliteDatabase());
|
|
184
|
+
|
|
185
|
+
describeRecordStoreContract(async () => (await makeStore()).records);
|
|
186
|
+
describeKeyValueContract(async () => (await makeStore()).keyValues);
|
|
187
|
+
describeSchemaMetadataContract(async () => (await makeStore()).schemaMetadata);
|
|
188
|
+
describeTransactionalStorageContract(makeStore);
|
|
189
|
+
describeScopedPersistenceContract(() => {
|
|
190
|
+
const directory = temporaryDirectory();
|
|
191
|
+
return {
|
|
192
|
+
open: (storeName) => openStore(new NodeSqliteDatabase(join(directory, `${storeName}.db`))),
|
|
193
|
+
};
|
|
194
|
+
});
|
|
195
|
+
});
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
import { mkdtempSync, rmSync } from 'node:fs';
|
|
2
|
+
import { tmpdir } from 'node:os';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { DatabaseSync, type SQLInputValue, type StatementSync } from 'node:sqlite';
|
|
5
|
+
|
|
6
|
+
import type { SQLiteBindParams, SQLiteRunResult, SQLiteVariadicBindParams } from 'expo-sqlite';
|
|
7
|
+
|
|
8
|
+
import type { ExpoSqliteDatabase } from './queued-database.js';
|
|
9
|
+
|
|
10
|
+
type NamedValues = Record<string, SQLInputValue>;
|
|
11
|
+
|
|
12
|
+
interface PreparedCall {
|
|
13
|
+
readonly statement: StatementSync;
|
|
14
|
+
readonly named: NamedValues;
|
|
15
|
+
readonly positional: SQLInputValue[];
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
interface DatabaseFile {
|
|
19
|
+
readonly path: string;
|
|
20
|
+
readonly ownedDirectory: string | undefined;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const MEMORY_DATABASE_PATH = ':memory:';
|
|
24
|
+
const TEMPORARY_DIRECTORY_PREFIX = 'baukit-sqlite-';
|
|
25
|
+
const TEMPORARY_DATABASE_FILE = 'database.sqlite';
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Expo opens every native connection with SQLite's compile-time defaults: foreign keys off,
|
|
29
|
+
* double-quoted string literals accepted, and no busy timeout.
|
|
30
|
+
*/
|
|
31
|
+
const EXPO_CONNECTION_OPTIONS = {
|
|
32
|
+
enableForeignKeyConstraints: false,
|
|
33
|
+
enableDoubleQuotedStringLiterals: true,
|
|
34
|
+
timeout: 0,
|
|
35
|
+
} as const;
|
|
36
|
+
|
|
37
|
+
/** Statement methods shared by the root handle and an exclusive transaction connection. */
|
|
38
|
+
export class NodeSqliteConnection {
|
|
39
|
+
public constructor(protected readonly connection: DatabaseSync) {}
|
|
40
|
+
|
|
41
|
+
public async execAsync(source: string): Promise<void> {
|
|
42
|
+
await nextTurn();
|
|
43
|
+
this.connection.exec(source);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
public runAsync(source: string, params: SQLiteBindParams): Promise<SQLiteRunResult>;
|
|
47
|
+
public runAsync(source: string, ...params: SQLiteVariadicBindParams): Promise<SQLiteRunResult>;
|
|
48
|
+
public async runAsync(source: string, ...params: unknown[]): Promise<SQLiteRunResult> {
|
|
49
|
+
await nextTurn();
|
|
50
|
+
const { statement, named, positional } = this.prepare(source, params);
|
|
51
|
+
const result = statement.run(named, ...positional);
|
|
52
|
+
return { changes: Number(result.changes), lastInsertRowId: Number(result.lastInsertRowid) };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
public getFirstAsync<T>(source: string, params: SQLiteBindParams): Promise<T | null>;
|
|
56
|
+
public getFirstAsync<T>(source: string, ...params: SQLiteVariadicBindParams): Promise<T | null>;
|
|
57
|
+
public async getFirstAsync<T>(source: string, ...params: unknown[]): Promise<T | null> {
|
|
58
|
+
await nextTurn();
|
|
59
|
+
const { statement, named, positional } = this.prepare(source, params);
|
|
60
|
+
const row = statement.get(named, ...positional);
|
|
61
|
+
return row === undefined ? null : ({ ...row } as T);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
public getAllAsync<T>(source: string, params: SQLiteBindParams): Promise<T[]>;
|
|
65
|
+
public getAllAsync<T>(source: string, ...params: SQLiteVariadicBindParams): Promise<T[]>;
|
|
66
|
+
public async getAllAsync<T>(source: string, ...params: unknown[]): Promise<T[]> {
|
|
67
|
+
await nextTurn();
|
|
68
|
+
const { statement, named, positional } = this.prepare(source, params);
|
|
69
|
+
return statement.all(named, ...positional).map((row) => ({ ...row }) as T);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
private prepare(source: string, params: readonly unknown[]): PreparedCall {
|
|
73
|
+
const statement = this.connection.prepare(source);
|
|
74
|
+
const normalized = normalizeParams(params);
|
|
75
|
+
if (isPositional(normalized)) {
|
|
76
|
+
return { statement, named: {}, positional: normalized.map(toSqlValue) };
|
|
77
|
+
}
|
|
78
|
+
statement.setAllowBareNamedParameters(false);
|
|
79
|
+
return { statement, named: namedValues(normalized), positional: [] };
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* A file-backed `node:sqlite` database with the statement surface of an Expo `SQLiteDatabase`
|
|
85
|
+
* that `ExpoSqliteStore` and the root stores call. Exclusive transactions open a second
|
|
86
|
+
* connection to the same file, as Expo does, so a root write that overlaps one fails with
|
|
87
|
+
* `database is locked` instead of silently joining it.
|
|
88
|
+
*/
|
|
89
|
+
export class NodeSqliteDatabase extends NodeSqliteConnection implements ExpoSqliteDatabase {
|
|
90
|
+
public readonly databasePath: string;
|
|
91
|
+
private readonly ownedDirectory: string | undefined;
|
|
92
|
+
|
|
93
|
+
/** Opens `databasePath`, or a new temporary file that `closeAsync()` deletes. */
|
|
94
|
+
public constructor(databasePath?: string) {
|
|
95
|
+
const file = resolveDatabaseFile(databasePath);
|
|
96
|
+
super(new DatabaseSync(file.path, EXPO_CONNECTION_OPTIONS));
|
|
97
|
+
this.databasePath = file.path;
|
|
98
|
+
this.ownedDirectory = file.ownedDirectory;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Runs `BEGIN`, the task, and `COMMIT` on a new connection, rolling back if the task throws. */
|
|
102
|
+
public async withExclusiveTransactionAsync(
|
|
103
|
+
task: (transaction: NodeSqliteConnection) => Promise<void>,
|
|
104
|
+
): Promise<void> {
|
|
105
|
+
await nextTurn();
|
|
106
|
+
const connection = new DatabaseSync(this.databasePath, EXPO_CONNECTION_OPTIONS);
|
|
107
|
+
try {
|
|
108
|
+
connection.exec('BEGIN');
|
|
109
|
+
await runInTransaction(connection, task);
|
|
110
|
+
} finally {
|
|
111
|
+
connection.close();
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
public async closeAsync(): Promise<void> {
|
|
116
|
+
await nextTurn();
|
|
117
|
+
this.connection.close();
|
|
118
|
+
if (this.ownedDirectory !== undefined) {
|
|
119
|
+
rmSync(this.ownedDirectory, { recursive: true, force: true });
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function resolveDatabaseFile(databasePath: string | undefined): DatabaseFile {
|
|
125
|
+
if (databasePath === MEMORY_DATABASE_PATH || databasePath === '') {
|
|
126
|
+
throw new TypeError(
|
|
127
|
+
'NodeSqliteDatabase needs a file path: an exclusive transaction opens a second connection that must see the same database.',
|
|
128
|
+
);
|
|
129
|
+
}
|
|
130
|
+
if (databasePath !== undefined) {
|
|
131
|
+
return { path: databasePath, ownedDirectory: undefined };
|
|
132
|
+
}
|
|
133
|
+
const ownedDirectory = mkdtempSync(join(tmpdir(), TEMPORARY_DIRECTORY_PREFIX));
|
|
134
|
+
return { path: join(ownedDirectory, TEMPORARY_DATABASE_FILE), ownedDirectory };
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
async function runInTransaction(
|
|
138
|
+
connection: DatabaseSync,
|
|
139
|
+
task: (transaction: NodeSqliteConnection) => Promise<void>,
|
|
140
|
+
): Promise<void> {
|
|
141
|
+
try {
|
|
142
|
+
await task(new NodeSqliteConnection(connection));
|
|
143
|
+
connection.exec('COMMIT');
|
|
144
|
+
} catch (cause) {
|
|
145
|
+
if (connection.isTransaction) {
|
|
146
|
+
connection.exec('ROLLBACK');
|
|
147
|
+
}
|
|
148
|
+
throw cause;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** Defers the statement to a later microtask, as a call into Expo's native module does. */
|
|
153
|
+
function nextTurn(): Promise<void> {
|
|
154
|
+
return Promise.resolve();
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** Mirrors `expo-sqlite`'s parameter normalization: variadic values, one array, or one object. */
|
|
158
|
+
function normalizeParams(params: readonly unknown[]): readonly unknown[] | Record<string, unknown> {
|
|
159
|
+
const candidate = params.length > 1 ? params : params[0];
|
|
160
|
+
if (candidate === undefined || candidate === null) {
|
|
161
|
+
return [];
|
|
162
|
+
}
|
|
163
|
+
if (
|
|
164
|
+
typeof candidate !== 'object' ||
|
|
165
|
+
candidate instanceof ArrayBuffer ||
|
|
166
|
+
ArrayBuffer.isView(candidate)
|
|
167
|
+
) {
|
|
168
|
+
return [candidate];
|
|
169
|
+
}
|
|
170
|
+
return candidate as readonly unknown[] | Record<string, unknown>;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function isPositional(
|
|
174
|
+
params: readonly unknown[] | Record<string, unknown>,
|
|
175
|
+
): params is readonly unknown[] {
|
|
176
|
+
return Array.isArray(params);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function namedValues(params: Record<string, unknown>): NamedValues {
|
|
180
|
+
const values: NamedValues = {};
|
|
181
|
+
for (const [key, value] of Object.entries(params)) {
|
|
182
|
+
values[key] = toSqlValue(value);
|
|
183
|
+
}
|
|
184
|
+
return values;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Binds values the way Expo's native module does: booleans and integral numbers as 64-bit
|
|
189
|
+
* integers, `undefined` as NULL, and an `ArrayBuffer` as a blob.
|
|
190
|
+
*/
|
|
191
|
+
function toSqlValue(value: unknown): SQLInputValue {
|
|
192
|
+
if (value === undefined || value === null) {
|
|
193
|
+
return null;
|
|
194
|
+
}
|
|
195
|
+
if (typeof value === 'boolean') {
|
|
196
|
+
return value ? 1n : 0n;
|
|
197
|
+
}
|
|
198
|
+
if (typeof value === 'number' && Number.isSafeInteger(value)) {
|
|
199
|
+
return BigInt(value);
|
|
200
|
+
}
|
|
201
|
+
if (value instanceof ArrayBuffer) {
|
|
202
|
+
return new Uint8Array(value);
|
|
203
|
+
}
|
|
204
|
+
return value as SQLInputValue;
|
|
205
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
|
|
3
|
+
import { OperationQueue, queueForFile } from './operation-queue.js';
|
|
4
|
+
|
|
5
|
+
describe('OperationQueue', () => {
|
|
6
|
+
it('runs operations one at a time in call order', async () => {
|
|
7
|
+
const queue = new OperationQueue();
|
|
8
|
+
const events: string[] = [];
|
|
9
|
+
const operation = (name: string) => async (): Promise<string> => {
|
|
10
|
+
events.push(`${name}:start`);
|
|
11
|
+
await Promise.resolve();
|
|
12
|
+
events.push(`${name}:end`);
|
|
13
|
+
return name;
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
const results = await Promise.all([
|
|
17
|
+
queue.run(operation('first')),
|
|
18
|
+
queue.run(operation('second')),
|
|
19
|
+
]);
|
|
20
|
+
|
|
21
|
+
expect(results).toEqual(['first', 'second']);
|
|
22
|
+
expect(events).toEqual(['first:start', 'first:end', 'second:start', 'second:end']);
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
it('continues after a rejected operation', async () => {
|
|
26
|
+
const queue = new OperationQueue();
|
|
27
|
+
const failure = new Error('failed');
|
|
28
|
+
const failed = queue.run(() => Promise.reject(failure));
|
|
29
|
+
const next = queue.run(() => Promise.resolve('next'));
|
|
30
|
+
|
|
31
|
+
await expect(failed).rejects.toBe(failure);
|
|
32
|
+
await expect(next).resolves.toBe('next');
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
it('reports idle once every accepted operation settles', async () => {
|
|
36
|
+
let idle = 0;
|
|
37
|
+
const queue = new OperationQueue(() => {
|
|
38
|
+
idle += 1;
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
await Promise.allSettled([
|
|
42
|
+
queue.run(() => Promise.resolve()),
|
|
43
|
+
queue.run(() => Promise.reject(new Error('failed'))),
|
|
44
|
+
]);
|
|
45
|
+
|
|
46
|
+
expect(idle).toBe(1);
|
|
47
|
+
});
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
describe('queueForFile', () => {
|
|
51
|
+
it('shares a queue per file while work is pending and drops it when idle', async () => {
|
|
52
|
+
let release = (): void => undefined;
|
|
53
|
+
const gate = new Promise<void>((resolve) => {
|
|
54
|
+
release = resolve;
|
|
55
|
+
});
|
|
56
|
+
const busy = queueForFile('/queue/shared.db');
|
|
57
|
+
const running = busy.run(() => gate);
|
|
58
|
+
|
|
59
|
+
expect(queueForFile('/queue/shared.db')).toBe(busy);
|
|
60
|
+
expect(queueForFile('/queue/other.db')).not.toBe(busy);
|
|
61
|
+
|
|
62
|
+
release();
|
|
63
|
+
await running;
|
|
64
|
+
await Promise.resolve();
|
|
65
|
+
|
|
66
|
+
expect(queueForFile('/queue/shared.db')).not.toBe(busy);
|
|
67
|
+
});
|
|
68
|
+
});
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/** Runs operations one at a time in call order. A rejected operation releases the queue. */
|
|
2
|
+
export class OperationQueue {
|
|
3
|
+
private tail: Promise<void> = Promise.resolve();
|
|
4
|
+
private pending = 0;
|
|
5
|
+
|
|
6
|
+
public constructor(private readonly onIdle: () => void = () => undefined) {}
|
|
7
|
+
|
|
8
|
+
public run<TResult>(operation: () => Promise<TResult>): Promise<TResult> {
|
|
9
|
+
this.pending += 1;
|
|
10
|
+
const result = this.tail.then(operation);
|
|
11
|
+
const settle = (): void => {
|
|
12
|
+
this.settle();
|
|
13
|
+
};
|
|
14
|
+
this.tail = result.then(settle, settle);
|
|
15
|
+
return result;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
private settle(): void {
|
|
19
|
+
this.pending -= 1;
|
|
20
|
+
if (this.pending === 0) {
|
|
21
|
+
this.onIdle();
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const fileQueues = new Map<string, OperationQueue>();
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Returns the queue shared by every adapter statement against one SQLite file.
|
|
30
|
+
* An entry exists only while work is pending, so closed databases leave nothing behind.
|
|
31
|
+
*/
|
|
32
|
+
export function queueForFile(databasePath: string): OperationQueue {
|
|
33
|
+
const existing = fileQueues.get(databasePath);
|
|
34
|
+
if (existing !== undefined) {
|
|
35
|
+
return existing;
|
|
36
|
+
}
|
|
37
|
+
const queue = new OperationQueue(() => {
|
|
38
|
+
fileQueues.delete(databasePath);
|
|
39
|
+
});
|
|
40
|
+
fileQueues.set(databasePath, queue);
|
|
41
|
+
return queue;
|
|
42
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { StorageError } from '@baukit/data-contracts';
|
|
2
|
+
import type { SQLiteDatabase } from 'expo-sqlite';
|
|
3
|
+
|
|
4
|
+
import { queueForFile } from './operation-queue.js';
|
|
5
|
+
import type { SQLiteConnection, StatementScope } from './statements.js';
|
|
6
|
+
|
|
7
|
+
export type SQLiteFileConnection = SQLiteConnection & Pick<SQLiteDatabase, 'databasePath'>;
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* The part of an Expo `SQLiteDatabase` this adapter calls. `NodeSqliteDatabase` from the
|
|
11
|
+
* `./testing` entry point implements it for Node unit tests.
|
|
12
|
+
*/
|
|
13
|
+
export interface ExpoSqliteDatabase extends SQLiteFileConnection {
|
|
14
|
+
closeAsync(): Promise<void>;
|
|
15
|
+
withExclusiveTransactionAsync(
|
|
16
|
+
task: (transaction: SQLiteConnection) => Promise<void>,
|
|
17
|
+
): Promise<void>;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Runs every statement on the queue shared by all adapter work against the database file. */
|
|
21
|
+
export function fileScope(
|
|
22
|
+
database: SQLiteFileConnection,
|
|
23
|
+
assertAvailable: () => void,
|
|
24
|
+
): StatementScope {
|
|
25
|
+
return {
|
|
26
|
+
assertAvailable,
|
|
27
|
+
run: (statement) => queueForFile(database.databasePath).run(() => statement(database)),
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Statements on an open transaction's connection, rejected once the transaction has settled. */
|
|
32
|
+
export class TransactionScope implements StatementScope {
|
|
33
|
+
private active = true;
|
|
34
|
+
|
|
35
|
+
public constructor(private readonly connection: SQLiteConnection) {}
|
|
36
|
+
|
|
37
|
+
public assertAvailable(): void {
|
|
38
|
+
if (!this.active) {
|
|
39
|
+
throw new StorageError('storage_closed', 'The transaction context is no longer active.');
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
public run<TResult>(
|
|
44
|
+
statement: (connection: SQLiteConnection) => Promise<TResult>,
|
|
45
|
+
): Promise<TResult> {
|
|
46
|
+
return statement(this.connection);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
public finish(): void {
|
|
50
|
+
this.active = false;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Queues work on the database file and closes the handle after all accepted work, when it owns
|
|
56
|
+
* the handle. Every `close()` caller gets the same promise.
|
|
57
|
+
*/
|
|
58
|
+
export class QueuedDatabase {
|
|
59
|
+
private closeResult: Promise<void> | undefined;
|
|
60
|
+
|
|
61
|
+
public constructor(
|
|
62
|
+
public readonly database: ExpoSqliteDatabase,
|
|
63
|
+
private readonly ownsDatabase: boolean,
|
|
64
|
+
) {}
|
|
65
|
+
|
|
66
|
+
public enqueue<TResult>(operation: () => Promise<TResult>): Promise<TResult> {
|
|
67
|
+
return queueForFile(this.database.databasePath).run(operation);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
public close(): Promise<void> {
|
|
71
|
+
this.closeResult ??= this.enqueue(() => this.closeOwnedDatabase());
|
|
72
|
+
return this.closeResult;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
public assertOpen(): void {
|
|
76
|
+
if (this.closeResult !== undefined) {
|
|
77
|
+
throw new StorageError('storage_closed', 'The storage adapter is closed.');
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
private async closeOwnedDatabase(): Promise<void> {
|
|
82
|
+
if (this.ownsDatabase) {
|
|
83
|
+
await this.database.closeAsync();
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|