neon 2.1.2 → 2.29.1

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 (166) hide show
  1. package/LICENSE.md +178 -0
  2. package/README.md +601 -0
  3. package/dist/analytics.js +156 -0
  4. package/dist/api.js +665 -0
  5. package/dist/auth.js +127 -0
  6. package/dist/callback.html +51 -0
  7. package/dist/cli.js +9 -0
  8. package/dist/commands/auth.js +214 -0
  9. package/dist/commands/bootstrap.js +481 -0
  10. package/dist/commands/branches.js +481 -0
  11. package/dist/commands/bucket.js +543 -0
  12. package/dist/commands/checkout.js +289 -0
  13. package/dist/commands/config.js +544 -0
  14. package/dist/commands/connection_string.js +172 -0
  15. package/dist/commands/data_api.js +285 -0
  16. package/dist/commands/databases.js +82 -0
  17. package/dist/commands/deploy.js +26 -0
  18. package/dist/commands/dev.js +698 -0
  19. package/dist/commands/env.js +166 -0
  20. package/dist/commands/functions.js +373 -0
  21. package/dist/commands/index.js +54 -0
  22. package/dist/commands/init.js +73 -0
  23. package/dist/commands/ip_allow.js +137 -0
  24. package/dist/commands/link.js +1121 -0
  25. package/dist/commands/neon_auth.js +1028 -0
  26. package/dist/commands/operations.js +28 -0
  27. package/dist/commands/orgs.js +24 -0
  28. package/dist/commands/projects.js +372 -0
  29. package/dist/commands/psql.js +62 -0
  30. package/dist/commands/roles.js +65 -0
  31. package/dist/commands/schema_diff.js +151 -0
  32. package/dist/commands/set_context.js +29 -0
  33. package/dist/commands/status.js +40 -0
  34. package/dist/commands/user.js +15 -0
  35. package/dist/commands/vpc_endpoints.js +134 -0
  36. package/dist/config.js +11 -0
  37. package/dist/config_format.js +72 -0
  38. package/dist/context.js +177 -0
  39. package/dist/current_branch_fast_path.js +55 -0
  40. package/dist/dev/env.js +240 -0
  41. package/dist/dev/functions.js +70 -0
  42. package/dist/dev/inputs.js +63 -0
  43. package/dist/dev/runtime.js +146 -0
  44. package/dist/env.js +36 -0
  45. package/dist/env_file.js +159 -0
  46. package/dist/errors.js +80 -0
  47. package/dist/functions_api.js +44 -0
  48. package/dist/help.js +146 -0
  49. package/dist/index.js +234 -0
  50. package/dist/log.js +18 -0
  51. package/dist/parameters.gen.js +480 -0
  52. package/dist/pkg.js +25 -0
  53. package/dist/psql/cli.js +53 -0
  54. package/dist/psql/command/cmd_cond.js +437 -0
  55. package/dist/psql/command/cmd_connect.js +820 -0
  56. package/dist/psql/command/cmd_copy.js +1035 -0
  57. package/dist/psql/command/cmd_describe.js +1815 -0
  58. package/dist/psql/command/cmd_format.js +922 -0
  59. package/dist/psql/command/cmd_io.js +2193 -0
  60. package/dist/psql/command/cmd_lo.js +393 -0
  61. package/dist/psql/command/cmd_meta.js +970 -0
  62. package/dist/psql/command/cmd_misc.js +187 -0
  63. package/dist/psql/command/cmd_pipeline.js +1148 -0
  64. package/dist/psql/command/cmd_restrict.js +171 -0
  65. package/dist/psql/command/cmd_show.js +766 -0
  66. package/dist/psql/command/dispatch.js +343 -0
  67. package/dist/psql/command/inputQueue.js +42 -0
  68. package/dist/psql/command/shared.js +71 -0
  69. package/dist/psql/complete/filenames.js +139 -0
  70. package/dist/psql/complete/index.js +104 -0
  71. package/dist/psql/complete/matcher.js +315 -0
  72. package/dist/psql/complete/psqlVars.js +247 -0
  73. package/dist/psql/complete/queries.js +493 -0
  74. package/dist/psql/complete/rules.js +2424 -0
  75. package/dist/psql/core/common.js +1253 -0
  76. package/dist/psql/core/help.js +576 -0
  77. package/dist/psql/core/mainloop.js +1360 -0
  78. package/dist/psql/core/prompt.js +440 -0
  79. package/dist/psql/core/settings.js +684 -0
  80. package/dist/psql/core/sqlHelp.js +1066 -0
  81. package/dist/psql/core/startup.js +846 -0
  82. package/dist/psql/core/syncVars.js +116 -0
  83. package/dist/psql/core/variables.js +287 -0
  84. package/dist/psql/describe/formatters.js +1290 -0
  85. package/dist/psql/describe/processNamePattern.js +270 -0
  86. package/dist/psql/describe/queries.js +2378 -0
  87. package/dist/psql/describe/versionGate.js +43 -0
  88. package/dist/psql/index.js +2030 -0
  89. package/dist/psql/io/history.js +299 -0
  90. package/dist/psql/io/input.js +120 -0
  91. package/dist/psql/io/lineEditor/buffer.js +325 -0
  92. package/dist/psql/io/lineEditor/complete.js +227 -0
  93. package/dist/psql/io/lineEditor/filename.js +159 -0
  94. package/dist/psql/io/lineEditor/index.js +894 -0
  95. package/dist/psql/io/lineEditor/keymap.js +745 -0
  96. package/dist/psql/io/lineEditor/vt100.js +363 -0
  97. package/dist/psql/io/pgpass.js +202 -0
  98. package/dist/psql/io/pgservice.js +194 -0
  99. package/dist/psql/io/psqlrc.js +422 -0
  100. package/dist/psql/print/aligned.js +1765 -0
  101. package/dist/psql/print/asciidoc.js +248 -0
  102. package/dist/psql/print/crosstab.js +463 -0
  103. package/dist/psql/print/csv.js +95 -0
  104. package/dist/psql/print/html.js +258 -0
  105. package/dist/psql/print/json.js +96 -0
  106. package/dist/psql/print/latex.js +396 -0
  107. package/dist/psql/print/pager.js +267 -0
  108. package/dist/psql/print/troff.js +258 -0
  109. package/dist/psql/print/unaligned.js +119 -0
  110. package/dist/psql/print/units.js +135 -0
  111. package/dist/psql/scanner/slash.js +515 -0
  112. package/dist/psql/scanner/sql.js +914 -0
  113. package/dist/psql/scanner/stringutils.js +394 -0
  114. package/dist/psql/types/backslash.js +1 -0
  115. package/dist/psql/types/connection.js +1 -0
  116. package/dist/psql/types/index.js +7 -0
  117. package/dist/psql/types/printer.js +1 -0
  118. package/dist/psql/types/repl.js +1 -0
  119. package/dist/psql/types/scanner.js +24 -0
  120. package/dist/psql/types/settings.js +1 -0
  121. package/dist/psql/types/variables.js +1 -0
  122. package/dist/psql/wire/connection.js +2858 -0
  123. package/dist/psql/wire/copy.js +108 -0
  124. package/dist/psql/wire/notify.js +59 -0
  125. package/dist/psql/wire/pipeline.js +521 -0
  126. package/dist/psql/wire/protocol.js +466 -0
  127. package/dist/psql/wire/sasl.js +296 -0
  128. package/dist/psql/wire/tls.js +602 -0
  129. package/dist/storage_api.js +147 -0
  130. package/dist/test_utils/fixtures.js +122 -0
  131. package/dist/test_utils/oauth_server.js +9 -0
  132. package/dist/types.js +1 -0
  133. package/dist/utils/api_enums.js +33 -0
  134. package/dist/utils/auth.js +5 -0
  135. package/dist/utils/branch_notice.js +22 -0
  136. package/dist/utils/branch_picker.js +103 -0
  137. package/dist/utils/compute_units.js +28 -0
  138. package/dist/utils/enrichers.js +161 -0
  139. package/dist/utils/esbuild.js +158 -0
  140. package/dist/utils/formats.js +18 -0
  141. package/dist/utils/middlewares.js +20 -0
  142. package/dist/utils/package_manager.js +68 -0
  143. package/dist/utils/point_in_time.js +56 -0
  144. package/dist/utils/psql.js +120 -0
  145. package/dist/utils/string.js +5 -0
  146. package/dist/utils/ui.js +59 -0
  147. package/dist/utils/zip.js +4 -0
  148. package/dist/writer.js +97 -0
  149. package/package.json +117 -14
  150. package/.jshintrc +0 -3
  151. package/CHANGELOG.markdown +0 -22
  152. package/LICENSE +0 -21
  153. package/README.markdown +0 -76
  154. package/bower.json +0 -23
  155. package/license.txt +0 -9
  156. package/neon.js +0 -234
  157. package/stdlib/bubbling_support.js +0 -32
  158. package/stdlib/custom_event.js +0 -54
  159. package/stdlib/custom_event_support.js +0 -195
  160. package/stdlib/index.js +0 -7
  161. package/stdlib/node_support.js +0 -123
  162. package/stdlib/widget.js +0 -340
  163. package/test/neon_browser.html +0 -11
  164. package/test/neon_stdlib_browser.html +0 -15
  165. package/test/neon_stdlib_test.js +0 -84
  166. package/test/neon_test.js +0 -64
@@ -0,0 +1,2858 @@
1
+ /**
2
+ * PgConnection — the wire-layer Connection implementation (WP-02 + WP-16).
3
+ *
4
+ * Implements `Connection` (frozen WP-00 interface in
5
+ * `src/psql/types/connection.ts`) on top of a single TCP / TLS socket. The
6
+ * class is essentially a state machine:
7
+ *
8
+ * auth → drive Authentication* messages
9
+ * await-ready → collect ParameterStatus + BackendKeyData
10
+ * idle → ready for a Query / extended-protocol cycle
11
+ * in-query → simple Query in flight, accumulating ResultSets
12
+ * in-copy-in → COPY FROM STDIN data transfer in progress (WP-16)
13
+ * in-copy-out → COPY TO STDOUT data transfer in progress (WP-16)
14
+ * closed → socket gone
15
+ *
16
+ * What this module owns:
17
+ * - Socket lifecycle (open, optional TLS, Terminate, close).
18
+ * - Auth: Cleartext, MD5, SASL/SCRAM (delegating to ./sasl.ts).
19
+ * - Tracking server `serverVersion` from ParameterStatus.
20
+ * - Simple-query path (`execSimple`) — collect RowDescription/DataRow/
21
+ * CommandComplete tuples into ResultSet[].
22
+ * - Async messages (Notice, Notification) routed through ./notify.ts.
23
+ * - ErrorResponse → rejected promise mapped to ConnectError shape.
24
+ * - Async cancel via a side connection (CancelRequest).
25
+ * - COPY streaming (WP-16): `startCopyIn` returns a `CopyInStream` that
26
+ * wires CopyData / CopyDone / CopyFail; `startCopyOut` returns an
27
+ * `AsyncIterable<Buffer>` that drains CopyData messages from the wire.
28
+ * The state machine threads through `in-copy-in` / `in-copy-out`.
29
+ *
30
+ * What is stubbed / deferred:
31
+ * - Extended-query protocol (Parse/Bind/Execute/Sync). The framing is in
32
+ * protocol.ts but the high-level path (parameterised `query()`, prepared
33
+ * statements, pipeline) is WP-21. We throw clearly when called.
34
+ */
35
+ import { Buffer } from "node:buffer";
36
+ import { createHash } from "node:crypto";
37
+ import * as dns from "node:dns/promises";
38
+ import * as net from "node:net";
39
+ import * as tls from "node:tls";
40
+ import { NoticeMultiplexer } from "./notify.js";
41
+ import { PipelineSession } from "./pipeline.js";
42
+ import { Bind, CancelRequest, Close, CopyData, CopyDone, CopyFail, Describe, Execute, fieldsToNotice, MessageParser, Parse, PasswordMessage, Query, SASLInitialResponse, SASLResponse, StartupMessage, Sync, Terminate, } from "./protocol.js";
43
+ import { createScramClient } from "./sasl.js";
44
+ import { negotiateTls } from "./tls.js";
45
+ /**
46
+ * Map a Notice-flavoured fields map into a `ConnectError` that includes a
47
+ * recognizable `message` plus a `cause` slot for the raw record.
48
+ */
49
+ function fieldsToConnectError(fields) {
50
+ return { ...fieldsToNotice(fields), cause: fields };
51
+ }
52
+ /**
53
+ * Synthetic ConnectError used as the rejection reason for queued
54
+ * pipeline ops that the server skipped after a preceding ErrorResponse.
55
+ * Mirrors libpq's `PGRES_PIPELINE_ABORTED` result — the message text
56
+ * matches the string libpq stamps onto skipped ops so the cmd layer
57
+ * can render it byte-identically with vanilla psql's `\getresults` /
58
+ * `\endpipeline` output.
59
+ */
60
+ function pipelineAbortedError() {
61
+ return {
62
+ severity: "ERROR",
63
+ code: "",
64
+ message: "Pipeline aborted, command did not run",
65
+ pipelineAborted: true,
66
+ };
67
+ }
68
+ /** Parse "PostgreSQL 16.2 …" into a numeric `major * 10000 + minor * 100`. */
69
+ function parseServerVersion(value) {
70
+ // libpq's PQserverVersion returns NNNNNN (e.g. 160002 for 16.2). For
71
+ // pre-10 versions the layout was NNMMSS (e.g. 90608 for 9.6.8). Our
72
+ // consumers only need monotonic comparability and a major-version
73
+ // accessor; the libpq formula is the simplest match.
74
+ const m = /^([0-9]+)(?:\.([0-9]+))?(?:\.([0-9]+))?/.exec(value);
75
+ if (!m)
76
+ return 0;
77
+ const major = parseInt(m[1], 10);
78
+ const minor = m[2] !== undefined ? parseInt(m[2], 10) : 0;
79
+ if (major >= 10) {
80
+ return major * 10000 + minor;
81
+ }
82
+ const patch = m[3] !== undefined ? parseInt(m[3], 10) : 0;
83
+ return major * 10000 + minor * 100 + patch;
84
+ }
85
+ /**
86
+ * MD5 auth: `'md5' + md5( md5(password + user) || salt )`. Inner hash uses
87
+ * the username; outer is salted. PG uses lowercase hex everywhere.
88
+ */
89
+ function md5AuthPayload(user, password, salt) {
90
+ const inner = createHash("md5")
91
+ .update(password + user, "utf8")
92
+ .digest("hex");
93
+ const outer = createHash("md5")
94
+ .update(inner, "utf8")
95
+ .update(salt)
96
+ .digest("hex");
97
+ return "md5" + outer;
98
+ }
99
+ /**
100
+ * Fisher-Yates in-place shuffle of the candidate hosts list. Used by
101
+ * `load_balance_hosts=random`. Hook the random source so tests can inject a
102
+ * deterministic permutation.
103
+ */
104
+ function shuffleInPlace(arr, rng = Math.random) {
105
+ for (let i = arr.length - 1; i > 0; i -= 1) {
106
+ const j = Math.floor(rng() * (i + 1));
107
+ const tmp = arr[i];
108
+ arr[i] = arr[j];
109
+ arr[j] = tmp;
110
+ }
111
+ }
112
+ /**
113
+ * After a successful handshake, decide whether this connection matches the
114
+ * caller's `target_session_attrs` constraint by running
115
+ * `SELECT pg_is_in_recovery()`. Returns `true` if the connection is
116
+ * acceptable, `false` if it should be torn down and the next host tried.
117
+ *
118
+ * - 'any' (or undefined) — always accepts.
119
+ * - 'read-write' / 'primary' — accepts when NOT in recovery.
120
+ * - 'read-only' / 'standby' — accepts when IN recovery.
121
+ *
122
+ * If the probe query itself fails we treat the connection as unacceptable
123
+ * (returns false) so the orchestrator falls through to the next candidate
124
+ * rather than handing the caller a half-broken connection.
125
+ */
126
+ async function checkSessionAttrs(conn, tsa) {
127
+ if (tsa === undefined || tsa === "any")
128
+ return true;
129
+ let inRecovery;
130
+ try {
131
+ const sets = await conn.execSimple("SELECT pg_is_in_recovery()");
132
+ if (sets.length === 0 || sets[0].rows.length === 0) {
133
+ return false;
134
+ }
135
+ const raw = sets[0].rows[0][0];
136
+ // pg_is_in_recovery returns boolean; text-format rows surface as
137
+ // 't' / 'f'. Be liberal: also handle 'true' / 'false'.
138
+ if (raw === true) {
139
+ inRecovery = true;
140
+ }
141
+ else if (raw === false) {
142
+ inRecovery = false;
143
+ }
144
+ else if (typeof raw === "string") {
145
+ inRecovery = raw === "t" || raw.toLowerCase() === "true";
146
+ }
147
+ else {
148
+ return false;
149
+ }
150
+ }
151
+ catch {
152
+ return false;
153
+ }
154
+ switch (tsa) {
155
+ case "read-write":
156
+ case "primary":
157
+ return !inRecovery;
158
+ case "read-only":
159
+ case "standby":
160
+ return inRecovery;
161
+ // 'prefer-standby' is unwrapped by the orchestrator into two passes
162
+ // ('standby' then 'any'), so we never see it here. Fall through to
163
+ // accept-any for safety.
164
+ default:
165
+ return true;
166
+ }
167
+ }
168
+ /**
169
+ * COPY-OUT backpressure thresholds (bytes). When buffered data exceeds the
170
+ * high-water mark we pause the socket; the consumer's `next()` resumes it once
171
+ * it drains below the low-water mark. Bounds RSS for a server that produces
172
+ * rows faster than the sink consumes them (review item #11).
173
+ */
174
+ const COPY_OUT_HWM = 8 * 1024 * 1024;
175
+ const COPY_OUT_LWM = 1 * 1024 * 1024;
176
+ export class PgConnection {
177
+ /**
178
+ * Queue one COPY-FROM-STDIN data block. Call once per expected
179
+ * CopyInResponse, in the order they will arrive during the upcoming
180
+ * `execSimple`. The mainloop owns the parsing of `\.`-terminated stdin
181
+ * blocks; we just buffer the raw bytes and ship them when the server is
182
+ * ready.
183
+ */
184
+ queueCopyInData(data) {
185
+ this.copyInMidBatchQueue.push(data);
186
+ }
187
+ /** Drop any queued COPY-FROM-STDIN data blocks. */
188
+ clearCopyInDataQueue() {
189
+ this.copyInMidBatchQueue.length = 0;
190
+ }
191
+ constructor(socket, opts, channelBindingData) {
192
+ this.parser = new MessageParser();
193
+ // -- Backend state
194
+ this.serverVersion = 0;
195
+ this.params = new Map();
196
+ this.processId = 0;
197
+ this.secretKey = 0;
198
+ this.txStatus = "I";
199
+ // -- Connection state machine
200
+ this.state = "auth";
201
+ this.pendingQuery = null;
202
+ this.extDriver = null;
203
+ /** True when `pipeline()` has handed out a PipelineSession (WP-21). */
204
+ this._extPipelineActive = false;
205
+ this.copyIn = null;
206
+ this.copyOut = null;
207
+ /**
208
+ * Resolver for `startCopyIn` / `startCopyOut`. Captured when the caller has
209
+ * already wired the `Query(COPY …)` and is now waiting for the server's
210
+ * CopyInResponse / CopyOutResponse to confirm that the protocol switched.
211
+ */
212
+ this.copyStartResolve = null;
213
+ this.copyStartReject = null;
214
+ /**
215
+ * Last-COPY command tag (e.g. `"COPY 17"`), or `null` if no COPY has run
216
+ * since connection startup. Used by the `\copy` command runner to print the
217
+ * upstream-style "COPY N" footer.
218
+ */
219
+ this.lastCopyTag = null;
220
+ /**
221
+ * Pre-buffered CopyData payloads keyed to the order of CopyInResponse
222
+ * messages we expect to see during the next `execSimple`. Used to drive
223
+ * `COPY ... FROM STDIN` segments that appear as part of a `\;`-chained
224
+ * simple-query batch — the mainloop pre-scans its input for `\.`-terminated
225
+ * COPY data blocks, hands the bytes in here, and the in-query dispatcher
226
+ * pops the head buffer when a CopyInResponse arrives. Each buffer becomes
227
+ * one CopyData frame followed by CopyDone (the upstream wire shape).
228
+ *
229
+ * If the queue is empty when CopyInResponse arrives, the wire layer falls
230
+ * back to CopyFail so the connection doesn't deadlock.
231
+ */
232
+ this.copyInMidBatchQueue = [];
233
+ /**
234
+ * Sink for COPY-TO-STDOUT mid-batch data. When `COPY ... TO STDOUT` is one
235
+ * segment of a `\;`-chained simple-query batch, the server pushes CopyData
236
+ * messages to us mid-`execSimple`. With no `startCopyOut` driver active,
237
+ * upstream `handleCopyOut` would write the bytes verbatim to the caller's
238
+ * output stream. We expose a settable sink so the mainloop can wire stdout
239
+ * (or any other WritableStream); if unset, the bytes are dropped (matching
240
+ * libpq's behaviour when `PQexec` lacks a copy handler — the data still
241
+ * gets consumed off the wire so the protocol stays in sync, but is
242
+ * silently discarded).
243
+ */
244
+ this.copyOutMidBatchSink = null;
245
+ /**
246
+ * Mid-batch COPY-OUT state. While `true`, CopyData/CopyDone messages
247
+ * arriving in `handleQueryMessage` are routed to the sink rather than
248
+ * triggering the "unexpected message" diagnostic. Flipped on by
249
+ * CopyOutResponse and off again when CopyDone arrives.
250
+ */
251
+ this.copyOutMidBatchActive = false;
252
+ /**
253
+ * Set to `true` once we actually respond to a server password challenge
254
+ * (cleartext, MD5, or the SASL/SCRAM exchange). Mirrors libpq's
255
+ * `conn->password_needed`, which `\conninfo` reports as "Password Used".
256
+ * A trust/cert/peer login leaves this `false` — the password may have been
257
+ * supplied but was never sent.
258
+ */
259
+ this.passwordUsed = false;
260
+ // -- Async messages
261
+ this.notify = new NoticeMultiplexer();
262
+ // -- Auth state (only used during state=auth)
263
+ this.scram = null;
264
+ /**
265
+ * True once the server has sent ANY authentication challenge (Cleartext,
266
+ * MD5, SASL, ...). Used by the AuthenticationOk handler to distinguish
267
+ * "server picked trust/cert auth" (no challenge, method=`none`) from
268
+ * "server just completed a SASL exchange" (challenge seen, method
269
+ * already validated when the challenge arrived).
270
+ */
271
+ this.authChallengeSeen = false;
272
+ /**
273
+ * True once `AuthenticationSASLFinal` arrived AND `scram.finish()` verified
274
+ * the server signature (RFC 5802 §3 mutual auth). Used to reject an
275
+ * `AuthenticationOk` that skips SASLFinal — a rogue/MITM server that doesn't
276
+ * know the password could otherwise send SASLContinue then jump straight to
277
+ * AuthenticationOk and never have its signature checked (review item #8).
278
+ */
279
+ this.saslFinalSeen = false;
280
+ // -- Error-after-close guard
281
+ this.socketError = null;
282
+ this.startupResolve = null;
283
+ this.startupReject = null;
284
+ this.socket = socket;
285
+ this.opts = opts;
286
+ this.channelBindingData = channelBindingData;
287
+ this._password = opts.password ?? null;
288
+ socket.on("data", (chunk) => {
289
+ this.onData(chunk);
290
+ });
291
+ socket.on("error", (err) => {
292
+ this.socketError = err;
293
+ this.failPending(err);
294
+ });
295
+ socket.on("close", () => {
296
+ if (this.state !== "closed") {
297
+ this.state = "closed";
298
+ this.failPending(this.socketError ?? new Error("Socket closed"));
299
+ }
300
+ });
301
+ }
302
+ /**
303
+ * Open a Postgres connection. Supports multi-host (`opts.hosts`) with
304
+ * sequential or random iteration, a `target_session_attrs` filter, and the
305
+ * libpq-style `prefer-standby` two-pass fallback.
306
+ *
307
+ * Iteration semantics:
308
+ * 1. Build the candidate list from `opts.hosts` (preferred) or
309
+ * `[{host: opts.host, port: opts.port}]`.
310
+ * 2. If `loadBalanceHosts === 'random'`, Fisher-Yates shuffle in place.
311
+ * 3. For each candidate (in order), attempt: openSocket → TLS → auth →
312
+ * startup. On failure, record the error and try the next.
313
+ * 4. On successful handshake, if `target_session_attrs` is restrictive,
314
+ * run `SELECT pg_is_in_recovery()`. If the role doesn't match, close
315
+ * this connection and try the next.
316
+ * 5. `prefer-standby` runs TWO passes: first accepting only standbys,
317
+ * second falling back to any host.
318
+ * 6. If no candidate succeeds, throw the LAST encountered error
319
+ * (preserves the most-recent failure mode for diagnostics).
320
+ */
321
+ static async connect(opts) {
322
+ const seed = opts.hosts !== undefined && opts.hosts.length > 0
323
+ ? [...opts.hosts]
324
+ : [{ host: opts.host, port: opts.port }];
325
+ // DNS fan-out: a single hostname can resolve to multiple A/AAAA records,
326
+ // and libpq treats each resulting IP as its own candidate so the
327
+ // iteration walks the FLAT (ip, port) list, not the (hostname, port)
328
+ // list. Each candidate carries BOTH the original hostname (for TLS
329
+ // SNI / SAN verification + `conn.host` reporting) AND the resolved
330
+ // address (used only by `net.connect`). Unix-domain socket paths
331
+ // and IP literals bypass the lookup — they become `{host, port}`
332
+ // with no address override.
333
+ //
334
+ // Active for every mode, not just `load_balance_hosts=random`: even
335
+ // `disable` benefits from the fall-through behaviour when the first
336
+ // A record is dead. Mirrors upstream `004_load_balance_dns.pl`.
337
+ //
338
+ // `hostaddr` short-circuits the lookup entirely: libpq connects to the
339
+ // fixed IP without consulting DNS while still using `host` for TLS SNI /
340
+ // certificate hostname verification. We map this onto the same
341
+ // `addressOverride` seam the DNS fan-out uses — the literal IP becomes
342
+ // the candidate's `address`, and `host` (the user-typed name) is
343
+ // preserved for SNI / `conn.host`. Only the single-host form carries a
344
+ // `hostaddr`; libpq does not support a hostaddr-per-host list here.
345
+ const candidates = opts.hostaddr !== undefined && opts.hostaddr !== ""
346
+ ? seed.map((c) => ({
347
+ host: c.host,
348
+ address: opts.hostaddr,
349
+ port: c.port,
350
+ }))
351
+ : await expandHostsViaDns(seed);
352
+ if (opts.loadBalanceHosts === "random") {
353
+ shuffleInPlace(candidates, PgConnection._loadBalanceRng ?? Math.random);
354
+ }
355
+ const tsa = opts.targetSessionAttrs ?? "any";
356
+ // `prefer-standby` runs two passes: first 'standby', then 'any'. Every
357
+ // other mode runs a single pass with the literal target.
358
+ const passes = tsa === "prefer-standby" ? ["standby", "any"] : [tsa];
359
+ let lastErr = null;
360
+ for (const passTsa of passes) {
361
+ for (const candidate of candidates) {
362
+ const candidateOpts = {
363
+ ...opts,
364
+ host: candidate.host,
365
+ port: candidate.port,
366
+ };
367
+ let conn;
368
+ try {
369
+ conn = await PgConnection.connectSingle(candidateOpts, candidate.address);
370
+ }
371
+ catch (err) {
372
+ lastErr = err;
373
+ continue;
374
+ }
375
+ // Apply target_session_attrs filter via pg_is_in_recovery().
376
+ const accepted = await checkSessionAttrs(conn, passTsa);
377
+ if (accepted) {
378
+ return conn;
379
+ }
380
+ // Mismatch: close this connection and move on.
381
+ try {
382
+ await conn.close();
383
+ }
384
+ catch {
385
+ // ignore
386
+ }
387
+ lastErr = new Error(`target_session_attrs=${String(passTsa)} did not match host ${candidate.host}:${String(candidate.port)}`);
388
+ }
389
+ }
390
+ if (lastErr !== null) {
391
+ // `throw lastErr` would trip the `only-throw-error` lint rule because
392
+ // `lastErr` is typed `unknown`. Normalise to an Error for the throw
393
+ // while preserving the original via `cause` so callers can introspect.
394
+ if (lastErr instanceof Error)
395
+ throw lastErr;
396
+ let message;
397
+ if (typeof lastErr === "object" &&
398
+ lastErr !== null &&
399
+ "message" in lastErr &&
400
+ typeof lastErr.message === "string") {
401
+ message = lastErr.message;
402
+ }
403
+ else if (typeof lastErr === "string" ||
404
+ typeof lastErr === "number" ||
405
+ typeof lastErr === "boolean") {
406
+ message = String(lastErr);
407
+ }
408
+ else {
409
+ message = "PgConnection.connect: unknown error";
410
+ }
411
+ const wrapped = new Error(message);
412
+ wrapped.cause = lastErr;
413
+ throw wrapped;
414
+ }
415
+ throw new Error("PgConnection.connect: no candidate hosts configured");
416
+ }
417
+ /**
418
+ * Per-host connect attempt: open the socket, negotiate TLS, run the auth
419
+ * dance, complete startup. Same shape as the pre-multihost `connect()`;
420
+ * the multi-host orchestrator above wraps this for each candidate.
421
+ */
422
+ static async connectSingle(opts,
423
+ /**
424
+ * Optional resolved IP address. When set, `openSocket` uses it for the
425
+ * actual `net.connect({host: address})`. `opts.host` remains the
426
+ * user-typed hostname so TLS SNI / SAN verification and `conn.host`
427
+ * report the original identity. Set by the DNS fan-out in `connect()`.
428
+ */
429
+ addressOverride) {
430
+ // TLS over Unix-domain sockets is meaningless (the kernel guarantees
431
+ // the channel) and libpq refuses `sslmode=require|verify-*` for socket
432
+ // connections. We mirror the early rejection so a misconfigured caller
433
+ // gets a clear diagnostic instead of a confused TLS handshake.
434
+ if (isUnixSocketHost(opts.host) &&
435
+ (opts.ssl === "require" ||
436
+ opts.ssl === "verify-ca" ||
437
+ opts.ssl === "verify-full")) {
438
+ throw new Error(`sslmode=${opts.ssl} is not supported over Unix-domain sockets (host=${opts.host})`);
439
+ }
440
+ // libpq `requirepeer`: for Unix-domain sockets, libpq verifies the server
441
+ // process runs as the named OS user via peer credentials (getpeereid /
442
+ // SO_PEERCRED). Node exposes NO portable peer-credential API for Unix
443
+ // sockets, so we CANNOT enforce this. We honestly do NOT verify it — to
444
+ // avoid pretending a security check passed, we reject the connection with
445
+ // a clear diagnostic when `requirepeer` is set on a socket connection,
446
+ // rather than silently connecting as if the check had succeeded. (TCP
447
+ // connections ignore `requirepeer`, matching libpq.)
448
+ if (isUnixSocketHost(opts.host) &&
449
+ opts.requirepeer !== undefined &&
450
+ opts.requirepeer !== "") {
451
+ throw new Error(`requirepeer="${opts.requirepeer}" cannot be enforced: Node provides no ` +
452
+ `Unix-domain socket peer-credential API; refusing to connect rather ` +
453
+ `than skip the check`);
454
+ }
455
+ const rawSocket = await openSocket(opts, addressOverride);
456
+ let socket = rawSocket;
457
+ let channelBindingData = null;
458
+ try {
459
+ // verify-ca skips hostname check; verify-full = default Node behavior.
460
+ // require/prefer/allow accept any cert chain (libpq default).
461
+ // NOTE: do NOT set `checkServerIdentity: undefined` — newer Node
462
+ // versions reject that with "must be of type function". Omit the
463
+ // property when verify-full so the default validator runs.
464
+ // libpq `sslsni=0` suppresses the TLS SNI extension: omit `servername`
465
+ // entirely so no hostname is sent in the ClientHello. Default (unset /
466
+ // true) sends SNI = the connection host, as libpq does.
467
+ const servername = tlsServername(opts);
468
+ const tlsConnectionOptions = {
469
+ ...(servername !== undefined ? { servername } : {}),
470
+ rejectUnauthorized: opts.ssl === "verify-ca" || opts.ssl === "verify-full",
471
+ // PG 17+ advertises ALPN for the 'postgresql' protocol; libpq sets
472
+ // this so a future-proof TLS proxy can route on ALPN instead of
473
+ // probing the wire. Always offer it — older servers ignore.
474
+ ALPNProtocols: ["postgresql"],
475
+ // Cipher preference is left to the runtime's TLS library. Our
476
+ // ClientHello offers the byte-identical TLS-1.3 ciphersuite list and
477
+ // order as libpq (AES-256-GCM, ChaCha20, AES-128-GCM), so the suite
478
+ // is the server's choice from an identical offer. Under Node
479
+ // (OpenSSL) that lands on AES-256-GCM, matching vanilla psql; under
480
+ // Bun (BoringSSL) it lands on AES-128-GCM. Both are TLS-1.3 AEAD
481
+ // suites with no practical security difference, and neither runtime
482
+ // exposes a client-side knob to steer TLS-1.3 selection (`ciphers`
483
+ // is TLS-1.2-only; `ciphersuites`/secureContext are ignored for the
484
+ // client offer), so this is left as-is.
485
+ };
486
+ if (opts.ssl !== "verify-full") {
487
+ tlsConnectionOptions.checkServerIdentity = () => undefined;
488
+ }
489
+ else if (opts.sslsni === false) {
490
+ // verify-full still verifies the peer name against `host`, but with
491
+ // SNI suppressed Node has no `servername` to drive its default
492
+ // identity check — so verify explicitly against the connection host.
493
+ // (libpq decouples SNI (sslsni) from peer-name verification (sslmode);
494
+ // we mirror that here.)
495
+ tlsConnectionOptions.checkServerIdentity = (_host, cert) => tls.checkServerIdentity(opts.host, cert);
496
+ }
497
+ applyTlsProtocolVersionRange(tlsConnectionOptions, opts);
498
+ const tlsResult = await negotiateTls(rawSocket,
499
+ // libpq refuses TLS on a socket connection even for sslmode=allow /
500
+ // prefer — instead of negotiating it just stays plain. We short-
501
+ // circuit by passing 'disable' to negotiateTls; the caller's
502
+ // requested sslmode is preserved on opts for error reporting.
503
+ isUnixSocketHost(opts.host) ? "disable" : opts.ssl, tlsConnectionOptions, {
504
+ sslcert: opts.sslcert,
505
+ sslkey: opts.sslkey,
506
+ sslcertmode: opts.sslcertmode,
507
+ sslpassword: opts.sslpassword,
508
+ sslrootcert: opts.sslrootcert,
509
+ sslcrl: opts.sslcrl,
510
+ sslcrldir: opts.sslcrldir,
511
+ sslkeylogfile: opts.sslkeylogfile,
512
+ },
513
+ // libpq `sslnegotiation=direct` (PG 17+): start TLS without the
514
+ // SSLRequest probe. Never reached for Unix-domain sockets (forced to
515
+ // sslmode 'disable' above) — direct SSL is a TCP-only concept. The
516
+ // ALPN protocol is already on `tlsConnectionOptions` for both paths.
517
+ isUnixSocketHost(opts.host)
518
+ ? "postgres"
519
+ : (opts.sslnegotiation ?? "postgres"));
520
+ if (tlsResult.kind === "tls") {
521
+ socket = tlsResult.socket;
522
+ channelBindingData = tlsResult.channelBindingData;
523
+ }
524
+ else {
525
+ socket = tlsResult.socket;
526
+ }
527
+ }
528
+ catch (err) {
529
+ try {
530
+ rawSocket.destroy();
531
+ }
532
+ catch {
533
+ // ignore
534
+ }
535
+ throw err;
536
+ }
537
+ const conn = new PgConnection(socket, opts, channelBindingData);
538
+ await conn.startup();
539
+ return conn;
540
+ }
541
+ // -------------------------------------------------------------------------
542
+ // Connection interface — public methods
543
+ // -------------------------------------------------------------------------
544
+ parameterStatus(name) {
545
+ return this.params.get(name);
546
+ }
547
+ /**
548
+ * Expose the connection target as `meta.database` / `meta.user` / `meta.host`
549
+ * / `meta.port` / `meta.pid` so the prompt renderer (which duck-types these
550
+ * via `MaybeWithMeta`) can render `%/`, `%n`, `%m`, `%>`, `%p` without
551
+ * additional plumbing. Postgres doesn't emit a `database` ParameterStatus,
552
+ * so these come from the connect opts / BackendKeyData.
553
+ */
554
+ get database() {
555
+ return this.opts.database;
556
+ }
557
+ get user() {
558
+ return this.opts.user;
559
+ }
560
+ get host() {
561
+ return this.opts.host;
562
+ }
563
+ get port() {
564
+ return this.opts.port;
565
+ }
566
+ get pid() {
567
+ return this.processId;
568
+ }
569
+ /**
570
+ * The password supplied at connect time (or `null`). Mirrors libpq's
571
+ * retention of the password on the live `PGconn` so `\c <newdb>` can
572
+ * reconnect transparently. Read-only by design — the field is set once in
573
+ * the constructor and never mutated.
574
+ */
575
+ get password() {
576
+ return this._password;
577
+ }
578
+ /**
579
+ * If the connection was upgraded to TLS during negotiation, return the
580
+ * cipher info for the active session. Returns `null` for plain-text
581
+ * connections. Used by the startup banner to render an `SSL connection
582
+ * (protocol: …, cipher: …)` line that mirrors upstream psql, and by
583
+ * `\conninfo` (PG18 connection-information table) to fill the SSL rows.
584
+ */
585
+ getTlsInfo() {
586
+ const s = this.socket;
587
+ if (typeof s.getCipher !== "function")
588
+ return null;
589
+ try {
590
+ const cipher = s.getCipher();
591
+ const protocol = s.getProtocol?.() ?? cipher.version ?? "unknown";
592
+ if (!cipher.name)
593
+ return null;
594
+ // TLS compression has been disabled by every modern stack since CRIME
595
+ // (2012); Node's TLS doesn't expose a compression accessor, so we
596
+ // always report "off". libpq does the same.
597
+ const compression = "off";
598
+ // Node exposes the negotiated ALPN protocol on TLSSocket.alpnProtocol
599
+ // (string when negotiated, false when not). Postgres 17+ uses
600
+ // 'postgresql' here.
601
+ const alpnRaw = s
602
+ .alpnProtocol;
603
+ const alpn = typeof alpnRaw === "string" && alpnRaw.length > 0
604
+ ? alpnRaw
605
+ : null;
606
+ return {
607
+ protocol: String(protocol),
608
+ cipher: cipher.standardName ?? cipher.name,
609
+ standardName: cipher.standardName,
610
+ compression,
611
+ alpn,
612
+ library: "OpenSSL",
613
+ keyBits: sslKeyBitsFromCipher(cipher.standardName ?? cipher.name),
614
+ };
615
+ }
616
+ catch {
617
+ return null;
618
+ }
619
+ }
620
+ /**
621
+ * Static connection facts for the PG18 `\conninfo` table, sourced from the
622
+ * connect opts and the live socket (no SQL is issued):
623
+ *
624
+ * - `host` / `port` / `options`: from the connect opts.
625
+ * - `hostaddr`: the resolved peer IP — `opts.hostaddr` if the caller
626
+ * fixed one, else the TCP socket's `remoteAddress` (undefined for a
627
+ * Unix-domain socket → `null`).
628
+ * - `backendPid`: the backend process id from BackendKeyData.
629
+ * - `passwordUsed`: whether a password was actually sent during auth.
630
+ * - `gssapiUsed`: always `false` — we have no GSSAPI support.
631
+ */
632
+ getConnectionInfo() {
633
+ const remote = this.opts.hostaddr !== undefined && this.opts.hostaddr !== ""
634
+ ? this.opts.hostaddr
635
+ : (this.socket.remoteAddress ?? null);
636
+ return {
637
+ host: this.opts.host,
638
+ hostaddr: remote,
639
+ port: this.opts.port,
640
+ options: this.opts.options ?? null,
641
+ backendPid: this.processId,
642
+ passwordUsed: this.passwordUsed,
643
+ gssapiUsed: false,
644
+ };
645
+ }
646
+ async query(sql, params) {
647
+ // `params === undefined` → caller has no intent to use extended protocol
648
+ // (e.g. a buffered SQL run without `\bind`). Use the simple-query path so
649
+ // chained `\;`-separated statements still work via `PQexec`-shaped
650
+ // semantics.
651
+ //
652
+ // `params` defined (even as `[]`) → caller staged a `\bind` (or a
653
+ // describe-formatter explicitly asking for the extended path). The
654
+ // extended protocol sends a single Parse message verbatim; the server
655
+ // rejects multi-statement SQL with SQLSTATE 42601 / "cannot insert
656
+ // multiple commands into a prepared statement", which is the upstream
657
+ // contract for `\bind`/`\parse`. Switching on length === 0 would silently
658
+ // fall back to simple-query and mask that diagnostic.
659
+ if (params === undefined) {
660
+ const sets = await this.execSimple(sql);
661
+ if (sets.length === 0) {
662
+ throw new Error("PgConnection.query: server returned no result sets");
663
+ }
664
+ return sets[sets.length - 1];
665
+ }
666
+ // Extended-protocol single-shot: Parse('', sql, []) → Bind('', '', [],
667
+ // text-encoded params, [text]) → Describe('P', '') → Execute('', 0) →
668
+ // Sync. Every param goes out in text format and the server coerces.
669
+ this.ensureIdle();
670
+ const encoded = encodeParams(params);
671
+ this.startExtendedBatch();
672
+ const parseP = this.enqueueParse();
673
+ const bindP = this.enqueueBind();
674
+ const descP = this.enqueueDescribePortalIntoNextExecute();
675
+ const execP = this.enqueueExecute();
676
+ const syncP = this.enqueueSync();
677
+ this.socket.write(Parse("", sql, []));
678
+ this.socket.write(Bind("", "", [], encoded, [0]));
679
+ this.socket.write(Describe("P", ""));
680
+ this.socket.write(Execute("", 0));
681
+ this.socket.write(Sync());
682
+ let firstErr = null;
683
+ const cap = (e) => {
684
+ if (firstErr === null)
685
+ firstErr = e;
686
+ };
687
+ parseP.catch(cap);
688
+ bindP.catch(cap);
689
+ descP.catch(cap);
690
+ let result = null;
691
+ execP.then((rs) => {
692
+ result = rs;
693
+ }, cap);
694
+ await syncP.catch(cap);
695
+ if (firstErr !== null)
696
+ throw asThrowable(firstErr);
697
+ if (result === null) {
698
+ throw new Error("PgConnection.query: server returned no result");
699
+ }
700
+ return result;
701
+ }
702
+ async execSimple(sql) {
703
+ this.ensureIdle();
704
+ return new Promise((resolve, reject) => {
705
+ this.pendingQuery = {
706
+ resolve,
707
+ reject,
708
+ current: null,
709
+ finished: [],
710
+ notices: [],
711
+ error: null,
712
+ };
713
+ this.state = "in-query";
714
+ this.socket.write(Query(sql));
715
+ });
716
+ }
717
+ async prepare(name, sql, paramTypes) {
718
+ this.ensureIdle();
719
+ const oids = paramTypes ?? [];
720
+ this.startExtendedBatch();
721
+ const parseP = this.enqueueParse();
722
+ const descP = this.enqueueDescribeStatement();
723
+ const syncP = this.enqueueSync();
724
+ this.socket.write(Parse(name, sql, oids));
725
+ this.socket.write(Describe("S", name));
726
+ this.socket.write(Sync());
727
+ let firstErr = null;
728
+ const cap = (e) => {
729
+ if (firstErr === null)
730
+ firstErr = e;
731
+ };
732
+ parseP.catch(cap);
733
+ let descResult = null;
734
+ descP.then((r) => {
735
+ descResult = r;
736
+ }, cap);
737
+ await syncP.catch(cap);
738
+ if (firstErr !== null)
739
+ throw asThrowable(firstErr);
740
+ if (descResult === null) {
741
+ throw new Error("PgConnection.prepare: server returned no parameter description");
742
+ }
743
+ const { paramOids, fields } = descResult;
744
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
745
+ const conn = this;
746
+ return {
747
+ name,
748
+ paramTypes: paramOids,
749
+ async bind(values, paramFormats) {
750
+ conn.ensureIdle();
751
+ const encoded = encodeParams(values);
752
+ conn.startExtendedBatch();
753
+ const bP = conn.enqueueBind();
754
+ const sP = conn.enqueueSync();
755
+ conn.socket.write(Bind("", name, paramFormats ?? [], encoded, [0]));
756
+ conn.socket.write(Sync());
757
+ let err = null;
758
+ bP.catch((e) => {
759
+ if (err === null)
760
+ err = e;
761
+ });
762
+ await sP.catch((e) => {
763
+ if (err === null)
764
+ err = e;
765
+ });
766
+ if (err !== null)
767
+ throw asThrowable(err);
768
+ },
769
+ describe() {
770
+ return Promise.resolve(fields);
771
+ },
772
+ async execute(maxRows) {
773
+ conn.ensureIdle();
774
+ conn.startExtendedBatch();
775
+ const eP = conn.enqueueExecuteWithFields(fields);
776
+ const sP = conn.enqueueSync();
777
+ conn.socket.write(Execute("", maxRows ?? 0));
778
+ conn.socket.write(Sync());
779
+ let err = null;
780
+ let rs = null;
781
+ eP.then((r) => {
782
+ rs = r;
783
+ }, (e) => {
784
+ if (err === null)
785
+ err = e;
786
+ });
787
+ await sP.catch((e) => {
788
+ if (err === null)
789
+ err = e;
790
+ });
791
+ if (err !== null)
792
+ throw asThrowable(err);
793
+ if (rs === null) {
794
+ throw new Error("PgConnection.prepare.execute: server returned no result");
795
+ }
796
+ return rs;
797
+ },
798
+ async bindAndExecute(values, maxRows, paramFormats) {
799
+ conn.ensureIdle();
800
+ const encoded = encodeParams(values);
801
+ conn.startExtendedBatch();
802
+ const bP = conn.enqueueBind();
803
+ const eP = conn.enqueueExecuteWithFields(fields);
804
+ const sP = conn.enqueueSync();
805
+ conn.socket.write(Bind("", name, paramFormats ?? [], encoded, [0]));
806
+ conn.socket.write(Execute("", maxRows ?? 0));
807
+ conn.socket.write(Sync());
808
+ let err = null;
809
+ let rs = null;
810
+ bP.catch((e) => {
811
+ if (err === null)
812
+ err = e;
813
+ });
814
+ eP.then((r) => {
815
+ rs = r;
816
+ }, (e) => {
817
+ if (err === null)
818
+ err = e;
819
+ });
820
+ await sP.catch((e) => {
821
+ if (err === null)
822
+ err = e;
823
+ });
824
+ if (err !== null)
825
+ throw asThrowable(err);
826
+ if (rs === null) {
827
+ throw new Error("PgConnection.prepare.bindAndExecute: server returned no result");
828
+ }
829
+ return rs;
830
+ },
831
+ async close() {
832
+ conn.ensureIdle();
833
+ conn.startExtendedBatch();
834
+ const cP = conn.enqueueClose();
835
+ const sP = conn.enqueueSync();
836
+ conn.socket.write(Close("S", name));
837
+ conn.socket.write(Sync());
838
+ let err = null;
839
+ cP.catch((e) => {
840
+ if (err === null)
841
+ err = e;
842
+ });
843
+ await sP.catch((e) => {
844
+ if (err === null)
845
+ err = e;
846
+ });
847
+ if (err !== null)
848
+ throw asThrowable(err);
849
+ },
850
+ };
851
+ }
852
+ /**
853
+ * Issue `Close('S', name) + Sync` directly, without a preceding Parse.
854
+ * The server responds with CloseComplete + ReadyForQuery (even when
855
+ * the named statement doesn't exist — PG treats unknown-name Close as
856
+ * a no-op). Used by `\close_prepared NAME` so we don't have to fake a
857
+ * Parse just to reach the Close step.
858
+ */
859
+ async closePreparedStatement(name) {
860
+ this.ensureIdle();
861
+ this.startExtendedBatch();
862
+ const cP = this.enqueueClose();
863
+ const sP = this.enqueueSync();
864
+ this.socket.write(Close("S", name));
865
+ this.socket.write(Sync());
866
+ let err = null;
867
+ cP.catch((e) => {
868
+ if (err === null)
869
+ err = e;
870
+ });
871
+ await sP.catch((e) => {
872
+ if (err === null)
873
+ err = e;
874
+ });
875
+ if (err !== null)
876
+ throw asThrowable(err);
877
+ }
878
+ startCopyIn(sql) {
879
+ this.ensureIdle();
880
+ // COPY mid-pipeline is rejected by libpq with a fixed diagnostic; we
881
+ // mirror that synchronously so callers don't need a round-trip to learn
882
+ // their command is invalid. The wire-level dispatch also guards this
883
+ // (see handleCopyStartMessage) for any path that bypasses this check.
884
+ if (this._extPipelineActive) {
885
+ this.abortForCopyInPipeline();
886
+ return Promise.reject(Object.assign(new Error("COPY in a pipeline is not supported, aborting connection"), { severity: "FATAL" }));
887
+ }
888
+ // The driver waits in `in-query` state until CopyInResponse arrives — at
889
+ // which point the protocol switches and we move to `in-copy-in`. The
890
+ // server can also reply with an ErrorResponse (e.g. "no such table"),
891
+ // which we surface as a rejected promise.
892
+ return new Promise((resolve, reject) => {
893
+ this.copyIn = {
894
+ resolveDone: null,
895
+ rejectDone: null,
896
+ error: null,
897
+ commandTag: null,
898
+ closed: false,
899
+ };
900
+ this.copyStartResolve = () => {
901
+ // The protocol-switch landed; hand the caller a usable stream.
902
+ resolve(this.makeCopyInStream());
903
+ };
904
+ this.copyStartReject = reject;
905
+ this.state = "in-query";
906
+ this.socket.write(Query(sql));
907
+ });
908
+ }
909
+ startCopyOut(sql) {
910
+ this.ensureIdle();
911
+ if (this._extPipelineActive) {
912
+ this.abortForCopyInPipeline();
913
+ return Promise.reject(Object.assign(new Error("COPY in a pipeline is not supported, aborting connection"), { severity: "FATAL" }));
914
+ }
915
+ return new Promise((resolve, reject) => {
916
+ this.copyOut = {
917
+ queue: [],
918
+ queuedBytes: 0,
919
+ waker: null,
920
+ done: false,
921
+ abandoned: false,
922
+ error: null,
923
+ commandTag: null,
924
+ };
925
+ this.copyStartResolve = () => {
926
+ resolve(this.makeCopyOutStream());
927
+ };
928
+ this.copyStartReject = reject;
929
+ this.state = "in-query";
930
+ this.socket.write(Query(sql));
931
+ });
932
+ }
933
+ pipeline() {
934
+ this.ensureIdle();
935
+ return new PipelineSession(this);
936
+ }
937
+ /**
938
+ * Cancel whatever the connection is currently doing.
939
+ *
940
+ * The routing is state-aware so the mainloop SIGINT handler can call this
941
+ * blindly without knowing the protocol phase:
942
+ *
943
+ * - `in-copy-in`: we hold the writing end of the data stream, so the
944
+ * correct action is a client-initiated CopyFail on the *same* socket.
945
+ * Sending a side CancelRequest would race with our own pending writes;
946
+ * CopyFail is the spec-blessed abort path. The server replies with
947
+ * ErrorResponse + ReadyForQuery and we transition back to idle.
948
+ * - `in-copy-out`: the server is pushing data at us. CopyFail is not a
949
+ * valid client message here, so we fall back to the side CancelRequest
950
+ * path that normal queries use. PG will surface an ErrorResponse and
951
+ * tear the COPY down.
952
+ * - everything else: side CancelRequest, the historical behaviour.
953
+ *
954
+ * Best-effort. We don't reject if BackendKeyData hasn't arrived yet
955
+ * during the auth dance — there's nothing to cancel; we just return.
956
+ */
957
+ async cancel() {
958
+ // In-copy-in: send CopyFail on the live socket so the server returns
959
+ // to ReadyForQuery cleanly. This is the same abort path the upstream
960
+ // SIGINT handler in `copy.c::handleCopyIn` triggers via longjmp.
961
+ if (this.state === "in-copy-in" && this.copyIn && !this.copyIn.closed) {
962
+ this.copyIn.closed = true;
963
+ try {
964
+ this.socket.write(CopyFail("canceled by user"));
965
+ }
966
+ catch {
967
+ // Socket may have died — failPending() will surface that.
968
+ }
969
+ return;
970
+ }
971
+ if (this.processId === 0) {
972
+ // Nothing to cancel — startup hasn't reached BackendKeyData. Be
973
+ // forgiving: the mainloop SIGINT handler shouldn't crash on cancel
974
+ // during a half-open connection.
975
+ return;
976
+ }
977
+ // Per the PG protocol, CancelRequest is sent on a *fresh* connection,
978
+ // not the one running the query. We TLS-negotiate against the same
979
+ // sslmode but we don't auth — we just write the request and close.
980
+ // Honour `hostaddr` on the cancel connection too: dial the fixed IP while
981
+ // keeping the user-typed host for SNI / cert verification, mirroring the
982
+ // primary connect path's `addressOverride`.
983
+ const cancelSocket = await openSocket(this.opts, this.opts.hostaddr !== undefined && this.opts.hostaddr !== ""
984
+ ? this.opts.hostaddr
985
+ : undefined);
986
+ let writeSocket = cancelSocket;
987
+ try {
988
+ // sslsni=0 suppresses SNI on the cancel connection too (mirrors the
989
+ // primary connect path).
990
+ const cancelServername = tlsServername(this.opts);
991
+ const cancelTlsOpts = {
992
+ ...(cancelServername !== undefined
993
+ ? { servername: cancelServername }
994
+ : {}),
995
+ rejectUnauthorized: this.opts.ssl === "verify-ca" ||
996
+ this.opts.ssl === "verify-full",
997
+ ALPNProtocols: ["postgresql"],
998
+ };
999
+ if (this.opts.ssl !== "verify-full") {
1000
+ cancelTlsOpts.checkServerIdentity = () => undefined;
1001
+ }
1002
+ else if (this.opts.sslsni === false) {
1003
+ const host = this.opts.host;
1004
+ cancelTlsOpts.checkServerIdentity = (_h, cert) => tls.checkServerIdentity(host, cert);
1005
+ }
1006
+ applyTlsProtocolVersionRange(cancelTlsOpts, this.opts);
1007
+ const t = await negotiateTls(cancelSocket,
1008
+ // Unix-domain socket: no TLS, regardless of caller's sslmode.
1009
+ isUnixSocketHost(this.opts.host) ? "disable" : this.opts.ssl, cancelTlsOpts, {
1010
+ sslcert: this.opts.sslcert,
1011
+ sslkey: this.opts.sslkey,
1012
+ sslcertmode: this.opts.sslcertmode,
1013
+ sslpassword: this.opts.sslpassword,
1014
+ sslrootcert: this.opts.sslrootcert,
1015
+ sslcrl: this.opts.sslcrl,
1016
+ sslcrldir: this.opts.sslcrldir,
1017
+ sslkeylogfile: this.opts.sslkeylogfile,
1018
+ },
1019
+ // Mirror the primary connect path's negotiation mode so a server
1020
+ // configured for direct SSL also accepts the cancel connection.
1021
+ isUnixSocketHost(this.opts.host)
1022
+ ? "postgres"
1023
+ : (this.opts.sslnegotiation ?? "postgres"));
1024
+ writeSocket = t.kind === "tls" ? t.socket : t.socket;
1025
+ await new Promise((resolve, reject) => {
1026
+ writeSocket.write(CancelRequest(this.processId, this.secretKey), (err) => {
1027
+ if (err)
1028
+ reject(err);
1029
+ else
1030
+ resolve();
1031
+ });
1032
+ });
1033
+ }
1034
+ finally {
1035
+ try {
1036
+ writeSocket.end();
1037
+ }
1038
+ catch {
1039
+ // ignore
1040
+ }
1041
+ try {
1042
+ cancelSocket.destroy();
1043
+ }
1044
+ catch {
1045
+ // ignore
1046
+ }
1047
+ }
1048
+ }
1049
+ escapeIdentifier(value) {
1050
+ return '"' + value.replace(/"/g, '""') + '"';
1051
+ }
1052
+ escapeLiteral(value) {
1053
+ // Per PG docs: doubled single-quotes always; if the string contains a
1054
+ // backslash, use the E'...' escape-string syntax so backslashes don't
1055
+ // depend on `standard_conforming_strings`.
1056
+ const doubled = value.replace(/'/g, "''");
1057
+ if (value.includes("\\")) {
1058
+ return "E'" + doubled.replace(/\\/g, "\\\\") + "'";
1059
+ }
1060
+ return "'" + doubled + "'";
1061
+ }
1062
+ async setClientEncoding(name) {
1063
+ // libpq's PQsetClientEncoding sends `SET client_encoding TO '<value>'`
1064
+ // down the wire (see fe-connect.c). We do the same via the simple-query
1065
+ // path, quoting the value as a string literal so encoding names are
1066
+ // never mistaken for SQL tokens. On success the server emits a
1067
+ // `client_encoding` ParameterStatus which the message loop folds into
1068
+ // `this.params` (see the ParameterStatus cases), so
1069
+ // `parameterStatus('client_encoding')` is up to date afterwards.
1070
+ //
1071
+ // We keep no separate client-side decoder state: text-format values are
1072
+ // always decoded as UTF-8 in `decodeDataRow`, matching how the rest of
1073
+ // this client treats backend text. Tracking only the ParameterStatus is
1074
+ // therefore sufficient. A non-zero `SET` failure (e.g. a name the server
1075
+ // rejects) surfaces as a thrown ConnectError from `execSimple`.
1076
+ await this.execSimple(`SET client_encoding TO ${this.escapeLiteral(name)}`);
1077
+ }
1078
+ onNotice(handler) {
1079
+ return this.notify.onNotice(handler);
1080
+ }
1081
+ onNotification(handler) {
1082
+ return this.notify.onNotification(handler);
1083
+ }
1084
+ async close() {
1085
+ if (this.state === "closed")
1086
+ return;
1087
+ try {
1088
+ this.socket.write(Terminate());
1089
+ }
1090
+ catch {
1091
+ // socket may already be dead; we still want to mark closed
1092
+ }
1093
+ this.state = "closed";
1094
+ this.notify.clear();
1095
+ await new Promise((resolve) => {
1096
+ this.socket.once("close", () => {
1097
+ resolve();
1098
+ });
1099
+ try {
1100
+ this.socket.end();
1101
+ }
1102
+ catch {
1103
+ resolve();
1104
+ }
1105
+ });
1106
+ }
1107
+ isClosed() {
1108
+ return this.state === "closed";
1109
+ }
1110
+ // -------------------------------------------------------------------------
1111
+ // Startup / auth state machine
1112
+ // -------------------------------------------------------------------------
1113
+ startup() {
1114
+ return new Promise((resolve, reject) => {
1115
+ const params = {
1116
+ user: this.opts.user,
1117
+ database: this.opts.database,
1118
+ // psql sends client_encoding=UTF8 by default; we follow.
1119
+ client_encoding: this.opts.clientEncoding ?? "UTF8",
1120
+ };
1121
+ if (this.opts.applicationName !== undefined) {
1122
+ params.application_name = this.opts.applicationName;
1123
+ }
1124
+ if (this.opts.options !== undefined) {
1125
+ params.options = this.opts.options;
1126
+ }
1127
+ // Walsender (replication) mode: the server enters a restricted
1128
+ // command set (IDENTIFY_SYSTEM, START_REPLICATION, etc.) keyed off
1129
+ // this startup parameter. Values mirror libpq's normalisation:
1130
+ // 'true' for physical, 'database' for logical. We do not stream the
1131
+ // CopyBoth phase — the Query path still surfaces ErrorResponse and
1132
+ // any pre-streaming ResultSet, which is enough for the negative
1133
+ // conformance test (`psql -c 'START_REPLICATION 0/1'` must exit
1134
+ // non-zero with a syntax error from the server).
1135
+ if (this.opts.replication !== undefined) {
1136
+ params.replication = this.opts.replication;
1137
+ }
1138
+ this.startupResolve = resolve;
1139
+ this.startupReject = reject;
1140
+ this.socket.write(StartupMessage(params));
1141
+ });
1142
+ }
1143
+ /**
1144
+ * Enforce `require_auth` against an observed server-requested method.
1145
+ * Returns true when the connection should proceed; false (with
1146
+ * {@link failStartup} already called) when the policy was violated.
1147
+ */
1148
+ checkRequireAuth(observed) {
1149
+ const policy = this.opts.requireAuth;
1150
+ if (policy === undefined)
1151
+ return true;
1152
+ const hit = policy.methods.has(observed);
1153
+ const allowed = policy.negated ? !hit : hit;
1154
+ if (!allowed) {
1155
+ this.failStartup(new Error(`auth method "${observed}" requirement failed`));
1156
+ return false;
1157
+ }
1158
+ return true;
1159
+ }
1160
+ handleAuthMessage(msg) {
1161
+ switch (msg.type) {
1162
+ case "AuthenticationOk": {
1163
+ // libpq parity: channel_binding=require demands that some prior
1164
+ // auth step actually negotiated channel binding. A bare
1165
+ // AuthenticationOk after no challenge ("trust") or after a cert
1166
+ // exchange ("cert" HBA, clientcert=verify-full) means no SCRAM
1167
+ // happened and we must refuse.
1168
+ if (this.opts.channelBinding === "require" &&
1169
+ (this.scram === null ||
1170
+ this.scram.mechanism !== "SCRAM-SHA-256-PLUS")) {
1171
+ this.failStartup(new Error("channel binding required, but server authenticated client without channel binding"));
1172
+ return;
1173
+ }
1174
+ // Mutual-auth integrity: if a SCRAM exchange was started it MUST have
1175
+ // completed via AuthenticationSASLFinal (where the server signature is
1176
+ // verified). A server that sends SASLContinue then jumps to
1177
+ // AuthenticationOk never proves it knows the password (review #8).
1178
+ if (this.scram !== null && !this.saslFinalSeen) {
1179
+ this.failStartup(new Error("server sent AuthenticationOk without completing SCRAM " +
1180
+ "authentication (server signature not verified)"));
1181
+ return;
1182
+ }
1183
+ // require_auth=none allows trust auth; anything else is rejected
1184
+ // here. If a prior challenge was sent and validated, skip — that
1185
+ // method was already accepted by the check at its own branch.
1186
+ if (!this.authChallengeSeen && !this.checkRequireAuth("none")) {
1187
+ return;
1188
+ }
1189
+ this.state = "await-ready";
1190
+ return;
1191
+ }
1192
+ case "AuthenticationCleartextPassword": {
1193
+ this.authChallengeSeen = true;
1194
+ if (this.opts.channelBinding === "require") {
1195
+ this.failStartup(new Error("channel binding required but not supported by server's authentication request"));
1196
+ return;
1197
+ }
1198
+ if (!this.checkRequireAuth("password"))
1199
+ return;
1200
+ if (this.opts.password === undefined) {
1201
+ this.failStartup(new Error("Server requested cleartext password but no password was provided"));
1202
+ return;
1203
+ }
1204
+ this.passwordUsed = true;
1205
+ this.socket.write(PasswordMessage(this.opts.password));
1206
+ return;
1207
+ }
1208
+ case "AuthenticationMD5Password": {
1209
+ this.authChallengeSeen = true;
1210
+ if (this.opts.channelBinding === "require") {
1211
+ this.failStartup(new Error("channel binding required but not supported by server's authentication request"));
1212
+ return;
1213
+ }
1214
+ if (!this.checkRequireAuth("md5"))
1215
+ return;
1216
+ if (this.opts.password === undefined) {
1217
+ this.failStartup(new Error("Server requested MD5 password but no password was provided"));
1218
+ return;
1219
+ }
1220
+ const payload = md5AuthPayload(this.opts.user, this.opts.password, msg.salt);
1221
+ this.passwordUsed = true;
1222
+ this.socket.write(PasswordMessage(payload));
1223
+ return;
1224
+ }
1225
+ case "AuthenticationSASL": {
1226
+ this.authChallengeSeen = true;
1227
+ if (this.opts.password === undefined) {
1228
+ this.failStartup(new Error("Server requested SASL auth but no password was provided"));
1229
+ return;
1230
+ }
1231
+ if (!this.checkRequireAuth("scram-sha-256"))
1232
+ return;
1233
+ // channel_binding=require AND server didn't offer the PLUS
1234
+ // variant — refuse before the SASL handshake starts. The check
1235
+ // is split between here (no PLUS in the mechanism list) and
1236
+ // chooseMechanism's fallback (PLUS present but no binding data).
1237
+ if (this.opts.channelBinding === "require" &&
1238
+ !msg.mechanisms.includes("SCRAM-SHA-256-PLUS")) {
1239
+ this.failStartup(new Error("channel binding required but not supported by server's authentication request"));
1240
+ return;
1241
+ }
1242
+ if (this.opts.channelBinding === "require" &&
1243
+ this.channelBindingData === null) {
1244
+ this.failStartup(new Error("channel binding required but not supported by server's authentication request"));
1245
+ return;
1246
+ }
1247
+ try {
1248
+ this.scram = createScramClient({
1249
+ user: this.opts.user,
1250
+ password: this.opts.password,
1251
+ mechanisms: msg.mechanisms,
1252
+ channelBinding: this.channelBindingData !== null &&
1253
+ this.opts.channelBinding !== "disable"
1254
+ ? {
1255
+ type: "tls-server-end-point",
1256
+ data: this.channelBindingData,
1257
+ }
1258
+ : undefined,
1259
+ });
1260
+ const { mechanism, clientFirstMessage } = this.scram.start();
1261
+ this.passwordUsed = true;
1262
+ this.socket.write(SASLInitialResponse(mechanism, clientFirstMessage));
1263
+ }
1264
+ catch (err) {
1265
+ this.failStartup(err);
1266
+ }
1267
+ return;
1268
+ }
1269
+ case "AuthenticationSASLContinue": {
1270
+ if (!this.scram) {
1271
+ this.failStartup(new Error("Received AuthenticationSASLContinue without an active SCRAM client"));
1272
+ return;
1273
+ }
1274
+ try {
1275
+ const reply = this.scram.continue(msg.data);
1276
+ this.socket.write(SASLResponse(reply));
1277
+ }
1278
+ catch (err) {
1279
+ this.failStartup(err);
1280
+ }
1281
+ return;
1282
+ }
1283
+ case "AuthenticationSASLFinal": {
1284
+ if (!this.scram) {
1285
+ this.failStartup(new Error("Received AuthenticationSASLFinal without an active SCRAM client"));
1286
+ return;
1287
+ }
1288
+ try {
1289
+ this.scram.finish(msg.data);
1290
+ this.saslFinalSeen = true;
1291
+ }
1292
+ catch (err) {
1293
+ this.failStartup(err);
1294
+ }
1295
+ return;
1296
+ }
1297
+ case "ErrorResponse":
1298
+ this.failStartup(fieldsToConnectError(msg.fields));
1299
+ return;
1300
+ case "NoticeResponse":
1301
+ this.notify.emit(fieldsToNotice(msg.fields));
1302
+ return;
1303
+ default:
1304
+ // ParameterStatus / BackendKeyData / ReadyForQuery may arrive in
1305
+ // `await-ready`; auth state shouldn't see them, but we tolerate by
1306
+ // forwarding to the post-auth handler if so.
1307
+ this.handleAwaitReady(msg);
1308
+ return;
1309
+ }
1310
+ }
1311
+ handleAwaitReady(msg) {
1312
+ switch (msg.type) {
1313
+ case "ParameterStatus":
1314
+ this.params.set(msg.name, msg.value);
1315
+ if (msg.name === "server_version") {
1316
+ this.serverVersion = parseServerVersion(msg.value);
1317
+ }
1318
+ return;
1319
+ case "BackendKeyData":
1320
+ this.processId = msg.processId;
1321
+ this.secretKey = msg.secretKey;
1322
+ return;
1323
+ case "ReadyForQuery":
1324
+ this.txStatus = msg.status;
1325
+ this.state = "idle";
1326
+ if (this.startupResolve) {
1327
+ const r = this.startupResolve;
1328
+ this.startupResolve = null;
1329
+ this.startupReject = null;
1330
+ r();
1331
+ }
1332
+ return;
1333
+ case "ErrorResponse":
1334
+ this.failStartup(fieldsToConnectError(msg.fields));
1335
+ return;
1336
+ case "NoticeResponse":
1337
+ this.notify.emit(fieldsToNotice(msg.fields));
1338
+ return;
1339
+ default:
1340
+ this.failStartup(new Error(`Unexpected message ${msg.type} during connection startup`));
1341
+ return;
1342
+ }
1343
+ }
1344
+ failStartup(err) {
1345
+ if (this.startupReject) {
1346
+ const r = this.startupReject;
1347
+ this.startupResolve = null;
1348
+ this.startupReject = null;
1349
+ r(err);
1350
+ }
1351
+ try {
1352
+ this.socket.destroy();
1353
+ }
1354
+ catch {
1355
+ // ignore
1356
+ }
1357
+ this.state = "closed";
1358
+ }
1359
+ // -------------------------------------------------------------------------
1360
+ // COPY state machine (WP-16).
1361
+ //
1362
+ // The frontend transitions through:
1363
+ // idle → in-query (after writing Query("COPY …"))
1364
+ // in-query → in-copy-in on CopyInResponse
1365
+ // in-query → in-copy-out on CopyOutResponse
1366
+ // in-copy-in → idle on ReadyForQuery (after our CopyDone/CopyFail +
1367
+ // server CommandComplete)
1368
+ // in-copy-out → idle on ReadyForQuery (after server CopyDone +
1369
+ // CommandComplete)
1370
+ //
1371
+ // ErrorResponse may arrive at any point; we drain until ReadyForQuery and
1372
+ // then surface as a rejected promise.
1373
+ // -------------------------------------------------------------------------
1374
+ makeCopyInStream() {
1375
+ const driver = this.copyIn;
1376
+ if (!driver) {
1377
+ throw new Error("PgConnection: makeCopyInStream called without driver");
1378
+ }
1379
+ return {
1380
+ write: (chunk) => {
1381
+ if (this.state === "closed") {
1382
+ return Promise.reject(new Error("Connection closed"));
1383
+ }
1384
+ if (driver.closed) {
1385
+ return Promise.reject(new Error("CopyInStream already closed"));
1386
+ }
1387
+ const data = typeof chunk === "string"
1388
+ ? Buffer.from(chunk, "utf8")
1389
+ : chunk;
1390
+ return new Promise((resolve, reject) => {
1391
+ this.socket.write(CopyData(data), (err) => {
1392
+ if (err)
1393
+ reject(err);
1394
+ else
1395
+ resolve();
1396
+ });
1397
+ });
1398
+ },
1399
+ end: () => {
1400
+ if (driver.closed) {
1401
+ return Promise.reject(new Error("CopyInStream already closed"));
1402
+ }
1403
+ driver.closed = true;
1404
+ return new Promise((resolve, reject) => {
1405
+ driver.resolveDone = resolve;
1406
+ driver.rejectDone = reject;
1407
+ this.socket.write(CopyDone());
1408
+ });
1409
+ },
1410
+ fail: (reason) => {
1411
+ if (driver.closed) {
1412
+ return Promise.reject(new Error("CopyInStream already closed"));
1413
+ }
1414
+ driver.closed = true;
1415
+ return new Promise((resolve, reject) => {
1416
+ // The server is expected to reject with an ErrorResponse echoing
1417
+ // our reason; we still resolve so callers can move on. We wire the
1418
+ // resolver after the socket flush so a fast-close error surfaces.
1419
+ driver.resolveDone = () => {
1420
+ resolve();
1421
+ };
1422
+ driver.rejectDone = reject;
1423
+ this.socket.write(CopyFail(reason));
1424
+ });
1425
+ },
1426
+ };
1427
+ }
1428
+ makeCopyOutStream() {
1429
+ const driver = this.copyOut;
1430
+ if (!driver) {
1431
+ throw new Error("PgConnection: makeCopyOutStream called without driver");
1432
+ }
1433
+ // Capture the state-getter as a closure so the iterator can observe
1434
+ // connection close without holding a `this` alias (no-this-alias rule).
1435
+ const isClosed = () => this.state === "closed";
1436
+ // Resume reading once the buffered data drains — paired with the
1437
+ // pause() the CopyData handler applies at the high-water mark (#11).
1438
+ const resumeSocket = () => {
1439
+ this.socket.resume?.();
1440
+ };
1441
+ return {
1442
+ [Symbol.asyncIterator]() {
1443
+ return {
1444
+ async next() {
1445
+ for (;;) {
1446
+ if (driver.queue.length > 0) {
1447
+ const next = driver.queue.shift();
1448
+ if (next === undefined)
1449
+ continue;
1450
+ driver.queuedBytes -= next.length;
1451
+ if (driver.queuedBytes <= COPY_OUT_LWM)
1452
+ resumeSocket();
1453
+ return { value: next, done: false };
1454
+ }
1455
+ if (driver.error) {
1456
+ // ConnectError isn't strictly an Error instance; the rule
1457
+ // wants a real Error. Wrap once before throwing.
1458
+ const ce = driver.error;
1459
+ const wrapped = new Error(ce.message);
1460
+ wrapped.cause =
1461
+ ce;
1462
+ throw wrapped;
1463
+ }
1464
+ if (driver.done) {
1465
+ return { value: undefined, done: true };
1466
+ }
1467
+ if (isClosed()) {
1468
+ throw new Error("Connection closed mid-COPY-OUT");
1469
+ }
1470
+ await new Promise((resolve) => {
1471
+ driver.waker = resolve;
1472
+ });
1473
+ }
1474
+ },
1475
+ return() {
1476
+ // Consumer broke early. We must keep reading the wire until
1477
+ // ReadyForQuery to clear the protocol state, but we mark the
1478
+ // stream abandoned (so the handler DROPS further CopyData rather
1479
+ // than buffering it) and free what's queued — otherwise RSS grows
1480
+ // to the full result size (review item #11). Resume in case the
1481
+ // socket was paused at the high-water mark.
1482
+ driver.abandoned = true;
1483
+ driver.queue.length = 0;
1484
+ driver.queuedBytes = 0;
1485
+ resumeSocket();
1486
+ return Promise.resolve({
1487
+ value: undefined,
1488
+ done: true,
1489
+ });
1490
+ },
1491
+ };
1492
+ },
1493
+ };
1494
+ }
1495
+ /**
1496
+ * Handle messages arriving in `in-query` state when there is no
1497
+ * `pendingQuery` — i.e. the caller invoked `startCopyIn` / `startCopyOut`
1498
+ * and is waiting for the server to switch into copy mode.
1499
+ */
1500
+ handleCopyStartMessage(msg) {
1501
+ switch (msg.type) {
1502
+ case "CopyInResponse":
1503
+ // COPY-in-pipeline: libpq aborts the connection with this exact
1504
+ // diagnostic (matching upstream psql's behaviour). The `\copy`
1505
+ // command layer detects pipeline-active and fails fast before
1506
+ // reaching the wire, but if anything else slips through we abort
1507
+ // here as a defence-in-depth.
1508
+ if (this._extPipelineActive) {
1509
+ this.abortForCopyInPipeline();
1510
+ return;
1511
+ }
1512
+ if (this.copyIn) {
1513
+ this.state = "in-copy-in";
1514
+ const r = this.copyStartResolve;
1515
+ this.copyStartResolve = null;
1516
+ this.copyStartReject = null;
1517
+ if (r)
1518
+ r();
1519
+ }
1520
+ return;
1521
+ case "CopyOutResponse":
1522
+ if (this._extPipelineActive) {
1523
+ this.abortForCopyInPipeline();
1524
+ return;
1525
+ }
1526
+ if (this.copyOut) {
1527
+ this.state = "in-copy-out";
1528
+ const r = this.copyStartResolve;
1529
+ this.copyStartResolve = null;
1530
+ this.copyStartReject = null;
1531
+ if (r)
1532
+ r();
1533
+ }
1534
+ return;
1535
+ case "ErrorResponse": {
1536
+ const err = fieldsToConnectError(msg.fields);
1537
+ if (this.copyIn) {
1538
+ if (this.copyStartReject)
1539
+ this.copyStartReject(err);
1540
+ this.copyStartResolve = null;
1541
+ this.copyStartReject = null;
1542
+ this.copyIn = null;
1543
+ }
1544
+ if (this.copyOut) {
1545
+ if (this.copyStartReject)
1546
+ this.copyStartReject(err);
1547
+ this.copyStartResolve = null;
1548
+ this.copyStartReject = null;
1549
+ this.copyOut = null;
1550
+ }
1551
+ // Stay in `in-query` until ReadyForQuery, then return to idle below.
1552
+ return;
1553
+ }
1554
+ case "ReadyForQuery":
1555
+ // ReadyForQuery without a prior CopyXxxResponse means the server
1556
+ // immediately rejected the COPY (we surfaced the ErrorResponse just
1557
+ // above) — return to idle so the next command can fire.
1558
+ this.txStatus = msg.status;
1559
+ this.state = "idle";
1560
+ return;
1561
+ case "NoticeResponse":
1562
+ this.notify.emit(fieldsToNotice(msg.fields));
1563
+ return;
1564
+ case "ParameterStatus":
1565
+ this.params.set(msg.name, msg.value);
1566
+ return;
1567
+ default:
1568
+ if (this.copyStartReject) {
1569
+ this.copyStartReject(new Error(`Unexpected backend message before COPY response: ${msg.type}`));
1570
+ }
1571
+ this.copyStartResolve = null;
1572
+ this.copyStartReject = null;
1573
+ return;
1574
+ }
1575
+ }
1576
+ handleCopyInMessage(msg) {
1577
+ const driver = this.copyIn;
1578
+ if (!driver)
1579
+ return;
1580
+ switch (msg.type) {
1581
+ case "CommandComplete":
1582
+ driver.commandTag = msg.tag;
1583
+ this.lastCopyTag = msg.tag;
1584
+ return;
1585
+ case "ErrorResponse":
1586
+ driver.error = fieldsToConnectError(msg.fields);
1587
+ return;
1588
+ case "NoticeResponse":
1589
+ this.notify.emit(fieldsToNotice(msg.fields));
1590
+ return;
1591
+ case "ParameterStatus":
1592
+ this.params.set(msg.name, msg.value);
1593
+ return;
1594
+ case "ReadyForQuery":
1595
+ this.txStatus = msg.status;
1596
+ this.state = "idle";
1597
+ this.copyIn = null;
1598
+ if (driver.error) {
1599
+ if (driver.rejectDone)
1600
+ driver.rejectDone(driver.error);
1601
+ }
1602
+ else if (driver.resolveDone) {
1603
+ driver.resolveDone();
1604
+ }
1605
+ return;
1606
+ default:
1607
+ // Unknown messages mid-COPY-IN are protocol errors; record and let
1608
+ // the trailing ReadyForQuery flush the state.
1609
+ driver.error = {
1610
+ severity: "ERROR",
1611
+ message: `Unexpected backend message during COPY IN: ${msg.type}`,
1612
+ };
1613
+ return;
1614
+ }
1615
+ }
1616
+ handleCopyOutMessage(msg) {
1617
+ const driver = this.copyOut;
1618
+ if (!driver)
1619
+ return;
1620
+ switch (msg.type) {
1621
+ case "CopyData": {
1622
+ // Consumer broke early: drop instead of buffering (review item #11).
1623
+ if (driver.abandoned)
1624
+ return;
1625
+ driver.queue.push(msg.data);
1626
+ driver.queuedBytes += msg.data.length;
1627
+ // Apply backpressure when the sink falls behind: pause the socket so
1628
+ // the server stops flooding us. `next()` resumes at the low-water
1629
+ // mark. (No-op if the socket doesn't expose pause(), e.g. a mock.)
1630
+ if (driver.queuedBytes >= COPY_OUT_HWM) {
1631
+ this.socket.pause?.();
1632
+ }
1633
+ if (driver.waker) {
1634
+ const w = driver.waker;
1635
+ driver.waker = null;
1636
+ w();
1637
+ }
1638
+ return;
1639
+ }
1640
+ case "CopyDone":
1641
+ // Server signals it's done sending — we now expect CommandComplete +
1642
+ // ReadyForQuery. Stay in in-copy-out until ReadyForQuery; the queue
1643
+ // may still drain via the consumer.
1644
+ return;
1645
+ case "CommandComplete":
1646
+ driver.commandTag = msg.tag;
1647
+ this.lastCopyTag = msg.tag;
1648
+ return;
1649
+ case "ErrorResponse":
1650
+ driver.error = fieldsToConnectError(msg.fields);
1651
+ return;
1652
+ case "NoticeResponse":
1653
+ this.notify.emit(fieldsToNotice(msg.fields));
1654
+ return;
1655
+ case "ParameterStatus":
1656
+ this.params.set(msg.name, msg.value);
1657
+ return;
1658
+ case "ReadyForQuery":
1659
+ this.txStatus = msg.status;
1660
+ this.state = "idle";
1661
+ driver.done = true;
1662
+ this.copyOut = null;
1663
+ if (driver.waker) {
1664
+ const w = driver.waker;
1665
+ driver.waker = null;
1666
+ w();
1667
+ }
1668
+ return;
1669
+ default:
1670
+ driver.error = {
1671
+ severity: "ERROR",
1672
+ message: `Unexpected backend message during COPY OUT: ${msg.type}`,
1673
+ };
1674
+ if (driver.waker) {
1675
+ const w = driver.waker;
1676
+ driver.waker = null;
1677
+ w();
1678
+ }
1679
+ return;
1680
+ }
1681
+ }
1682
+ // -------------------------------------------------------------------------
1683
+ // Query state machine
1684
+ // -------------------------------------------------------------------------
1685
+ handleQueryMessage(msg) {
1686
+ const q = this.pendingQuery;
1687
+ if (!q) {
1688
+ // No active execSimple — we must be in the "starting a COPY" phase
1689
+ // where the caller wrote Query("COPY …") via startCopyIn/startCopyOut.
1690
+ this.handleCopyStartMessage(msg);
1691
+ return;
1692
+ }
1693
+ switch (msg.type) {
1694
+ case "RowDescription":
1695
+ q.current = {
1696
+ command: "",
1697
+ rowCount: null,
1698
+ oid: null,
1699
+ fields: msg.fields,
1700
+ rows: [],
1701
+ notices: [],
1702
+ };
1703
+ return;
1704
+ case "DataRow": {
1705
+ if (!q.current) {
1706
+ // Server sent rows without a prior description — extremely rare
1707
+ // (only for some legacy COPY error paths). Treat as empty desc.
1708
+ q.current = {
1709
+ command: "",
1710
+ rowCount: null,
1711
+ oid: null,
1712
+ fields: [],
1713
+ rows: [],
1714
+ notices: [],
1715
+ };
1716
+ }
1717
+ q.current.rows.push(decodeDataRow(msg.values, q.current.fields));
1718
+ return;
1719
+ }
1720
+ case "CommandComplete": {
1721
+ const { command, rowCount, oid } = parseCommandTag(msg.tag);
1722
+ const set = q.current ?? {
1723
+ command,
1724
+ rowCount: rowCount,
1725
+ oid,
1726
+ fields: [],
1727
+ rows: [],
1728
+ notices: [],
1729
+ };
1730
+ set.command = command;
1731
+ set.rowCount = rowCount;
1732
+ set.oid = oid;
1733
+ set.notices = q.notices.splice(0);
1734
+ q.finished.push(set);
1735
+ q.current = null;
1736
+ return;
1737
+ }
1738
+ case "EmptyQueryResponse": {
1739
+ const set = {
1740
+ command: "",
1741
+ rowCount: null,
1742
+ oid: null,
1743
+ fields: [],
1744
+ rows: [],
1745
+ notices: q.notices.splice(0),
1746
+ };
1747
+ q.finished.push(set);
1748
+ q.current = null;
1749
+ return;
1750
+ }
1751
+ case "ParameterStatus":
1752
+ this.params.set(msg.name, msg.value);
1753
+ if (msg.name === "server_version") {
1754
+ this.serverVersion = parseServerVersion(msg.value);
1755
+ }
1756
+ return;
1757
+ case "NoticeResponse": {
1758
+ const notice = fieldsToNotice(msg.fields);
1759
+ q.notices.push(notice);
1760
+ this.notify.emit(notice);
1761
+ return;
1762
+ }
1763
+ case "NotificationResponse":
1764
+ this.notify.emitNotification(msg.channel, msg.payload, msg.processId);
1765
+ return;
1766
+ case "ErrorResponse": {
1767
+ q.error = fieldsToConnectError(msg.fields);
1768
+ // Don't reject yet — ReadyForQuery will arrive shortly and we want
1769
+ // to drain queued NoticeResponse messages first.
1770
+ return;
1771
+ }
1772
+ case "ReadyForQuery": {
1773
+ this.txStatus = msg.status;
1774
+ this.state = "idle";
1775
+ this.pendingQuery = null;
1776
+ if (q.error) {
1777
+ // Mirror libpq's behaviour: the result list contains every
1778
+ // PGresult the server produced before the ErrorResponse — for
1779
+ // a `\;`-chained simple-query batch, that's all the statements
1780
+ // before the failing one. We surface them by attaching the
1781
+ // accumulated `finished[]` to the thrown Error so callers
1782
+ // (`executeAndPrint`) can render the pre-error rows in order
1783
+ // before printing the error itself.
1784
+ const err = asThrowable(q.error);
1785
+ err.partialResults = q.finished;
1786
+ q.reject(err);
1787
+ }
1788
+ else {
1789
+ q.resolve(q.finished);
1790
+ }
1791
+ return;
1792
+ }
1793
+ case "CopyInResponse": {
1794
+ // PG 17 added pipeline + COPY support but libpq still rejects the
1795
+ // combination ("COPY in a pipeline is not supported, aborting
1796
+ // connection"). Upstream psql surfaces that diagnostic and tears down
1797
+ // the connection. We mirror the behaviour: if the user fires a COPY
1798
+ // statement via execSimple while a pipeline is active, abort.
1799
+ if (this._extPipelineActive) {
1800
+ this.abortForCopyInPipeline();
1801
+ return;
1802
+ }
1803
+ // CopyInResponse during execSimple (no active CopyIn driver) — the
1804
+ // common path is `COPY ... FROM STDIN` as one segment of a `\;`-chained
1805
+ // simple-query batch. Upstream psql pumps stdin lines until `\.`; the
1806
+ // mainloop pre-scans its input and buffers the bytes into
1807
+ // `copyInMidBatchQueue` before calling execSimple. We pop the head
1808
+ // buffer and ship it as CopyData + CopyDone. If no buffer is queued
1809
+ // (caller forgot to seed, or scan was inaccurate), CopyFail so the
1810
+ // server returns to ReadyForQuery rather than blocking.
1811
+ const data = this.copyInMidBatchQueue.shift();
1812
+ if (data !== undefined) {
1813
+ try {
1814
+ // Empty payload still needs a CopyDone — the server transitions
1815
+ // back to CopyIn-done state on CopyDone regardless of byte
1816
+ // count. Wrapping a zero-length CopyData is harmless.
1817
+ if (data.length > 0) {
1818
+ this.socket.write(CopyData(data));
1819
+ }
1820
+ this.socket.write(CopyDone());
1821
+ }
1822
+ catch {
1823
+ // Write failures are surfaced via socket 'error' / 'close'
1824
+ // handlers which will fail the pending query.
1825
+ }
1826
+ return;
1827
+ }
1828
+ q.error = {
1829
+ severity: "ERROR",
1830
+ message: "COPY FROM STDIN not supported via execSimple — use \\copy or startCopyIn",
1831
+ };
1832
+ try {
1833
+ this.socket.write(CopyFail("COPY FROM STDIN not driven by client"));
1834
+ }
1835
+ catch {
1836
+ // Write failures are surfaced via socket 'error' / 'close' handlers
1837
+ // which will fail the pending query — nothing to do here.
1838
+ }
1839
+ return;
1840
+ }
1841
+ case "CopyOutResponse": {
1842
+ if (this._extPipelineActive) {
1843
+ this.abortForCopyInPipeline();
1844
+ return;
1845
+ }
1846
+ // CopyOutResponse during execSimple (no active CopyOut driver) — the
1847
+ // common path is `COPY ... TO STDOUT` as one segment of a `\;`-chained
1848
+ // simple-query batch. We accumulate the CopyData payloads onto the
1849
+ // current ResultSet's `copyOutBytes` so the renderer emits them at
1850
+ // the result's position in the chain — instead of streaming them
1851
+ // straight to a sink at receive time, which would hoist the COPY
1852
+ // bytes above any tuples-producing results that haven't been
1853
+ // rendered yet (see hunk 5722-5730 in regress/psql).
1854
+ this.copyOutMidBatchActive = true;
1855
+ q.current = q.current ?? {
1856
+ command: "",
1857
+ rowCount: null,
1858
+ oid: null,
1859
+ fields: [],
1860
+ rows: [],
1861
+ notices: [],
1862
+ };
1863
+ q.current.copyOutBytes = q.current.copyOutBytes ?? [];
1864
+ return;
1865
+ }
1866
+ case "CopyData": {
1867
+ // CopyData arrives during execSimple only when we're in the mid-batch
1868
+ // COPY-OUT phase (CopyOutResponse flipped the flag above). Stash the
1869
+ // payload on the current result's `copyOutBytes` so the caller can
1870
+ // render in order. Anything else is a protocol error.
1871
+ if (this.copyOutMidBatchActive) {
1872
+ const cur = q.current;
1873
+ if (cur) {
1874
+ cur.copyOutBytes = cur.copyOutBytes ?? [];
1875
+ cur.copyOutBytes.push(msg.data);
1876
+ }
1877
+ return;
1878
+ }
1879
+ q.error = {
1880
+ severity: "ERROR",
1881
+ message: "Unexpected backend message during query: CopyData",
1882
+ };
1883
+ return;
1884
+ }
1885
+ case "CopyDone": {
1886
+ // Server signals end of COPY-OUT data — next message will be
1887
+ // CommandComplete for the COPY statement, then the batch resumes.
1888
+ if (this.copyOutMidBatchActive) {
1889
+ this.copyOutMidBatchActive = false;
1890
+ return;
1891
+ }
1892
+ q.error = {
1893
+ severity: "ERROR",
1894
+ message: "Unexpected backend message during query: CopyDone",
1895
+ };
1896
+ return;
1897
+ }
1898
+ case "CopyBothResponse": {
1899
+ // Walsender (`replication=database` / `replication=true`) commands
1900
+ // such as `START_REPLICATION` transition the connection into a
1901
+ // CopyBoth streaming phase (WAL records flowing from server +
1902
+ // keepalive replies flowing from client). This client does not
1903
+ // implement WAL streaming — upstream libpq's `PQexec` similarly
1904
+ // refuses to handle PGRES_COPY_BOTH and surfaces a diagnostic. We
1905
+ // mirror that: reject the pending query with a "syntax error" style
1906
+ // message (matching the conformance assertion) and tear the socket
1907
+ // down so the next query / process exit is clean.
1908
+ const cbErr = {
1909
+ severity: "ERROR",
1910
+ code: "0A000",
1911
+ message: "syntax error: unexpected CopyBothResponse from server (replication streaming is not supported by this client)",
1912
+ };
1913
+ q.error = cbErr;
1914
+ q.reject(asThrowable(cbErr));
1915
+ this.pendingQuery = null;
1916
+ this.socketError = new Error(cbErr.message);
1917
+ try {
1918
+ this.socket.destroy();
1919
+ }
1920
+ catch {
1921
+ // ignore
1922
+ }
1923
+ this.state = "closed";
1924
+ return;
1925
+ }
1926
+ default:
1927
+ // Unknown messages during a query are protocol errors but not fatal
1928
+ // for the connection — record them.
1929
+ q.error = {
1930
+ severity: "ERROR",
1931
+ message: `Unexpected backend message during query: ${msg.type}`,
1932
+ };
1933
+ return;
1934
+ }
1935
+ }
1936
+ // -------------------------------------------------------------------------
1937
+ // Socket → parser → state dispatch
1938
+ // -------------------------------------------------------------------------
1939
+ onData(chunk) {
1940
+ let messages;
1941
+ try {
1942
+ messages = this.parser.feed(chunk);
1943
+ }
1944
+ catch (err) {
1945
+ this.socketError =
1946
+ err instanceof Error ? err : new Error(String(err));
1947
+ this.failPending(this.socketError);
1948
+ try {
1949
+ this.socket.destroy();
1950
+ }
1951
+ catch {
1952
+ // ignore
1953
+ }
1954
+ this.state = "closed";
1955
+ return;
1956
+ }
1957
+ for (const msg of messages) {
1958
+ this.dispatch(msg);
1959
+ if (this.state === "closed")
1960
+ break;
1961
+ }
1962
+ }
1963
+ dispatch(msg) {
1964
+ // Async backend messages always allowed. NotificationResponse can arrive
1965
+ // in *any* state since LISTEN payloads come in whenever a NOTIFY fires.
1966
+ if (msg.type === "NotificationResponse") {
1967
+ this.notify.emitNotification(msg.channel, msg.payload, msg.processId);
1968
+ return;
1969
+ }
1970
+ switch (this.state) {
1971
+ case "auth":
1972
+ this.handleAuthMessage(msg);
1973
+ return;
1974
+ case "await-ready":
1975
+ this.handleAwaitReady(msg);
1976
+ return;
1977
+ case "idle":
1978
+ // ParameterStatus changes can arrive asynchronously (SET).
1979
+ if (msg.type === "ParameterStatus") {
1980
+ this.params.set(msg.name, msg.value);
1981
+ if (msg.name === "server_version") {
1982
+ this.serverVersion = parseServerVersion(msg.value);
1983
+ }
1984
+ return;
1985
+ }
1986
+ if (msg.type === "NoticeResponse") {
1987
+ this.notify.emit(fieldsToNotice(msg.fields));
1988
+ return;
1989
+ }
1990
+ // (NotificationResponse is handled by the early-out above.)
1991
+ // Anything else in idle is unexpected.
1992
+ this.socketError = new Error(`Unexpected ${msg.type} in idle state`);
1993
+ try {
1994
+ this.socket.destroy();
1995
+ }
1996
+ catch {
1997
+ // ignore
1998
+ }
1999
+ this.state = "closed";
2000
+ return;
2001
+ case "in-query":
2002
+ this.handleQueryMessage(msg);
2003
+ return;
2004
+ case "in-extended":
2005
+ this.handleExtendedMessage(msg);
2006
+ return;
2007
+ case "in-copy-in":
2008
+ this.handleCopyInMessage(msg);
2009
+ return;
2010
+ case "in-copy-out":
2011
+ this.handleCopyOutMessage(msg);
2012
+ return;
2013
+ case "closed":
2014
+ return;
2015
+ }
2016
+ }
2017
+ failPending(err) {
2018
+ if (this.pendingQuery) {
2019
+ const q = this.pendingQuery;
2020
+ this.pendingQuery = null;
2021
+ // If the server delivered an ErrorResponse just before the socket
2022
+ // closed (e.g. a FATAL "terminating connection due to administrator
2023
+ // command" when the backend is killed mid-query), prefer that
2024
+ // structured error over the generic "Socket closed" fallback so the
2025
+ // diagnostic carries the server's wording. Mirrors libpq's behaviour
2026
+ // where `PQexec` surfaces the FATAL message and `PQerrorMessage`
2027
+ // returns the server-supplied text.
2028
+ //
2029
+ // `q.error` is initialised to `null` by `execSimple`; only a non-null
2030
+ // value indicates a server-side ErrorResponse was actually captured.
2031
+ q.reject(q.error != null ? asThrowable(q.error) : err);
2032
+ }
2033
+ if (this.extDriver) {
2034
+ const d = this.extDriver;
2035
+ this.extDriver = null;
2036
+ for (const op of d.queue)
2037
+ op.reject(err);
2038
+ }
2039
+ if (this.startupReject) {
2040
+ const r = this.startupReject;
2041
+ this.startupResolve = null;
2042
+ this.startupReject = null;
2043
+ r(err);
2044
+ }
2045
+ if (this.copyStartReject) {
2046
+ const r = this.copyStartReject;
2047
+ this.copyStartResolve = null;
2048
+ this.copyStartReject = null;
2049
+ r(err);
2050
+ }
2051
+ if (this.copyIn) {
2052
+ const d = this.copyIn;
2053
+ this.copyIn = null;
2054
+ if (d.rejectDone)
2055
+ d.rejectDone(err);
2056
+ }
2057
+ if (this.copyOut) {
2058
+ const d = this.copyOut;
2059
+ this.copyOut = null;
2060
+ d.error =
2061
+ err instanceof Error
2062
+ ? { severity: "ERROR", message: err.message }
2063
+ : { severity: "ERROR", message: String(err) };
2064
+ if (d.waker) {
2065
+ const w = d.waker;
2066
+ d.waker = null;
2067
+ w();
2068
+ }
2069
+ }
2070
+ }
2071
+ ensureIdle() {
2072
+ if (this.state === "closed") {
2073
+ throw new Error("PgConnection: connection is closed");
2074
+ }
2075
+ if (this.state !== "idle" && this.state !== "in-extended") {
2076
+ throw new Error(`PgConnection: cannot start query in state ${this.state}`);
2077
+ }
2078
+ }
2079
+ // -------------------------------------------------------------------------
2080
+ // Extended-protocol driver (WP-21).
2081
+ //
2082
+ // Each public enqueueX method appends one op to `extDriver.queue` and
2083
+ // returns a Promise that resolves when the op's terminator backend message
2084
+ // arrives. The caller is responsible for writing the matching wire frame
2085
+ // (Parse/Bind/Describe/Execute/Close/Sync) to the socket.
2086
+ // -------------------------------------------------------------------------
2087
+ startExtendedBatch() {
2088
+ if (this.state === "idle") {
2089
+ this.state = "in-extended";
2090
+ this.extDriver = { queue: [], error: null };
2091
+ }
2092
+ else if (this.state !== "in-extended") {
2093
+ throw new Error(`PgConnection: cannot start extended batch in state ${this.state}`);
2094
+ }
2095
+ else if (!this.extDriver) {
2096
+ this.extDriver = { queue: [], error: null };
2097
+ }
2098
+ }
2099
+ writeRaw(buf) {
2100
+ this.socket.write(buf);
2101
+ }
2102
+ enqueueParse() {
2103
+ return this.enqueueOp({
2104
+ kind: "parse",
2105
+ resolve: () => undefined,
2106
+ reject: () => undefined,
2107
+ });
2108
+ }
2109
+ enqueueBind() {
2110
+ return this.enqueueOp({
2111
+ kind: "bind",
2112
+ resolve: () => undefined,
2113
+ reject: () => undefined,
2114
+ });
2115
+ }
2116
+ enqueueDescribeStatement() {
2117
+ return this.enqueueOp({
2118
+ kind: "describeS",
2119
+ resolve: () => undefined,
2120
+ reject: () => undefined,
2121
+ paramOids: null,
2122
+ });
2123
+ }
2124
+ enqueueDescribePortal() {
2125
+ return this.enqueueOp({
2126
+ kind: "describeP",
2127
+ resolve: () => undefined,
2128
+ reject: () => undefined,
2129
+ });
2130
+ }
2131
+ /**
2132
+ * Variant of {@link enqueueDescribePortal} that pipes the resolved fields
2133
+ * onto the very next `execute` op already (or yet to be) on the queue.
2134
+ */
2135
+ enqueueDescribePortalIntoNextExecute() {
2136
+ const driver = this.extDriver;
2137
+ if (!driver) {
2138
+ return Promise.reject(new Error("enqueueDescribePortalIntoNextExecute: not in extended state"));
2139
+ }
2140
+ return new Promise((resolve, reject) => {
2141
+ driver.queue.push({
2142
+ kind: "describeP",
2143
+ resolve: (v) => {
2144
+ const fields = v;
2145
+ for (const op of driver.queue) {
2146
+ if (op.kind === "execute" && op.fields === null) {
2147
+ op.fields = fields;
2148
+ break;
2149
+ }
2150
+ }
2151
+ resolve();
2152
+ },
2153
+ reject,
2154
+ });
2155
+ });
2156
+ }
2157
+ enqueueExecute() {
2158
+ return this.enqueueOp({
2159
+ kind: "execute",
2160
+ resolve: () => undefined,
2161
+ reject: () => undefined,
2162
+ current: null,
2163
+ notices: [],
2164
+ fields: null,
2165
+ });
2166
+ }
2167
+ enqueueExecuteWithFields(fields) {
2168
+ return this.enqueueOp({
2169
+ kind: "execute",
2170
+ resolve: () => undefined,
2171
+ reject: () => undefined,
2172
+ current: null,
2173
+ notices: [],
2174
+ fields,
2175
+ });
2176
+ }
2177
+ enqueueClose() {
2178
+ return this.enqueueOp({
2179
+ kind: "close",
2180
+ resolve: () => undefined,
2181
+ reject: () => undefined,
2182
+ });
2183
+ }
2184
+ enqueueSync() {
2185
+ return this.enqueueOp({
2186
+ kind: "sync",
2187
+ resolve: () => undefined,
2188
+ reject: () => undefined,
2189
+ });
2190
+ }
2191
+ enqueueOp(opSkeleton) {
2192
+ if (!this.extDriver) {
2193
+ return Promise.reject(new Error("enqueueOp: not in extended state"));
2194
+ }
2195
+ const driver = this.extDriver;
2196
+ return new Promise((resolve, reject) => {
2197
+ const op = opSkeleton;
2198
+ op.resolve = resolve;
2199
+ op.reject = reject;
2200
+ driver.queue.push(op);
2201
+ });
2202
+ }
2203
+ handleExtendedMessage(msg) {
2204
+ const driver = this.extDriver;
2205
+ if (!driver)
2206
+ return;
2207
+ if (msg.type === "ParameterStatus") {
2208
+ this.params.set(msg.name, msg.value);
2209
+ if (msg.name === "server_version") {
2210
+ this.serverVersion = parseServerVersion(msg.value);
2211
+ }
2212
+ return;
2213
+ }
2214
+ if (msg.type === "NoticeResponse") {
2215
+ const notice = fieldsToNotice(msg.fields);
2216
+ this.notify.emit(notice);
2217
+ const head = driver.queue[0];
2218
+ if (head && head.kind === "execute")
2219
+ head.notices.push(notice);
2220
+ return;
2221
+ }
2222
+ if (msg.type === "NotificationResponse") {
2223
+ this.notify.emitNotification(msg.channel, msg.payload, msg.processId);
2224
+ return;
2225
+ }
2226
+ if (msg.type === "ErrorResponse") {
2227
+ driver.error = fieldsToConnectError(msg.fields);
2228
+ // Reject ALL queued non-sync ops eagerly. Upstream server semantics:
2229
+ // once a P/B/D/E op errors, the server skips every subsequent message
2230
+ // until the next Sync. If the client (e.g. `\flushrequest` + `\getresults`
2231
+ // after an aborted bind) doesn't issue Sync next, no further wire
2232
+ // messages will arrive — so we must cascade-reject the rest of the
2233
+ // queue NOW or those promises hang forever.
2234
+ //
2235
+ // Mirror libpq's `PGRES_PIPELINE_ABORTED` marker for follow-on ops:
2236
+ // the FIRST failing op carries the real `ErrorResponse` payload,
2237
+ // every subsequent op gets a synthetic "Pipeline aborted, command
2238
+ // did not run" error so `\getresults` / `\endpipeline` can
2239
+ // distinguish the originating ERROR from the cascaded skips. See
2240
+ // upstream `pqPipelineProcessQueue` in `fe-exec.c`.
2241
+ let first = true;
2242
+ while (driver.queue.length > 0) {
2243
+ const head = driver.queue[0];
2244
+ if (head.kind === "sync")
2245
+ break;
2246
+ driver.queue.shift();
2247
+ if (first) {
2248
+ head.reject(driver.error);
2249
+ first = false;
2250
+ }
2251
+ else {
2252
+ head.reject(pipelineAbortedError());
2253
+ }
2254
+ }
2255
+ return;
2256
+ }
2257
+ // COPY-in-pipeline: when an `Execute` in pipeline mode hits a
2258
+ // `COPY ... FROM STDIN` / `COPY ... TO STDOUT`, the server replies
2259
+ // with `CopyInResponse` / `CopyOutResponse` instead of the usual
2260
+ // result-stream messages. Upstream libpq refuses the combination
2261
+ // with "COPY in a pipeline is not supported, aborting connection"
2262
+ // and tears the connection down. Mirror that so `\startpipeline +
2263
+ // COPY ...` surfaces the expected fatal error rather than hanging
2264
+ // on a response the extended driver doesn't know how to consume.
2265
+ if (msg.type === "CopyInResponse" || msg.type === "CopyOutResponse") {
2266
+ this.abortForCopyInPipeline();
2267
+ return;
2268
+ }
2269
+ // Drain any ops added to the queue AFTER the initial cascade-reject
2270
+ // (e.g. a `\sendpipeline` issued by the user once `\getresults`
2271
+ // returned the first ErrorResponse) — those ops were never visible
2272
+ // to the original cascade loop, but the server skipped them too
2273
+ // because it stays in PIPELINE_ABORTED until the next Sync. Mark
2274
+ // them as cascaded (`pipelineAborted`) rather than the real error:
2275
+ // libpq surfaces the real error only on the OP that actually
2276
+ // failed, and stamps every subsequent skipped op with the
2277
+ // PGRES_PIPELINE_ABORTED marker. The cmd layer's `\getresults` /
2278
+ // `\endpipeline` paths render the marker as
2279
+ // `Pipeline aborted, command did not run` (no `ERROR:` prefix).
2280
+ while (driver.error !== null) {
2281
+ const head = driver.queue[0];
2282
+ if (!head || head.kind === "sync")
2283
+ break;
2284
+ driver.queue.shift();
2285
+ head.reject(pipelineAbortedError());
2286
+ }
2287
+ const head = driver.queue[0];
2288
+ if (!head) {
2289
+ this.protocolFail(new Error(`Unexpected backend message ${msg.type} in in-extended`));
2290
+ return;
2291
+ }
2292
+ switch (msg.type) {
2293
+ case "ParseComplete":
2294
+ if (head.kind !== "parse") {
2295
+ this.protocolFail(new Error("ParseComplete arrived but head op is " + head.kind));
2296
+ return;
2297
+ }
2298
+ driver.queue.shift();
2299
+ head.resolve(undefined);
2300
+ return;
2301
+ case "BindComplete":
2302
+ if (head.kind !== "bind") {
2303
+ this.protocolFail(new Error("BindComplete arrived but head op is " + head.kind));
2304
+ return;
2305
+ }
2306
+ driver.queue.shift();
2307
+ head.resolve(undefined);
2308
+ return;
2309
+ case "CloseComplete":
2310
+ if (head.kind !== "close") {
2311
+ this.protocolFail(new Error("CloseComplete arrived but head op is " + head.kind));
2312
+ return;
2313
+ }
2314
+ driver.queue.shift();
2315
+ head.resolve(undefined);
2316
+ return;
2317
+ case "ParameterDescription":
2318
+ if (head.kind !== "describeS") {
2319
+ this.protocolFail(new Error("ParameterDescription arrived but head op is " +
2320
+ head.kind));
2321
+ return;
2322
+ }
2323
+ head.paramOids = msg.oids;
2324
+ return;
2325
+ case "RowDescription":
2326
+ if (head.kind === "describeS") {
2327
+ driver.queue.shift();
2328
+ head.resolve({
2329
+ paramOids: head.paramOids ?? [],
2330
+ fields: msg.fields,
2331
+ });
2332
+ return;
2333
+ }
2334
+ if (head.kind === "describeP") {
2335
+ driver.queue.shift();
2336
+ head.resolve(msg.fields);
2337
+ return;
2338
+ }
2339
+ if (head.kind === "execute") {
2340
+ head.current = {
2341
+ command: "",
2342
+ rowCount: null,
2343
+ oid: null,
2344
+ fields: msg.fields,
2345
+ rows: [],
2346
+ notices: [],
2347
+ };
2348
+ head.fields = msg.fields;
2349
+ return;
2350
+ }
2351
+ this.protocolFail(new Error("Unexpected RowDescription at head op " + head.kind));
2352
+ return;
2353
+ case "NoData":
2354
+ if (head.kind === "describeS") {
2355
+ driver.queue.shift();
2356
+ head.resolve({
2357
+ paramOids: head.paramOids ?? [],
2358
+ fields: [],
2359
+ });
2360
+ return;
2361
+ }
2362
+ if (head.kind === "describeP") {
2363
+ driver.queue.shift();
2364
+ head.resolve([]);
2365
+ return;
2366
+ }
2367
+ this.protocolFail(new Error("Unexpected NoData at head op " + head.kind));
2368
+ return;
2369
+ case "DataRow": {
2370
+ if (head.kind !== "execute") {
2371
+ this.protocolFail(new Error("DataRow at head op " + head.kind));
2372
+ return;
2373
+ }
2374
+ const fields = head.fields ?? head.current?.fields ?? [];
2375
+ if (!head.current) {
2376
+ head.current = {
2377
+ command: "",
2378
+ rowCount: null,
2379
+ oid: null,
2380
+ fields,
2381
+ rows: [],
2382
+ notices: [],
2383
+ };
2384
+ }
2385
+ head.current.rows.push(decodeDataRow(msg.values, fields));
2386
+ return;
2387
+ }
2388
+ case "CommandComplete": {
2389
+ if (head.kind !== "execute") {
2390
+ this.protocolFail(new Error("CommandComplete at head op " + head.kind));
2391
+ return;
2392
+ }
2393
+ const { command, rowCount, oid } = parseCommandTag(msg.tag);
2394
+ const set = head.current ?? {
2395
+ command,
2396
+ rowCount,
2397
+ oid,
2398
+ fields: head.fields ?? [],
2399
+ rows: [],
2400
+ notices: [],
2401
+ };
2402
+ set.command = command;
2403
+ set.rowCount = rowCount;
2404
+ set.oid = oid;
2405
+ set.notices = head.notices.splice(0);
2406
+ driver.queue.shift();
2407
+ head.resolve(set);
2408
+ return;
2409
+ }
2410
+ case "EmptyQueryResponse": {
2411
+ if (head.kind !== "execute") {
2412
+ this.protocolFail(new Error("EmptyQueryResponse at head op " + head.kind));
2413
+ return;
2414
+ }
2415
+ const set = {
2416
+ command: "",
2417
+ rowCount: null,
2418
+ oid: null,
2419
+ fields: [],
2420
+ rows: [],
2421
+ notices: head.notices.splice(0),
2422
+ };
2423
+ driver.queue.shift();
2424
+ head.resolve(set);
2425
+ return;
2426
+ }
2427
+ case "PortalSuspended": {
2428
+ if (head.kind !== "execute") {
2429
+ this.protocolFail(new Error("PortalSuspended at head op " + head.kind));
2430
+ return;
2431
+ }
2432
+ const set = head.current ?? {
2433
+ command: "",
2434
+ rowCount: null,
2435
+ oid: null,
2436
+ fields: head.fields ?? [],
2437
+ rows: [],
2438
+ notices: head.notices.splice(0),
2439
+ };
2440
+ set.notices = head.notices.splice(0);
2441
+ driver.queue.shift();
2442
+ head.resolve(set);
2443
+ return;
2444
+ }
2445
+ case "ReadyForQuery": {
2446
+ this.txStatus = msg.status;
2447
+ if (head.kind !== "sync") {
2448
+ this.protocolFail(new Error("ReadyForQuery but head op is " + head.kind));
2449
+ return;
2450
+ }
2451
+ driver.queue.shift();
2452
+ const stickyErr = driver.error;
2453
+ driver.error = null;
2454
+ if (stickyErr) {
2455
+ head.reject(stickyErr);
2456
+ }
2457
+ else {
2458
+ head.resolve(undefined);
2459
+ }
2460
+ if (driver.queue.length === 0 && !this._extPipelineActive) {
2461
+ this.state = "idle";
2462
+ this.extDriver = null;
2463
+ }
2464
+ return;
2465
+ }
2466
+ default:
2467
+ this.protocolFail(new Error(`Unexpected ${msg.type} in in-extended state`));
2468
+ return;
2469
+ }
2470
+ }
2471
+ protocolFail(err) {
2472
+ this.socketError = err;
2473
+ this.failPending(err);
2474
+ try {
2475
+ this.socket.destroy();
2476
+ }
2477
+ catch {
2478
+ // ignore
2479
+ }
2480
+ this.state = "closed";
2481
+ }
2482
+ /**
2483
+ * Abort the connection because the server replied with CopyInResponse /
2484
+ * CopyOutResponse while a pipeline (`_extPipelineActive`) was active.
2485
+ * Upstream libpq emits the exact diagnostic
2486
+ * `"COPY in a pipeline is not supported, aborting connection"` and tears
2487
+ * the socket down — we mirror that. Pending operations are rejected; the
2488
+ * connection is left in `closed` so subsequent commands fail cleanly
2489
+ * (matching the "aborting connection" promise).
2490
+ */
2491
+ abortForCopyInPipeline() {
2492
+ const err = {
2493
+ severity: "FATAL",
2494
+ message: "COPY in a pipeline is not supported, aborting connection",
2495
+ };
2496
+ this.socketError = new Error(err.message);
2497
+ this.failPending(err);
2498
+ try {
2499
+ this.socket.destroy();
2500
+ }
2501
+ catch {
2502
+ // ignore
2503
+ }
2504
+ this.state = "closed";
2505
+ }
2506
+ }
2507
+ // -------------------------------------------------------------------------
2508
+ // Public factory
2509
+ // -------------------------------------------------------------------------
2510
+ /**
2511
+ * Pluggable random source for `load_balance_hosts=random`. Public so tests
2512
+ * can inject a deterministic permutation; production code leaves it `null`
2513
+ * and falls back to `Math.random`. NOT part of the connection's external
2514
+ * contract — internal-only escape hatch.
2515
+ */
2516
+ PgConnection._loadBalanceRng = null;
2517
+ /**
2518
+ * Pluggable DNS resolver for the multi-IP host fan-out (libpq's
2519
+ * `getaddrinfo`-then-iterate behaviour, exercised by upstream's
2520
+ * `004_load_balance_dns.pl`). Tests inject a fake to drive a hostname
2521
+ * through a fixed IP set without touching the real resolver; production
2522
+ * code leaves it `null` and falls back to `dns.lookup(host, {all: true})`.
2523
+ * Returning an empty array signals "treat as unresolvable" and the
2524
+ * candidate is dropped from the iteration set (matching libpq's "no
2525
+ * results from getaddrinfo" path).
2526
+ */
2527
+ PgConnection._dnsLookupAll = null;
2528
+ // ---------------------------------------------------------------------------
2529
+ // Socket open helper. Supports TCP (default) and Unix-domain sockets when
2530
+ // `opts.host` starts with `/` — matching libpq's `pqUnixSocketPath()` which
2531
+ // reads the directory from PGHOST and builds `<dir>/.s.PGSQL.<port>` as the
2532
+ // actual filesystem socket path.
2533
+ // ---------------------------------------------------------------------------
2534
+ /**
2535
+ * `true` if the host value should be interpreted as a Unix-domain socket
2536
+ * directory. libpq's rule: any value starting with `/` is a path.
2537
+ */
2538
+ export function isUnixSocketHost(host) {
2539
+ return host.startsWith("/");
2540
+ }
2541
+ /**
2542
+ * Build the actual filesystem path Postgres listens on under a socket
2543
+ * directory: `<dir>/.s.PGSQL.<port>`. Mirrors the libpq layout so any
2544
+ * server started with `unix_socket_directories=<dir>` is reachable.
2545
+ */
2546
+ export function unixSocketPath(dir, port) {
2547
+ return `${dir}/.s.PGSQL.${String(port)}`;
2548
+ }
2549
+ /**
2550
+ * Expand the configured (host, port) list by resolving each hostname to
2551
+ * its full set of A/AAAA records. Mirrors libpq's `getaddrinfo`-then-
2552
+ * iterate-all behaviour exercised by upstream's
2553
+ * `src/interfaces/libpq/t/004_load_balance_dns.pl`. Without this step a
2554
+ * single hostname that resolves to N IPs would only ever produce one
2555
+ * candidate (Node's `net.connect({host})` picks one address from the
2556
+ * lookup result), so `load_balance_hosts=random` couldn't shuffle across
2557
+ * the DNS-returned set.
2558
+ *
2559
+ * - Unix-domain socket paths (`/var/run/postgres`) are passed through
2560
+ * unchanged — they don't participate in DNS at all.
2561
+ * - IPv4/IPv6 literals are passed through unchanged — DNS resolution
2562
+ * would just round-trip them.
2563
+ * - Hostnames are resolved via `dns.lookup(host, {all: true})`. The
2564
+ * test seam `PgConnection._dnsLookupAll` overrides the resolver so
2565
+ * unit tests can drive a hostname through a fixed IP set without
2566
+ * touching the real DNS.
2567
+ * - A hostname that fails to resolve (or returns zero records) is
2568
+ * dropped from the iteration set. The connect loop's `lastErr`
2569
+ * surfaces the original error if every host fails.
2570
+ */
2571
+ async function expandHostsViaDns(seed) {
2572
+ const out = [];
2573
+ for (const c of seed) {
2574
+ if (isUnixSocketHost(c.host) || net.isIP(c.host) !== 0) {
2575
+ // Unix-domain socket paths and IP literals don't go through DNS.
2576
+ // Leave `address` undefined so `openSocket` uses `host` directly.
2577
+ out.push({ host: c.host, port: c.port });
2578
+ continue;
2579
+ }
2580
+ let addrs;
2581
+ try {
2582
+ addrs = PgConnection._dnsLookupAll
2583
+ ? await PgConnection._dnsLookupAll(c.host)
2584
+ : await dns.lookup(c.host, { all: true, family: 0 });
2585
+ }
2586
+ catch {
2587
+ // dns.lookup rejects with ENOTFOUND / EAI_AGAIN / EAI_NONAME on
2588
+ // resolution failure. Skip this host; the outer connect loop will
2589
+ // surface the failure via `lastErr` if every candidate is dropped.
2590
+ continue;
2591
+ }
2592
+ for (const a of addrs) {
2593
+ // Keep the ORIGINAL hostname on `host` so TLS SNI / verify-full
2594
+ // and `conn.host` see the user-typed name. The IP goes on
2595
+ // `address`, used only by `openSocket` for the actual TCP connect.
2596
+ out.push({ host: c.host, address: a.address, port: c.port });
2597
+ }
2598
+ }
2599
+ return out;
2600
+ }
2601
+ /**
2602
+ * Map a libpq protocol-version string (`TLSv1` / `TLSv1.1` / `TLSv1.2` /
2603
+ * `TLSv1.3`) to Node's `SecureVersion` literal. Returns `undefined` for
2604
+ * unset / empty input. Unknown values shouldn't reach here (the parsing
2605
+ * layer in `index.ts` validates them), but we return `undefined` rather than
2606
+ * casting so a stray value can't smuggle a bogus literal into Node's TLS
2607
+ * options.
2608
+ */
2609
+ function toSecureVersion(value) {
2610
+ switch (value) {
2611
+ case "TLSv1":
2612
+ case "TLSv1.1":
2613
+ case "TLSv1.2":
2614
+ case "TLSv1.3":
2615
+ return value;
2616
+ default:
2617
+ return undefined;
2618
+ }
2619
+ }
2620
+ /**
2621
+ * Map libpq's `ssl_min_protocol_version` / `ssl_max_protocol_version` onto
2622
+ * Node's `tls.connect` `minVersion` / `maxVersion`. Unset values leave Node's
2623
+ * compiled-in defaults in place.
2624
+ */
2625
+ function applyTlsProtocolVersionRange(tlsOpts, opts) {
2626
+ const min = toSecureVersion(opts.sslMinProtocolVersion);
2627
+ if (min !== undefined)
2628
+ tlsOpts.minVersion = min;
2629
+ const max = toSecureVersion(opts.sslMaxProtocolVersion);
2630
+ if (max !== undefined)
2631
+ tlsOpts.maxVersion = max;
2632
+ }
2633
+ /**
2634
+ * libpq `sslsni`: the TLS SNI servername to send, or `undefined` to suppress
2635
+ * the SNI extension entirely. `sslsni=0` (`opts.sslsni === false`) suppresses
2636
+ * it; unset / `sslsni=1` sends `opts.host` (libpq's default). Returned value
2637
+ * is spread into the `tls.connect` options as `servername`.
2638
+ *
2639
+ * Exported for unit tests.
2640
+ */
2641
+ export function tlsServername(opts) {
2642
+ return opts.sslsni === false ? undefined : opts.host;
2643
+ }
2644
+ /**
2645
+ * Translate libpq's `keepalives` / `keepalives_idle` into the arguments for
2646
+ * Node's `socket.setKeepAlive(enable, initialDelay)`:
2647
+ * - `enable`: `false` only when `keepalives === false` (libpq `keepalives=0`);
2648
+ * unset / `true` keeps keepalives on (libpq default).
2649
+ * - `initialDelayMs`: `keepalives_idle` seconds → milliseconds, or
2650
+ * `undefined` to leave the OS default.
2651
+ *
2652
+ * libpq's `keepalives_interval` and `keepalives_count` have NO Node net API
2653
+ * equivalent (`setKeepAlive` exposes only enable + initial delay), so they are
2654
+ * intentionally not represented here.
2655
+ *
2656
+ * Exported for unit tests.
2657
+ */
2658
+ export function keepAliveArgs(opts) {
2659
+ return {
2660
+ enable: opts.keepalives !== false,
2661
+ initialDelayMs: opts.keepalivesIdle !== undefined
2662
+ ? opts.keepalivesIdle * 1000
2663
+ : undefined,
2664
+ };
2665
+ }
2666
+ /**
2667
+ * Derive the symmetric key length (in bits) from a negotiated TLS cipher
2668
+ * name, for the PG18 `\conninfo` "SSL Key Bits" row. Node's TLS API doesn't
2669
+ * expose the key length directly, so we parse it out of the cipher name the
2670
+ * way upstream's `SSL_CIPHER_get_bits` effectively reports it:
2671
+ *
2672
+ * - `AES_256` / `CHACHA20` → 256
2673
+ * - `AES_128` → 128
2674
+ * - otherwise, the first run of digits in the standard name (`…128…` etc.)
2675
+ * - `null` when no length can be determined.
2676
+ *
2677
+ * Both the OpenSSL standard name (`TLS_AES_256_GCM_SHA384`,
2678
+ * `ECDHE-RSA-AES128-GCM-SHA256`) and Node's IANA-style name are handled by
2679
+ * uppercasing and matching the keyword forms first. Exported for unit tests.
2680
+ */
2681
+ export function sslKeyBitsFromCipher(name) {
2682
+ const upper = name.toUpperCase();
2683
+ if (upper.includes("CHACHA20"))
2684
+ return 256;
2685
+ if (upper.includes("AES_256") || upper.includes("AES256"))
2686
+ return 256;
2687
+ if (upper.includes("AES_128") || upper.includes("AES128"))
2688
+ return 128;
2689
+ if (upper.includes("AES_192") || upper.includes("AES192"))
2690
+ return 192;
2691
+ const digits = /(\d{2,4})/.exec(upper);
2692
+ if (digits) {
2693
+ const n = parseInt(digits[1], 10);
2694
+ if (Number.isFinite(n) && n > 0)
2695
+ return n;
2696
+ }
2697
+ return null;
2698
+ }
2699
+ function openSocket(opts,
2700
+ /**
2701
+ * Pre-resolved IP. When set, used for `net.connect({host})` instead
2702
+ * of `opts.host` — lets DNS fan-out direct the TCP connect to a
2703
+ * specific A record while keeping the user-typed hostname elsewhere
2704
+ * (TLS SNI / `conn.host`). Ignored for Unix-domain socket paths,
2705
+ * which take their address from `opts.host` directly.
2706
+ */
2707
+ addressOverride) {
2708
+ return new Promise((resolve, reject) => {
2709
+ const isUnix = isUnixSocketHost(opts.host);
2710
+ const socket = isUnix
2711
+ ? net.connect({ path: unixSocketPath(opts.host, opts.port) })
2712
+ : net.connect({
2713
+ host: addressOverride ?? opts.host,
2714
+ port: opts.port,
2715
+ });
2716
+ // libpq TCP keepalives (no-op for Unix-domain sockets, matching libpq,
2717
+ // which only applies SO_KEEPALIVE on TCP).
2718
+ if (!isUnix) {
2719
+ const { enable, initialDelayMs } = keepAliveArgs(opts);
2720
+ if (initialDelayMs !== undefined) {
2721
+ socket.setKeepAlive(enable, initialDelayMs);
2722
+ }
2723
+ else {
2724
+ socket.setKeepAlive(enable);
2725
+ }
2726
+ }
2727
+ const timeout = opts.connectTimeoutMs;
2728
+ let timer = null;
2729
+ if (timeout !== undefined && timeout > 0) {
2730
+ timer = setTimeout(() => {
2731
+ socket.destroy(new Error(`Connect timed out after ${String(timeout)} ms`));
2732
+ }, timeout);
2733
+ }
2734
+ const cleanup = () => {
2735
+ if (timer)
2736
+ clearTimeout(timer);
2737
+ socket.removeListener("error", onError);
2738
+ socket.removeListener("connect", onConnect);
2739
+ };
2740
+ const onError = (err) => {
2741
+ cleanup();
2742
+ reject(err);
2743
+ };
2744
+ const onConnect = () => {
2745
+ cleanup();
2746
+ resolve(socket);
2747
+ };
2748
+ socket.once("error", onError);
2749
+ socket.once("connect", onConnect);
2750
+ });
2751
+ }
2752
+ // ---------------------------------------------------------------------------
2753
+ // Result decoding helpers
2754
+ // ---------------------------------------------------------------------------
2755
+ /**
2756
+ * Decode a wire-protocol DataRow into JS values. We follow the simple psql
2757
+ * policy: text format → utf-8 string, binary format → Buffer. Type-aware
2758
+ * decoding (timestamps, arrays, etc.) is the caller's responsibility — that
2759
+ * matches `psql` which prints raw server text.
2760
+ */
2761
+ function decodeDataRow(values, fields) {
2762
+ const out = new Array(values.length);
2763
+ for (let i = 0; i < values.length; i++) {
2764
+ const v = values[i];
2765
+ if (v === null) {
2766
+ out[i] = null;
2767
+ continue;
2768
+ }
2769
+ const fmt = fields[i]?.format ?? 0;
2770
+ out[i] = fmt === 1 ? v : v.toString("utf8");
2771
+ }
2772
+ return out;
2773
+ }
2774
+ /**
2775
+ * Parse the CommandComplete tag — examples:
2776
+ * "SELECT 17"
2777
+ * "INSERT 0 1" (oid is 0 in modern PG; second number is rowCount)
2778
+ * "UPDATE 3"
2779
+ * "CREATE TABLE" (no rowCount)
2780
+ *
2781
+ * Anything that doesn't match → command = the whole tag, rowCount = null.
2782
+ */
2783
+ function parseCommandTag(tag) {
2784
+ const trimmed = tag.trim();
2785
+ // INSERT is the only tag with the legacy oid + rowCount layout.
2786
+ const insertMatch = /^INSERT (\d+) (\d+)$/.exec(trimmed);
2787
+ if (insertMatch) {
2788
+ return {
2789
+ command: "INSERT",
2790
+ oid: parseInt(insertMatch[1], 10),
2791
+ rowCount: parseInt(insertMatch[2], 10),
2792
+ };
2793
+ }
2794
+ const m = /^([A-Z][A-Z ]*?)(?: (\d+))?$/.exec(trimmed);
2795
+ if (!m)
2796
+ return { command: trimmed, rowCount: null, oid: null };
2797
+ return {
2798
+ command: m[1],
2799
+ rowCount: m[2] !== undefined ? parseInt(m[2], 10) : null,
2800
+ oid: null,
2801
+ };
2802
+ }
2803
+ /**
2804
+ * Encode JS values into the (Buffer | string | null)[] format that
2805
+ * {@link Bind} accepts. Text-format only — server coerces. Matches psql's
2806
+ * default `\bind` behaviour.
2807
+ */
2808
+ export function encodeParams(values) {
2809
+ return values.map((v) => {
2810
+ if (v === null || v === undefined)
2811
+ return null;
2812
+ if (Buffer.isBuffer(v))
2813
+ return v;
2814
+ if (typeof v === "string")
2815
+ return v;
2816
+ if (typeof v === "boolean")
2817
+ return v ? "t" : "f";
2818
+ if (typeof v === "number" || typeof v === "bigint")
2819
+ return v.toString();
2820
+ try {
2821
+ return JSON.stringify(v);
2822
+ }
2823
+ catch {
2824
+ return "";
2825
+ }
2826
+ });
2827
+ }
2828
+ /**
2829
+ * Coerce arbitrary rejection values to a thrown `Error`.
2830
+ *
2831
+ * For our `ConnectError` shape (`{ severity, code, message, … }`), the
2832
+ * resulting Error preserves every enumerable field of the source object as
2833
+ * own properties — so callers can still read `.code`, `.severity`, `.hint`,
2834
+ * `.position`, etc. directly off the thrown value while also getting a proper
2835
+ * `Error` instance (so `instanceof Error` works and `.message` / `.stack` are
2836
+ * populated for generic loggers).
2837
+ */
2838
+ function asThrowable(v) {
2839
+ if (v instanceof Error)
2840
+ return v;
2841
+ if (typeof v === "object" &&
2842
+ v !== null &&
2843
+ "message" in v &&
2844
+ typeof v.message === "string") {
2845
+ const source = v;
2846
+ const err = new Error(source.message);
2847
+ // Copy every own enumerable field (severity, code, detail, hint, …) onto
2848
+ // the Error so structural consumers keep working.
2849
+ for (const key of Object.keys(source)) {
2850
+ if (key === "message")
2851
+ continue;
2852
+ err[key] = source[key];
2853
+ }
2854
+ err.cause = v;
2855
+ return err;
2856
+ }
2857
+ return new Error(String(v));
2858
+ }