@tursodatabase/database-common 0.7.0 → 0.8.0-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.
@@ -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/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
@@ -23,11 +23,23 @@ export interface ResultSet {
23
23
  /** Number of rows changed by the statement (0 for SELECT). */
24
24
  rowsAffected: number;
25
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;
26
35
  /**
27
36
  * A wrapped transaction function. Calling it runs the wrapped function inside a
28
37
  * `BEGIN`/`COMMIT` block; the mode properties (`deferred`, `concurrent`, etc.)
29
38
  * return equivalent wrappers that begin the transaction with the corresponding
30
39
  * locking mode.
40
+ *
41
+ * @deprecated Returned by the deprecated `Database.transaction()`; use
42
+ * `Database.transactionAsync()` and {@link AsyncTransactionFunction} instead.
31
43
  */
32
44
  export interface TransactionFunction<F extends (...args: any[]) => Promise<any> = (...args: any[]) => Promise<any>> {
33
45
  (...args: Parameters<F>): ReturnType<F>;
@@ -38,6 +50,42 @@ export interface TransactionFunction<F extends (...args: any[]) => Promise<any>
38
50
  exclusive: TransactionFunction<F>;
39
51
  database: Database;
40
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
+ }
41
89
  /**
42
90
  * Database represents a connection that can prepare and execute SQL statements.
43
91
  */
@@ -65,9 +113,36 @@ declare class Database {
65
113
  /**
66
114
  * Returns a function that executes the given function in a transaction.
67
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
+ *
68
124
  * @param {function} fn - The function to wrap in a transaction.
69
125
  */
70
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>;
71
146
  /**
72
147
  * Executes a batch of SQL statements sequentially over this connection.
73
148
  *
@@ -117,10 +192,10 @@ declare class Database {
117
192
  * ], "immediate");
118
193
  *
119
194
  * @example
120
- * // Atomic via the transaction() API for mixed workloads.
121
- * const txn = db.transaction(async () => {
122
- * await db.batch([{ sql: "INSERT INTO users(name) VALUES (?)", args: ["Eve"] }]);
123
- * 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");
124
199
  * });
125
200
  * await txn.immediate();
126
201
  */
@@ -190,6 +265,85 @@ declare class Database {
190
265
  close(): Promise<void>;
191
266
  io(): Promise<void>;
192
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
+ }
193
347
  interface MaybeLazy<T> {
194
348
  apply(fn: (value: T) => void): any;
195
349
  resolve(): Promise<T>;
@@ -205,7 +359,7 @@ declare class Statement {
205
359
  private db;
206
360
  private execLock;
207
361
  private ioStep;
208
- constructor(stmt: MaybeLazy<NativeStatement>, db: NativeDatabase, execLock: AsyncLock, ioStep: () => Promise<void>);
362
+ constructor(stmt: MaybeLazy<NativeStatement>, db: NativeDatabase, execLock: ExecLock, ioStep: () => Promise<void>);
209
363
  /**
210
364
  * Toggle raw mode.
211
365
  *
@@ -272,5 +426,5 @@ declare class Statement {
272
426
  bind(...bindParameters: any[]): this;
273
427
  close(): void;
274
428
  }
275
- export { Database, Statement, maybePromise, maybeValue };
429
+ export { Database, Statement, Transaction, assertTransactionCallback, maybePromise, maybeValue };
276
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;AAoDvH;;GAEG;AACH,MAAM,MAAM,SAAS,GAAG,OAAO,GAAG,MAAM,GAAG,UAAU,GAAG,WAAW,GAAG,WAAW,GAAG,YAAY,GAAG,MAAM,CAAC;AAE1G,MAAM,WAAW,YAAY;IAC3B,IAAI,CAAC,EAAE,SAAS,CAAC;IACjB,GAAG,CAAC,EAAE,OAAO,CAAC;CACf;AAED,MAAM,MAAM,QAAQ,GAAG,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,GAAG,EAAE,CAAC;AAEnD;;;GAGG;AACH,MAAM,WAAW,SAAS;IACxB,4EAA4E;IAC5E,OAAO,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IACvB,oDAAoD;IACpD,WAAW,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IAC3B,oDAAoD;IACpD,IAAI,EAAE,KAAK,CAAC,QAAQ,CAAC,CAAC;IACtB,8DAA8D;IAC9D,YAAY,EAAE,MAAM,CAAC;CACtB;AAkDD;;;;;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,G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AKf;;;;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;IACG,GAAG,CAAC,GAAG,cAAc,OAAA;;;;IAmC3B;;;;OAIG;IACG,GAAG,CAAC,GAAG,cAAc,OAAA;IA+B3B;;;;OAIG;IACI,OAAO,CAAC,GAAG,cAAc,OAAA;IA4BhC;;;;OAIG;IACG,GAAG,CAAC,GAAG,cAAc,OAAA;IA+BrB,EAAE;IAIR;;OAEG;IACH,SAAS;IAKT;;;;;OAKG;IACH,IAAI,CAAC,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
@@ -81,6 +81,25 @@ function makeResultSet(columns, columnTypes, rows, rowsAffected) {
81
81
  rowsAffected,
82
82
  };
83
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
+ }
84
103
  /**
85
104
  * Database represents a connection that can prepare and execute SQL statements.
86
105
  */
@@ -150,6 +169,14 @@ class Database {
150
169
  /**
151
170
  * Returns a function that executes the given function in a transaction.
152
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
+ *
153
180
  * @param {function} fn - The function to wrap in a transaction.
154
181
  */
155
182
  transaction(fn) {
@@ -185,6 +212,72 @@ class Database {
185
212
  Object.defineProperties(properties.exclusive.value, properties);
186
213
  return properties.default.value;
187
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
+ }
188
281
  /**
189
282
  * Executes a batch of SQL statements sequentially over this connection.
190
283
  *
@@ -234,10 +327,10 @@ class Database {
234
327
  * ], "immediate");
235
328
  *
236
329
  * @example
237
- * // Atomic via the transaction() API for mixed workloads.
238
- * const txn = db.transaction(async () => {
239
- * await db.batch([{ sql: "INSERT INTO users(name) VALUES (?)", args: ["Eve"] }]);
240
- * 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");
241
334
  * });
242
335
  * await txn.immediate();
243
336
  */
@@ -252,96 +345,11 @@ class Database {
252
345
  throw new TypeError("The database connection is not open");
253
346
  }
254
347
  // Hold execLock across the entire batch so it is observed as a
255
- // single unit by other callers on this connection. The helpers
256
- // 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.
257
350
  await this.execLock.acquire();
258
351
  try {
259
- const runRawSql = async (sql) => {
260
- const exec = this.db.executor(sql);
261
- try {
262
- while (true) {
263
- const stepResult = exec.stepSync();
264
- if (stepResult === STEP_IO) {
265
- await this.io();
266
- continue;
267
- }
268
- if (stepResult === STEP_DONE) {
269
- break;
270
- }
271
- }
272
- }
273
- finally {
274
- exec.reset();
275
- }
276
- };
277
- const { mode, raw } = normalizeBatchOptions(options);
278
- const wrap = mode != null && !this.db.inTransaction();
279
- if (wrap) {
280
- await runRawSql(`BEGIN ${normalizeBatchMode(mode)}`);
281
- }
282
- const results = [];
283
- try {
284
- for (const statement of statements) {
285
- const sql = typeof statement === "string" ? statement : statement.sql;
286
- const args = typeof statement === "string" ? undefined : statement.args;
287
- let nativeStmt;
288
- try {
289
- nativeStmt = this.db.prepare(sql);
290
- }
291
- catch (err) {
292
- throw convertError(err);
293
- }
294
- try {
295
- if (args !== undefined) {
296
- bindParams(nativeStmt, [args]);
297
- }
298
- const cols = nativeStmt.columns();
299
- const columnNames = cols.map((c) => c.name);
300
- const columnTypes = cols.map((c) => c.type ?? "");
301
- if (columnNames.length > 0) {
302
- nativeStmt.raw(raw);
303
- }
304
- const totalChangesBefore = this.db.totalChanges();
305
- const rows = [];
306
- try {
307
- while (true) {
308
- const stepResult = await nativeStmt.stepSync();
309
- if (stepResult === STEP_IO) {
310
- await this.io();
311
- continue;
312
- }
313
- if (stepResult === STEP_DONE) {
314
- break;
315
- }
316
- rows.push(nativeStmt.row());
317
- }
318
- const rowsAffected = columnNames.length > 0
319
- ? 0
320
- : this.db.totalChanges() !== totalChangesBefore ? this.db.changes() : 0;
321
- results.push(makeResultSet(columnNames, columnTypes, rows, rowsAffected));
322
- }
323
- finally {
324
- nativeStmt.reset();
325
- }
326
- }
327
- finally {
328
- nativeStmt.finalize();
329
- }
330
- }
331
- if (wrap) {
332
- await runRawSql("COMMIT");
333
- }
334
- }
335
- catch (err) {
336
- if (wrap) {
337
- try {
338
- await runRawSql("ROLLBACK");
339
- }
340
- catch { /* ignore */ }
341
- }
342
- throw err;
343
- }
344
- return results;
352
+ return await executeBatch(this.db, () => this.io(), statements, options);
345
353
  }
346
354
  finally {
347
355
  this.execLock.release();
@@ -505,6 +513,277 @@ class Database {
505
513
  await this.ioStep();
506
514
  }
507
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
+ }
508
787
  function maybePromise(arg) {
509
788
  let lazy = arg;
510
789
  let promise = null;
@@ -771,4 +1050,4 @@ class Statement {
771
1050
  stmt.finalize();
772
1051
  }
773
1052
  }
774
- 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",
3
+ "version": "0.8.0-pre.1",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/tursodatabase/turso"