drizzle-sybase 2.0.1 → 3.0.0

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.
Files changed (91) hide show
  1. package/README.md +72 -6
  2. package/dist/columns/index.d.ts +186 -36
  3. package/dist/columns/index.d.ts.map +1 -1
  4. package/dist/columns/index.js +113 -23
  5. package/dist/columns/index.js.map +1 -1
  6. package/dist/connection.d.ts +77 -157
  7. package/dist/connection.d.ts.map +1 -1
  8. package/dist/connection.js +244 -506
  9. package/dist/connection.js.map +1 -1
  10. package/dist/datetime.d.ts +15 -0
  11. package/dist/datetime.d.ts.map +1 -1
  12. package/dist/datetime.js +25 -0
  13. package/dist/datetime.js.map +1 -1
  14. package/dist/db.d.ts +36 -10
  15. package/dist/db.d.ts.map +1 -1
  16. package/dist/db.js +15 -25
  17. package/dist/db.js.map +1 -1
  18. package/dist/dialect.d.ts +24 -0
  19. package/dist/dialect.d.ts.map +1 -1
  20. package/dist/dialect.js +63 -9
  21. package/dist/dialect.js.map +1 -1
  22. package/dist/index.d.ts +11 -5
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +5 -3
  25. package/dist/index.js.map +1 -1
  26. package/dist/introspect/codegen.d.ts +8 -1
  27. package/dist/introspect/codegen.d.ts.map +1 -1
  28. package/dist/introspect/codegen.js +117 -29
  29. package/dist/introspect/codegen.js.map +1 -1
  30. package/dist/introspect/fetch.d.ts +9 -2
  31. package/dist/introspect/fetch.d.ts.map +1 -1
  32. package/dist/introspect/fetch.js +37 -8
  33. package/dist/introspect/fetch.js.map +1 -1
  34. package/dist/introspect/index.d.ts +1 -0
  35. package/dist/introspect/index.d.ts.map +1 -1
  36. package/dist/introspect/index.js +8 -5
  37. package/dist/introspect/index.js.map +1 -1
  38. package/dist/introspect/type-map.d.ts +17 -8
  39. package/dist/introspect/type-map.d.ts.map +1 -1
  40. package/dist/introspect/type-map.js +28 -9
  41. package/dist/introspect/type-map.js.map +1 -1
  42. package/dist/native/index.d.ts +4 -1
  43. package/dist/native/index.d.ts.map +1 -1
  44. package/dist/native/index.js.map +1 -1
  45. package/dist/native/sybase_native.darwin-arm64.node +0 -0
  46. package/dist/native/sybase_native.darwin-x64.node +0 -0
  47. package/dist/native/sybase_native.linux-arm64.node +0 -0
  48. package/dist/native/sybase_native.linux-x64.node +0 -0
  49. package/dist/native/sybase_native.win32-x64.node +0 -0
  50. package/dist/pool.d.ts +197 -0
  51. package/dist/pool.d.ts.map +1 -0
  52. package/dist/pool.js +638 -0
  53. package/dist/pool.js.map +1 -0
  54. package/dist/query-builders/delete.d.ts +6 -4
  55. package/dist/query-builders/delete.d.ts.map +1 -1
  56. package/dist/query-builders/delete.js +4 -4
  57. package/dist/query-builders/delete.js.map +1 -1
  58. package/dist/query-builders/index.d.ts +1 -1
  59. package/dist/query-builders/index.d.ts.map +1 -1
  60. package/dist/query-builders/index.js.map +1 -1
  61. package/dist/query-builders/insert.d.ts +28 -4
  62. package/dist/query-builders/insert.d.ts.map +1 -1
  63. package/dist/query-builders/insert.js +8 -5
  64. package/dist/query-builders/insert.js.map +1 -1
  65. package/dist/query-builders/select-types.d.ts +132 -0
  66. package/dist/query-builders/select-types.d.ts.map +1 -0
  67. package/dist/query-builders/select-types.js +2 -0
  68. package/dist/query-builders/select-types.js.map +1 -0
  69. package/dist/query-builders/select.d.ts +54 -34
  70. package/dist/query-builders/select.d.ts.map +1 -1
  71. package/dist/query-builders/select.js +99 -92
  72. package/dist/query-builders/select.js.map +1 -1
  73. package/dist/query-builders/update.d.ts +7 -5
  74. package/dist/query-builders/update.d.ts.map +1 -1
  75. package/dist/query-builders/update.js +4 -4
  76. package/dist/query-builders/update.js.map +1 -1
  77. package/dist/session.d.ts +141 -14
  78. package/dist/session.d.ts.map +1 -1
  79. package/dist/session.js +456 -40
  80. package/dist/session.js.map +1 -1
  81. package/dist/sql-classify.d.ts +70 -0
  82. package/dist/sql-classify.d.ts.map +1 -0
  83. package/dist/sql-classify.js +189 -0
  84. package/dist/sql-classify.js.map +1 -0
  85. package/dist/table.d.ts +85 -3
  86. package/dist/table.d.ts.map +1 -1
  87. package/dist/table.js +8 -2
  88. package/dist/table.js.map +1 -1
  89. package/package.json +9 -8
  90. package/scripts/clean.ts +4 -3
  91. package/src/native/binding.c +463 -62
@@ -45,6 +45,8 @@
45
45
  #include <sybfront.h>
46
46
  #include <sybdb.h>
47
47
  #include <uv.h>
48
+ #include <stdarg.h>
49
+ #include <stdint.h>
48
50
  #include <string.h>
49
51
  #include <stdlib.h>
50
52
  #include <stdio.h>
@@ -57,10 +59,11 @@
57
59
  #define ERR_BUF_SIZE 4096
58
60
  // Maximum rows to return by default (safety limit against accidental OOM).
59
61
  #define DEFAULT_MAX_ROWS 1000000
60
- // Default TDS network packet size (bytes). Larger than the FreeTDS default
61
- // of 512 — fewer round-trips on big result sets. The server may negotiate
62
- // down if it can't go this high.
63
- #define DEFAULT_PACKET_SIZE 4096
62
+ // Default TDS network packet size (bytes): ASE's out-of-the-box `max network
63
+ // packet size`. The server does not negotiate a larger request down — it
64
+ // refuses the login (Msg 4002, as for a bad password) — so the default is the
65
+ // stock limit; a server configured lower (down to 512) needs packetSize set.
66
+ #define DEFAULT_PACKET_SIZE 2048
64
67
 
65
68
  // ---------------------------------------------------------------------------
66
69
  // Global mutex for serializing inherently process-wide db-lib calls.
@@ -73,6 +76,40 @@
73
76
  static uv_once_t global_init_once = UV_ONCE_INIT;
74
77
  static uv_mutex_t login_mutex;
75
78
 
79
+ /*
80
+ * Messages raised while dbopen() runs. The handlers find a connection through
81
+ * the DBPROCESS's user data, which does not exist until dbopen() returns, so
82
+ * without this every login failure — bad password, unknown database, a packet
83
+ * size the server refuses — surfaced only as "Failed to connect".
84
+ *
85
+ * Thread-local, not guarded by login_mutex: db-lib calls the handlers on the
86
+ * thread that made the call, so a thread's login messages are exactly what its
87
+ * own dbopen() raised. A shared buffer would also collect errors other threads
88
+ * raise with no DBPROCESS (db-lib reports e.g. allocation failures that way)
89
+ * — racing on the buffer and blaming the wrong login.
90
+ */
91
+ #if defined(_MSC_VER)
92
+ #define THREAD_LOCAL __declspec(thread)
93
+ #else
94
+ #define THREAD_LOCAL _Thread_local
95
+ #endif
96
+ static THREAD_LOCAL char login_error[ERR_BUF_SIZE];
97
+ static THREAD_LOCAL int login_in_progress = 0;
98
+
99
+ static void append_login_error(const char *fmt, ...) {
100
+ if (!login_in_progress) {
101
+ return;
102
+ }
103
+ size_t used = strlen(login_error);
104
+ if (used + 1 >= sizeof(login_error)) {
105
+ return;
106
+ }
107
+ va_list args;
108
+ va_start(args, fmt);
109
+ vsnprintf(login_error + used, sizeof(login_error) - used, fmt, args);
110
+ va_end(args);
111
+ }
112
+
76
113
  static void init_globals(void) {
77
114
  uv_mutex_init(&login_mutex);
78
115
  }
@@ -109,7 +146,7 @@ typedef struct {
109
146
  int timed_out; // set when err_handler sees SYBETIME
110
147
  int timeout_seconds; // remembered so watchdog can compute its deadline
111
148
  uv_mutex_t lock;
112
- int in_flight; // # of running queries on this connection (0 or 1)
149
+ int in_flight; // # of queries pinning this connection, from enqueue to completion
113
150
  int pending_close; // 1 if fn_close was called while in_flight > 0
114
151
  } SybaseConnection;
115
152
 
@@ -146,6 +183,23 @@ static void conn_release(SybaseConnection *conn) {
146
183
  }
147
184
  }
148
185
 
186
+ /**
187
+ * `dead` is written by the worker (err_handler), the watchdog thread and the
188
+ * JS thread (fn_close), so every access goes through `conn->lock`.
189
+ */
190
+ static void conn_mark_dead(SybaseConnection *conn) {
191
+ uv_mutex_lock(&conn->lock);
192
+ conn->dead = 1;
193
+ uv_mutex_unlock(&conn->lock);
194
+ }
195
+
196
+ static int conn_is_dead(SybaseConnection *conn) {
197
+ uv_mutex_lock(&conn->lock);
198
+ int dead = conn->dead;
199
+ uv_mutex_unlock(&conn->lock);
200
+ return dead;
201
+ }
202
+
149
203
  /**
150
204
  * Actually free a connection. Must be called outside conn->lock; this
151
205
  * function destroys the lock itself.
@@ -163,6 +217,69 @@ static void destroy_connection(SybaseConnection *conn) {
163
217
  free(conn);
164
218
  }
165
219
 
220
+ /**
221
+ * Close a connection now, or — if a query is still running on it — mark it
222
+ * so the last worker to finish frees it (see conn_release).
223
+ */
224
+ static void close_connection(SybaseConnection *conn) {
225
+ uv_mutex_lock(&conn->lock);
226
+ int can_destroy_now = (conn->in_flight == 0);
227
+ int already_pending = conn->pending_close;
228
+ conn->pending_close = 1;
229
+ conn->dead = 1; // reject any subsequent acquire
230
+ uv_mutex_unlock(&conn->lock);
231
+
232
+ if (can_destroy_now && !already_pending) {
233
+ destroy_connection(conn);
234
+ }
235
+ // else: the worker holding in_flight frees it in conn_release.
236
+ }
237
+
238
+ // ---------------------------------------------------------------------------
239
+ // JS-facing connection handle
240
+ //
241
+ // JS holds an external pointing at this box, never at the connection itself:
242
+ // the connection is freed on close, but the external lives on for as long as
243
+ // JS keeps a reference. Clearing `conn` on close makes every later use of the
244
+ // handle — a second close, isAlive, query — see a closed connection instead of
245
+ // freed memory. Only the JS thread touches the box, so it needs no lock.
246
+ // ---------------------------------------------------------------------------
247
+
248
+ typedef struct {
249
+ SybaseConnection *conn; // NULL once closed
250
+ } ConnHandle;
251
+
252
+ // Identifies externals created by connect(), so an arbitrary value passed as a
253
+ // handle is rejected rather than dereferenced.
254
+ static const napi_type_tag CONN_HANDLE_TAG = {0x8f1c2a7d3b4e5f60ULL, 0x91a2b3c4d5e6f708ULL};
255
+
256
+ /** GC of a handle that was never closed: close the connection it still owns. */
257
+ static void conn_handle_finalize(napi_env env, void *data, void *hint) {
258
+ (void)env;
259
+ (void)hint;
260
+ ConnHandle *handle = (ConnHandle *)data;
261
+ if (handle->conn) {
262
+ close_connection(handle->conn);
263
+ handle->conn = NULL;
264
+ }
265
+ free(handle);
266
+ }
267
+
268
+ /**
269
+ * The handle behind `value`, or NULL (with a TypeError thrown) if `value` is
270
+ * not one returned by connect().
271
+ */
272
+ static ConnHandle *get_conn_handle(napi_env env, napi_value value) {
273
+ bool tagged = false;
274
+ void *data = NULL;
275
+ if (napi_check_object_type_tag(env, value, &CONN_HANDLE_TAG, &tagged) != napi_ok || !tagged ||
276
+ napi_get_value_external(env, value, &data) != napi_ok || data == NULL) {
277
+ napi_throw_type_error(env, NULL, "Expected a connection handle returned by connect()");
278
+ return NULL;
279
+ }
280
+ return (ConnHandle *)data;
281
+ }
282
+
166
283
  // ---------------------------------------------------------------------------
167
284
  // Error/message handlers
168
285
  //
@@ -180,6 +297,11 @@ static int err_handler(DBPROCESS *dbproc, int severity, int dberr,
180
297
  conn = (SybaseConnection *)dbgetuserdata(dbproc);
181
298
  }
182
299
 
300
+ if (!conn) {
301
+ // During dbopen there is no connection to attach it to yet.
302
+ append_login_error("DB-Lib error %d (severity %d): %s\n", dberr, severity, dberrstr);
303
+ }
304
+
183
305
  if (conn) {
184
306
  size_t cur_len = strlen(conn->last_error);
185
307
  if (cur_len < ERR_BUF_SIZE - 100) {
@@ -193,7 +315,7 @@ static int err_handler(DBPROCESS *dbproc, int severity, int dberr,
193
315
  }
194
316
 
195
317
  if (DBDEAD(dbproc)) {
196
- conn->dead = 1;
318
+ conn_mark_dead(conn);
197
319
  }
198
320
  }
199
321
 
@@ -223,6 +345,11 @@ static int msg_handler(DBPROCESS *dbproc, DBINT msgno, int msgstate,
223
345
  conn = (SybaseConnection *)dbgetuserdata(dbproc);
224
346
  }
225
347
 
348
+ if (!conn) {
349
+ append_login_error("Msg %ld, Level %d, State %d: %s\n", (long)msgno, severity, msgstate,
350
+ msgtext);
351
+ }
352
+
226
353
  if (conn) {
227
354
  size_t cur_len = strlen(conn->last_error);
228
355
  if (cur_len < ERR_BUF_SIZE - 200) {
@@ -249,9 +376,62 @@ static void clear_error(SybaseConnection *conn) {
249
376
  typedef struct {
250
377
  char *name;
251
378
  char **values;
379
+ // Byte length per value; allocated only for binary columns, whose values
380
+ // are raw bytes (may contain NUL) rather than NUL-terminated text.
381
+ int *lengths;
252
382
  int type;
253
383
  } ResultColumn;
254
384
 
385
+ /** Whether a column carries raw bytes, handed to JS as a Buffer. */
386
+ static int is_binary_type(int coltype) {
387
+ return coltype == SYBBINARY || coltype == SYBVARBINARY || coltype == SYBIMAGE;
388
+ }
389
+
390
+ /**
391
+ * Discard the rest of the current result set. dbnextrow() returns FAIL — and
392
+ * keeps returning it — once the connection is dead, so a bare
393
+ * `while (dbnextrow() != NO_MORE_ROWS)` would spin forever on a broken
394
+ * stream. Returns FAIL in that case so the caller can bail out.
395
+ */
396
+ static RETCODE discard_rows(DBPROCESS *dbproc) {
397
+ RETCODE rc;
398
+ while ((rc = dbnextrow(dbproc)) != NO_MORE_ROWS) {
399
+ if (rc == FAIL) {
400
+ return FAIL;
401
+ }
402
+ }
403
+ return SUCCEED;
404
+ }
405
+
406
+ /*
407
+ * ASE's unsigned integer types. db-lib defines no names for them, so they reach
408
+ * `dbcoltype` as their TDS type codes — the same code whether or not the column
409
+ * is nullable (checked against ASE 15.7).
410
+ */
411
+ #define TDS_USMALLINT 65
412
+ #define TDS_UINT 66
413
+ #define TDS_UBIGINT 67
414
+ /* Nullable variant, as computed expressions report it; the size says which. */
415
+ #define TDS_UINTN 68
416
+
417
+ /** `dbcoltype`, with the nullable unsigned variant resolved by size like db-lib does for the rest. */
418
+ static int column_type(DBPROCESS *dbproc, int column) {
419
+ int type = dbcoltype(dbproc, column);
420
+ if (type != TDS_UINTN) {
421
+ return type;
422
+ }
423
+ switch (dbcollen(dbproc, column)) {
424
+ case 2:
425
+ return TDS_USMALLINT;
426
+ case 4:
427
+ return TDS_UINT;
428
+ case 8:
429
+ return TDS_UBIGINT;
430
+ default:
431
+ return type;
432
+ }
433
+ }
434
+
255
435
  /**
256
436
  * Sybase system type name for a db-lib column type, using the same spelling as
257
437
  * the schema/introspection layer. Exposed to JS as `columnTypes` so callers can
@@ -264,6 +444,16 @@ typedef struct {
264
444
  * need no cases here.
265
445
  */
266
446
  static const char *syb_type_name(int coltype) {
447
+ switch (coltype) {
448
+ case TDS_USMALLINT:
449
+ return "usmallint";
450
+ case TDS_UINT:
451
+ return "uint";
452
+ case TDS_UBIGINT:
453
+ return "ubigint";
454
+ default:
455
+ break;
456
+ }
267
457
  switch (coltype) {
268
458
  case SYBINT1:
269
459
  return "tinyint";
@@ -418,6 +608,7 @@ static void free_columns(ResultColumn *columns, int num_columns, int num_rows) {
418
608
  }
419
609
  free(columns[i].values);
420
610
  }
611
+ free(columns[i].lengths);
421
612
  free(columns[i].name);
422
613
  }
423
614
  free(columns);
@@ -495,15 +686,18 @@ static void connect_execute(napi_env env, void *data) {
495
686
  if (w->timeout_seconds > 0) {
496
687
  dbsetlogintime(w->timeout_seconds);
497
688
  }
689
+ login_error[0] = '\0';
690
+ login_in_progress = 1;
498
691
  w->conn->dbproc = dbopen(w->conn->login, server);
692
+ login_in_progress = 0;
499
693
  uv_mutex_unlock(&login_mutex);
500
694
 
501
695
  if (!w->conn->dbproc) {
502
- if (w->conn->has_error) {
503
- snprintf(w->error, sizeof(w->error), "%s", w->conn->last_error);
504
- } else {
505
- snprintf(w->error, sizeof(w->error), "Failed to connect to %s:%d",
506
- w->host, w->port);
696
+ // Prefix, then as much of the server's messages as fits: they are what
697
+ // says why (e.g. Msg 4002, Msg 911), and may be truncated, never overrun.
698
+ int n = snprintf(w->error, sizeof(w->error), "Failed to connect to %s:%d", w->host, w->port);
699
+ if (login_error[0] != '\0' && n > 0 && (size_t)n < sizeof(w->error)) {
700
+ snprintf(w->error + n, sizeof(w->error) - (size_t)n, ": %s", login_error);
507
701
  }
508
702
  dbloginfree(w->conn->login);
509
703
  uv_mutex_destroy(&w->conn->lock);
@@ -552,14 +746,32 @@ static void connect_complete(napi_env env, napi_status status, void *data) {
552
746
  ConnectWork *w = (ConnectWork *)data;
553
747
 
554
748
  if (status == napi_cancelled || !w->success) {
749
+ // Cancelled after a successful connect: nothing will ever own it.
750
+ if (w->success && w->conn) {
751
+ close_connection(w->conn);
752
+ }
555
753
  napi_value error_msg, error_obj;
556
754
  napi_create_string_utf8(env, w->error, NAPI_AUTO_LENGTH, &error_msg);
557
755
  napi_create_error(env, NULL, error_msg, &error_obj);
558
756
  napi_reject_deferred(env, w->deferred, error_obj);
559
757
  } else {
560
758
  napi_value result;
561
- napi_create_external(env, w->conn, NULL, NULL, &result);
562
- napi_resolve_deferred(env, w->deferred, result);
759
+ ConnHandle *handle = (ConnHandle *)malloc(sizeof(ConnHandle));
760
+ if (handle == NULL ||
761
+ napi_create_external(env, handle, conn_handle_finalize, NULL, &result) != napi_ok) {
762
+ // No handle for JS to close it through: close it here.
763
+ free(handle);
764
+ close_connection(w->conn);
765
+ napi_value error_msg, error_obj;
766
+ napi_create_string_utf8(env, "Could not create a connection handle", NAPI_AUTO_LENGTH,
767
+ &error_msg);
768
+ napi_create_error(env, NULL, error_msg, &error_obj);
769
+ napi_reject_deferred(env, w->deferred, error_obj);
770
+ } else {
771
+ handle->conn = w->conn;
772
+ napi_type_tag_object(env, result, &CONN_HANDLE_TAG);
773
+ napi_resolve_deferred(env, w->deferred, result);
774
+ }
563
775
  }
564
776
 
565
777
  napi_delete_async_work(env, w->work);
@@ -667,6 +879,10 @@ typedef struct {
667
879
  SybaseConnection *conn;
668
880
  char *sql;
669
881
  int max_rows;
882
+ // 1 when the caller asked for maxRows: hitting it is then the requested
883
+ // truncation. Hitting the internal safety cap instead fails the query.
884
+ int max_rows_explicit;
885
+ int truncated;
670
886
  int hard_timeout_ms;
671
887
  // Results
672
888
  ResultColumn *columns;
@@ -680,6 +896,11 @@ typedef struct {
680
896
  // dereferencing w->conn — which may have been freed by then.
681
897
  int conn_dead;
682
898
  int conn_timed_out;
899
+ // 1 while this work item holds an in-flight slot on `conn`. Taken in
900
+ // fn_query on the JS thread *before* the work is queued, so a close issued
901
+ // while the work waits in the libuv queue defers the free instead of
902
+ // leaving the worker with a dangling pointer.
903
+ int holds_conn;
683
904
  // Watchdog
684
905
  Watchdog wd;
685
906
  } QueryWork;
@@ -694,7 +915,7 @@ static void watchdog_thread(void *arg) {
694
915
  if (rc == UV_ETIMEDOUT && !wd->finished) {
695
916
  wd->fired = 1;
696
917
  if (wd->conn) {
697
- wd->conn->dead = 1;
918
+ conn_mark_dead(wd->conn);
698
919
  }
699
920
  }
700
921
  }
@@ -740,33 +961,48 @@ static void watchdog_stop(Watchdog *wd) {
740
961
  wd->started = 0;
741
962
  }
742
963
 
964
+ /**
965
+ * Drop this work item's in-flight slot. May free the connection if a close is
966
+ * pending; w->conn must not be dereferenced afterwards.
967
+ */
968
+ static void work_release_conn(QueryWork *w) {
969
+ if (w->holds_conn) {
970
+ w->holds_conn = 0;
971
+ conn_release(w->conn);
972
+ }
973
+ }
974
+
743
975
  static void query_execute(napi_env env, void *data) {
744
976
  (void)env;
745
977
  QueryWork *w = (QueryWork *)data;
746
978
 
747
- if (!w->conn) {
979
+ // No slot means the connection was already closed when the query was
980
+ // submitted; w->conn may be freed, so it must not be touched.
981
+ if (!w->holds_conn) {
748
982
  snprintf(w->error, sizeof(w->error), "Connection is closed");
749
983
  w->success = 0;
750
984
  return;
751
985
  }
752
986
 
753
- // Acquire an in-flight slot. If the connection is closed (or close is
754
- // pending from a JS-side hard-timeout abort) we reject without touching
755
- // dbproc — the close path in conn_release will free the struct.
756
- if (conn_acquire(w->conn) != 0) {
987
+ // Closed while this work waited in the libuv queue — the slot kept the
988
+ // struct alive, but the caller has abandoned the connection, so do not
989
+ // send the SQL.
990
+ uv_mutex_lock(&w->conn->lock);
991
+ int closing = w->conn->pending_close;
992
+ uv_mutex_unlock(&w->conn->lock);
993
+ if (closing) {
757
994
  snprintf(w->error, sizeof(w->error), "Connection is closed");
758
995
  w->success = 0;
759
- // Important: do NOT touch w->conn after this point, except via
760
- // query_complete which checks pending_close before re-acquiring.
996
+ work_release_conn(w);
761
997
  return;
762
998
  }
763
999
 
764
1000
  // Check if connection is dead.
765
- if (w->conn->dead || DBDEAD(w->conn->dbproc)) {
1001
+ if (conn_is_dead(w->conn) || DBDEAD(w->conn->dbproc)) {
766
1002
  snprintf(w->error, sizeof(w->error), "Connection is dead");
767
- w->conn->dead = 1;
1003
+ conn_mark_dead(w->conn);
768
1004
  w->success = 0;
769
- conn_release(w->conn);
1005
+ work_release_conn(w);
770
1006
  return;
771
1007
  }
772
1008
 
@@ -814,6 +1050,13 @@ static void query_execute(napi_env env, void *data) {
814
1050
  } else {
815
1051
  snprintf(w->error, sizeof(w->error), "dbresults() failed");
816
1052
  }
1053
+ // A statement-level error (e.g. a duplicate key) fails only that
1054
+ // statement: the server goes on with the rest of the batch, whose
1055
+ // results are still pending. Left unread, they make the next query on
1056
+ // this connection fail with "results pending" (DB-Lib 20019).
1057
+ if (!DBDEAD(w->conn->dbproc)) {
1058
+ dbcancel(w->conn->dbproc);
1059
+ }
817
1060
  free_columns(w->columns, w->num_columns, w->num_rows);
818
1061
  w->columns = NULL;
819
1062
  w->num_columns = 0;
@@ -830,14 +1073,18 @@ static void query_execute(napi_env env, void *data) {
830
1073
  if (cnt > 0) {
831
1074
  w->affected_rows += cnt;
832
1075
  }
833
- while (dbnextrow(w->conn->dbproc) != NO_MORE_ROWS) {}
1076
+ if (discard_rows(w->conn->dbproc) == FAIL) {
1077
+ goto rows_failed;
1078
+ }
834
1079
  continue;
835
1080
  }
836
1081
 
837
1082
  // If we already found a result set, skip subsequent ones
838
1083
  // (we return the FIRST result set with columns)
839
1084
  if (found_resultset) {
840
- while (dbnextrow(w->conn->dbproc) != NO_MORE_ROWS) {}
1085
+ if (discard_rows(w->conn->dbproc) == FAIL) {
1086
+ goto rows_failed;
1087
+ }
841
1088
  continue;
842
1089
  }
843
1090
  found_resultset = 1;
@@ -855,8 +1102,17 @@ static void query_execute(napi_env env, void *data) {
855
1102
  for (int i = 0; i < w->num_columns; i++) {
856
1103
  const char *colname = dbcolname(w->conn->dbproc, i + 1);
857
1104
  w->columns[i].name = strdup(colname ? colname : "");
858
- w->columns[i].type = dbcoltype(w->conn->dbproc, i + 1);
1105
+ w->columns[i].type = column_type(w->conn->dbproc, i + 1);
859
1106
  w->columns[i].values = NULL;
1107
+ if (!w->columns[i].name) {
1108
+ snprintf(w->error, sizeof(w->error), "Memory allocation failed for column names");
1109
+ free_columns(w->columns, w->num_columns, 0);
1110
+ w->columns = NULL;
1111
+ w->num_columns = 0;
1112
+ dbcancel(w->conn->dbproc);
1113
+ w->success = 0;
1114
+ goto done;
1115
+ }
860
1116
  }
861
1117
 
862
1118
  // Read rows
@@ -866,7 +1122,11 @@ static void query_execute(napi_env env, void *data) {
866
1122
 
867
1123
  for (int i = 0; i < w->num_columns; i++) {
868
1124
  w->columns[i].values = (char **)calloc(capacity, sizeof(char *));
869
- if (!w->columns[i].values) {
1125
+ if (w->columns[i].values && is_binary_type(w->columns[i].type)) {
1126
+ w->columns[i].lengths = (int *)calloc(capacity, sizeof(int));
1127
+ }
1128
+ if (!w->columns[i].values ||
1129
+ (is_binary_type(w->columns[i].type) && !w->columns[i].lengths)) {
870
1130
  snprintf(w->error, sizeof(w->error), "Memory allocation failed for rows");
871
1131
  free_columns(w->columns, w->num_columns, w->num_rows);
872
1132
  w->columns = NULL;
@@ -902,8 +1162,11 @@ static void query_execute(napi_env env, void *data) {
902
1162
 
903
1163
  // Safety: cap rows
904
1164
  if (w->num_rows >= max_rows) {
1165
+ w->truncated = 1;
905
1166
  // Drain remaining rows without storing
906
- while (dbnextrow(w->conn->dbproc) != NO_MORE_ROWS) {}
1167
+ if (discard_rows(w->conn->dbproc) == FAIL) {
1168
+ goto rows_failed;
1169
+ }
907
1170
  break;
908
1171
  }
909
1172
 
@@ -926,9 +1189,30 @@ static void query_execute(napi_env env, void *data) {
926
1189
  goto done;
927
1190
  }
928
1191
  w->columns[i].values = new_vals;
1192
+ if (w->columns[i].lengths) {
1193
+ int *new_lens = (int *)realloc(w->columns[i].lengths, capacity * sizeof(int));
1194
+ if (!new_lens) {
1195
+ snprintf(w->error, sizeof(w->error), "Memory realloc failed at row %d", w->num_rows);
1196
+ free_columns(w->columns, w->num_columns, w->num_rows);
1197
+ w->columns = NULL;
1198
+ w->num_columns = 0;
1199
+ w->num_rows = 0;
1200
+ dbcancel(w->conn->dbproc);
1201
+ w->success = 0;
1202
+ goto done;
1203
+ }
1204
+ w->columns[i].lengths = new_lens;
1205
+ }
929
1206
  }
930
1207
  }
931
1208
 
1209
+ // Clear this row's slots first: realloc'd storage is uninitialized, and a
1210
+ // failure partway through the row frees it with `num_rows + 1`, which
1211
+ // must only see the values actually stored so far.
1212
+ for (int i = 0; i < w->num_columns; i++) {
1213
+ w->columns[i].values[w->num_rows] = NULL;
1214
+ }
1215
+
932
1216
  // Read column values
933
1217
  for (int i = 0; i < w->num_columns; i++) {
934
1218
  int col = i + 1;
@@ -936,6 +1220,26 @@ static void query_execute(napi_env env, void *data) {
936
1220
 
937
1221
  if (datalen == 0 && dbdata(w->conn->dbproc, col) == NULL) {
938
1222
  w->columns[i].values[w->num_rows] = NULL;
1223
+ } else if (w->columns[i].lengths) {
1224
+ // Binary: keep the raw bytes. Converting to SYBCHAR would hand JS a
1225
+ // hex string, which is neither what the schema declares nor what a
1226
+ // write of the same value produces.
1227
+ char *bytes = (char *)malloc(datalen > 0 ? (size_t)datalen : 1);
1228
+ if (!bytes) {
1229
+ snprintf(w->error, sizeof(w->error), "Memory allocation failed for column value");
1230
+ free_columns(w->columns, w->num_columns, w->num_rows + 1);
1231
+ w->columns = NULL;
1232
+ w->num_columns = 0;
1233
+ w->num_rows = 0;
1234
+ dbcancel(w->conn->dbproc);
1235
+ w->success = 0;
1236
+ goto done;
1237
+ }
1238
+ if (datalen > 0) {
1239
+ memcpy(bytes, dbdata(w->conn->dbproc, col), (size_t)datalen);
1240
+ }
1241
+ w->columns[i].values[w->num_rows] = bytes;
1242
+ w->columns[i].lengths[w->num_rows] = datalen;
939
1243
  } else {
940
1244
  int coltype = dbcoltype(w->conn->dbproc, col);
941
1245
  BYTE *src = dbdata(w->conn->dbproc, col);
@@ -947,7 +1251,7 @@ static void query_execute(napi_env env, void *data) {
947
1251
  char *buf = (buf_size <= 8192) ? stack_buf : (char *)malloc(buf_size);
948
1252
  if (!buf) {
949
1253
  snprintf(w->error, sizeof(w->error), "Memory allocation failed for column value");
950
- free_columns(w->columns, w->num_columns, w->num_rows);
1254
+ free_columns(w->columns, w->num_columns, w->num_rows + 1);
951
1255
  w->columns = NULL;
952
1256
  w->num_columns = 0;
953
1257
  w->num_rows = 0;
@@ -977,7 +1281,7 @@ static void query_execute(napi_env env, void *data) {
977
1281
  if (buf != stack_buf) {
978
1282
  free(buf);
979
1283
  }
980
- free_columns(w->columns, w->num_columns, w->num_rows);
1284
+ free_columns(w->columns, w->num_columns, w->num_rows + 1);
981
1285
  w->columns = NULL;
982
1286
  w->num_columns = 0;
983
1287
  w->num_rows = 0;
@@ -1005,6 +1309,18 @@ static void query_execute(napi_env env, void *data) {
1005
1309
  if (buf != stack_buf) {
1006
1310
  free(buf);
1007
1311
  }
1312
+
1313
+ // A NULL here would be read back as SQL NULL — silently wrong data.
1314
+ if (!w->columns[i].values[w->num_rows]) {
1315
+ snprintf(w->error, sizeof(w->error), "Memory allocation failed for column value");
1316
+ free_columns(w->columns, w->num_columns, w->num_rows + 1);
1317
+ w->columns = NULL;
1318
+ w->num_columns = 0;
1319
+ w->num_rows = 0;
1320
+ dbcancel(w->conn->dbproc);
1321
+ w->success = 0;
1322
+ goto done;
1323
+ }
1008
1324
  }
1009
1325
  }
1010
1326
  w->num_rows++;
@@ -1017,8 +1333,28 @@ static void query_execute(napi_env env, void *data) {
1017
1333
  }
1018
1334
  }
1019
1335
 
1020
- // Check if any error occurred during result processing
1021
- if (w->conn->has_error && !found_resultset && w->affected_rows == 0) {
1336
+ // Rows were dropped without the caller asking for a cap: returning the rest
1337
+ // as if it were the whole result would be silently wrong data.
1338
+ if (w->truncated && !w->max_rows_explicit) {
1339
+ snprintf(w->error, sizeof(w->error),
1340
+ "Result exceeded %d rows; pass maxRows to accept a truncated result, "
1341
+ "or narrow the query",
1342
+ DEFAULT_MAX_ROWS);
1343
+ free_columns(w->columns, w->num_columns, w->num_rows);
1344
+ w->columns = NULL;
1345
+ w->num_columns = 0;
1346
+ w->num_rows = 0;
1347
+ w->success = 0;
1348
+ goto done;
1349
+ }
1350
+
1351
+ // Any server error (severity > 10) or db-lib error fails the query, even if
1352
+ // a result set or affected rows were seen first. Runtime errors such as a
1353
+ // conversion failure or divide-by-zero arrive after the column metadata and
1354
+ // abort the rest of the batch without making dbresults() return FAIL —
1355
+ // reporting success there would hide a failed statement (and, for a
1356
+ // paginated select, a skipped trailing `SET ROWCOUNT 0`).
1357
+ if (w->conn->has_error) {
1022
1358
  snprintf(w->error, sizeof(w->error), "%s", w->conn->last_error);
1023
1359
  free_columns(w->columns, w->num_columns, w->num_rows);
1024
1360
  w->columns = NULL;
@@ -1029,6 +1365,21 @@ static void query_execute(napi_env env, void *data) {
1029
1365
  }
1030
1366
 
1031
1367
  w->success = 1;
1368
+ goto done;
1369
+
1370
+ rows_failed:
1371
+ // The result stream broke while discarding rows (typically a dead
1372
+ // connection). No dbcancel: there is nothing left to cancel on.
1373
+ if (w->conn->has_error) {
1374
+ snprintf(w->error, sizeof(w->error), "%s", w->conn->last_error);
1375
+ } else {
1376
+ snprintf(w->error, sizeof(w->error), "dbnextrow() failed");
1377
+ }
1378
+ free_columns(w->columns, w->num_columns, w->num_rows);
1379
+ w->columns = NULL;
1380
+ w->num_columns = 0;
1381
+ w->num_rows = 0;
1382
+ w->success = 0;
1032
1383
 
1033
1384
  done:
1034
1385
  // Stop the watchdog before returning. If it already fired (forced cancel),
@@ -1047,7 +1398,7 @@ done:
1047
1398
 
1048
1399
  // Snapshot connection flags before releasing — w->conn may be freed
1049
1400
  // inside conn_release if a close was pending.
1050
- w->conn_dead = w->conn->dead;
1401
+ w->conn_dead = conn_is_dead(w->conn);
1051
1402
  w->conn_timed_out = w->conn->timed_out;
1052
1403
 
1053
1404
  // Release the in-flight slot. If a close was queued while we were running
@@ -1055,7 +1406,7 @@ done:
1055
1406
  // the SybaseConnection struct are actually freed. After this call we MUST
1056
1407
  // NOT touch w->conn — query_complete will run on the JS thread but only
1057
1408
  // reads w->error / w->wd.fired / w->success, never w->conn->dbproc.
1058
- conn_release(w->conn);
1409
+ work_release_conn(w);
1059
1410
  }
1060
1411
 
1061
1412
  static void query_complete(napi_env env, napi_status status, void *data) {
@@ -1114,6 +1465,9 @@ static void query_complete(napi_env env, napi_status status, void *data) {
1114
1465
 
1115
1466
  if (w->columns[c].values[r] == NULL) {
1116
1467
  napi_get_null(env, &val);
1468
+ } else if (w->columns[c].lengths) {
1469
+ napi_create_buffer_copy(env, (size_t)w->columns[c].lengths[r],
1470
+ w->columns[c].values[r], NULL, &val);
1117
1471
  } else {
1118
1472
  int coltype = w->columns[c].type;
1119
1473
  char *strval = w->columns[c].values[r];
@@ -1130,6 +1484,12 @@ static void query_complete(napi_env env, napi_status status, void *data) {
1130
1484
  // corrupting the result, which is the behaviour we want here.
1131
1485
  long long llval = atoll(strval);
1132
1486
  napi_create_bigint_int64(env, llval, &val);
1487
+ } else if (coltype == TDS_USMALLINT || coltype == TDS_UINT) {
1488
+ // Up to 4294967295: past int32, but exact in a double.
1489
+ napi_create_double(env, (double)strtoul(strval, NULL, 10), &val);
1490
+ } else if (coltype == TDS_UBIGINT) {
1491
+ // Up to 18446744073709551615 — past even int64, so a uint64 BigInt.
1492
+ napi_create_bigint_uint64(env, (uint64_t)strtoull(strval, NULL, 10), &val);
1133
1493
  } else if (coltype == SYBFLT8 || coltype == SYBREAL) {
1134
1494
  double dval = atof(strval);
1135
1495
  napi_create_double(env, dval, &val);
@@ -1171,6 +1531,8 @@ static void query_complete(napi_env env, napi_status status, void *data) {
1171
1531
  }
1172
1532
 
1173
1533
  // Cleanup — always runs regardless of success/failure
1534
+ // A cancelled work item never ran query_execute, so its slot is still held.
1535
+ work_release_conn(w);
1174
1536
  free_columns(w->columns, w->num_columns, w->num_rows);
1175
1537
  free(w->sql);
1176
1538
  napi_delete_async_work(env, w->work);
@@ -1187,17 +1549,32 @@ static napi_value fn_query(napi_env env, napi_callback_info info) {
1187
1549
  napi_value args[3];
1188
1550
  napi_get_cb_info(env, info, &argc, args, NULL, NULL);
1189
1551
 
1190
- QueryWork *w = (QueryWork *)calloc(1, sizeof(QueryWork));
1552
+ ConnHandle *handle = get_conn_handle(env, args[0]);
1553
+ if (handle == NULL) {
1554
+ return NULL; // TypeError pending
1555
+ }
1191
1556
 
1192
- // Get connection
1193
- napi_get_value_external(env, args[0], (void **)&w->conn);
1557
+ size_t sql_len = 0;
1558
+ if (argc < 2 || napi_get_value_string_utf8(env, args[1], NULL, 0, &sql_len) != napi_ok) {
1559
+ napi_throw_type_error(env, NULL, "Expected the SQL as a string");
1560
+ return NULL;
1561
+ }
1194
1562
 
1195
- // Get SQL string
1196
- size_t sql_len;
1197
- napi_get_value_string_utf8(env, args[1], NULL, 0, &sql_len);
1198
- w->sql = (char *)malloc(sql_len + 1);
1563
+ QueryWork *w = (QueryWork *)calloc(1, sizeof(QueryWork));
1564
+ char *sql = (char *)malloc(sql_len + 1);
1565
+ if (w == NULL || sql == NULL) {
1566
+ free(w);
1567
+ free(sql);
1568
+ napi_throw_error(env, NULL, "Out of memory");
1569
+ return NULL;
1570
+ }
1571
+ w->sql = sql;
1199
1572
  napi_get_value_string_utf8(env, args[1], w->sql, sql_len + 1, &sql_len);
1200
1573
 
1574
+ // A closed handle has no connection: the query is rejected as on a closed
1575
+ // connection (holds_conn stays 0 below).
1576
+ w->conn = handle->conn;
1577
+
1201
1578
  // Defaults
1202
1579
  w->max_rows = DEFAULT_MAX_ROWS;
1203
1580
  // Hard timeout: 2x the cooperative timeout, with a 30s floor so very small
@@ -1219,7 +1596,12 @@ static napi_value fn_query(napi_env env, napi_callback_info info) {
1219
1596
  napi_get_named_property(env, args[2], "maxRows", &v);
1220
1597
  napi_typeof(env, v, &vtype);
1221
1598
  if (vtype == napi_number) {
1222
- napi_get_value_int32(env, v, &w->max_rows);
1599
+ int32_t requested = 0;
1600
+ napi_get_value_int32(env, v, &requested);
1601
+ if (requested > 0) {
1602
+ w->max_rows = requested;
1603
+ w->max_rows_explicit = 1;
1604
+ }
1223
1605
  }
1224
1606
 
1225
1607
  napi_get_named_property(env, args[2], "hardTimeoutMs", &v);
@@ -1233,10 +1615,32 @@ static napi_value fn_query(napi_env env, napi_callback_info info) {
1233
1615
  napi_value promise;
1234
1616
  napi_create_promise(env, &w->deferred, &promise);
1235
1617
 
1618
+ // Pin the connection now, on the JS thread, rather than when a worker picks
1619
+ // the job up: fn_close only defers the free while in_flight > 0, and the
1620
+ // job may sit in the libuv queue behind other queries for a long time.
1621
+ w->holds_conn = (w->conn != NULL && conn_acquire(w->conn) == 0);
1622
+
1236
1623
  napi_value work_name;
1237
1624
  napi_create_string_utf8(env, "sybase_query", NAPI_AUTO_LENGTH, &work_name);
1238
- napi_create_async_work(env, NULL, work_name, query_execute, query_complete, w, &w->work);
1239
- napi_queue_async_work(env, w->work);
1625
+ napi_status st = napi_create_async_work(env, NULL, work_name, query_execute, query_complete,
1626
+ w, &w->work);
1627
+ if (st == napi_ok) {
1628
+ st = napi_queue_async_work(env, w->work);
1629
+ if (st != napi_ok) {
1630
+ napi_delete_async_work(env, w->work);
1631
+ }
1632
+ }
1633
+ if (st != napi_ok) {
1634
+ // query_complete will never run, so undo here what it would have:
1635
+ // release the connection slot, settle the promise and free the work.
1636
+ work_release_conn(w);
1637
+ napi_value msg, err;
1638
+ napi_create_string_utf8(env, "Failed to schedule query", NAPI_AUTO_LENGTH, &msg);
1639
+ napi_create_error(env, NULL, msg, &err);
1640
+ napi_reject_deferred(env, w->deferred, err);
1641
+ free(w->sql);
1642
+ free(w);
1643
+ }
1240
1644
 
1241
1645
  return promise;
1242
1646
  }
@@ -1263,21 +1667,15 @@ static napi_value fn_close(napi_env env, napi_callback_info info) {
1263
1667
  napi_value args[1];
1264
1668
  napi_get_cb_info(env, info, &argc, args, NULL, NULL);
1265
1669
 
1266
- SybaseConnection *conn;
1267
- napi_get_value_external(env, args[0], (void **)&conn);
1268
-
1269
- if (conn) {
1270
- uv_mutex_lock(&conn->lock);
1271
- int can_destroy_now = (conn->in_flight == 0);
1272
- int already_pending = conn->pending_close;
1273
- conn->pending_close = 1;
1274
- conn->dead = 1; // reject any subsequent acquire
1275
- uv_mutex_unlock(&conn->lock);
1276
-
1277
- if (can_destroy_now && !already_pending) {
1278
- destroy_connection(conn);
1279
- }
1280
- // else: worker (or someone holding in_flight) will free in conn_release.
1670
+ ConnHandle *handle = get_conn_handle(env, args[0]);
1671
+ if (handle == NULL) {
1672
+ return NULL; // TypeError pending
1673
+ }
1674
+ // Closing twice is a no-op: the second call finds no connection.
1675
+ if (handle->conn) {
1676
+ SybaseConnection *conn = handle->conn;
1677
+ handle->conn = NULL;
1678
+ close_connection(conn);
1281
1679
  }
1282
1680
 
1283
1681
  napi_value undefined;
@@ -1294,8 +1692,11 @@ static napi_value fn_is_alive(napi_env env, napi_callback_info info) {
1294
1692
  napi_value args[1];
1295
1693
  napi_get_cb_info(env, info, &argc, args, NULL, NULL);
1296
1694
 
1297
- SybaseConnection *conn;
1298
- napi_get_value_external(env, args[0], (void **)&conn);
1695
+ ConnHandle *handle = get_conn_handle(env, args[0]);
1696
+ if (handle == NULL) {
1697
+ return NULL; // TypeError pending
1698
+ }
1699
+ SybaseConnection *conn = handle->conn;
1299
1700
 
1300
1701
  int alive = 0;
1301
1702
  if (conn) {