vsql-node 1.2.1 → 1.2.8

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
@@ -55,11 +55,17 @@ The `length` of a column is the maximum length of a `CHARACTER` or
55
55
  `CHARACTER VARYING` (in characters) or a `BINARY` or `BINARY VARYING` (in
56
56
  octets). The `precision` and `scale` are those of a `DECIMAL` or `NUMERIC` (or
57
57
  the `precision` of a `DECFLOAT`), or the leading field precision and fractional
58
- seconds precision of an interval. The others are `null`. When vsql knows the key
58
+ seconds precision of an interval. The `precision` of a `TIME` or `TIMESTAMP`
59
+ (with or without a time zone) is its fractional seconds precision (6 for a
60
+ `TIMESTAMP` and 0 for a `TIME`, unless it's given). The others are `null`. When vsql knows the key
59
61
  of the rows (such as when they're all the columns of a `PRIMARY KEY`), each of
60
62
  its columns has a `key` of `"PRIMARY"` (or `"PREFERRED"` for a key that isn't
61
63
  the primary key, such as a `UNIQUE NOT NULL` column).
62
64
 
65
+ The columns are checked each time a statement is executed, so a prepared
66
+ statement follows a table that was replaced or altered after it was prepared
67
+ (the rows and `stmt.columns()` have the new names and types).
68
+
63
69
  `stmt.parameters()` describes each `?` with the type that vsql works out from
64
70
  where it's used (such as the type of `x` in `x = ?`):
65
71
 
@@ -118,11 +124,29 @@ db.transaction(() => {
118
124
  }); // commits 1 and 3
119
125
  ```
120
126
 
127
+ `fn` can't call `db.commit()` or `db.rollback()` (they throw a `TypeError`, like
128
+ in better-sqlite3), since `db.transaction(fn)` ends the transaction (or the
129
+ savepoint) itself.
130
+
121
131
  Ending a transaction closes the rows of its queries, which finishes their
122
132
  iterators. `START TRANSACTION`, `COMMIT` and `ROLLBACK` can't be executed as
123
- statements. `SAVEPOINT` and `RELEASE SAVEPOINT` can, and `db.rollback(name)`
124
- rolls back to a savepoint (the name is an identifier, like in SQL, so `'a'` is
125
- `A` and `'"a"'` is `a`).
133
+ statements.
134
+
135
+ In a transaction, `db.savepoint(name)` makes a savepoint, `db.rollback(name)`
136
+ rolls back what came after it (and the transaction carries on), and
137
+ `db.release(name)` releases it (and the savepoints after it), keeping what came
138
+ after it. The name is an identifier, like in SQL, so `'a'` is `A` and `'"a"'` is
139
+ `a`. They throw a `TypeError` if there's no transaction:
140
+
141
+ ```js
142
+ db.begin();
143
+ insert.run([1]);
144
+ db.savepoint('a');
145
+ insert.run([2]);
146
+ db.rollback('a');
147
+ db.release('a');
148
+ db.commit(); // commits 1
149
+ ```
126
150
 
127
151
  `db.begin(options)` and `db.transaction(fn, options)` take `readOnly` (`false`
128
152
  by default) and `isolationLevel` (`"READ COMMITTED"` by default, or
@@ -162,6 +186,9 @@ be a parameter for any type that isn't binary, in vsql's format (such as
162
186
  `INTERVAL YEAR TO MONTH`). A binary string can only be a `Buffer` (or another
163
187
  view), and a `Buffer` can only be a binary string.
164
188
 
189
+ A string with a lone surrogate (such as `"\uD800"`) is a `RangeError`, because
190
+ it can't be converted to UTF-8 (see `String.prototype.isWellFormed`).
191
+
165
192
  `vsql.numeric` (from a string such as `"-12.50"`, a number or a bigint),
166
193
  `vsql.date` (`"YYYY-MM-DD"`), `vsql.time` (`"HH:MM:SS"`) and `vsql.timestamp`
167
194
  (`"YYYY-MM-DD HH:MM:SS"`) send a value as that type instead, and take the
@@ -239,9 +266,37 @@ try {
239
266
  }
240
267
  ```
241
268
 
269
+ `diagnostics` are the other conditions that vsql raised with the error, each an
270
+ object of `sqlstate`, `message` and the same fields (it's usually empty):
271
+
272
+ ```js
273
+ try {
274
+ db.all('SELECT SUM(x) / 0 FROM t');
275
+ } catch (e) {
276
+ console.log(e.sqlstate, e.diagnostics); // 22012 [{ sqlstate: '01003', message: 'null value eliminated in set function' }]
277
+ }
278
+ ```
279
+
242
280
  An error from the driver itself (such as using a closed connection, or a value
243
281
  that can't be a parameter) is a `TypeError` or `RangeError`.
244
282
 
283
+ ### Warnings
284
+
285
+ A statement that succeeds with a warning from vsql (such as `01003` when a
286
+ `NULL` is eliminated from `SUM`, or `01004` when a string is truncated) gives a
287
+ `vsql.VsqlWarning` to `process.emitWarning`, which is how Node reports problems
288
+ that shouldn't stop the program. It has the same fields as a `VsqlError`. Node
289
+ prints warnings to stderr, unless they're handled with `process.on('warning')`
290
+ or Node is run with `--no-warnings` (or `--disable-warning=VsqlWarning`):
291
+
292
+ ```js
293
+ process.on('warning', (w) => {
294
+ if (w instanceof vsql.VsqlWarning) {
295
+ console.log(w.sqlstate, w.message); // 01003 null value eliminated in set function (SQLSTATE 01003)
296
+ }
297
+ });
298
+ ```
299
+
245
300
  ## Threads
246
301
 
247
302
  Each connection has its own libvsql environment, so connections in different
@@ -288,5 +343,5 @@ which has all of libvsql's C in one `libvsql.c`.
288
343
  ### Releasing
289
344
 
290
345
  Publishing a GitHub release (with a tag such as `v1.2.3`) publishes the
291
- package to npm, with the prebuilds from
292
- [release.yml](.github/workflows/release.yml).
346
+ package to npm ([release.yml](.github/workflows/release.yml)), with the
347
+ prebuilds from [test.yml](.github/workflows/test.yml).
package/index.d.ts CHANGED
@@ -43,8 +43,9 @@ export interface TypeInfo {
43
43
  */
44
44
  length: number | null;
45
45
  /**
46
- * The precision of a DECIMAL, NUMERIC or DECFLOAT, or the leading field
47
- * precision of an interval.
46
+ * The precision of a DECIMAL, NUMERIC or DECFLOAT, the fractional seconds
47
+ * precision of a TIME or TIMESTAMP (with or without a time zone), or the
48
+ * leading field precision of an interval.
48
49
  */
49
50
  precision: number | null;
50
51
  /**
@@ -151,10 +152,21 @@ export class Connection {
151
152
  * (an identifier, like in SQL), it only rolls back to that savepoint.
152
153
  */
153
154
  rollback(savepoint?: string): void;
155
+ /**
156
+ * Makes a savepoint in the transaction. The name is an identifier, like in
157
+ * SQL. It throws a TypeError if there's no transaction.
158
+ */
159
+ savepoint(name: string): void;
160
+ /**
161
+ * Releases a savepoint (and the savepoints after it), keeping what came
162
+ * after it. It throws a TypeError if there's no transaction.
163
+ */
164
+ release(name: string): void;
154
165
  /**
155
166
  * Calls fn in a transaction, which is committed when it returns (and its
156
167
  * value is returned), or rolled back if it throws. In another transaction,
157
- * it's a savepoint instead (and it can't have options).
168
+ * 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.
158
170
  */
159
171
  transaction<T>(fn: () => T, options?: TransactionOptions): T;
160
172
 
@@ -174,6 +186,7 @@ export class Statement<R = Row> {
174
186
  /** Whether the statement returns rows (certain once it's executed). */
175
187
  readonly reader: boolean;
176
188
 
189
+ /** Describes each column, as of the last execution (or when prepared). */
177
190
  columns(): Column[];
178
191
  /** Describes each parameter ("?"), from where it's used. */
179
192
  parameters(): ParameterInfo[];
@@ -212,9 +225,49 @@ export class VsqlError extends Error {
212
225
  readonly cursorName?: string;
213
226
  /** Whether vsql raised more conditions than it kept. */
214
227
  readonly more: boolean;
228
+ /** The other conditions that vsql raised with the error (usually none). */
229
+ readonly diagnostics: Diagnostic[];
230
+ }
231
+
232
+ /** A condition that vsql raised with an error. */
233
+ export interface Diagnostic {
234
+ /** The SQLSTATE, such as "01003". */
235
+ readonly sqlstate: string;
236
+ readonly message: string;
237
+ readonly constraintCatalog?: string;
238
+ readonly constraintSchema?: string;
239
+ readonly constraintName?: string;
240
+ readonly catalogName?: string;
241
+ readonly schemaName?: string;
242
+ readonly tableName?: string;
243
+ readonly columnName?: string;
244
+ readonly cursorName?: string;
245
+ }
246
+
247
+ /**
248
+ * A warning from vsql (such as "01003" when a NULL is eliminated from SUM),
249
+ * which is given to process.emitWarning.
250
+ */
251
+ export class VsqlWarning extends Error {
252
+ readonly name: 'VsqlWarning';
253
+ /** The SQLSTATE, such as "01003". */
254
+ readonly sqlstate: string;
255
+ /** The same as sqlstate. */
256
+ readonly code: string;
257
+ readonly constraintCatalog?: string;
258
+ readonly constraintSchema?: string;
259
+ readonly constraintName?: string;
260
+ readonly catalogName?: string;
261
+ readonly schemaName?: string;
262
+ readonly tableName?: string;
263
+ readonly columnName?: string;
264
+ readonly cursorName?: string;
215
265
  }
216
266
 
217
- /** A parameter that's sent as a particular SQL type. */
267
+ /**
268
+ * A parameter that's sent as a particular SQL type, made by numeric, date, time
269
+ * or timestamp (the constructor throws a TypeError).
270
+ */
218
271
  export class SqlValue {
219
272
  private constructor();
220
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,6 +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).
101
+ this._inFn = false;
102
+
99
103
  const env = lib.allocHandle(lib.SQL_HANDLE_ENV, lib.SQL_NULL_HANDLE);
100
104
  let dbc;
101
105
  try {
@@ -229,30 +233,65 @@ class Connection {
229
233
 
230
234
  // commit commits the transaction, if there is one.
231
235
  commit() {
236
+ this._checkNotInFn('commit');
232
237
  this._end(true);
233
238
  }
234
239
 
240
+ _checkNotInFn(name) {
241
+ if (this._inFn) {
242
+ throw new TypeError(`${name}() can't be called in the function of transaction()`);
243
+ }
244
+ }
245
+
235
246
  // rollback rolls back the transaction, if there is one. With the name of a
236
- // savepoint (made with SAVEPOINT), it only rolls back what came after it,
237
- // and the transaction continues. The name is an identifier, like it is in
238
- // SQL (so "sp" is SP, and '"sp"' is sp).
247
+ // savepoint (see savepoint), it only rolls back what came after it, and the
248
+ // transaction continues.
239
249
  rollback(savepoint) {
240
250
  if (savepoint === undefined) {
251
+ this._checkNotInFn('rollback');
241
252
  this._end(false);
242
253
  return;
243
254
  }
244
255
 
256
+ this._checkSavepoint(savepoint);
257
+ lib.endSavepoint(this._state.dbc, savepoint, false);
258
+ }
259
+
260
+ // savepoint makes a savepoint in the transaction, which can be rolled back
261
+ // to (see rollback) or released. The name is an identifier, like it is in
262
+ // SQL (so "sp" is SP, and '"sp"' is sp). A savepoint with the same name
263
+ // replaces it.
264
+ savepoint(name) {
265
+ this._checkSavepoint(name);
266
+ this.run(`SAVEPOINT ${name}`);
267
+ }
268
+
269
+ // release releases a savepoint, and the savepoints after it, keeping what
270
+ // came after them in the transaction.
271
+ release(name) {
272
+ this._checkSavepoint(name);
273
+ lib.endSavepoint(this._state.dbc, name, true);
274
+ }
275
+
276
+ // _checkSavepoint checks the name of a savepoint, and that there's a
277
+ // transaction (vsql accepts SAVEPOINT without one, but it does nothing
278
+ // useful, since each statement is committed on its own).
279
+ _checkSavepoint(name) {
245
280
  this._check();
246
- if (typeof savepoint !== 'string') {
281
+ if (typeof name !== 'string') {
247
282
  throw new TypeError('the savepoint must be a string');
248
283
  }
249
- lib.endSavepoint(this._state.dbc, savepoint, false);
284
+ if (!this._state.inTransaction) {
285
+ throw new TypeError('there is no transaction');
286
+ }
250
287
  }
251
288
 
252
289
  // transaction calls fn in a transaction, which is committed when it returns
253
290
  // (and its value is returned), or rolled back if it throws. In another
254
291
  // transaction, it uses a savepoint instead, which is released when fn
255
292
  // returns, or rolled back to if it throws, so only what fn did is undone.
293
+ // fn can't call commit or rollback (without a savepoint), since then it
294
+ // wouldn't be clear what was committed (like better-sqlite3).
256
295
  transaction(fn, options) {
257
296
  if (this._state.inTransaction) {
258
297
  if (options !== undefined) {
@@ -263,28 +302,33 @@ class Connection {
263
302
 
264
303
  this.begin(options);
265
304
  let result;
305
+ this._inFn = true;
266
306
  try {
267
307
  result = call(fn);
268
308
  } catch (e) {
269
309
  if (this._state.open) {
270
- this.rollback();
310
+ this._end(false);
271
311
  }
272
312
  throw e;
313
+ } finally {
314
+ this._inFn = false;
273
315
  }
274
- this.commit();
316
+ this._end(true);
275
317
 
276
318
  return result;
277
319
  }
278
320
 
279
321
  _nested(fn) {
280
322
  const name = `VSQL_NODE_${++this._savepoints}`;
323
+ const inFn = this._inFn;
281
324
  try {
282
325
  this.run(`SAVEPOINT ${name}`);
326
+ this._inFn = true;
283
327
  let result;
284
328
  try {
285
329
  result = call(fn);
286
330
  } catch (e) {
287
- // The transaction may have been ended by fn.
331
+ // fn may have closed the connection.
288
332
  if (this._state.open && this._state.inTransaction) {
289
333
  lib.endSavepoint(this._state.dbc, name, false);
290
334
  lib.endSavepoint(this._state.dbc, name, true);
@@ -295,6 +339,7 @@ class Connection {
295
339
 
296
340
  return result;
297
341
  } finally {
342
+ this._inFn = inFn;
298
343
  this._savepoints--;
299
344
  }
300
345
  }
@@ -375,10 +420,9 @@ class Statement {
375
420
  statements.register(this, { state: this._state, stmt: this._stmt }, this);
376
421
  }
377
422
 
378
- // _describe reads the columns of the statement (if it's a query). n is given
379
- // again after each execution, in case the columns aren't the same as when it
380
- // was prepared.
423
+ // _describe reads the columns of the statement (if it's a query).
381
424
  _describe(n = lib.numResultCols(this._stmt)) {
425
+ this._described = [];
382
426
  this._columns = [];
383
427
  this._names = [];
384
428
  this._kinds = '';
@@ -386,7 +430,9 @@ class Statement {
386
430
  // The columns of the key of the rows (if vsql knows it) have a KEY_MEMBER.
387
431
  const keyType = n > 0 ? this._ird(0, lib.SQL_DESC_KEY_TYPE) : null;
388
432
  for (let i = 1; i <= n; i++) {
389
- const [name, dataType, size, digits, nullable] = lib.describeCol(this._stmt, i);
433
+ const described = lib.describeCol(this._stmt, i);
434
+ this._described.push(described);
435
+ const [name, dataType, size, digits, nullable] = described;
390
436
  const [type, kind, converter] = types.get(dataType) ?? ['', 's', null];
391
437
  const c = column(name, type, size, digits, nullable,
392
438
  this._ird(i, lib.SQL_DESC_DATETIME_INTERVAL_PRECISION));
@@ -401,6 +447,29 @@ class Statement {
401
447
  }
402
448
  }
403
449
 
450
+ // _changed is true if the columns aren't the same as when they were last
451
+ // described. A table can be replaced (or altered) after the statement was
452
+ // prepared, giving columns with the same count but other names or types.
453
+ // Comparing what describeCol gives is about a third of the work of
454
+ // _describe (which also reads the descriptor fields of each column).
455
+ _changed() {
456
+ const n = lib.numResultCols(this._stmt);
457
+ if (n !== this._described.length) {
458
+ return true;
459
+ }
460
+ for (let i = 0; i < n; i++) {
461
+ const was = this._described[i];
462
+ const now = lib.describeCol(this._stmt, i + 1);
463
+ for (let j = 0; j < now.length; j++) {
464
+ if (now[j] !== was[j]) {
465
+ return true;
466
+ }
467
+ }
468
+ }
469
+
470
+ return false;
471
+ }
472
+
404
473
  // reader is true if the statement returns rows (such as a SELECT). It's
405
474
  // only certain once the statement has been executed.
406
475
  get reader() {
@@ -448,7 +517,7 @@ class Statement {
448
517
  } else if (type === 'DECIMAL' || type === 'NUMERIC') {
449
518
  p.precision = ipd(i, lib.SQL_DESC_PRECISION);
450
519
  p.scale = ipd(i, lib.SQL_DESC_SCALE);
451
- } else if (type === 'DECFLOAT') {
520
+ } else if (type === 'DECFLOAT' || datetimes.has(type)) {
452
521
  p.precision = ipd(i, lib.SQL_DESC_PRECISION);
453
522
  } else if (type?.startsWith('INTERVAL ')) {
454
523
  p.precision = ipd(i, lib.SQL_DESC_DATETIME_INTERVAL_PRECISION);
@@ -493,9 +562,8 @@ class Statement {
493
562
  this._closeCursor();
494
563
  this._execution++;
495
564
  lib.execute(this._stmt, values);
496
- const n = lib.numResultCols(this._stmt);
497
- if (n !== this._columns.length) {
498
- this._describe(n);
565
+ if (this._changed()) {
566
+ this._describe();
499
567
  }
500
568
  if (this.reader) {
501
569
  this._open = true;
@@ -624,14 +692,19 @@ class Statement {
624
692
  }
625
693
  }
626
694
 
695
+ // The types that have a fractional seconds precision (such as TIMESTAMP(3)),
696
+ // which is their precision.
697
+ const datetimes = new Set(['TIME', 'TIME WITH TIME ZONE', 'TIMESTAMP', 'TIMESTAMP WITH TIME ZONE']);
698
+
627
699
  // The key that a column is part of, from KEY_TYPE.
628
700
  const keyTypes = { 1: 'PRIMARY', 2: 'PREFERRED' };
629
701
 
630
702
  // column describes a column: its name and type, whether it can be NULL, the
631
703
  // maximum length of a CHARACTER, CHARACTER VARYING, BINARY or BINARY VARYING,
632
704
  // the precision and scale of a DECIMAL or NUMERIC (or the precision of a
633
- // DECFLOAT), and the leading field precision and fractional seconds precision
634
- // of an interval (the others are null). key is the key of the rows that the
705
+ // DECFLOAT), the fractional seconds precision of a TIME or TIMESTAMP (with or
706
+ // without a time zone), and the leading field precision and fractional seconds
707
+ // precision of an interval (the others are null). key is the key of the rows that the
635
708
  // column is part of ("PRIMARY" or "PREFERRED"), if vsql knows it.
636
709
  function column(name, type, size, digits, nullable, intervalPrecision) {
637
710
  let length = null;
@@ -647,6 +720,10 @@ function column(name, type, size, digits, nullable, intervalPrecision) {
647
720
  scale = digits;
648
721
  } else if (type === 'DECFLOAT') {
649
722
  precision = size;
723
+ } else if (datetimes.has(type)) {
724
+ // The fractional seconds precision is the decimal digits (the size is the
725
+ // length of the literal).
726
+ precision = digits;
650
727
  } else if (type?.startsWith('INTERVAL ')) {
651
728
  precision = intervalPrecision;
652
729
  scale = type.endsWith('SECOND') ? digits : null;
package/lib/convert.js CHANGED
@@ -8,12 +8,21 @@ const lib = require('./binding');
8
8
  const BIGINT_MIN = -(2n ** 63n);
9
9
  const BIGINT_MAX = 2n ** 63n - 1n;
10
10
 
11
+ // sqlValueToken is given to the constructor of SqlValue by sqlValue, which is
12
+ // only called by numeric, date, time and timestamp (after they check the
13
+ // value). SqlValue is exported (for instanceof), but can't be constructed
14
+ // without it.
15
+ const sqlValueToken = Symbol('SqlValue');
16
+
11
17
  // SqlValue is a parameter that's sent as a particular SQL type, from numeric,
12
18
  // date, time or timestamp. A string is cast to the type of the parameter
13
19
  // (which vsql works out from where it's used), so these are only needed to send
14
20
  // a value as a particular type.
15
21
  class SqlValue {
16
- constructor(type, parameterType, columnSize, decimalDigits, value) {
22
+ constructor(token, type, parameterType, columnSize, decimalDigits, value) {
23
+ if (token !== sqlValueToken) {
24
+ throw new TypeError('SqlValue can only be made by numeric, date, time or timestamp');
25
+ }
17
26
  this.type = type;
18
27
  this.value = value;
19
28
  this.param = [lib.SQL_CHAR, parameterType, columnSize, decimalDigits, value];
@@ -25,6 +34,10 @@ class SqlValue {
25
34
  }
26
35
  }
27
36
 
37
+ function sqlValue(type, parameterType, columnSize, decimalDigits, value) {
38
+ return new SqlValue(sqlValueToken, type, parameterType, columnSize, decimalDigits, value);
39
+ }
40
+
28
41
  const numericRe = /^([+-]?)(\d*)(?:\.(\d*))?$/;
29
42
 
30
43
  // numeric is a NUMERIC with the precision and scale of its digits, from a
@@ -44,7 +57,7 @@ function numeric(value) {
44
57
  const fraction = m[3] || '';
45
58
  const precision = (integer.replace(/^0+/, '').length || 1) + fraction.length;
46
59
 
47
- return new SqlValue('NUMERIC', lib.SQL_NUMERIC, precision, fraction.length,
60
+ return sqlValue('NUMERIC', lib.SQL_NUMERIC, precision, fraction.length,
48
61
  sign + integer + (fraction && `.${fraction}`));
49
62
  }
50
63
 
@@ -75,7 +88,7 @@ function offset(s) {
75
88
  function date(s) {
76
89
  checkString('DATE', s, dateRe);
77
90
 
78
- return new SqlValue('DATE', lib.SQL_TYPE_DATE, s.length, 0, s);
91
+ return sqlValue('DATE', lib.SQL_TYPE_DATE, s.length, 0, s);
79
92
  }
80
93
 
81
94
  // time is a TIME, from "HH:MM:SS" with up to 6 fractional digits. It's WITH
@@ -84,11 +97,11 @@ function time(s) {
84
97
  const [, hms, fraction = '', zone] = checkString('TIME', s, timeRe);
85
98
  const value = hms + (fraction && `.${fraction}`);
86
99
  if (zone === undefined) {
87
- return new SqlValue('TIME', lib.SQL_TYPE_TIME, value.length, fraction.length, value);
100
+ return sqlValue('TIME', lib.SQL_TYPE_TIME, value.length, fraction.length, value);
88
101
  }
89
102
 
90
103
  const withZone = value + offset(zone);
91
- return new SqlValue('TIME WITH TIME ZONE', lib.SQL_TYPE_TIME_WITH_TIMEZONE, withZone.length,
104
+ return sqlValue('TIME WITH TIME ZONE', lib.SQL_TYPE_TIME_WITH_TIMEZONE, withZone.length,
92
105
  fraction.length, withZone);
93
106
  }
94
107
 
@@ -99,11 +112,11 @@ function timestamp(s) {
99
112
  const [, ymd, hms, fraction = '', zone] = checkString('TIMESTAMP', s, timestampRe);
100
113
  const value = `${ymd} ${hms}${fraction && `.${fraction}`}`;
101
114
  if (zone === undefined) {
102
- return new SqlValue('TIMESTAMP', lib.SQL_TYPE_TIMESTAMP, value.length, fraction.length, value);
115
+ return sqlValue('TIMESTAMP', lib.SQL_TYPE_TIMESTAMP, value.length, fraction.length, value);
103
116
  }
104
117
 
105
118
  const withZone = value + offset(zone);
106
- return new SqlValue('TIMESTAMP WITH TIME ZONE', lib.SQL_TYPE_TIMESTAMP_WITH_TIMEZONE,
119
+ return sqlValue('TIMESTAMP WITH TIME ZONE', lib.SQL_TYPE_TIMESTAMP_WITH_TIMEZONE,
107
120
  withZone.length, fraction.length, withZone);
108
121
  }
109
122
 
@@ -159,6 +172,11 @@ function toParam(value) {
159
172
  return numeric(value).param;
160
173
 
161
174
  case 'string':
175
+ // A lone surrogate can't be converted to UTF-8 (it would be replaced
176
+ // with U+FFFD), so a different string would be stored.
177
+ if (!value.isWellFormed()) {
178
+ throw new RangeError('a string has a lone surrogate');
179
+ }
162
180
  return [lib.SQL_CHAR, lib.SQL_VARCHAR, 0, 0, value];
163
181
 
164
182
  default:
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.1",
3
+ "version": "1.2.8",
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,13 +46,53 @@ 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
- // NAPI_CALL returns NULL from the function if a Node-API call fails, which
50
- // has thrown an exception.
52
+ // throw_napi_error throws an error for the Node-API call that just failed, unless
53
+ // it threw an exception itself. Most calls (such as napi_get_value_int32) only
54
+ // return a status, and returning without an exception would be undefined in
55
+ // JavaScript, as if the function worked.
56
+ static void throw_napi_error(napi_env env) {
57
+ // The error info is only valid until the next Node-API call. Its message is
58
+ // a constant, so it's still valid after that.
59
+ const napi_extended_error_info *error = NULL;
60
+ const char *message = "Node-API call failed";
61
+ napi_status status = napi_generic_failure;
62
+ if (napi_get_last_error_info(env, &error) == napi_ok && error != NULL) {
63
+ status = error->error_code;
64
+ if (error->error_message != NULL) {
65
+ message = error->error_message;
66
+ }
67
+ }
68
+
69
+ bool pending = false;
70
+ if (napi_is_exception_pending(env, &pending) != napi_ok || pending) {
71
+ return;
72
+ }
73
+
74
+ // An argument of the wrong type (such as a number that's a string).
75
+ switch (status) {
76
+ case napi_invalid_arg:
77
+ case napi_object_expected:
78
+ case napi_string_expected:
79
+ case napi_number_expected:
80
+ case napi_boolean_expected:
81
+ case napi_array_expected:
82
+ case napi_bigint_expected:
83
+ napi_throw_type_error(env, NULL, message);
84
+ return;
85
+ default:
86
+ napi_throw_error(env, NULL, message);
87
+ }
88
+ }
89
+
90
+ // NAPI_CALL throws an error (see throw_napi_error) and returns NULL from the
91
+ // function if a Node-API call fails.
51
92
  #define NAPI_CALL(call) \
52
93
  do { \
53
94
  if ((call) != napi_ok) { \
95
+ throw_napi_error(env); \
54
96
  return NULL; \
55
97
  } \
56
98
  } while (0)
@@ -70,6 +112,7 @@ static void throw_error_fields(napi_env env, const char *sqlstate, const char *m
70
112
 
71
113
  napi_value args[3], global, err;
72
114
  if (fields == NULL && napi_get_undefined(env, &fields) != napi_ok) {
115
+ throw_napi_error(env);
73
116
  return;
74
117
  }
75
118
  args[2] = fields;
@@ -77,6 +120,7 @@ static void throw_error_fields(napi_env env, const char *sqlstate, const char *m
77
120
  napi_create_string_utf8(env, message, length, &args[1]) != napi_ok ||
78
121
  napi_get_global(env, &global) != napi_ok ||
79
122
  napi_call_function(env, global, factory, 3, args, &err) != napi_ok) {
123
+ throw_napi_error(env);
80
124
  return;
81
125
  }
82
126
  napi_throw(env, err);
@@ -103,10 +147,11 @@ static const struct {
103
147
  {NULL, 0},
104
148
  };
105
149
 
106
- // get_diag_fields is an object of the diagnostic fields of the first record
107
- // (see diag_fields), and "more" (SQL_DIAG_MORE) if a condition was dropped.
108
- // It's NULL if the fields can't be read.
109
- 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) {
110
155
  napi_value result, value;
111
156
  if (napi_create_object(env, &result) != napi_ok) {
112
157
  return NULL;
@@ -116,7 +161,7 @@ static napi_value get_diag_fields(napi_env env, SQLSMALLINT handle_type, SQLINTE
116
161
  SQLCHAR buf[4 * 128 + 1];
117
162
  for (int i = 0; diag_fields[i].name != NULL; i++) {
118
163
  SQLSMALLINT length = 0;
119
- 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,
120
165
  sizeof(buf), &length);
121
166
  if ((rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO) || length <= 0) {
122
167
  continue;
@@ -132,7 +177,7 @@ static napi_value get_diag_fields(napi_env env, SQLSMALLINT handle_type, SQLINTE
132
177
 
133
178
  SQLINTEGER more = 0;
134
179
  SQLRETURN rc = SQLGetDiagField(handle_type, handle, 0, SQL_DIAG_MORE, &more, 0, NULL);
135
- if ((rc == SQL_SUCCESS || rc == SQL_SUCCESS_WITH_INFO) && more) {
180
+ if (record == 1 && (rc == SQL_SUCCESS || rc == SQL_SUCCESS_WITH_INFO) && more) {
136
181
  if (napi_get_boolean(env, true, &value) != napi_ok ||
137
182
  napi_set_named_property(env, result, "more", value) != napi_ok) {
138
183
  return NULL;
@@ -142,49 +187,141 @@ static napi_value get_diag_fields(napi_env env, SQLSMALLINT handle_type, SQLINTE
142
187
  return result;
143
188
  }
144
189
 
145
- // check returns 0 for a return code that isn't an error (SQL_NO_DATA isn't),
146
- // otherwise it throws the error from the diagnostics of the handle and returns
147
- // -1.
148
- static int check(napi_env env, SQLRETURN rc, SQLSMALLINT handle_type, SQLINTEGER handle) {
149
- switch (rc) {
150
- case SQL_SUCCESS:
151
- case SQL_SUCCESS_WITH_INFO:
152
- case SQL_NO_DATA:
153
- return 0;
154
- case SQL_INVALID_HANDLE:
155
- throw_error(env, "HY000", "invalid handle", NAPI_AUTO_LENGTH);
156
- return -1;
157
- }
158
-
159
- SQLCHAR sqlstate[6];
160
- SQLSMALLINT size = 512, length = 0;
161
- 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;
162
196
  for (;;) {
163
- if (message == NULL) {
164
- napi_throw_error(env, NULL, "out of memory");
165
- return -1;
197
+ *message = malloc(size);
198
+ if (*message == NULL) {
199
+ return -2;
166
200
  }
167
201
 
168
- 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);
169
204
  if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO) {
170
- free(message);
171
- throw_error(env, "HY000", "unknown error", NAPI_AUTO_LENGTH);
205
+ free(*message);
206
+ *message = NULL;
172
207
  return -1;
173
208
  }
174
209
 
175
210
  // The message was truncated.
176
- if (length >= size) {
177
- size = length + 1;
178
- free(message);
179
- message = malloc(size);
211
+ if (*length >= size) {
212
+ size = *length + 1;
213
+ free(*message);
180
214
  continue;
181
215
  }
182
216
 
183
- napi_value fields = get_diag_fields(env, handle_type, handle);
184
- 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);
185
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);
186
298
  return -1;
187
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");
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);
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);
188
325
  }
189
326
 
190
327
  // CHECK returns NULL from the function if a libvsql routine fails.
@@ -199,6 +336,7 @@ static int check(napi_env env, SQLRETURN rc, SQLSMALLINT handle_type, SQLINTEGER
199
336
  static int args(napi_env env, napi_callback_info info, size_t n, napi_value *argv) {
200
337
  size_t argc = n;
201
338
  if (napi_get_cb_info(env, info, &argc, argv, NULL, NULL) != napi_ok) {
339
+ throw_napi_error(env);
202
340
  return -1;
203
341
  }
204
342
  if (argc < n) {
@@ -220,6 +358,7 @@ static int args(napi_env env, napi_callback_info info, size_t n, napi_value *arg
220
358
  // or NULL if it isn't a string (which has thrown an exception).
221
359
  static char *get_string(napi_env env, napi_value value, size_t *length) {
222
360
  if (napi_get_value_string_utf8(env, value, NULL, 0, length) != napi_ok) {
361
+ throw_napi_error(env);
223
362
  return NULL;
224
363
  }
225
364
 
@@ -229,6 +368,7 @@ static char *get_string(napi_env env, napi_value value, size_t *length) {
229
368
  return NULL;
230
369
  }
231
370
  if (napi_get_value_string_utf8(env, value, s, *length + 1, length) != napi_ok) {
371
+ throw_napi_error(env);
232
372
  free(s);
233
373
  return NULL;
234
374
  }
@@ -248,16 +388,22 @@ static napi_value number(napi_env env, double n) {
248
388
  return result;
249
389
  }
250
390
 
251
- // setErrorFactory(factory)
391
+ // setErrorFactory(factory, warn) sets the function that makes errors, and the
392
+ // function that's called with the records of warnings.
252
393
  static napi_value set_error_factory(napi_env env, napi_callback_info info) {
253
- ARGS(1);
394
+ ARGS(2);
254
395
  instance *inst = NULL;
255
396
  NAPI_CALL(napi_get_instance_data(env, (void **)&inst));
256
397
  if (inst->error_factory != NULL) {
257
398
  napi_delete_reference(env, inst->error_factory);
258
399
  inst->error_factory = NULL;
259
400
  }
401
+ if (inst->warn != NULL) {
402
+ napi_delete_reference(env, inst->warn);
403
+ inst->warn = NULL;
404
+ }
260
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));
261
407
 
262
408
  return undefined(env);
263
409
  }
@@ -526,6 +672,7 @@ static int bind_param(napi_env env, SQLINTEGER stmt, SQLSMALLINT n, napi_value a
526
672
  napi_value fields[5];
527
673
  for (uint32_t i = 0; i < 5; i++) {
528
674
  if (napi_get_element(env, array, i, &fields[i]) != napi_ok) {
675
+ throw_napi_error(env);
529
676
  return -1;
530
677
  }
531
678
  }
@@ -535,11 +682,13 @@ static int bind_param(napi_env env, SQLINTEGER stmt, SQLSMALLINT n, napi_value a
535
682
  napi_get_value_int32(env, fields[1], &parameter_type) != napi_ok ||
536
683
  napi_get_value_int32(env, fields[2], &column_size) != napi_ok ||
537
684
  napi_get_value_int32(env, fields[3], &decimal_digits) != napi_ok) {
685
+ throw_napi_error(env);
538
686
  return -1;
539
687
  }
540
688
 
541
689
  napi_valuetype type;
542
690
  if (napi_typeof(env, fields[4], &type) != napi_ok) {
691
+ throw_napi_error(env);
543
692
  return -1;
544
693
  }
545
694
 
@@ -551,15 +700,18 @@ static int bind_param(napi_env env, SQLINTEGER stmt, SQLSMALLINT n, napi_value a
551
700
  if (type == napi_bigint) {
552
701
  bool lossless;
553
702
  if (napi_get_value_bigint_int64(env, fields[4], &p->i, &lossless) != napi_ok) {
703
+ throw_napi_error(env);
554
704
  return -1;
555
705
  }
556
706
  } else if (napi_get_value_int64(env, fields[4], &p->i) != napi_ok) {
707
+ throw_napi_error(env);
557
708
  return -1;
558
709
  }
559
710
  pointer = &p->i;
560
711
  buffer_length = sizeof(SQLBIGINT);
561
712
  } else if (value_type == SQL_DOUBLE) {
562
713
  if (napi_get_value_double(env, fields[4], &p->d) != napi_ok) {
714
+ throw_napi_error(env);
563
715
  return -1;
564
716
  }
565
717
  pointer = &p->d;
@@ -572,6 +724,7 @@ static int bind_param(napi_env env, SQLINTEGER stmt, SQLSMALLINT n, napi_value a
572
724
  void *data;
573
725
  if (napi_get_typedarray_info(env, fields[4], &array_type, &length, &data, NULL, NULL) !=
574
726
  napi_ok) {
727
+ throw_napi_error(env);
575
728
  return -1;
576
729
  }
577
730
  if (column_size == 0) {
@@ -625,8 +778,11 @@ static napi_value execute(napi_env env, napi_callback_info info) {
625
778
  napi_value result = NULL;
626
779
  for (uint32_t i = 0; i < n; i++) {
627
780
  napi_value array;
628
- if (napi_get_element(env, argv[1], i, &array) != napi_ok ||
629
- bind_param(env, stmt, (SQLSMALLINT)(i + 1), array, &params[i]) < 0) {
781
+ if (napi_get_element(env, argv[1], i, &array) != napi_ok) {
782
+ throw_napi_error(env);
783
+ goto done;
784
+ }
785
+ if (bind_param(env, stmt, (SQLSMALLINT)(i + 1), array, &params[i]) < 0) {
630
786
  goto done;
631
787
  }
632
788
  }
@@ -689,7 +845,7 @@ static napi_value describe_col(napi_env env, napi_callback_info info) {
689
845
 
690
846
  SQLRETURN rc = SQLDescribeCol(stmt, (SQLSMALLINT)n, name, size, &length, &data_type,
691
847
  &column_size, &decimal_digits, &nullable);
692
- if (check(env, rc, SQL_HANDLE_STMT, stmt) < 0) {
848
+ if (check_warn(env, rc, SQL_HANDLE_STMT, stmt, 0) < 0) {
693
849
  free(name);
694
850
  return NULL;
695
851
  }
@@ -738,7 +894,7 @@ static napi_value get_chars(napi_env env, SQLINTEGER stmt, SQLSMALLINT n) {
738
894
  size_t length = 0;
739
895
  for (;;) {
740
896
  SQLRETURN rc = SQLGetData(stmt, n, SQL_CHAR, buf + length, size - (SQLINTEGER)length, &ind);
741
- if (check(env, rc, SQL_HANDLE_STMT, stmt) < 0) {
897
+ if (check_warn(env, rc, SQL_HANDLE_STMT, stmt, 0) < 0) {
742
898
  free(large);
743
899
  return NULL;
744
900
  }
@@ -749,10 +905,11 @@ static napi_value get_chars(napi_env env, SQLINTEGER stmt, SQLSMALLINT n) {
749
905
  return result;
750
906
  }
751
907
 
752
- // The rest of the string (ind) didn't fit, so the buffer has a null
753
- // terminated piece of it.
908
+ // The rest of the string (ind) didn't fit, so the buffer is full: a piece
909
+ // of it and the null terminator. The size of the piece comes from the size
910
+ // of the buffer, not strlen, because the string can contain U+0000.
754
911
  if (rc == SQL_SUCCESS_WITH_INFO && ind >= size - (SQLINTEGER)length) {
755
- size_t piece = strlen(buf + length);
912
+ size_t piece = (size_t)size - length - 1;
756
913
  size_t new_size = length + piece + (size_t)ind + 1;
757
914
  char *grown = malloc(new_size);
758
915
  if (grown == NULL) {
@@ -786,7 +943,7 @@ static napi_value get_octets(napi_env env, SQLINTEGER stmt, SQLSMALLINT n) {
786
943
  for (;;) {
787
944
  SQLRETURN rc =
788
945
  SQLGetData(stmt, n, SQL_BINARY, buf + length, size - (SQLINTEGER)length, &ind);
789
- if (check(env, rc, SQL_HANDLE_STMT, stmt) < 0) {
946
+ if (check_warn(env, rc, SQL_HANDLE_STMT, stmt, 0) < 0) {
790
947
  free(large);
791
948
  return NULL;
792
949
  }
@@ -884,6 +1041,33 @@ static napi_value get_value(napi_env env, SQLINTEGER stmt, SQLSMALLINT column, c
884
1041
  return result;
885
1042
  }
886
1043
 
1044
+ // fetch_rows fetches the rows for fetch, with the kind of each column.
1045
+ static napi_value fetch_rows(napi_env env, SQLINTEGER stmt, const char *kinds, size_t n,
1046
+ int32_t max) {
1047
+ napi_value rows;
1048
+ NAPI_CALL(napi_create_array(env, &rows));
1049
+ for (uint32_t r = 0; max == 0 || r < (uint32_t)max; r++) {
1050
+ SQLRETURN rc = SQLFetch(stmt);
1051
+ if (rc == SQL_NO_DATA) {
1052
+ break;
1053
+ }
1054
+ CHECK(SQL_HANDLE_STMT, stmt, rc);
1055
+
1056
+ napi_value row;
1057
+ NAPI_CALL(napi_create_array_with_length(env, n, &row));
1058
+ for (size_t i = 0; i < n; i++) {
1059
+ napi_value value = get_value(env, stmt, (SQLSMALLINT)(i + 1), kinds[i]);
1060
+ if (value == NULL) {
1061
+ return NULL;
1062
+ }
1063
+ NAPI_CALL(napi_set_element(env, row, (uint32_t)i, value));
1064
+ }
1065
+ NAPI_CALL(napi_set_element(env, rows, r, row));
1066
+ }
1067
+
1068
+ return rows;
1069
+ }
1070
+
887
1071
  // fetch(stmt, kinds, max) -> rows fetches the next rows (at most max, or all
888
1072
  // of them if max is 0), each as an array. Fewer than max rows means that there
889
1073
  // are no more. kinds has a character for how each column is read:
@@ -903,35 +1087,23 @@ static napi_value fetch(napi_env env, napi_callback_info info) {
903
1087
  int32_t stmt, max;
904
1088
  NAPI_CALL(napi_get_value_int32(env, argv[0], &stmt));
905
1089
  NAPI_CALL(napi_get_value_int32(env, argv[2], &max));
906
- char kinds[1024];
1090
+
1091
+ // A query can have any number of columns, so kinds is allocated.
907
1092
  size_t n;
908
- NAPI_CALL(napi_get_value_string_latin1(env, argv[1], kinds, sizeof(kinds), &n));
909
- if (n >= sizeof(kinds) - 1) {
910
- napi_throw_range_error(env, NULL, "too many columns");
1093
+ NAPI_CALL(napi_get_value_string_latin1(env, argv[1], NULL, 0, &n));
1094
+ char *kinds = malloc(n + 1);
1095
+ if (kinds == NULL) {
1096
+ napi_throw_error(env, NULL, "out of memory");
911
1097
  return NULL;
912
1098
  }
913
-
914
- napi_value rows;
915
- NAPI_CALL(napi_create_array(env, &rows));
916
- for (uint32_t r = 0; max == 0 || r < (uint32_t)max; r++) {
917
- SQLRETURN rc = SQLFetch(stmt);
918
- if (rc == SQL_NO_DATA) {
919
- break;
920
- }
921
- CHECK(SQL_HANDLE_STMT, stmt, rc);
922
-
923
- napi_value row;
924
- NAPI_CALL(napi_create_array_with_length(env, n, &row));
925
- for (size_t i = 0; i < n; i++) {
926
- napi_value value = get_value(env, stmt, (SQLSMALLINT)(i + 1), kinds[i]);
927
- if (value == NULL) {
928
- return NULL;
929
- }
930
- NAPI_CALL(napi_set_element(env, row, (uint32_t)i, value));
931
- }
932
- NAPI_CALL(napi_set_element(env, rows, r, row));
1099
+ if (napi_get_value_string_latin1(env, argv[1], kinds, n + 1, &n) != napi_ok) {
1100
+ throw_napi_error(env);
1101
+ free(kinds);
1102
+ return NULL;
933
1103
  }
934
1104
 
1105
+ napi_value rows = fetch_rows(env, stmt, kinds, n, max);
1106
+ free(kinds);
935
1107
  return rows;
936
1108
  }
937
1109
 
@@ -940,6 +1112,9 @@ static void free_instance(napi_env env, void *data, void *hint) {
940
1112
  if (inst->error_factory != NULL) {
941
1113
  napi_delete_reference(env, inst->error_factory);
942
1114
  }
1115
+ if (inst->warn != NULL) {
1116
+ napi_delete_reference(env, inst->warn);
1117
+ }
943
1118
  free(inst);
944
1119
  }
945
1120