neonctl 2.37.0 → 2.38.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (160) hide show
  1. package/{LICENSE.md → LICENSE} +27 -3
  2. package/README.md +15 -700
  3. package/bin/cli.js +3 -0
  4. package/package.json +8 -75
  5. package/dist/analytics.js +0 -168
  6. package/dist/api.js +0 -720
  7. package/dist/auth.js +0 -125
  8. package/dist/callback.html +0 -51
  9. package/dist/cli.js +0 -9
  10. package/dist/commands/api.js +0 -278
  11. package/dist/commands/auth.js +0 -214
  12. package/dist/commands/bootstrap.js +0 -481
  13. package/dist/commands/branches.js +0 -488
  14. package/dist/commands/bucket.js +0 -549
  15. package/dist/commands/checkout.js +0 -321
  16. package/dist/commands/config.js +0 -626
  17. package/dist/commands/connection_string.js +0 -172
  18. package/dist/commands/data_api.js +0 -284
  19. package/dist/commands/databases.js +0 -82
  20. package/dist/commands/deploy.js +0 -26
  21. package/dist/commands/dev.js +0 -698
  22. package/dist/commands/diff.js +0 -222
  23. package/dist/commands/env.js +0 -189
  24. package/dist/commands/functions.js +0 -373
  25. package/dist/commands/index.js +0 -62
  26. package/dist/commands/init.js +0 -73
  27. package/dist/commands/inspect.js +0 -65
  28. package/dist/commands/ip_allow.js +0 -137
  29. package/dist/commands/link.js +0 -1121
  30. package/dist/commands/neon_auth.js +0 -1028
  31. package/dist/commands/operations.js +0 -28
  32. package/dist/commands/orgs.js +0 -24
  33. package/dist/commands/projects.js +0 -413
  34. package/dist/commands/psql.js +0 -62
  35. package/dist/commands/roles.js +0 -65
  36. package/dist/commands/schema_diff.js +0 -151
  37. package/dist/commands/set_context.js +0 -29
  38. package/dist/commands/snapshots.js +0 -455
  39. package/dist/commands/status.js +0 -40
  40. package/dist/commands/user.js +0 -15
  41. package/dist/commands/vpc_endpoints.js +0 -134
  42. package/dist/config.js +0 -11
  43. package/dist/config_format.js +0 -72
  44. package/dist/context.js +0 -231
  45. package/dist/current_branch_fast_path.js +0 -55
  46. package/dist/dev/env.js +0 -244
  47. package/dist/dev/functions.js +0 -70
  48. package/dist/dev/inputs.js +0 -63
  49. package/dist/dev/runtime.js +0 -146
  50. package/dist/env.js +0 -36
  51. package/dist/env_file.js +0 -159
  52. package/dist/errors.js +0 -80
  53. package/dist/functions_api.js +0 -48
  54. package/dist/help.js +0 -146
  55. package/dist/index.js +0 -240
  56. package/dist/log.js +0 -18
  57. package/dist/parameters.gen.js +0 -480
  58. package/dist/pkg.js +0 -25
  59. package/dist/psql/cli.js +0 -53
  60. package/dist/psql/command/cmd_cond.js +0 -437
  61. package/dist/psql/command/cmd_connect.js +0 -820
  62. package/dist/psql/command/cmd_copy.js +0 -1035
  63. package/dist/psql/command/cmd_describe.js +0 -1815
  64. package/dist/psql/command/cmd_format.js +0 -948
  65. package/dist/psql/command/cmd_io.js +0 -2193
  66. package/dist/psql/command/cmd_lo.js +0 -393
  67. package/dist/psql/command/cmd_meta.js +0 -969
  68. package/dist/psql/command/cmd_misc.js +0 -187
  69. package/dist/psql/command/cmd_pipeline.js +0 -1148
  70. package/dist/psql/command/cmd_restrict.js +0 -171
  71. package/dist/psql/command/cmd_show.js +0 -766
  72. package/dist/psql/command/dispatch.js +0 -343
  73. package/dist/psql/command/inputQueue.js +0 -42
  74. package/dist/psql/command/shared.js +0 -71
  75. package/dist/psql/complete/filenames.js +0 -139
  76. package/dist/psql/complete/index.js +0 -104
  77. package/dist/psql/complete/matcher.js +0 -315
  78. package/dist/psql/complete/psqlVars.js +0 -249
  79. package/dist/psql/complete/queries.js +0 -493
  80. package/dist/psql/complete/rules.js +0 -2424
  81. package/dist/psql/core/common.js +0 -1253
  82. package/dist/psql/core/help.js +0 -576
  83. package/dist/psql/core/mainloop.js +0 -1360
  84. package/dist/psql/core/prompt.js +0 -439
  85. package/dist/psql/core/settings.js +0 -686
  86. package/dist/psql/core/sqlHelp.js +0 -1066
  87. package/dist/psql/core/startup.js +0 -846
  88. package/dist/psql/core/syncVars.js +0 -116
  89. package/dist/psql/core/variables.js +0 -287
  90. package/dist/psql/describe/formatters.js +0 -1330
  91. package/dist/psql/describe/processNamePattern.js +0 -270
  92. package/dist/psql/describe/queries.js +0 -2452
  93. package/dist/psql/describe/versionGate.js +0 -44
  94. package/dist/psql/index.js +0 -2030
  95. package/dist/psql/io/history.js +0 -299
  96. package/dist/psql/io/input.js +0 -120
  97. package/dist/psql/io/lineEditor/buffer.js +0 -325
  98. package/dist/psql/io/lineEditor/complete.js +0 -227
  99. package/dist/psql/io/lineEditor/filename.js +0 -159
  100. package/dist/psql/io/lineEditor/index.js +0 -893
  101. package/dist/psql/io/lineEditor/keymap.js +0 -745
  102. package/dist/psql/io/lineEditor/vt100.js +0 -363
  103. package/dist/psql/io/pgpass.js +0 -202
  104. package/dist/psql/io/pgservice.js +0 -194
  105. package/dist/psql/io/psqlrc.js +0 -422
  106. package/dist/psql/print/aligned.js +0 -1748
  107. package/dist/psql/print/asciidoc.js +0 -230
  108. package/dist/psql/print/crosstab.js +0 -463
  109. package/dist/psql/print/csv.js +0 -76
  110. package/dist/psql/print/html.js +0 -240
  111. package/dist/psql/print/json.js +0 -96
  112. package/dist/psql/print/latex.js +0 -379
  113. package/dist/psql/print/pager.js +0 -267
  114. package/dist/psql/print/troff.js +0 -240
  115. package/dist/psql/print/unaligned.js +0 -99
  116. package/dist/psql/print/units.js +0 -188
  117. package/dist/psql/scanner/slash.js +0 -515
  118. package/dist/psql/scanner/sql.js +0 -914
  119. package/dist/psql/scanner/stringutils.js +0 -394
  120. package/dist/psql/types/backslash.js +0 -1
  121. package/dist/psql/types/connection.js +0 -1
  122. package/dist/psql/types/index.js +0 -7
  123. package/dist/psql/types/printer.js +0 -1
  124. package/dist/psql/types/repl.js +0 -1
  125. package/dist/psql/types/scanner.js +0 -24
  126. package/dist/psql/types/settings.js +0 -1
  127. package/dist/psql/types/variables.js +0 -1
  128. package/dist/psql/wire/connection.js +0 -2857
  129. package/dist/psql/wire/copy.js +0 -108
  130. package/dist/psql/wire/notify.js +0 -59
  131. package/dist/psql/wire/pipeline.js +0 -521
  132. package/dist/psql/wire/protocol.js +0 -466
  133. package/dist/psql/wire/sasl.js +0 -294
  134. package/dist/psql/wire/tls.js +0 -602
  135. package/dist/storage_api.js +0 -147
  136. package/dist/test_utils/fixtures.js +0 -121
  137. package/dist/test_utils/oauth_server.js +0 -9
  138. package/dist/types.js +0 -1
  139. package/dist/utils/ai_gateway_notice.js +0 -180
  140. package/dist/utils/api_enums.js +0 -33
  141. package/dist/utils/auth.js +0 -5
  142. package/dist/utils/branch_notice.js +0 -22
  143. package/dist/utils/branch_picker.js +0 -103
  144. package/dist/utils/compute_units.js +0 -28
  145. package/dist/utils/config_diff.js +0 -185
  146. package/dist/utils/enrichers.js +0 -161
  147. package/dist/utils/esbuild.js +0 -158
  148. package/dist/utils/formats.js +0 -18
  149. package/dist/utils/git_diff.js +0 -90
  150. package/dist/utils/inspect_db.js +0 -153
  151. package/dist/utils/inspect_queries.js +0 -372
  152. package/dist/utils/middlewares.js +0 -20
  153. package/dist/utils/openapi.js +0 -114
  154. package/dist/utils/package_manager.js +0 -68
  155. package/dist/utils/point_in_time.js +0 -56
  156. package/dist/utils/psql.js +0 -120
  157. package/dist/utils/string.js +0 -5
  158. package/dist/utils/ui.js +0 -59
  159. package/dist/utils/zip.js +0 -4
  160. package/dist/writer.js +0 -97
@@ -1,846 +0,0 @@
1
- /**
2
- * psql startup-args parser + applier.
3
- *
4
- * TypeScript port of `parse_psql_options()` / the top of `main()` in
5
- * `src/bin/psql/startup.c`. Two responsibilities:
6
- *
7
- * 1. `parseStartupArgs(argv)` — hand-written getopt_long-equivalent that
8
- * walks the argv array once, decoding short (`-c`) and long (`--command`)
9
- * options, and accumulates an ordered list of `-c`/`-f` actions plus a
10
- * bag of settings flags. Positional arguments follow the upstream
11
- * `[DBNAME [USERNAME]]` rule.
12
- *
13
- * We hand-roll the parser instead of pulling in `yargs` (or similar)
14
- * because upstream psql has subtle precedence rules — actions are
15
- * ordered, `-v NAME` without `=` deletes the variable, `-X` interacts
16
- * with `.psqlrc` discovery, etc. The parser stays under ~250 LOC and is
17
- * fully covered by unit tests.
18
- *
19
- * 2. `applyStartupArgs(args, settings, baseConnect)` — mutates `settings`
20
- * (and its var store) in-place to reflect parsed flags, then returns
21
- * the connect options the caller should use plus the ordered list of
22
- * pre-REPL actions to execute (currently just `-c` / `-f`).
23
- *
24
- * Out-of-scope for WP-26 but the table mentions them so they're listed below:
25
- * - `-1` / `--single-transaction` — we accept and record on the args but
26
- * do not wire its semantics in the caller. Tracked for a follow-up.
27
- * - `-C` — accepted as a no-op (since-PG17 connection-check skip).
28
- * - `-l` / `--list` — recorded; the caller may use it later to short-circuit
29
- * the REPL with a `\l` and exit. Not wired here.
30
- * - `-L logfile`, `-o output` — recorded on args. Routing into the printer
31
- * is owned by other WPs (logfile streaming and output redirection).
32
- * - `--help[=topic]` — returns a ParseError with `kind: 'help'` and the
33
- * help text already rendered as `message`. Caller writes and exits 0.
34
- * - `-V` / `--version` — returns `kind: 'version'` with the version string.
35
- * Caller writes and exits 0.
36
- *
37
- * Help/version text is rendered through `./help.ts` so the formatting stays
38
- * in lock-step with `\?` output (WP-18). The version string mirrors upstream
39
- * `psql (PostgreSQL) PG_VERSION` and is currently hard-coded — the embedded
40
- * psql doesn't have a build-system PG_VERSION constant. A follow-up could
41
- * surface the real PG version from a const, but for now we expose the
42
- * embedded build's version label.
43
- */
44
- import { envConnectionDefaults, libpqConnectionDefaults, looksLikeConnectionString, mergeConnectOptions, parseConnectionUriPartial, parseConninfo, serviceEntryToConnectOptions, } from "../index.js";
45
- import { lookupPgPass } from "../io/pgpass.js";
46
- import { helpVariables, slashUsage, usage } from "./help.js";
47
- import { setStartupVars } from "./syncVars.js";
48
- // ---------------------------------------------------------------------------
49
- // Internal helpers.
50
- // ---------------------------------------------------------------------------
51
- /** Short options that consume the next argv slot (or attached value). */
52
- const SHORT_WITH_ARG = new Set([
53
- "c",
54
- "d",
55
- "f",
56
- "F",
57
- "h",
58
- "L",
59
- "o",
60
- "p",
61
- "P",
62
- "R",
63
- "T",
64
- "U",
65
- "v",
66
- ]);
67
- /** Short flags (no argument). */
68
- const SHORT_NO_ARG = new Set([
69
- "a",
70
- "A",
71
- "b",
72
- "C",
73
- "e",
74
- "E",
75
- "H",
76
- "l",
77
- "n",
78
- "q",
79
- "s",
80
- "S",
81
- "t",
82
- "V",
83
- "w",
84
- "W",
85
- "x",
86
- "X",
87
- "z",
88
- "0",
89
- "1",
90
- "?",
91
- ]);
92
- /** Long option → canonical short equivalent (or sentinel string). */
93
- const LONG_MAP = {
94
- "echo-all": "a",
95
- "no-align": "A",
96
- command: "c",
97
- dbname: "d",
98
- "echo-queries": "e",
99
- "echo-errors": "b",
100
- "echo-hidden": "E",
101
- file: "f",
102
- "field-separator": "F",
103
- "field-separator-zero": "z",
104
- host: "h",
105
- html: "H",
106
- list: "l",
107
- "log-file": "L",
108
- "no-readline": "n",
109
- "single-transaction": "1",
110
- output: "o",
111
- port: "p",
112
- pset: "P",
113
- quiet: "q",
114
- "record-separator": "R",
115
- "record-separator-zero": "0",
116
- "single-step": "s",
117
- "single-line": "S",
118
- "tuples-only": "t",
119
- "table-attr": "T",
120
- username: "U",
121
- set: "v",
122
- variable: "v",
123
- version: "V",
124
- "no-password": "w",
125
- password: "W",
126
- expanded: "x",
127
- "no-psqlrc": "X",
128
- "no-pager": "__no_pager__",
129
- "on-error-stop": "__on_error_stop__",
130
- help: "__help__",
131
- csv: "__csv__",
132
- };
133
- /** Long options that REQUIRE an attached value (or one in the next argv). */
134
- const LONG_WITH_ARG = new Set([
135
- "command",
136
- "dbname",
137
- "file",
138
- "field-separator",
139
- "host",
140
- "log-file",
141
- "output",
142
- "port",
143
- "pset",
144
- "record-separator",
145
- "table-attr",
146
- "username",
147
- "set",
148
- "variable",
149
- ]);
150
- /** Long options whose value is optional (only attached with `=`). */
151
- const LONG_OPTIONAL_ARG = new Set(["help", "echo-hidden"]);
152
- const blankArgs = () => ({
153
- actions: [],
154
- variables: [],
155
- noPsqlrc: false,
156
- noReadline: false,
157
- echoAll: false,
158
- echoHidden: "off",
159
- echoErrors: false,
160
- echoQueries: false,
161
- quiet: false,
162
- singleline: false,
163
- singlestep: false,
164
- noAlign: false,
165
- noPager: false,
166
- htmlMode: false,
167
- tuplesOnly: false,
168
- expanded: false,
169
- csvOutput: false,
170
- onErrorStop: false,
171
- fieldSepZero: false,
172
- recordSepZero: false,
173
- pset: [],
174
- list: false,
175
- singleTransaction: false,
176
- help: false,
177
- version: false,
178
- positional: [],
179
- });
180
- const renderToString = (fn) => {
181
- const chunks = [];
182
- const sink = {
183
- write(chunk) {
184
- chunks.push(typeof chunk === "string"
185
- ? chunk
186
- : Buffer.from(chunk).toString("utf8"));
187
- return true;
188
- },
189
- };
190
- fn(sink);
191
- return chunks.join("");
192
- };
193
- const renderHelp = (topic) => {
194
- if (topic === undefined || topic === "options") {
195
- return renderToString((out) => {
196
- usage(out);
197
- });
198
- }
199
- if (topic === "commands") {
200
- return renderToString((out) => {
201
- slashUsage(out, false);
202
- });
203
- }
204
- if (topic === "variables") {
205
- return renderToString((out) => {
206
- helpVariables(out);
207
- });
208
- }
209
- return "";
210
- };
211
- /**
212
- * Version label for the embedded TypeScript psql. This is the "client"
213
- * identifier — the analogue of upstream psql's compiled-in `PG_VERSION`.
214
- * The embedded psql is not a real PostgreSQL build, so we track our own
215
- * implementation version here. It seeds the `VERSION_NAME` psql var (and,
216
- * via {@link setStartupVars}, the numeric `VERSION_NUM`); keep it as a
217
- * `MAJOR.MINOR.PATCH` string so the numeric mapping stays meaningful. Bump
218
- * alongside meaningful behaviour changes to the embedded psql.
219
- */
220
- export const CLIENT_VERSION = "1.0.0";
221
- // `psql --version` / `-V` output. Mirrors upstream's `psql (PostgreSQL)
222
- // <PG_VERSION>` SHAPE (tools parse the leading `psql (PostgreSQL)`), with an
223
- // `embedded-ts` label in place of a real PG build number since this is a
224
- // reimplementation, not a compiled psql. Distinct from the `:VERSION` psql
225
- // variable (the client-identity string seeded from CLIENT_VERSION).
226
- const VERSION_STRING = `psql (PostgreSQL) embedded-ts (neonctl ${CLIENT_VERSION})`;
227
- const pushAction = (acts, a) => {
228
- acts.push(a);
229
- };
230
- const pushVariable = (vars, raw) => {
231
- const eq = raw.indexOf("=");
232
- if (eq < 0) {
233
- // psql treats `-v NAME` (no value) as "delete this variable". We surface
234
- // an empty value; the caller decides whether to set or unset. Tests
235
- // verify both shapes.
236
- vars.push({ name: raw, value: "" });
237
- return;
238
- }
239
- vars.push({ name: raw.slice(0, eq), value: raw.slice(eq + 1) });
240
- };
241
- /**
242
- * `-d VALUE` resolution. libpq accepts three shapes for the value:
243
- *
244
- * 1. Bare database name (no `=`, no `postgres[ql]://` prefix) — set
245
- * `args.database` directly. This is by far the common case.
246
- * 2. Connection URI (`postgresql://…` / `postgres://…`) — parse it and
247
- * lift the fields it specifies onto `args` (host, port, user, etc.).
248
- * 3. Conninfo key=value pairs separated by whitespace — same, but parsed
249
- * via `parseConninfo`.
250
- *
251
- * The test corpus for upstream `001_basic.pl` uses shape (3) to open a
252
- * walsender connection: `-d "dbname=postgres replication=database"`. We
253
- * fold any conninfo-only fields (currently only `replication`) onto a
254
- * dedicated `args.replication` slot that `applyStartupArgs` threads into
255
- * `ConnectOptions.replication`.
256
- */
257
- const applyDashD = (args, value) => {
258
- if (!looksLikeConnectionString(value)) {
259
- args.database = value;
260
- return;
261
- }
262
- // Use the *partial* URI parser, NOT parseConnectionUri: the latter applies
263
- // libpq's lowest-priority OS-user fallback (`user = $USER`, `database =
264
- // user`) eagerly, and those non-undefined defaults would then land in the
265
- // top-priority argv layer and override `PGUSER` / `PGDATABASE` (review #7).
266
- // The partial parser returns only the keys the URI actually specified.
267
- const parsed = value.startsWith("postgresql://") || value.startsWith("postgres://")
268
- ? parseConnectionUriPartial(value)
269
- : parseConninfo(value);
270
- // Keep the whole partial (incl. ssl*/channelBinding/hostaddr/requireAuth)
271
- // so the connection layer carries it (review #6).
272
- args.dashD = { ...(args.dashD ?? {}), ...parsed };
273
- // Continue to mirror the core target fields onto the flag slots so the
274
- // positional-arg / dbname-username precedence logic below sees them. Only
275
- // when not already set by an explicit flag (flags win over -d).
276
- if (parsed.host !== undefined && args.host === undefined) {
277
- args.host = parsed.host;
278
- }
279
- if (parsed.port !== undefined && args.port === undefined) {
280
- args.port = parsed.port;
281
- }
282
- if (parsed.user !== undefined && args.user === undefined) {
283
- args.user = parsed.user;
284
- }
285
- if (parsed.password !== undefined && args.password === undefined) {
286
- args.password = parsed.password;
287
- }
288
- if (parsed.database !== undefined && args.database === undefined) {
289
- args.database = parsed.database;
290
- }
291
- if (parsed.replication !== undefined) {
292
- args.replication = parsed.replication;
293
- }
294
- };
295
- // ---------------------------------------------------------------------------
296
- // parseStartupArgs.
297
- // ---------------------------------------------------------------------------
298
- export const parseStartupArgs = (argv) => {
299
- const args = blankArgs();
300
- const actions = [];
301
- const variables = [];
302
- const pset = [];
303
- let i = 0;
304
- const n = argv.length;
305
- const needValue = (flagDisplay) => {
306
- if (i + 1 >= n) {
307
- return {
308
- kind: "missing-arg",
309
- message: `option requires an argument -- ${flagDisplay}`,
310
- };
311
- }
312
- i += 1;
313
- return argv[i];
314
- };
315
- const applyShort = (letter, attachedValue, flagDisplay) => {
316
- // Resolve the value: either attached (already next to the flag) or the
317
- // next argv slot. If the flag does not take an argument, attachedValue
318
- // must be undefined.
319
- const takesArg = SHORT_WITH_ARG.has(letter);
320
- let value;
321
- if (takesArg) {
322
- if (attachedValue !== undefined) {
323
- value = attachedValue;
324
- }
325
- else {
326
- const v = needValue(flagDisplay);
327
- if (typeof v !== "string")
328
- return v;
329
- value = v;
330
- }
331
- }
332
- else if (attachedValue !== undefined) {
333
- // A value was attached to a short flag that doesn't accept one. Treat
334
- // this as an invalid-option error (matches `getopt_long` behaviour
335
- // for clusters like `-Xy` where `X` doesn't take an argument — flex
336
- // continues to `y`; we keep it strict for clarity).
337
- return {
338
- kind: "invalid-option",
339
- message: `option does not take an argument -- ${letter}`,
340
- };
341
- }
342
- switch (letter) {
343
- case "a":
344
- args.echoAll = true;
345
- return null;
346
- case "A":
347
- args.noAlign = true;
348
- return null;
349
- case "b":
350
- args.echoErrors = true;
351
- return null;
352
- case "C":
353
- // Since-PG17 "skip connection check" — no-op for our use.
354
- return null;
355
- case "c":
356
- pushAction(actions, { kind: "command", sql: value });
357
- return null;
358
- case "d":
359
- applyDashD(args, value);
360
- return null;
361
- case "e":
362
- args.echoQueries = true;
363
- return null;
364
- case "E":
365
- args.echoHidden = "on";
366
- return null;
367
- case "f":
368
- pushAction(actions, { kind: "file", path: value });
369
- return null;
370
- case "F":
371
- args.fieldSep = value;
372
- args.fieldSepZero = false;
373
- return null;
374
- case "h":
375
- args.host = value;
376
- return null;
377
- case "H":
378
- args.htmlMode = true;
379
- return null;
380
- case "l":
381
- args.list = true;
382
- return null;
383
- case "L":
384
- args.log = value;
385
- return null;
386
- case "n":
387
- args.noReadline = true;
388
- return null;
389
- case "o":
390
- args.output = value;
391
- return null;
392
- case "p": {
393
- const p = Number.parseInt(value, 10);
394
- if (!Number.isFinite(p) || p <= 0 || p > 65535) {
395
- return {
396
- kind: "invalid-value",
397
- message: `invalid port number: "${value}"`,
398
- };
399
- }
400
- args.port = p;
401
- return null;
402
- }
403
- case "P":
404
- pset.push(value);
405
- return null;
406
- case "q":
407
- args.quiet = true;
408
- return null;
409
- case "R":
410
- args.recordSep = value;
411
- args.recordSepZero = false;
412
- return null;
413
- case "s":
414
- args.singlestep = true;
415
- return null;
416
- case "S":
417
- args.singleline = true;
418
- return null;
419
- case "t":
420
- args.tuplesOnly = true;
421
- return null;
422
- case "T":
423
- // -T TEXT → push a synthetic pset directive so it routes through
424
- // the same `\pset tableattr` plumbing.
425
- pset.push(`tableattr=${value}`);
426
- return null;
427
- case "U":
428
- args.user = value;
429
- return null;
430
- case "v":
431
- pushVariable(variables, value);
432
- return null;
433
- case "V":
434
- return {
435
- kind: "version",
436
- message: VERSION_STRING,
437
- };
438
- case "w":
439
- args.promptPassword = false;
440
- return null;
441
- case "W":
442
- args.promptPassword = true;
443
- return null;
444
- case "x":
445
- args.expanded = true;
446
- return null;
447
- case "X":
448
- args.noPsqlrc = true;
449
- return null;
450
- case "z":
451
- args.fieldSepZero = true;
452
- return null;
453
- case "0":
454
- args.recordSepZero = true;
455
- return null;
456
- case "1":
457
- args.singleTransaction = true;
458
- return null;
459
- case "?":
460
- return {
461
- kind: "help",
462
- message: renderHelp(undefined),
463
- };
464
- default:
465
- return {
466
- kind: "invalid-option",
467
- message: `invalid option -- ${letter}`,
468
- };
469
- }
470
- };
471
- // ---- Main loop. -------------------------------------------------------
472
- while (i < n) {
473
- const tok = argv[i];
474
- if (tok === "--") {
475
- // End of options. Everything after is positional.
476
- i += 1;
477
- while (i < n) {
478
- args.positional.push(argv[i]);
479
- i += 1;
480
- }
481
- break;
482
- }
483
- if (tok.startsWith("--")) {
484
- // Long option: `--name` or `--name=value`.
485
- const eq = tok.indexOf("=");
486
- const name = eq < 0 ? tok.slice(2) : tok.slice(2, eq);
487
- const attached = eq < 0 ? undefined : tok.slice(eq + 1);
488
- // Special-case the long-only synthetic options first.
489
- if (name === "csv") {
490
- if (attached !== undefined) {
491
- return {
492
- kind: "invalid-option",
493
- message: `option does not take an argument: --${name}`,
494
- };
495
- }
496
- args.csvOutput = true;
497
- i += 1;
498
- continue;
499
- }
500
- if (name === "no-pager") {
501
- if (attached !== undefined) {
502
- return {
503
- kind: "invalid-option",
504
- message: `option does not take an argument: --${name}`,
505
- };
506
- }
507
- args.noPager = true;
508
- i += 1;
509
- continue;
510
- }
511
- if (name === "on-error-stop") {
512
- if (attached !== undefined) {
513
- return {
514
- kind: "invalid-option",
515
- message: `option does not take an argument: --${name}`,
516
- };
517
- }
518
- args.onErrorStop = true;
519
- variables.push({ name: "ON_ERROR_STOP", value: "on" });
520
- i += 1;
521
- continue;
522
- }
523
- if (name === "help") {
524
- const topic = attached;
525
- if (topic !== undefined &&
526
- topic !== "options" &&
527
- topic !== "commands" &&
528
- topic !== "variables") {
529
- return {
530
- kind: "invalid-option",
531
- message: `unrecognized help topic: ${topic}`,
532
- };
533
- }
534
- return { kind: "help", message: renderHelp(topic) };
535
- }
536
- if (name === "echo-hidden") {
537
- if (attached === undefined) {
538
- args.echoHidden = "on";
539
- }
540
- else if (attached === "noexec") {
541
- args.echoHidden = "noexec";
542
- }
543
- else if (attached === "" || attached === "on") {
544
- args.echoHidden = "on";
545
- }
546
- else {
547
- return {
548
- kind: "invalid-value",
549
- message: `invalid value for --echo-hidden: "${attached}"`,
550
- };
551
- }
552
- i += 1;
553
- continue;
554
- }
555
- const short = LONG_MAP[name];
556
- if (short === undefined) {
557
- return {
558
- kind: "invalid-option",
559
- message: `unrecognized option: --${name}`,
560
- };
561
- }
562
- const requiresArg = LONG_WITH_ARG.has(name);
563
- const optionalArg = LONG_OPTIONAL_ARG.has(name);
564
- let value = attached;
565
- if (requiresArg && value === undefined) {
566
- if (i + 1 >= n) {
567
- return {
568
- kind: "missing-arg",
569
- message: `option requires an argument: --${name}`,
570
- };
571
- }
572
- i += 1;
573
- value = argv[i];
574
- }
575
- else if (!requiresArg && !optionalArg && value !== undefined) {
576
- return {
577
- kind: "invalid-option",
578
- message: `option does not take an argument: --${name}`,
579
- };
580
- }
581
- const err = applyShort(short, value, `--${name}`);
582
- if (err)
583
- return err;
584
- i += 1;
585
- continue;
586
- }
587
- if (tok.startsWith("-") && tok.length > 1) {
588
- // Short option cluster. Each char might consume the rest of the token
589
- // (or the next argv) as its value.
590
- let k = 1;
591
- while (k < tok.length) {
592
- const letter = tok[k];
593
- if (!SHORT_WITH_ARG.has(letter) && !SHORT_NO_ARG.has(letter)) {
594
- return {
595
- kind: "invalid-option",
596
- message: `invalid option -- ${letter}`,
597
- };
598
- }
599
- if (SHORT_WITH_ARG.has(letter)) {
600
- // Consume the rest of this token as the value if anything remains,
601
- // otherwise pull from the next argv.
602
- const remainder = tok.slice(k + 1);
603
- const value = remainder.length > 0 ? remainder : undefined;
604
- const err = applyShort(letter, value, letter);
605
- if (err)
606
- return err;
607
- k = tok.length; // Consumed the rest.
608
- break;
609
- }
610
- const err = applyShort(letter, undefined, letter);
611
- if (err)
612
- return err;
613
- k += 1;
614
- }
615
- i += 1;
616
- continue;
617
- }
618
- // Positional.
619
- args.positional.push(tok);
620
- i += 1;
621
- }
622
- // Upstream consumes only DBNAME and USERNAME from positionals; extras are
623
- // warned about and ignored. We surface them all on `positional` so the
624
- // caller can warn/log; applyStartupArgs takes care of the first two.
625
- return {
626
- ...args,
627
- actions,
628
- variables,
629
- pset,
630
- };
631
- };
632
- export const applyStartupArgs = (args, settings, baseConnectOpts, resolution) => {
633
- // -------- 0) Constant client-version vars. -----------------------------
634
- // Seed VERSION / VERSION_NAME / VERSION_NUM once (upstream seeds these from
635
- // its compiled-in PG_VERSION before reading psqlrc / CLI vars). Done before
636
- // the `-v` loop so a user-supplied `-v VERSION=…` still wins.
637
- setStartupVars(settings.vars, CLIENT_VERSION);
638
- // -------- 1) Variable assignments. -------------------------------------
639
- for (const v of args.variables) {
640
- if (v.value === "") {
641
- // Mirror upstream `-v NAME` (no `=`): DeleteVariable.
642
- settings.vars.unset(v.name);
643
- }
644
- else {
645
- settings.vars.set(v.name, v.value);
646
- }
647
- }
648
- // -------- 2) Settings flags. -------------------------------------------
649
- if (args.echoAll)
650
- settings.vars.set("ECHO", "all");
651
- if (args.echoErrors)
652
- settings.vars.set("ECHO", "errors");
653
- if (args.echoQueries)
654
- settings.vars.set("ECHO", "queries");
655
- if (args.echoHidden !== "off") {
656
- settings.echoHidden = args.echoHidden;
657
- settings.vars.set("ECHO_HIDDEN", args.echoHidden === "noexec" ? "noexec" : "on");
658
- }
659
- if (args.quiet) {
660
- settings.quiet = true;
661
- settings.vars.set("QUIET", "on");
662
- }
663
- if (args.singleline) {
664
- settings.singleline = true;
665
- settings.vars.set("SINGLELINE", "on");
666
- }
667
- if (args.singlestep) {
668
- settings.singlestep = true;
669
- settings.vars.set("SINGLESTEP", "on");
670
- }
671
- if (args.onErrorStop) {
672
- settings.onErrorStop = true;
673
- settings.vars.set("ON_ERROR_STOP", "on");
674
- }
675
- // -------- 3) Output formatting. ----------------------------------------
676
- if (args.noAlign) {
677
- settings.popt.topt.format = "unaligned";
678
- }
679
- if (args.htmlMode) {
680
- settings.popt.topt.format = "html";
681
- }
682
- if (args.csvOutput) {
683
- settings.popt.topt.format = "csv";
684
- }
685
- if (args.tuplesOnly) {
686
- settings.popt.topt.tuplesOnly = true;
687
- }
688
- if (args.expanded) {
689
- settings.popt.topt.expanded = "on";
690
- }
691
- if (args.fieldSepZero) {
692
- settings.popt.topt.fieldSep = "\0";
693
- }
694
- else if (args.fieldSep !== undefined) {
695
- settings.popt.topt.fieldSep = args.fieldSep;
696
- }
697
- if (args.recordSepZero) {
698
- settings.popt.topt.recordSep = "\0";
699
- }
700
- else if (args.recordSep !== undefined) {
701
- settings.popt.topt.recordSep = args.recordSep;
702
- }
703
- if (args.noPager) {
704
- settings.popt.topt.pager = "off";
705
- }
706
- // -------- 4) pset directives. ------------------------------------------
707
- // We don't have a parsed `do_pset` here yet (lives in command/cmd_format),
708
- // so we surface them as raw strings and let the integration layer feed
709
- // them through once parsed. For tableattr (the most common -T use), apply
710
- // directly.
711
- for (const directive of args.pset) {
712
- const eq = directive.indexOf("=");
713
- if (eq >= 0) {
714
- const key = directive.slice(0, eq);
715
- const val = directive.slice(eq + 1);
716
- if (key === "tableattr" || key === "T") {
717
- settings.popt.topt.tableAttr = val.length > 0 ? val : null;
718
- }
719
- else if (key === "pager") {
720
- if (val === "on" || val === "off" || val === "always") {
721
- settings.popt.topt.pager = val;
722
- }
723
- }
724
- // Other directives left to the broader -P plumbing.
725
- }
726
- }
727
- // -------- 5) Connection overrides. -------------------------------------
728
- // Positional args follow upstream: positional[0] → dbname, positional[1] →
729
- // username (if not already set by a flag).
730
- let dbname = args.database;
731
- let username = args.user;
732
- if (args.positional[0] && !dbname)
733
- dbname = args.positional[0];
734
- if (args.positional[1] && !username)
735
- username = args.positional[1];
736
- // The argv flag layer mirrors the highest-priority CLI inputs (`-h`/`-p`
737
- // / positional DBNAME / etc). Only populated entries end up in the layer
738
- // so they don't accidentally clobber URI/env values.
739
- // Seed with the full `-d` partial (carries ssl*/channelBinding/hostaddr/
740
- // requireAuth — review #6), then overlay the explicit flag/positional
741
- // values so `-h`/`-p`/`-U`/`-W`/positional still take precedence over `-d`.
742
- const argvLayer = { ...(args.dashD ?? {}) };
743
- if (args.host !== undefined)
744
- argvLayer.host = args.host;
745
- if (args.port !== undefined)
746
- argvLayer.port = args.port;
747
- if (username !== undefined)
748
- argvLayer.user = username;
749
- if (dbname !== undefined)
750
- argvLayer.database = dbname;
751
- if (args.password !== undefined)
752
- argvLayer.password = args.password;
753
- if (args.replication !== undefined)
754
- argvLayer.replication = args.replication;
755
- // Two modes:
756
- // - LEGACY: no `resolution` provided → behave exactly like before, with
757
- // `baseConnectOpts` supplying every default and argv overriding it.
758
- // - LAYERED: `resolution` provided → run the full vanilla-psql chain.
759
- let connect;
760
- if (resolution === undefined) {
761
- const base = baseConnectOpts ?? {
762
- host: "localhost",
763
- port: 5432,
764
- user: "",
765
- database: "",
766
- ssl: "prefer",
767
- };
768
- connect = { ...base, ...argvLayer };
769
- }
770
- else {
771
- connect = resolveLayeredConnect(argvLayer, resolution, baseConnectOpts);
772
- }
773
- return { connect, preActions: args.actions };
774
- };
775
- /**
776
- * Run the layered connection-parameter merge.
777
- *
778
- * argv > URI partial > PG* env > .pgpass (password only) > service > libpq defaults
779
- *
780
- * `baseConnectOpts` (the legacy `ConnectOptions` argument) is treated as a
781
- * pre-baked URI partial when the resolution path is used WITHOUT an explicit
782
- * `uriPartial`. This keeps the door open for callers that still want to
783
- * pass a fully-defaulted URI shape from `parseConnectionUri`.
784
- */
785
- const resolveLayeredConnect = (argvLayer, resolution, legacyBase) => {
786
- const env = resolution.env ?? {};
787
- const uriPartial = resolution.uriPartial ??
788
- (legacyBase !== undefined
789
- ? legacyBase
790
- : {});
791
- // Pick the service entry: explicit `serviceName` argument first, else fall
792
- // back to `$PGSERVICE`. The URI parser threads `?service=` through to its
793
- // caller via this same field, so callers should populate `serviceName`
794
- // from there before invoking us.
795
- const serviceName = resolution.serviceName ?? env.PGSERVICE;
796
- let serviceEntry;
797
- if (serviceName !== undefined && serviceName !== "") {
798
- serviceEntry = resolution.services?.get(serviceName);
799
- if (serviceEntry === undefined) {
800
- // Mirror libpq: if the user explicitly named a service (via
801
- // `?service=`, conninfo `service=`, or `$PGSERVICE`) and it isn't
802
- // found in any loaded service file, fail fast with the exact
803
- // upstream wording. Without this the empty service layer would
804
- // silently degrade to a different connection target — surprising
805
- // and very hard to debug.
806
- throw new Error(`definition of service "${serviceName}" not found`);
807
- }
808
- }
809
- const serviceLayer = serviceEntry !== undefined
810
- ? serviceEntryToConnectOptions(serviceEntry)
811
- : {};
812
- // Build the layer stack (highest priority first).
813
- const envLayer = envConnectionDefaults(env);
814
- const defaults = libpqConnectionDefaults(env);
815
- const layers = [
816
- argvLayer,
817
- uriPartial,
818
- envLayer,
819
- serviceLayer,
820
- ];
821
- // First-pass merge (without pgpass) so we know what host/port/db/user
822
- // ended up as. pgpass is a password-only layer that depends on the
823
- // resolved target.
824
- let merged = mergeConnectOptions(layers, defaults);
825
- if (merged.password === undefined) {
826
- const pgpassPwd = lookupPgPass(resolution.pgpassEntries ?? [], {
827
- host: merged.host,
828
- port: merged.port,
829
- database: merged.database !== "" ? merged.database : merged.user,
830
- user: merged.user,
831
- });
832
- if (pgpassPwd !== undefined) {
833
- // Re-merge with pgpass slotted in just above libpq defaults so any
834
- // explicit `password=` in env / service still wins.
835
- const pgpassLayer = {
836
- password: pgpassPwd,
837
- };
838
- merged = mergeConnectOptions([...layers, pgpassLayer], defaults);
839
- }
840
- }
841
- return merged;
842
- };
843
- // ---------------------------------------------------------------------------
844
- // Error-formatting helper for the integration layer.
845
- // ---------------------------------------------------------------------------
846
- export const formatParseError = (err) => err.message;