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
@@ -1,24 +1,111 @@
1
1
  /**
2
- * Sybase connection management with production-grade connection pooling.
3
- *
4
- * Features:
5
- * - Persistent db-lib connections via N-API
6
- * - Connection pool with max sizing
7
- * - Health checks (dead connection detection + optional ping)
8
- * - Idle connection cleanup
9
- * - Automatic reconnection for dead connections
10
- * - Acquire timeout with queuing
11
- * - Retry on transient failures
12
- * - Graceful drain/shutdown
13
- * - Observable pool metrics
14
- * - Query logging/middleware support
2
+ * A single Sybase connection over the native db-lib addon: opening it (and
3
+ * establishing the session baseline), serialized queries, timeouts, and
4
+ * restoring the session state. Also the options and validation it shares with
5
+ * the pool (see `./pool.ts`).
15
6
  */
16
- import { resolveTimeZone } from "./datetime.js";
17
- import { SybaseError, SybaseConnectionError, SybaseQueryError, SybaseTimeoutError, SybasePoolError } from "./errors.js";
7
+ import { describeTimeZoneMismatch, resolveTimeZone } from "./datetime.js";
8
+ import { escapeName } from "./dialect.js";
9
+ import { SybaseError, SybaseConnectionError, SybaseQueryError, SybaseTimeoutError } from "./errors.js";
18
10
  import { native } from "./native/index.js";
11
+ /**
12
+ * Hand a log entry to the logger, isolating the caller from it: a throwing
13
+ * logger must not turn a successful query into a failure, nor skip releasing
14
+ * or rolling back the connection.
15
+ *
16
+ * @internal
17
+ */
18
+ export const emitQueryLog = (logger, log) => {
19
+ if (!logger) {
20
+ return;
21
+ }
22
+ try {
23
+ logger.query(log);
24
+ }
25
+ catch {
26
+ // Observability must not affect query outcome.
27
+ }
28
+ };
29
+ /**
30
+ * A single integer server variable from a one-row result, or `undefined` if
31
+ * the result is not shaped that way. `Number(null)` and `Number("")` are 0, so
32
+ * those are rejected explicitly — a missing value must not read as one.
33
+ *
34
+ * @internal
35
+ */
36
+ export const readServerInt = (rows, key) => {
37
+ const row = rows.length === 1 ? rows[0] : undefined;
38
+ const raw = row?.[key];
39
+ if (typeof raw !== "number" && !(typeof raw === "string" && /^-?\d+$/.test(raw))) {
40
+ return undefined;
41
+ }
42
+ const value = Number(raw);
43
+ return Number.isSafeInteger(value) ? value : undefined;
44
+ };
19
45
  // ---------------------------------------------------------------------------
20
46
  // Single connection
21
47
  // ---------------------------------------------------------------------------
48
+ /** @internal */
49
+ export const MAX_INT32 = 2147483647;
50
+ /**
51
+ * Default TDS packet size: ASE's out-of-the-box `max network packet size`, so
52
+ * a server with stock settings accepts the login.
53
+ */
54
+ const DEFAULT_PACKET_SIZE = 2048;
55
+ /** The lowest `max network packet size` a server can be configured with. */
56
+ const MIN_SERVER_PACKET_SIZE = 512;
57
+ /**
58
+ * Reject a numeric option that is not an integer in range. These values end
59
+ * up in timers (which treat anything past 2^31-1 ms as 1 ms), in C ints, or in
60
+ * pool arithmetic where `NaN` makes every comparison false and the pool never
61
+ * opens a connection — each a silent malfunction, so a bad value fails here.
62
+ */
63
+ /** @internal */
64
+ export const checkInteger = (name, value, min, max, message = `${name} must be an integer between ${min} and ${max}`) => {
65
+ if (value !== undefined && !(Number.isInteger(value) && value >= min && value <= max)) {
66
+ throw new RangeError(`${message}, got ${String(value)}`);
67
+ }
68
+ };
69
+ /** Validate the options a single connection uses. */
70
+ /** @internal */
71
+ export const validateConnectionConfig = (config) => {
72
+ checkInteger("port", config.port, 1, 65535);
73
+ // Seconds; the native hard timeout derived from it (2x, in ms) must fit an int.
74
+ checkInteger("timeout", config.timeout, 0, Math.floor(MAX_INT32 / 2000));
75
+ checkInteger("packetSize", config.packetSize, 512, 65535);
76
+ checkInteger("hardTimeoutMs", config.hardTimeoutMs, 1, MAX_INT32);
77
+ // `timeZone` is consumed by the session and dialect, not here, but this is a
78
+ // public entry point that accepts it — validating it here keeps the promise
79
+ // on `SybaseConnectionConfig.timeZone` true wherever a config is accepted.
80
+ resolveTimeZone(config.timeZone);
81
+ };
82
+ /** Validate the options of a single query. */
83
+ /** @internal */
84
+ export const validateQueryOptions = (options) => {
85
+ checkInteger("maxRows", options?.maxRows, 1, MAX_INT32);
86
+ checkInteger("hardTimeoutMs", options?.hardTimeoutMs, 1, MAX_INT32);
87
+ };
88
+ /** Servers already warned about, so a pool does not warn once per connection. */
89
+ const timeZoneWarned = new Set();
90
+ /**
91
+ * Warn — once per server, database and zone — when the server's clock is not
92
+ * in the zone datetime values are converted in. Every datetime read or written
93
+ * would be off by the difference, so it must not pass unnoticed; but it is a
94
+ * warning, not an error, because an application may compensate for it itself
95
+ * and must be able to start while that is sorted out.
96
+ */
97
+ const warnOnTimeZoneMismatch = (config, serverOffset) => {
98
+ const timeZone = resolveTimeZone(config.timeZone);
99
+ const key = `${config.host}:${config.port}/${config.database}/${timeZone}`;
100
+ if (timeZoneWarned.has(key)) {
101
+ return;
102
+ }
103
+ const mismatch = describeTimeZoneMismatch(serverOffset, timeZone);
104
+ if (mismatch) {
105
+ timeZoneWarned.add(key);
106
+ process.emitWarning(`${key}: ${mismatch}`, { code: "DRIZZLE_SYBASE_TIMEZONE" });
107
+ }
108
+ };
22
109
  /**
23
110
  * A single Sybase connection wrapping the native FreeTDS handle.
24
111
  *
@@ -29,40 +116,170 @@ export class SybaseConnection {
29
116
  config;
30
117
  handle = null;
31
118
  closed = false;
32
- inUse = false;
33
119
  /** Promise queue to serialize queries on a single DBPROCESS (not thread-safe). */
34
120
  queryQueue = Promise.resolve();
35
121
  constructor(config) {
36
122
  this.config = config;
37
- // `timeZone` is consumed by the session and dialect, not here, but this is a
38
- // public entry point that accepts it — validating it here keeps the promise
39
- // on `SybaseConnectionConfig.timeZone` true wherever a config is accepted.
40
- resolveTimeZone(config.timeZone);
123
+ validateConnectionConfig(config);
41
124
  }
42
125
  async connect() {
43
126
  if (this.handle && !this.closed) {
44
127
  return;
45
128
  }
129
+ // Concurrent callers share one attempt; a second native connect would
130
+ // overwrite `handle` and leak the first.
131
+ if (this.connecting) {
132
+ return this.connecting;
133
+ }
134
+ this.connecting = this.open().finally(() => {
135
+ this.connecting = null;
136
+ });
137
+ return this.connecting;
138
+ }
139
+ connecting = null;
140
+ async open() {
141
+ // A handle abandoned after a hard timeout is still open natively.
142
+ if (this.handle) {
143
+ try {
144
+ native.close(this.handle);
145
+ }
146
+ catch {
147
+ // Ignore close errors
148
+ }
149
+ this.handle = null;
150
+ }
46
151
  this.closed = false;
152
+ const packetSize = this.config.packetSize ?? DEFAULT_PACKET_SIZE;
153
+ let handle;
47
154
  try {
48
- this.handle = await native.connect({
155
+ handle = await native.connect({
49
156
  host: this.config.host,
50
157
  port: this.config.port,
51
158
  database: this.config.database,
52
159
  username: this.config.username,
53
160
  password: this.config.password,
54
161
  timeout: this.config.timeout ?? 30,
55
- packetSize: this.config.packetSize ?? 4096
162
+ packetSize
56
163
  });
57
164
  }
58
165
  catch (err) {
59
- throw new SybaseConnectionError(err.message ?? String(err), {
166
+ let message = err.message ?? String(err);
167
+ // ASE refuses an oversized packet with the same message as bad
168
+ // credentials; say so, or the user will only check the password.
169
+ if (/Msg 4002\b/.test(message) && packetSize > MIN_SERVER_PACKET_SIZE) {
170
+ message +=
171
+ ` (packetSize is ${packetSize}: if the credentials are right, the server's ` +
172
+ `'max network packet size' may be lower — set packetSize to fit it)`;
173
+ }
174
+ throw new SybaseConnectionError(message, {
175
+ host: this.config.host,
176
+ port: this.config.port
177
+ });
178
+ }
179
+ // close() was called while connecting — honour it rather than resurrect
180
+ // the connection with a handle nothing would ever close.
181
+ if (this.closed) {
182
+ native.close(handle);
183
+ throw new SybaseConnectionError("Connection was closed while connecting", {
60
184
  host: this.config.host,
61
185
  port: this.config.port
62
186
  });
63
187
  }
188
+ // Establish the baseline every pooled user can rely on. A login trigger
189
+ // can switch on chained mode, where every statement opens a transaction
190
+ // that nothing would ever commit; the isolation level found here is what
191
+ // {@link resetSessionState} restores.
192
+ let isolation;
193
+ let serverOffset;
194
+ try {
195
+ const { rows } = (await native.query(handle, "if @@tranchained = 1 set chained off\n" +
196
+ // In seconds: the two clocks are read an instant apart, and datediff
197
+ // counts boundaries crossed, so a minute count can be off by one.
198
+ "select @@isolation as iso, datediff(second, getutcdate(), getdate()) as tz", {}));
199
+ isolation = readServerInt(rows, "iso");
200
+ const offsetSeconds = readServerInt(rows, "tz");
201
+ serverOffset = offsetSeconds === undefined ? undefined : Math.round(offsetSeconds / 60);
202
+ }
203
+ catch (err) {
204
+ native.close(handle);
205
+ throw new SybaseConnectionError(`Could not initialise the session: ${err?.message ?? String(err)}`, { host: this.config.host, port: this.config.port });
206
+ }
207
+ if (isolation === undefined || isolation < 0 || isolation > 3) {
208
+ native.close(handle);
209
+ throw new SybaseConnectionError("Could not read the session isolation level", {
210
+ host: this.config.host,
211
+ port: this.config.port
212
+ });
213
+ }
214
+ // close() may have been called while the session was being initialised:
215
+ // `this.handle` was not set yet, so it could not close this one.
216
+ if (this.closed) {
217
+ native.close(handle);
218
+ throw new SybaseConnectionError("Connection was closed while connecting", {
219
+ host: this.config.host,
220
+ port: this.config.port
221
+ });
222
+ }
223
+ this.baseline = isolation;
224
+ this.handle = handle;
225
+ if (serverOffset !== undefined && this.config.warnOnTimeZoneMismatch !== false) {
226
+ warnOnTimeZoneMismatch(this.config, serverOffset);
227
+ }
228
+ }
229
+ /** Isolation level the session had when it was opened; what {@link resetSessionState} restores. */
230
+ baseline = 1;
231
+ /**
232
+ * Return the session to the state it was opened in: no open transaction,
233
+ * unchained, `ROWCOUNT 0`, the original isolation level and the configured
234
+ * database — so whatever a statement changed cannot reach the next user of a
235
+ * pooled connection.
236
+ *
237
+ * Resolves to whether a transaction was left open or chained mode was on
238
+ * (both are undone). Rejects if the state cannot be established; the caller
239
+ * must then discard the connection.
240
+ *
241
+ * @internal
242
+ */
243
+ async resetSessionState() {
244
+ const { rows } = await this.query([
245
+ "SET ROWCOUNT 0",
246
+ "select @@trancount as tc, @@tranchained as ch",
247
+ "if @@trancount > 0 rollback tran",
248
+ "if @@tranchained = 1 set chained off",
249
+ `SET TRANSACTION ISOLATION LEVEL ${this.baseline}`,
250
+ // After the rollback: `use` is not allowed inside a transaction.
251
+ `use ${escapeName(this.config.database)}`
252
+ ].join("\n"));
253
+ const trancount = readServerInt(rows, "tc");
254
+ const chained = readServerInt(rows, "ch");
255
+ if (trancount === undefined || chained === undefined) {
256
+ throw new SybaseError("Could not read the session state");
257
+ }
258
+ return { leftOpen: trancount > 0 || chained !== 0 };
259
+ }
260
+ /**
261
+ * Drop every temporary table this session has created, so a pooled
262
+ * connection does not hand them to its next user.
263
+ *
264
+ * ASE stores `#t` in the session's tempdb (one of several, see
265
+ * `@@tempdbid`) as `#t` plus a 17-character session suffix. A row is this
266
+ * session's own exactly when `object_id` of its base name — resolved per
267
+ * session — is that row's id. Temporary table names cannot be quoted
268
+ * (Msg 11717), so the base names are used as they are.
269
+ *
270
+ * @internal
271
+ */
272
+ async dropTempTables() {
273
+ const { rows } = await this.query("declare @db varchar(30) select @db = db_name(@@tempdbid) " +
274
+ "exec('select substring(name, 1, char_length(name) - 17) as name from ' + @db + " +
275
+ "'..sysobjects where type = ''U'' and name like ''#%'' " +
276
+ "and object_id(substring(name, 1, char_length(name) - 17)) = id')");
277
+ if (rows.length > 0) {
278
+ await this.query(rows.map(row => `drop table ${row.name}`).join("\n"));
279
+ }
64
280
  }
65
281
  async query(sql, options) {
282
+ validateQueryOptions(options);
66
283
  // Serialize queries on this connection — db-lib DBPROCESS is not reentrant.
67
284
  const task = this.queryQueue.then(() => this.executeQuery(sql, options));
68
285
  // Update queue head; swallow rejections so subsequent queries still run.
@@ -78,12 +295,14 @@ export class SybaseConnection {
78
295
  }
79
296
  const baseTimeoutS = this.config.timeout ?? 30;
80
297
  const nativeHardMs = options?.hardTimeoutMs ?? this.config.hardTimeoutMs;
298
+ // Mirrors the native default (see binding.c) so errors report the real value.
299
+ const effectiveHardMs = nativeHardMs ?? Math.max(baseTimeoutS * 2 * 1000, 30000);
81
300
  // JS-side fallback: even longer than the native watchdog. If THIS fires,
82
301
  // the native worker is stuck despite dbcancel — we bail at the JS layer
83
302
  // and mark the connection dead so the pool replaces it. The worker may
84
303
  // continue running until the OS finally gives up the socket; that's
85
304
  // acceptable because libuv's worker pool will reclaim the slot eventually.
86
- const jsHardMs = (nativeHardMs ?? Math.max(baseTimeoutS * 2 * 1000, 30000)) + 5000;
305
+ const jsHardMs = effectiveHardMs + 5000;
87
306
  let timer = null;
88
307
  const timeoutPromise = new Promise((_, reject) => {
89
308
  timer = setTimeout(() => {
@@ -115,7 +334,7 @@ export class SybaseConnection {
115
334
  // Native-side hard timeout — connection is dead.
116
335
  if (err && err.hardTimeout) {
117
336
  this.closed = true;
118
- throw new SybaseTimeoutError(err.message ?? "Query hard timeout", "query", baseTimeoutS * 2 * 1000);
337
+ throw new SybaseTimeoutError(err.message ?? "Query hard timeout", "query", effectiveHardMs);
119
338
  }
120
339
  // Cooperative timeout (db-lib's DBSETTIME fired). Connection itself
121
340
  // may still be usable, but to be safe we let the pool decide via
@@ -163,486 +382,5 @@ export class SybaseConnection {
163
382
  }
164
383
  return native.isAlive(this.handle);
165
384
  }
166
- /** @internal */
167
- get _inUse() {
168
- return this.inUse;
169
- }
170
- /** @internal */
171
- set _inUse(val) {
172
- this.inUse = val;
173
- }
174
- }
175
- /**
176
- * Production-grade connection pool for Sybase ASE.
177
- *
178
- * Features:
179
- * - max pool sizing with automatic scaling
180
- * - Health checks (dead connection detection + optional ping)
181
- * - Idle connection cleanup
182
- * - Acquire timeout with fair queuing
183
- * - Retry on transient connection failures
184
- * - Graceful drain/shutdown
185
- * - Observable metrics for monitoring
186
- * - Query logging middleware
187
- *
188
- * @example
189
- * ```ts
190
- * const pool = new SybasePool({
191
- * host: "sybase-host",
192
- * port: 5000,
193
- * database: "mydb",
194
- * username: "sa",
195
- * password: "secret",
196
- * max: 10,
197
- * logger: { query(log) { console.log(`[${log.durationMs}ms] ${log.sql}`); } }
198
- * });
199
- *
200
- * const result = await pool.query("SELECT 1 AS val");
201
- * console.log(pool.metrics);
202
- * await pool.drain();
203
- * ```
204
- */
205
- export class SybasePool {
206
- pool = [];
207
- waitQueue = [];
208
- closed = false;
209
- draining = false;
210
- cleanupTimer = null;
211
- cfg;
212
- // Metrics tracking
213
- _totalConnectionsCreated = 0;
214
- _totalConnectionsDestroyed = 0;
215
- _totalQueriesExecuted = 0;
216
- _totalQueryErrors = 0;
217
- _totalAcquireTimeouts = 0;
218
- _queryDurationSum = 0;
219
- _queryDurationCount = 0;
220
- _activeCount = 0;
221
- /** Number of connections currently being created (prevents exceeding max). */
222
- _pendingCreates = 0;
223
- constructor(config) {
224
- const max = config.max ?? 5;
225
- if (max < 1) {
226
- throw new SybasePoolError("Pool max must be at least 1", "closed");
227
- }
228
- // Before the cleanup timer is started, so an invalid zone cannot leave a
229
- // half-built pool behind.
230
- resolveTimeZone(config.timeZone);
231
- this.cfg = {
232
- ...config,
233
- timeout: config.timeout ?? 30,
234
- max,
235
- idleTimeoutMs: config.idleTimeoutMs ?? 60000,
236
- acquireTimeoutMs: config.acquireTimeoutMs ?? 10000,
237
- cleanupIntervalMs: config.cleanupIntervalMs ?? 30000,
238
- healthCheck: config.healthCheck ?? false,
239
- retries: config.retries ?? 2,
240
- retryDelayMs: config.retryDelayMs ?? 500,
241
- logger: config.logger
242
- };
243
- // Start idle cleanup timer
244
- this.cleanupTimer = setInterval(() => {
245
- this.cleanupIdle();
246
- }, this.cfg.cleanupIntervalMs);
247
- // Unref so it doesn't keep the process alive
248
- if (this.cleanupTimer && typeof this.cleanupTimer.unref === "function") {
249
- this.cleanupTimer.unref();
250
- }
251
- }
252
- /**
253
- * Acquire a connection from the pool.
254
- * - Validates existing connections (health check)
255
- * - Creates new connections up to `max`
256
- * - Queues if pool is full
257
- */
258
- async acquire() {
259
- if (this.closed) {
260
- throw new SybasePoolError("Pool is closed", "closed");
261
- }
262
- if (this.draining) {
263
- throw new SybasePoolError("Pool is draining — no new connections allowed", "draining");
264
- }
265
- // Try to find an idle, healthy connection
266
- for (let i = 0; i < this.pool.length; i++) {
267
- const pooled = this.pool[i];
268
- if (!pooled.inUse) {
269
- // Check if connection is still alive
270
- if (!pooled.conn.isConnected) {
271
- // Dead connection — remove and continue
272
- this.removeFromPool(i);
273
- i--;
274
- continue;
275
- }
276
- // Optional health check (lightweight query)
277
- if (this.cfg.healthCheck) {
278
- try {
279
- await pooled.conn.query("SELECT 1");
280
- }
281
- catch {
282
- // Health check failed — remove dead connection
283
- this.removeFromPool(i);
284
- i--;
285
- continue;
286
- }
287
- }
288
- pooled.inUse = true;
289
- pooled.conn._inUse = true;
290
- pooled.lastUsed = Date.now();
291
- this._activeCount++;
292
- return pooled.conn;
293
- }
294
- }
295
- // Can we create a new connection?
296
- if (this.pool.length + this._pendingCreates < this.cfg.max) {
297
- this._pendingCreates++;
298
- let conn;
299
- try {
300
- conn = await this.createConnection();
301
- }
302
- catch (err) {
303
- this._pendingCreates--;
304
- throw err;
305
- }
306
- this._pendingCreates--;
307
- // Re-check after async gap: another acquire may have filled pool
308
- if (this.pool.length >= this.cfg.max) {
309
- // Pool is full now — close the extra connection
310
- conn.close();
311
- this._totalConnectionsDestroyed++;
312
- // Fall through to wait queue below
313
- }
314
- else {
315
- const pooled = {
316
- conn,
317
- lastUsed: Date.now(),
318
- createdAt: Date.now(),
319
- inUse: true
320
- };
321
- conn._inUse = true;
322
- this._activeCount++;
323
- this.pool.push(pooled);
324
- return conn;
325
- }
326
- }
327
- // Pool full — wait for one to become available
328
- return new Promise((resolve, reject) => {
329
- const timer = setTimeout(() => {
330
- const idx = this.waitQueue.findIndex(w => w.resolve === resolve);
331
- if (idx !== -1) {
332
- this.waitQueue.splice(idx, 1);
333
- }
334
- this._totalAcquireTimeouts++;
335
- reject(new SybaseTimeoutError(`Connection acquire timeout after ${this.cfg.acquireTimeoutMs}ms`, "acquire", this.cfg.acquireTimeoutMs));
336
- }, this.cfg.acquireTimeoutMs);
337
- this.waitQueue.push({ resolve, reject, timer });
338
- });
339
- }
340
- /**
341
- * Release a connection back to the pool.
342
- */
343
- release(conn) {
344
- const pooled = this.pool.find(p => p.conn === conn);
345
- if (!pooled || !pooled.inUse) {
346
- // Already released or not in pool — ignore
347
- return;
348
- }
349
- pooled.inUse = false;
350
- conn._inUse = false;
351
- pooled.lastUsed = Date.now();
352
- this._activeCount--;
353
- // Note: SET ROWCOUNT is already reset to 0 within query batches by
354
- // SybaseSelectBuilder (appends "SET ROWCOUNT 0" after every paginated query).
355
- // We do NOT issue an async reset here to avoid race conditions where the
356
- // reset command would execute concurrently with the next user's query.
357
- // If connection died during use, remove it
358
- if (!conn.isConnected) {
359
- const idx = this.pool.indexOf(pooled);
360
- if (idx !== -1) {
361
- this.pool.splice(idx, 1);
362
- conn.close();
363
- this._totalConnectionsDestroyed++;
364
- }
365
- // Try to serve a waiter with a new connection (only if not draining)
366
- if (!this.draining) {
367
- void this.serveWaiter();
368
- }
369
- return;
370
- }
371
- // If draining and no in-use connections, we're done
372
- if (this.draining) {
373
- this.checkDrainComplete();
374
- return;
375
- }
376
- // If someone is waiting, give them this connection
377
- if (this.waitQueue.length > 0) {
378
- const waiter = this.waitQueue.shift();
379
- clearTimeout(waiter.timer);
380
- pooled.inUse = true;
381
- conn._inUse = true;
382
- pooled.lastUsed = Date.now();
383
- this._activeCount++;
384
- waiter.resolve(conn);
385
- }
386
- }
387
- /**
388
- * Execute a query using a pooled connection (auto acquire/release).
389
- * Retries on transient connection failures.
390
- */
391
- async query(sql, options) {
392
- let lastError = null;
393
- for (let attempt = 0; attempt <= this.cfg.retries; attempt++) {
394
- const conn = await this.acquire();
395
- const startTime = Date.now();
396
- try {
397
- const result = await conn.query(sql, options);
398
- const durationMs = Date.now() - startTime;
399
- this._totalQueriesExecuted++;
400
- this._queryDurationSum += durationMs;
401
- this._queryDurationCount++;
402
- // Log successful query
403
- if (this.cfg.logger) {
404
- this.cfg.logger.query({
405
- sql,
406
- durationMs,
407
- rowCount: result.rowCount,
408
- timestamp: new Date(startTime)
409
- });
410
- }
411
- this.release(conn);
412
- return result;
413
- }
414
- catch (err) {
415
- const durationMs = Date.now() - startTime;
416
- this._totalQueryErrors++;
417
- // Log failed query
418
- if (this.cfg.logger) {
419
- this.cfg.logger.query({
420
- sql,
421
- durationMs,
422
- rowCount: 0,
423
- error: err instanceof Error ? err : new Error(String(err)),
424
- timestamp: new Date(startTime)
425
- });
426
- }
427
- // Reset session state (SET ROWCOUNT) if connection is still alive
428
- // to prevent state leaking to the next query on this pooled connection.
429
- if (conn.isConnected) {
430
- try {
431
- await conn.query("SET ROWCOUNT 0");
432
- }
433
- catch {
434
- // If reset fails, connection will be detected dead on release
435
- }
436
- }
437
- this.release(conn);
438
- if (err instanceof SybaseConnectionError && attempt < this.cfg.retries) {
439
- // Transient failure — retry after delay
440
- lastError = err;
441
- await this.delay(this.cfg.retryDelayMs);
442
- continue;
443
- }
444
- throw err;
445
- }
446
- }
447
- throw lastError ?? new SybaseError("Query failed after retries");
448
- }
449
- /**
450
- * Gracefully drain the pool — finish all in-flight operations, then close.
451
- *
452
- * New acquire() calls will be rejected immediately.
453
- * Returns a promise that resolves when all active connections are released.
454
- *
455
- * @param timeoutMs - Maximum time to wait for drain. Default: 30000ms
456
- */
457
- async drain(timeoutMs = 30000) {
458
- if (this.closed) {
459
- return;
460
- }
461
- this.draining = true;
462
- // Reject all waiters immediately
463
- for (const waiter of this.waitQueue) {
464
- clearTimeout(waiter.timer);
465
- waiter.reject(new SybasePoolError("Pool is draining", "draining"));
466
- }
467
- this.waitQueue = [];
468
- // If no active connections, close immediately
469
- if (this.active === 0) {
470
- return this.close();
471
- }
472
- // Wait for all active connections to be released
473
- return new Promise((resolve, reject) => {
474
- const timer = setTimeout(() => {
475
- // Force close after timeout
476
- this.close().then(resolve, reject);
477
- }, timeoutMs);
478
- if (typeof timer.unref === "function") {
479
- timer.unref();
480
- }
481
- this._drainResolve = () => {
482
- clearTimeout(timer);
483
- this.close().then(resolve, reject);
484
- };
485
- });
486
- }
487
- _drainResolve;
488
- checkDrainComplete() {
489
- if (this.draining && this.active === 0 && this._drainResolve) {
490
- this._drainResolve();
491
- this._drainResolve = undefined;
492
- }
493
- }
494
- /**
495
- * Close all connections and shut down the pool.
496
- */
497
- async close() {
498
- this.closed = true;
499
- this.draining = false;
500
- // Stop cleanup timer
501
- if (this.cleanupTimer) {
502
- clearInterval(this.cleanupTimer);
503
- this.cleanupTimer = null;
504
- }
505
- // Reject all waiters
506
- for (const waiter of this.waitQueue) {
507
- clearTimeout(waiter.timer);
508
- waiter.reject(new SybasePoolError("Pool is closing", "closed"));
509
- }
510
- this.waitQueue = [];
511
- // Close all connections
512
- for (const pooled of this.pool) {
513
- pooled.conn.close();
514
- this._totalConnectionsDestroyed++;
515
- }
516
- this.pool = [];
517
- this._activeCount = 0;
518
- }
519
- // ---------------------------------------------------------------------------
520
- // Pool state accessors
521
- // ---------------------------------------------------------------------------
522
- /** Number of total connections in the pool. */
523
- get size() {
524
- return this.pool.length;
525
- }
526
- /** Number of idle (available) connections. */
527
- get idle() {
528
- return this.pool.length - this._activeCount;
529
- }
530
- /** Number of active (in-use) connections. */
531
- get active() {
532
- return this._activeCount;
533
- }
534
- /** Number of waiters in queue. */
535
- get waiting() {
536
- return this.waitQueue.length;
537
- }
538
- /** Whether the pool is currently draining. */
539
- get isDraining() {
540
- return this.draining;
541
- }
542
- /** Whether the pool is closed. */
543
- get isClosed() {
544
- return this.closed;
545
- }
546
- /** @internal Get the configured logger (if any). */
547
- get logger() {
548
- return this.cfg.logger;
549
- }
550
- /**
551
- * Get a snapshot of pool metrics for monitoring/observability.
552
- */
553
- get metrics() {
554
- return {
555
- totalConnectionsCreated: this._totalConnectionsCreated,
556
- totalConnectionsDestroyed: this._totalConnectionsDestroyed,
557
- totalQueriesExecuted: this._totalQueriesExecuted,
558
- totalQueryErrors: this._totalQueryErrors,
559
- totalAcquireTimeouts: this._totalAcquireTimeouts,
560
- avgQueryDurationMs: this._queryDurationCount > 0
561
- ? Math.round(this._queryDurationSum / this._queryDurationCount)
562
- : 0,
563
- currentSize: this.size,
564
- currentActive: this.active,
565
- currentIdle: this.idle,
566
- currentWaiting: this.waiting
567
- };
568
- }
569
- // ---------------------------------------------------------------------------
570
- // Private
571
- // ---------------------------------------------------------------------------
572
- async createConnection() {
573
- const conn = new SybaseConnection(this.cfg);
574
- await conn.connect();
575
- this._totalConnectionsCreated++;
576
- return conn;
577
- }
578
- removeFromPool(index) {
579
- const removed = this.pool.splice(index, 1)[0];
580
- if (removed) {
581
- removed.conn.close();
582
- this._totalConnectionsDestroyed++;
583
- }
584
- }
585
- async serveWaiter() {
586
- if (this.waitQueue.length === 0) {
587
- return;
588
- }
589
- this._pendingCreates++;
590
- try {
591
- const conn = await this.createConnection();
592
- this._pendingCreates--;
593
- const pooled = {
594
- conn,
595
- lastUsed: Date.now(),
596
- createdAt: Date.now(),
597
- inUse: true
598
- };
599
- conn._inUse = true;
600
- this._activeCount++;
601
- this.pool.push(pooled);
602
- // Re-check queue after async operation — waiter may have timed out
603
- const waiter = this.waitQueue.shift();
604
- if (waiter) {
605
- clearTimeout(waiter.timer);
606
- waiter.resolve(conn);
607
- }
608
- else {
609
- // No waiter left — release the connection back to idle
610
- pooled.inUse = false;
611
- conn._inUse = false;
612
- this._activeCount--;
613
- }
614
- }
615
- catch (err) {
616
- this._pendingCreates--;
617
- // Can't create connection — reject the first waiter if any
618
- const waiter = this.waitQueue.shift();
619
- if (waiter) {
620
- clearTimeout(waiter.timer);
621
- waiter.reject(err instanceof Error ? err : new SybaseError(String(err)));
622
- }
623
- }
624
- }
625
- /**
626
- * Remove idle connections that have exceeded the idle timeout.
627
- */
628
- cleanupIdle() {
629
- const now = Date.now();
630
- let i = 0;
631
- while (i < this.pool.length) {
632
- const pooled = this.pool[i];
633
- const isIdle = !pooled.inUse;
634
- const isExpired = now - pooled.lastUsed > this.cfg.idleTimeoutMs;
635
- if (isIdle && isExpired) {
636
- this.removeFromPool(i);
637
- // Don't increment i — the array shifted
638
- }
639
- else {
640
- i++;
641
- }
642
- }
643
- }
644
- delay(ms) {
645
- return new Promise(resolve => setTimeout(resolve, ms));
646
- }
647
385
  }
648
386
  //# sourceMappingURL=connection.js.map