@hulla/db-sqlite 0.0.0-stage → 0.2.0
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/LICENSE +21 -0
- package/README.md +25 -2
- package/dist/browser.d.ts +5 -0
- package/dist/browser.js +9 -0
- package/dist/bun-driver.d.ts +3 -0
- package/dist/bun-driver.js +18 -0
- package/dist/bun.d.ts +3 -0
- package/dist/bun.js +2 -0
- package/dist/client-storage.d.ts +12 -0
- package/dist/client-storage.js +209 -0
- package/dist/descriptor.d.ts +26 -0
- package/dist/descriptor.js +16 -0
- package/dist/driver.d.ts +25 -0
- package/dist/driver.js +18 -0
- package/dist/engine.d.ts +43 -0
- package/dist/engine.js +346 -0
- package/dist/expo.d.ts +4 -0
- package/dist/expo.js +2 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +23 -0
- package/dist/node-driver.d.ts +3 -0
- package/dist/node-driver.js +11 -0
- package/dist/node.d.ts +3 -0
- package/dist/node.js +2 -0
- package/dist/runtime.d.ts +16 -0
- package/dist/runtime.js +170 -0
- package/dist/worker.d.ts +2 -0
- package/dist/worker.js +2 -0
- package/package.json +79 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Samuel Hulla
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,26 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @hulla/db-sqlite
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
SQLite application instances for Node, Bun, browsers and Expo.
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
import { defineSchema, defineTable, v } from '@hulla/db'
|
|
7
|
+
import { sqlite } from '@hulla/db-sqlite'
|
|
8
|
+
|
|
9
|
+
const schema = defineSchema({ drafts: defineTable({ title: v.string() }) })
|
|
10
|
+
const db = sqlite({ schema, filename: './drafts.sqlite' })
|
|
11
|
+
await db.insert('drafts', { title: 'A draft' })
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
Schema imports are inert. `sqlite({...})` starts opening existing storage; operations
|
|
15
|
+
wait automatically. `sqlite.initialize({...})` explicitly provisions fresh storage.
|
|
16
|
+
Optional `ready()`, observable `state`/`subscribe()` and terminal `close()` expose the
|
|
17
|
+
instance lifecycle. Register local functions through one barrel import callback or
|
|
18
|
+
an application glob compiled by [`@hulla/db/build`](https://github.com/hulladev/db/blob/main/docs/build.md);
|
|
19
|
+
combine shared/app handlers using ordinary exports.
|
|
20
|
+
|
|
21
|
+
The browser and Expo entrypoints accept `open`, which supplies a dedicated driver.
|
|
22
|
+
Readonly replicas require explicit source URL bindings. Offline mutations queue
|
|
23
|
+
server calls with mandatory device-side conflict callbacks and optional optimistic
|
|
24
|
+
feedback. Native Rust SQLite storage and SQLite managed HTTP hosting remain work.
|
|
25
|
+
See [SQLite and authoring](https://github.com/hulladev/db/blob/main/docs/sqlite.md) for
|
|
26
|
+
examples, supported queries, build-time globs and recovery behavior.
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { BrowserSQLiteConnection } from "./descriptor.ts";
|
|
2
|
+
export { wasmSQLiteDriver } from "./driver.ts";
|
|
3
|
+
export type { SQLiteWasmConnection, SQLiteDriver } from "./driver.ts";
|
|
4
|
+
export type { BrowserSQLiteConnection as SQLiteConnection } from "./descriptor.ts";
|
|
5
|
+
export declare const sqlite: import("./descriptor.ts").SQLiteFactory<BrowserSQLiteConnection>;
|
package/dist/browser.js
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { sqliteFactory } from "./descriptor.js";
|
|
2
|
+
import { openSQLiteDatabase } from "./runtime.js";
|
|
3
|
+
export { wasmSQLiteDriver } from "./driver.js";
|
|
4
|
+
export const sqlite = sqliteFactory(async (schema, settings, initialize) => {
|
|
5
|
+
if (!settings || typeof settings !== "object" || Reflect.ownKeys(settings).some(key => !["open", "randomBytes", "transactionTimeoutMs"].includes(key))
|
|
6
|
+
|| settings.filename !== undefined || typeof settings.open !== "function")
|
|
7
|
+
throw new TypeError("Browser SQLite requires open: () => a dedicated SQLite driver");
|
|
8
|
+
return openSQLiteDatabase(schema, await settings.open(), settings, initialize);
|
|
9
|
+
});
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/** Bun-only entrypoint. Use a private connection for each database handle. */
|
|
2
|
+
export async function bunSQLiteDriver(filename) {
|
|
3
|
+
// Keep this built-in lazy even when a Node bundler follows the Bun branch.
|
|
4
|
+
const { Database } = await import('bun:sqlite');
|
|
5
|
+
const connection = new Database(filename, { strict: true });
|
|
6
|
+
return {
|
|
7
|
+
execute(sql, parameters = []) {
|
|
8
|
+
const statement = connection.prepare(sql);
|
|
9
|
+
try {
|
|
10
|
+
return statement.all(...parameters);
|
|
11
|
+
}
|
|
12
|
+
finally {
|
|
13
|
+
statement.finalize();
|
|
14
|
+
}
|
|
15
|
+
},
|
|
16
|
+
close() { connection.close(true); },
|
|
17
|
+
};
|
|
18
|
+
}
|
package/dist/bun.d.ts
ADDED
package/dist/bun.js
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { type ClientStorage, type DatabaseIdentity, type StorageChange } from "@hulla/db/internal/engine";
|
|
2
|
+
import type { SchemaDefinition } from "@hulla/db";
|
|
3
|
+
import { SQLiteEngine } from "./engine.ts";
|
|
4
|
+
type Atomic = <T>(handler: () => Promise<T>) => Promise<T>;
|
|
5
|
+
/** Persistent client state shares the connection scheduler with application transactions. */
|
|
6
|
+
export declare function sqliteClientStorage(engine: SQLiteEngine, schema: SchemaDefinition, atomic: Atomic, notify: (change: StorageChange) => void): {
|
|
7
|
+
readonly epoch: number;
|
|
8
|
+
isReplica: (name: string) => boolean;
|
|
9
|
+
assertReadable(name: string): void;
|
|
10
|
+
factory(owner: DatabaseIdentity): ClientStorage;
|
|
11
|
+
};
|
|
12
|
+
export {};
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
import { replicaSources } from "@hulla/db/internal/engine";
|
|
2
|
+
import { sqliteFailure } from "./engine.js";
|
|
3
|
+
/** Persistent client state shares the connection scheduler with application transactions. */
|
|
4
|
+
export function sqliteClientStorage(engine, schema, atomic, notify) {
|
|
5
|
+
const replicas = Object.entries(schema.tables).flatMap(([name, definition]) => {
|
|
6
|
+
const source = replicaSources.get(definition);
|
|
7
|
+
return source ? [{ name, source }] : [];
|
|
8
|
+
});
|
|
9
|
+
const stores = new Map();
|
|
10
|
+
const activeOwners = new Map();
|
|
11
|
+
let epoch = 0;
|
|
12
|
+
const namespace = (group, key) => JSON.stringify([group, key]);
|
|
13
|
+
async function read(space, kind, key) {
|
|
14
|
+
const rows = await engine.execute("SELECT value FROM _hulla_client WHERE namespace=? AND kind=? AND key=?", [space, kind, key]);
|
|
15
|
+
return rows.length ? JSON.parse(String(rows[0].value)) : undefined;
|
|
16
|
+
}
|
|
17
|
+
async function list(space, kind) {
|
|
18
|
+
const rows = await engine.execute("SELECT value FROM _hulla_client WHERE namespace=? AND kind=? ORDER BY sequence", [space, kind]);
|
|
19
|
+
return rows.map(row => JSON.parse(String(row.value)));
|
|
20
|
+
}
|
|
21
|
+
async function checkCapacity(space, kind, key, text) {
|
|
22
|
+
const bytes = new TextEncoder().encode(text).byteLength;
|
|
23
|
+
const quota = await engine.execute("SELECT count(*) AS n, coalesce(sum(length(CAST(value AS BLOB))),0) AS bytes FROM _hulla_client WHERE kind=? AND NOT(namespace=? AND key=?)", [kind, space, key]);
|
|
24
|
+
if (Number(quota[0]?.n) >= 128 || Number(quota[0]?.bytes) + bytes > 16 * 1024 * 1024)
|
|
25
|
+
throw sqliteFailure("capacity", "Persistent client storage is full; acknowledge completed calls or release downloaded queries explicitly");
|
|
26
|
+
}
|
|
27
|
+
async function put(space, kind, key, value) {
|
|
28
|
+
const text = JSON.stringify(value);
|
|
29
|
+
await checkCapacity(space, kind, key, text);
|
|
30
|
+
await engine.execute("INSERT INTO _hulla_client(namespace,kind,key,value) VALUES(?,?,?,?) ON CONFLICT(namespace,kind,key) DO UPDATE SET value=excluded.value", [space, kind, key, text]);
|
|
31
|
+
}
|
|
32
|
+
for (const table of engine.tables)
|
|
33
|
+
if (!replicas.some(replica => replica.name === table.name) && Object.values(table.fields).some(field => typeof field.target === "string" && replicas.some(replica => replica.name === field.target)))
|
|
34
|
+
throw new TypeError("Local foreign keys cannot target partially downloaded replicas; store an unconstrained scalar ID instead");
|
|
35
|
+
async function rebuild(owner, key) {
|
|
36
|
+
const targets = replicas.filter(replica => replica.source.database === owner);
|
|
37
|
+
for (const replica of targets)
|
|
38
|
+
await engine.execute(`DELETE FROM ${engine.physical(engine.table(replica.name))}`);
|
|
39
|
+
const group = JSON.stringify(targets.map(replica => replica.name));
|
|
40
|
+
const snapshots = await list(namespace(group, key), "snapshot");
|
|
41
|
+
const rows = new Map();
|
|
42
|
+
for (const saved of snapshots)
|
|
43
|
+
for (const target of targets.filter(target => target.source.name === saved.replica.table && target.source.columns.every(column => saved.replica.columns.includes(column)))) {
|
|
44
|
+
const table = engine.table(target.name);
|
|
45
|
+
for (const row of saved.rows) {
|
|
46
|
+
const identity = JSON.stringify([target.name, row[table.primaryKey]]);
|
|
47
|
+
const revision = BigInt(saved.snapshot.revision);
|
|
48
|
+
if ((rows.get(identity)?.revision ?? -1n) <= revision)
|
|
49
|
+
rows.set(identity, { revision, row, local: target.name });
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
let current, insert = '';
|
|
53
|
+
let names = [], values = [], parameters = [];
|
|
54
|
+
const flush = async () => {
|
|
55
|
+
if (values.length)
|
|
56
|
+
await engine.execute(insert + values.join(','), parameters);
|
|
57
|
+
values = [];
|
|
58
|
+
parameters = [];
|
|
59
|
+
};
|
|
60
|
+
for (const { row, local } of rows.values()) {
|
|
61
|
+
const table = engine.table(local);
|
|
62
|
+
if (local !== current) {
|
|
63
|
+
await flush();
|
|
64
|
+
current = local;
|
|
65
|
+
names = Object.keys(table.fields);
|
|
66
|
+
insert = `INSERT INTO ${engine.physical(table)} (${names.map(name => engine.column(table, name)).join(',')}) VALUES `;
|
|
67
|
+
}
|
|
68
|
+
// Bound each native call independently of the downloaded working-set size.
|
|
69
|
+
if (parameters.length + names.length > 999)
|
|
70
|
+
await flush();
|
|
71
|
+
values.push(`(${names.map(name => engine.bind(table, name, row[name], parameters)).join(',')})`);
|
|
72
|
+
}
|
|
73
|
+
await flush();
|
|
74
|
+
}
|
|
75
|
+
return {
|
|
76
|
+
get epoch() { return epoch; },
|
|
77
|
+
isReplica: (name) => replicas.some(replica => replica.name === name),
|
|
78
|
+
assertReadable(name) { const replica = replicas.find(replica => replica.name === name); if (replica && !activeOwners.has(replica.source.database))
|
|
79
|
+
throw sqliteFailure("replica_scope_uninitialized", "Connect an authenticated upstream before reading replica rows"); },
|
|
80
|
+
factory(owner) {
|
|
81
|
+
const existing = stores.get(owner);
|
|
82
|
+
if (existing)
|
|
83
|
+
return existing;
|
|
84
|
+
const targets = replicas.filter(replica => replica.source.database === owner);
|
|
85
|
+
if (!targets.length)
|
|
86
|
+
throw new TypeError("The device schema has no replicas of this source database");
|
|
87
|
+
const group = JSON.stringify(targets.map(replica => replica.name));
|
|
88
|
+
const space = (key) => namespace(group, key);
|
|
89
|
+
let active, generation = 0;
|
|
90
|
+
const store = {
|
|
91
|
+
deactivate() { active = undefined; activeOwners.delete(owner); generation++; epoch++; notify('scope'); },
|
|
92
|
+
async activate(key) {
|
|
93
|
+
if (active === key)
|
|
94
|
+
return;
|
|
95
|
+
const token = ++generation;
|
|
96
|
+
active = undefined;
|
|
97
|
+
activeOwners.delete(owner);
|
|
98
|
+
epoch++;
|
|
99
|
+
notify('scope');
|
|
100
|
+
await atomic(async () => { if (token !== generation)
|
|
101
|
+
return; await rebuild(owner, key ?? "anonymous"); if (token !== generation)
|
|
102
|
+
throw sqliteFailure("context_changed", "Replica scope changed"); });
|
|
103
|
+
if (token !== generation)
|
|
104
|
+
throw sqliteFailure("context_changed", "Replica scope changed");
|
|
105
|
+
active = key ?? "anonymous";
|
|
106
|
+
activeOwners.set(owner, active);
|
|
107
|
+
notify('rows');
|
|
108
|
+
},
|
|
109
|
+
session: key => atomic(() => read(space(key), "session", "last")),
|
|
110
|
+
async bind(key, session) {
|
|
111
|
+
await atomic(async () => {
|
|
112
|
+
const previous = await read(space(key), "session", "last");
|
|
113
|
+
const anchor = await read(group, "source", "id");
|
|
114
|
+
if (anchor && anchor !== session.source) {
|
|
115
|
+
store.deactivate();
|
|
116
|
+
throw sqliteFailure("reset_required", "The replica source changed; existing rows and pending calls were retained");
|
|
117
|
+
}
|
|
118
|
+
if (previous && (previous.scope !== session.scope || previous.principal !== session.principal)) {
|
|
119
|
+
store.deactivate();
|
|
120
|
+
throw sqliteFailure("context_changed", "Verified identity changed within the same local account key");
|
|
121
|
+
}
|
|
122
|
+
if (previous && previous.authorizationScope !== session.authorizationScope) {
|
|
123
|
+
store.deactivate();
|
|
124
|
+
await engine.execute("DELETE FROM _hulla_client WHERE namespace=? AND kind='snapshot'", [space(key)]);
|
|
125
|
+
}
|
|
126
|
+
await put(group, "source", "id", session.source);
|
|
127
|
+
await put(space(key), "session", "last", session);
|
|
128
|
+
});
|
|
129
|
+
},
|
|
130
|
+
mutations: key => atomic(() => list(space(key), "intent")),
|
|
131
|
+
async enqueue(key, mutation) {
|
|
132
|
+
await atomic(async () => {
|
|
133
|
+
if (await read(space(key), "intent", mutation.id))
|
|
134
|
+
throw sqliteFailure("request_id_reused", "Queued call already exists");
|
|
135
|
+
await put(space(key), "intent", mutation.id, mutation);
|
|
136
|
+
});
|
|
137
|
+
},
|
|
138
|
+
async update(key, mutation, previous) {
|
|
139
|
+
return atomic(async () => {
|
|
140
|
+
const text = JSON.stringify(mutation);
|
|
141
|
+
await checkCapacity(space(key), "intent", mutation.id, text);
|
|
142
|
+
return (await engine.execute("UPDATE _hulla_client SET value=? WHERE namespace=? AND kind='intent' AND key=? AND value=? RETURNING key", [text, space(key), mutation.id, JSON.stringify(previous)])).length === 1;
|
|
143
|
+
});
|
|
144
|
+
},
|
|
145
|
+
async remove(key, id) { await atomic(async () => { await engine.execute("DELETE FROM _hulla_client WHERE namespace=? AND kind='intent' AND key=?", [space(key), id]); }); },
|
|
146
|
+
snapshot: keyQuery,
|
|
147
|
+
async saveSnapshot(key, query, snapshot, contract, input) {
|
|
148
|
+
await store.apply(key, [{ query, snapshot, replica: contract, rows: input }]);
|
|
149
|
+
},
|
|
150
|
+
async apply(key, changes) {
|
|
151
|
+
const token = generation;
|
|
152
|
+
try {
|
|
153
|
+
await atomic(async () => {
|
|
154
|
+
for (const change of changes) {
|
|
155
|
+
if (!change.snapshot) {
|
|
156
|
+
await engine.execute("DELETE FROM _hulla_client WHERE namespace=? AND kind='snapshot' AND key=?", [space(key), change.query]);
|
|
157
|
+
continue;
|
|
158
|
+
}
|
|
159
|
+
if (active !== key || token !== generation)
|
|
160
|
+
throw sqliteFailure("context_changed", "Replica scope changed");
|
|
161
|
+
const { snapshot, replica: contract, rows: input } = change;
|
|
162
|
+
if (!Array.isArray(input))
|
|
163
|
+
throw new TypeError("Replica results must be rows");
|
|
164
|
+
const matching = targets.filter(target => target.source.name === contract.table);
|
|
165
|
+
if (!matching.length)
|
|
166
|
+
continue;
|
|
167
|
+
const fields = matching[0].source.table.fields;
|
|
168
|
+
const rows = input.map(value => Object.fromEntries(contract.columns.map(name => {
|
|
169
|
+
if (!value || typeof value !== "object" || !Object.hasOwn(value, name) || !fields[name])
|
|
170
|
+
throw new TypeError("Invalid replica row");
|
|
171
|
+
const encoded = fields[name].encode(value[name]);
|
|
172
|
+
return [name, typeof encoded === "bigint" ? encoded.toString() : encoded];
|
|
173
|
+
})));
|
|
174
|
+
const previous = await read(space(key), "snapshot", change.query);
|
|
175
|
+
if (previous && BigInt(previous.snapshot.revision) > BigInt(snapshot.revision))
|
|
176
|
+
continue;
|
|
177
|
+
await put(space(key), "snapshot", change.query, { snapshot, replica: contract, rows });
|
|
178
|
+
}
|
|
179
|
+
if (active === key)
|
|
180
|
+
await rebuild(owner, key);
|
|
181
|
+
if (changes.some(change => change.snapshot) && token !== generation)
|
|
182
|
+
throw sqliteFailure("context_changed", "Replica scope changed");
|
|
183
|
+
});
|
|
184
|
+
notify('rows');
|
|
185
|
+
}
|
|
186
|
+
catch (error) {
|
|
187
|
+
// A failed new round cannot leave superseded authorization coverage active.
|
|
188
|
+
try {
|
|
189
|
+
await atomic(async () => { for (const change of changes)
|
|
190
|
+
await engine.execute("DELETE FROM _hulla_client WHERE namespace=? AND kind='snapshot' AND key=?", [space(key), change.query]); if (active === key)
|
|
191
|
+
await rebuild(owner, key); });
|
|
192
|
+
notify('rows');
|
|
193
|
+
}
|
|
194
|
+
catch {
|
|
195
|
+
store.deactivate();
|
|
196
|
+
}
|
|
197
|
+
throw error;
|
|
198
|
+
}
|
|
199
|
+
},
|
|
200
|
+
async forgetSnapshot(key, query) {
|
|
201
|
+
await store.apply(key, [{ query }]);
|
|
202
|
+
},
|
|
203
|
+
};
|
|
204
|
+
async function keyQuery(key, query) { return atomic(async () => (await read(space(key), "snapshot", query))?.snapshot); }
|
|
205
|
+
stores.set(owner, store);
|
|
206
|
+
return store;
|
|
207
|
+
},
|
|
208
|
+
};
|
|
209
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { Database, DatabaseEngine, SchemaDefinition, ConnectedDatabase, SourceConnection } from "@hulla/db";
|
|
2
|
+
import { type DatabaseOptions } from "@hulla/db/engine";
|
|
3
|
+
import type { FunctionSource } from "@hulla/db";
|
|
4
|
+
import type { SourcesOf } from "@hulla/db/internal/engine";
|
|
5
|
+
import type { SQLiteDriver } from "./driver.ts";
|
|
6
|
+
interface SQLiteSettings {
|
|
7
|
+
readonly randomBytes?: (length: number) => Uint8Array;
|
|
8
|
+
readonly transactionTimeoutMs?: number;
|
|
9
|
+
}
|
|
10
|
+
/** Each instance owns a fresh dedicated driver connection. */
|
|
11
|
+
export type BrowserSQLiteConnection = SQLiteSettings & {
|
|
12
|
+
readonly open: () => SQLiteDriver | PromiseLike<SQLiteDriver>;
|
|
13
|
+
readonly filename?: never;
|
|
14
|
+
};
|
|
15
|
+
export type SQLiteConnection = BrowserSQLiteConnection | (SQLiteSettings & {
|
|
16
|
+
readonly filename: string;
|
|
17
|
+
readonly open?: never;
|
|
18
|
+
});
|
|
19
|
+
export type Connector<C extends SQLiteConnection = SQLiteConnection> = <S extends SchemaDefinition>(schema: S, settings: C, initialize: boolean) => Promise<ConnectedDatabase<S>>;
|
|
20
|
+
export declare function sqliteDescriptor<C extends SQLiteConnection = SQLiteConnection>(connect: Connector<C>): DatabaseEngine<"sqlite", C>;
|
|
21
|
+
export type SQLiteConstructor<C extends SQLiteConnection = SQLiteConnection> = <const S extends SchemaDefinition, const F extends FunctionSource | undefined = undefined, const R extends readonly SourceConnection<SourcesOf<S>>[] = readonly SourceConnection<SourcesOf<S>>[]>(options: DatabaseOptions<S, C, F, R>) => Database<S, F>;
|
|
22
|
+
export type SQLiteFactory<C extends SQLiteConnection = SQLiteConnection> = SQLiteConstructor<C> & {
|
|
23
|
+
readonly initialize: SQLiteConstructor<C>;
|
|
24
|
+
};
|
|
25
|
+
export declare function sqliteFactory<C extends SQLiteConnection = SQLiteConnection>(connect: Connector<C>): SQLiteFactory<C>;
|
|
26
|
+
export {};
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { createDatabase, registerDatabaseFactory } from "@hulla/db/engine";
|
|
2
|
+
export function sqliteDescriptor(connect) {
|
|
3
|
+
return Object.freeze({
|
|
4
|
+
name: "sqlite", replicaStorage: true, serialTransactions: true,
|
|
5
|
+
connect: (schema, settings) => connect(schema, settings, false),
|
|
6
|
+
initialize: (schema, settings) => connect(schema, settings, true),
|
|
7
|
+
});
|
|
8
|
+
}
|
|
9
|
+
export function sqliteFactory(connect) {
|
|
10
|
+
const engine = sqliteDescriptor(connect);
|
|
11
|
+
const create = (options) => createDatabase(engine, options);
|
|
12
|
+
const initialize = (options) => createDatabase(engine, options, true);
|
|
13
|
+
registerDatabaseFactory(create, engine);
|
|
14
|
+
registerDatabaseFactory(initialize, engine);
|
|
15
|
+
return Object.assign(create, { initialize });
|
|
16
|
+
}
|
package/dist/driver.d.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/** Values crossing a SQLite driver boundary. Int64 columns are read as text. */
|
|
2
|
+
export type SQLiteValue = string | number | null;
|
|
3
|
+
export type SQLiteRecord = Record<string, SQLiteValue>;
|
|
4
|
+
/** A dedicated connection, owned by the database until close(). Do not share it with other SQL users. */
|
|
5
|
+
export interface SQLiteDriver {
|
|
6
|
+
execute(sql: string, parameters?: readonly SQLiteValue[]): PromiseLike<readonly SQLiteRecord[]> | readonly SQLiteRecord[];
|
|
7
|
+
close(): void | PromiseLike<void>;
|
|
8
|
+
}
|
|
9
|
+
export interface SQLiteWasmConnection {
|
|
10
|
+
exec(options: {
|
|
11
|
+
sql: string;
|
|
12
|
+
bind: SQLiteValue[];
|
|
13
|
+
rowMode: "object";
|
|
14
|
+
resultRows: SQLiteRecord[];
|
|
15
|
+
}): unknown;
|
|
16
|
+
close(): unknown;
|
|
17
|
+
}
|
|
18
|
+
/** Wrap an official sqlite3.oo1.DB/OpfsDb in the thread which owns it (normally a worker). */
|
|
19
|
+
export declare function wasmSQLiteDriver(connection: SQLiteWasmConnection): SQLiteDriver;
|
|
20
|
+
export interface ExpoSQLiteConnection {
|
|
21
|
+
getAllAsync<T>(sql: string, parameters: SQLiteValue[]): Promise<T[]>;
|
|
22
|
+
closeAsync(): Promise<void>;
|
|
23
|
+
}
|
|
24
|
+
/** Wrap a dedicated expo-sqlite connection; the application owns opening/configuring its file. */
|
|
25
|
+
export declare function expoSQLiteDriver(connection: ExpoSQLiteConnection): SQLiteDriver;
|
package/dist/driver.js
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/** Wrap an official sqlite3.oo1.DB/OpfsDb in the thread which owns it (normally a worker). */
|
|
2
|
+
export function wasmSQLiteDriver(connection) {
|
|
3
|
+
return {
|
|
4
|
+
execute(sql, parameters = []) {
|
|
5
|
+
const resultRows = [];
|
|
6
|
+
connection.exec({ sql, bind: [...parameters], rowMode: "object", resultRows });
|
|
7
|
+
return resultRows;
|
|
8
|
+
},
|
|
9
|
+
close() { connection.close(); },
|
|
10
|
+
};
|
|
11
|
+
}
|
|
12
|
+
/** Wrap a dedicated expo-sqlite connection; the application owns opening/configuring its file. */
|
|
13
|
+
export function expoSQLiteDriver(connection) {
|
|
14
|
+
return {
|
|
15
|
+
execute: (sql, parameters = []) => connection.getAllAsync(sql, [...parameters]),
|
|
16
|
+
close: () => connection.closeAsync(),
|
|
17
|
+
};
|
|
18
|
+
}
|
package/dist/engine.d.ts
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { DatabaseError } from "@hulla/db/internal/engine";
|
|
2
|
+
import { type CompiledTable, type SchemaDefinition } from "@hulla/db/internal/engine";
|
|
3
|
+
import type { Predicate } from "@hulla/db/internal/engine";
|
|
4
|
+
import type { SQLiteDriver, SQLiteRecord, SQLiteValue } from "./driver.ts";
|
|
5
|
+
export type StoredRow = Record<string, unknown>;
|
|
6
|
+
export declare const sqliteFailure: (code: string, message: string) => DatabaseError;
|
|
7
|
+
type Sort = {
|
|
8
|
+
field: string;
|
|
9
|
+
direction: "asc" | "desc";
|
|
10
|
+
};
|
|
11
|
+
export declare class SQLiteEngine {
|
|
12
|
+
#private;
|
|
13
|
+
readonly tables: readonly CompiledTable[];
|
|
14
|
+
readonly contract: string;
|
|
15
|
+
readonly driver: SQLiteDriver;
|
|
16
|
+
readonly randomBytes: (length: number) => Uint8Array;
|
|
17
|
+
source: string;
|
|
18
|
+
constructor(driver: SQLiteDriver, schema: SchemaDefinition, randomBytes?: (length: number) => Uint8Array);
|
|
19
|
+
execute(sql: string, parameters?: readonly SQLiteValue[]): Promise<readonly SQLiteRecord[]>;
|
|
20
|
+
table(name: string): CompiledTable;
|
|
21
|
+
physical(table: CompiledTable): string;
|
|
22
|
+
column(table: CompiledTable, name: string): string;
|
|
23
|
+
bind(table: CompiledTable, name: string, value: unknown, parameters: SQLiteValue[]): string;
|
|
24
|
+
fields(table: CompiledTable, prefix?: string): string;
|
|
25
|
+
decode(table: CompiledTable, value: SQLiteRecord): StoredRow;
|
|
26
|
+
envelope(row: StoredRow, projection?: string[]): {
|
|
27
|
+
row: StoredRow;
|
|
28
|
+
version: string;
|
|
29
|
+
};
|
|
30
|
+
private configure;
|
|
31
|
+
verify(): Promise<void>;
|
|
32
|
+
initialize(): Promise<void>;
|
|
33
|
+
private createTable;
|
|
34
|
+
private predicate;
|
|
35
|
+
where(table: CompiledTable, filters: Predicate[], parameters: SQLiteValue[]): string;
|
|
36
|
+
private order;
|
|
37
|
+
read(table: CompiledTable, filters: Predicate[], order?: Sort[], limit?: number | null): Promise<StoredRow[]>;
|
|
38
|
+
private expression;
|
|
39
|
+
private update;
|
|
40
|
+
operation(operation: Record<string, unknown>): Promise<unknown>;
|
|
41
|
+
private aggregate;
|
|
42
|
+
}
|
|
43
|
+
export {};
|
package/dist/engine.js
ADDED
|
@@ -0,0 +1,346 @@
|
|
|
1
|
+
import { DatabaseError } from "@hulla/db/internal/engine";
|
|
2
|
+
import { compileSchema } from "@hulla/db/internal/engine";
|
|
3
|
+
import { schemaDescriptor } from "@hulla/db/internal/engine";
|
|
4
|
+
export const sqliteFailure = (code, message) => new DatabaseError({ code, message });
|
|
5
|
+
const quote = (value) => '"' + value.replaceAll('"', '""') + '"';
|
|
6
|
+
const literal = (value) => value === null ? "NULL" : typeof value === "number" ? String(value) : "'" + value.replaceAll("'", "''") + "'";
|
|
7
|
+
const checkLiteral = (value) => typeof value === "bigint" ? String(value) : typeof value === "boolean" ? String(Number(value)) : literal(value);
|
|
8
|
+
export class SQLiteEngine {
|
|
9
|
+
tables;
|
|
10
|
+
contract;
|
|
11
|
+
driver;
|
|
12
|
+
randomBytes;
|
|
13
|
+
#layout;
|
|
14
|
+
source = "";
|
|
15
|
+
constructor(driver, schema, randomBytes = length => {
|
|
16
|
+
if (!globalThis.crypto?.getRandomValues)
|
|
17
|
+
throw new TypeError("Supply randomBytes using a cryptographically secure platform RNG (for example expo-crypto)");
|
|
18
|
+
return globalThis.crypto.getRandomValues(new Uint8Array(length));
|
|
19
|
+
}) {
|
|
20
|
+
this.driver = driver;
|
|
21
|
+
this.randomBytes = randomBytes;
|
|
22
|
+
this.tables = compileSchema(schema);
|
|
23
|
+
this.#layout = new Map(this.tables.map((table, index) => [table.name, {
|
|
24
|
+
table, physical: quote(`_hulla_t${index}`),
|
|
25
|
+
columns: new Map(Object.keys(table.fields).map((name, index) => [name, quote(`c${index}`)])),
|
|
26
|
+
}]));
|
|
27
|
+
this.contract = JSON.stringify(schemaDescriptor(schema));
|
|
28
|
+
if (this.tables.some(table => typeof table.keyGeneration === "object"))
|
|
29
|
+
throw new TypeError("SQLite custom key handlers are not supported; supply explicit keys with keyGeneration: 'none'");
|
|
30
|
+
}
|
|
31
|
+
execute(sql, parameters = []) { return Promise.resolve(this.driver.execute(sql, parameters)); }
|
|
32
|
+
table(name) {
|
|
33
|
+
const table = this.#layout.get(name)?.table;
|
|
34
|
+
if (!table)
|
|
35
|
+
throw new TypeError(`Unknown table ${name}`);
|
|
36
|
+
return table;
|
|
37
|
+
}
|
|
38
|
+
physical(table) { return this.#layout.get(table.name).physical; }
|
|
39
|
+
column(table, name) {
|
|
40
|
+
const column = this.#layout.get(table.name).columns.get(name);
|
|
41
|
+
if (column === undefined)
|
|
42
|
+
throw new TypeError(`Unknown field ${table.name}.${name}`);
|
|
43
|
+
return column;
|
|
44
|
+
}
|
|
45
|
+
bind(table, name, value, parameters) {
|
|
46
|
+
const field = table.fields[name];
|
|
47
|
+
if (value === null)
|
|
48
|
+
parameters.push(null);
|
|
49
|
+
else if (field.scalar === "json")
|
|
50
|
+
parameters.push(JSON.stringify(value));
|
|
51
|
+
else if (field.scalar === "boolean")
|
|
52
|
+
parameters.push(value ? 1 : 0);
|
|
53
|
+
else if (["string", "number"].includes(typeof value))
|
|
54
|
+
parameters.push(value);
|
|
55
|
+
else
|
|
56
|
+
throw new TypeError("Invalid SQLite wire value");
|
|
57
|
+
return field.scalar === "int64" ? "CAST(? AS INTEGER)" : "?";
|
|
58
|
+
}
|
|
59
|
+
fields(table, prefix = "") {
|
|
60
|
+
return [...this.#layout.get(table.name).columns].map(([name, physical]) => {
|
|
61
|
+
const column = prefix + physical;
|
|
62
|
+
return `${table.fields[name].scalar === "int64" ? `CAST(${column} AS TEXT)` : column} AS ${quote(name)}`;
|
|
63
|
+
}).join(", ");
|
|
64
|
+
}
|
|
65
|
+
decode(table, value) {
|
|
66
|
+
return Object.fromEntries(Object.entries(table.fields).map(([name, field]) => {
|
|
67
|
+
let item = value[name];
|
|
68
|
+
if (item !== null && field.scalar === "json")
|
|
69
|
+
item = JSON.parse(item);
|
|
70
|
+
if (item !== null && field.scalar === "boolean")
|
|
71
|
+
item = item === 1;
|
|
72
|
+
// Decode checks storage constraints and codecs, but transport stays in wire representation.
|
|
73
|
+
field.decode(item);
|
|
74
|
+
return [name, item];
|
|
75
|
+
}));
|
|
76
|
+
}
|
|
77
|
+
envelope(row, projection) {
|
|
78
|
+
return { row: projection ? Object.fromEntries(projection.map(name => [name, row[name]])) : row, version: "1" };
|
|
79
|
+
}
|
|
80
|
+
async configure() {
|
|
81
|
+
await this.execute("PRAGMA foreign_keys = ON");
|
|
82
|
+
const flags = await this.execute("PRAGMA foreign_keys");
|
|
83
|
+
if (flags[0]?.foreign_keys !== 1)
|
|
84
|
+
throw sqliteFailure("sqlite_configuration", "SQLite must enforce foreign keys");
|
|
85
|
+
await this.execute("PRAGMA busy_timeout = 5000");
|
|
86
|
+
}
|
|
87
|
+
async verify() {
|
|
88
|
+
await this.configure();
|
|
89
|
+
const exists = await this.execute("SELECT name FROM sqlite_master WHERE type = 'table' AND name = '_hulla_meta'");
|
|
90
|
+
if (!exists.length)
|
|
91
|
+
throw sqliteFailure("database_uninitialized", "Initialize SQLite explicitly before connecting");
|
|
92
|
+
const meta = await this.execute("SELECT contract, source FROM _hulla_meta");
|
|
93
|
+
if (meta.length !== 1 || meta[0]?.contract !== this.contract)
|
|
94
|
+
throw sqliteFailure("schema_mismatch", "SQLite schema differs; migrate explicitly without resetting existing data");
|
|
95
|
+
this.source = String(meta[0].source);
|
|
96
|
+
}
|
|
97
|
+
async initialize() {
|
|
98
|
+
await this.configure();
|
|
99
|
+
await this.execute("BEGIN IMMEDIATE");
|
|
100
|
+
try {
|
|
101
|
+
const existing = await this.execute("SELECT name FROM sqlite_master WHERE name NOT LIKE 'sqlite_%'");
|
|
102
|
+
if (existing.length) {
|
|
103
|
+
await this.verify();
|
|
104
|
+
}
|
|
105
|
+
else {
|
|
106
|
+
this.source = uuid(true, this.randomBytes);
|
|
107
|
+
await this.execute("CREATE TABLE _hulla_meta (contract TEXT NOT NULL, source TEXT NOT NULL) STRICT");
|
|
108
|
+
await this.execute("CREATE TABLE _hulla_client (sequence INTEGER PRIMARY KEY AUTOINCREMENT, namespace TEXT NOT NULL, kind TEXT NOT NULL, key TEXT NOT NULL, value TEXT NOT NULL, UNIQUE(namespace,kind,key)) STRICT");
|
|
109
|
+
await this.execute("INSERT INTO _hulla_meta VALUES (?, ?)", [this.contract, this.source]);
|
|
110
|
+
for (const table of this.tables)
|
|
111
|
+
await this.createTable(table);
|
|
112
|
+
}
|
|
113
|
+
await this.execute("COMMIT");
|
|
114
|
+
}
|
|
115
|
+
catch (error) {
|
|
116
|
+
await this.execute("ROLLBACK");
|
|
117
|
+
throw error;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
async createTable(table) {
|
|
121
|
+
const definitions = Object.entries(table.fields).map(([name, field]) => {
|
|
122
|
+
const column = this.column(table, name);
|
|
123
|
+
const type = field.scalar === "int64" || field.scalar === "boolean" ? "INTEGER" : field.scalar === "float64" ? "REAL" : "TEXT";
|
|
124
|
+
const checks = [];
|
|
125
|
+
if (field.scalar === "boolean")
|
|
126
|
+
checks.push(`${column} IN (0, 1)`);
|
|
127
|
+
if (field.scalar === "json")
|
|
128
|
+
checks.push(`json_valid(${column})`);
|
|
129
|
+
if (field.constraints?.min !== undefined)
|
|
130
|
+
checks.push(`${field.scalar === "string" ? `length(${column})` : column} >= ${checkLiteral(field.constraints.min)}`);
|
|
131
|
+
if (field.constraints?.max !== undefined)
|
|
132
|
+
checks.push(`${field.scalar === "string" ? `length(${column})` : column} <= ${checkLiteral(field.constraints.max)}`);
|
|
133
|
+
if (field.constraints?.oneOf)
|
|
134
|
+
checks.push(`${column} IN (${field.constraints.oneOf.map(checkLiteral).join(", ")})`);
|
|
135
|
+
let reference = "";
|
|
136
|
+
if (field.target !== undefined) {
|
|
137
|
+
const target = this.table(field.target);
|
|
138
|
+
reference = ` REFERENCES ${this.physical(target)} (${this.column(target, target.primaryKey)}) ON DELETE ${{ restrict: "RESTRICT", cascade: "CASCADE", setNull: "SET NULL" }[field.onDelete ?? "restrict"]} DEFERRABLE INITIALLY DEFERRED`;
|
|
139
|
+
}
|
|
140
|
+
return `${column} ${type}${field.allowsNull ? "" : " NOT NULL"}${name === table.primaryKey ? " PRIMARY KEY" : ""}${reference}${checks.map(check => ` CHECK (${check})`).join("")}`;
|
|
141
|
+
});
|
|
142
|
+
for (const check of table.checks) {
|
|
143
|
+
let expression = check.parts[0];
|
|
144
|
+
check.operands.forEach((operand, index) => {
|
|
145
|
+
expression += ("field" in operand ? this.column(table, operand.field) : checkLiteral(operand.value)) + check.parts[index + 1];
|
|
146
|
+
});
|
|
147
|
+
definitions.push(`CONSTRAINT ${quote(check.name)} CHECK (${expression})`);
|
|
148
|
+
}
|
|
149
|
+
await this.execute(`CREATE TABLE ${this.physical(table)} (${definitions.join(", ")}) STRICT`);
|
|
150
|
+
let index = 0;
|
|
151
|
+
for (const unique of Object.values(table.unique)) {
|
|
152
|
+
const fields = unique.fields.flatMap(name => {
|
|
153
|
+
const column = this.column(table, name);
|
|
154
|
+
return unique.nulls === "notDistinct" && table.fields[name].allowsNull ? [`(${column} IS NULL)`, `coalesce(${column}, '')`] : [column];
|
|
155
|
+
});
|
|
156
|
+
await this.execute(`CREATE UNIQUE INDEX ${quote(`_hulla_u${this.tables.indexOf(table)}_${index++}`)} ON ${this.physical(table)} (${fields.join(", ")})`);
|
|
157
|
+
}
|
|
158
|
+
for (const item of table.indexes)
|
|
159
|
+
await this.execute(`CREATE INDEX ${quote(`_hulla_i${this.tables.indexOf(table)}_${index++}`)} ON ${this.physical(table)} (${item.fields.map(name => this.column(table, name)).join(", ")})`);
|
|
160
|
+
}
|
|
161
|
+
predicate(table, predicate, parameters) {
|
|
162
|
+
if (predicate.kind === "constant")
|
|
163
|
+
return predicate.value ? "1" : "0";
|
|
164
|
+
if (predicate.kind === "and" || predicate.kind === "or")
|
|
165
|
+
return predicate.predicates.length ? `(${predicate.predicates.map(item => this.predicate(table, item, parameters)).join(predicate.kind === "and" ? " AND " : " OR ")})` : predicate.kind === "and" ? "1" : "0";
|
|
166
|
+
if (predicate.kind === "not")
|
|
167
|
+
return `(NOT (${this.predicate(table, predicate.predicate, parameters)}))`;
|
|
168
|
+
if (predicate.kind !== "compare")
|
|
169
|
+
throw new TypeError("Invalid predicate");
|
|
170
|
+
const path = typeof predicate.field === "string" ? [predicate.field] : predicate.field;
|
|
171
|
+
const name = path[0];
|
|
172
|
+
if (path.length !== 1 || predicate.transform)
|
|
173
|
+
throw sqliteFailure("unsupported_query", "SQLite JSON predicates are not supported yet");
|
|
174
|
+
const column = this.column(table, name);
|
|
175
|
+
let operator = predicate.operator;
|
|
176
|
+
if (operator === "is" || operator === "is not")
|
|
177
|
+
return `${column} ${operator.toUpperCase()} NULL`;
|
|
178
|
+
if (operator === "exists")
|
|
179
|
+
return predicate.operand.kind === "value" && predicate.operand.value === true ? "1" : "0";
|
|
180
|
+
if (table.fields[name].scalar === "json")
|
|
181
|
+
throw sqliteFailure("unsupported_query", "SQLite JSON predicates are not supported yet");
|
|
182
|
+
if (predicate.operand.kind === "field") {
|
|
183
|
+
const other = typeof predicate.operand.field === "string" ? [predicate.operand.field] : predicate.operand.field;
|
|
184
|
+
if (other.length !== 1 || predicate.operand.transform)
|
|
185
|
+
throw sqliteFailure("unsupported_query", "SQLite JSON predicates are not supported yet");
|
|
186
|
+
return `${column} ${operator} ${this.column(table, other[0])}`;
|
|
187
|
+
}
|
|
188
|
+
const value = predicate.operand.value;
|
|
189
|
+
const bind = (value) => this.bind(table, name, value, parameters);
|
|
190
|
+
if (operator === "in" || operator === "not in") {
|
|
191
|
+
const values = value;
|
|
192
|
+
const nonNull = values.filter(item => item !== null);
|
|
193
|
+
const matches = [];
|
|
194
|
+
if (nonNull.length)
|
|
195
|
+
matches.push(`${column} IN (${nonNull.map(bind).join(", ")})`);
|
|
196
|
+
if (values.includes(null))
|
|
197
|
+
matches.push(`${column} IS NULL`);
|
|
198
|
+
const result = matches.length ? `(${matches.join(" OR ")})` : "0";
|
|
199
|
+
return operator === "not in" ? `(NOT ${result})` : result;
|
|
200
|
+
}
|
|
201
|
+
if (operator === "between" || operator === "not between")
|
|
202
|
+
return `${column} ${operator.toUpperCase()} ${bind(value[0])} AND ${bind(value[1])}`;
|
|
203
|
+
const negated = operator.startsWith("not ");
|
|
204
|
+
if (negated)
|
|
205
|
+
operator = operator.slice(4);
|
|
206
|
+
if (["contains", "startsWith", "endsWith", "like", "ilike"].includes(operator)) {
|
|
207
|
+
if (operator === "like" || operator === "ilike") {
|
|
208
|
+
// SQLite LIKE is ASCII-insensitive by default. Require a deliberate supported operation.
|
|
209
|
+
throw sqliteFailure("unsupported_query", "SQLite pattern matching is not supported; use literal text predicates");
|
|
210
|
+
}
|
|
211
|
+
const text = String(value), expression = column;
|
|
212
|
+
if (predicate.caseSensitive === false)
|
|
213
|
+
throw sqliteFailure("unsupported_query", "SQLite Unicode-insensitive text matching requires a platform extension and is not supported");
|
|
214
|
+
parameters.push(text);
|
|
215
|
+
const comparison = operator === "contains" ? `instr(${expression}, ?) > 0` : operator === "startsWith" ? `substr(${expression}, 1, length(?)) = ${bindText(text, parameters)}` : `substr(${expression}, length(${expression}) - length(?) + 1) = ${bindText(text, parameters)}`;
|
|
216
|
+
return negated ? `(NOT (${comparison}))` : `(${comparison})`;
|
|
217
|
+
}
|
|
218
|
+
return `${column} ${operator} ${bind(value)}`;
|
|
219
|
+
}
|
|
220
|
+
where(table, filters, parameters) {
|
|
221
|
+
return filters.length ? filters.map(item => `(${this.predicate(table, item, parameters)})`).join(" AND ") : "1";
|
|
222
|
+
}
|
|
223
|
+
order(table, order) {
|
|
224
|
+
const items = [...order];
|
|
225
|
+
if (!items.some(item => item.field === table.primaryKey))
|
|
226
|
+
items.push({ field: table.primaryKey, direction: items.at(-1)?.direction ?? "asc" });
|
|
227
|
+
return items;
|
|
228
|
+
}
|
|
229
|
+
async read(table, filters, order = [], limit = null) {
|
|
230
|
+
const parameters = [];
|
|
231
|
+
const where = this.where(table, filters, parameters);
|
|
232
|
+
const sort = this.order(table, order).map(item => `${this.column(table, item.field)} ${item.direction.toUpperCase()} NULLS ${item.direction === "asc" ? "LAST" : "FIRST"}`).join(", ");
|
|
233
|
+
return (await this.execute(`SELECT ${this.fields(table)} FROM ${this.physical(table)} WHERE ${where} ORDER BY ${sort}${limit === null ? "" : ` LIMIT ${limit}`}`, parameters)).map(row => this.decode(table, row));
|
|
234
|
+
}
|
|
235
|
+
expression(table, name, node, parameters, incoming) {
|
|
236
|
+
if (node.kind === "value")
|
|
237
|
+
return this.bind(table, name, node.value, parameters);
|
|
238
|
+
if (node.kind === "field")
|
|
239
|
+
return node.source === "current" ? this.column(table, node.field) : this.bind(table, node.field, incoming[node.field], parameters);
|
|
240
|
+
return `(${this.expression(table, name, node.left, parameters, incoming)} + ${this.expression(table, name, node.right, parameters, incoming)})`;
|
|
241
|
+
}
|
|
242
|
+
async update(table, values, filters, incoming) {
|
|
243
|
+
const parameters = [];
|
|
244
|
+
const assignments = Object.entries(values).map(([name, node]) => `${this.column(table, name)} = ${this.expression(table, name, node, parameters, incoming)}`);
|
|
245
|
+
if (!assignments.length)
|
|
246
|
+
assignments.push(`${this.column(table, table.primaryKey)} = ${this.column(table, table.primaryKey)}`);
|
|
247
|
+
const where = this.where(table, filters, parameters);
|
|
248
|
+
return (await this.execute(`UPDATE ${this.physical(table)} SET ${assignments.join(", ")} WHERE ${where} RETURNING ${this.fields(table)}`, parameters)).map(row => this.decode(table, row));
|
|
249
|
+
}
|
|
250
|
+
async operation(operation) {
|
|
251
|
+
const table = this.table(operation.table);
|
|
252
|
+
const filters = (operation.filters ?? []);
|
|
253
|
+
const projection = operation.projection;
|
|
254
|
+
const envelopes = (rows) => rows.map(row => this.envelope(row, projection));
|
|
255
|
+
if (operation.method === "select")
|
|
256
|
+
return envelopes(await this.read(table, filters, operation.order, operation.limit));
|
|
257
|
+
if (operation.method === "paginate")
|
|
258
|
+
throw sqliteFailure("unsupported_query", "SQLite pagination is not supported yet; use an explicit key boundary and limit");
|
|
259
|
+
if (operation.method === "aggregate")
|
|
260
|
+
return this.aggregate(table, operation, filters);
|
|
261
|
+
if (operation.method === "update")
|
|
262
|
+
return envelopes(await this.update(table, operation.values, filters));
|
|
263
|
+
if (operation.method === "delete") {
|
|
264
|
+
const parameters = [];
|
|
265
|
+
const where = this.where(table, filters, parameters);
|
|
266
|
+
return envelopes((await this.execute(`DELETE FROM ${this.physical(table)} WHERE ${where} RETURNING ${this.fields(table)}`, parameters)).map(row => this.decode(table, row)));
|
|
267
|
+
}
|
|
268
|
+
if (operation.method !== "insert")
|
|
269
|
+
throw new TypeError("Unknown SQLite operation");
|
|
270
|
+
const bulk = Array.isArray(operation.values);
|
|
271
|
+
const inputs = (bulk ? operation.values : [operation.values]);
|
|
272
|
+
const conflict = operation.conflict;
|
|
273
|
+
const touched = new Set();
|
|
274
|
+
const result = [];
|
|
275
|
+
for (const input of inputs) {
|
|
276
|
+
const row = { ...input };
|
|
277
|
+
for (const [name, field] of Object.entries(table.fields)) {
|
|
278
|
+
if (Object.hasOwn(row, name))
|
|
279
|
+
continue;
|
|
280
|
+
if (field.hasDefault) {
|
|
281
|
+
const value = field.encode(field.defaultValue);
|
|
282
|
+
row[name] = typeof value === "bigint" ? String(value) : value;
|
|
283
|
+
}
|
|
284
|
+
else if (name === table.primaryKey)
|
|
285
|
+
row[name] = uuid(table.keyGeneration === "uuidV4", this.randomBytes);
|
|
286
|
+
}
|
|
287
|
+
for (const [name, field] of Object.entries(table.fields))
|
|
288
|
+
field.decode(row[name]);
|
|
289
|
+
if (conflict) {
|
|
290
|
+
const nullsDistinct = conflict.fields.some(name => row[name] === null) && Object.values(table.unique).some(unique => unique.nulls === "distinct" && unique.fields.length === conflict.fields.length && unique.fields.every(name => conflict.fields.includes(name)));
|
|
291
|
+
const matches = nullsDistinct ? [] : await this.read(table, conflict.fields.map(name => ({ kind: "compare", field: name, operator: row[name] === null ? "is" : "=", operand: { kind: "value", value: row[name] } })));
|
|
292
|
+
if (matches.length) {
|
|
293
|
+
if (conflict.action.kind === "skip")
|
|
294
|
+
continue;
|
|
295
|
+
const key = String(matches[0][table.primaryKey]);
|
|
296
|
+
if (touched.has(key))
|
|
297
|
+
throw sqliteFailure("cardinality_violation", "A bulk conflict update cannot update the same row twice");
|
|
298
|
+
touched.add(key);
|
|
299
|
+
result.push(...await this.update(table, conflict.action.values, [{ kind: "compare", field: table.primaryKey, operator: "=", operand: { kind: "value", value: matches[0][table.primaryKey] } }], row));
|
|
300
|
+
continue;
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
const parameters = [];
|
|
304
|
+
const names = Object.keys(table.fields);
|
|
305
|
+
const values = names.map(name => this.bind(table, name, row[name], parameters));
|
|
306
|
+
await this.execute(`INSERT INTO ${this.physical(table)} (${names.map(name => this.column(table, name)).join(", ")}) VALUES (${values.join(", ")})`, parameters);
|
|
307
|
+
touched.add(String(row[table.primaryKey]));
|
|
308
|
+
result.push(row);
|
|
309
|
+
}
|
|
310
|
+
return bulk ? envelopes(result) : result.length ? this.envelope(result[0], projection) : null;
|
|
311
|
+
}
|
|
312
|
+
async aggregate(table, operation, filters) {
|
|
313
|
+
const groups = operation.groupBy;
|
|
314
|
+
const aggregates = operation.aggregates;
|
|
315
|
+
if (groups.length || operation.having.length)
|
|
316
|
+
throw sqliteFailure("unsupported_query", "SQLite grouped aggregates are not supported yet");
|
|
317
|
+
const columns = Object.entries(aggregates).map(([alias, item]) => {
|
|
318
|
+
if (item.op === "count")
|
|
319
|
+
return `count(*) AS ${quote(alias)}`;
|
|
320
|
+
const field = table.fields[item.field];
|
|
321
|
+
if (field.scalar === "int64" && item.op === "avg")
|
|
322
|
+
throw sqliteFailure("unsupported_query", "SQLite cannot preserve decimal int64 averages");
|
|
323
|
+
const expression = `${item.op}(${this.column(table, item.field)})`;
|
|
324
|
+
return `${field.scalar === "int64" ? `CAST(${expression} AS TEXT)` : expression} AS ${quote(alias)}`;
|
|
325
|
+
});
|
|
326
|
+
const parameters = [];
|
|
327
|
+
const where = this.where(table, filters, parameters);
|
|
328
|
+
return (await this.execute(`SELECT ${columns.join(", ")} FROM ${this.physical(table)} WHERE ${where}`, parameters))[0];
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
function bindText(text, parameters) { parameters.push(text); return "?"; }
|
|
332
|
+
function uuid(v4, randomBytes) {
|
|
333
|
+
const bytes = new Uint8Array(randomBytes(16));
|
|
334
|
+
if (bytes.length !== 16)
|
|
335
|
+
throw new TypeError("randomBytes must return the requested number of bytes");
|
|
336
|
+
let timestamp = BigInt(Date.now());
|
|
337
|
+
if (!v4)
|
|
338
|
+
for (let index = 5; index >= 0; index--) {
|
|
339
|
+
bytes[index] = Number(timestamp & 255n);
|
|
340
|
+
timestamp >>= 8n;
|
|
341
|
+
}
|
|
342
|
+
bytes[6] = (bytes[6] & 15) | (v4 ? 64 : 112);
|
|
343
|
+
bytes[8] = (bytes[8] & 63) | 128;
|
|
344
|
+
const hex = Array.from(bytes, byte => byte.toString(16).padStart(2, "0")).join("");
|
|
345
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
346
|
+
}
|
package/dist/expo.d.ts
ADDED
package/dist/expo.js
ADDED
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { sqliteFactory } from "./descriptor.js";
|
|
2
|
+
export const sqlite = sqliteFactory(async (schema, settings, initialize) => {
|
|
3
|
+
if (!settings || typeof settings !== "object" || Reflect.ownKeys(settings).some(key => !["filename", "open", "randomBytes", "transactionTimeoutMs"].includes(key))
|
|
4
|
+
|| (settings.filename === undefined) === (settings.open === undefined))
|
|
5
|
+
throw new TypeError("SQLite requires exactly one of filename or open");
|
|
6
|
+
let driver;
|
|
7
|
+
if (settings.open !== undefined) {
|
|
8
|
+
if (typeof settings.open !== "function")
|
|
9
|
+
throw new TypeError("SQLite open must create a dedicated connection");
|
|
10
|
+
driver = await settings.open();
|
|
11
|
+
}
|
|
12
|
+
else {
|
|
13
|
+
if (typeof settings.filename !== "string" || !settings.filename || settings.filename.includes("\0"))
|
|
14
|
+
throw new TypeError("SQLite filename must be a nonempty path");
|
|
15
|
+
if (typeof process === "undefined")
|
|
16
|
+
throw new TypeError("Use the browser/Expo adapter and provide open");
|
|
17
|
+
driver = await (process.versions.bun
|
|
18
|
+
? (await import("./bun-driver.js")).bunSQLiteDriver(settings.filename)
|
|
19
|
+
: (await import("./node-driver.js")).nodeSQLiteDriver(settings.filename));
|
|
20
|
+
}
|
|
21
|
+
const { openSQLiteDatabase } = await import("./runtime.js");
|
|
22
|
+
return openSQLiteDatabase(schema, driver, settings, initialize);
|
|
23
|
+
});
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { DatabaseSync } from "node:sqlite";
|
|
2
|
+
/** Node-only entrypoint. Opening a file is explicit; importing this module opens nothing. */
|
|
3
|
+
export function nodeSQLiteDriver(filename) {
|
|
4
|
+
const connection = new DatabaseSync(filename, { enableForeignKeyConstraints: true, enableDoubleQuotedStringLiterals: false });
|
|
5
|
+
return {
|
|
6
|
+
execute(sql, parameters = []) {
|
|
7
|
+
return connection.prepare(sql).all(...parameters);
|
|
8
|
+
},
|
|
9
|
+
close() { connection.close(); },
|
|
10
|
+
};
|
|
11
|
+
}
|
package/dist/node.d.ts
ADDED
package/dist/node.js
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { type WriteDatabase } from "@hulla/db/internal/engine";
|
|
2
|
+
import type { SchemaDefinition } from "@hulla/db";
|
|
3
|
+
import type { SQLiteDriver } from "./driver.ts";
|
|
4
|
+
export interface SQLiteOptions {
|
|
5
|
+
/** Platform CSPRNG when Web Crypto is unavailable, e.g. expo-crypto.getRandomBytes. */
|
|
6
|
+
readonly randomBytes?: (length: number) => Uint8Array;
|
|
7
|
+
/** Callback deadline, excluding time in the connection queue. Defaults to 5000. */
|
|
8
|
+
readonly transactionTimeoutMs?: number;
|
|
9
|
+
}
|
|
10
|
+
export interface SQLiteDatabase<S extends SchemaDefinition> extends WriteDatabase<S> {
|
|
11
|
+
/** Runs once. Use only the supplied tx until the callback completes. */
|
|
12
|
+
transaction<T>(handler: (tx: WriteDatabase<S>) => T | PromiseLike<T>): Promise<T>;
|
|
13
|
+
close(): Promise<void>;
|
|
14
|
+
}
|
|
15
|
+
/** Open schema-typed local storage. The driver belongs exclusively to the returned handle. */
|
|
16
|
+
export declare function openSQLiteDatabase<S extends SchemaDefinition>(schema: S, driver: SQLiteDriver, options?: SQLiteOptions, initialize?: boolean): Promise<SQLiteDatabase<S>>;
|
package/dist/runtime.js
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
import { registerClientStorage, registerStorageExecution, registerStorageChanges, transactionDatabase } from "@hulla/db/internal/engine";
|
|
2
|
+
import { SQLiteEngine, sqliteFailure } from "./engine.js";
|
|
3
|
+
import { sqliteClientStorage } from "./client-storage.js";
|
|
4
|
+
/** Open schema-typed local storage. The driver belongs exclusively to the returned handle. */
|
|
5
|
+
export async function openSQLiteDatabase(schema, driver, options = {}, initialize = false) {
|
|
6
|
+
let engine;
|
|
7
|
+
const timeoutMs = options.transactionTimeoutMs ?? 5000;
|
|
8
|
+
try {
|
|
9
|
+
if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 60_000)
|
|
10
|
+
throw new TypeError("transactionTimeoutMs must be an integer from 1 to 60000");
|
|
11
|
+
engine = new SQLiteEngine(driver, schema, options.randomBytes);
|
|
12
|
+
}
|
|
13
|
+
catch (error) {
|
|
14
|
+
await driver.close();
|
|
15
|
+
throw error;
|
|
16
|
+
}
|
|
17
|
+
let closed = false, userTransaction = false, queued = 0;
|
|
18
|
+
let tail = Promise.resolve();
|
|
19
|
+
function enqueue(handler, internal = false) {
|
|
20
|
+
if (closed)
|
|
21
|
+
return Promise.reject(sqliteFailure("database_closed", "Database is closed"));
|
|
22
|
+
if (userTransaction && !internal)
|
|
23
|
+
return Promise.reject(sqliteFailure("transaction_scope", "Use the supplied tx while a SQLite transaction is active"));
|
|
24
|
+
if (queued >= 64)
|
|
25
|
+
return Promise.reject(sqliteFailure("capacity", "SQLite connection queue is full"));
|
|
26
|
+
queued++;
|
|
27
|
+
const result = tail.then(async () => {
|
|
28
|
+
let began = false;
|
|
29
|
+
try {
|
|
30
|
+
await engine.execute("BEGIN IMMEDIATE");
|
|
31
|
+
began = true;
|
|
32
|
+
const value = await handler();
|
|
33
|
+
await engine.execute("COMMIT");
|
|
34
|
+
began = false;
|
|
35
|
+
return value;
|
|
36
|
+
}
|
|
37
|
+
catch (error) {
|
|
38
|
+
if (began) {
|
|
39
|
+
try {
|
|
40
|
+
await engine.execute("ROLLBACK");
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
closed = true;
|
|
44
|
+
await driver.close();
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
throw error;
|
|
48
|
+
}
|
|
49
|
+
finally {
|
|
50
|
+
queued--;
|
|
51
|
+
}
|
|
52
|
+
});
|
|
53
|
+
tail = result.catch(() => { });
|
|
54
|
+
return result;
|
|
55
|
+
}
|
|
56
|
+
const atomic = handler => enqueue(handler);
|
|
57
|
+
const listeners = new Set();
|
|
58
|
+
const notify = (change) => { for (const listener of [...listeners])
|
|
59
|
+
listener(change); };
|
|
60
|
+
let storage;
|
|
61
|
+
try {
|
|
62
|
+
storage = sqliteClientStorage(engine, schema, handler => enqueue(handler, true), notify);
|
|
63
|
+
}
|
|
64
|
+
catch (error) {
|
|
65
|
+
await driver.close();
|
|
66
|
+
throw error;
|
|
67
|
+
}
|
|
68
|
+
try {
|
|
69
|
+
if (initialize)
|
|
70
|
+
await engine.initialize();
|
|
71
|
+
else
|
|
72
|
+
await engine.verify();
|
|
73
|
+
}
|
|
74
|
+
catch (error) {
|
|
75
|
+
await driver.close();
|
|
76
|
+
throw error;
|
|
77
|
+
}
|
|
78
|
+
function guard(operation) {
|
|
79
|
+
if (typeof operation.table === "string" && storage.isReplica(operation.table)) {
|
|
80
|
+
if (["insert", "update", "delete"].includes(String(operation.method)))
|
|
81
|
+
throw sqliteFailure("replica_read_only", "Write through a server mutation; offline calls queue that mutation explicitly");
|
|
82
|
+
storage.assertReadable(operation.table);
|
|
83
|
+
return true;
|
|
84
|
+
}
|
|
85
|
+
return false;
|
|
86
|
+
}
|
|
87
|
+
function transaction(handler) {
|
|
88
|
+
return atomic(async () => {
|
|
89
|
+
userTransaction = true;
|
|
90
|
+
let replicaEpoch;
|
|
91
|
+
let live = true, pending = 0, failed = false;
|
|
92
|
+
let failure;
|
|
93
|
+
let statements = Promise.resolve();
|
|
94
|
+
let timer;
|
|
95
|
+
const request = (operation, validate) => {
|
|
96
|
+
if (!live)
|
|
97
|
+
return Promise.reject(sqliteFailure("transaction_closed", "Transaction handle is no longer active"));
|
|
98
|
+
if (pending >= 64) {
|
|
99
|
+
failed = true;
|
|
100
|
+
failure = sqliteFailure("capacity", "Too many queued SQLite operations");
|
|
101
|
+
return Promise.reject(failure);
|
|
102
|
+
}
|
|
103
|
+
pending++;
|
|
104
|
+
const result = statements.then(async () => {
|
|
105
|
+
if (!live)
|
|
106
|
+
throw sqliteFailure("transaction_closed", "Transaction handle is no longer active");
|
|
107
|
+
if (guard(operation))
|
|
108
|
+
replicaEpoch ??= storage.epoch;
|
|
109
|
+
const result = await engine.operation(operation);
|
|
110
|
+
validate?.(result);
|
|
111
|
+
return result;
|
|
112
|
+
}).catch(error => { failed = true; failure = error; throw error; }).finally(() => { pending--; });
|
|
113
|
+
statements = result;
|
|
114
|
+
void result.catch(() => { });
|
|
115
|
+
return result;
|
|
116
|
+
};
|
|
117
|
+
try {
|
|
118
|
+
const tx = transactionDatabase(schema, true, request);
|
|
119
|
+
const result = await Promise.race([
|
|
120
|
+
Promise.resolve().then(() => handler(tx)),
|
|
121
|
+
new Promise((_, reject) => {
|
|
122
|
+
timer = setTimeout(() => reject(sqliteFailure("transaction_timeout", "SQLite transaction callback exceeded its deadline")), timeoutMs);
|
|
123
|
+
}),
|
|
124
|
+
]);
|
|
125
|
+
live = false;
|
|
126
|
+
if (pending)
|
|
127
|
+
throw sqliteFailure("unawaited_operations", "Await all database operations before returning from a transaction");
|
|
128
|
+
if (failed)
|
|
129
|
+
throw failure;
|
|
130
|
+
if (replicaEpoch !== undefined && replicaEpoch !== storage.epoch)
|
|
131
|
+
throw sqliteFailure("context_changed", "Replica scope changed during the transaction");
|
|
132
|
+
return result;
|
|
133
|
+
}
|
|
134
|
+
finally {
|
|
135
|
+
clearTimeout(timer);
|
|
136
|
+
live = false;
|
|
137
|
+
// An already-started asynchronous driver operation must finish before rollback.
|
|
138
|
+
await statements.catch(() => { });
|
|
139
|
+
userTransaction = false;
|
|
140
|
+
}
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
const execute = (operation, validate) => atomic(async () => {
|
|
144
|
+
const replica = guard(operation), epoch = storage.epoch;
|
|
145
|
+
const result = await engine.operation(operation);
|
|
146
|
+
if (replica && epoch !== storage.epoch)
|
|
147
|
+
throw sqliteFailure("context_changed", "Replica scope changed");
|
|
148
|
+
validate?.(result);
|
|
149
|
+
return result;
|
|
150
|
+
});
|
|
151
|
+
const root = transactionDatabase(schema, true, execute);
|
|
152
|
+
let closing;
|
|
153
|
+
const database = Object.freeze({
|
|
154
|
+
...root,
|
|
155
|
+
transaction,
|
|
156
|
+
close() {
|
|
157
|
+
if (userTransaction)
|
|
158
|
+
return Promise.reject(sqliteFailure("transaction_scope", "Close SQLite after the transaction completes"));
|
|
159
|
+
if (!closing) {
|
|
160
|
+
closed = true;
|
|
161
|
+
closing = tail.then(() => driver.close());
|
|
162
|
+
}
|
|
163
|
+
return closing;
|
|
164
|
+
},
|
|
165
|
+
});
|
|
166
|
+
registerClientStorage(database, storage.factory);
|
|
167
|
+
registerStorageExecution(database, execute);
|
|
168
|
+
registerStorageChanges(database, listener => { listeners.add(listener); return () => { listeners.delete(listener); }; });
|
|
169
|
+
return database;
|
|
170
|
+
}
|
package/dist/worker.d.ts
ADDED
package/dist/worker.js
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,81 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hulla/db-sqlite",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "SQLite application instances and platform adapters for Hulla schemas",
|
|
6
|
+
"exports": {
|
|
7
|
+
".": {
|
|
8
|
+
"hulladb-worker": {
|
|
9
|
+
"types": "./dist/worker.d.ts",
|
|
10
|
+
"default": "./dist/worker.js"
|
|
11
|
+
},
|
|
12
|
+
"browser": {
|
|
13
|
+
"types": "./dist/browser.d.ts",
|
|
14
|
+
"default": "./dist/browser.js"
|
|
15
|
+
},
|
|
16
|
+
"types": "./dist/index.d.ts",
|
|
17
|
+
"default": "./dist/index.js"
|
|
18
|
+
},
|
|
19
|
+
"./node": {
|
|
20
|
+
"hulladb-worker": {
|
|
21
|
+
"types": "./dist/worker.d.ts",
|
|
22
|
+
"default": "./dist/worker.js"
|
|
23
|
+
},
|
|
24
|
+
"types": "./dist/node.d.ts",
|
|
25
|
+
"default": "./dist/node.js"
|
|
26
|
+
},
|
|
27
|
+
"./bun": {
|
|
28
|
+
"hulladb-worker": {
|
|
29
|
+
"types": "./dist/worker.d.ts",
|
|
30
|
+
"default": "./dist/worker.js"
|
|
31
|
+
},
|
|
32
|
+
"types": "./dist/bun.d.ts",
|
|
33
|
+
"default": "./dist/bun.js"
|
|
34
|
+
},
|
|
35
|
+
"./browser": {
|
|
36
|
+
"hulladb-worker": {
|
|
37
|
+
"types": "./dist/worker.d.ts",
|
|
38
|
+
"default": "./dist/worker.js"
|
|
39
|
+
},
|
|
40
|
+
"types": "./dist/browser.d.ts",
|
|
41
|
+
"default": "./dist/browser.js"
|
|
42
|
+
},
|
|
43
|
+
"./expo": {
|
|
44
|
+
"hulladb-worker": {
|
|
45
|
+
"types": "./dist/worker.d.ts",
|
|
46
|
+
"default": "./dist/worker.js"
|
|
47
|
+
},
|
|
48
|
+
"types": "./dist/expo.d.ts",
|
|
49
|
+
"default": "./dist/expo.js"
|
|
50
|
+
}
|
|
51
|
+
},
|
|
52
|
+
"files": [
|
|
53
|
+
"dist",
|
|
54
|
+
"README.md",
|
|
55
|
+
"LICENSE"
|
|
56
|
+
],
|
|
57
|
+
"peerDependencies": {
|
|
58
|
+
"@hulla/db": "^0.2.0"
|
|
59
|
+
},
|
|
60
|
+
"engines": {
|
|
61
|
+
"node": ">=22.18.0"
|
|
62
|
+
},
|
|
63
|
+
"license": "MIT",
|
|
64
|
+
"author": {
|
|
65
|
+
"name": "Samuel Hulla",
|
|
66
|
+
"url": "https://hulla.dev"
|
|
67
|
+
},
|
|
68
|
+
"homepage": "https://github.com/hulladev/db#readme",
|
|
69
|
+
"repository": {
|
|
70
|
+
"type": "git",
|
|
71
|
+
"url": "git+https://github.com/hulladev/db.git",
|
|
72
|
+
"directory": "packages/db-sqlite"
|
|
73
|
+
},
|
|
74
|
+
"bugs": {
|
|
75
|
+
"url": "https://github.com/hulladev/db/issues"
|
|
76
|
+
},
|
|
77
|
+
"publishConfig": {
|
|
78
|
+
"access": "public",
|
|
79
|
+
"registry": "https://registry.npmjs.org/"
|
|
80
|
+
}
|
|
81
|
+
}
|