@velarscript-labs/sqlite 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/CHANGELOG.md ADDED
@@ -0,0 +1,12 @@
1
+ # Changelog
2
+
3
+ ## 0.2.0 — 2026-08-23
4
+
5
+ - Publish the companion package as `@velarscript-labs/sqlite`, outside the
6
+ Standard/toolchain scope.
7
+ - Replace the historical ORM-shaped adapter with a parameterized SQL capability.
8
+ - Add a bounded Worker queue, runtime-typed rows, automatic transaction scope,
9
+ reentrancy rejection, safe-integer handling, and idempotent cleanup.
10
+
11
+ Version 0.1.0 was published from the VelarScript main repository and is not the
12
+ implementation restored here.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,47 @@
1
+ # @velarscript-labs/sqlite
2
+
3
+ A bounded asynchronous SQLite capability for VelarScript Node applications,
4
+ backed by Node's built-in SQLite driver on one owned Worker thread.
5
+
6
+ The API deliberately stops at parameterized SQL. It does not provide models,
7
+ repositories, schema inference, an ORM, or application migrations. Those are
8
+ application data and policy, not a reusable driver concern.
9
+
10
+ ```velar
11
+ import {SqliteTransaction, openSqlite} from "@velarscript-labs/sqlite"
12
+
13
+ type User:
14
+ id: number
15
+ name: string
16
+
17
+ using database = await openSqlite("app.sqlite")
18
+ await database.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT NOT NULL)")
19
+
20
+ async def create(transaction: SqliteTransaction) -> User:
21
+ await transaction.execute("INSERT INTO users (id, name) VALUES (?, ?)", [1, "Ada"])
22
+ return (await transaction.one("SELECT id, name FROM users WHERE id = ?", User, [1]))!
23
+
24
+ const user = await database.transaction(create)
25
+ ```
26
+
27
+ ## Bounds and concurrency
28
+
29
+ - One Worker owns one SQLite connection; all connection operations are queued
30
+ and serialized.
31
+ - `queueCapacity` bounds admitted operations. Default 64, maximum 1,024.
32
+ - One statement accepts at most 999 parameters and 1 MiB of SQL text.
33
+ - `maxRows` defaults to 10,000 and is capped at 1,000,000.
34
+ - `maxResultBytes` defaults to 64 MiB and is capped at 128 MiB. It also bounds
35
+ parameter bytes for one operation.
36
+ - Numbers must be finite; integer parameters and results must fit JavaScript's
37
+ safe integer range. BLOB values use `Bytes`.
38
+ - A transaction callback is the exclusive connection owner. Use the supplied
39
+ `SqliteTransaction`; calling the connection from that callback fails with
40
+ `SqliteConcurrencyError` instead of waiting on itself.
41
+ - The callback commits on success and rolls back on failure. Transactions do
42
+ not expose manual commit/rollback handles.
43
+ - `close` is idempotent, joins concurrent callers, drains admitted work, rolls
44
+ back an active transaction, closes the driver, and waits for the Worker.
45
+
46
+ Cancellation and streaming are intentionally absent from version 0.2. They
47
+ will not be claimed until their cleanup and backpressure contracts are proven.
package/package.json ADDED
@@ -0,0 +1,36 @@
1
+ {
2
+ "name": "@velarscript-labs/sqlite",
3
+ "version": "0.2.0",
4
+ "description": "Bounded asynchronous SQLite capability for VelarScript Node applications.",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "files": [
8
+ "src/index.vel",
9
+ "README.md",
10
+ "CHANGELOG.md",
11
+ "LICENSE"
12
+ ],
13
+ "scripts": {
14
+ "check": "velar format --check && velar check",
15
+ "test": "velar test"
16
+ },
17
+ "engines": {
18
+ "node": ">=24"
19
+ },
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "git+https://github.com/VelarOS-AI/VelarScript-Libraries.git",
23
+ "directory": "packages/sqlite"
24
+ },
25
+ "publishConfig": {
26
+ "access": "public"
27
+ },
28
+ "velar": {
29
+ "entry": "src/index.vel",
30
+ "targets": ["node"],
31
+ "requires": {"capabilities": ["node"], "language": ">=0.13 <0.14"}
32
+ },
33
+ "dependencies": {
34
+ "@velarscript-labs/database": "0.2.0"
35
+ }
36
+ }
package/src/index.vel ADDED
@@ -0,0 +1,634 @@
1
+ /// Per-connection bounds. Every operation is serialized through one Worker;
2
+ /// queueCapacity bounds admitted operations waiting for that connection.
3
+ import {DatabaseExecutor} from "@velarscript-labs/database"
4
+
5
+ export type SqliteOptions:
6
+ busyTimeoutMilliseconds: number?
7
+ queueCapacity: number?
8
+ maxRows: number?
9
+ maxResultBytes: number?
10
+
11
+ extern js()`
12
+ import { AsyncLocalStorage } from "node:async_hooks";
13
+ import { Worker } from "node:worker_threads";
14
+
15
+ const TOKEN = Object.freeze({});
16
+ const connectionStates = new WeakMap();
17
+ const transactionStates = new WeakMap();
18
+ const transactionContext = new AsyncLocalStorage();
19
+
20
+ export class NativeSqliteError extends Error {
21
+ constructor(message = "SQLite operation failed", sqliteCode = null, operation = "unknown", retryable = false) {
22
+ super(message);
23
+ this.name = "NativeSqliteError";
24
+ this.sqliteCode = sqliteCode;
25
+ this.operation = operation;
26
+ this.retryable = retryable;
27
+ }
28
+ }
29
+
30
+ export class NativeSqliteBackpressureError extends NativeSqliteError {
31
+ constructor(message = "SQLite queue is full") {
32
+ super(message, "SQLITE_BACKPRESSURE", "queue", true);
33
+ this.name = "NativeSqliteBackpressureError";
34
+ }
35
+ }
36
+
37
+ export class NativeSqliteConcurrencyError extends NativeSqliteError {
38
+ constructor(message = "SQLite connection cannot be used from its transaction callback") {
39
+ super(message, "SQLITE_CONCURRENCY", "transaction", true);
40
+ this.name = "NativeSqliteConcurrencyError";
41
+ }
42
+ }
43
+
44
+ function integer(value, fallback, minimum, maximum, label) {
45
+ const selected = value == null ? fallback : value;
46
+ if (!Number.isSafeInteger(selected) || selected < minimum || selected > maximum) {
47
+ throw new TypeError(label + " must be an integer from " + minimum + " through " + maximum);
48
+ }
49
+ return selected;
50
+ }
51
+
52
+ function checkedOptions(value) {
53
+ if (value === null || typeof value !== "object" || Array.isArray(value)) throw new TypeError("SQLite options must be a record");
54
+ const allowed = new Set(["busyTimeoutMilliseconds", "queueCapacity", "maxRows", "maxResultBytes"]);
55
+ for (const key of Object.keys(value)) if (!allowed.has(key)) throw new TypeError("Unknown SQLite option " + key);
56
+ return {
57
+ busyTimeoutMilliseconds: integer(value.busyTimeoutMilliseconds, 2000, 1, 60000, "SQLite busy timeout"),
58
+ queueCapacity: integer(value.queueCapacity, 64, 1, 1024, "SQLite queue capacity"),
59
+ maxRows: integer(value.maxRows, 10000, 1, 1000000, "SQLite row limit"),
60
+ maxResultBytes: integer(value.maxResultBytes, 64 * 1024 * 1024, 1, 128 * 1024 * 1024, "SQLite result byte limit"),
61
+ };
62
+ }
63
+
64
+ function workerMain() {
65
+ const { Buffer } = require("node:buffer");
66
+ const { parentPort, workerData } = require("node:worker_threads");
67
+ const { DatabaseSync } = require("node:sqlite");
68
+ let database = null;
69
+ let closed = false;
70
+
71
+ function failure(message, code, operation, retryable = false) {
72
+ const error = new Error(message);
73
+ error.code = code;
74
+ error.operation = operation;
75
+ error.retryable = retryable;
76
+ return error;
77
+ }
78
+
79
+ function errorData(error, operation) {
80
+ const message = error instanceof Error ? error.message : String(error);
81
+ const rawCode = error && typeof error === "object" ? error.errstr ?? error.code ?? null : null;
82
+ const code = rawCode == null ? null : String(rawCode);
83
+ const upper = code == null ? "" : code.toUpperCase();
84
+ return {
85
+ message,
86
+ sqliteCode: code,
87
+ operation: error && typeof error.operation === "string" ? error.operation : operation,
88
+ retryable: error && error.retryable === true || upper.includes("BUSY") || upper.includes("LOCKED"),
89
+ };
90
+ }
91
+
92
+ function sqlText(value, operation) {
93
+ if (typeof value !== "string" || value.length === 0 || value.length > 1024 * 1024 || value.includes("\0")) {
94
+ throw failure("SQLite SQL must be non-empty text no longer than 1 MiB", "SQLITE_INPUT", operation);
95
+ }
96
+ return value;
97
+ }
98
+
99
+ function parameter(value, budget) {
100
+ if (value === null) return null;
101
+ if (typeof value === "boolean") return value ? 1 : 0;
102
+ if (typeof value === "string") {
103
+ budget.value += Buffer.byteLength(value, "utf8");
104
+ return value;
105
+ }
106
+ if (typeof value === "number") {
107
+ if (!Number.isFinite(value)) throw failure("SQLite number parameters must be finite", "SQLITE_INPUT", "params");
108
+ if (Number.isInteger(value) && !Number.isSafeInteger(value)) throw failure("SQLite integer parameters must be safe integers", "SQLITE_INPUT", "params");
109
+ budget.value += 8;
110
+ return value;
111
+ }
112
+ if (value instanceof Uint8Array) {
113
+ budget.value += value.byteLength;
114
+ return value;
115
+ }
116
+ throw failure("SQLite parameters support only null, bool, string, finite number, and Bytes", "SQLITE_INPUT", "params");
117
+ }
118
+
119
+ function parameters(value) {
120
+ if (!Array.isArray(value) || value.length > 999) throw failure("SQLite parameters must be a List with at most 999 values", "SQLITE_INPUT", "params");
121
+ const budget = { value: 0 };
122
+ const output = value.map(item => parameter(item, budget));
123
+ if (budget.value > workerData.maxResultBytes) throw failure("SQLite parameters exceed the connection byte limit", "SQLITE_INPUT", "params");
124
+ return output;
125
+ }
126
+
127
+ function count(value, label) {
128
+ const number = typeof value === "bigint" ? Number(value) : value;
129
+ if (!Number.isSafeInteger(number) || number < 0) throw failure(label + " is outside VelarScript's safe integer range", "SQLITE_INTEGER_RANGE", "result");
130
+ return number;
131
+ }
132
+
133
+ function resultValue(value, budget, field) {
134
+ if (value === null) return null;
135
+ if (typeof value === "string") {
136
+ budget.value += Buffer.byteLength(value, "utf8");
137
+ return value;
138
+ }
139
+ if (typeof value === "number") {
140
+ if (!Number.isFinite(value)) throw failure("SQLite returned a non-finite number in " + field, "SQLITE_RESULT", "result");
141
+ budget.value += 8;
142
+ return value;
143
+ }
144
+ if (typeof value === "bigint") {
145
+ const number = Number(value);
146
+ if (!Number.isSafeInteger(number)) throw failure("SQLite returned an integer outside VelarScript's safe range in " + field, "SQLITE_INTEGER_RANGE", "result");
147
+ budget.value += 8;
148
+ return number;
149
+ }
150
+ if (value instanceof Uint8Array) {
151
+ budget.value += value.byteLength;
152
+ return value;
153
+ }
154
+ throw failure("SQLite returned an unsupported value in " + field, "SQLITE_RESULT", "result");
155
+ }
156
+
157
+ function resultRow(value, budget) {
158
+ if (value === null || typeof value !== "object" || Array.isArray(value)) throw failure("SQLite returned a non-record row", "SQLITE_RESULT", "result");
159
+ const output = Object.create(null);
160
+ for (const key of Object.keys(value)) {
161
+ budget.value += Buffer.byteLength(key, "utf8");
162
+ output[key] = resultValue(value[key], budget, key);
163
+ if (budget.value > workerData.maxResultBytes) throw failure("SQLite result exceeds the connection byte limit", "SQLITE_RESULT_LIMIT", "result");
164
+ }
165
+ return output;
166
+ }
167
+
168
+ function statement(sql, operation) {
169
+ const prepared = database.prepare(sqlText(sql, operation));
170
+ if (typeof prepared.setReadBigInts === "function") prepared.setReadBigInts(true);
171
+ return prepared;
172
+ }
173
+
174
+ function execute(message) {
175
+ const prepared = statement(message.sql, "execute");
176
+ const result = prepared.run(...parameters(message.params));
177
+ return count(result.changes, "SQLite affected row count");
178
+ }
179
+
180
+ function one(message) {
181
+ const prepared = statement(message.sql, "one");
182
+ const row = prepared.get(...parameters(message.params));
183
+ if (row === undefined) return null;
184
+ return resultRow(row, { value: 0 });
185
+ }
186
+
187
+ function all(message) {
188
+ const prepared = statement(message.sql, "all");
189
+ const rows = [];
190
+ const budget = { value: 0 };
191
+ for (const row of prepared.iterate(...parameters(message.params))) {
192
+ if (rows.length >= workerData.maxRows) throw failure("SQLite result exceeds the connection row limit", "SQLITE_ROW_LIMIT", "all");
193
+ rows.push(resultRow(row, budget));
194
+ }
195
+ return rows;
196
+ }
197
+
198
+ function dispatch(message) {
199
+ if (closed) throw failure("SQLite connection is closed", "SQLITE_CLOSED", message.operation);
200
+ if (message.operation === "execute") return execute(message);
201
+ if (message.operation === "one") return one(message);
202
+ if (message.operation === "all") return all(message);
203
+ if (message.operation === "begin") {
204
+ if (database.isTransaction) throw failure("SQLite transaction is already active", "SQLITE_TRANSACTION", "begin", true);
205
+ database.exec("BEGIN IMMEDIATE");
206
+ return null;
207
+ }
208
+ if (message.operation === "commit") {
209
+ if (!database.isTransaction) throw failure("SQLite transaction is not active", "SQLITE_TRANSACTION", "commit");
210
+ database.exec("COMMIT");
211
+ return null;
212
+ }
213
+ if (message.operation === "rollback") {
214
+ if (database.isTransaction) database.exec("ROLLBACK");
215
+ return null;
216
+ }
217
+ if (message.operation === "close") {
218
+ try {
219
+ if (database.isTransaction) database.exec("ROLLBACK");
220
+ } finally {
221
+ database.close();
222
+ closed = true;
223
+ }
224
+ return null;
225
+ }
226
+ throw failure("Unknown SQLite operation", "SQLITE_PROTOCOL", String(message.operation));
227
+ }
228
+
229
+ try {
230
+ database = new DatabaseSync(workerData.path, { timeout: workerData.busyTimeoutMilliseconds });
231
+ database.exec("PRAGMA foreign_keys = ON");
232
+ parentPort.postMessage({ kind: "ready" });
233
+ } catch (error) {
234
+ parentPort.postMessage({ kind: "ready", error: errorData(error, "open") });
235
+ parentPort.close();
236
+ return;
237
+ }
238
+
239
+ parentPort.on("message", message => {
240
+ try {
241
+ const value = dispatch(message);
242
+ parentPort.postMessage({ kind: "response", id: message.id, value });
243
+ if (message.operation === "close") parentPort.close();
244
+ } catch (error) {
245
+ parentPort.postMessage({ kind: "response", id: message.id, error: errorData(error, message.operation) });
246
+ }
247
+ });
248
+ }
249
+
250
+ function nativeError(value) {
251
+ return new NativeSqliteError(value.message, value.sqliteCode, value.operation, value.retryable);
252
+ }
253
+
254
+ function failPending(state, error) {
255
+ if (state.readyReject !== null) {
256
+ state.readyReject(error);
257
+ state.readyReject = null;
258
+ state.readyResolve = null;
259
+ }
260
+ for (const pending of state.pending.values()) pending.reject(error);
261
+ state.pending.clear();
262
+ }
263
+
264
+ function request(state, operation, sql = "", params = []) {
265
+ if (state.closed) return Promise.reject(new NativeSqliteError("SQLite connection is closed", "SQLITE_CLOSED", operation));
266
+ const id = state.nextId++;
267
+ return new Promise((resolve, reject) => {
268
+ state.pending.set(id, { resolve, reject });
269
+ try {
270
+ state.worker.postMessage({ id, operation, sql, params });
271
+ } catch (error) {
272
+ state.pending.delete(id);
273
+ reject(error);
274
+ }
275
+ });
276
+ }
277
+
278
+ function stateOf(connection) {
279
+ const state = connectionStates.get(connection);
280
+ if (!state) throw new TypeError("Invalid SQLite connection");
281
+ return state;
282
+ }
283
+
284
+ function transactionStateOf(transaction) {
285
+ const state = transactionStates.get(transaction);
286
+ if (!state || !state.active) throw new NativeSqliteConcurrencyError("SQLite transaction is no longer active");
287
+ return state;
288
+ }
289
+
290
+ function transactionRequest(transaction, operation, sql = "", params = []) {
291
+ const state = transactionStateOf(transaction);
292
+ if (state.busy) return Promise.reject(new NativeSqliteConcurrencyError("SQLite transaction operations must be awaited one at a time"));
293
+ state.busy = true;
294
+ return request(state.connection, operation, sql, params).finally(() => { state.busy = false; });
295
+ }
296
+
297
+ function enqueue(state, operation) {
298
+ if (state.closed || state.closing) return Promise.reject(new NativeSqliteError("SQLite connection is closed", "SQLITE_CLOSED", "queue"));
299
+ if (transactionContext.getStore() === state) return Promise.reject(new NativeSqliteConcurrencyError());
300
+ if (state.queued >= state.queueCapacity) return Promise.reject(new NativeSqliteBackpressureError());
301
+ state.queued += 1;
302
+ const running = state.tail.then(operation, operation);
303
+ state.tail = running.then(() => null, () => null);
304
+ return running.finally(() => { state.queued -= 1; });
305
+ }
306
+
307
+ export class NativeSqliteTransaction {
308
+ constructor(token, state) {
309
+ if (token !== TOKEN) throw new TypeError("SQLite transactions are created by connection.transaction");
310
+ transactionStates.set(this, state);
311
+ }
312
+
313
+ execute(sql, params = []) { return transactionRequest(this, "execute", sql, params); }
314
+ one(sql, params = []) { return transactionRequest(this, "one", sql, params); }
315
+ all(sql, params = []) { return transactionRequest(this, "all", sql, params); }
316
+ }
317
+
318
+ export class NativeSqliteConnection {
319
+ constructor(token, state) {
320
+ if (token !== TOKEN) throw new TypeError("Use openSqlite to create a SQLite connection");
321
+ connectionStates.set(this, state);
322
+ }
323
+
324
+ execute(sql, params = []) {
325
+ const state = stateOf(this);
326
+ return enqueue(state, () => request(state, "execute", sql, params));
327
+ }
328
+
329
+ one(sql, params = []) {
330
+ const state = stateOf(this);
331
+ return enqueue(state, () => request(state, "one", sql, params));
332
+ }
333
+
334
+ all(sql, params = []) {
335
+ const state = stateOf(this);
336
+ return enqueue(state, () => request(state, "all", sql, params));
337
+ }
338
+
339
+ transaction(operation) {
340
+ if (typeof operation !== "function") return Promise.reject(new TypeError("SQLite transaction requires an async operation"));
341
+ const state = stateOf(this);
342
+ return enqueue(state, async () => {
343
+ await request(state, "begin");
344
+ const transactionState = { connection: state, active: true, busy: false };
345
+ const transaction = new NativeSqliteTransaction(TOKEN, transactionState);
346
+ try {
347
+ await transactionContext.run(state, () => operation(transaction));
348
+ await transactionRequest(transaction, "commit");
349
+ transactionState.active = false;
350
+ return null;
351
+ } catch (error) {
352
+ try {
353
+ if (transactionState.active) await transactionRequest(transaction, "rollback");
354
+ } catch {
355
+ state.closing = true;
356
+ state.worker.terminate();
357
+ } finally {
358
+ transactionState.active = false;
359
+ }
360
+ throw error;
361
+ }
362
+ });
363
+ }
364
+
365
+ close() {
366
+ const state = stateOf(this);
367
+ if (state.closePromise !== null) return state.closePromise;
368
+ if (transactionContext.getStore() === state) return Promise.reject(new NativeSqliteConcurrencyError("SQLite connection cannot close inside its transaction callback"));
369
+ state.closing = true;
370
+ state.closePromise = state.tail.then(async () => {
371
+ try {
372
+ if (!state.closed) await request(state, "close");
373
+ await state.exited;
374
+ } finally {
375
+ state.closed = true;
376
+ }
377
+ });
378
+ return state.closePromise;
379
+ }
380
+ }
381
+
382
+ export async function openNativeSqlite(path, options = {}) {
383
+ if (typeof path !== "string" || path.trim() === "" || path.length > 4096 || path.includes("\0")) throw new TypeError("SQLite path must be non-empty bounded text");
384
+ const checked = checkedOptions(options);
385
+ const source = "(" + workerMain.toString() + ")()";
386
+ const worker = new Worker(source, { eval: true, workerData: { path, ...checked } });
387
+ let readyResolve;
388
+ let readyReject;
389
+ let exitResolve;
390
+ const ready = new Promise((resolve, reject) => { readyResolve = resolve; readyReject = reject; });
391
+ const exited = new Promise(resolve => { exitResolve = resolve; });
392
+ const state = {
393
+ worker,
394
+ readyResolve,
395
+ readyReject,
396
+ exited,
397
+ pending: new Map(),
398
+ nextId: 1,
399
+ queueCapacity: checked.queueCapacity,
400
+ queued: 0,
401
+ tail: Promise.resolve(),
402
+ closing: false,
403
+ closed: false,
404
+ closePromise: null,
405
+ };
406
+ worker.on("message", message => {
407
+ if (message.kind === "ready") {
408
+ const resolve = state.readyResolve;
409
+ const reject = state.readyReject;
410
+ state.readyResolve = null;
411
+ state.readyReject = null;
412
+ if (message.error) reject(nativeError(message.error));
413
+ else resolve();
414
+ return;
415
+ }
416
+ if (message.kind !== "response") return;
417
+ const pending = state.pending.get(message.id);
418
+ if (!pending) return;
419
+ state.pending.delete(message.id);
420
+ if (message.error) pending.reject(nativeError(message.error));
421
+ else pending.resolve(message.value);
422
+ });
423
+ worker.on("error", error => {
424
+ state.closed = true;
425
+ failPending(state, new NativeSqliteError(error.message, "SQLITE_WORKER", "worker"));
426
+ });
427
+ worker.on("exit", code => {
428
+ exitResolve(code);
429
+ if (code !== 0 && !state.closed) {
430
+ state.closed = true;
431
+ failPending(state, new NativeSqliteError("SQLite Worker exited with code " + code, "SQLITE_WORKER", "worker"));
432
+ }
433
+ });
434
+ await ready;
435
+ return new NativeSqliteConnection(TOKEN, state);
436
+ }
437
+ `:
438
+ export class NativeSqliteError:
439
+ const message: string
440
+ const sqliteCode: string?
441
+ const operation: string
442
+ const retryable: bool
443
+
444
+ export class NativeSqliteBackpressureError:
445
+ const message: string
446
+
447
+ export class NativeSqliteConcurrencyError:
448
+ const message: string
449
+
450
+ export class NativeSqliteTransaction:
451
+ async def execute(sql: string, params: List<unknown> = []) -> number
452
+ async def one(sql: string, params: List<unknown> = []) -> unknown
453
+ async def all(sql: string, params: List<unknown> = []) -> List<unknown>
454
+
455
+ export class NativeSqliteConnection:
456
+ async def execute(sql: string, params: List<unknown> = []) -> number
457
+ async def one(sql: string, params: List<unknown> = []) -> unknown
458
+ async def all(sql: string, params: List<unknown> = []) -> List<unknown>
459
+ async def transaction(operation: (NativeSqliteTransaction) -> Promise<null>) -> null
460
+ async def close() -> null
461
+
462
+ export async def openNativeSqlite(path: string, options: SqliteOptions = {}) -> NativeSqliteConnection
463
+
464
+ /// A checked SQLite failure. sqliteCode preserves the driver result code when
465
+ /// Node exposes one; retryable is true for busy, locked, and queue pressure.
466
+ export class SqliteError extends Error:
467
+ const sqliteCode: string?
468
+ const operation: string
469
+ const retryable: bool
470
+
471
+ constructor(message: string, sqliteCode: string? = null, operation: string = "unknown", retryable: bool = false):
472
+ super(message)
473
+ self.sqliteCode = sqliteCode
474
+ self.operation = operation
475
+ self.retryable = retryable
476
+
477
+ export class SqliteBackpressureError extends SqliteError:
478
+ constructor(message: string = "SQLite queue is full"):
479
+ super(message, "SQLITE_BACKPRESSURE", "queue", true)
480
+
481
+ export class SqliteConcurrencyError extends SqliteError:
482
+ constructor(message: string = "SQLite connection cannot be used from its transaction callback"):
483
+ super(message, "SQLITE_CONCURRENCY", "transaction", true)
484
+
485
+ def sqliteFailure(error: NativeSqliteError) -> SqliteError:
486
+ if error is NativeSqliteBackpressureError:
487
+ return SqliteBackpressureError(error.message)
488
+ if error is NativeSqliteConcurrencyError:
489
+ return SqliteConcurrencyError(error.message)
490
+ if error is NativeSqliteError:
491
+ return SqliteError(error.message, error.sqliteCode, error.operation, error.retryable)
492
+ return SqliteError(error.message)
493
+
494
+ export class SqliteTransaction:
495
+ constructor(private const native: NativeSqliteTransaction):
496
+ pass
497
+
498
+ async def execute(sql: string, params: List<unknown> = []) -> number:
499
+ try:
500
+ return await self.native.execute(sql, params)
501
+ catch error:
502
+ if error is NativeSqliteError:
503
+ throw sqliteFailure(error)
504
+ throw SqliteError(error.message)
505
+
506
+ /// Projects this transaction into the engine-neutral functional operation layer.
507
+ def executor() -> DatabaseExecutor:
508
+ async def executeStatement(text: string, parameters: List<unknown>) -> number:
509
+ return await self.execute(text, parameters)
510
+
511
+ async def oneRow(text: string, parameters: List<unknown>) -> unknown:
512
+ try:
513
+ return await self.native.one(text, parameters)
514
+ catch error:
515
+ if error is NativeSqliteError:
516
+ throw sqliteFailure(error)
517
+ throw SqliteError(error.message)
518
+
519
+ async def allRows(text: string, parameters: List<unknown>) -> List<unknown>:
520
+ try:
521
+ return await self.native.all(text, parameters)
522
+ catch error:
523
+ if error is NativeSqliteError:
524
+ throw sqliteFailure(error)
525
+ throw SqliteError(error.message)
526
+
527
+ return {execute: executeStatement, one: oneRow, all: allRows}
528
+
529
+ async def one<T>(sql: string, RowType: Type<T>, params: List<unknown> = []) -> T?:
530
+ try:
531
+ const row = await self.native.one(sql, params)
532
+ if row == null:
533
+ return null
534
+ return RowType.parse(row)
535
+ catch error:
536
+ if error is NativeSqliteError:
537
+ throw sqliteFailure(error)
538
+ throw SqliteError(error.message)
539
+
540
+ async def all<T>(sql: string, RowType: Type<T>, params: List<unknown> = []) -> List<T>:
541
+ try:
542
+ const rows = await self.native.all(sql, params)
543
+ return rows.map(row => RowType.parse(row))
544
+ catch error:
545
+ if error is NativeSqliteError:
546
+ throw sqliteFailure(error)
547
+ throw SqliteError(error.message)
548
+
549
+ export class SqliteConnection:
550
+ constructor(private const native: NativeSqliteConnection):
551
+ pass
552
+
553
+ async def execute(sql: string, params: List<unknown> = []) -> number:
554
+ try:
555
+ return await self.native.execute(sql, params)
556
+ catch error:
557
+ if error is NativeSqliteError:
558
+ throw sqliteFailure(error)
559
+ throw SqliteError(error.message)
560
+
561
+ /// Projects this connection into the engine-neutral functional operation layer.
562
+ def executor() -> DatabaseExecutor:
563
+ async def executeStatement(text: string, parameters: List<unknown>) -> number:
564
+ return await self.execute(text, parameters)
565
+
566
+ async def oneRow(text: string, parameters: List<unknown>) -> unknown:
567
+ try:
568
+ return await self.native.one(text, parameters)
569
+ catch error:
570
+ if error is NativeSqliteError:
571
+ throw sqliteFailure(error)
572
+ throw SqliteError(error.message)
573
+
574
+ async def allRows(text: string, parameters: List<unknown>) -> List<unknown>:
575
+ try:
576
+ return await self.native.all(text, parameters)
577
+ catch error:
578
+ if error is NativeSqliteError:
579
+ throw sqliteFailure(error)
580
+ throw SqliteError(error.message)
581
+
582
+ return {execute: executeStatement, one: oneRow, all: allRows}
583
+
584
+ async def one<T>(sql: string, RowType: Type<T>, params: List<unknown> = []) -> T?:
585
+ try:
586
+ const row = await self.native.one(sql, params)
587
+ if row == null:
588
+ return null
589
+ return RowType.parse(row)
590
+ catch error:
591
+ if error is NativeSqliteError:
592
+ throw sqliteFailure(error)
593
+ throw SqliteError(error.message)
594
+
595
+ async def all<T>(sql: string, RowType: Type<T>, params: List<unknown> = []) -> List<T>:
596
+ try:
597
+ const rows = await self.native.all(sql, params)
598
+ return rows.map(row => RowType.parse(row))
599
+ catch error:
600
+ if error is NativeSqliteError:
601
+ throw sqliteFailure(error)
602
+ throw SqliteError(error.message)
603
+
604
+ async def transaction<T>(operation: (SqliteTransaction) -> Promise<T>) -> T:
605
+ const results: List<T> = []
606
+ async def run<T>(native: NativeSqliteTransaction):
607
+ results.append(await operation(SqliteTransaction(native)))
608
+ try:
609
+ await self.native.transaction(run)
610
+ assert results.size == 1 else "SQLite transaction did not return exactly one result"
611
+ return results[0]
612
+ catch error:
613
+ if error is NativeSqliteError:
614
+ throw sqliteFailure(error)
615
+ throw error
616
+
617
+ async def close():
618
+ try:
619
+ await self.native.close()
620
+ catch error:
621
+ if error is NativeSqliteError:
622
+ throw sqliteFailure(error)
623
+ throw SqliteError(error.message)
624
+
625
+ @dispose:
626
+ await self.close()
627
+
628
+ export async def openSqlite(path: string, options: SqliteOptions = {}) -> SqliteConnection:
629
+ try:
630
+ return SqliteConnection(await openNativeSqlite(path, options))
631
+ catch error:
632
+ if error is NativeSqliteError:
633
+ throw sqliteFailure(error)
634
+ throw SqliteError(error.message)