@baukit/data-contracts-expo-sqlite 0.7.2 → 0.7.4

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.
@@ -0,0 +1,328 @@
1
+ import {
2
+ DEFAULT_PAGE_SIZE,
3
+ MAX_PAGE_SIZE,
4
+ type JsonValue,
5
+ type KeyValueStore,
6
+ type Page,
7
+ type PageOptions,
8
+ type RecordStore,
9
+ type SchemaMeta,
10
+ type SchemaMetadataStore,
11
+ type StoredRecord,
12
+ normalizeStorageError,
13
+ } from '@baukit/data-contracts';
14
+ import type { SQLiteDatabase } from 'expo-sqlite';
15
+
16
+ interface StoredRow {
17
+ readonly id: string;
18
+ readonly payload: string;
19
+ }
20
+
21
+ interface KeyValueRow {
22
+ readonly payload: string;
23
+ }
24
+
25
+ interface SchemaRow {
26
+ readonly name: string;
27
+ readonly version: number;
28
+ }
29
+
30
+ export type SQLiteConnection = Pick<
31
+ SQLiteDatabase,
32
+ 'execAsync' | 'getAllAsync' | 'getFirstAsync' | 'runAsync'
33
+ >;
34
+
35
+ /** Decides when a statement may be accepted and on which connection it runs. */
36
+ export interface StatementScope {
37
+ assertAvailable(): void;
38
+ run<TResult>(statement: (connection: SQLiteConnection) => Promise<TResult>): Promise<TResult>;
39
+ }
40
+
41
+ const CURSOR_PREFIX = 'sqlite1:';
42
+
43
+ const CREATE_RECORDS_TABLE =
44
+ 'CREATE TABLE IF NOT EXISTS baukit_records (namespace TEXT NOT NULL, id TEXT NOT NULL, payload TEXT NOT NULL, PRIMARY KEY (namespace, id));';
45
+ const CREATE_KEY_VALUES_TABLE =
46
+ 'CREATE TABLE IF NOT EXISTS baukit_key_values (namespace TEXT NOT NULL, key TEXT NOT NULL, payload TEXT NOT NULL, PRIMARY KEY (namespace, key));';
47
+ const CREATE_SCHEMA_METADATA_TABLE =
48
+ 'CREATE TABLE IF NOT EXISTS baukit_schema_metadata (namespace TEXT PRIMARY KEY NOT NULL, name TEXT NOT NULL, version INTEGER NOT NULL);';
49
+
50
+ export const CREATE_ADAPTER_TABLES = [
51
+ CREATE_KEY_VALUES_TABLE,
52
+ CREATE_RECORDS_TABLE,
53
+ CREATE_SCHEMA_METADATA_TABLE,
54
+ ].join(' ');
55
+
56
+ export async function write<TResult>(operation: () => Promise<TResult>): Promise<TResult> {
57
+ try {
58
+ return await operation();
59
+ } catch (cause) {
60
+ throw normalizeStorageError(cause);
61
+ }
62
+ }
63
+
64
+ export class RecordStatements<T extends StoredRecord> implements RecordStore<T> {
65
+ public constructor(
66
+ private readonly scope: StatementScope,
67
+ private readonly namespace: string,
68
+ ) {
69
+ if (namespace.length === 0) {
70
+ throw new TypeError('Record store namespace must not be empty.');
71
+ }
72
+ }
73
+
74
+ /** Creates the shared adapter table if needed. Safe to call repeatedly. */
75
+ public async initialize(): Promise<void> {
76
+ this.scope.assertAvailable();
77
+ await write(() => this.scope.run((connection) => connection.execAsync(CREATE_RECORDS_TABLE)));
78
+ }
79
+
80
+ public async put(record: T): Promise<void> {
81
+ this.scope.assertAvailable();
82
+ if (record.id.length === 0) {
83
+ throw new TypeError('Record id must not be empty.');
84
+ }
85
+ const payload = serialize(record, 'Record');
86
+ await write(() =>
87
+ this.scope.run((connection) =>
88
+ connection.runAsync(
89
+ 'INSERT INTO baukit_records (namespace, id, payload) VALUES (?, ?, ?) ON CONFLICT(namespace, id) DO UPDATE SET payload = excluded.payload',
90
+ this.namespace,
91
+ record.id,
92
+ payload,
93
+ ),
94
+ ),
95
+ );
96
+ }
97
+
98
+ public async get(id: string): Promise<T | undefined> {
99
+ this.scope.assertAvailable();
100
+ const row = await this.scope.run((connection) =>
101
+ connection.getFirstAsync<StoredRow>(
102
+ 'SELECT id, payload FROM baukit_records WHERE namespace = ? AND id = ?',
103
+ this.namespace,
104
+ id,
105
+ ),
106
+ );
107
+ return row === null ? undefined : (parseRecord(row.payload) as T);
108
+ }
109
+
110
+ public async delete(id: string): Promise<void> {
111
+ this.scope.assertAvailable();
112
+ await write(() =>
113
+ this.scope.run((connection) =>
114
+ connection.runAsync(
115
+ 'DELETE FROM baukit_records WHERE namespace = ? AND id = ?',
116
+ this.namespace,
117
+ id,
118
+ ),
119
+ ),
120
+ );
121
+ }
122
+
123
+ public async list(options: PageOptions = {}): Promise<Page<T>> {
124
+ this.scope.assertAvailable();
125
+ const limit = pageLimit(options.limit);
126
+ const afterId = decodeCursor(options.cursor);
127
+ const rows = await this.scope.run((connection) =>
128
+ connection.getAllAsync<StoredRow>(
129
+ 'SELECT id, payload FROM baukit_records WHERE namespace = ? AND id > ? ORDER BY id ASC LIMIT ?',
130
+ this.namespace,
131
+ afterId,
132
+ limit + 1,
133
+ ),
134
+ );
135
+ const hasNext = rows.length > limit;
136
+ const pageRows = rows.slice(0, limit);
137
+ const last = pageRows.at(-1);
138
+ return {
139
+ items: pageRows.map((row) => parseRecord(row.payload) as T),
140
+ nextCursor: hasNext && last !== undefined ? encodeCursor(last.id) : null,
141
+ };
142
+ }
143
+ }
144
+
145
+ export class KeyValueStatements implements KeyValueStore {
146
+ public constructor(
147
+ private readonly scope: StatementScope,
148
+ private readonly namespace: string,
149
+ ) {}
150
+
151
+ public async initialize(): Promise<void> {
152
+ this.scope.assertAvailable();
153
+ await write(() =>
154
+ this.scope.run((connection) => connection.execAsync(CREATE_KEY_VALUES_TABLE)),
155
+ );
156
+ }
157
+
158
+ public async get(key: string): Promise<JsonValue | undefined> {
159
+ this.scope.assertAvailable();
160
+ const row = await this.scope.run((connection) =>
161
+ connection.getFirstAsync<KeyValueRow>(
162
+ 'SELECT payload FROM baukit_key_values WHERE namespace = ? AND key = ?',
163
+ this.namespace,
164
+ key,
165
+ ),
166
+ );
167
+ return row === null ? undefined : parseJson(row.payload, 'key/value');
168
+ }
169
+
170
+ public async set(key: string, value: JsonValue): Promise<void> {
171
+ this.scope.assertAvailable();
172
+ const payload = serialize(value, 'Value');
173
+ await write(() =>
174
+ this.scope.run((connection) =>
175
+ connection.runAsync(
176
+ 'INSERT INTO baukit_key_values (namespace, key, payload) VALUES (?, ?, ?) ON CONFLICT(namespace, key) DO UPDATE SET payload = excluded.payload',
177
+ this.namespace,
178
+ key,
179
+ payload,
180
+ ),
181
+ ),
182
+ );
183
+ }
184
+
185
+ public async delete(key: string): Promise<void> {
186
+ this.scope.assertAvailable();
187
+ await write(() =>
188
+ this.scope.run((connection) =>
189
+ connection.runAsync(
190
+ 'DELETE FROM baukit_key_values WHERE namespace = ? AND key = ?',
191
+ this.namespace,
192
+ key,
193
+ ),
194
+ ),
195
+ );
196
+ }
197
+
198
+ public async clear(): Promise<void> {
199
+ this.scope.assertAvailable();
200
+ await write(() =>
201
+ this.scope.run((connection) =>
202
+ connection.runAsync('DELETE FROM baukit_key_values WHERE namespace = ?', this.namespace),
203
+ ),
204
+ );
205
+ }
206
+
207
+ public async clearPrefix(prefix: string): Promise<void> {
208
+ this.scope.assertAvailable();
209
+ await write(() =>
210
+ this.scope.run((connection) =>
211
+ connection.runAsync(
212
+ 'DELETE FROM baukit_key_values WHERE namespace = ? AND substr(CAST(key AS BLOB), 1, length(CAST(? AS BLOB))) = CAST(? AS BLOB)',
213
+ this.namespace,
214
+ prefix,
215
+ prefix,
216
+ ),
217
+ ),
218
+ );
219
+ }
220
+ }
221
+
222
+ export class SchemaMetadataStatements implements SchemaMetadataStore {
223
+ public constructor(
224
+ private readonly scope: StatementScope,
225
+ private readonly namespace: string,
226
+ ) {}
227
+
228
+ public async initialize(): Promise<void> {
229
+ this.scope.assertAvailable();
230
+ await write(() =>
231
+ this.scope.run((connection) => connection.execAsync(CREATE_SCHEMA_METADATA_TABLE)),
232
+ );
233
+ }
234
+
235
+ public async getSchemaMeta(): Promise<SchemaMeta | undefined> {
236
+ this.scope.assertAvailable();
237
+ const row = await this.scope.run((connection) =>
238
+ connection.getFirstAsync<SchemaRow>(
239
+ 'SELECT name, version FROM baukit_schema_metadata WHERE namespace = ?',
240
+ this.namespace,
241
+ ),
242
+ );
243
+ return row === null ? undefined : { name: row.name, version: row.version };
244
+ }
245
+
246
+ public async setSchemaMeta(metadata: SchemaMeta): Promise<void> {
247
+ this.scope.assertAvailable();
248
+ validateSchemaMeta(metadata);
249
+ await write(() =>
250
+ this.scope.run((connection) =>
251
+ connection.runAsync(
252
+ 'INSERT INTO baukit_schema_metadata (namespace, name, version) VALUES (?, ?, ?) ON CONFLICT(namespace) DO UPDATE SET name = excluded.name, version = excluded.version',
253
+ this.namespace,
254
+ metadata.name,
255
+ metadata.version,
256
+ ),
257
+ ),
258
+ );
259
+ }
260
+ }
261
+
262
+ function pageLimit(requested: number | undefined): number {
263
+ const limit = requested ?? DEFAULT_PAGE_SIZE;
264
+ if (!Number.isInteger(limit) || limit < 1 || limit > MAX_PAGE_SIZE) {
265
+ throw new RangeError(`Page limit must be an integer from 1 to ${String(MAX_PAGE_SIZE)}.`);
266
+ }
267
+ return limit;
268
+ }
269
+
270
+ function encodeCursor(id: string): string {
271
+ return `${CURSOR_PREFIX}${encodeURIComponent(id)}`;
272
+ }
273
+
274
+ function decodeCursor(cursor: string | null | undefined): string {
275
+ if (cursor === undefined || cursor === null) {
276
+ return '';
277
+ }
278
+ if (!cursor.startsWith(CURSOR_PREFIX)) {
279
+ throw new TypeError('Invalid record cursor.');
280
+ }
281
+ try {
282
+ return decodeURIComponent(cursor.slice(CURSOR_PREFIX.length));
283
+ } catch {
284
+ throw new TypeError('Invalid record cursor.');
285
+ }
286
+ }
287
+
288
+ function serialize(value: unknown, kind: string): string {
289
+ try {
290
+ return JSON.stringify(value);
291
+ } catch {
292
+ throw new TypeError(`${kind} must be JSON serializable.`);
293
+ }
294
+ }
295
+
296
+ function parseJson(payload: string, kind: string): JsonValue {
297
+ try {
298
+ return JSON.parse(payload) as JsonValue;
299
+ } catch {
300
+ throw new TypeError(`The local database contains an invalid ${kind} value.`);
301
+ }
302
+ }
303
+
304
+ function parseRecord(payload: string): StoredRecord {
305
+ try {
306
+ const value: unknown = JSON.parse(payload);
307
+ if (
308
+ typeof value !== 'object' ||
309
+ value === null ||
310
+ Array.isArray(value) ||
311
+ typeof Reflect.get(value, 'id') !== 'string'
312
+ ) {
313
+ throw new TypeError('invalid record');
314
+ }
315
+ return value as StoredRecord;
316
+ } catch {
317
+ throw new TypeError('The local database contains an invalid record.');
318
+ }
319
+ }
320
+
321
+ function validateSchemaMeta(metadata: SchemaMeta): void {
322
+ if (metadata.name.length === 0) {
323
+ throw new TypeError('Schema name must not be empty.');
324
+ }
325
+ if (!Number.isInteger(metadata.version) || metadata.version < 0) {
326
+ throw new TypeError('Schema version must be a non-negative integer.');
327
+ }
328
+ }
package/src/testing.ts ADDED
@@ -0,0 +1,7 @@
1
+ export { NodeSqliteConnection, NodeSqliteDatabase } from './node-sqlite.js';
2
+ export {
3
+ createSqliteMigrationConformanceTests,
4
+ type SqliteMigrationConformanceAdapter,
5
+ type SqliteMigrationConformanceTestCase,
6
+ type SqliteMigrationStep,
7
+ } from './migration-conformance.js';