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,970 @@
1
+ /**
2
+ * Meta backslash commands.
3
+ *
4
+ * TypeScript port of the corresponding `exec_command_*` functions in
5
+ * upstream PostgreSQL's `src/bin/psql/command.c`:
6
+ *
7
+ * - `\q` / `\quit` → exec_command_quit
8
+ * - `\r` / `\reset` → exec_command_reset
9
+ * - `\!` → exec_command_shell_escape (do_shell)
10
+ * - `\cd` → exec_command_cd
11
+ * - `\echo`, `\qecho`, `\warn` → exec_command_echo / qecho / warn
12
+ * - `\prompt` → exec_command_prompt
13
+ * - `\set`, `\unset` → exec_command_set / exec_command_unset
14
+ * - `\getenv`, `\setenv` → exec_command_getenv / exec_command_setenv
15
+ * - `\errverbose` → exec_command_errverbose
16
+ * - `\timing` → exec_command_timing
17
+ * - `\copyright` → exec_command_copyright
18
+ * - `\h` / `\help` → exec_command_help (helpSQL)
19
+ *
20
+ * Each command is exported as a `BackslashCmdSpec` so {@link defaultRegistry}
21
+ * in `dispatch.ts` can register them. Error messages follow upstream's
22
+ * `\<cmd>: <message>` shape and go to stderr; on failure we return
23
+ * `{ status: 'error' }`. Successful invocations return `{ status: 'ok' }`.
24
+ *
25
+ * Stubs / deferred behaviour:
26
+ *
27
+ * - `\!` always returns `{ status: 'ok' }` — upstream does not propagate
28
+ * the child's exit status to the surrounding script, only the run-mode.
29
+ * Tests use a stdio mock; in interactive use the child inherits stdio.
30
+ * - `\prompt -` (no-echo password prompting) reads via the shared input
31
+ * layer with echo suppressed on a TTY (falling back to a plain read on
32
+ * non-interactive input).
33
+ * - `\qecho` writes to `settings.logfile` if set, else stdout. Upstream
34
+ * additionally honours a separate "query output" file set via `\o`;
35
+ * that wiring lives in WP-15 and we leave the hook in place.
36
+ */
37
+ import { spawnSync } from "node:child_process";
38
+ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
39
+ import { tmpdir } from "node:os";
40
+ import { join } from "node:path";
41
+ import { helpSQL, slashUsage } from "../core/help.js";
42
+ import { getHistory } from "../io/history.js";
43
+ import { readLine } from "../io/input.js";
44
+ import { parseBool, writeErr, writeOut } from "./shared.js";
45
+ /** `\q` / `\quit` — exit the REPL. */
46
+ export const cmdQuit = {
47
+ name: "q",
48
+ aliases: ["quit"],
49
+ helpKey: "q",
50
+ run: () => Promise.resolve({ status: "exit" }),
51
+ };
52
+ /**
53
+ * `\!` — shell escape. Whole-line mode: the entire rest of the line is the
54
+ * command string.
55
+ *
56
+ * - `\!` (no args) → spawn `$SHELL -i` (fallback `sh -i`)
57
+ * - `\!command args` → spawn `sh -c 'command args'`
58
+ *
59
+ * In both cases the child inherits stdio and we return `{ status: 'ok' }`
60
+ * regardless of the child's exit status — matching upstream `do_shell`,
61
+ * which keeps the REPL alive after a failing shell command rather than
62
+ * propagating the exit code. Catching a spawn-time exception keeps us
63
+ * resilient against environments where `sh` is unavailable.
64
+ */
65
+ export const cmdShell = {
66
+ name: "!",
67
+ argMode: "whole-line",
68
+ helpKey: "!",
69
+ run: (ctx) => {
70
+ const line = ctx.restOfLine().trim();
71
+ try {
72
+ if (line.length === 0) {
73
+ const shell = process.env.SHELL ?? "/bin/sh";
74
+ spawnSync(shell, ["-i"], { stdio: "inherit" });
75
+ }
76
+ else {
77
+ spawnSync("sh", ["-c", line], { stdio: "inherit" });
78
+ }
79
+ }
80
+ catch {
81
+ // Upstream `do_shell` swallows shell-spawn failures: the REPL has to
82
+ // keep running even when the child won't start. Status stays `ok` so
83
+ // a failing `\!` is purely informational.
84
+ }
85
+ return Promise.resolve({ status: "ok" });
86
+ },
87
+ };
88
+ /** `\cd [dir]` — change cwd. No arg falls back to `$HOME`. */
89
+ export const cmdCd = {
90
+ name: "cd",
91
+ helpKey: "cd",
92
+ run: (ctx) => {
93
+ const dir = ctx.nextArg("normal");
94
+ const target = dir && dir.length > 0 ? dir : (process.env.HOME ?? null);
95
+ if (!target) {
96
+ writeErr(`\\${ctx.cmdName}: could not determine home directory\n`);
97
+ return Promise.resolve({ status: "error" });
98
+ }
99
+ try {
100
+ process.chdir(target);
101
+ return Promise.resolve({ status: "ok" });
102
+ }
103
+ catch (err) {
104
+ const msg = err instanceof Error ? err.message : String(err);
105
+ writeErr(`\\${ctx.cmdName}: ${msg}\n`);
106
+ return Promise.resolve({ status: "error" });
107
+ }
108
+ },
109
+ };
110
+ /**
111
+ * Helper for `\echo` / `\qecho` / `\warn`. Reads args until exhausted,
112
+ * honours the leading `-n` flag (suppresses trailing newline), joins with
113
+ * single spaces, and writes to the chosen stream.
114
+ *
115
+ * Upstream `exec_command_echo` only treats `-n` as a flag when the source
116
+ * was the unquoted two-character token `-n`. `'-n'` (single-quoted) is a
117
+ * literal value: it should be printed AND the trailing newline kept. We
118
+ * inspect `ctx.rawArgs` directly because `nextArg` discards quote
119
+ * metadata after lexing.
120
+ */
121
+ const runEcho = (ctx, write) => {
122
+ const parts = [];
123
+ let noNewline = false;
124
+ let first = true;
125
+ // Pre-scan the raw text to decide whether the first arg was the
126
+ // unquoted `-n` token. We can't rely on the lexed arg value alone:
127
+ // `'-n'` / `"-n"` produce the same string but must be treated as data.
128
+ const firstArgIsUnquotedDashN = (() => {
129
+ let i = 0;
130
+ while (i < ctx.rawArgs.length && /\s/.test(ctx.rawArgs[i]))
131
+ i++;
132
+ return (ctx.rawArgs.slice(i, i + 2) === "-n" &&
133
+ (i + 2 === ctx.rawArgs.length || /\s/.test(ctx.rawArgs[i + 2])));
134
+ })();
135
+ for (;;) {
136
+ const arg = ctx.nextArg("normal");
137
+ if (arg === null)
138
+ break;
139
+ if (first && firstArgIsUnquotedDashN && arg === "-n") {
140
+ noNewline = true;
141
+ first = false;
142
+ continue;
143
+ }
144
+ first = false;
145
+ parts.push(arg);
146
+ }
147
+ const out = parts.join(" ") + (noNewline ? "" : "\n");
148
+ write(out);
149
+ return { status: "ok" };
150
+ };
151
+ /** `\echo` — write args to stdout. */
152
+ export const cmdEcho = {
153
+ name: "echo",
154
+ helpKey: "echo",
155
+ run: (ctx) => Promise.resolve(runEcho(ctx, writeOut)),
156
+ };
157
+ /** `\qecho` — write args to the query output (logfile if set, else stdout). */
158
+ export const cmdQecho = {
159
+ name: "qecho",
160
+ helpKey: "qecho",
161
+ run: (ctx) => {
162
+ const { logfile } = ctx.settings;
163
+ const write = (s) => {
164
+ if (logfile) {
165
+ logfile.write(s);
166
+ }
167
+ else {
168
+ writeOut(s);
169
+ }
170
+ };
171
+ return Promise.resolve(runEcho(ctx, write));
172
+ },
173
+ };
174
+ /** `\warn` — write args to stderr. */
175
+ export const cmdWarn = {
176
+ name: "warn",
177
+ helpKey: "warn",
178
+ run: (ctx) => Promise.resolve(runEcho(ctx, writeErr)),
179
+ };
180
+ /**
181
+ * `\prompt [TEXT] varname`
182
+ *
183
+ * Upstream: read one line of input from the terminal, optionally with a
184
+ * prompt prefix, and assign it to a psql variable. A leading `-` flag
185
+ * requests a no-echo read (used for password prompts); we honour it by
186
+ * reading through the shared input layer with echo suppressed on a TTY
187
+ * (and a plain read otherwise — non-interactive input still consumes the
188
+ * line, matching upstream).
189
+ *
190
+ * Args after the optional `-` flag are `[TEXT] varname`: if only one
191
+ * remains it is the variable name and no prompt prefix is shown; if two,
192
+ * the first is the prompt and the second the variable.
193
+ */
194
+ export const cmdPrompt = {
195
+ name: "prompt",
196
+ helpKey: "prompt",
197
+ run: async (ctx) => {
198
+ const args = [];
199
+ for (;;) {
200
+ const a = ctx.nextArg("normal");
201
+ if (a === null)
202
+ break;
203
+ args.push(a);
204
+ }
205
+ // A leading `-` selects the no-echo (password) read path.
206
+ let echo = true;
207
+ if (args.length > 0 && args[0] === "-") {
208
+ echo = false;
209
+ args.shift();
210
+ }
211
+ if (args.length === 0) {
212
+ writeErr(`\\${ctx.cmdName}: missing required argument\n`);
213
+ return { status: "error" };
214
+ }
215
+ let promptText = "";
216
+ let varname;
217
+ if (args.length === 1) {
218
+ varname = args[0];
219
+ }
220
+ else {
221
+ promptText = args[0];
222
+ varname = args[1];
223
+ }
224
+ const line = await readLine(promptText, { echo });
225
+ if (!ctx.settings.vars.set(varname, line)) {
226
+ writeErr(`\\${ctx.cmdName}: invalid variable name "${varname}"\n`);
227
+ return { status: "error" };
228
+ }
229
+ return { status: "ok" };
230
+ },
231
+ };
232
+ /**
233
+ * `\set [varname [value...]]`
234
+ *
235
+ * - No args → list all variables (sorted, `name = 'value'` per line) to
236
+ * stdout. Upstream uses single-quotes around the value.
237
+ * - One arg → set the variable to the empty string.
238
+ * - More args → join the rest with a single space and set the variable.
239
+ *
240
+ * Diagnostics mirror upstream `exec_command_set` in `src/bin/psql/command.c`:
241
+ *
242
+ * - Names containing characters outside `[A-Za-z_][A-Za-z0-9_]*` produce
243
+ * `invalid variable name: "<name>"` (prefixed with `psql: `).
244
+ * - Per-variable hook rejections (AUTOCOMMIT / FETCH_COUNT /
245
+ * ON_ERROR_ROLLBACK / VERBOSITY / etc.) carry the hook's message
246
+ * verbatim; we add only the `psql: ` prefix.
247
+ * - Hook vetoes with no message fall back to a generic line. This
248
+ * should not happen in practice — every registered hook either
249
+ * accepts or returns a wording string.
250
+ */
251
+ export const cmdSet = {
252
+ name: "set",
253
+ helpKey: "set",
254
+ run: (ctx) => {
255
+ const name = ctx.nextArg("normal");
256
+ if (name === null) {
257
+ // List all vars sorted by name.
258
+ const entries = [...ctx.settings.vars.entries()].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
259
+ for (const [k, v] of entries) {
260
+ writeOut(`${k} = '${v}'\n`);
261
+ }
262
+ return Promise.resolve({ status: "ok" });
263
+ }
264
+ const values = [];
265
+ for (;;) {
266
+ const a = ctx.nextArg("normal");
267
+ if (a === null)
268
+ break;
269
+ values.push(a);
270
+ }
271
+ const value = values.join("");
272
+ const result = ctx.settings.vars.trySet(name, value);
273
+ if (!result.ok) {
274
+ const prefix = psqlErrorPrefix(ctx.settings);
275
+ if (result.reason === "invalid-name") {
276
+ writeErr(`${prefix}invalid variable name: "${name}"\n`);
277
+ }
278
+ else if (result.error !== undefined) {
279
+ // Hook supplied its own wording — emit verbatim, prefixed with
280
+ // `psql: `. The message intentionally does NOT carry a severity
281
+ // (`error:` / `ERROR:`) because upstream's per-variable hooks
282
+ // also emit just `psql: <msg>` (see `bool_substitute_hook` etc.).
283
+ writeErr(`${prefix}${result.error}\n`);
284
+ }
285
+ else {
286
+ // Hook returned `false` without a message — fall back to a
287
+ // generic line so callers still see something. None of the
288
+ // built-in hooks take this path, but third-party callers might.
289
+ writeErr(`${prefix}error while setting variable "${name}"\n`);
290
+ }
291
+ return Promise.resolve({ status: "error" });
292
+ }
293
+ return Promise.resolve({ status: "ok" });
294
+ },
295
+ };
296
+ /**
297
+ * `\r` / `\reset` — discard the accumulated query buffer.
298
+ *
299
+ * Mirrors upstream `exec_command_reset`:
300
+ *
301
+ * resetPQExpBuffer(query_buf);
302
+ * psql_scan_reset(scan_state);
303
+ * if (!pset.quiet)
304
+ * puts(_("Query buffer reset (cleared)."));
305
+ *
306
+ * We model the buffer + scanner reset via `status: 'reset-buf'`; the
307
+ * mainloop wipes `queryBuf` and re-initialises `scanState` when it sees
308
+ * this. The diagnostic is gated on the `quiet` setting so `psql -q` (and
309
+ * the regress harness, which passes `--quiet`) produces no output.
310
+ */
311
+ export const cmdReset = {
312
+ name: "r",
313
+ aliases: ["reset"],
314
+ helpKey: "r",
315
+ run: (ctx) => {
316
+ if (!ctx.settings.quiet) {
317
+ writeOut("Query buffer reset (cleared).\n");
318
+ }
319
+ return Promise.resolve({ status: "reset-buf", newBuf: "" });
320
+ },
321
+ };
322
+ /** `\unset varname` — unset a psql variable. */
323
+ export const cmdUnset = {
324
+ name: "unset",
325
+ helpKey: "unset",
326
+ run: (ctx) => {
327
+ const name = ctx.nextArg("normal");
328
+ if (name === null) {
329
+ writeErr(`\\${ctx.cmdName}: missing required argument\n`);
330
+ return Promise.resolve({ status: "error" });
331
+ }
332
+ ctx.settings.vars.unset(name);
333
+ return Promise.resolve({ status: "ok" });
334
+ },
335
+ };
336
+ export const cmdGetenv = {
337
+ name: "getenv",
338
+ helpKey: "getenv",
339
+ run: (ctx) => {
340
+ const varname = ctx.nextArg("normal");
341
+ const envname = ctx.nextArg("normal");
342
+ if (varname === null || envname === null) {
343
+ writeErr(`\\${ctx.cmdName}: missing required argument\n`);
344
+ return Promise.resolve({ status: "error" });
345
+ }
346
+ const value = process.env[envname];
347
+ if (value === undefined) {
348
+ return Promise.resolve({ status: "ok" });
349
+ }
350
+ if (!ctx.settings.vars.set(varname, value)) {
351
+ writeErr(`\\${ctx.cmdName}: invalid variable name "${varname}"\n`);
352
+ return Promise.resolve({ status: "error" });
353
+ }
354
+ return Promise.resolve({ status: "ok" });
355
+ },
356
+ };
357
+ /**
358
+ * `\setenv envvar [value]`
359
+ *
360
+ * Set `process.env[envvar] = value`; with no value, delete it. Upstream
361
+ * rejects names containing `=`.
362
+ */
363
+ export const cmdSetenv = {
364
+ name: "setenv",
365
+ helpKey: "setenv",
366
+ run: (ctx) => {
367
+ const envname = ctx.nextArg("normal");
368
+ if (envname === null) {
369
+ writeErr(`\\${ctx.cmdName}: missing required argument\n`);
370
+ return Promise.resolve({ status: "error" });
371
+ }
372
+ if (envname.includes("=")) {
373
+ writeErr(`\\${ctx.cmdName}: environment variable name must not contain "="\n`);
374
+ return Promise.resolve({ status: "error" });
375
+ }
376
+ // Upstream `exec_command_setenv` reads BOTH the name AND the value with
377
+ // OT_NORMAL — `:VAR` substitution applies to the value so
378
+ // `\setenv FOO :BAR` propagates the psql-variable value into the env.
379
+ // (Earlier 'no-vars' was a misread; vanilla psql expands inside the
380
+ // value.) The mainloop context maintains a per-mode cursor, so using
381
+ // a single mode for both calls also keeps positional reads in sync —
382
+ // each cursor advances exactly once per call.
383
+ const value = ctx.nextArg("normal");
384
+ if (value === null) {
385
+ // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
386
+ delete process.env[envname];
387
+ }
388
+ else {
389
+ process.env[envname] = value;
390
+ }
391
+ return Promise.resolve({ status: "ok" });
392
+ },
393
+ };
394
+ /**
395
+ * Build the `psql:` diagnostic prefix that upstream `pg_log_pre_callback`
396
+ * prepends to error lines, but ONLY when reading from a script file. Mirrors:
397
+ *
398
+ * if (cur_cmd_source == QUERY_FROM_FILE)
399
+ * fprintf(stderr, "psql:%s:%d: ", cur_cmd_filename, cur_cmd_lineno);
400
+ *
401
+ * - `curCmdSource === 'file'` (running under `-f FILE`, `\i FILE`,
402
+ * `\ir FILE`, or `.psqlrc`): `psql:<inputfile>:<lineno>: `.
403
+ * - Stdin pipe, `-c "..."`, interactive REPL: empty string — vanilla
404
+ * `psql --no-psqlrc -X` reading SQL from stdin emits NO prefix on
405
+ * either `\set` validation errors or server `ERROR:` lines.
406
+ *
407
+ * Returned string ends in a trailing space when non-empty so callers can
408
+ * concatenate the severity directly (`prefix + 'ERROR: msg'`).
409
+ */
410
+ export const psqlErrorPrefix = (settings, lineNumber) => {
411
+ if (settings.curCmdSource === "file" && settings.inputfile) {
412
+ const lineSuffix = lineNumber !== undefined ? String(lineNumber) : "";
413
+ return `psql:${settings.inputfile}:${lineSuffix}: `;
414
+ }
415
+ return "";
416
+ };
417
+ /**
418
+ * Walk past leading whitespace + `--` line comments + slash-star block
419
+ * comments at the head of `sqlText`. Returns the byte index of the first
420
+ * "real" content character. Used by `renderLineAndCaret` to align the
421
+ * `LINE N:` counter with upstream psql — vanilla strips these from the
422
+ * buffer before `PQexec` (so the server's `position` is relative to the
423
+ * trimmed buffer), but `captureLastError`/`normaliseSqlAndPosition` only
424
+ * strips whitespace. Re-stripping here closes the gap when the captured
425
+ * `sqlText` still carries leading `-- comment` lines (the common case
426
+ * for SQL that the mainloop dispatched directly via `sendQuery`,
427
+ * because that path doesn't pre-trim comments).
428
+ *
429
+ * Idempotent for already-trimmed input: if `sqlText` has no leading
430
+ * prelude we return `0`, the caller takes the existing fast-path, and
431
+ * the LINE count remains the count of newlines strictly before
432
+ * `position - 1`.
433
+ */
434
+ const skipLeadingPrelude = (sqlText) => {
435
+ let i = 0;
436
+ const n = sqlText.length;
437
+ while (i < n) {
438
+ const c = sqlText.charCodeAt(i);
439
+ if (c === 0x20 ||
440
+ c === 0x09 ||
441
+ c === 0x0a ||
442
+ c === 0x0d ||
443
+ c === 0x0c ||
444
+ c === 0x0b) {
445
+ i++;
446
+ continue;
447
+ }
448
+ if (c === 0x2d && sqlText.charCodeAt(i + 1) === 0x2d) {
449
+ i += 2;
450
+ while (i < n && sqlText.charCodeAt(i) !== 0x0a)
451
+ i++;
452
+ continue;
453
+ }
454
+ if (c === 0x2f && sqlText.charCodeAt(i + 1) === 0x2a) {
455
+ i += 2;
456
+ let depth = 1;
457
+ while (i < n && depth > 0) {
458
+ if (sqlText.charCodeAt(i) === 0x2f &&
459
+ sqlText.charCodeAt(i + 1) === 0x2a) {
460
+ depth++;
461
+ i += 2;
462
+ }
463
+ else if (sqlText.charCodeAt(i) === 0x2a &&
464
+ sqlText.charCodeAt(i + 1) === 0x2f) {
465
+ depth--;
466
+ i += 2;
467
+ }
468
+ else {
469
+ i++;
470
+ }
471
+ }
472
+ continue;
473
+ }
474
+ break;
475
+ }
476
+ return i;
477
+ };
478
+ /**
479
+ * Render the `LINE N: …` re-print plus the `^` pointer underneath the
480
+ * failing character, mirroring upstream psql's `report_error_query`
481
+ * helper. Returns `null` when we don't have enough context (no SQL text
482
+ * or no position) so the caller can skip the lines entirely.
483
+ *
484
+ * `position` is a 1-based character offset into `sqlText` (as delivered
485
+ * in the server's `P` field). We pick the LINE containing that offset
486
+ * and emit:
487
+ *
488
+ * LINE N: <that line>
489
+ * ^
490
+ *
491
+ * The caret column is aligned to the offset within the picked line so
492
+ * it points at the failing token. Trailing newlines on the picked line
493
+ * are stripped so the `$` end-anchor in upstream's regex still matches.
494
+ *
495
+ * Leading whitespace + comments are skipped before computing the LINE
496
+ * number so the count starts at the first content line — vanilla
497
+ * advances past these before `PQexec`, so the server's `position` is
498
+ * 1-based relative to a trimmed buffer; without the same skip here we'd
499
+ * count newlines that vanilla never sent.
500
+ *
501
+ * Trailing-whitespace fix-up: callers in `cmd_io.ts` strip a `\g`-style
502
+ * buffer's trailing whitespace before handing the SQL to `db.execSimple`
503
+ * / `db.query`, so the server's `position` is relative to the trimmed
504
+ * SQL while `sqlText` (used for the LINE echo) still carries the
505
+ * trailing space(s). When `position` lands on trailing whitespace of
506
+ * the LINE we picked — i.e., past `lineText.trimEnd().length` — that's
507
+ * the "syntax error at end of input" case: vanilla sends the trailing
508
+ * whitespace verbatim and the server reports a position one past the
509
+ * full LINE length. Snap the caret to the end of `lineText` so our
510
+ * output matches vanilla's `^` column. PostgreSQL's scanner never
511
+ * emits positions pointing AT whitespace tokens (they're not lexed as
512
+ * tokens), so the only realistic source of an "in trailing
513
+ * whitespace" position is this trim-on-send delta.
514
+ *
515
+ * Exported so the per-statement error renderer in `core/common.ts` can
516
+ * share the helper with `\errverbose`.
517
+ */
518
+ export const renderLineAndCaret = (sqlText, position) => {
519
+ if (!sqlText || !position)
520
+ return null;
521
+ const pos = parseInt(position, 10);
522
+ if (!Number.isFinite(pos) || pos <= 0)
523
+ return null;
524
+ // Advance past leading WS + comments so the LINE count starts at the
525
+ // first content line. The server's position is into the on-the-wire
526
+ // bytes — typically already past these, so rebasing keeps it inside
527
+ // the content range; if the rebased position would underflow we drop
528
+ // the LINE/caret block rather than mis-pointing.
529
+ const skip = skipLeadingPrelude(sqlText);
530
+ const trimmed = skip === 0 ? sqlText : sqlText.slice(skip);
531
+ const rebasedPos = pos - skip;
532
+ if (rebasedPos <= 0)
533
+ return null;
534
+ // The server's offset is 1-based and points at the failing character.
535
+ const idx = Math.min(rebasedPos - 1, trimmed.length);
536
+ // Find the line containing `idx`.
537
+ let lineStart = trimmed.lastIndexOf("\n", idx - 1);
538
+ lineStart = lineStart === -1 ? 0 : lineStart + 1;
539
+ let lineEnd = trimmed.indexOf("\n", lineStart);
540
+ if (lineEnd === -1)
541
+ lineEnd = trimmed.length;
542
+ const lineText = trimmed.slice(lineStart, lineEnd);
543
+ // Line number for the `LINE N:` prefix — 1-based.
544
+ const before = trimmed.slice(0, lineStart);
545
+ const lineNumber = (before.match(/\n/gu)?.length ?? 0) + 1;
546
+ // Column inside the picked line (0-based) where the `^` goes. Tabs
547
+ // upstream are expanded to a fixed width; we approximate with a
548
+ // single space so the pointer at least lands in the right ballpark.
549
+ let col = idx - lineStart;
550
+ // Snap past trailing whitespace when the position lands inside it —
551
+ // see the function header for the rationale (trim-on-send delta).
552
+ const lineTrimEndLen = lineText.replace(/[ \t\f\v]+$/u, "").length;
553
+ if (col >= lineTrimEndLen && col < lineText.length) {
554
+ col = lineText.length;
555
+ }
556
+ const caretIndent = " ".repeat(Math.max(0, col));
557
+ const prefix = `LINE ${String(lineNumber)}: `;
558
+ return {
559
+ line: `${prefix}${lineText}`,
560
+ caret: `${" ".repeat(prefix.length)}${caretIndent}^`,
561
+ };
562
+ };
563
+ /**
564
+ * Render an ErrorResponse-shaped payload as the layered, verbosity-aware
565
+ * report that upstream psql emits to stderr after a failed statement
566
+ * (`PSQLExec` / `ProcessResult` in `src/bin/psql/common.c`).
567
+ *
568
+ * Returned array contains one element per logical line, without trailing
569
+ * newlines — callers join with `\n` and write to their stream.
570
+ *
571
+ * Verbosity / SHOW_CONTEXT semantics, mirrored from upstream:
572
+ *
573
+ * - `terse`: only the severity line (`<sev>: <msg>`) is emitted.
574
+ *
575
+ * - `default`: severity + message, plus `LINE N` / caret, DETAIL, HINT,
576
+ * STATEMENT (we omit STATEMENT — we never echo the query verbatim).
577
+ * CONTEXT and LOCATION are suppressed unless `SHOW_CONTEXT='always'`.
578
+ *
579
+ * - `verbose`: adds the SQLSTATE prefix on the severity line, and
580
+ * CONTEXT plus LOCATION are unconditionally included when present.
581
+ *
582
+ * - `sqlstate`: prepend the SQLSTATE on the severity line (same as
583
+ * `verbose`'s first line), but suppress LINE/DETAIL/HINT/CONTEXT/
584
+ * LOCATION. Matches the upstream "just give me the code" flavour.
585
+ *
586
+ * Empty server fields are skipped silently. The `LINE` / `^` pair only
587
+ * appears when we have both originating SQL text and a 1-based position
588
+ * pointing inside it.
589
+ */
590
+ export const formatErrorReport = (e, verbosity = "default", showContext = "errors") => {
591
+ const severity = e.severity ?? "ERROR";
592
+ const sqlstate = e.code ?? e.sqlstate ?? "XX000";
593
+ const message = e.message ?? "";
594
+ const out = [];
595
+ // `sqlstate` mode is the upstream "just give me the code" flavour:
596
+ // emit `<severity>: <sqlstate>` with NO message body. `verbose` mode
597
+ // adds the SQLSTATE prefix and keeps the message + LINE/DETAIL/HINT
598
+ // layers below. Default/terse omit the SQLSTATE entirely.
599
+ //
600
+ // Reference: upstream `pg_log_pre_callback` / `PQresultErrorMessage`
601
+ // with `verbosity = PQERRORS_SQLSTATE`, which formats just
602
+ // `severity: sqlstate\n` and stops.
603
+ if (verbosity === "sqlstate") {
604
+ out.push(`${severity}: ${sqlstate}`);
605
+ return out;
606
+ }
607
+ if (verbosity === "verbose") {
608
+ out.push(`${severity}: ${sqlstate}: ${message}`);
609
+ }
610
+ else if (verbosity === "terse") {
611
+ // Terse suppresses LINE/caret/DETAIL/HINT/CONTEXT, but it merges the
612
+ // server's `position` into the severity line as `at character N` —
613
+ // matches libpq's `pqGetErrorNotice3` with `PQERRORS_TERSE` (and
614
+ // vanilla psql in the regress fixture). Only fires when position is a
615
+ // positive integer; the LINE/caret block below would have shown the
616
+ // same anchor for default verbosity.
617
+ const pos = e.position ? Number.parseInt(e.position, 10) : NaN;
618
+ if (Number.isFinite(pos) && pos > 0) {
619
+ out.push(`${severity}: ${message} at character ${String(pos)}`);
620
+ }
621
+ else {
622
+ out.push(`${severity}: ${message}`);
623
+ }
624
+ return out;
625
+ }
626
+ else {
627
+ out.push(`${severity}: ${message}`);
628
+ }
629
+ const lineCaret = renderLineAndCaret(e.sqlText, e.position);
630
+ if (lineCaret) {
631
+ out.push(lineCaret.line);
632
+ out.push(lineCaret.caret);
633
+ }
634
+ if (e.detail)
635
+ out.push(`DETAIL: ${e.detail}`);
636
+ if (e.hint)
637
+ out.push(`HINT: ${e.hint}`);
638
+ // CONTEXT under default verbosity follows SHOW_CONTEXT: 'never' / 'errors'
639
+ // (the default — show on errors) / 'always'. We treat every call into the
640
+ // formatter as an error report, so 'errors' and 'always' both include
641
+ // CONTEXT, while 'never' suppresses it. Verbose verbosity unconditionally
642
+ // includes CONTEXT.
643
+ const includeContext = verbosity === "verbose" || showContext !== "never";
644
+ if (includeContext && e.where) {
645
+ out.push(`CONTEXT: ${e.where}`);
646
+ }
647
+ if (verbosity === "verbose" && (e.routine || e.file || e.line)) {
648
+ const location = (e.routine ?? "") + (e.file ? `, ${e.file}:${e.line ?? ""}` : "");
649
+ out.push(`LOCATION: ${location}`);
650
+ }
651
+ return out;
652
+ };
653
+ /**
654
+ * `\errverbose` — print the last error in verbose form. We rely on the
655
+ * mainloop to have stored `settings.lastErrorResult`; this command only
656
+ * formats and prints. Without a saved error, upstream emits "There is no
657
+ * previous error."
658
+ *
659
+ * Verbose output (PG 18 form):
660
+ *
661
+ * ERROR: <sqlstate>: <message>
662
+ * LINE N: <originating line of SQL>
663
+ * ^
664
+ * DETAIL: <detail>
665
+ * HINT: <hint>
666
+ * CONTEXT: <where>
667
+ * LOCATION: <routine>, <file>:<line>
668
+ *
669
+ * Empty fields are omitted. The `LINE` / `^` pair is only emitted when
670
+ * we have both the originating SQL text and a server-provided position.
671
+ */
672
+ export const cmdErrverbose = {
673
+ name: "errverbose",
674
+ helpKey: "errverbose",
675
+ run: (ctx) => {
676
+ const e = ctx.settings.lastErrorResult;
677
+ if (!e || (!e.message && !e.sqlstate && !e.code)) {
678
+ // Upstream `exec_command_errverbose` writes the "no previous error"
679
+ // notice to stdout (via `printf`); only the verbose re-render goes to
680
+ // stderr (via `pg_log_error`).
681
+ writeOut("There is no previous error.\n");
682
+ return Promise.resolve({ status: "ok" });
683
+ }
684
+ // `\errverbose` always emits the full verbose form regardless of the
685
+ // currently active VERBOSITY setting. Output is prefixed with the same
686
+ // `psql:[<file>:<n>]:` tag upstream's `pg_log_pre_callback` adds — only
687
+ // on the leading severity line; subsequent layers (LINE / caret / DETAIL
688
+ // / HINT / LOCATION) stay unprefixed to match libpq's `PQresultErrorMessage`.
689
+ const lines = formatErrorReport(e, "verbose", "always");
690
+ const prefix = psqlErrorPrefix(ctx.settings);
691
+ const prefixed = [prefix + lines[0], ...lines.slice(1)];
692
+ writeErr(prefixed.join("\n") + "\n");
693
+ return Promise.resolve({ status: "ok" });
694
+ },
695
+ };
696
+ /**
697
+ * `\timing [on|off]` — set `settings.timing`. With no arg the value is
698
+ * flipped. Prints the new state to stdout. `toggle` is NOT a valid value —
699
+ * upstream errors "Boolean expected" (review: minor divergences).
700
+ */
701
+ export const cmdTiming = {
702
+ name: "timing",
703
+ helpKey: "timing",
704
+ run: (ctx) => {
705
+ const arg = ctx.nextArg("normal");
706
+ let next;
707
+ if (arg === null) {
708
+ next = !ctx.settings.timing;
709
+ }
710
+ else {
711
+ const parsed = parseBool(arg);
712
+ if (parsed === null) {
713
+ writeErr(`\\${ctx.cmdName}: unrecognized value "${arg}" for "\\timing": Boolean expected\n`);
714
+ return Promise.resolve({ status: "error" });
715
+ }
716
+ next = parsed;
717
+ }
718
+ ctx.settings.timing = next;
719
+ writeOut(`Timing is ${next ? "on" : "off"}.\n`);
720
+ return Promise.resolve({ status: "ok" });
721
+ },
722
+ };
723
+ /**
724
+ * Static text emitted by `\copyright`. Mirrors upstream psql's
725
+ * `exec_command_copyright()` literal in `src/bin/psql/command.c`.
726
+ */
727
+ const COPYRIGHT_TEXT = `PostgreSQL Database Management System
728
+ (formerly known as Postgres, then as Postgres95)
729
+
730
+ Portions Copyright (c) 1996-2024, PostgreSQL Global Development Group
731
+
732
+ Portions Copyright (c) 1994, The Regents of the University of California
733
+
734
+ Permission to use, copy, modify, and distribute this software and its
735
+ documentation for any purpose, without fee, and without a written agreement
736
+ is hereby granted, provided that the above copyright notice and this
737
+ paragraph and the following two paragraphs appear in all copies.
738
+
739
+ IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
740
+ DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING
741
+ LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION,
742
+ EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF
743
+ SUCH DAMAGE.
744
+
745
+ THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
746
+ INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
747
+ AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
748
+ ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATIONS TO
749
+ PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
750
+ `;
751
+ /**
752
+ * neonctl-specific notice appended after the upstream PostgreSQL block.
753
+ * This psql is a pure-TypeScript reimplementation embedded in neonctl, not
754
+ * upstream psql — so we attribute it accordingly. No license claim is made
755
+ * here on purpose (see the project's LICENSE file for terms).
756
+ */
757
+ const NEON_NOTICE = `
758
+ This is an embedded psql reimplementation that ships with neonctl, the
759
+ command-line interface for Neon (https://neon.tech). Neon is part of
760
+ Databricks (https://www.databricks.com).
761
+
762
+ It is an independent reimplementation of psql and is not affiliated with
763
+ or endorsed by the PostgreSQL Global Development Group. See the neonctl
764
+ LICENSE file for distribution terms.
765
+ `;
766
+ /**
767
+ * `\copyright` — print the PostgreSQL copyright / license notice, followed
768
+ * by a neonctl + Neon/Databricks attribution block. Takes no arguments.
769
+ * The upstream block is preserved verbatim so the conformance regex
770
+ * `/Copyright/` (from upstream `001_basic.pl` line 75) is satisfied; the
771
+ * Neon notice is appended after it.
772
+ */
773
+ export const cmdCopyright = {
774
+ name: "copyright",
775
+ helpKey: "copyright",
776
+ run: () => {
777
+ writeOut(COPYRIGHT_TEXT + NEON_NOTICE);
778
+ return Promise.resolve({ status: "ok" });
779
+ },
780
+ };
781
+ /**
782
+ * Terminal width used to lay out `\h` / `\help` topic lists. Upstream
783
+ * uses `pset.popt.topt.envColumns` falling back to `ioctl(TIOCGWINSZ)`;
784
+ * we read `process.stdout.columns` (Node populates this for TTYs) and
785
+ * default to 80 if absent (non-TTY, piped output, etc.).
786
+ */
787
+ const screenWidth = () => {
788
+ const cols = process.stdout.columns;
789
+ return typeof cols === "number" && cols > 0 ? cols : 80;
790
+ };
791
+ /**
792
+ * `\h [TOPIC]` (alias `\help`) — show SQL command help.
793
+ *
794
+ * Delegates to {@link helpSQL} in `core/help.ts`, passing the remainder
795
+ * of the line as the topic. With no topic, prints the "Available help:"
796
+ * overview; with a topic, prints the matching synopsis or a list of
797
+ * matches. Mirrors upstream `exec_command_help` in `command.c`.
798
+ */
799
+ export const cmdHelpSQL = {
800
+ name: "h",
801
+ aliases: ["help"],
802
+ helpKey: "h",
803
+ run: (ctx) => {
804
+ // Upstream consumes the rest of the line in `OT_WHOLE_LINE` mode so
805
+ // multi-word topics like "CREATE TABLE" come through intact.
806
+ const topic = ctx.restOfLine();
807
+ helpSQL(process.stdout, topic.length === 0 ? null : topic, screenWidth());
808
+ return Promise.resolve({ status: "ok" });
809
+ },
810
+ };
811
+ /**
812
+ * `\?` — show help for the backslash commands.
813
+ *
814
+ * Delegates to {@link slashUsage} in `core/help.ts`. We pass the output
815
+ * stream (`process.stdout`) and request the pager only when that stream is
816
+ * an interactive TTY — `slashUsage`/`emitHelp` re-check interactivity, but
817
+ * gating the request here keeps the non-interactive path (scripts, piped
818
+ * output, the regress harness) writing straight to stdout with no pager.
819
+ *
820
+ * Upstream `exec_command_help` reads `[commands|options|variables]`; we
821
+ * mirror the default (backslash commands) form, which is the only variant
822
+ * `\?` reaches without an argument. The remainder of the line is consumed
823
+ * so a stray topic doesn't leak into the next command.
824
+ */
825
+ export const cmdSlashHelp = {
826
+ name: "?",
827
+ argMode: "whole-line",
828
+ helpKey: "?",
829
+ run: (ctx) => {
830
+ // Consume the rest of the line (`\? options`, `\? variables`) so the
831
+ // cursor doesn't strand trailing text; we only render the command help.
832
+ ctx.restOfLine();
833
+ const out = process.stdout;
834
+ const pager = Boolean(out.isTTY);
835
+ slashUsage(out, pager);
836
+ return Promise.resolve({ status: "ok" });
837
+ },
838
+ };
839
+ /**
840
+ * Resolve the editor command psql would launch for `\e` / `\ef` / `\ev`,
841
+ * mirroring upstream `editFile` / `get_alternate_expansion`:
842
+ *
843
+ * $PSQL_EDITOR || $EDITOR || $VISUAL || platform default
844
+ *
845
+ * The platform default is `notepad.exe` on Windows and `vi` elsewhere,
846
+ * matching upstream's `DEFAULT_EDITOR`.
847
+ */
848
+ export const resolveEditor = (env = process.env) => {
849
+ const explicit = env.PSQL_EDITOR ?? env.EDITOR ?? env.VISUAL;
850
+ if (explicit !== undefined && explicit.length > 0)
851
+ return explicit;
852
+ return process.platform === "win32" ? "notepad.exe" : "vi";
853
+ };
854
+ /**
855
+ * `\e` / `\edit [FILE] [LINE]` — edit the current query buffer (or a file)
856
+ * in the user's editor, then load the edited text back into the query
857
+ * buffer.
858
+ *
859
+ * This port implements the common no-FILE form: dump the current query
860
+ * buffer to a temp file, spawn the editor on it inheriting stdio (upstream
861
+ * `do_edit` → `editFile`), and on a clean exit read the file back and
862
+ * return it as the new query buffer via `status: 'reset-buf'`. Upstream
863
+ * strips a single trailing newline the editor may add; we do the same so
864
+ * round-tripping an unchanged buffer is a no-op.
865
+ *
866
+ * Editor selection follows {@link resolveEditor}. The spawn uses
867
+ * `spawnSync(..., { stdio: 'inherit' })` so the editor owns the terminal.
868
+ * If the editor exits non-zero (or fails to spawn) we leave the buffer
869
+ * untouched and report an error, matching upstream's behaviour of not
870
+ * importing a failed edit.
871
+ *
872
+ * FILE / LINE arguments are accepted but the buffer is still seeded from
873
+ * the current query buffer; a future WP can layer file-backed editing
874
+ * (`\e file`) and `\ef`/`\ev` on top.
875
+ */
876
+ export const cmdEdit = {
877
+ name: "e",
878
+ aliases: ["edit"],
879
+ argMode: "whole-line",
880
+ helpKey: "e",
881
+ run: (ctx) => {
882
+ // We don't yet support `\e FILE`; consume the args so they don't strand.
883
+ ctx.restOfLine();
884
+ const editor = resolveEditor();
885
+ // psql seeds the temp file with the current query buffer. A trailing
886
+ // newline keeps editors that expect newline-terminated files happy.
887
+ const seed = ctx.queryBuf.length > 0 && !ctx.queryBuf.endsWith("\n")
888
+ ? ctx.queryBuf + "\n"
889
+ : ctx.queryBuf;
890
+ let dir = null;
891
+ try {
892
+ dir = mkdtempSync(join(tmpdir(), "psql.edit."));
893
+ const file = join(dir, "edit.sql");
894
+ writeFileSync(file, seed, "utf8");
895
+ const result = spawnSync(editor, [file], { stdio: "inherit" });
896
+ if (result.error ||
897
+ (result.status !== null && result.status !== 0)) {
898
+ const why = result.error
899
+ ? result.error.message
900
+ : `editor exited with status ${String(result.status)}`;
901
+ writeErr(`\\${ctx.cmdName}: ${why}\n`);
902
+ return Promise.resolve({ status: "error" });
903
+ }
904
+ let edited = readFileSync(file, "utf8");
905
+ // Upstream drops a single trailing newline the editor may have added
906
+ // so an unchanged round-trip restores the original buffer exactly.
907
+ if (edited.endsWith("\n"))
908
+ edited = edited.slice(0, -1);
909
+ return Promise.resolve({ status: "reset-buf", newBuf: edited });
910
+ }
911
+ catch (err) {
912
+ const msg = err instanceof Error ? err.message : String(err);
913
+ writeErr(`\\${ctx.cmdName}: ${msg}\n`);
914
+ return Promise.resolve({ status: "error" });
915
+ }
916
+ finally {
917
+ if (dir) {
918
+ try {
919
+ rmSync(dir, { recursive: true, force: true });
920
+ }
921
+ catch {
922
+ // Temp-dir cleanup is best-effort; a leftover dir is harmless.
923
+ }
924
+ }
925
+ }
926
+ },
927
+ };
928
+ /**
929
+ * `\s [FILENAME]` — print the command-line history, or save it to FILENAME.
930
+ *
931
+ * Mirrors upstream `exec_command_s` / `printHistory`:
932
+ *
933
+ * - No argument: write the in-memory history (one entry per line) to
934
+ * stdout. Multi-line entries are printed verbatim (with their embedded
935
+ * newlines), matching readline's `\s` dump.
936
+ * - FILENAME given: write the same dump to that file. On success, and
937
+ * unless `\set QUIET` is in effect, print `Wrote history to file
938
+ * "<file>".` to stdout. On failure, emit the OS error to stderr and
939
+ * return an error.
940
+ *
941
+ * The history source is {@link getHistory}, the session's in-memory list
942
+ * populated as each line is submitted (see `io/history.ts`).
943
+ */
944
+ export const cmdS = {
945
+ name: "s",
946
+ helpKey: "s",
947
+ run: (ctx) => {
948
+ const fname = ctx.nextArg("normal");
949
+ const entries = getHistory();
950
+ // Each entry is one logical command; readline's `\s` prints them one
951
+ // per line, so a trailing newline per entry reproduces that layout.
952
+ const body = entries.map((e) => e + "\n").join("");
953
+ if (fname === null || fname.length === 0) {
954
+ writeOut(body);
955
+ return Promise.resolve({ status: "ok" });
956
+ }
957
+ try {
958
+ writeFileSync(fname, body, "utf8");
959
+ }
960
+ catch (err) {
961
+ const msg = err instanceof Error ? err.message : String(err);
962
+ writeErr(`\\${ctx.cmdName}: ${msg}\n`);
963
+ return Promise.resolve({ status: "error" });
964
+ }
965
+ if (!ctx.settings.quiet) {
966
+ writeOut(`Wrote history to file "${fname}".\n`);
967
+ }
968
+ return Promise.resolve({ status: "ok" });
969
+ },
970
+ };