@tursodatabase/database-common 0.7.0-pre.1 → 0.7.0-pre.3

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/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { NativeDatabase, NativeStatement, DatabaseOpts, EncryptionCipher, EncryptionOpts } from "./types.js";
2
2
  import { Database as DatabaseCompat, Statement as StatementCompat } from "./compat.js";
3
- import { Database as DatabasePromise, Statement as StatementPromise } from "./promise.js";
3
+ import { Database as DatabasePromise, Statement as StatementPromise, TransactionFunction } from "./promise.js";
4
4
  import { SqliteError } from "./sqlite-error.js";
5
5
  import { AsyncLock } from "./async-lock.js";
6
- export { DatabaseOpts, EncryptionCipher, EncryptionOpts, DatabaseCompat, StatementCompat, DatabasePromise, StatementPromise, NativeDatabase, NativeStatement, SqliteError, AsyncLock };
6
+ export { DatabaseOpts, EncryptionCipher, EncryptionOpts, DatabaseCompat, StatementCompat, DatabasePromise, StatementPromise, TransactionFunction, 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,MAAM,YAAY,CAAC;AAC7G,OAAO,EAAE,QAAQ,IAAI,cAAc,EAAE,SAAS,IAAI,eAAe,EAAE,MAAM,aAAa,CAAC;AACvF,OAAO,EAAE,QAAQ,IAAI,eAAe,EAAE,SAAS,IAAI,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAC1F,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAE5C,OAAO,EACH,YAAY,EACZ,gBAAgB,EAChB,cAAc,EACd,cAAc,EAAE,eAAe,EAC/B,eAAe,EAAE,gBAAgB,EACjC,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,MAAM,YAAY,CAAC;AAC7G,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,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"}
package/dist/promise.d.ts CHANGED
@@ -1,5 +1,26 @@
1
1
  import { AsyncLock } from "./async-lock.js";
2
2
  import { NativeDatabase, NativeStatement, QueryOptions } from "./types.js";
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).
7
+ */
8
+ export type BatchMode = "deferred" | "immediate" | "exclusive" | "concurrent";
9
+ /**
10
+ * A wrapped transaction function. Calling it runs the wrapped function inside a
11
+ * `BEGIN`/`COMMIT` block; the mode properties (`deferred`, `concurrent`, etc.)
12
+ * return equivalent wrappers that begin the transaction with the corresponding
13
+ * locking mode.
14
+ */
15
+ export interface TransactionFunction<F extends (...args: any[]) => Promise<any> = (...args: any[]) => Promise<any>> {
16
+ (...args: Parameters<F>): ReturnType<F>;
17
+ default: TransactionFunction<F>;
18
+ deferred: TransactionFunction<F>;
19
+ concurrent: TransactionFunction<F>;
20
+ immediate: TransactionFunction<F>;
21
+ exclusive: TransactionFunction<F>;
22
+ database: Database;
23
+ }
3
24
  /**
4
25
  * Database represents a connection that can prepare and execute SQL statements.
5
26
  */
@@ -30,7 +51,69 @@ declare class Database {
30
51
  *
31
52
  * @param {function} fn - The function to wrap in a transaction.
32
53
  */
33
- transaction(fn: (...any: any[]) => Promise<any>): (...bindParameters: any[]) => Promise<any>;
54
+ transaction<F extends (...args: any[]) => Promise<any>>(fn: F): TransactionFunction<F>;
55
+ /**
56
+ * Executes a batch of SQL statements sequentially over this connection.
57
+ *
58
+ * By default, batch() is not transactional: each statement runs in its
59
+ * own autocommit step, so a failure mid-batch leaves earlier successful
60
+ * statements committed. Pass a `mode` to make the batch atomic — the
61
+ * statements are wrapped in `BEGIN <mode>` / `COMMIT`, and `ROLLBACK`
62
+ * runs if any statement fails. When called from inside a
63
+ * `db.transaction(...)` callback the `mode` argument is ignored and the
64
+ * surrounding transaction is reused.
65
+ *
66
+ * When `mode` is set, `batch()` owns the surrounding
67
+ * `BEGIN`/`COMMIT`/`ROLLBACK`, so the `statements` array must not
68
+ * contain its own transaction-control SQL (`BEGIN`, `COMMIT`,
69
+ * `ROLLBACK`, `SAVEPOINT`, `RELEASE`). The input is not validated
70
+ * for that — a user-supplied `COMMIT` will close the wrapper
71
+ * transaction mid-batch and leave earlier statements committed,
72
+ * defeating the all-or-nothing contract.
73
+ *
74
+ * @param statements - An array of SQL strings or `{ sql, args }` objects.
75
+ * @param mode - When set, wraps the batch in `BEGIN <mode>` / `COMMIT`
76
+ * (with `ROLLBACK` on failure). Ignored when already inside a
77
+ * transaction.
78
+ * @returns An object with `rowsAffected` (sum of affected rows) and
79
+ * `lastInsertRowid` (rowid of the last successful insert).
80
+ *
81
+ * @example
82
+ * // Plain SQL strings (non-atomic).
83
+ * await db.batch([
84
+ * "INSERT INTO users(name) VALUES ('Alice')",
85
+ * "INSERT INTO users(name) VALUES ('Bob')",
86
+ * ]);
87
+ *
88
+ * @example
89
+ * // Positional and named bind parameters.
90
+ * await db.batch([
91
+ * { sql: "INSERT INTO users(name, email) VALUES (?, ?)", args: ["Carol", "carol@example.net"] },
92
+ * { sql: "INSERT INTO users(name, email) VALUES (:name, :email)", args: { name: "Dave", email: "dave@example.net" } },
93
+ * ]);
94
+ *
95
+ * @example
96
+ * // Atomic via the mode parameter.
97
+ * await db.batch([
98
+ * { sql: "INSERT INTO users(name) VALUES (?)", args: ["Eve"] },
99
+ * { sql: "INSERT INTO users(name) VALUES (?)", args: ["Frank"] },
100
+ * ], "immediate");
101
+ *
102
+ * @example
103
+ * // Atomic via the transaction() API for mixed workloads.
104
+ * const txn = db.transaction(async () => {
105
+ * await db.batch([{ sql: "INSERT INTO users(name) VALUES (?)", args: ["Eve"] }]);
106
+ * await db.exec("UPDATE counters SET n = n + 1");
107
+ * });
108
+ * await txn.immediate();
109
+ */
110
+ batch(statements: Array<string | {
111
+ sql: string;
112
+ args?: any[] | Record<string, any>;
113
+ }>, mode?: BatchMode): Promise<{
114
+ rowsAffected: number;
115
+ lastInsertRowid: number | bigint | undefined;
116
+ }>;
34
117
  /**
35
118
  * Prepares the SQL and executes it as `Statement.run`, returning the run info.
36
119
  *
@@ -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,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,C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;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;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,YAAY,EAAE,UAAU,EAAE,CAAA"}
package/dist/promise.js CHANGED
@@ -132,16 +132,185 @@ class Database {
132
132
  const properties = {
133
133
  default: { value: wrapTxn("") },
134
134
  deferred: { value: wrapTxn("DEFERRED") },
135
+ concurrent: { value: wrapTxn("CONCURRENT") },
135
136
  immediate: { value: wrapTxn("IMMEDIATE") },
136
137
  exclusive: { value: wrapTxn("EXCLUSIVE") },
137
138
  database: { value: this, enumerable: true },
138
139
  };
139
140
  Object.defineProperties(properties.default.value, properties);
140
141
  Object.defineProperties(properties.deferred.value, properties);
142
+ Object.defineProperties(properties.concurrent.value, properties);
141
143
  Object.defineProperties(properties.immediate.value, properties);
142
144
  Object.defineProperties(properties.exclusive.value, properties);
143
145
  return properties.default.value;
144
146
  }
147
+ /**
148
+ * Executes a batch of SQL statements sequentially over this connection.
149
+ *
150
+ * By default, batch() is not transactional: each statement runs in its
151
+ * own autocommit step, so a failure mid-batch leaves earlier successful
152
+ * statements committed. Pass a `mode` to make the batch atomic — the
153
+ * statements are wrapped in `BEGIN <mode>` / `COMMIT`, and `ROLLBACK`
154
+ * runs if any statement fails. When called from inside a
155
+ * `db.transaction(...)` callback the `mode` argument is ignored and the
156
+ * surrounding transaction is reused.
157
+ *
158
+ * When `mode` is set, `batch()` owns the surrounding
159
+ * `BEGIN`/`COMMIT`/`ROLLBACK`, so the `statements` array must not
160
+ * contain its own transaction-control SQL (`BEGIN`, `COMMIT`,
161
+ * `ROLLBACK`, `SAVEPOINT`, `RELEASE`). The input is not validated
162
+ * for that — a user-supplied `COMMIT` will close the wrapper
163
+ * transaction mid-batch and leave earlier statements committed,
164
+ * defeating the all-or-nothing contract.
165
+ *
166
+ * @param statements - An array of SQL strings or `{ sql, args }` objects.
167
+ * @param mode - When set, wraps the batch in `BEGIN <mode>` / `COMMIT`
168
+ * (with `ROLLBACK` on failure). Ignored when already inside a
169
+ * transaction.
170
+ * @returns An object with `rowsAffected` (sum of affected rows) and
171
+ * `lastInsertRowid` (rowid of the last successful insert).
172
+ *
173
+ * @example
174
+ * // Plain SQL strings (non-atomic).
175
+ * await db.batch([
176
+ * "INSERT INTO users(name) VALUES ('Alice')",
177
+ * "INSERT INTO users(name) VALUES ('Bob')",
178
+ * ]);
179
+ *
180
+ * @example
181
+ * // Positional and named bind parameters.
182
+ * await db.batch([
183
+ * { sql: "INSERT INTO users(name, email) VALUES (?, ?)", args: ["Carol", "carol@example.net"] },
184
+ * { sql: "INSERT INTO users(name, email) VALUES (:name, :email)", args: { name: "Dave", email: "dave@example.net" } },
185
+ * ]);
186
+ *
187
+ * @example
188
+ * // Atomic via the mode parameter.
189
+ * await db.batch([
190
+ * { sql: "INSERT INTO users(name) VALUES (?)", args: ["Eve"] },
191
+ * { sql: "INSERT INTO users(name) VALUES (?)", args: ["Frank"] },
192
+ * ], "immediate");
193
+ *
194
+ * @example
195
+ * // Atomic via the transaction() API for mixed workloads.
196
+ * const txn = db.transaction(async () => {
197
+ * await db.batch([{ sql: "INSERT INTO users(name) VALUES (?)", args: ["Eve"] }]);
198
+ * await db.exec("UPDATE counters SET n = n + 1");
199
+ * });
200
+ * await txn.immediate();
201
+ */
202
+ async batch(statements, mode) {
203
+ if (!Array.isArray(statements)) {
204
+ throw new TypeError("Expected first argument to be an array of statements");
205
+ }
206
+ if (!this.connected) {
207
+ await this.connect();
208
+ }
209
+ if (!this.open) {
210
+ throw new TypeError("The database connection is not open");
211
+ }
212
+ // Hold execLock across the entire batch so it is observed as a
213
+ // single unit by other callers on this connection. The helpers
214
+ // below run their own step loops without re-acquiring the lock.
215
+ await this.execLock.acquire();
216
+ try {
217
+ const runRawSql = async (sql) => {
218
+ const exec = this.db.executor(sql);
219
+ try {
220
+ while (true) {
221
+ const stepResult = exec.stepSync();
222
+ if (stepResult === STEP_IO) {
223
+ await this.io();
224
+ continue;
225
+ }
226
+ if (stepResult === STEP_DONE) {
227
+ break;
228
+ }
229
+ }
230
+ }
231
+ finally {
232
+ exec.reset();
233
+ }
234
+ };
235
+ const wrap = mode !== undefined && !this._inTransaction;
236
+ if (wrap) {
237
+ await runRawSql(`BEGIN ${mode.toUpperCase()}`);
238
+ this._inTransaction = true;
239
+ }
240
+ let rowsAffected = 0;
241
+ let lastInsertRowid;
242
+ try {
243
+ for (const statement of statements) {
244
+ const sql = typeof statement === "string" ? statement : statement.sql;
245
+ const args = typeof statement === "string" ? undefined : statement.args;
246
+ let nativeStmt;
247
+ try {
248
+ nativeStmt = this.db.prepare(sql);
249
+ }
250
+ catch (err) {
251
+ throw convertError(err);
252
+ }
253
+ try {
254
+ if (args !== undefined) {
255
+ bindParams(nativeStmt, [args]);
256
+ }
257
+ const totalChangesBefore = this.db.totalChanges();
258
+ const lastInsertRowidBefore = this.db.lastInsertRowid();
259
+ try {
260
+ while (true) {
261
+ const stepResult = await nativeStmt.stepSync();
262
+ if (stepResult === STEP_IO) {
263
+ await this.io();
264
+ continue;
265
+ }
266
+ if (stepResult === STEP_DONE) {
267
+ break;
268
+ }
269
+ // STEP_ROW results are discarded; batch() does not
270
+ // surface rows.
271
+ }
272
+ if (this.db.totalChanges() !== totalChangesBefore) {
273
+ rowsAffected += this.db.changes();
274
+ }
275
+ // SQLite keeps last_insert_rowid() sticky across
276
+ // non-INSERT statements, so just checking the value is
277
+ // not enough — UPDATE/DELETE would inherit a stale
278
+ // rowid. Use the delta as the per-statement INSERT
279
+ // signal.
280
+ const lastInsertRowidAfter = this.db.lastInsertRowid();
281
+ if (lastInsertRowidAfter !== lastInsertRowidBefore) {
282
+ lastInsertRowid = lastInsertRowidAfter;
283
+ }
284
+ }
285
+ finally {
286
+ nativeStmt.reset();
287
+ }
288
+ }
289
+ finally {
290
+ nativeStmt.finalize();
291
+ }
292
+ }
293
+ if (wrap) {
294
+ await runRawSql("COMMIT");
295
+ this._inTransaction = false;
296
+ }
297
+ }
298
+ catch (err) {
299
+ if (wrap) {
300
+ try {
301
+ await runRawSql("ROLLBACK");
302
+ }
303
+ catch { /* ignore */ }
304
+ this._inTransaction = false;
305
+ }
306
+ throw err;
307
+ }
308
+ return { rowsAffected, lastInsertRowid };
309
+ }
310
+ finally {
311
+ this.execLock.release();
312
+ }
313
+ }
145
314
  /**
146
315
  * Prepares the SQL and executes it as `Statement.run`, returning the run info.
147
316
  *
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tursodatabase/database-common",
3
- "version": "0.7.0-pre.1",
3
+ "version": "0.7.0-pre.3",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/tursodatabase/turso"