neonctl 2.22.2 → 2.23.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 (113) hide show
  1. package/README.md +84 -0
  2. package/analytics.js +5 -2
  3. package/commands/branches.js +9 -1
  4. package/commands/connection_string.js +9 -1
  5. package/commands/functions.js +277 -0
  6. package/commands/index.js +4 -0
  7. package/commands/neon_auth.js +1013 -0
  8. package/commands/projects.js +9 -1
  9. package/commands/psql.js +6 -1
  10. package/functions_api.js +44 -0
  11. package/package.json +15 -5
  12. package/psql/cli.js +51 -0
  13. package/psql/command/cmd_cond.js +437 -0
  14. package/psql/command/cmd_connect.js +815 -0
  15. package/psql/command/cmd_copy.js +1025 -0
  16. package/psql/command/cmd_describe.js +1810 -0
  17. package/psql/command/cmd_format.js +909 -0
  18. package/psql/command/cmd_io.js +2187 -0
  19. package/psql/command/cmd_lo.js +385 -0
  20. package/psql/command/cmd_meta.js +970 -0
  21. package/psql/command/cmd_misc.js +187 -0
  22. package/psql/command/cmd_pipeline.js +1141 -0
  23. package/psql/command/cmd_restrict.js +171 -0
  24. package/psql/command/cmd_show.js +751 -0
  25. package/psql/command/dispatch.js +343 -0
  26. package/psql/command/inputQueue.js +42 -0
  27. package/psql/command/shared.js +71 -0
  28. package/psql/complete/filenames.js +139 -0
  29. package/psql/complete/index.js +104 -0
  30. package/psql/complete/matcher.js +314 -0
  31. package/psql/complete/psqlVars.js +247 -0
  32. package/psql/complete/queries.js +491 -0
  33. package/psql/complete/rules.js +2387 -0
  34. package/psql/core/common.js +1250 -0
  35. package/psql/core/help.js +576 -0
  36. package/psql/core/mainloop.js +1353 -0
  37. package/psql/core/prompt.js +437 -0
  38. package/psql/core/settings.js +684 -0
  39. package/psql/core/sqlHelp.js +1066 -0
  40. package/psql/core/startup.js +840 -0
  41. package/psql/core/syncVars.js +116 -0
  42. package/psql/core/variables.js +287 -0
  43. package/psql/describe/formatters.js +1277 -0
  44. package/psql/describe/processNamePattern.js +270 -0
  45. package/psql/describe/queries.js +2373 -0
  46. package/psql/describe/versionGate.js +43 -0
  47. package/psql/index.js +2005 -0
  48. package/psql/io/history.js +299 -0
  49. package/psql/io/input.js +120 -0
  50. package/psql/io/lineEditor/buffer.js +323 -0
  51. package/psql/io/lineEditor/complete.js +227 -0
  52. package/psql/io/lineEditor/filename.js +159 -0
  53. package/psql/io/lineEditor/index.js +891 -0
  54. package/psql/io/lineEditor/keymap.js +738 -0
  55. package/psql/io/lineEditor/vt100.js +363 -0
  56. package/psql/io/pgpass.js +202 -0
  57. package/psql/io/pgservice.js +194 -0
  58. package/psql/io/psqlrc.js +422 -0
  59. package/psql/print/aligned.js +1756 -0
  60. package/psql/print/asciidoc.js +248 -0
  61. package/psql/print/crosstab.js +460 -0
  62. package/psql/print/csv.js +92 -0
  63. package/psql/print/html.js +258 -0
  64. package/psql/print/json.js +96 -0
  65. package/psql/print/latex.js +396 -0
  66. package/psql/print/pager.js +265 -0
  67. package/psql/print/troff.js +258 -0
  68. package/psql/print/unaligned.js +118 -0
  69. package/psql/print/units.js +135 -0
  70. package/psql/scanner/slash.js +513 -0
  71. package/psql/scanner/sql.js +910 -0
  72. package/psql/scanner/stringutils.js +390 -0
  73. package/psql/types/backslash.js +1 -0
  74. package/psql/types/connection.js +1 -0
  75. package/psql/types/index.js +7 -0
  76. package/psql/types/printer.js +1 -0
  77. package/psql/types/repl.js +1 -0
  78. package/psql/types/scanner.js +24 -0
  79. package/psql/types/settings.js +1 -0
  80. package/psql/types/variables.js +1 -0
  81. package/psql/wire/connection.js +2844 -0
  82. package/psql/wire/copy.js +108 -0
  83. package/psql/wire/notify.js +59 -0
  84. package/psql/wire/pipeline.js +519 -0
  85. package/psql/wire/protocol.js +466 -0
  86. package/psql/wire/sasl.js +296 -0
  87. package/psql/wire/tls.js +596 -0
  88. package/test_utils/fixtures.js +1 -0
  89. package/utils/esbuild.js +147 -0
  90. package/utils/psql.js +107 -11
  91. package/utils/zip.js +4 -0
  92. package/writer.js +1 -1
  93. package/commands/auth.test.js +0 -211
  94. package/commands/branches.test.js +0 -460
  95. package/commands/checkout.test.js +0 -170
  96. package/commands/connection_string.test.js +0 -196
  97. package/commands/data_api.test.js +0 -169
  98. package/commands/databases.test.js +0 -39
  99. package/commands/help.test.js +0 -9
  100. package/commands/init.test.js +0 -56
  101. package/commands/ip_allow.test.js +0 -59
  102. package/commands/link.test.js +0 -381
  103. package/commands/operations.test.js +0 -7
  104. package/commands/orgs.test.js +0 -7
  105. package/commands/projects.test.js +0 -144
  106. package/commands/psql.test.js +0 -49
  107. package/commands/roles.test.js +0 -37
  108. package/commands/set_context.test.js +0 -159
  109. package/commands/vpc_endpoints.test.js +0 -69
  110. package/context.test.js +0 -119
  111. package/env.test.js +0 -55
  112. package/utils/formats.test.js +0 -32
  113. package/writer.test.js +0 -104
@@ -0,0 +1,576 @@
1
+ /**
2
+ * psql help text — TypeScript port of upstream `src/bin/psql/help.c`.
3
+ *
4
+ * Phase-0 (WP-18). The literal text matches PostgreSQL master; whitespace and
5
+ * line breaks are load-bearing because output is compared against upstream
6
+ * psql. Runtime-dependent fields (current DB name, format toggles, timing,
7
+ * default field/CSV separators, etc.) are accepted via the optional `opts`
8
+ * object so that callers can wire them in without this module reaching into
9
+ * `pset` directly.
10
+ *
11
+ * `helpSQL` ships a curated subset of upstream's auto-generated `sql_help.h`
12
+ * — ~70 commands covering the everyday DML/DDL/transaction/role surface. See
13
+ * {@link ./sqlHelp.ts} for the data and lookup logic. Rarer commands resolve
14
+ * through the docs URL on each entry rather than being inlined here.
15
+ */
16
+ import { openPager } from '../print/pager.js';
17
+ import { SQL_HELP, findMatches, formatEntry } from './sqlHelp.js';
18
+ let pagerOpener = openPager;
19
+ /** Override the pager opener (tests only). Returns a restore function. */
20
+ export const setHelpPagerOpener = (opener) => {
21
+ const prev = pagerOpener;
22
+ pagerOpener = opener;
23
+ return () => {
24
+ pagerOpener = prev;
25
+ };
26
+ };
27
+ /** True when `out` is a TTY whose height we can sensibly page against. */
28
+ const isInteractive = (out) => Boolean(out.isTTY);
29
+ /**
30
+ * Emit help text. When `pager` is requested and `out` is interactive, route
31
+ * the text through the external pager (upstream `PageOutput`); otherwise write
32
+ * it straight to `out`.
33
+ *
34
+ * The pager decision (TTY, line count vs. terminal height, resolved pager
35
+ * command) is delegated to {@link openPager}, which falls back to a no-op
36
+ * handle wrapping `out` when paging isn't warranted. We pass the help text's
37
+ * own line count so the auto threshold matches what the user will see.
38
+ */
39
+ const emitHelp = (out, text, pager) => {
40
+ if (!pager || !isInteractive(out)) {
41
+ out.write(text);
42
+ return;
43
+ }
44
+ // Count lines so `openPager`'s auto-mode threshold reflects the real output.
45
+ const lines = text.length === 0 ? 0 : text.split('\n').length;
46
+ const handle = pagerOpener({
47
+ pager: 'on',
48
+ pagerMinLines: 0,
49
+ lines,
50
+ stdout: out,
51
+ });
52
+ handle.out.write(text);
53
+ // `close()` waits for the pager to drain & exit and never rejects (spawn
54
+ // failures settle to a non-zero code), so detaching it here cannot produce
55
+ // an unhandled rejection. When no pager spawned, this resolves immediately.
56
+ void handle.close();
57
+ };
58
+ const DEFAULTS = {
59
+ progname: 'psql',
60
+ defaultFieldSep: '|',
61
+ defaultCsvFieldSep: ',',
62
+ defaultWatchInterval: '2',
63
+ packageBugReport: 'pgsql-bugs@lists.postgresql.org',
64
+ packageName: 'PostgreSQL',
65
+ packageUrl: 'https://www.postgresql.org/',
66
+ currentDb: null,
67
+ htmlMode: false,
68
+ tuplesOnly: false,
69
+ expanded: false,
70
+ timing: false,
71
+ win32: false,
72
+ useReadline: true,
73
+ };
74
+ const resolve = (opts) => ({
75
+ ...DEFAULTS,
76
+ ...opts,
77
+ });
78
+ const on = (v) => (v ? 'on' : 'off');
79
+ const expandedLabel = (v) => v === 'auto' ? 'auto' : on(v);
80
+ /**
81
+ * `psql --help` text — top-level command-line options.
82
+ *
83
+ * Always written inline: this is the `--help` path (and `\? options`), which
84
+ * upstream emits without a pager. Interactive `\?` paging is handled by
85
+ * {@link slashUsage} via its `pager` flag.
86
+ */
87
+ export const usage = (out, opts) => {
88
+ const o = resolve(opts);
89
+ const buf = [];
90
+ const w = (s) => {
91
+ buf.push(s);
92
+ };
93
+ w(`${o.progname} is the PostgreSQL interactive terminal.\n\n`);
94
+ w('Usage:\n');
95
+ w(` ${o.progname} [OPTION]... [DBNAME [USERNAME]]\n\n`);
96
+ w('General options:\n');
97
+ w(' -c, --command=COMMAND run only single command (SQL or internal) and exit\n');
98
+ w(' -d, --dbname=DBNAME database name to connect to\n');
99
+ w(' -f, --file=FILENAME execute commands from file, then exit\n');
100
+ w(' -l, --list list available databases, then exit\n');
101
+ w(' -v, --set=, --variable=NAME=VALUE\n' +
102
+ ' set psql variable NAME to VALUE\n' +
103
+ ' (e.g., -v ON_ERROR_STOP=1)\n');
104
+ w(' -V, --version output version information, then exit\n');
105
+ w(' -X, --no-psqlrc do not read startup file (~/.psqlrc)\n');
106
+ w(' -1 ("one"), --single-transaction\n' +
107
+ ' execute as a single transaction (if non-interactive)\n');
108
+ w(' -?, --help[=options] show this help, then exit\n');
109
+ w(' --help=commands list backslash commands, then exit\n');
110
+ w(' --help=variables list special variables, then exit\n');
111
+ w('\nInput and output options:\n');
112
+ w(' -a, --echo-all echo all input from script\n');
113
+ w(' -b, --echo-errors echo failed commands\n');
114
+ w(' -e, --echo-queries echo commands sent to server\n');
115
+ w(' -E, --echo-hidden display queries that internal commands generate\n');
116
+ w(' -L, --log-file=FILENAME send session log to file\n');
117
+ w(' -n, --no-readline disable enhanced command line editing (readline)\n');
118
+ w(' -o, --output=FILENAME send query results to file (or |pipe)\n');
119
+ w(' -q, --quiet run quietly (no messages, only query output)\n');
120
+ w(' -s, --single-step single-step mode (confirm each query)\n');
121
+ w(' -S, --single-line single-line mode (end of line terminates SQL command)\n');
122
+ w('\nOutput format options:\n');
123
+ w(' -A, --no-align unaligned table output mode\n');
124
+ w(' --csv CSV (Comma-Separated Values) table output mode\n');
125
+ w(' -F, --field-separator=STRING\n' +
126
+ ` field separator for unaligned output (default: "${o.defaultFieldSep}")\n`);
127
+ w(' -H, --html HTML table output mode\n');
128
+ w(' -P, --pset=VAR[=ARG] set printing option VAR to ARG (see \\pset command)\n');
129
+ w(' -R, --record-separator=STRING\n' +
130
+ ' record separator for unaligned output (default: newline)\n');
131
+ w(' -t, --tuples-only print rows only\n');
132
+ w(' -T, --table-attr=TEXT set HTML table tag attributes (e.g., width, border)\n');
133
+ w(' -x, --expanded turn on expanded table output\n');
134
+ w(' -z, --field-separator-zero\n' +
135
+ ' set field separator for unaligned output to zero byte\n');
136
+ w(' -0, --record-separator-zero\n' +
137
+ ' set record separator for unaligned output to zero byte\n');
138
+ w('\nConnection options:\n');
139
+ w(' -h, --host=HOSTNAME database server host or socket directory\n');
140
+ w(' -p, --port=PORT database server port\n');
141
+ w(' -U, --username=USERNAME database user name\n');
142
+ w(' -w, --no-password never prompt for password\n');
143
+ w(' -W, --password force password prompt (should happen automatically)\n');
144
+ w('\nFor more information, type "\\?" (for internal commands) or "\\help" (for SQL\n' +
145
+ 'commands) from within psql, or consult the psql section in the PostgreSQL\n' +
146
+ 'documentation.\n\n');
147
+ w(`Report bugs to <${o.packageBugReport}>.\n`);
148
+ w(`${o.packageName} home page: <${o.packageUrl}>\n`);
149
+ out.write(buf.join(''));
150
+ };
151
+ /**
152
+ * `\?` general output — help for the backslash commands.
153
+ *
154
+ * When `pager` is true and `out` is interactive, the rendered text is routed
155
+ * through the external pager (see {@link emitHelp}); otherwise it is written
156
+ * straight to `out`.
157
+ */
158
+ export const slashUsage = (out, pager, opts) => {
159
+ const o = resolve(opts);
160
+ const buf = [];
161
+ const w = (s) => {
162
+ buf.push(s);
163
+ };
164
+ w('General\n');
165
+ w(' \\copyright show PostgreSQL usage and distribution terms\n');
166
+ w(' \\crosstabview [COLUMNS] execute query and display result in crosstab\n');
167
+ w(' \\errverbose show most recent error message at maximum verbosity\n');
168
+ w(' \\g [(OPTIONS)] [FILE] execute query (and send result to file or |pipe);\n' +
169
+ ' \\g with no arguments is equivalent to a semicolon\n');
170
+ w(' \\gdesc describe result of query, without executing it\n');
171
+ w(' \\gexec execute query, then execute each value in its result\n');
172
+ w(' \\gset [PREFIX] execute query and store result in psql variables\n');
173
+ w(' \\gx [(OPTIONS)] [FILE] as \\g, but forces expanded output mode\n');
174
+ w(' \\q quit psql\n');
175
+ w(' \\restrict RESTRICT_KEY\n' +
176
+ ' enter restricted mode with provided key\n');
177
+ w(' \\unrestrict RESTRICT_KEY\n' +
178
+ ' exit restricted mode if key matches\n');
179
+ w(' \\watch [[i=]SEC] [c=N] [m=MIN]\n' +
180
+ ' execute query every SEC seconds, up to N times,\n' +
181
+ ' stop if less than MIN rows are returned\n');
182
+ w('\n');
183
+ w('Help\n');
184
+ w(' \\? [commands] show help on backslash commands\n');
185
+ w(' \\? options show help on psql command-line options\n');
186
+ w(' \\? variables show help on special variables\n');
187
+ w(' \\h [NAME] help on syntax of SQL commands, * for all commands\n');
188
+ w('\n');
189
+ w('Query Buffer\n');
190
+ w(' \\e [FILE] [LINE] edit the query buffer (or file) with external editor\n');
191
+ w(' \\ef [FUNCNAME [LINE]] edit function definition with external editor\n');
192
+ w(' \\ev [VIEWNAME [LINE]] edit view definition with external editor\n');
193
+ w(' \\p show the contents of the query buffer\n');
194
+ w(' \\r reset (clear) the query buffer\n');
195
+ if (o.useReadline) {
196
+ w(' \\s [FILE] display history or save it to file\n');
197
+ }
198
+ w(' \\w FILE write query buffer to file\n');
199
+ w('\n');
200
+ w('Input/Output\n');
201
+ w(' \\copy ... perform SQL COPY with data stream to the client host\n');
202
+ w(' \\echo [-n] [STRING] write string to standard output (-n for no newline)\n');
203
+ w(' \\i FILE execute commands from file\n');
204
+ w(' \\ir FILE as \\i, but relative to location of current script\n');
205
+ w(' \\o [FILE] send all query results to file or |pipe\n');
206
+ w(' \\qecho [-n] [STRING] write string to \\o output stream (-n for no newline)\n');
207
+ w(' \\warn [-n] [STRING] write string to standard error (-n for no newline)\n');
208
+ w('\n');
209
+ w('Conditional\n');
210
+ w(' \\if EXPR begin conditional block\n');
211
+ w(' \\elif EXPR alternative within current conditional block\n');
212
+ w(' \\else final alternative within current conditional block\n');
213
+ w(' \\endif end conditional block\n');
214
+ w('\n');
215
+ w('Informational\n');
216
+ w(' (options: S = show system objects, x = expanded mode, + = additional detail)\n');
217
+ w(' \\d[Sx+] list tables, views, sequences, and property graphs\n');
218
+ w(' \\d[S+] NAME describe table, view, sequence, index, or property graph\n');
219
+ w(' \\da[Sx] [PATTERN] list aggregates\n');
220
+ w(' \\dA[x+] [PATTERN] list access methods\n');
221
+ w(' \\dAc[x+] [AMPTRN [TYPEPTRN]] list operator classes\n');
222
+ w(' \\dAf[x+] [AMPTRN [TYPEPTRN]] list operator families\n');
223
+ w(' \\dAo[x+] [AMPTRN [OPFPTRN]] list operators of operator families\n');
224
+ w(' \\dAp[x+] [AMPTRN [OPFPTRN]] list support functions of operator families\n');
225
+ w(' \\db[x+] [PATTERN] list tablespaces\n');
226
+ w(' \\dc[Sx+] [PATTERN] list conversions\n');
227
+ w(' \\dconfig[x+] [PATTERN] list configuration parameters\n');
228
+ w(' \\dC[x+] [PATTERN] list casts\n');
229
+ w(' \\dd[Sx] [PATTERN] show object descriptions not displayed elsewhere\n');
230
+ w(' \\dD[Sx+] [PATTERN] list domains\n');
231
+ w(' \\ddp[x] [PATTERN] list default privileges\n');
232
+ w(' \\dE[Sx+] [PATTERN] list foreign tables\n');
233
+ w(' \\des[x+] [PATTERN] list foreign servers\n');
234
+ w(' \\det[x+] [PATTERN] list foreign tables\n');
235
+ w(' \\deu[x+] [PATTERN] list user mappings\n');
236
+ w(' \\dew[x+] [PATTERN] list foreign-data wrappers\n');
237
+ w(' \\df[anptw][Sx+] [FUNCPTRN [TYPEPTRN ...]]\n' +
238
+ ' list [only agg/normal/procedure/trigger/window] functions\n');
239
+ w(' \\dF[x+] [PATTERN] list text search configurations\n');
240
+ w(' \\dFd[x+] [PATTERN] list text search dictionaries\n');
241
+ w(' \\dFp[x+] [PATTERN] list text search parsers\n');
242
+ w(' \\dFt[x+] [PATTERN] list text search templates\n');
243
+ w(' \\dg[Sx+] [PATTERN] list roles\n');
244
+ w(' \\dG[Sx+] [PATTERN] list property graphs\n');
245
+ w(' \\di[Sx+] [PATTERN] list indexes\n');
246
+ w(' \\dl[x+] list large objects, same as \\lo_list\n');
247
+ w(' \\dL[Sx+] [PATTERN] list procedural languages\n');
248
+ w(' \\dm[Sx+] [PATTERN] list materialized views\n');
249
+ w(' \\dn[Sx+] [PATTERN] list schemas\n');
250
+ w(' \\do[Sx+] [OPPTRN [TYPEPTRN [TYPEPTRN]]]\n' +
251
+ ' list operators\n');
252
+ w(' \\dO[Sx+] [PATTERN] list collations\n');
253
+ w(' \\dp[Sx] [PATTERN] list table, view, and sequence access privileges\n');
254
+ w(' \\dP[itnx+] [PATTERN] list [only index/table] partitioned relations [n=nested]\n');
255
+ w(' \\drds[x] [ROLEPTRN [DBPTRN]]\n' +
256
+ ' list per-database role settings\n');
257
+ w(' \\drg[Sx] [PATTERN] list role grants\n');
258
+ w(' \\dRp[x+] [PATTERN] list replication publications\n');
259
+ w(' \\dRs[x+] [PATTERN] list replication subscriptions\n');
260
+ w(' \\ds[Sx+] [PATTERN] list sequences\n');
261
+ w(' \\dt[Sx+] [PATTERN] list tables\n');
262
+ w(' \\dT[Sx+] [PATTERN] list data types\n');
263
+ w(' \\du[Sx+] [PATTERN] list roles\n');
264
+ w(' \\dv[Sx+] [PATTERN] list views\n');
265
+ w(' \\dx[x+] [PATTERN] list extensions\n');
266
+ w(' \\dX[x+] [PATTERN] list extended statistics\n');
267
+ w(' \\dy[x+] [PATTERN] list event triggers\n');
268
+ w(' \\l[x+] [PATTERN] list databases\n');
269
+ w(" \\sf[+] FUNCNAME show a function's definition\n");
270
+ w(" \\sv[+] VIEWNAME show a view's definition\n");
271
+ w(' \\z[Sx] [PATTERN] same as \\dp\n');
272
+ w('\n');
273
+ w('Large Objects\n');
274
+ w(' \\lo_export LOBOID FILE write large object to file\n');
275
+ w(' \\lo_import FILE [COMMENT]\n' +
276
+ ' read large object from file\n');
277
+ w(' \\lo_list[x+] list large objects\n');
278
+ w(' \\lo_unlink LOBOID delete a large object\n');
279
+ w('\n');
280
+ w('Formatting\n');
281
+ w(' \\a toggle between unaligned and aligned output mode\n');
282
+ w(' \\C [STRING] set table title, or unset if none\n');
283
+ w(' \\f [STRING] show or set field separator for unaligned query output\n');
284
+ w(` \\H toggle HTML output mode (currently ${on(o.htmlMode)})\n`);
285
+ w(' \\pset [NAME [VALUE]] set table output option\n' +
286
+ ' see "\\? variables" for valid options\n');
287
+ w(` \\t [on|off] show only rows (currently ${on(o.tuplesOnly)})\n`);
288
+ w(' \\T [STRING] set HTML <table> tag attributes, or unset if none\n');
289
+ w(` \\x [on|off|auto] toggle expanded output (currently ${expandedLabel(o.expanded)})\n`);
290
+ w('\n');
291
+ w('Connection\n');
292
+ if (o.currentDb) {
293
+ w(' \\c[onnect] {[DBNAME|- USER|- HOST|- PORT|-] | conninfo}\n' +
294
+ ` connect to new database (currently "${o.currentDb}")\n`);
295
+ }
296
+ else {
297
+ w(' \\c[onnect] {[DBNAME|- USER|- HOST|- PORT|-] | conninfo}\n' +
298
+ ' connect to new database (currently no connection)\n');
299
+ }
300
+ w(' \\conninfo display information about current connection\n');
301
+ w(' \\encoding [ENCODING] show or set client encoding\n');
302
+ w(' \\password [USERNAME] securely change the password for a user\n');
303
+ w('\n');
304
+ w('Operating System\n');
305
+ w(' \\cd [DIR] change the current working directory\n');
306
+ w(' \\getenv PSQLVAR ENVVAR fetch environment variable\n');
307
+ w(' \\setenv NAME [VALUE] set or unset environment variable\n');
308
+ w(` \\timing [on|off] toggle timing of commands (currently ${on(o.timing)})\n`);
309
+ w(' \\! [COMMAND] execute command in shell or start interactive shell\n');
310
+ w('\n');
311
+ w('Variables\n');
312
+ w(' \\prompt [TEXT] NAME prompt user to set internal variable\n');
313
+ w(' \\set [NAME [VALUE]] set internal variable, or list all if no parameters\n');
314
+ w(' \\unset NAME unset (delete) internal variable\n');
315
+ w('\n');
316
+ w('Extended Query Protocol\n');
317
+ w(' \\bind [PARAM]... set query parameters\n');
318
+ w(' \\bind_named STMT_NAME [PARAM]...\n' +
319
+ ' set query parameters for an existing prepared statement\n');
320
+ w(' \\close_prepared STMT_NAME\n' +
321
+ ' close an existing prepared statement\n');
322
+ w(' \\endpipeline exit pipeline mode\n');
323
+ w(' \\flush flush output data to the server\n');
324
+ w(' \\flushrequest send request to the server to flush its output buffer\n');
325
+ w(' \\getresults [NUM_RES] read NUM_RES pending results, or all if no argument\n');
326
+ w(' \\parse STMT_NAME create a prepared statement\n');
327
+ w(' \\sendpipeline send an extended query to an ongoing pipeline\n');
328
+ w(' \\startpipeline enter pipeline mode\n');
329
+ w(' \\syncpipeline add a synchronisation point to an ongoing pipeline\n');
330
+ emitHelp(out, buf.join(''), pager);
331
+ };
332
+ /**
333
+ * `\?` with a topic argument. Routes to the appropriate help renderer:
334
+ * - `commands` → `slashUsage` (backslash commands)
335
+ * - `options` → `usage` (CLI options)
336
+ * - `variables` → `helpVariables`
337
+ */
338
+ export const slashUsageHelp = (out, topic, opts) => {
339
+ switch (topic) {
340
+ case 'commands':
341
+ slashUsage(out, false, opts);
342
+ return;
343
+ case 'options':
344
+ usage(out, opts);
345
+ return;
346
+ case 'variables':
347
+ helpVariables(out, opts);
348
+ return;
349
+ }
350
+ };
351
+ /**
352
+ * `\? variables` output — list of specially treated psql variables, display
353
+ * settings, and environment variables.
354
+ */
355
+ export const helpVariables = (out, opts) => {
356
+ const o = resolve(opts);
357
+ const buf = [];
358
+ const w = (s) => {
359
+ buf.push(s);
360
+ };
361
+ w('List of specially treated variables\n\n');
362
+ w('psql variables:\n');
363
+ w('Usage:\n');
364
+ w(` ${o.progname} --set=NAME=VALUE\n or \\set NAME VALUE inside psql\n\n`);
365
+ w(' AUTOCOMMIT\n' +
366
+ ' if set, successful SQL commands are automatically committed\n');
367
+ w(' COMP_KEYWORD_CASE\n' +
368
+ ' determines the case used to complete SQL key words\n' +
369
+ ' [lower, upper, preserve-lower, preserve-upper]\n');
370
+ w(' DBNAME\n the currently connected database name\n');
371
+ w(' ECHO\n' +
372
+ ' controls what input is written to standard output\n' +
373
+ ' [all, errors, none, queries]\n');
374
+ w(' ECHO_HIDDEN\n' +
375
+ ' if set, display internal queries executed by backslash commands;\n' +
376
+ ' if set to "noexec", just show them without execution\n');
377
+ w(' ENCODING\n current client character set encoding\n');
378
+ w(' ERROR\n "true" if last query failed, else "false"\n');
379
+ w(' FETCH_COUNT\n' +
380
+ ' the number of result rows to fetch and display at a time (0 = unlimited)\n');
381
+ w(' HIDE_TABLEAM\n if set, table access methods are not displayed\n');
382
+ w(' HIDE_TOAST_COMPRESSION\n' +
383
+ ' if set, compression methods are not displayed\n');
384
+ w(' HISTCONTROL\n' +
385
+ ' controls command history [ignorespace, ignoredups, ignoreboth]\n');
386
+ w(' HISTFILE\n file name used to store the command history\n');
387
+ w(' HISTSIZE\n' +
388
+ ' maximum number of commands to store in the command history\n');
389
+ w(' HOST\n the currently connected database server host\n');
390
+ w(' IGNOREEOF\n' +
391
+ ' number of EOFs needed to terminate an interactive session\n');
392
+ w(' LASTOID\n value of the last affected OID\n');
393
+ w(' LAST_ERROR_MESSAGE\n' +
394
+ ' LAST_ERROR_SQLSTATE\n' +
395
+ ' message and SQLSTATE of last error, or empty string and "00000" if none\n');
396
+ w(' ON_ERROR_ROLLBACK\n' +
397
+ " if set, an error doesn't stop a transaction (uses implicit savepoints)\n");
398
+ w(' ON_ERROR_STOP\n stop batch execution after error\n');
399
+ w(' PORT\n server port of the current connection\n');
400
+ w(' PROMPT1\n specifies the standard psql prompt\n');
401
+ w(' PROMPT2\n' +
402
+ ' specifies the prompt used when a statement continues from a previous line\n');
403
+ w(' PROMPT3\n specifies the prompt used during COPY ... FROM STDIN\n');
404
+ w(' QUIET\n run quietly (same as -q option)\n');
405
+ w(' ROW_COUNT\n' +
406
+ ' number of rows returned or affected by last query, or 0\n');
407
+ w(' SERVER_VERSION_NAME\n' +
408
+ ' SERVER_VERSION_NUM\n' +
409
+ " server's version (in short string or numeric format)\n");
410
+ w(' SHELL_ERROR\n' +
411
+ ' "true" if the last shell command failed, "false" if it succeeded\n');
412
+ w(' SHELL_EXIT_CODE\n exit status of the last shell command\n');
413
+ w(' SHOW_ALL_RESULTS\n' +
414
+ ' show all results of a combined query (\\;) instead of only the last\n');
415
+ w(' SHOW_CONTEXT\n' +
416
+ ' controls display of message context fields [never, errors, always]\n');
417
+ w(' SINGLELINE\n' +
418
+ ' if set, end of line terminates SQL commands (same as -S option)\n');
419
+ w(' SINGLESTEP\n single-step mode (same as -s option)\n');
420
+ w(' SQLSTATE\n SQLSTATE of last query, or "00000" if no error\n');
421
+ w(' USER\n the currently connected database user\n');
422
+ w(' VERBOSITY\n' +
423
+ ' controls verbosity of error reports [default, verbose, terse, sqlstate]\n');
424
+ w(' VERSION\n' +
425
+ ' VERSION_NAME\n' +
426
+ ' VERSION_NUM\n' +
427
+ " psql's version (in verbose string, short string, or numeric format)\n");
428
+ w(' WATCH_INTERVAL\n' +
429
+ ` number of seconds \\watch waits between executions (default ${o.defaultWatchInterval})\n`);
430
+ w('\nDisplay settings:\n');
431
+ w('Usage:\n');
432
+ w(` ${o.progname} --pset=NAME[=VALUE]\n or \\pset NAME [VALUE] inside psql\n\n`);
433
+ w(' border\n border style (number)\n');
434
+ w(' columns\n target width for the wrapped format\n');
435
+ w(' csv_fieldsep\n' +
436
+ ` field separator for CSV output format (default "${o.defaultCsvFieldSep}")\n`);
437
+ w(' display_false\n' +
438
+ " set the string to be printed in place of a boolean 'false'\n");
439
+ w(' display_true\n' +
440
+ " set the string to be printed in place of a boolean 'true'\n");
441
+ w(' expanded (or x)\n expanded output [on, off, auto]\n');
442
+ w(' fieldsep\n' +
443
+ ` field separator for unaligned output (default "${o.defaultFieldSep}")\n`);
444
+ w(' fieldsep_zero\n' +
445
+ ' set field separator for unaligned output to a zero byte\n');
446
+ w(' footer\n' +
447
+ ' enable or disable display of the table footer [on, off]\n');
448
+ w(' format\n' +
449
+ ' set output format [unaligned, aligned, wrapped, html, asciidoc, ...]\n');
450
+ w(' linestyle\n' +
451
+ ' set the border line drawing style [ascii, old-ascii, unicode]\n');
452
+ w(' null\n set the string to be printed in place of a null value\n');
453
+ w(' numericlocale\n' +
454
+ ' enable display of a locale-specific character to separate groups of digits\n');
455
+ w(' pager\n' +
456
+ ' control when an external pager is used [yes, no, always]\n');
457
+ w(' recordsep\n record (line) separator for unaligned output\n');
458
+ w(' recordsep_zero\n' +
459
+ ' set record separator for unaligned output to a zero byte\n');
460
+ w(' tableattr (or T)\n' +
461
+ ' specify attributes for table tag in html format, or proportional\n' +
462
+ ' column widths for left-aligned data types in latex-longtable format\n');
463
+ w(' title\n set the table title for subsequently printed tables\n');
464
+ w(' tuples_only\n if set, only actual table data is shown\n');
465
+ w(' unicode_border_linestyle\n' +
466
+ ' unicode_column_linestyle\n' +
467
+ ' unicode_header_linestyle\n' +
468
+ ' set the style of Unicode line drawing [single, double]\n');
469
+ w(' xheader_width\n' +
470
+ ' set the maximum width of the header for expanded output\n' +
471
+ ' [full, column, page, integer value]\n');
472
+ w('\nEnvironment variables:\n');
473
+ w('Usage:\n');
474
+ if (!o.win32) {
475
+ w(` NAME=VALUE [NAME=VALUE] ${o.progname} ...\n or \\setenv NAME [VALUE] inside psql\n\n`);
476
+ }
477
+ else {
478
+ w(` set NAME=VALUE\n ${o.progname} ...\n or \\setenv NAME [VALUE] inside psql\n\n`);
479
+ }
480
+ w(' COLUMNS\n number of columns for wrapped format\n');
481
+ w(' PGAPPNAME\n same as the application_name connection parameter\n');
482
+ w(' PGDATABASE\n same as the dbname connection parameter\n');
483
+ w(' PGHOST\n same as the host connection parameter\n');
484
+ w(' PGPASSFILE\n password file name\n');
485
+ w(' PGPASSWORD\n connection password (not recommended)\n');
486
+ w(' PGPORT\n same as the port connection parameter\n');
487
+ w(' PGUSER\n same as the user connection parameter\n');
488
+ w(' PSQL_EDITOR, EDITOR, VISUAL\n' +
489
+ ' editor used by the \\e, \\ef, and \\ev commands\n');
490
+ w(' PSQL_EDITOR_LINENUMBER_ARG\n' +
491
+ ' how to specify a line number when invoking the editor\n');
492
+ w(' PSQL_HISTORY\n' +
493
+ ' alternative location for the command history file\n');
494
+ w(' PSQL_PAGER, PAGER\n name of external pager program\n');
495
+ if (!o.win32) {
496
+ w(' PSQL_WATCH_PAGER\n' +
497
+ ' name of external pager program used for \\watch\n');
498
+ }
499
+ w(" PSQLRC\n alternative location for the user's .psqlrc file\n");
500
+ w(' SHELL\n shell used by the \\! command\n');
501
+ w(' TMPDIR\n directory for temporary files\n');
502
+ out.write(buf.join(''));
503
+ };
504
+ /**
505
+ * Render the "Available help:" overview — every command name in the table,
506
+ * laid out in fixed-width columns that fit `screenWidth`. Mirrors upstream
507
+ * `print_topic_list` in `help.c`: 4-column default falling back to fewer
508
+ * columns on narrow terminals. Column width is `max(cmd.length) + 2` so the
509
+ * tallest CREATE * entries line up cleanly.
510
+ */
511
+ const writeCommandList = (out, screenWidth) => {
512
+ out.write('Available help:\n');
513
+ const names = SQL_HELP.map((e) => e.cmd);
514
+ const maxLen = names.reduce((m, n) => Math.max(m, n.length), 0);
515
+ const colW = maxLen + 2;
516
+ // 2-space left margin per upstream; ensure at least one column fits.
517
+ const usable = Math.max(colW, screenWidth - 2);
518
+ const cols = Math.max(1, Math.floor(usable / colW));
519
+ const rows = Math.ceil(names.length / cols);
520
+ for (let r = 0; r < rows; r++) {
521
+ let line = ' ';
522
+ for (let c = 0; c < cols; c++) {
523
+ const i = c * rows + r;
524
+ if (i >= names.length)
525
+ break;
526
+ const name = names[i];
527
+ // Last cell on the row: no trailing padding.
528
+ const isLast = c === cols - 1 || (c + 1) * rows + r >= names.length;
529
+ line += isLast ? name : name.padEnd(colW, ' ');
530
+ }
531
+ out.write(line.replace(/\s+$/u, '') + '\n');
532
+ }
533
+ };
534
+ /** Render a single matched entry; pure formatter, exported for tests. */
535
+ const writeEntry = (out, entry) => {
536
+ out.write(formatEntry(entry));
537
+ };
538
+ /**
539
+ * `\h` SQL command help.
540
+ *
541
+ * Behaviour matches upstream psql:
542
+ * - No topic → list every command name in fixed-width columns.
543
+ * - Unknown topic → "No help available for ..." hint.
544
+ * - One or more prefix matches → render the full synopsis of each match
545
+ * (blank-line separated), exactly as upstream does.
546
+ *
547
+ * Lookups are case-insensitive and prefix-matched per token. "create t"
548
+ * matches CREATE TABLE / CREATE TRIGGER / CREATE TYPE.
549
+ *
550
+ * @param out output stream
551
+ * @param topic SQL command name (e.g. "SELECT"), or null/empty for the
552
+ * "available help" overview
553
+ * @param screenWidth column count, used to lay out the overview list. Line
554
+ * wrapping of the synopsis itself is a follow-up.
555
+ */
556
+ export const helpSQL = (out, topic, screenWidth) => {
557
+ if (topic === null || topic.length === 0 || topic.trim().length === 0) {
558
+ writeCommandList(out, screenWidth);
559
+ return;
560
+ }
561
+ const matches = findMatches(topic);
562
+ if (matches.length === 0) {
563
+ out.write(`No help available for "${topic}".\n` +
564
+ 'Try \\h with no arguments to see available help.\n');
565
+ return;
566
+ }
567
+ // psql has no "several matches" name listing — it prints the full help
568
+ // block for every command whose name prefix-matches the topic, whether one
569
+ // or many. Blocks are separated by a blank line, mirroring
570
+ // upstream's trailing newline after each entry's `URL:` line.
571
+ matches.forEach((m, idx) => {
572
+ if (idx > 0)
573
+ out.write('\n');
574
+ writeEntry(out, m);
575
+ });
576
+ };