vsql-node 1.2.7 → 1.2.9

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
@@ -148,6 +148,13 @@ db.release('a');
148
148
  db.commit(); // commits 1
149
149
  ```
150
150
 
151
+ vsql rolls back the whole transaction for some errors, such as a `40001`
152
+ serialization failure (other errors only undo the statement). After that,
153
+ `db.inTransaction` is `false` and each statement is committed on its own again.
154
+ If `fn` of `db.transaction(fn)` catches the error, the statements after it throw
155
+ a `TypeError` (rather than being committed one at a time), and so does
156
+ `db.transaction(fn)` when `fn` returns.
157
+
151
158
  `db.begin(options)` and `db.transaction(fn, options)` take `readOnly` (`false`
152
159
  by default) and `isolationLevel` (`"READ COMMITTED"` by default, or
153
160
  `"READ UNCOMMITTED"`, `"REPEATABLE READ"` or `"SERIALIZABLE"`):
@@ -266,9 +273,37 @@ try {
266
273
  }
267
274
  ```
268
275
 
276
+ `diagnostics` are the other conditions that vsql raised with the error, each an
277
+ object of `sqlstate`, `message` and the same fields (it's usually empty):
278
+
279
+ ```js
280
+ try {
281
+ db.all('SELECT SUM(x) / 0 FROM t');
282
+ } catch (e) {
283
+ console.log(e.sqlstate, e.diagnostics); // 22012 [{ sqlstate: '01003', message: 'null value eliminated in set function' }]
284
+ }
285
+ ```
286
+
269
287
  An error from the driver itself (such as using a closed connection, or a value
270
288
  that can't be a parameter) is a `TypeError` or `RangeError`.
271
289
 
290
+ ### Warnings
291
+
292
+ A statement that succeeds with a warning from vsql (such as `01003` when a
293
+ `NULL` is eliminated from `SUM`, or `01004` when a string is truncated) gives a
294
+ `vsql.VsqlWarning` to `process.emitWarning`, which is how Node reports problems
295
+ that shouldn't stop the program. It has the same fields as a `VsqlError`. Node
296
+ prints warnings to stderr, unless they're handled with `process.on('warning')`
297
+ or Node is run with `--no-warnings` (or `--disable-warning=VsqlWarning`):
298
+
299
+ ```js
300
+ process.on('warning', (w) => {
301
+ if (w instanceof vsql.VsqlWarning) {
302
+ console.log(w.sqlstate, w.message); // 01003 null value eliminated in set function (SQLSTATE 01003)
303
+ }
304
+ });
305
+ ```
306
+
272
307
  ## Threads
273
308
 
274
309
  Each connection has its own libvsql environment, so connections in different
package/index.d.ts CHANGED
@@ -133,6 +133,10 @@ export class Connection {
133
133
  readonly name: string;
134
134
  readonly bigint: boolean;
135
135
  readonly open: boolean;
136
+ /**
137
+ * Whether there's a transaction. It's false after vsql rolls back the
138
+ * transaction (such as for a 40001 serialization failure).
139
+ */
136
140
  readonly inTransaction: boolean;
137
141
 
138
142
  /** Prepares a statement, with a "?" for each parameter. */
@@ -166,7 +170,9 @@ export class Connection {
166
170
  * Calls fn in a transaction, which is committed when it returns (and its
167
171
  * value is returned), or rolled back if it throws. In another transaction,
168
172
  * 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.
173
+ * or rollback (without a savepoint), which throw a TypeError. If vsql rolls
174
+ * back the transaction and fn catches the error, the statements after it,
175
+ * and transaction itself, throw a TypeError.
170
176
  */
171
177
  transaction<T>(fn: () => T, options?: TransactionOptions): T;
172
178
 
@@ -225,6 +231,43 @@ export class VsqlError extends Error {
225
231
  readonly cursorName?: string;
226
232
  /** Whether vsql raised more conditions than it kept. */
227
233
  readonly more: boolean;
234
+ /** The other conditions that vsql raised with the error (usually none). */
235
+ readonly diagnostics: Diagnostic[];
236
+ }
237
+
238
+ /** A condition that vsql raised with an error. */
239
+ export interface Diagnostic {
240
+ /** The SQLSTATE, such as "01003". */
241
+ readonly sqlstate: string;
242
+ readonly message: string;
243
+ readonly constraintCatalog?: string;
244
+ readonly constraintSchema?: string;
245
+ readonly constraintName?: string;
246
+ readonly catalogName?: string;
247
+ readonly schemaName?: string;
248
+ readonly tableName?: string;
249
+ readonly columnName?: string;
250
+ readonly cursorName?: string;
251
+ }
252
+
253
+ /**
254
+ * A warning from vsql (such as "01003" when a NULL is eliminated from SUM),
255
+ * which is given to process.emitWarning.
256
+ */
257
+ export class VsqlWarning extends Error {
258
+ readonly name: 'VsqlWarning';
259
+ /** The SQLSTATE, such as "01003". */
260
+ readonly sqlstate: string;
261
+ /** The same as sqlstate. */
262
+ readonly code: string;
263
+ readonly constraintCatalog?: string;
264
+ readonly constraintSchema?: string;
265
+ readonly constraintName?: string;
266
+ readonly catalogName?: string;
267
+ readonly schemaName?: string;
268
+ readonly tableName?: string;
269
+ readonly columnName?: string;
270
+ readonly cursorName?: string;
228
271
  }
229
272
 
230
273
  /**
package/lib/binding.js CHANGED
@@ -4,10 +4,17 @@
4
4
 
5
5
  const path = require('node:path');
6
6
 
7
- const { VsqlError } = require('./errors');
7
+ const { VsqlError, VsqlWarning } = require('./errors');
8
8
 
9
9
  const lib = require('node-gyp-build')(path.join(__dirname, '..'));
10
10
 
11
- lib.setErrorFactory((sqlstate, message, fields) => new VsqlError(sqlstate, message, fields));
11
+ lib.setErrorFactory(
12
+ (sqlstate, message, fields) => new VsqlError(sqlstate, message, fields),
13
+ (records) => {
14
+ for (const record of records) {
15
+ process.emitWarning(new VsqlWarning(record.sqlstate, record.message, record));
16
+ }
17
+ },
18
+ );
12
19
 
13
20
  module.exports = lib;
package/lib/connection.js CHANGED
@@ -96,8 +96,10 @@ class Connection {
96
96
  // when the transaction ends.
97
97
  this._cursors = new Set();
98
98
 
99
- // Whether fn of transaction is running, when commit and rollback can't be
100
- // called (transaction ends the transaction, or the savepoint, itself).
99
+ // Whether fn of transaction is running (in any transaction), when commit
100
+ // and rollback can't be called (transaction ends the transaction, or the
101
+ // savepoint, itself), and a statement after vsql rolled back the
102
+ // transaction fails instead of being committed on its own.
101
103
  this._inFn = false;
102
104
 
103
105
  const env = lib.allocHandle(lib.SQL_HANDLE_ENV, lib.SQL_NULL_HANDLE);
@@ -227,8 +229,38 @@ class Connection {
227
229
  for (const stmt of this._cursors) {
228
230
  stmt._closeCursor();
229
231
  }
232
+ try {
233
+ lib.endTran(this._state.dbc, commit);
234
+ } finally {
235
+ // A commit that fails may leave the transaction active, or roll it back.
236
+ this._state.inTransaction = lib.transactionActive(this._state.dbc);
237
+ }
238
+ }
239
+
240
+ // _sync is called after an error. vsql rolls back the whole transaction for
241
+ // some errors (such as a 40001 serialization failure). Each statement after
242
+ // that is committed on its own.
243
+ _sync() {
244
+ if (!this._state.open || !this._state.inTransaction ||
245
+ lib.transactionActive(this._state.dbc)) {
246
+ return;
247
+ }
248
+
249
+ // The rows of the transaction's queries are closed, like they are by
250
+ // commit and rollback. An open cursor would stop the next statement from
251
+ // being committed.
230
252
  this._state.inTransaction = false;
231
- lib.endTran(this._state.dbc, commit);
253
+ for (const stmt of this._cursors) {
254
+ stmt._closeCursor();
255
+ }
256
+ }
257
+
258
+ // _checkRolledBack throws if vsql rolled back the transaction while fn of
259
+ // transaction was running (and fn caught the error).
260
+ _checkRolledBack() {
261
+ if (this._inFn && !this._state.inTransaction) {
262
+ throw new TypeError('the transaction was rolled back by vsql');
263
+ }
232
264
  }
233
265
 
234
266
  // commit commits the transaction, if there is one.
@@ -254,7 +286,7 @@ class Connection {
254
286
  }
255
287
 
256
288
  this._checkSavepoint(savepoint);
257
- lib.endSavepoint(this._state.dbc, savepoint, false);
289
+ this._endSavepoint(savepoint, false);
258
290
  }
259
291
 
260
292
  // savepoint makes a savepoint in the transaction, which can be rolled back
@@ -270,7 +302,7 @@ class Connection {
270
302
  // came after them in the transaction.
271
303
  release(name) {
272
304
  this._checkSavepoint(name);
273
- lib.endSavepoint(this._state.dbc, name, true);
305
+ this._endSavepoint(name, true);
274
306
  }
275
307
 
276
308
  // _checkSavepoint checks the name of a savepoint, and that there's a
@@ -286,12 +318,25 @@ class Connection {
286
318
  }
287
319
  }
288
320
 
321
+ _endSavepoint(name, release) {
322
+ try {
323
+ lib.endSavepoint(this._state.dbc, name, release);
324
+ } catch (e) {
325
+ this._sync();
326
+ throw e;
327
+ }
328
+ }
329
+
289
330
  // transaction calls fn in a transaction, which is committed when it returns
290
331
  // (and its value is returned), or rolled back if it throws. In another
291
332
  // transaction, it uses a savepoint instead, which is released when fn
292
333
  // returns, or rolled back to if it throws, so only what fn did is undone.
293
334
  // fn can't call commit or rollback (without a savepoint), since then it
294
335
  // wouldn't be clear what was committed (like better-sqlite3).
336
+ //
337
+ // If vsql rolls back the transaction (such as for a 40001) and fn catches
338
+ // the error, the statements after it would be committed one at a time, so
339
+ // they throw instead, and so does transaction when fn returns.
295
340
  transaction(fn, options) {
296
341
  if (this._state.inTransaction) {
297
342
  if (options !== undefined) {
@@ -305,6 +350,7 @@ class Connection {
305
350
  this._inFn = true;
306
351
  try {
307
352
  result = call(fn);
353
+ this._checkRolledBack();
308
354
  } catch (e) {
309
355
  if (this._state.open) {
310
356
  this._end(false);
@@ -330,12 +376,13 @@ class Connection {
330
376
  } catch (e) {
331
377
  // fn may have closed the connection.
332
378
  if (this._state.open && this._state.inTransaction) {
333
- lib.endSavepoint(this._state.dbc, name, false);
334
- lib.endSavepoint(this._state.dbc, name, true);
379
+ this._endSavepoint(name, false);
380
+ this._endSavepoint(name, true);
335
381
  }
336
382
  throw e;
337
383
  }
338
- lib.endSavepoint(this._state.dbc, name, true);
384
+ this._checkRolledBack();
385
+ this._endSavepoint(name, true);
339
386
 
340
387
  return result;
341
388
  } finally {
@@ -558,10 +605,16 @@ class Statement {
558
605
  if (this._iterating) {
559
606
  throw new TypeError('the statement is being iterated');
560
607
  }
608
+ this.connection._checkRolledBack();
561
609
  const values = toParams(params);
562
610
  this._closeCursor();
563
611
  this._execution++;
564
- lib.execute(this._stmt, values);
612
+ try {
613
+ lib.execute(this._stmt, values);
614
+ } catch (e) {
615
+ this.connection._sync();
616
+ throw e;
617
+ }
565
618
  if (this._changed()) {
566
619
  this._describe();
567
620
  }
@@ -598,7 +651,13 @@ class Statement {
598
651
  }
599
652
 
600
653
  _fetch(max) {
601
- const rows = lib.fetch(this._stmt, this._kinds, max);
654
+ let rows;
655
+ try {
656
+ rows = lib.fetch(this._stmt, this._kinds, max);
657
+ } catch (e) {
658
+ this.connection._sync();
659
+ throw e;
660
+ }
602
661
  if (max === 0 || rows.length < max) {
603
662
  this._closeCursor();
604
663
  }
package/lib/errors.js CHANGED
@@ -11,17 +11,47 @@ class VsqlError extends Error {
11
11
  // constraintName), the table or column (catalogName, schemaName, tableName
12
12
  // and columnName) and the cursor (cursorName). more is true if vsql raised
13
13
  // more conditions than it kept.
14
+ //
15
+ // diagnostics are the other conditions that vsql raised with the error (each
16
+ // an object of sqlstate, message and the same fields), which is usually
17
+ // empty.
14
18
  constructor(sqlstate, message, fields = {}) {
15
19
  super(`${message} (SQLSTATE ${sqlstate})`);
16
20
  this.name = 'VsqlError';
17
21
  this.sqlstate = sqlstate;
18
22
  this.code = sqlstate;
19
- for (const name of FIELDS) {
20
- if (fields[name] !== undefined) {
21
- this[name] = fields[name];
22
- }
23
- }
23
+ setFields(this, fields);
24
24
  this.more = Boolean(fields.more);
25
+ this.diagnostics = (fields.diagnostics ?? []).map((record) => {
26
+ const d = { sqlstate: record.sqlstate, message: record.message };
27
+ setFields(d, record);
28
+ return d;
29
+ });
30
+ }
31
+ }
32
+
33
+ // VsqlWarning is a warning from vsql (a completion condition, such as "01003"
34
+ // when a NULL is eliminated from SUM), when a statement still succeeds. Each
35
+ // warning is given to process.emitWarning, which is how Node reports problems
36
+ // that shouldn't stop the program: they're printed to stderr, unless there's
37
+ // a listener for process.on('warning') or Node is run with --no-warnings (or
38
+ // --disable-warning=VsqlWarning). It has the same fields as VsqlError.
39
+ class VsqlWarning extends Error {
40
+ constructor(sqlstate, message, fields = {}) {
41
+ super(`${message} (SQLSTATE ${sqlstate})`);
42
+ this.name = 'VsqlWarning';
43
+ this.sqlstate = sqlstate;
44
+ this.code = sqlstate;
45
+ setFields(this, fields);
46
+ }
47
+ }
48
+
49
+ // setFields copies the diagnostic fields that vsql gave.
50
+ function setFields(target, fields) {
51
+ for (const name of FIELDS) {
52
+ if (fields[name] !== undefined) {
53
+ target[name] = fields[name];
54
+ }
25
55
  }
26
56
  }
27
57
 
@@ -36,4 +66,4 @@ const FIELDS = [
36
66
  'cursorName',
37
67
  ];
38
68
 
39
- module.exports = { VsqlError };
69
+ module.exports = { VsqlError, VsqlWarning };
package/lib/index.js CHANGED
@@ -18,7 +18,7 @@
18
18
 
19
19
  const { Connection, Statement } = require('./connection');
20
20
  const { SqlValue, numeric, date, time, timestamp } = require('./convert');
21
- const { VsqlError } = require('./errors');
21
+ const { VsqlError, VsqlWarning } = require('./errors');
22
22
 
23
23
  // connect opens a connection to a database file (which is created if it
24
24
  // doesn't exist), or ":memory:" for a database that only exists for the life
@@ -33,6 +33,7 @@ module.exports = {
33
33
  Connection,
34
34
  Statement,
35
35
  VsqlError,
36
+ VsqlWarning,
36
37
  SqlValue,
37
38
  numeric,
38
39
  date,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vsql-node",
3
- "version": "1.2.7",
3
+ "version": "1.2.9",
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
@@ -8,7 +8,9 @@
8
8
  //
9
9
  // When a routine fails, the error is made by the function given to
10
10
  // setErrorFactory, from the SQLSTATE, message and other fields (see
11
- // diag_fields) of the first diagnostic record.
11
+ // diag_fields) of the first diagnostic record, with the other records as
12
+ // "diagnostics". When it succeeds with warnings (SQL_SUCCESS_WITH_INFO), the
13
+ // records are given to the warning function given to setErrorFactory.
12
14
 
13
15
  #include <stdlib.h>
14
16
  #include <string.h>
@@ -44,6 +46,7 @@ static void vsql_gc_after_node_init(void) {
44
46
  // The data of each instance of the addon (one for each thread that loads it).
45
47
  typedef struct {
46
48
  napi_ref error_factory;
49
+ napi_ref warn;
47
50
  } instance;
48
51
 
49
52
  // throw_napi_error throws an error for the Node-API call that just failed, unless
@@ -144,10 +147,11 @@ static const struct {
144
147
  {NULL, 0},
145
148
  };
146
149
 
147
- // get_diag_fields is an object of the diagnostic fields of the first record
148
- // (see diag_fields), and "more" (SQL_DIAG_MORE) if a condition was dropped.
149
- // It's NULL if the fields can't be read.
150
- static napi_value get_diag_fields(napi_env env, SQLSMALLINT handle_type, SQLINTEGER handle) {
150
+ // get_diag_fields is an object of the diagnostic fields of a record (see
151
+ // diag_fields), and for the first record "more" (SQL_DIAG_MORE, a header
152
+ // field) if a condition was dropped. It's NULL if the fields can't be read.
153
+ static napi_value get_diag_fields(napi_env env, SQLSMALLINT handle_type, SQLINTEGER handle,
154
+ SQLSMALLINT record) {
151
155
  napi_value result, value;
152
156
  if (napi_create_object(env, &result) != napi_ok) {
153
157
  return NULL;
@@ -157,7 +161,7 @@ static napi_value get_diag_fields(napi_env env, SQLSMALLINT handle_type, SQLINTE
157
161
  SQLCHAR buf[4 * 128 + 1];
158
162
  for (int i = 0; diag_fields[i].name != NULL; i++) {
159
163
  SQLSMALLINT length = 0;
160
- SQLRETURN rc = SQLGetDiagField(handle_type, handle, 1, diag_fields[i].field, buf,
164
+ SQLRETURN rc = SQLGetDiagField(handle_type, handle, record, diag_fields[i].field, buf,
161
165
  sizeof(buf), &length);
162
166
  if ((rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO) || length <= 0) {
163
167
  continue;
@@ -173,7 +177,7 @@ static napi_value get_diag_fields(napi_env env, SQLSMALLINT handle_type, SQLINTE
173
177
 
174
178
  SQLINTEGER more = 0;
175
179
  SQLRETURN rc = SQLGetDiagField(handle_type, handle, 0, SQL_DIAG_MORE, &more, 0, NULL);
176
- if ((rc == SQL_SUCCESS || rc == SQL_SUCCESS_WITH_INFO) && more) {
180
+ if (record == 1 && (rc == SQL_SUCCESS || rc == SQL_SUCCESS_WITH_INFO) && more) {
177
181
  if (napi_get_boolean(env, true, &value) != napi_ok ||
178
182
  napi_set_named_property(env, result, "more", value) != napi_ok) {
179
183
  return NULL;
@@ -183,49 +187,141 @@ static napi_value get_diag_fields(napi_env env, SQLSMALLINT handle_type, SQLINTE
183
187
  return result;
184
188
  }
185
189
 
186
- // check returns 0 for a return code that isn't an error (SQL_NO_DATA isn't),
187
- // otherwise it throws the error from the diagnostics of the handle and returns
188
- // -1.
189
- static int check(napi_env env, SQLRETURN rc, SQLSMALLINT handle_type, SQLINTEGER handle) {
190
- switch (rc) {
191
- case SQL_SUCCESS:
192
- case SQL_SUCCESS_WITH_INFO:
193
- case SQL_NO_DATA:
194
- return 0;
195
- case SQL_INVALID_HANDLE:
196
- throw_error(env, "HY000", "invalid handle", NAPI_AUTO_LENGTH);
197
- return -1;
198
- }
199
-
200
- SQLCHAR sqlstate[6];
201
- SQLSMALLINT size = 512, length = 0;
202
- SQLCHAR *message = malloc(size);
190
+ // get_message reads the SQLSTATE and message of a diagnostic record. The
191
+ // message must be freed. It returns -1 if there's no such record, or -2 if it's
192
+ // out of memory.
193
+ static int get_message(SQLSMALLINT handle_type, SQLINTEGER handle, SQLSMALLINT record,
194
+ SQLCHAR sqlstate[6], SQLCHAR **message, SQLSMALLINT *length) {
195
+ SQLSMALLINT size = 512;
203
196
  for (;;) {
204
- if (message == NULL) {
205
- napi_throw_error(env, NULL, "out of memory");
206
- return -1;
197
+ *message = malloc(size);
198
+ if (*message == NULL) {
199
+ return -2;
207
200
  }
208
201
 
209
- rc = SQLGetDiagRec(handle_type, handle, 1, sqlstate, NULL, message, size, &length);
202
+ SQLRETURN rc = SQLGetDiagRec(handle_type, handle, record, sqlstate, NULL, *message, size,
203
+ length);
210
204
  if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO) {
211
- free(message);
212
- throw_error(env, "HY000", "unknown error", NAPI_AUTO_LENGTH);
205
+ free(*message);
206
+ *message = NULL;
213
207
  return -1;
214
208
  }
215
209
 
216
210
  // The message was truncated.
217
- if (length >= size) {
218
- size = length + 1;
219
- free(message);
220
- message = malloc(size);
211
+ if (*length >= size) {
212
+ size = *length + 1;
213
+ free(*message);
221
214
  continue;
222
215
  }
223
216
 
224
- napi_value fields = get_diag_fields(env, handle_type, handle);
225
- throw_error_fields(env, (const char *)sqlstate, (const char *)message, length, fields);
217
+ return 0;
218
+ }
219
+ }
220
+
221
+ // get_records is an array of the diagnostic records from first, each an object
222
+ // of its sqlstate, message and fields (see get_diag_fields). It's NULL if they
223
+ // can't be read.
224
+ static napi_value get_records(napi_env env, SQLSMALLINT handle_type, SQLINTEGER handle,
225
+ SQLSMALLINT first) {
226
+ SQLINTEGER number = 0;
227
+ SQLRETURN rc = SQLGetDiagField(handle_type, handle, 0, SQL_DIAG_NUMBER, &number, 0, NULL);
228
+ if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO) {
229
+ number = 0;
230
+ }
231
+
232
+ napi_value records;
233
+ if (napi_create_array(env, &records) != napi_ok) {
234
+ return NULL;
235
+ }
236
+ for (SQLINTEGER i = first; i <= number; i++) {
237
+ SQLCHAR sqlstate[6], *message = NULL;
238
+ SQLSMALLINT length = 0;
239
+ if (get_message(handle_type, handle, (SQLSMALLINT)i, sqlstate, &message, &length) < 0) {
240
+ break;
241
+ }
242
+
243
+ napi_value record = get_diag_fields(env, handle_type, handle, (SQLSMALLINT)i), value;
244
+ napi_status status = record == NULL ? napi_generic_failure
245
+ : napi_create_string_utf8(env, (const char *)message,
246
+ length, &value);
226
247
  free(message);
248
+ if (status != napi_ok || napi_set_named_property(env, record, "message", value) != napi_ok ||
249
+ napi_create_string_utf8(env, (const char *)sqlstate, NAPI_AUTO_LENGTH, &value) !=
250
+ napi_ok ||
251
+ napi_set_named_property(env, record, "sqlstate", value) != napi_ok ||
252
+ napi_set_element(env, records, (uint32_t)(i - first), record) != napi_ok) {
253
+ return NULL;
254
+ }
255
+ }
256
+
257
+ return records;
258
+ }
259
+
260
+ // warn gives the diagnostic records of a routine that succeeded with warnings
261
+ // to the warning function. It returns -1 if that throws.
262
+ static int warn(napi_env env, SQLSMALLINT handle_type, SQLINTEGER handle) {
263
+ instance *inst = NULL;
264
+ napi_value fn = NULL, records, global, result;
265
+ napi_get_instance_data(env, (void **)&inst);
266
+ if (inst == NULL || inst->warn == NULL ||
267
+ napi_get_reference_value(env, inst->warn, &fn) != napi_ok || fn == NULL) {
268
+ return 0;
269
+ }
270
+
271
+ records = get_records(env, handle_type, handle, 1);
272
+ if (records == NULL) {
273
+ return 0;
274
+ }
275
+ if (napi_get_global(env, &global) != napi_ok ||
276
+ napi_call_function(env, global, fn, 1, &records, &result) != napi_ok) {
277
+ return -1;
278
+ }
279
+
280
+ return 0;
281
+ }
282
+
283
+ // check_warn returns 0 for a return code that isn't an error (SQL_NO_DATA
284
+ // isn't), otherwise it throws the error from the diagnostics of the handle and
285
+ // returns -1. If warnings is 1, the warnings of SQL_SUCCESS_WITH_INFO are
286
+ // given to the warning function (see warn). It's 0 when the routine is
287
+ // expected to truncate a value (01004) that's then read in pieces.
288
+ static int check_warn(napi_env env, SQLRETURN rc, SQLSMALLINT handle_type, SQLINTEGER handle,
289
+ int warnings) {
290
+ switch (rc) {
291
+ case SQL_SUCCESS_WITH_INFO:
292
+ return warnings ? warn(env, handle_type, handle) : 0;
293
+ case SQL_SUCCESS:
294
+ case SQL_NO_DATA:
295
+ return 0;
296
+ case SQL_INVALID_HANDLE:
297
+ throw_error(env, "HY000", "invalid handle", NAPI_AUTO_LENGTH);
298
+ return -1;
299
+ }
300
+
301
+ SQLCHAR sqlstate[6], *message = NULL;
302
+ SQLSMALLINT length = 0;
303
+ switch (get_message(handle_type, handle, 1, sqlstate, &message, &length)) {
304
+ case -2:
305
+ napi_throw_error(env, NULL, "out of memory");
227
306
  return -1;
307
+ case -1:
308
+ throw_error(env, "HY000", "unknown error", NAPI_AUTO_LENGTH);
309
+ return -1;
310
+ }
311
+
312
+ // The other records (if any) are "diagnostics".
313
+ napi_value fields = get_diag_fields(env, handle_type, handle, 1);
314
+ napi_value records = fields == NULL ? NULL : get_records(env, handle_type, handle, 2);
315
+ if (records != NULL) {
316
+ napi_set_named_property(env, fields, "diagnostics", records);
228
317
  }
318
+ throw_error_fields(env, (const char *)sqlstate, (const char *)message, length, fields);
319
+ free(message);
320
+ return -1;
321
+ }
322
+
323
+ static int check(napi_env env, SQLRETURN rc, SQLSMALLINT handle_type, SQLINTEGER handle) {
324
+ return check_warn(env, rc, handle_type, handle, 1);
229
325
  }
230
326
 
231
327
  // CHECK returns NULL from the function if a libvsql routine fails.
@@ -292,16 +388,22 @@ static napi_value number(napi_env env, double n) {
292
388
  return result;
293
389
  }
294
390
 
295
- // setErrorFactory(factory)
391
+ // setErrorFactory(factory, warn) sets the function that makes errors, and the
392
+ // function that's called with the records of warnings.
296
393
  static napi_value set_error_factory(napi_env env, napi_callback_info info) {
297
- ARGS(1);
394
+ ARGS(2);
298
395
  instance *inst = NULL;
299
396
  NAPI_CALL(napi_get_instance_data(env, (void **)&inst));
300
397
  if (inst->error_factory != NULL) {
301
398
  napi_delete_reference(env, inst->error_factory);
302
399
  inst->error_factory = NULL;
303
400
  }
401
+ if (inst->warn != NULL) {
402
+ napi_delete_reference(env, inst->warn);
403
+ inst->warn = NULL;
404
+ }
304
405
  NAPI_CALL(napi_create_reference(env, argv[0], 1, &inst->error_factory));
406
+ NAPI_CALL(napi_create_reference(env, argv[1], 1, &inst->warn));
305
407
 
306
408
  return undefined(env);
307
409
  }
@@ -432,6 +534,22 @@ static napi_value end_savepoint(napi_env env, napi_callback_info info) {
432
534
  return undefined(env);
433
535
  }
434
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
+
435
553
  // getInfo(dbc, infoType, kind) -> value reads SQLGetInfo, as a string (kind
436
554
  // "s") or an SQLSMALLINT ("h") or SQLINTEGER ("i").
437
555
  static napi_value get_info(napi_env env, napi_callback_info info) {
@@ -743,7 +861,7 @@ static napi_value describe_col(napi_env env, napi_callback_info info) {
743
861
 
744
862
  SQLRETURN rc = SQLDescribeCol(stmt, (SQLSMALLINT)n, name, size, &length, &data_type,
745
863
  &column_size, &decimal_digits, &nullable);
746
- if (check(env, rc, SQL_HANDLE_STMT, stmt) < 0) {
864
+ if (check_warn(env, rc, SQL_HANDLE_STMT, stmt, 0) < 0) {
747
865
  free(name);
748
866
  return NULL;
749
867
  }
@@ -792,7 +910,7 @@ static napi_value get_chars(napi_env env, SQLINTEGER stmt, SQLSMALLINT n) {
792
910
  size_t length = 0;
793
911
  for (;;) {
794
912
  SQLRETURN rc = SQLGetData(stmt, n, SQL_CHAR, buf + length, size - (SQLINTEGER)length, &ind);
795
- if (check(env, rc, SQL_HANDLE_STMT, stmt) < 0) {
913
+ if (check_warn(env, rc, SQL_HANDLE_STMT, stmt, 0) < 0) {
796
914
  free(large);
797
915
  return NULL;
798
916
  }
@@ -841,7 +959,7 @@ static napi_value get_octets(napi_env env, SQLINTEGER stmt, SQLSMALLINT n) {
841
959
  for (;;) {
842
960
  SQLRETURN rc =
843
961
  SQLGetData(stmt, n, SQL_BINARY, buf + length, size - (SQLINTEGER)length, &ind);
844
- if (check(env, rc, SQL_HANDLE_STMT, stmt) < 0) {
962
+ if (check_warn(env, rc, SQL_HANDLE_STMT, stmt, 0) < 0) {
845
963
  free(large);
846
964
  return NULL;
847
965
  }
@@ -1010,6 +1128,9 @@ static void free_instance(napi_env env, void *data, void *hint) {
1010
1128
  if (inst->error_factory != NULL) {
1011
1129
  napi_delete_reference(env, inst->error_factory);
1012
1130
  }
1131
+ if (inst->warn != NULL) {
1132
+ napi_delete_reference(env, inst->warn);
1133
+ }
1013
1134
  free(inst);
1014
1135
  }
1015
1136
 
@@ -1124,6 +1245,7 @@ NAPI_MODULE_INIT() {
1124
1245
  {"startTran", NULL, start_tran, NULL, NULL, NULL, napi_default, NULL},
1125
1246
  {"endTran", NULL, end_tran, NULL, NULL, NULL, napi_default, NULL},
1126
1247
  {"endSavepoint", NULL, end_savepoint, NULL, NULL, NULL, napi_default, NULL},
1248
+ {"transactionActive", NULL, transaction_active, NULL, NULL, NULL, napi_default, NULL},
1127
1249
  {"getInfo", NULL, get_info, NULL, NULL, NULL, napi_default, NULL},
1128
1250
  {"descField", NULL, desc_field, NULL, NULL, NULL, napi_default, NULL},
1129
1251
  {"execDirect", NULL, exec_direct, NULL, NULL, NULL, napi_default, NULL},