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,766 @@
1
+ /**
2
+ * `\sf [+] FUNCNAME` / `\sv [+] VIEWNAME` show-source commands and their
3
+ * `\ef` / `\ev` edit-form siblings, ported from upstream `command.c`'s
4
+ * `exec_command_sf_sv` and `exec_command_ef_ev`.
5
+ *
6
+ * Behaviour matches upstream byte-for-byte for the show forms:
7
+ *
8
+ * 1. Lookup the object's OID — function via `regproc` (or `regprocedure`
9
+ * when the name carries an argument list `(int)`), view via `regclass`.
10
+ * 2. Fetch the definition — `pg_get_functiondef(oid)` for functions; for
11
+ * views we re-assemble the `CREATE OR REPLACE VIEW … AS …` head (with
12
+ * schema-qualified name, reloptions, and optional `WITH CHECK OPTION`)
13
+ * around the body returned by `pg_get_viewdef(oid, true)`.
14
+ * 3. Stream the rendered text to `stdout`, optionally prefixed by line
15
+ * numbers when the user passed `+` (e.g. `\sf+ foo`).
16
+ *
17
+ * Line-number formatting (mirrors upstream `print_with_linenumbers`):
18
+ *
19
+ * - For functions: lines before the body marker (`AS `, `BEGIN `, or
20
+ * `RETURN `) are unnumbered and rendered as ` <line>\n` (8 spaces
21
+ * of padding). Body lines render as `<lineno> <line>\n` where the
22
+ * numeric field is left-justified in a 7-character slot, with one
23
+ * literal space separator. The first body line becomes line 1.
24
+ * - For views: every line is a "body" line — `lineno` starts at 1 and
25
+ * increments for every output line, no header padding.
26
+ *
27
+ * Edit forms (`\ef` / `\ev`):
28
+ * We do not implement editor invocation — that needs TTY interaction and
29
+ * `$EDITOR` semantics outside the scope of this embedded psql. When the
30
+ * user supplies a name we route through the same fetch+print path as the
31
+ * show forms (`\ef foo` ≡ `\sf foo`); without a name we error with a hint
32
+ * pointing back at `\sf` / `\sv`.
33
+ *
34
+ * Argument parsing matches upstream's `OT_WHOLE_LINE`: we slurp the rest of
35
+ * the line and trim, so `\sf myschema.foo ` round-trips cleanly without
36
+ * splitting on the dot or whitespace inside parens.
37
+ */
38
+ import { writeErr, writeOut } from "./shared.js";
39
+ // ---------------------------------------------------------------------------
40
+ // Helpers
41
+ // ---------------------------------------------------------------------------
42
+ /**
43
+ * Emit a `\<cmd>: <message>` error to stderr, stash the message on
44
+ * `lastErrorResult` so `\errverbose` / the mainloop fallback see it, and
45
+ * return an error result with `errorWritten: true` so the mainloop doesn't
46
+ * double-print.
47
+ */
48
+ const errResult = (ctx, message) => {
49
+ ctx.settings.lastErrorResult = { message };
50
+ writeErr(`\\${ctx.cmdName}: ${message}\n`);
51
+ return { status: "error", errorWritten: true };
52
+ };
53
+ /**
54
+ * Format a server error for stderr the way upstream's
55
+ * `minimal_error_message` does: `<severity>: <primary message>\n`. Falls
56
+ * back to "ERROR:" + Error.message when the error doesn't carry severity /
57
+ * message fields (e.g. a wire-layer rejection).
58
+ */
59
+ const formatServerError = (err) => {
60
+ if (err && typeof err === "object") {
61
+ const e = err;
62
+ const sev = e.severity ?? "ERROR";
63
+ const msg = e.message ??
64
+ (err instanceof Error ? err.message : safeToString(err));
65
+ return `${sev}: ${msg}`;
66
+ }
67
+ if (err instanceof Error)
68
+ return `ERROR: ${err.message}`;
69
+ return `ERROR: ${safeToString(err)}`;
70
+ };
71
+ /**
72
+ * Coerce an unknown value to a string defensively. Plain non-`Error`
73
+ * objects would render as `[object Object]` via the default `String()`
74
+ * path; we sidestep that by JSON-encoding when possible (falls back to
75
+ * the typeof when JSON throws — e.g. circular structures).
76
+ */
77
+ const safeToString = (v) => {
78
+ if (v === null)
79
+ return "null";
80
+ if (v === undefined)
81
+ return "undefined";
82
+ if (typeof v === "string")
83
+ return v;
84
+ if (typeof v === "number" ||
85
+ typeof v === "boolean" ||
86
+ typeof v === "bigint") {
87
+ return String(v);
88
+ }
89
+ try {
90
+ return JSON.stringify(v) ?? typeof v;
91
+ }
92
+ catch {
93
+ return typeof v;
94
+ }
95
+ };
96
+ /**
97
+ * Print a server-side query failure the way upstream does — `<sev>: <msg>`
98
+ * directly on stderr, without the `\<cmd>: ` prefix that local-only errors
99
+ * use. Also stashes the message on `lastErrorResult` so `\errverbose`
100
+ * survives.
101
+ */
102
+ const queryErrResult = (ctx, err) => {
103
+ const line = formatServerError(err);
104
+ ctx.settings.lastErrorResult = {
105
+ message: err &&
106
+ typeof err === "object" &&
107
+ err.message
108
+ ? err.message
109
+ : err instanceof Error
110
+ ? err.message
111
+ : safeToString(err),
112
+ };
113
+ writeErr(`${line}\n`);
114
+ return { status: "error", errorWritten: true };
115
+ };
116
+ const conn = (ctx) => ctx.settings.db;
117
+ const noConn = (ctx) => errResult(ctx, "no connection to the server");
118
+ /**
119
+ * Read the object descriptor as a whole-line argument with surrounding
120
+ * whitespace AND trailing semicolons stripped. Returns `null` when no
121
+ * name was supplied (after the strip — i.e. `\sf ` or `\sf ;;` is
122
+ * treated as empty).
123
+ *
124
+ * Upstream `psql_scan_slash_option(scan_state, OT_WHOLE_LINE, …)` keeps
125
+ * the `;` in the returned string, but `exec_command_sf_sv` (and its `ef`/
126
+ * `ev` siblings) trim trailing whitespace + `;` before passing the
127
+ * descriptor to `lookup_object_oid`. Without this, `\sf ts_debug(text);`
128
+ * sends `'ts_debug(text);'::regprocedure` to the server, which the
129
+ * regprocedure input parser rejects with "expected a right parenthesis".
130
+ */
131
+ const readObjDesc = (ctx) => {
132
+ const raw = ctx.restOfLine();
133
+ // Strip trailing whitespace and `;` (in any order, any count) so
134
+ // `\sf foo(arg) ;; ` round-trips like vanilla psql.
135
+ const trimmed = raw.replace(/[\s;]+$/, "").trimStart();
136
+ return trimmed.length === 0 ? null : trimmed;
137
+ };
138
+ /**
139
+ * Decode whether the command name ends in `+` (request line numbers). The
140
+ * caller knows the base name (`sf`, `sv`, `ef`, `ev`); any extra letters
141
+ * are looked at for a literal `+`.
142
+ */
143
+ const decodeShowSuffix = (cmdName, base) => {
144
+ const tail = cmdName.slice(base.length);
145
+ return { plus: tail.includes("+") };
146
+ };
147
+ /**
148
+ * Look up a function OID from `desc`. Mirrors upstream's
149
+ * `lookup_object_oid(EditableFunction, ...)` exactly:
150
+ *
151
+ * - If `desc` contains `(`, cast through `regprocedure` (which resolves
152
+ * by full argument signature, e.g. `foo(int)`).
153
+ * - Otherwise cast through `regproc` (which matches by bare name and
154
+ * errors on overloaded ambiguity).
155
+ *
156
+ * The descriptor is passed as a SQL string literal — we use the server's
157
+ * `escapeLiteral` to mirror libpq's `appendStringLiteralConn`.
158
+ */
159
+ const lookupFunctionOid = async (c, desc) => {
160
+ const cast = desc.includes("(") ? "regprocedure" : "regproc";
161
+ const sql = `SELECT ${c.escapeLiteral(desc)}::pg_catalog.${cast}::pg_catalog.oid`;
162
+ try {
163
+ const rs = await c.query(sql, []);
164
+ if (rs.rows.length !== 1 || rs.rows[0][0] === null) {
165
+ return {
166
+ ok: false,
167
+ err: new Error("object lookup returned no rows"),
168
+ };
169
+ }
170
+ const raw = cellToString(rs.rows[0][0]);
171
+ const oid = Number(raw);
172
+ if (!Number.isFinite(oid)) {
173
+ return {
174
+ ok: false,
175
+ err: new Error(`invalid oid in lookup result: ${raw}`),
176
+ };
177
+ }
178
+ return { ok: true, oid };
179
+ }
180
+ catch (err) {
181
+ return { ok: false, err };
182
+ }
183
+ };
184
+ /**
185
+ * Look up a view OID from `desc` via `regclass`. Matches upstream's
186
+ * `lookup_object_oid(EditableView, ...)`. Note that this does NOT verify
187
+ * the relation is actually a view; the kind check happens in
188
+ * `getViewCreateCmd` where upstream catches it via the relkind column.
189
+ */
190
+ const lookupRelationOid = async (c, desc) => {
191
+ const sql = `SELECT ${c.escapeLiteral(desc)}::pg_catalog.regclass::pg_catalog.oid`;
192
+ try {
193
+ const rs = await c.query(sql, []);
194
+ if (rs.rows.length !== 1 || rs.rows[0][0] === null) {
195
+ return {
196
+ ok: false,
197
+ err: new Error("object lookup returned no rows"),
198
+ };
199
+ }
200
+ const raw = cellToString(rs.rows[0][0]);
201
+ const oid = Number(raw);
202
+ if (!Number.isFinite(oid)) {
203
+ return {
204
+ ok: false,
205
+ err: new Error(`invalid oid in lookup result: ${raw}`),
206
+ };
207
+ }
208
+ return { ok: true, oid };
209
+ }
210
+ catch (err) {
211
+ return { ok: false, err };
212
+ }
213
+ };
214
+ /**
215
+ * Coerce a wire-layer cell to a string. Text-mode results arrive as
216
+ * strings; null is treated as "" so missing-row paths fall through to
217
+ * empty output instead of crashing.
218
+ */
219
+ const cellToString = (v) => {
220
+ if (v === null || v === undefined)
221
+ return "";
222
+ if (typeof v === "string")
223
+ return v;
224
+ if (Buffer.isBuffer(v))
225
+ return v.toString("utf-8");
226
+ if (typeof v === "number" ||
227
+ typeof v === "boolean" ||
228
+ typeof v === "bigint") {
229
+ return String(v);
230
+ }
231
+ // Non-primitive fallback: encode JSON so we never emit a stray
232
+ // `[object Object]`. The wire layer hands us strings or nulls in
233
+ // practice, so this branch is defensive only.
234
+ try {
235
+ return JSON.stringify(v) ?? "";
236
+ }
237
+ catch {
238
+ return "";
239
+ }
240
+ };
241
+ /**
242
+ * Fetch the CREATE FUNCTION source for `oid` via
243
+ * `pg_catalog.pg_get_functiondef(oid)`. Upstream guarantees the result is
244
+ * newline-terminated; we re-assert that here so the caller can stream
245
+ * straight to stdout (or hand to the line-number formatter).
246
+ */
247
+ const getFunctionCreateCmd = async (c, oid) => {
248
+ const sql = `SELECT pg_catalog.pg_get_functiondef(${oid})`;
249
+ try {
250
+ const rs = await c.query(sql, []);
251
+ if (rs.rows.length !== 1) {
252
+ return {
253
+ ok: false,
254
+ err: new Error("function definition not found"),
255
+ };
256
+ }
257
+ let def = cellToString(rs.rows[0][0]);
258
+ if (def.length > 0 && !def.endsWith("\n"))
259
+ def += "\n";
260
+ return { ok: true, def };
261
+ }
262
+ catch (err) {
263
+ return { ok: false, err };
264
+ }
265
+ };
266
+ /**
267
+ * Quote an SQL identifier when needed. Mirrors libpq's `fmtId`: lowercase
268
+ * ASCII identifiers starting with `[a-z_]` and continuing with
269
+ * `[a-z0-9_$]` may go unquoted; anything else gets double-quoted with
270
+ * embedded double-quotes doubled. Used to schema-qualify view names in
271
+ * the synthesised `CREATE OR REPLACE VIEW …` head.
272
+ */
273
+ const fmtId = (ident) => {
274
+ if (/^[a-z_][a-z0-9_$]*$/.test(ident) && !RESERVED_WORDS.has(ident)) {
275
+ return ident;
276
+ }
277
+ return `"${ident.replace(/"/g, '""')}"`;
278
+ };
279
+ /**
280
+ * Minimal reserved-word set used by `fmtId`. Upstream's `fmtId` is much
281
+ * more conservative — any keyword needs quoting regardless of category.
282
+ * For our use case we only quote the keywords that show up as actual
283
+ * relation names; that's vanishingly rare in practice (CREATE VIEW
284
+ * "select" AS … is legal but no one does it). Keeping the set small
285
+ * avoids a large keyword table; the worst case is an un-needed
286
+ * double-quote pair, which is still valid SQL.
287
+ */
288
+ const RESERVED_WORDS = new Set([
289
+ "all",
290
+ "analyse",
291
+ "analyze",
292
+ "and",
293
+ "any",
294
+ "array",
295
+ "as",
296
+ "asc",
297
+ "asymmetric",
298
+ "both",
299
+ "case",
300
+ "cast",
301
+ "check",
302
+ "collate",
303
+ "column",
304
+ "constraint",
305
+ "create",
306
+ "current_catalog",
307
+ "current_date",
308
+ "current_role",
309
+ "current_time",
310
+ "current_timestamp",
311
+ "current_user",
312
+ "default",
313
+ "deferrable",
314
+ "desc",
315
+ "distinct",
316
+ "do",
317
+ "else",
318
+ "end",
319
+ "except",
320
+ "false",
321
+ "fetch",
322
+ "for",
323
+ "foreign",
324
+ "from",
325
+ "grant",
326
+ "group",
327
+ "having",
328
+ "in",
329
+ "initially",
330
+ "intersect",
331
+ "into",
332
+ "lateral",
333
+ "leading",
334
+ "limit",
335
+ "localtime",
336
+ "localtimestamp",
337
+ "not",
338
+ "null",
339
+ "offset",
340
+ "on",
341
+ "only",
342
+ "or",
343
+ "order",
344
+ "placing",
345
+ "primary",
346
+ "references",
347
+ "returning",
348
+ "select",
349
+ "session_user",
350
+ "some",
351
+ "symmetric",
352
+ "table",
353
+ "then",
354
+ "to",
355
+ "trailing",
356
+ "true",
357
+ "union",
358
+ "unique",
359
+ "user",
360
+ "using",
361
+ "variadic",
362
+ "when",
363
+ "where",
364
+ "window",
365
+ "with",
366
+ ]);
367
+ /**
368
+ * Re-build a `CREATE OR REPLACE VIEW <schema>.<name>[ WITH (opts)] AS
369
+ * <body>[\n WITH <checkoption> CHECK OPTION]\n` definition the same way
370
+ * upstream's `get_create_object_cmd(EditableView)` does. Returns either
371
+ * the assembled text or a synthetic error when the relation isn't
372
+ * actually a view.
373
+ */
374
+ const getViewCreateCmd = async (c, oid) => {
375
+ const ver = c.serverVersion >= 90400 ? "modern" : "legacy";
376
+ const sql = ver === "modern"
377
+ ? `SELECT nspname, relname, relkind, ` +
378
+ `pg_catalog.pg_get_viewdef(c.oid, true), ` +
379
+ `pg_catalog.array_remove(pg_catalog.array_remove(c.reloptions,'check_option=local'),'check_option=cascaded') AS reloptions, ` +
380
+ `CASE WHEN 'check_option=local' = ANY (c.reloptions) THEN 'LOCAL'::text ` +
381
+ `WHEN 'check_option=cascaded' = ANY (c.reloptions) THEN 'CASCADED'::text ELSE NULL END AS checkoption ` +
382
+ `FROM pg_catalog.pg_class c ` +
383
+ `LEFT JOIN pg_catalog.pg_namespace n ` +
384
+ `ON c.relnamespace = n.oid WHERE c.oid = ${oid}`
385
+ : `SELECT nspname, relname, relkind, ` +
386
+ `pg_catalog.pg_get_viewdef(c.oid, true), ` +
387
+ `c.reloptions AS reloptions, ` +
388
+ `NULL AS checkoption ` +
389
+ `FROM pg_catalog.pg_class c ` +
390
+ `LEFT JOIN pg_catalog.pg_namespace n ` +
391
+ `ON c.relnamespace = n.oid WHERE c.oid = ${oid}`;
392
+ let rs;
393
+ try {
394
+ rs = await c.query(sql, []);
395
+ }
396
+ catch (err) {
397
+ return { ok: false, err };
398
+ }
399
+ if (rs.rows.length !== 1) {
400
+ return { ok: false, err: new Error("view definition not found") };
401
+ }
402
+ const row = rs.rows[0];
403
+ const nspname = cellToString(row[0]);
404
+ const relname = cellToString(row[1]);
405
+ const relkind = cellToString(row[2]);
406
+ const viewdef = cellToString(row[3]);
407
+ const reloptions = row[4]; // may be string ("{a=b,c=d}") or null
408
+ const checkoption = cellToString(row[5]);
409
+ if (relkind !== "v") {
410
+ return {
411
+ ok: false,
412
+ err: new Error(`"${nspname}.${relname}" is not a view`),
413
+ };
414
+ }
415
+ let out = "CREATE OR REPLACE VIEW ";
416
+ out += `${fmtId(nspname)}.${fmtId(relname)}`;
417
+ // reloptions: postgres returns it as a text-mode array literal like
418
+ // `{foo=bar,baz=qux}`; we only need to detect non-empty (different
419
+ // from the literal `{}`) and split entries on `,` outside quotes.
420
+ const reloptStr = reloptions === null ? null : cellToString(reloptions);
421
+ if (reloptStr !== null && reloptStr.length > 2) {
422
+ out += "\n WITH (";
423
+ out += renderReloptions(reloptStr);
424
+ out += ")";
425
+ }
426
+ out += ` AS\n${viewdef}`;
427
+ // Strip trailing semicolon from pg_get_viewdef.
428
+ if (out.endsWith(";")) {
429
+ out = out.slice(0, -1);
430
+ }
431
+ if (checkoption !== "") {
432
+ out += `\n WITH ${checkoption} CHECK OPTION`;
433
+ }
434
+ if (!out.endsWith("\n"))
435
+ out += "\n";
436
+ return { ok: true, def: out };
437
+ };
438
+ /**
439
+ * Render a Postgres text-mode array literal of `key=value` reloption
440
+ * entries (e.g. `{security_barrier=true,security_invoker=false}`) into
441
+ * the comma-separated `key=value, key2=value2` form upstream emits
442
+ * inside the `WITH (…)` clause.
443
+ *
444
+ * Mirrors `appendReloptionsArray`'s output behaviour for the limited
445
+ * surface relevant to views (no per-namespace options, no embedded
446
+ * quotes). For any value that contains characters that would need
447
+ * escaping in SQL — anything other than `[A-Za-z0-9_.\-]` — we render
448
+ * it as a quoted string literal, matching upstream's `appendStringLiteral`
449
+ * fallback.
450
+ */
451
+ const renderReloptions = (literal) => {
452
+ // Strip surrounding `{}`.
453
+ if (!literal.startsWith("{") || !literal.endsWith("}")) {
454
+ return literal;
455
+ }
456
+ const inside = literal.slice(1, -1);
457
+ if (inside.length === 0)
458
+ return "";
459
+ // Postgres array literals quote individual elements with `"…"` when
460
+ // they contain commas or special chars. For reloptions on a view the
461
+ // values are typically bare `key=value` strings, but we still need to
462
+ // tolerate the quoted form.
463
+ const entries = splitArrayElems(inside);
464
+ const out = [];
465
+ for (let entry of entries) {
466
+ // unquote double-quoted entries
467
+ if (entry.startsWith('"') && entry.endsWith('"')) {
468
+ entry = entry
469
+ .slice(1, -1)
470
+ .replace(/\\"/g, '"')
471
+ .replace(/\\\\/g, "\\");
472
+ }
473
+ const eq = entry.indexOf("=");
474
+ if (eq < 0) {
475
+ out.push(entry);
476
+ continue;
477
+ }
478
+ const key = entry.slice(0, eq);
479
+ const value = entry.slice(eq + 1);
480
+ if (/^[A-Za-z0-9_.-]+$/.test(value)) {
481
+ out.push(`${key}=${value}`);
482
+ }
483
+ else {
484
+ // Quote the value as a SQL string literal.
485
+ out.push(`${key}='${value.replace(/'/g, "''")}'`);
486
+ }
487
+ }
488
+ return out.join(", ");
489
+ };
490
+ /** Split a Postgres text-mode array's inner content on top-level commas. */
491
+ const splitArrayElems = (s) => {
492
+ const out = [];
493
+ let i = 0;
494
+ let cur = "";
495
+ let inQuote = false;
496
+ while (i < s.length) {
497
+ const ch = s[i];
498
+ if (ch === "\\" && i + 1 < s.length) {
499
+ cur += s[i] + s[i + 1];
500
+ i += 2;
501
+ continue;
502
+ }
503
+ if (ch === '"') {
504
+ inQuote = !inQuote;
505
+ cur += ch;
506
+ i++;
507
+ continue;
508
+ }
509
+ if (ch === "," && !inQuote) {
510
+ out.push(cur);
511
+ cur = "";
512
+ i++;
513
+ continue;
514
+ }
515
+ cur += ch;
516
+ i++;
517
+ }
518
+ if (cur.length > 0 || s.endsWith(","))
519
+ out.push(cur);
520
+ return out;
521
+ };
522
+ /**
523
+ * Print `buf` with line numbers in the upstream format:
524
+ *
525
+ * - For functions (`isFunc=true`): scan for the first line whose first
526
+ * three / six / seven bytes are `AS `, `BEGIN `, or `RETURN ` and
527
+ * treat that as the start of the body. Header lines (before the
528
+ * marker) render as ` <line>\n`; body lines render as
529
+ * `<lineno><6 spaces> <line>\n` (`%-7d %s\n`), with `lineno` starting
530
+ * at 1 on the marker line.
531
+ * - For views (`isFunc=false`): everything is body; `lineno` starts at
532
+ * 1 and increments per output line.
533
+ */
534
+ const writeWithLineNumbers = (buf, isFunc, out) => {
535
+ let inHeader = isFunc;
536
+ let lineno = 0;
537
+ let i = 0;
538
+ while (i < buf.length) {
539
+ // Find end-of-line.
540
+ const eol = buf.indexOf("\n", i);
541
+ const line = eol === -1 ? buf.slice(i) : buf.slice(i, eol);
542
+ if (inHeader &&
543
+ (line.startsWith("AS ") ||
544
+ line.startsWith("BEGIN ") ||
545
+ line.startsWith("RETURN "))) {
546
+ inHeader = false;
547
+ }
548
+ if (!inHeader)
549
+ lineno++;
550
+ if (inHeader) {
551
+ out(` ${line}\n`);
552
+ }
553
+ else {
554
+ // %-7d → left-justified, padded to 7. Then literal space, then line.
555
+ const numStr = String(lineno);
556
+ const pad = numStr.length >= 7 ? "" : " ".repeat(7 - numStr.length);
557
+ out(`${numStr}${pad} ${line}\n`);
558
+ }
559
+ if (eol === -1)
560
+ break;
561
+ i = eol + 1;
562
+ }
563
+ };
564
+ /** Stream the definition (with or without line numbers) to stdout. */
565
+ const emitDefinition = (def, plus, isFunc) => {
566
+ if (plus) {
567
+ writeWithLineNumbers(def, isFunc, writeOut);
568
+ }
569
+ else {
570
+ writeOut(def);
571
+ }
572
+ };
573
+ // ---------------------------------------------------------------------------
574
+ // Shared core: \sf / \ef (function) and \sv / \ev (view).
575
+ // ---------------------------------------------------------------------------
576
+ /**
577
+ * Resolve a function/view definition and dump it to stdout. Used by
578
+ * both the show forms (`\sf` / `\sv`) and the edit forms (`\ef` / `\ev`)
579
+ * when the user supplies a name.
580
+ */
581
+ const runShowFunction = async (ctx, cmdName, base) => {
582
+ const c = conn(ctx);
583
+ if (!c)
584
+ return noConn(ctx);
585
+ const { plus } = decodeShowSuffix(cmdName, base);
586
+ const desc = readObjDesc(ctx);
587
+ if (desc === null) {
588
+ return errResult(ctx, "function name is required");
589
+ }
590
+ const oidLookup = await lookupFunctionOid(c, desc);
591
+ if (!oidLookup.ok)
592
+ return queryErrResult(ctx, oidLookup.err);
593
+ const defLookup = await getFunctionCreateCmd(c, oidLookup.oid);
594
+ if (!defLookup.ok)
595
+ return queryErrResult(ctx, defLookup.err);
596
+ emitDefinition(defLookup.def, plus, /*isFunc=*/ true);
597
+ return { status: "ok" };
598
+ };
599
+ const runShowView = async (ctx, cmdName, base) => {
600
+ const c = conn(ctx);
601
+ if (!c)
602
+ return noConn(ctx);
603
+ const { plus } = decodeShowSuffix(cmdName, base);
604
+ const desc = readObjDesc(ctx);
605
+ if (desc === null) {
606
+ return errResult(ctx, "view name is required");
607
+ }
608
+ const oidLookup = await lookupRelationOid(c, desc);
609
+ if (!oidLookup.ok)
610
+ return queryErrResult(ctx, oidLookup.err);
611
+ const defLookup = await getViewCreateCmd(c, oidLookup.oid);
612
+ if (!defLookup.ok)
613
+ return queryErrResult(ctx, defLookup.err);
614
+ emitDefinition(defLookup.def, plus, /*isFunc=*/ false);
615
+ return { status: "ok" };
616
+ };
617
+ // ---------------------------------------------------------------------------
618
+ // BackslashCmdSpec exports
619
+ // ---------------------------------------------------------------------------
620
+ /** `\sf [+] FUNCNAME` — show function source. */
621
+ export const cmdShowFunction = {
622
+ name: "sf",
623
+ argMode: "whole-line",
624
+ helpKey: "sf",
625
+ run: (ctx) => runShowFunction(ctx, ctx.cmdName, "sf"),
626
+ };
627
+ /** `\sf+ FUNCNAME` — show function source with line numbers. */
628
+ export const cmdShowFunctionPlus = {
629
+ name: "sf+",
630
+ argMode: "whole-line",
631
+ helpKey: "sf",
632
+ run: (ctx) => runShowFunction(ctx, ctx.cmdName, "sf"),
633
+ };
634
+ /** `\sv [+] VIEWNAME` — show view source. */
635
+ export const cmdShowView = {
636
+ name: "sv",
637
+ argMode: "whole-line",
638
+ helpKey: "sv",
639
+ run: (ctx) => runShowView(ctx, ctx.cmdName, "sv"),
640
+ };
641
+ /** `\sv+ VIEWNAME` — show view source with line numbers. */
642
+ export const cmdShowViewPlus = {
643
+ name: "sv+",
644
+ argMode: "whole-line",
645
+ helpKey: "sv",
646
+ run: (ctx) => runShowView(ctx, ctx.cmdName, "sv"),
647
+ };
648
+ /**
649
+ * `\ef [+] [FUNCNAME [LINE]]` — upstream opens `$EDITOR` on the function's
650
+ * source. We don't implement editor invocation; when a name is supplied we
651
+ * route through the same fetch+print path as `\sf` (with a stripped line
652
+ * number — the trailing LINE argument is ignored). Without a name we error
653
+ * with a hint pointing at `\sf`.
654
+ */
655
+ export const cmdEditFunction = {
656
+ name: "ef",
657
+ argMode: "whole-line",
658
+ helpKey: "ef",
659
+ async run(ctx) {
660
+ const c = conn(ctx);
661
+ if (!c)
662
+ return noConn(ctx);
663
+ const { plus } = decodeShowSuffix(ctx.cmdName, "ef");
664
+ const desc = readObjDesc(ctx);
665
+ if (desc === null) {
666
+ return errResult(ctx, "editing not supported in embedded psql; supply a name to display the source");
667
+ }
668
+ // Strip a possible trailing LINE number (upstream behaviour for \ef
669
+ // FUNCNAME LINE — the editor opens at that line; we just discard it).
670
+ const objDesc = stripTrailingLine(desc);
671
+ const oidLookup = await lookupFunctionOid(c, objDesc);
672
+ if (!oidLookup.ok)
673
+ return queryErrResult(ctx, oidLookup.err);
674
+ const defLookup = await getFunctionCreateCmd(c, oidLookup.oid);
675
+ if (!defLookup.ok)
676
+ return queryErrResult(ctx, defLookup.err);
677
+ emitDefinition(defLookup.def, plus, /*isFunc=*/ true);
678
+ return { status: "ok" };
679
+ },
680
+ };
681
+ /**
682
+ * `\ev [+] [VIEWNAME [LINE]]` — same contract as `\ef` but for views.
683
+ */
684
+ export const cmdEditView = {
685
+ name: "ev",
686
+ argMode: "whole-line",
687
+ helpKey: "ev",
688
+ async run(ctx) {
689
+ const c = conn(ctx);
690
+ if (!c)
691
+ return noConn(ctx);
692
+ const { plus } = decodeShowSuffix(ctx.cmdName, "ev");
693
+ const desc = readObjDesc(ctx);
694
+ if (desc === null) {
695
+ return errResult(ctx, "editing not supported in embedded psql; supply a name to display the source");
696
+ }
697
+ const objDesc = stripTrailingLine(desc);
698
+ const oidLookup = await lookupRelationOid(c, objDesc);
699
+ if (!oidLookup.ok)
700
+ return queryErrResult(ctx, oidLookup.err);
701
+ const defLookup = await getViewCreateCmd(c, oidLookup.oid);
702
+ if (!defLookup.ok)
703
+ return queryErrResult(ctx, defLookup.err);
704
+ emitDefinition(defLookup.def, plus, /*isFunc=*/ false);
705
+ return { status: "ok" };
706
+ },
707
+ };
708
+ /**
709
+ * Aliases so that `\ef+` and `\ev+` resolve to the corresponding command;
710
+ * we register the plus variants explicitly because the registry is keyed
711
+ * by full name.
712
+ */
713
+ export const cmdEditFunctionPlus = {
714
+ ...cmdEditFunction,
715
+ name: "ef+",
716
+ };
717
+ export const cmdEditViewPlus = {
718
+ ...cmdEditView,
719
+ name: "ev+",
720
+ };
721
+ /**
722
+ * Strip a trailing LINE number from an object descriptor, matching
723
+ * upstream's `strip_lineno_from_objdesc`. We rebuild the simpler subset
724
+ * here because the slash-arg scanner already handed us a single trimmed
725
+ * whole-line string: if it ends with `<digits>` separated from the
726
+ * preceding name by whitespace or `)`, strip the digits.
727
+ *
728
+ * Returns the descriptor with any trailing line number removed. Invalid
729
+ * line numbers (zero) are not detected here — we treat them the same as
730
+ * "no line number" because the LINE arg is meaningless to our
731
+ * show-only impl.
732
+ */
733
+ const stripTrailingLine = (desc) => {
734
+ let i = desc.length - 1;
735
+ while (i > 0 && /\s/.test(desc[i]))
736
+ i--;
737
+ if (i <= 0 || !/[0-9]/.test(desc[i]))
738
+ return desc;
739
+ while (i > 0 && /[0-9]/.test(desc[i]))
740
+ i--;
741
+ // The char before the digit run must be whitespace or `)` and not the
742
+ // very first char.
743
+ if (i <= 0)
744
+ return desc;
745
+ const sep = desc[i];
746
+ if (!(/\s/.test(sep) || sep === ")"))
747
+ return desc;
748
+ return desc.slice(0, i + 1).trimEnd();
749
+ };
750
+ // ---------------------------------------------------------------------------
751
+ // Registration
752
+ // ---------------------------------------------------------------------------
753
+ /**
754
+ * Register `\sf`, `\sf+`, `\sv`, `\sv+`, `\ef`, `\ef+`, `\ev`, `\ev+` on
755
+ * the supplied registry. Wired into `defaultRegistry()` from `dispatch.ts`.
756
+ */
757
+ export const registerShowCommands = (registry) => {
758
+ registry.register(cmdShowFunction);
759
+ registry.register(cmdShowFunctionPlus);
760
+ registry.register(cmdShowView);
761
+ registry.register(cmdShowViewPlus);
762
+ registry.register(cmdEditFunction);
763
+ registry.register(cmdEditFunctionPlus);
764
+ registry.register(cmdEditView);
765
+ registry.register(cmdEditViewPlus);
766
+ };