@tursodatabase/database-common 0.7.0-pre.9 → 0.7.1-pre.1

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/README.md CHANGED
@@ -4,5 +4,5 @@ This package is the Turso embedded database common JS library which is shared be
4
4
 
5
5
  Do not use this package directly - instead you must use `@tursodatabase/database` or `@tursodatabase/database-wasm`.
6
6
 
7
- > **⚠️ Warning:** This software is in BETA. It may still contain bugs and unexpected behavior. Use caution with production data and ensure you have backups.
7
+ Turso Database runs in production today at multiple organizations. It has not yet reached 1.0, so as with any database we recommend keeping backups — see the [FAQ](https://github.com/tursodatabase/turso#faq) for where the project stands.
8
8
 
@@ -2,7 +2,7 @@ export declare class AsyncLock {
2
2
  locked: boolean;
3
3
  queue: any[];
4
4
  constructor();
5
- acquire(): Promise<unknown>;
5
+ acquire(): Promise<void>;
6
6
  release(): void;
7
7
  }
8
8
  //# sourceMappingURL=async-lock.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"async-lock.d.ts","sourceRoot":"","sources":["../async-lock.ts"],"names":[],"mappings":"AAAA,qBAAa,SAAS;IAClB,MAAM,EAAE,OAAO,CAAC;IAChB,KAAK,EAAE,GAAG,EAAE,CAAC;;IAKP,OAAO;IASb,OAAO;CAYV"}
1
+ {"version":3,"file":"async-lock.d.ts","sourceRoot":"","sources":["../async-lock.ts"],"names":[],"mappings":"AAAA,qBAAa,SAAS;IAClB,MAAM,EAAE,OAAO,CAAC;IAChB,KAAK,EAAE,GAAG,EAAE,CAAC;;IAKP,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IAS9B,OAAO;CAYV"}
package/dist/compat.d.ts CHANGED
@@ -1,4 +1,16 @@
1
1
  import { NativeDatabase, NativeStatement, QueryOptions } from "./types.js";
2
+ export type BatchMode = "write" | "read" | "deferred" | "immediate" | "exclusive" | "concurrent" | string;
3
+ export interface BatchOptions {
4
+ mode?: BatchMode;
5
+ raw?: boolean;
6
+ }
7
+ export type BatchRow = Record<string, any> | any[];
8
+ export interface ResultSet {
9
+ columns: Array<string>;
10
+ columnTypes: Array<string>;
11
+ rows: Array<BatchRow>;
12
+ rowsAffected: number;
13
+ }
2
14
  /**
3
15
  * Database represents a connection that can prepare and execute SQL statements.
4
16
  */
@@ -48,6 +60,10 @@ declare class Database {
48
60
  * @param {string} sql - The string containing SQL statements to execute
49
61
  */
50
62
  exec(sql: any, queryOptions?: QueryOptions): void;
63
+ batch(statements: Array<string | {
64
+ sql: string;
65
+ args?: any[] | Record<string, any>;
66
+ }>, options?: BatchMode | BatchOptions): ResultSet[];
51
67
  /**
52
68
  * Interrupts the database connection.
53
69
  */
@@ -1 +1 @@
1
- {"version":3,"file":"compat.d.ts","sourceRoot":"","sources":["../compat.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,cAAc,EAAE,eAAe,EAAE,YAAY,EAAgC,MAAM,YAAY,CAAC;AAoDzG;;GAEG;AACH,cAAM,QAAQ;IACZ,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,OAAO,CAAC;IAClB,IAAI,EAAE,OAAO,CAAC;IACd,MAAM,EAAE,OAAO,CAAC;IAChB,aAAa,EAAE,OAAO,CAAC;IAEvB,OAAO,CAAC,EAAE,CAAiB;IAE3B;;;;;;;;;;OAUG;gBACS,EAAE,EAAE,cAAc;IAa9B;;;;OAIG;IACH,OAAO,CAAC,GAAG,KAAA;IAeX;;;;OAIG;IACH,WAAW,CAAC,EAAE,KAAA;IAgCd,MAAM,CAAC,MAAM,KAAA,EAAE,OAAO,KAAA;IAoBtB,MAAM,CAAC,QAAQ,KAAA,EAAE,OAAO,KAAA;IAIxB,SAAS,CAAC,OAAO,KAAA;IAIjB,QAAQ,CAAC,IAAI,KAAA,EAAE,OAAO,KAAA,EAAE,EAAE,KAAA;IAI1B,SAAS,CAAC,IAAI,KAAA,EAAE,OAAO,KAAA;IAIvB,KAAK,CAAC,IAAI,KAAA,EAAE,OAAO,KAAA;IAInB,aAAa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AM,CAAC;QAAC,IAAI,CAAC,EAAE,GAAG,EAAE,GAAG,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;KAAE,CAAC,EAC/E,OAAO,CAAC,EAAE,SAAS,GAAG,YAAY,GACjC,SAAS,EAAE;IA2Ed;;OAEG;IACH,SAAS;IAIT;;;;OAIG;IACH,mBAAmB,CAAC,MAAM,KAAA;IAI1B;;OAEG;IACH,KAAK;CAGN;AAED;;GAEG;AACH,cAAM,SAAS;IACb,IAAI,EAAE,eAAe,CAAC;IACtB,EAAE,EAAE,cAAc,CAAC;gBAEP,IAAI,EAAE,eAAe,EAAE,EAAE,EAAE,cAAc;IAKrD;;;;OAIG;IACH,GAAG,CAAC,GAAG,KAAA;IAKP;;;;OAIG;IACH,KAAK,CAAC,SAAS,KAAA;IAKf;;;;OAIG;IACH,YAAY,CAAC,MAAM,KAAA;IAKnB;;;;OAIG;IACH,OAAO;IAIP,IAAI,MAAM,SAET;IAED,IAAI,MAAM,IAAI,OAAO,CAEpB;IAED,IAAI,QAAQ,mBAEX;IAED;;OAEG;IACH,GAAG,CAAC,GAAG,cAAc,OAAA;;;;IA4BrB;;;;OAIG;IACH,GAAG,CAAC,GAAG,cAAc,OAAA;IAsBrB;;;;OAIG;IACF,OAAO,CAAC,GAAG,cAAc,OAAA;IAqB1B;;;;OAIG;IACH,GAAG,CAAC,GAAG,cAAc,OAAA;IAsBrB;;OAEG;IACH,SAAS;IAKT;;;;;OAKG;IACH,IAAI,CAAC,GAAG,cAAc,OAAA;IAStB,KAAK;CAGN;AAED,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,CAAA"}
package/dist/compat.js CHANGED
@@ -40,6 +40,43 @@ function toBindArgs(params) {
40
40
  }
41
41
  return [params];
42
42
  }
43
+ function normalizeBatchMode(mode) {
44
+ switch (String(mode).toLowerCase()) {
45
+ case "write":
46
+ return "IMMEDIATE";
47
+ case "read":
48
+ case "deferred":
49
+ return "DEFERRED";
50
+ case "immediate":
51
+ return "IMMEDIATE";
52
+ case "exclusive":
53
+ return "EXCLUSIVE";
54
+ case "concurrent":
55
+ return "CONCURRENT";
56
+ default:
57
+ return String(mode).toUpperCase();
58
+ }
59
+ }
60
+ function normalizeBatchOptions(options) {
61
+ if (options != null && typeof options === "object") {
62
+ return {
63
+ mode: options.mode,
64
+ raw: options.raw === true,
65
+ };
66
+ }
67
+ return {
68
+ mode: options,
69
+ raw: false,
70
+ };
71
+ }
72
+ function makeResultSet(columns, columnTypes, rows, rowsAffected) {
73
+ return {
74
+ columns,
75
+ columnTypes,
76
+ rows,
77
+ rowsAffected,
78
+ };
79
+ }
43
80
  /**
44
81
  * Database represents a connection that can prepare and execute SQL statements.
45
82
  */
@@ -196,6 +233,80 @@ class Database {
196
233
  exec.reset();
197
234
  }
198
235
  }
236
+ batch(statements, options) {
237
+ if (!Array.isArray(statements)) {
238
+ throw new TypeError("Expected first argument to be an array of statements");
239
+ }
240
+ if (!this.open) {
241
+ throw new TypeError("The database connection is not open");
242
+ }
243
+ const { mode, raw } = normalizeBatchOptions(options);
244
+ const wrap = mode != null && !this.db.inTransaction();
245
+ if (wrap) {
246
+ this.exec(`BEGIN ${normalizeBatchMode(mode)}`);
247
+ }
248
+ const results = [];
249
+ try {
250
+ for (const statement of statements) {
251
+ const sql = typeof statement === "string" ? statement : statement.sql;
252
+ const args = typeof statement === "string" ? undefined : statement.args;
253
+ const stmt = this.db.prepare(sql);
254
+ try {
255
+ if (args !== undefined) {
256
+ bindParams(stmt, [args]);
257
+ }
258
+ const cols = stmt.columns();
259
+ const columnNames = cols.map((c) => c.name);
260
+ const columnTypes = cols.map((c) => c.type ?? "");
261
+ if (columnNames.length > 0) {
262
+ stmt.raw(raw);
263
+ }
264
+ const totalChangesBefore = this.db.totalChanges();
265
+ const rows = [];
266
+ try {
267
+ while (true) {
268
+ const stepResult = stmt.stepSync();
269
+ if (stepResult === STEP_IO) {
270
+ this.db.ioLoopSync();
271
+ continue;
272
+ }
273
+ if (stepResult === STEP_DONE) {
274
+ break;
275
+ }
276
+ if (stepResult === STEP_ROW) {
277
+ rows.push(stmt.row());
278
+ }
279
+ }
280
+ const rowsAffected = columnNames.length > 0
281
+ ? 0
282
+ : this.db.totalChanges() !== totalChangesBefore ? this.db.changes() : 0;
283
+ results.push(makeResultSet(columnNames, columnTypes, rows, rowsAffected));
284
+ }
285
+ finally {
286
+ stmt.reset();
287
+ }
288
+ }
289
+ finally {
290
+ stmt.finalize();
291
+ }
292
+ }
293
+ if (wrap) {
294
+ this.exec("COMMIT");
295
+ }
296
+ }
297
+ catch (err) {
298
+ if (wrap) {
299
+ try {
300
+ this.exec("ROLLBACK");
301
+ }
302
+ catch {
303
+ // Keep the original statement error.
304
+ }
305
+ }
306
+ throw convertError(err);
307
+ }
308
+ return results;
309
+ }
199
310
  /**
200
311
  * Interrupts the database connection.
201
312
  */
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { NativeDatabase, NativeStatement, DatabaseOpts, EncryptionCipher, EncryptionOpts, ExperimentalFeature } from "./types.js";
2
2
  import { Database as DatabaseCompat, Statement as StatementCompat } from "./compat.js";
3
- import { Database as DatabasePromise, Statement as StatementPromise, TransactionFunction } from "./promise.js";
3
+ import { Database as DatabasePromise, Statement as StatementPromise, Transaction, TransactionFunction, AsyncTransactionFunction, assertTransactionCallback } from "./promise.js";
4
4
  import { SqliteError } from "./sqlite-error.js";
5
5
  import { AsyncLock } from "./async-lock.js";
6
- export { DatabaseOpts, ExperimentalFeature, EncryptionCipher, EncryptionOpts, DatabaseCompat, StatementCompat, DatabasePromise, StatementPromise, TransactionFunction, NativeDatabase, NativeStatement, SqliteError, AsyncLock };
6
+ export { DatabaseOpts, ExperimentalFeature, EncryptionCipher, EncryptionOpts, DatabaseCompat, StatementCompat, DatabasePromise, StatementPromise, Transaction, TransactionFunction, AsyncTransactionFunction, assertTransactionCallback, NativeDatabase, NativeStatement, SqliteError, AsyncLock };
7
7
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,eAAe,EAAE,YAAY,EAAE,gBAAgB,EAAE,cAAc,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC;AAClI,OAAO,EAAE,QAAQ,IAAI,cAAc,EAAE,SAAS,IAAI,eAAe,EAAE,MAAM,aAAa,CAAC;AACvF,OAAO,EAAE,QAAQ,IAAI,eAAe,EAAE,SAAS,IAAI,gBAAgB,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AAC/G,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAE5C,OAAO,EACH,YAAY,EACZ,mBAAmB,EACnB,gBAAgB,EAChB,cAAc,EACd,cAAc,EAAE,eAAe,EAC/B,eAAe,EAAE,gBAAgB,EAAE,mBAAmB,EACtD,cAAc,EAAE,eAAe,EAC/B,WAAW,EACX,SAAS,EACZ,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,eAAe,EAAE,YAAY,EAAE,gBAAgB,EAAE,cAAc,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC;AAClI,OAAO,EAAE,QAAQ,IAAI,cAAc,EAAE,SAAS,IAAI,eAAe,EAAE,MAAM,aAAa,CAAC;AACvF,OAAO,EAAE,QAAQ,IAAI,eAAe,EAAE,SAAS,IAAI,gBAAgB,EAAE,WAAW,EAAE,mBAAmB,EAAE,wBAAwB,EAAE,yBAAyB,EAAE,MAAM,cAAc,CAAC;AACjL,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAE5C,OAAO,EACH,YAAY,EACZ,mBAAmB,EACnB,gBAAgB,EAChB,cAAc,EACd,cAAc,EAAE,eAAe,EAC/B,eAAe,EAAE,gBAAgB,EAAE,WAAW,EAAE,mBAAmB,EAAE,wBAAwB,EAAE,yBAAyB,EACxH,cAAc,EAAE,eAAe,EAC/B,WAAW,EACX,SAAS,EACZ,CAAA"}
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { Database as DatabaseCompat, Statement as StatementCompat } from "./compat.js";
2
- import { Database as DatabasePromise, Statement as StatementPromise } from "./promise.js";
2
+ import { Database as DatabasePromise, Statement as StatementPromise, Transaction, assertTransactionCallback } from "./promise.js";
3
3
  import { SqliteError } from "./sqlite-error.js";
4
4
  import { AsyncLock } from "./async-lock.js";
5
- export { DatabaseCompat, StatementCompat, DatabasePromise, StatementPromise, SqliteError, AsyncLock };
5
+ export { DatabaseCompat, StatementCompat, DatabasePromise, StatementPromise, Transaction, assertTransactionCallback, SqliteError, AsyncLock };
package/dist/promise.d.ts CHANGED
@@ -1,16 +1,45 @@
1
1
  import { AsyncLock } from "./async-lock.js";
2
2
  import { NativeDatabase, NativeStatement, QueryOptions } from "./types.js";
3
3
  /**
4
- * Locking mode for `Database.batch(stmts, mode)` and the variants of
5
- * `Database.transaction(...)`. When passed to `batch()`, the statements are
6
- * wrapped in `BEGIN <mode>` / `COMMIT` (with `ROLLBACK` on failure).
4
+ * Locking mode for `Database.batch(stmts, options)`.
7
5
  */
8
- export type BatchMode = "deferred" | "immediate" | "exclusive" | "concurrent";
6
+ export type BatchMode = "write" | "read" | "deferred" | "immediate" | "exclusive" | "concurrent" | string;
7
+ export interface BatchOptions {
8
+ mode?: BatchMode;
9
+ raw?: boolean;
10
+ }
11
+ export type BatchRow = Record<string, any> | any[];
12
+ /**
13
+ * The result of executing a single statement within `batch()`, matching the
14
+ * libSQL client's `ResultSet` shape.
15
+ */
16
+ export interface ResultSet {
17
+ /** Column names of the result, empty for statements that return no rows. */
18
+ columns: Array<string>;
19
+ /** Declared column types, parallel to `columns`. */
20
+ columnTypes: Array<string>;
21
+ /** Result rows; empty for non-SELECT statements. */
22
+ rows: Array<BatchRow>;
23
+ /** Number of rows changed by the statement (0 for SELECT). */
24
+ rowsAffected: number;
25
+ }
26
+ /**
27
+ * Rejects transaction callbacks that cannot be using the `Transaction`
28
+ * handle. A callback that declares no parameters is the pre-0.8 shape:
29
+ * its statements target the `Database` and would deadlock against the
30
+ * lock its own transaction holds. `fn.length` counts declared parameters,
31
+ * so rest-only signatures (`(...args)`) are rejected too — the handle
32
+ * parameter must be declared explicitly.
33
+ */
34
+ declare function assertTransactionCallback(fn: Function): void;
9
35
  /**
10
36
  * A wrapped transaction function. Calling it runs the wrapped function inside a
11
37
  * `BEGIN`/`COMMIT` block; the mode properties (`deferred`, `concurrent`, etc.)
12
38
  * return equivalent wrappers that begin the transaction with the corresponding
13
39
  * locking mode.
40
+ *
41
+ * @deprecated Returned by the deprecated `Database.transaction()`; use
42
+ * `Database.transactionAsync()` and {@link AsyncTransactionFunction} instead.
14
43
  */
15
44
  export interface TransactionFunction<F extends (...args: any[]) => Promise<any> = (...args: any[]) => Promise<any>> {
16
45
  (...args: Parameters<F>): ReturnType<F>;
@@ -21,6 +50,42 @@ export interface TransactionFunction<F extends (...args: any[]) => Promise<any>
21
50
  exclusive: TransactionFunction<F>;
22
51
  database: Database;
23
52
  }
53
+ /**
54
+ * The user-supplied arguments of a transaction callback: everything after
55
+ * the leading `Transaction` handle.
56
+ */
57
+ export type TransactionArgs<F> = F extends (txn: Transaction, ...args: infer A) => any ? A : never;
58
+ /**
59
+ * A wrapped transaction function returned by `Database.transactionAsync(fn)`.
60
+ * Calling it opens a transaction, invokes `fn` with a `Transaction` handle
61
+ * followed by the call's own arguments, and commits on success or rolls
62
+ * back on error. The mode properties (`deferred`, `concurrent`, etc.)
63
+ * return equivalent wrappers that begin the transaction with the
64
+ * corresponding locking mode.
65
+ */
66
+ export interface AsyncTransactionFunction<F extends (txn: Transaction, ...args: any[]) => Promise<any> = (txn: Transaction, ...args: any[]) => Promise<any>> {
67
+ (...args: TransactionArgs<F>): ReturnType<F>;
68
+ default: AsyncTransactionFunction<F>;
69
+ deferred: AsyncTransactionFunction<F>;
70
+ concurrent: AsyncTransactionFunction<F>;
71
+ immediate: AsyncTransactionFunction<F>;
72
+ exclusive: AsyncTransactionFunction<F>;
73
+ database: Database;
74
+ }
75
+ /**
76
+ * The subset of the `AsyncLock` interface statement execution serializes on.
77
+ * Statements created from a `Database` use the database's real `AsyncLock`;
78
+ * statements created from a `Transaction` use a per-transaction gate that
79
+ * serializes native calls within the transaction (so concurrent statements
80
+ * in the callback cannot interleave on the shared connection) and rejects
81
+ * use of a completed transaction. The transaction wrapper already holds the
82
+ * database's lock for the whole transaction, so this gate never contends
83
+ * with other transactions or database-level calls.
84
+ */
85
+ interface ExecLock {
86
+ acquire(): Promise<void>;
87
+ release(): void;
88
+ }
24
89
  /**
25
90
  * Database represents a connection that can prepare and execute SQL statements.
26
91
  */
@@ -32,7 +97,7 @@ declare class Database {
32
97
  inTransaction: boolean;
33
98
  private db;
34
99
  private ioStep;
35
- private execLock;
100
+ protected execLock: AsyncLock;
36
101
  protected connected: boolean;
37
102
  constructor(db: NativeDatabase, ioStep?: () => Promise<void>);
38
103
  /**
@@ -48,9 +113,36 @@ declare class Database {
48
113
  /**
49
114
  * Returns a function that executes the given function in a transaction.
50
115
  *
116
+ * @deprecated Use {@link transactionAsync} instead. This wrapper only
117
+ * emits `BEGIN`/`COMMIT` around the callback without owning the
118
+ * connection, so concurrent statements and transactions can interleave
119
+ * their own statements into the transaction's window (and be committed
120
+ * or rolled back with it). `transactionAsync` holds the connection for
121
+ * the whole transaction and hands the callback a dedicated `Transaction`
122
+ * handle.
123
+ *
51
124
  * @param {function} fn - The function to wrap in a transaction.
52
125
  */
53
126
  transaction<F extends (...args: any[]) => Promise<any>>(fn: F): TransactionFunction<F>;
127
+ /**
128
+ * Returns a function that executes the given function in a transaction.
129
+ *
130
+ * The wrapper owns the connection for the whole BEGIN..COMMIT window: it
131
+ * acquires the database's execution lock before BEGIN and releases it
132
+ * only after COMMIT/ROLLBACK, so no concurrent statement or transaction
133
+ * can interleave its own statements into the transaction's window. The
134
+ * callback receives a `Transaction` handle as its first argument,
135
+ * followed by the arguments the wrapped function was called with — all
136
+ * SQL inside the callback must go through that handle. Calls on the
137
+ * `Database` itself (or statements prepared from it) are not part of the
138
+ * transaction: they queue on the lock until the transaction finishes, so
139
+ * awaiting them inside the callback deadlocks the transaction. Callbacks
140
+ * that do not declare the handle parameter are rejected.
141
+ *
142
+ * @param {function} fn - The function to wrap in a transaction; receives
143
+ * the `Transaction` handle followed by the caller's arguments.
144
+ */
145
+ transactionAsync<F extends (txn: Transaction, ...args: any[]) => Promise<any>>(fn: F): AsyncTransactionFunction<F>;
54
146
  /**
55
147
  * Executes a batch of SQL statements sequentially over this connection.
56
148
  *
@@ -74,8 +166,9 @@ declare class Database {
74
166
  * @param mode - When set, wraps the batch in `BEGIN <mode>` / `COMMIT`
75
167
  * (with `ROLLBACK` on failure). Ignored when already inside a
76
168
  * transaction.
77
- * @returns An object with `rowsAffected` (sum of affected rows) and
78
- * `lastInsertRowid` (rowid of the last successful insert).
169
+ * @returns An array of `ResultSet`s — one per input statement, in order —
170
+ * matching the libsql-js batch contract. Each `ResultSet` carries that
171
+ * statement's `columns`, `columnTypes`, `rows`, and `rowsAffected`.
79
172
  *
80
173
  * @example
81
174
  * // Plain SQL strings (non-atomic).
@@ -99,20 +192,17 @@ declare class Database {
99
192
  * ], "immediate");
100
193
  *
101
194
  * @example
102
- * // Atomic via the transaction() API for mixed workloads.
103
- * const txn = db.transaction(async () => {
104
- * await db.batch([{ sql: "INSERT INTO users(name) VALUES (?)", args: ["Eve"] }]);
105
- * await db.exec("UPDATE counters SET n = n + 1");
195
+ * // Atomic via the transactionAsync() API for mixed workloads.
196
+ * const txn = db.transactionAsync(async (tx) => {
197
+ * await tx.batch([{ sql: "INSERT INTO users(name) VALUES (?)", args: ["Eve"] }]);
198
+ * await tx.exec("UPDATE counters SET n = n + 1");
106
199
  * });
107
200
  * await txn.immediate();
108
201
  */
109
202
  batch(statements: Array<string | {
110
203
  sql: string;
111
204
  args?: any[] | Record<string, any>;
112
- }>, mode?: BatchMode): Promise<{
113
- rowsAffected: number;
114
- lastInsertRowid: number | bigint | undefined;
115
- }>;
205
+ }>, options?: BatchMode | BatchOptions): Promise<ResultSet[]>;
116
206
  /**
117
207
  * Prepares the SQL and executes it as `Statement.run`, returning the run info.
118
208
  *
@@ -175,6 +265,85 @@ declare class Database {
175
265
  close(): Promise<void>;
176
266
  io(): Promise<void>;
177
267
  }
268
+ /**
269
+ * A handle to an open transaction, passed as the first argument to the
270
+ * callback of `Database.transactionAsync()`. All SQL of the transaction
271
+ * must go through this handle: the transaction wrapper holds the database's
272
+ * execution lock for the whole BEGIN..COMMIT window, so `Database` calls
273
+ * issued inside the callback wait for the transaction to finish (and
274
+ * deadlock it if awaited), while the handle executes on the already-owned
275
+ * connection. Once the transaction commits or rolls back the handle is
276
+ * closed and every method throws.
277
+ */
278
+ declare class Transaction {
279
+ private db;
280
+ private ioStep;
281
+ private active;
282
+ private gate;
283
+ constructor(db: NativeDatabase, ioStep: () => Promise<void>);
284
+ /** Whether the transaction is still open (COMMIT/ROLLBACK not executed yet). */
285
+ get open(): boolean;
286
+ private assertActive;
287
+ /** @internal Marks the transaction completed; called by the wrapper. */
288
+ finish(): void;
289
+ /**
290
+ * Executes the given SQL string inside the transaction.
291
+ * Unlike prepared statements, this can execute strings that contain multiple SQL statements.
292
+ *
293
+ * @param {string} sql - The string containing SQL statements to execute
294
+ */
295
+ exec(sql: string, queryOptions?: QueryOptions): Promise<void>;
296
+ /**
297
+ * Prepares a SQL statement scoped to the transaction. The statement runs
298
+ * on the transaction's connection without re-acquiring the database lock
299
+ * and becomes unusable once the transaction completes.
300
+ *
301
+ * @param {string} sql - The SQL statement string to prepare.
302
+ */
303
+ prepare(sql: string): Promise<Statement>;
304
+ /**
305
+ * Prepares the SQL and executes it as `Statement.run`, returning the run info.
306
+ *
307
+ * @param {string} sql - The SQL statement string.
308
+ * @param {...any} bindParameters - Bind parameters, optionally followed by a query options object.
309
+ */
310
+ run(sql: any, ...bindParameters: any[]): Promise<{
311
+ changes: number;
312
+ lastInsertRowid: number;
313
+ }>;
314
+ /**
315
+ * Prepares the SQL and executes it as `Statement.get`, returning the first row.
316
+ *
317
+ * @param {string} sql - The SQL statement string.
318
+ * @param {...any} bindParameters - Bind parameters, optionally followed by a query options object.
319
+ */
320
+ get(sql: any, ...bindParameters: any[]): Promise<any>;
321
+ /**
322
+ * Prepares the SQL and executes it as `Statement.all`, returning all rows.
323
+ *
324
+ * @param {string} sql - The SQL statement string.
325
+ * @param {...any} bindParameters - Bind parameters, optionally followed by a query options object.
326
+ */
327
+ all(sql: any, ...bindParameters: any[]): Promise<any[]>;
328
+ /**
329
+ * Prepares the SQL and executes it as `Statement.iterate`, yielding each row.
330
+ *
331
+ * @param {string} sql - The SQL statement string.
332
+ * @param {...any} bindParameters - Bind parameters, optionally followed by a query options object.
333
+ */
334
+ iterate(sql: any, ...bindParameters: any[]): AsyncGenerator<any, void, unknown>;
335
+ /**
336
+ * Executes a batch of SQL statements inside the transaction. The batch
337
+ * joins the surrounding transaction: any `mode` option is ignored since
338
+ * the connection is already inside `BEGIN`.
339
+ *
340
+ * @param statements - An array of SQL strings or `{ sql, args }` objects.
341
+ */
342
+ batch(statements: Array<string | {
343
+ sql: string;
344
+ args?: any[] | Record<string, any>;
345
+ }>, options?: BatchMode | BatchOptions): Promise<ResultSet[]>;
346
+ }
178
347
  interface MaybeLazy<T> {
179
348
  apply(fn: (value: T) => void): any;
180
349
  resolve(): Promise<T>;
@@ -190,7 +359,7 @@ declare class Statement {
190
359
  private db;
191
360
  private execLock;
192
361
  private ioStep;
193
- constructor(stmt: MaybeLazy<NativeStatement>, db: NativeDatabase, execLock: AsyncLock, ioStep: () => Promise<void>);
362
+ constructor(stmt: MaybeLazy<NativeStatement>, db: NativeDatabase, execLock: ExecLock, ioStep: () => Promise<void>);
194
363
  /**
195
364
  * Toggle raw mode.
196
365
  *
@@ -257,5 +426,5 @@ declare class Statement {
257
426
  bind(...bindParameters: any[]): this;
258
427
  close(): void;
259
428
  }
260
- export { Database, Statement, maybePromise, maybeValue };
429
+ export { Database, Statement, Transaction, assertTransactionCallback, maybePromise, maybeValue };
261
430
  //# sourceMappingURL=promise.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"promise.d.ts","sourceRoot":"","sources":["../promise.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAG5C,OAAO,EAAE,cAAc,EAAE,eAAe,EAAE,YAAY,EAA8C,MAAM,YAAY,CAAC;AAqDvH;;;;GAIG;AACH,MAAM,MAAM,SAAS,GAAG,UAAU,GAAG,WAAW,GAAG,WAAW,GAAG,YAAY,CAAC;AAE9E;;;;;GAKG;AACH,MAAM,WAAW,mBAAmB,CAClC,CAAC,SAAS,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,OAAO,CAAC,GAAG,CAAC;IAE7E,CAAC,GAAG,IAAI,EAAE,UAAU,CAAC,CAAC,CAAC,GAAG,UAAU,CAAC,CAAC,CAAC,CAAC;IACxC,OAAO,EAAE,mBAAmB,CAAC,CAAC,CAAC,CAAC;IAChC,QAAQ,EAAE,mBAAmB,CAAC,CAAC,CAAC,CAAC;IACjC,UAAU,EAAE,mBAAmB,CAAC,CAAC,CAAC,CAAC;IACnC,SAAS,EAAE,mBAAmB,CAAC,CAAC,CAAC,CAAC;IAClC,SAAS,EAAE,mBAAmB,CAAC,CAAC,CAAC,CAAC;IAClC,QAAQ,EAAE,QAAQ,CAAC;CACpB;AAED;;GAEG;AACH,cAAM,QAAQ;IACZ,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,OAAO,CAAC;IAClB,IAAI,EAAE,OAAO,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AC,GAAG,cAAc,OAAA;IAStB,KAAK;CAUN;AAED,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,WAAW,EAAE,yBAAyB,EAAE,YAAY,EAAE,UAAU,EAAE,CAAA"}
package/dist/promise.js CHANGED
@@ -41,6 +41,65 @@ function toBindArgs(params) {
41
41
  }
42
42
  return [params];
43
43
  }
44
+ function normalizeBatchMode(mode) {
45
+ switch (String(mode).toLowerCase()) {
46
+ case "write":
47
+ return "IMMEDIATE";
48
+ case "read":
49
+ case "deferred":
50
+ return "DEFERRED";
51
+ case "immediate":
52
+ return "IMMEDIATE";
53
+ case "exclusive":
54
+ return "EXCLUSIVE";
55
+ case "concurrent":
56
+ return "CONCURRENT";
57
+ default:
58
+ return String(mode).toUpperCase();
59
+ }
60
+ }
61
+ function normalizeBatchOptions(options) {
62
+ if (options != null && typeof options === "object") {
63
+ return {
64
+ mode: options.mode,
65
+ raw: options.raw === true,
66
+ };
67
+ }
68
+ return {
69
+ mode: options,
70
+ raw: false,
71
+ };
72
+ }
73
+ /**
74
+ * Builds a libSQL-style `ResultSet` for a single statement in a `batch()`.
75
+ */
76
+ function makeResultSet(columns, columnTypes, rows, rowsAffected) {
77
+ return {
78
+ columns,
79
+ columnTypes,
80
+ rows,
81
+ rowsAffected,
82
+ };
83
+ }
84
+ /**
85
+ * Rejects transaction callbacks that cannot be using the `Transaction`
86
+ * handle. A callback that declares no parameters is the pre-0.8 shape:
87
+ * its statements target the `Database` and would deadlock against the
88
+ * lock its own transaction holds. `fn.length` counts declared parameters,
89
+ * so rest-only signatures (`(...args)`) are rejected too — the handle
90
+ * parameter must be declared explicitly.
91
+ */
92
+ function assertTransactionCallback(fn) {
93
+ if (typeof fn !== "function") {
94
+ throw new TypeError("Expected first argument to be a function");
95
+ }
96
+ if (fn.length === 0) {
97
+ throw new TypeError("transactionAsync() callbacks receive a Transaction handle as their first argument " +
98
+ "and must declare it: db.transactionAsync(async (txn, ...args) => { await txn.run(...) }). " +
99
+ "Statements inside the callback must go through the handle - database-level calls " +
100
+ "wait for the transaction to finish and deadlock it if awaited inside the callback.");
101
+ }
102
+ }
44
103
  /**
45
104
  * Database represents a connection that can prepare and execute SQL statements.
46
105
  */
@@ -52,6 +111,11 @@ class Database {
52
111
  inTransaction;
53
112
  db;
54
113
  ioStep;
114
+ // Serializes native calls on this connection. Subclasses that also drive
115
+ // the same underlying core database from async worker tasks (the sync
116
+ // engine on wasm) must hold this lock around those windows too: on
117
+ // browser wasm the main thread cannot block on a contended core lock, so
118
+ // main-thread native calls must never overlap an in-flight worker task.
55
119
  execLock;
56
120
  connected = false;
57
121
  constructor(db, ioStep) {
@@ -105,6 +169,14 @@ class Database {
105
169
  /**
106
170
  * Returns a function that executes the given function in a transaction.
107
171
  *
172
+ * @deprecated Use {@link transactionAsync} instead. This wrapper only
173
+ * emits `BEGIN`/`COMMIT` around the callback without owning the
174
+ * connection, so concurrent statements and transactions can interleave
175
+ * their own statements into the transaction's window (and be committed
176
+ * or rolled back with it). `transactionAsync` holds the connection for
177
+ * the whole transaction and hands the callback a dedicated `Transaction`
178
+ * handle.
179
+ *
108
180
  * @param {function} fn - The function to wrap in a transaction.
109
181
  */
110
182
  transaction(fn) {
@@ -140,6 +212,72 @@ class Database {
140
212
  Object.defineProperties(properties.exclusive.value, properties);
141
213
  return properties.default.value;
142
214
  }
215
+ /**
216
+ * Returns a function that executes the given function in a transaction.
217
+ *
218
+ * The wrapper owns the connection for the whole BEGIN..COMMIT window: it
219
+ * acquires the database's execution lock before BEGIN and releases it
220
+ * only after COMMIT/ROLLBACK, so no concurrent statement or transaction
221
+ * can interleave its own statements into the transaction's window. The
222
+ * callback receives a `Transaction` handle as its first argument,
223
+ * followed by the arguments the wrapped function was called with — all
224
+ * SQL inside the callback must go through that handle. Calls on the
225
+ * `Database` itself (or statements prepared from it) are not part of the
226
+ * transaction: they queue on the lock until the transaction finishes, so
227
+ * awaiting them inside the callback deadlocks the transaction. Callbacks
228
+ * that do not declare the handle parameter are rejected.
229
+ *
230
+ * @param {function} fn - The function to wrap in a transaction; receives
231
+ * the `Transaction` handle followed by the caller's arguments.
232
+ */
233
+ transactionAsync(fn) {
234
+ assertTransactionCallback(fn);
235
+ const db = this;
236
+ const wrapTxn = (mode) => {
237
+ return async (...bindParameters) => {
238
+ if (!db.connected) {
239
+ await db.connect();
240
+ }
241
+ if (!db.open) {
242
+ throw new TypeError("The database connection is not open");
243
+ }
244
+ // own the connection for the whole transaction: everything else
245
+ // queues on execLock until COMMIT/ROLLBACK releases it
246
+ await db.execLock.acquire();
247
+ const txn = new Transaction(db.db, () => db.io());
248
+ try {
249
+ await txn.exec("BEGIN " + mode);
250
+ try {
251
+ const result = await fn(txn, ...bindParameters);
252
+ await txn.exec("COMMIT");
253
+ return result;
254
+ }
255
+ catch (err) {
256
+ await txn.exec("ROLLBACK");
257
+ throw err;
258
+ }
259
+ }
260
+ finally {
261
+ txn.finish();
262
+ db.execLock.release();
263
+ }
264
+ };
265
+ };
266
+ const properties = {
267
+ default: { value: wrapTxn("") },
268
+ deferred: { value: wrapTxn("DEFERRED") },
269
+ concurrent: { value: wrapTxn("CONCURRENT") },
270
+ immediate: { value: wrapTxn("IMMEDIATE") },
271
+ exclusive: { value: wrapTxn("EXCLUSIVE") },
272
+ database: { value: this, enumerable: true },
273
+ };
274
+ Object.defineProperties(properties.default.value, properties);
275
+ Object.defineProperties(properties.deferred.value, properties);
276
+ Object.defineProperties(properties.concurrent.value, properties);
277
+ Object.defineProperties(properties.immediate.value, properties);
278
+ Object.defineProperties(properties.exclusive.value, properties);
279
+ return properties.default.value;
280
+ }
143
281
  /**
144
282
  * Executes a batch of SQL statements sequentially over this connection.
145
283
  *
@@ -163,8 +301,9 @@ class Database {
163
301
  * @param mode - When set, wraps the batch in `BEGIN <mode>` / `COMMIT`
164
302
  * (with `ROLLBACK` on failure). Ignored when already inside a
165
303
  * transaction.
166
- * @returns An object with `rowsAffected` (sum of affected rows) and
167
- * `lastInsertRowid` (rowid of the last successful insert).
304
+ * @returns An array of `ResultSet`s — one per input statement, in order —
305
+ * matching the libsql-js batch contract. Each `ResultSet` carries that
306
+ * statement's `columns`, `columnTypes`, `rows`, and `rowsAffected`.
168
307
  *
169
308
  * @example
170
309
  * // Plain SQL strings (non-atomic).
@@ -188,14 +327,14 @@ class Database {
188
327
  * ], "immediate");
189
328
  *
190
329
  * @example
191
- * // Atomic via the transaction() API for mixed workloads.
192
- * const txn = db.transaction(async () => {
193
- * await db.batch([{ sql: "INSERT INTO users(name) VALUES (?)", args: ["Eve"] }]);
194
- * await db.exec("UPDATE counters SET n = n + 1");
330
+ * // Atomic via the transactionAsync() API for mixed workloads.
331
+ * const txn = db.transactionAsync(async (tx) => {
332
+ * await tx.batch([{ sql: "INSERT INTO users(name) VALUES (?)", args: ["Eve"] }]);
333
+ * await tx.exec("UPDATE counters SET n = n + 1");
195
334
  * });
196
335
  * await txn.immediate();
197
336
  */
198
- async batch(statements, mode) {
337
+ async batch(statements, options) {
199
338
  if (!Array.isArray(statements)) {
200
339
  throw new TypeError("Expected first argument to be an array of statements");
201
340
  }
@@ -206,99 +345,11 @@ class Database {
206
345
  throw new TypeError("The database connection is not open");
207
346
  }
208
347
  // Hold execLock across the entire batch so it is observed as a
209
- // single unit by other callers on this connection. The helpers
210
- // below run their own step loops without re-acquiring the lock.
348
+ // single unit by other callers on this connection. The helper
349
+ // runs its own step loops without re-acquiring the lock.
211
350
  await this.execLock.acquire();
212
351
  try {
213
- const runRawSql = async (sql) => {
214
- const exec = this.db.executor(sql);
215
- try {
216
- while (true) {
217
- const stepResult = exec.stepSync();
218
- if (stepResult === STEP_IO) {
219
- await this.io();
220
- continue;
221
- }
222
- if (stepResult === STEP_DONE) {
223
- break;
224
- }
225
- }
226
- }
227
- finally {
228
- exec.reset();
229
- }
230
- };
231
- const wrap = mode !== undefined && !this.db.inTransaction();
232
- if (wrap) {
233
- await runRawSql(`BEGIN ${mode.toUpperCase()}`);
234
- }
235
- let rowsAffected = 0;
236
- let lastInsertRowid;
237
- try {
238
- for (const statement of statements) {
239
- const sql = typeof statement === "string" ? statement : statement.sql;
240
- const args = typeof statement === "string" ? undefined : statement.args;
241
- let nativeStmt;
242
- try {
243
- nativeStmt = this.db.prepare(sql);
244
- }
245
- catch (err) {
246
- throw convertError(err);
247
- }
248
- try {
249
- if (args !== undefined) {
250
- bindParams(nativeStmt, [args]);
251
- }
252
- const totalChangesBefore = this.db.totalChanges();
253
- const lastInsertRowidBefore = this.db.lastInsertRowid();
254
- try {
255
- while (true) {
256
- const stepResult = await nativeStmt.stepSync();
257
- if (stepResult === STEP_IO) {
258
- await this.io();
259
- continue;
260
- }
261
- if (stepResult === STEP_DONE) {
262
- break;
263
- }
264
- // STEP_ROW results are discarded; batch() does not
265
- // surface rows.
266
- }
267
- if (this.db.totalChanges() !== totalChangesBefore) {
268
- rowsAffected += this.db.changes();
269
- }
270
- // SQLite keeps last_insert_rowid() sticky across
271
- // non-INSERT statements, so just checking the value is
272
- // not enough — UPDATE/DELETE would inherit a stale
273
- // rowid. Use the delta as the per-statement INSERT
274
- // signal.
275
- const lastInsertRowidAfter = this.db.lastInsertRowid();
276
- if (lastInsertRowidAfter !== lastInsertRowidBefore) {
277
- lastInsertRowid = lastInsertRowidAfter;
278
- }
279
- }
280
- finally {
281
- nativeStmt.reset();
282
- }
283
- }
284
- finally {
285
- nativeStmt.finalize();
286
- }
287
- }
288
- if (wrap) {
289
- await runRawSql("COMMIT");
290
- }
291
- }
292
- catch (err) {
293
- if (wrap) {
294
- try {
295
- await runRawSql("ROLLBACK");
296
- }
297
- catch { /* ignore */ }
298
- }
299
- throw err;
300
- }
301
- return { rowsAffected, lastInsertRowid };
352
+ return await executeBatch(this.db, () => this.io(), statements, options);
302
353
  }
303
354
  finally {
304
355
  this.execLock.release();
@@ -462,6 +513,277 @@ class Database {
462
513
  await this.ioStep();
463
514
  }
464
515
  }
516
+ /**
517
+ * Runs a batch over a connection whose execution lock is already owned by
518
+ * the caller: `Database.batch()` calls it while holding `execLock`,
519
+ * `Transaction.batch()` while the transaction wrapper holds the lock for
520
+ * the whole transaction.
521
+ */
522
+ async function executeBatch(native, io, statements, options) {
523
+ const runRawSql = async (sql) => {
524
+ const exec = native.executor(sql);
525
+ try {
526
+ while (true) {
527
+ const stepResult = exec.stepSync();
528
+ if (stepResult === STEP_IO) {
529
+ await io();
530
+ continue;
531
+ }
532
+ if (stepResult === STEP_DONE) {
533
+ break;
534
+ }
535
+ }
536
+ }
537
+ finally {
538
+ exec.reset();
539
+ }
540
+ };
541
+ const { mode, raw } = normalizeBatchOptions(options);
542
+ const wrap = mode != null && !native.inTransaction();
543
+ if (wrap) {
544
+ await runRawSql(`BEGIN ${normalizeBatchMode(mode)}`);
545
+ }
546
+ const results = [];
547
+ try {
548
+ for (const statement of statements) {
549
+ const sql = typeof statement === "string" ? statement : statement.sql;
550
+ const args = typeof statement === "string" ? undefined : statement.args;
551
+ let nativeStmt;
552
+ try {
553
+ nativeStmt = native.prepare(sql);
554
+ }
555
+ catch (err) {
556
+ throw convertError(err);
557
+ }
558
+ try {
559
+ if (args !== undefined) {
560
+ bindParams(nativeStmt, [args]);
561
+ }
562
+ const cols = nativeStmt.columns();
563
+ const columnNames = cols.map((c) => c.name);
564
+ const columnTypes = cols.map((c) => c.type ?? "");
565
+ if (columnNames.length > 0) {
566
+ nativeStmt.raw(raw);
567
+ }
568
+ const totalChangesBefore = native.totalChanges();
569
+ const rows = [];
570
+ try {
571
+ while (true) {
572
+ const stepResult = await nativeStmt.stepSync();
573
+ if (stepResult === STEP_IO) {
574
+ await io();
575
+ continue;
576
+ }
577
+ if (stepResult === STEP_DONE) {
578
+ break;
579
+ }
580
+ rows.push(nativeStmt.row());
581
+ }
582
+ const rowsAffected = columnNames.length > 0
583
+ ? 0
584
+ : native.totalChanges() !== totalChangesBefore ? native.changes() : 0;
585
+ results.push(makeResultSet(columnNames, columnTypes, rows, rowsAffected));
586
+ }
587
+ finally {
588
+ nativeStmt.reset();
589
+ }
590
+ }
591
+ finally {
592
+ nativeStmt.finalize();
593
+ }
594
+ }
595
+ if (wrap) {
596
+ await runRawSql("COMMIT");
597
+ }
598
+ }
599
+ catch (err) {
600
+ if (wrap) {
601
+ try {
602
+ await runRawSql("ROLLBACK");
603
+ }
604
+ catch { /* ignore */ }
605
+ }
606
+ throw err;
607
+ }
608
+ return results;
609
+ }
610
+ /**
611
+ * A handle to an open transaction, passed as the first argument to the
612
+ * callback of `Database.transactionAsync()`. All SQL of the transaction
613
+ * must go through this handle: the transaction wrapper holds the database's
614
+ * execution lock for the whole BEGIN..COMMIT window, so `Database` calls
615
+ * issued inside the callback wait for the transaction to finish (and
616
+ * deadlock it if awaited), while the handle executes on the already-owned
617
+ * connection. Once the transaction commits or rolls back the handle is
618
+ * closed and every method throws.
619
+ */
620
+ class Transaction {
621
+ db;
622
+ ioStep;
623
+ active = true;
624
+ // Per-transaction execution gate. The wrapper already holds the database's
625
+ // execLock for the whole transaction, so this never contends with other
626
+ // transactions or database-level calls; it serializes native calls *within*
627
+ // this transaction — the same invariant the database's execLock enforces on
628
+ // the connection — so statements issued concurrently in the callback cannot
629
+ // interleave their step loops on the shared connection. It also rejects use
630
+ // of a completed transaction.
631
+ gate;
632
+ constructor(db, ioStep) {
633
+ this.db = db;
634
+ this.ioStep = ioStep;
635
+ const lock = new AsyncLock();
636
+ this.gate = {
637
+ acquire: async () => { this.assertActive(); await lock.acquire(); },
638
+ release: () => { lock.release(); },
639
+ };
640
+ }
641
+ /** Whether the transaction is still open (COMMIT/ROLLBACK not executed yet). */
642
+ get open() {
643
+ return this.active;
644
+ }
645
+ assertActive() {
646
+ if (!this.active) {
647
+ throw new TypeError("The transaction has already completed");
648
+ }
649
+ }
650
+ /** @internal Marks the transaction completed; called by the wrapper. */
651
+ finish() {
652
+ this.active = false;
653
+ }
654
+ /**
655
+ * Executes the given SQL string inside the transaction.
656
+ * Unlike prepared statements, this can execute strings that contain multiple SQL statements.
657
+ *
658
+ * @param {string} sql - The string containing SQL statements to execute
659
+ */
660
+ async exec(sql, queryOptions) {
661
+ await this.gate.acquire();
662
+ try {
663
+ const exec = this.db.executor(sql, queryOptions);
664
+ try {
665
+ while (true) {
666
+ const stepResult = exec.stepSync();
667
+ if (stepResult === STEP_IO) {
668
+ await this.ioStep();
669
+ continue;
670
+ }
671
+ if (stepResult === STEP_DONE) {
672
+ break;
673
+ }
674
+ if (stepResult === STEP_ROW) {
675
+ continue;
676
+ }
677
+ }
678
+ }
679
+ finally {
680
+ exec.reset();
681
+ }
682
+ }
683
+ finally {
684
+ this.gate.release();
685
+ }
686
+ }
687
+ /**
688
+ * Prepares a SQL statement scoped to the transaction. The statement runs
689
+ * on the transaction's connection without re-acquiring the database lock
690
+ * and becomes unusable once the transaction completes.
691
+ *
692
+ * @param {string} sql - The SQL statement string to prepare.
693
+ */
694
+ prepare(sql) {
695
+ this.assertActive();
696
+ if (!sql) {
697
+ throw new RangeError("The supplied SQL string contains no statements");
698
+ }
699
+ try {
700
+ return new Statement(maybeValue(this.db.prepare(sql)), this.db, this.gate, this.ioStep);
701
+ }
702
+ catch (err) {
703
+ throw convertError(err);
704
+ }
705
+ }
706
+ /**
707
+ * Prepares the SQL and executes it as `Statement.run`, returning the run info.
708
+ *
709
+ * @param {string} sql - The SQL statement string.
710
+ * @param {...any} bindParameters - Bind parameters, optionally followed by a query options object.
711
+ */
712
+ async run(sql, ...bindParameters) {
713
+ const stmt = await this.prepare(sql);
714
+ try {
715
+ return await stmt.run(...bindParameters);
716
+ }
717
+ finally {
718
+ await stmt.close();
719
+ }
720
+ }
721
+ /**
722
+ * Prepares the SQL and executes it as `Statement.get`, returning the first row.
723
+ *
724
+ * @param {string} sql - The SQL statement string.
725
+ * @param {...any} bindParameters - Bind parameters, optionally followed by a query options object.
726
+ */
727
+ async get(sql, ...bindParameters) {
728
+ const stmt = await this.prepare(sql);
729
+ try {
730
+ return await stmt.get(...bindParameters);
731
+ }
732
+ finally {
733
+ await stmt.close();
734
+ }
735
+ }
736
+ /**
737
+ * Prepares the SQL and executes it as `Statement.all`, returning all rows.
738
+ *
739
+ * @param {string} sql - The SQL statement string.
740
+ * @param {...any} bindParameters - Bind parameters, optionally followed by a query options object.
741
+ */
742
+ async all(sql, ...bindParameters) {
743
+ const stmt = await this.prepare(sql);
744
+ try {
745
+ return await stmt.all(...bindParameters);
746
+ }
747
+ finally {
748
+ await stmt.close();
749
+ }
750
+ }
751
+ /**
752
+ * Prepares the SQL and executes it as `Statement.iterate`, yielding each row.
753
+ *
754
+ * @param {string} sql - The SQL statement string.
755
+ * @param {...any} bindParameters - Bind parameters, optionally followed by a query options object.
756
+ */
757
+ async *iterate(sql, ...bindParameters) {
758
+ const stmt = await this.prepare(sql);
759
+ try {
760
+ yield* stmt.iterate(...bindParameters);
761
+ }
762
+ finally {
763
+ await stmt.close();
764
+ }
765
+ }
766
+ /**
767
+ * Executes a batch of SQL statements inside the transaction. The batch
768
+ * joins the surrounding transaction: any `mode` option is ignored since
769
+ * the connection is already inside `BEGIN`.
770
+ *
771
+ * @param statements - An array of SQL strings or `{ sql, args }` objects.
772
+ */
773
+ async batch(statements, options) {
774
+ this.assertActive();
775
+ if (!Array.isArray(statements)) {
776
+ throw new TypeError("Expected first argument to be an array of statements");
777
+ }
778
+ await this.gate.acquire();
779
+ try {
780
+ return await executeBatch(this.db, this.ioStep, statements, options);
781
+ }
782
+ finally {
783
+ this.gate.release();
784
+ }
785
+ }
786
+ }
465
787
  function maybePromise(arg) {
466
788
  let lazy = arg;
467
789
  let promise = null;
@@ -728,4 +1050,4 @@ class Statement {
728
1050
  stmt.finalize();
729
1051
  }
730
1052
  }
731
- export { Database, Statement, maybePromise, maybeValue };
1053
+ export { Database, Statement, Transaction, assertTransactionCallback, maybePromise, maybeValue };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tursodatabase/database-common",
3
- "version": "0.7.0-pre.9",
3
+ "version": "0.7.1-pre.1",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/tursodatabase/turso"