vsql-node 1.2.8 → 1.2.10

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
@@ -34,6 +34,17 @@ when it's finished (like `node:sqlite` and better-sqlite3). To run queries at
34
34
  the same time, use a connection in each
35
35
  [worker thread](https://nodejs.org/api/worker_threads.html).
36
36
 
37
+ This includes waiting for a lock: a `SERIALIZABLE` statement or transaction
38
+ (see [Transactions](#transactions)) waits up to 5 seconds for the other
39
+ connections to the file to finish their transactions, and the event loop is
40
+ blocked while it waits. If the other connection is on the same thread, it
41
+ can't finish, so the wait always fails with `40001` after 5 seconds (see
42
+ [#10](https://github.com/elliotchance/vsql-node/issues/10)).
43
+
44
+ Each call is one statement. More than one (`INSERT ...; INSERT ...`) is a
45
+ syntax error (`42601`), although a `;` at the end is allowed. A `--` comment
46
+ is an error (`42000`), so use `/* ... */` instead.
47
+
37
48
  | Connection | Statement | |
38
49
  |---------------------------------|---------------------------|-----------------------------------------------------|
39
50
  | `db.prepare(sql)` | | Prepares a statement |
@@ -86,7 +97,9 @@ db.info();
86
97
  ```
87
98
 
88
99
  A statement that hasn't been closed is freed when it's garbage collected, as is
89
- a connection (which rolls back its transaction). Both can be declared with
100
+ a connection (which rolls back its transaction). A statement with rows that
101
+ haven't all been fetched isn't, since the connection keeps it until its rows
102
+ are closed (see [Transactions](#transactions)). Both can be declared with
90
103
  `using` (on Node 24 or later).
91
104
 
92
105
  ## Transactions
@@ -106,6 +119,23 @@ db.transaction(() => {
106
119
  });
107
120
  ```
108
121
 
122
+ Until a query's rows have all been fetched (or the statement is closed, or the
123
+ iterator is left with `break` or `return`), its transaction is still going. An
124
+ iterator that's left part way through (such as one that only had `next()`
125
+ called once) keeps the file locked, so the other connections to it wait and
126
+ fail with `40001` after 5 seconds, and `db.begin()` (or `db.transaction(fn)`)
127
+ on the same connection fails with `25001`. Fetch all the rows, or close the
128
+ statement, first (see
129
+ [#5](https://github.com/elliotchance/vsql-node/issues/5)):
130
+
131
+ ```js
132
+ const it = db.iterate('SELECT x FROM foo');
133
+ it.next();
134
+ db.begin(); // VsqlError 25001: active SQL-transaction
135
+ it.return(); // closes the statement
136
+ db.begin();
137
+ ```
138
+
109
139
  A transaction in another one (`db.transaction(fn)` while there's already a
110
140
  transaction) is a savepoint, which is released when `fn` returns, or rolled back
111
141
  to if it throws, so only what `fn` did is undone and the outer transaction
@@ -148,9 +178,17 @@ db.release('a');
148
178
  db.commit(); // commits 1
149
179
  ```
150
180
 
181
+ vsql rolls back the whole transaction for some errors, such as a `40001`
182
+ serialization failure (other errors only undo the statement). After that,
183
+ `db.inTransaction` is `false` and each statement is committed on its own again.
184
+ If `fn` of `db.transaction(fn)` catches the error, the statements after it throw
185
+ a `TypeError` (rather than being committed one at a time), and so does
186
+ `db.transaction(fn)` when `fn` returns.
187
+
151
188
  `db.begin(options)` and `db.transaction(fn, options)` take `readOnly` (`false`
152
189
  by default) and `isolationLevel` (`"READ COMMITTED"` by default, or
153
- `"READ UNCOMMITTED"`, `"REPEATABLE READ"` or `"SERIALIZABLE"`):
190
+ `"READ UNCOMMITTED"`, `"REPEATABLE READ"` or `"SERIALIZABLE"`). The names are
191
+ case sensitive, so `'serializable'` is a `RangeError`:
154
192
 
155
193
  ```js
156
194
  db.transaction(() => report(), { readOnly: true, isolationLevel: 'SERIALIZABLE' });
@@ -158,8 +196,11 @@ db.transaction(() => report(), { readOnly: true, isolationLevel: 'SERIALIZABLE'
158
196
 
159
197
  vsql runs `READ UNCOMMITTED` (which must be `readOnly`) as `READ COMMITTED`, and
160
198
  `REPEATABLE READ` as `SERIALIZABLE`. A statement outside of a transaction is
161
- `SERIALIZABLE`. A `SERIALIZABLE` transaction waits for the other connections to
162
- the file, while a `READ COMMITTED` one fails if it can't commit.
199
+ `SERIALIZABLE` (vsql's default). A `SERIALIZABLE` transaction waits (up to 5
200
+ seconds) for the other connections to the file, while a `READ COMMITTED` one
201
+ doesn't wait, and fails with `40001` if another transaction changed the same
202
+ rows. Since a wait blocks the event loop (see [API](#api)), the default for
203
+ `db.begin()` is `READ COMMITTED` instead of vsql's `SERIALIZABLE`.
163
204
 
164
205
  ## Parameters
165
206
 
@@ -180,6 +221,12 @@ type, which is cast to the type it's used as:
180
221
  | `vsql.time(value)` | `TIME` (`WITH TIME ZONE` if it has an offset) |
181
222
  | `vsql.timestamp(value)` | `TIMESTAMP` (`WITH TIME ZONE` if it has an offset) |
182
223
 
224
+ The type of a parameter comes from where it's used, and the value is cast to
225
+ it. So a `number` that isn't an integer is truncated when it's used as an
226
+ integer (`WHERE x = ?` with `1.5` is `x = 1` when `x` is an `INTEGER`), and a
227
+ `?` that has no type from where it's used (such as `SELECT ?`) is a syntax
228
+ error (`42601`). Use `CAST(? AS DOUBLE PRECISION)` to give it a type.
229
+
183
230
  A string is cast to the type of the parameter (from where it's used), so it can
184
231
  be a parameter for any type that isn't binary, in vsql's format (such as
185
232
  `"2024-01-02"` for a `DATE`, `"1.5E+400"` for a `DECFLOAT` or `"-1-02"` for an
@@ -309,7 +356,7 @@ threads, so don't listen for them with `process.on`.
309
356
  ## Requirements
310
357
 
311
358
  Node 22 or later. The addon is prebuilt for macOS (ARM64 and x86-64), Linux
312
- (ARM64 and x86-64, with glibc 2.29 or later) and Windows (x86-64), so npm
359
+ (ARM64 and x86-64, with glibc 2.31 or later) and Windows (x86-64), so npm
313
360
  doesn't need to compile anything. It uses Node-API, so the same prebuild works
314
361
  for every version of Node.
315
362
 
package/index.d.ts CHANGED
@@ -80,8 +80,10 @@ export interface TransactionOptions {
80
80
  /** A READ ONLY transaction (it's READ WRITE by default). */
81
81
  readOnly?: boolean;
82
82
  /**
83
- * "READ COMMITTED" by default. vsql runs REPEATABLE READ as SERIALIZABLE,
84
- * and READ UNCOMMITTED (which must be readOnly) as READ COMMITTED.
83
+ * "READ COMMITTED" by default (vsql's default is SERIALIZABLE, which waits
84
+ * for other connections and blocks the event loop while it does). vsql runs
85
+ * REPEATABLE READ as SERIALIZABLE, and READ UNCOMMITTED (which must be
86
+ * readOnly) as READ COMMITTED.
85
87
  */
86
88
  isolationLevel?: IsolationLevel;
87
89
  }
@@ -133,6 +135,10 @@ export class Connection {
133
135
  readonly name: string;
134
136
  readonly bigint: boolean;
135
137
  readonly open: boolean;
138
+ /**
139
+ * Whether there's a transaction. It's false after vsql rolls back the
140
+ * transaction (such as for a 40001 serialization failure).
141
+ */
136
142
  readonly inTransaction: boolean;
137
143
 
138
144
  /** Prepares a statement, with a "?" for each parameter. */
@@ -166,7 +172,9 @@ export class Connection {
166
172
  * Calls fn in a transaction, which is committed when it returns (and its
167
173
  * value is returned), or rolled back if it throws. In another transaction,
168
174
  * it's a savepoint instead (and it can't have options). fn can't call commit
169
- * or rollback (without a savepoint), which throw a TypeError.
175
+ * or rollback (without a savepoint), which throw a TypeError. If vsql rolls
176
+ * back the transaction and fn catches the error, the statements after it,
177
+ * and transaction itself, throw a TypeError.
170
178
  */
171
179
  transaction<T>(fn: () => T, options?: TransactionOptions): T;
172
180
 
package/lib/connection.js CHANGED
@@ -28,8 +28,10 @@ const infoFields = [
28
28
  ];
29
29
 
30
30
  // Handles that weren't freed (with close) are freed when their connection or
31
- // statement is garbage collected. Handles are numbers that libvsql reuses, so
32
- // a statement's handle is only freed while its connection is open.
31
+ // statement is garbage collected. A statement with rows that haven't all been
32
+ // fetched isn't garbage collected, since it's in its connection's _cursors.
33
+ // Handles are numbers that libvsql reuses, so a statement's handle is only
34
+ // freed while its connection is open.
33
35
  const connections = new FinalizationRegistry((state) => {
34
36
  try {
35
37
  closeConnection(state);
@@ -96,8 +98,10 @@ class Connection {
96
98
  // when the transaction ends.
97
99
  this._cursors = new Set();
98
100
 
99
- // Whether fn of transaction is running, when commit and rollback can't be
100
- // called (transaction ends the transaction, or the savepoint, itself).
101
+ // Whether fn of transaction is running (in any transaction), when commit
102
+ // and rollback can't be called (transaction ends the transaction, or the
103
+ // savepoint, itself), and a statement after vsql rolled back the
104
+ // transaction fails instead of being committed on its own.
101
105
  this._inFn = false;
102
106
 
103
107
  const env = lib.allocHandle(lib.SQL_HANDLE_ENV, lib.SQL_NULL_HANDLE);
@@ -199,7 +203,9 @@ class Connection {
199
203
  // begin starts a transaction, which is ended by commit or rollback. Until
200
204
  // then, each statement is committed when it finishes (or when all the rows of
201
205
  // a query have been fetched). The options are readOnly (false by default)
202
- // and isolationLevel ("READ COMMITTED" by default).
206
+ // and isolationLevel ("READ COMMITTED" by default, rather than vsql's
207
+ // SERIALIZABLE, which waits for other connections and blocks the event loop
208
+ // while it does). The isolation level's name is case sensitive.
203
209
  begin(options = {}) {
204
210
  this._check();
205
211
  if (this._state.inTransaction) {
@@ -227,8 +233,38 @@ class Connection {
227
233
  for (const stmt of this._cursors) {
228
234
  stmt._closeCursor();
229
235
  }
236
+ try {
237
+ lib.endTran(this._state.dbc, commit);
238
+ } finally {
239
+ // A commit that fails may leave the transaction active, or roll it back.
240
+ this._state.inTransaction = lib.transactionActive(this._state.dbc);
241
+ }
242
+ }
243
+
244
+ // _sync is called after an error. vsql rolls back the whole transaction for
245
+ // some errors (such as a 40001 serialization failure). Each statement after
246
+ // that is committed on its own.
247
+ _sync() {
248
+ if (!this._state.open || !this._state.inTransaction ||
249
+ lib.transactionActive(this._state.dbc)) {
250
+ return;
251
+ }
252
+
253
+ // The rows of the transaction's queries are closed, like they are by
254
+ // commit and rollback. An open cursor would stop the next statement from
255
+ // being committed.
230
256
  this._state.inTransaction = false;
231
- lib.endTran(this._state.dbc, commit);
257
+ for (const stmt of this._cursors) {
258
+ stmt._closeCursor();
259
+ }
260
+ }
261
+
262
+ // _checkRolledBack throws if vsql rolled back the transaction while fn of
263
+ // transaction was running (and fn caught the error).
264
+ _checkRolledBack() {
265
+ if (this._inFn && !this._state.inTransaction) {
266
+ throw new TypeError('the transaction was rolled back by vsql');
267
+ }
232
268
  }
233
269
 
234
270
  // commit commits the transaction, if there is one.
@@ -254,7 +290,7 @@ class Connection {
254
290
  }
255
291
 
256
292
  this._checkSavepoint(savepoint);
257
- lib.endSavepoint(this._state.dbc, savepoint, false);
293
+ this._endSavepoint(savepoint, false);
258
294
  }
259
295
 
260
296
  // savepoint makes a savepoint in the transaction, which can be rolled back
@@ -270,7 +306,7 @@ class Connection {
270
306
  // came after them in the transaction.
271
307
  release(name) {
272
308
  this._checkSavepoint(name);
273
- lib.endSavepoint(this._state.dbc, name, true);
309
+ this._endSavepoint(name, true);
274
310
  }
275
311
 
276
312
  // _checkSavepoint checks the name of a savepoint, and that there's a
@@ -286,12 +322,25 @@ class Connection {
286
322
  }
287
323
  }
288
324
 
325
+ _endSavepoint(name, release) {
326
+ try {
327
+ lib.endSavepoint(this._state.dbc, name, release);
328
+ } catch (e) {
329
+ this._sync();
330
+ throw e;
331
+ }
332
+ }
333
+
289
334
  // transaction calls fn in a transaction, which is committed when it returns
290
335
  // (and its value is returned), or rolled back if it throws. In another
291
336
  // transaction, it uses a savepoint instead, which is released when fn
292
337
  // returns, or rolled back to if it throws, so only what fn did is undone.
293
338
  // fn can't call commit or rollback (without a savepoint), since then it
294
339
  // wouldn't be clear what was committed (like better-sqlite3).
340
+ //
341
+ // If vsql rolls back the transaction (such as for a 40001) and fn catches
342
+ // the error, the statements after it would be committed one at a time, so
343
+ // they throw instead, and so does transaction when fn returns.
295
344
  transaction(fn, options) {
296
345
  if (this._state.inTransaction) {
297
346
  if (options !== undefined) {
@@ -305,6 +354,7 @@ class Connection {
305
354
  this._inFn = true;
306
355
  try {
307
356
  result = call(fn);
357
+ this._checkRolledBack();
308
358
  } catch (e) {
309
359
  if (this._state.open) {
310
360
  this._end(false);
@@ -330,12 +380,13 @@ class Connection {
330
380
  } catch (e) {
331
381
  // fn may have closed the connection.
332
382
  if (this._state.open && this._state.inTransaction) {
333
- lib.endSavepoint(this._state.dbc, name, false);
334
- lib.endSavepoint(this._state.dbc, name, true);
383
+ this._endSavepoint(name, false);
384
+ this._endSavepoint(name, true);
335
385
  }
336
386
  throw e;
337
387
  }
338
- lib.endSavepoint(this._state.dbc, name, true);
388
+ this._checkRolledBack();
389
+ this._endSavepoint(name, true);
339
390
 
340
391
  return result;
341
392
  } finally {
@@ -558,10 +609,16 @@ class Statement {
558
609
  if (this._iterating) {
559
610
  throw new TypeError('the statement is being iterated');
560
611
  }
612
+ this.connection._checkRolledBack();
561
613
  const values = toParams(params);
562
614
  this._closeCursor();
563
615
  this._execution++;
564
- lib.execute(this._stmt, values);
616
+ try {
617
+ lib.execute(this._stmt, values);
618
+ } catch (e) {
619
+ this.connection._sync();
620
+ throw e;
621
+ }
565
622
  if (this._changed()) {
566
623
  this._describe();
567
624
  }
@@ -598,7 +655,13 @@ class Statement {
598
655
  }
599
656
 
600
657
  _fetch(max) {
601
- const rows = lib.fetch(this._stmt, this._kinds, max);
658
+ let rows;
659
+ try {
660
+ rows = lib.fetch(this._stmt, this._kinds, max);
661
+ } catch (e) {
662
+ this.connection._sync();
663
+ throw e;
664
+ }
602
665
  if (max === 0 || rows.length < max) {
603
666
  this._closeCursor();
604
667
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vsql-node",
3
- "version": "1.2.8",
3
+ "version": "1.2.10",
4
4
  "description": "A Node.js driver for vsql, a single file or in-memory SQL database.",
5
5
  "keywords": [
6
6
  "vsql",
package/src/binding.c CHANGED
@@ -534,6 +534,22 @@ static napi_value end_savepoint(napi_env env, napi_callback_info info) {
534
534
  return undefined(env);
535
535
  }
536
536
 
537
+ // transactionActive(dbc) -> bool is whether the connection has a transaction
538
+ // (SQL_DIAG_TRANSACTION_ACTIVE). vsql rolls back the whole transaction for
539
+ // some errors, so this is the only way to know after one.
540
+ static napi_value transaction_active(napi_env env, napi_callback_info info) {
541
+ ARGS(1);
542
+ int32_t dbc;
543
+ NAPI_CALL(napi_get_value_int32(env, argv[0], &dbc));
544
+
545
+ SQLINTEGER active = 0;
546
+ CHECK(SQL_HANDLE_DBC, dbc,
547
+ SQLGetDiagField(SQL_HANDLE_DBC, dbc, 0, SQL_DIAG_TRANSACTION_ACTIVE, &active, 0, NULL));
548
+ napi_value result;
549
+ NAPI_CALL(napi_get_boolean(env, active != 0, &result));
550
+ return result;
551
+ }
552
+
537
553
  // getInfo(dbc, infoType, kind) -> value reads SQLGetInfo, as a string (kind
538
554
  // "s") or an SQLSMALLINT ("h") or SQLINTEGER ("i").
539
555
  static napi_value get_info(napi_env env, napi_callback_info info) {
@@ -1229,6 +1245,7 @@ NAPI_MODULE_INIT() {
1229
1245
  {"startTran", NULL, start_tran, NULL, NULL, NULL, napi_default, NULL},
1230
1246
  {"endTran", NULL, end_tran, NULL, NULL, NULL, napi_default, NULL},
1231
1247
  {"endSavepoint", NULL, end_savepoint, NULL, NULL, NULL, napi_default, NULL},
1248
+ {"transactionActive", NULL, transaction_active, NULL, NULL, NULL, napi_default, NULL},
1232
1249
  {"getInfo", NULL, get_info, NULL, NULL, NULL, napi_default, NULL},
1233
1250
  {"descField", NULL, desc_field, NULL, NULL, NULL, napi_default, NULL},
1234
1251
  {"execDirect", NULL, exec_direct, NULL, NULL, NULL, napi_default, NULL},