Debian Codegraph @

src/bin/psql/command.c

raw
1 /*
2 * psql - the PostgreSQL interactive terminal
3 *
4 * Copyright (c) 2000-2025, PostgreSQL Global Development Group
5 *
6 * src/bin/psql/command.c
7 */
8 #include "postgres_fe.h"
9
10 #include <ctype.h>
11 #include <time.h>
12 #include <pwd.h>
13 #include <utime.h>
14 #ifndef WIN32
15 #include <sys/stat.h> /* for stat() */
16 #include <sys/time.h> /* for setitimer() */
17 #include <fcntl.h> /* open() flags */
18 #include <unistd.h> /* for geteuid(), getpid(), stat() */
19 #else
20 #include <win32.h>
21 #include <io.h>
22 #include <fcntl.h>
23 #include <direct.h>
24 #include <sys/stat.h> /* for stat() */
25 #endif
26
27 #include "catalog/pg_class_d.h"
28 #include "command.h"
29 #include "common.h"
30 #include "common/logging.h"
31 #include "common/string.h"
32 #include "copy.h"
33 #include "describe.h"
34 #include "fe_utils/cancel.h"
35 #include "fe_utils/print.h"
36 #include "fe_utils/string_utils.h"
37 #include "help.h"
38 #include "input.h"
39 #include "large_obj.h"
40 #include "libpq/pqcomm.h"
41 #include "mainloop.h"
42 #include "pqexpbuffer.h"
43 #include "psqlscanslash.h"
44 #include "settings.h"
45 #include "variables.h"
46
47 /*
48 * Editable database object types.
49 */
50 typedef enum EditableObjectType
51 {
52 EditableFunction,
53 EditableView,
54 } EditableObjectType;
55
56 /* local function declarations */
57 static backslashResult exec_command(const char *cmd,
58 PsqlScanState scan_state,
59 ConditionalStack cstack,
60 PQExpBuffer query_buf,
61 PQExpBuffer previous_buf);
62 static backslashResult exec_command_a(PsqlScanState scan_state, bool active_branch);
63 static backslashResult exec_command_bind(PsqlScanState scan_state, bool active_branch);
64 static backslashResult exec_command_bind_named(PsqlScanState scan_state, bool active_branch,
65 const char *cmd);
66 static backslashResult exec_command_C(PsqlScanState scan_state, bool active_branch);
67 static backslashResult exec_command_connect(PsqlScanState scan_state, bool active_branch);
68 static backslashResult exec_command_cd(PsqlScanState scan_state, bool active_branch,
69 const char *cmd);
70 static backslashResult exec_command_close_prepared(PsqlScanState scan_state,
71 bool active_branch, const char *cmd);
72 static backslashResult exec_command_conninfo(PsqlScanState scan_state, bool active_branch);
73 static backslashResult exec_command_copy(PsqlScanState scan_state, bool active_branch);
74 static backslashResult exec_command_copyright(PsqlScanState scan_state, bool active_branch);
75 static backslashResult exec_command_crosstabview(PsqlScanState scan_state, bool active_branch);
76 static backslashResult exec_command_d(PsqlScanState scan_state, bool active_branch,
77 const char *cmd);
78 static bool exec_command_dfo(PsqlScanState scan_state, const char *cmd,
79 const char *pattern,
80 bool show_verbose, bool show_system);
81 static backslashResult exec_command_edit(PsqlScanState scan_state, bool active_branch,
82 PQExpBuffer query_buf, PQExpBuffer previous_buf);
83 static backslashResult exec_command_ef_ev(PsqlScanState scan_state, bool active_branch,
84 PQExpBuffer query_buf, bool is_func);
85 static backslashResult exec_command_echo(PsqlScanState scan_state, bool active_branch,
86 const char *cmd);
87 static backslashResult exec_command_elif(PsqlScanState scan_state, ConditionalStack cstack,
88 PQExpBuffer query_buf);
89 static backslashResult exec_command_else(PsqlScanState scan_state, ConditionalStack cstack,
90 PQExpBuffer query_buf);
91 static backslashResult exec_command_endif(PsqlScanState scan_state, ConditionalStack cstack,
92 PQExpBuffer query_buf);
93 static backslashResult exec_command_endpipeline(PsqlScanState scan_state, bool active_branch);
94 static backslashResult exec_command_encoding(PsqlScanState scan_state, bool active_branch);
95 static backslashResult exec_command_errverbose(PsqlScanState scan_state, bool active_branch);
96 static backslashResult exec_command_f(PsqlScanState scan_state, bool active_branch);
97 static backslashResult exec_command_flush(PsqlScanState scan_state, bool active_branch);
98 static backslashResult exec_command_flushrequest(PsqlScanState scan_state, bool active_branch);
99 static backslashResult exec_command_g(PsqlScanState scan_state, bool active_branch,
100 const char *cmd);
101 static backslashResult process_command_g_options(char *first_option,
102 PsqlScanState scan_state,
103 bool active_branch,
104 const char *cmd);
105 static backslashResult exec_command_gdesc(PsqlScanState scan_state, bool active_branch);
106 static backslashResult exec_command_getenv(PsqlScanState scan_state, bool active_branch,
107 const char *cmd);
108 static backslashResult exec_command_gexec(PsqlScanState scan_state, bool active_branch);
109 static backslashResult exec_command_getresults(PsqlScanState scan_state, bool active_branch);
110 static backslashResult exec_command_gset(PsqlScanState scan_state, bool active_branch);
111 static backslashResult exec_command_help(PsqlScanState scan_state, bool active_branch);
112 static backslashResult exec_command_html(PsqlScanState scan_state, bool active_branch);
113 static backslashResult exec_command_include(PsqlScanState scan_state, bool active_branch,
114 const char *cmd);
115 static backslashResult exec_command_if(PsqlScanState scan_state, ConditionalStack cstack,
116 PQExpBuffer query_buf);
117 static backslashResult exec_command_list(PsqlScanState scan_state, bool active_branch,
118 const char *cmd);
119 static backslashResult exec_command_lo(PsqlScanState scan_state, bool active_branch,
120 const char *cmd);
121 static backslashResult exec_command_out(PsqlScanState scan_state, bool active_branch);
122 static backslashResult exec_command_print(PsqlScanState scan_state, bool active_branch,
123 PQExpBuffer query_buf, PQExpBuffer previous_buf);
124 static backslashResult exec_command_parse(PsqlScanState scan_state, bool active_branch,
125 const char *cmd);
126 static backslashResult exec_command_password(PsqlScanState scan_state, bool active_branch);
127 static backslashResult exec_command_prompt(PsqlScanState scan_state, bool active_branch,
128 const char *cmd);
129 static backslashResult exec_command_pset(PsqlScanState scan_state, bool active_branch);
130 static backslashResult exec_command_quit(PsqlScanState scan_state, bool active_branch);
131 static backslashResult exec_command_reset(PsqlScanState scan_state, bool active_branch,
132 PQExpBuffer query_buf);
133 static backslashResult exec_command_restrict(PsqlScanState scan_state, bool active_branch,
134 const char *cmd);
135 static backslashResult exec_command_s(PsqlScanState scan_state, bool active_branch);
136 static backslashResult exec_command_sendpipeline(PsqlScanState scan_state, bool active_branch);
137 static backslashResult exec_command_set(PsqlScanState scan_state, bool active_branch);
138 static backslashResult exec_command_setenv(PsqlScanState scan_state, bool active_branch,
139 const char *cmd);
140 static backslashResult exec_command_sf_sv(PsqlScanState scan_state, bool active_branch,
141 const char *cmd, bool is_func);
142 static backslashResult exec_command_startpipeline(PsqlScanState scan_state, bool active_branch);
143 static backslashResult exec_command_syncpipeline(PsqlScanState scan_state, bool active_branch);
144 static backslashResult exec_command_t(PsqlScanState scan_state, bool active_branch);
145 static backslashResult exec_command_T(PsqlScanState scan_state, bool active_branch);
146 static backslashResult exec_command_timing(PsqlScanState scan_state, bool active_branch);
147 static backslashResult exec_command_unrestrict(PsqlScanState scan_state, bool active_branch,
148 const char *cmd);
149 static backslashResult exec_command_unset(PsqlScanState scan_state, bool active_branch,
150 const char *cmd);
151 static backslashResult exec_command_write(PsqlScanState scan_state, bool active_branch,
152 const char *cmd,
153 PQExpBuffer query_buf, PQExpBuffer previous_buf);
154 static backslashResult exec_command_watch(PsqlScanState scan_state, bool active_branch,
155 PQExpBuffer query_buf, PQExpBuffer previous_buf);
156 static backslashResult exec_command_x(PsqlScanState scan_state, bool active_branch);
157 static backslashResult exec_command_z(PsqlScanState scan_state, bool active_branch,
158 const char *cmd);
159 static backslashResult exec_command_shell_escape(PsqlScanState scan_state, bool active_branch);
160 static backslashResult exec_command_slash_command_help(PsqlScanState scan_state, bool active_branch);
161 static char *read_connect_arg(PsqlScanState scan_state);
162 static PQExpBuffer gather_boolean_expression(PsqlScanState scan_state);
163 static bool is_true_boolean_expression(PsqlScanState scan_state, const char *name);
164 static void ignore_boolean_expression(PsqlScanState scan_state);
165 static void ignore_slash_options(PsqlScanState scan_state);
166 static void ignore_slash_filepipe(PsqlScanState scan_state);
167 static void ignore_slash_whole_line(PsqlScanState scan_state);
168 static bool is_branching_command(const char *cmd);
169 static void save_query_text_state(PsqlScanState scan_state, ConditionalStack cstack,
170 PQExpBuffer query_buf);
171 static void discard_query_text(PsqlScanState scan_state, ConditionalStack cstack,
172 PQExpBuffer query_buf);
173 static bool copy_previous_query(PQExpBuffer query_buf, PQExpBuffer previous_buf);
174 static bool do_connect(enum trivalue reuse_previous_specification,
175 char *dbname, char *user, char *host, char *port);
176 static void wait_until_connected(PGconn *conn);
177 static bool do_edit(const char *filename_arg, PQExpBuffer query_buf,
178 int lineno, bool discard_on_quit, bool *edited);
179 static bool do_shell(const char *command);
180 static bool do_watch(PQExpBuffer query_buf, double sleep, int iter, int min_rows);
181 static bool lookup_object_oid(EditableObjectType obj_type, const char *desc,
182 Oid *obj_oid);
183 static bool get_create_object_cmd(EditableObjectType obj_type, Oid oid,
184 PQExpBuffer buf);
185 static int strip_lineno_from_objdesc(char *obj);
186 static int count_lines_in_buf(PQExpBuffer buf);
187 static void print_with_linenumbers(FILE *output, char *lines, bool is_func);
188 static void minimal_error_message(PGresult *res);
189
190 static void printSSLInfo(void);
191 static void printGSSInfo(void);
192 static bool printPsetInfo(const char *param, printQueryOpt *popt);
193 static char *pset_value_string(const char *param, printQueryOpt *popt);
194
195 #ifdef WIN32
196 static void checkWin32Codepage(void);
197 #endif
198
199 static bool restricted;
200 static char *restrict_key;
201
202
203 /*----------
204 * HandleSlashCmds:
205 *
206 * Handles all the different commands that start with '\'.
207 * Ordinarily called by MainLoop().
208 *
209 * scan_state is a lexer working state that is set to continue scanning
210 * just after the '\'. The lexer is advanced past the command and all
211 * arguments on return.
212 *
213 * cstack is the current \if stack state. This will be examined, and
214 * possibly modified by conditional commands.
215 *
216 * query_buf contains the query-so-far, which may be modified by
217 * execution of the backslash command (for example, \r clears it).
218 *
219 * previous_buf contains the query most recently sent to the server
220 * (empty if none yet). This should not be modified here, but some
221 * commands copy its content into query_buf.
222 *
223 * query_buf and previous_buf will be NULL when executing a "-c"
224 * command-line option.
225 *
226 * Returns a status code indicating what action is desired, see command.h.
227 *----------
228 */
229
230 backslashResult
231 HandleSlashCmds(PsqlScanState scan_state,
232 ConditionalStack cstack,
233 PQExpBuffer query_buf,
234 PQExpBuffer previous_buf)
235 {
236 backslashResult status;
237 char *cmd;
238 char *arg;
239
240 Assert(scan_state != NULL);
241 Assert(cstack != NULL);
242
243 /* Parse off the command name */
244 cmd = psql_scan_slash_command(scan_state);
245
246 /*
247 * And try to execute it.
248 *
249 * If we are in "restricted" mode, the only allowable backslash command is
250 * \unrestrict (to exit restricted mode).
251 */
252 if (restricted && strcmp(cmd, "unrestrict") != 0)
253 {
254 pg_log_error("backslash commands are restricted; only \\unrestrict is allowed");
255 status = PSQL_CMD_ERROR;
256 }
257 else
258 status = exec_command(cmd, scan_state, cstack, query_buf, previous_buf);
259
260 if (status == PSQL_CMD_UNKNOWN)
261 {
262 pg_log_error("invalid command \\%s", cmd);
263 if (pset.cur_cmd_interactive)
264 pg_log_error_hint("Try \\? for help.");
265 status = PSQL_CMD_ERROR;
266 }
267
268 if (status != PSQL_CMD_ERROR)
269 {
270 /*
271 * Eat any remaining arguments after a valid command. We want to
272 * suppress evaluation of backticks in this situation, so transiently
273 * push an inactive conditional-stack entry.
274 */
275 bool active_branch = conditional_active(cstack);
276
277 conditional_stack_push(cstack, IFSTATE_IGNORED);
278 while ((arg = psql_scan_slash_option(scan_state,
279 OT_NORMAL, NULL, false)))
280 {
281 if (active_branch)
282 pg_log_warning("\\%s: extra argument \"%s\" ignored", cmd, arg);
283 free(arg);
284 }
285 conditional_stack_pop(cstack);
286 }
287 else
288 {
289 /* silently throw away rest of line after an erroneous command */
290 while ((arg = psql_scan_slash_option(scan_state,
291 OT_WHOLE_LINE, NULL, false)))
292 free(arg);
293 }
294
295 /* if there is a trailing \\, swallow it */
296 psql_scan_slash_command_end(scan_state);
297
298 free(cmd);
299
300 /* some commands write to queryFout, so make sure output is sent */
301 fflush(pset.queryFout);
302
303 return status;
304 }
305
306
307 /*
308 * Subroutine to actually try to execute a backslash command.
309 *
310 * The typical "success" result code is PSQL_CMD_SKIP_LINE, although some
311 * commands return something else. Failure result code is PSQL_CMD_ERROR,
312 * unless PSQL_CMD_UNKNOWN is more appropriate.
313 */
314 static backslashResult
315 exec_command(const char *cmd,
316 PsqlScanState scan_state,
317 ConditionalStack cstack,
318 PQExpBuffer query_buf,
319 PQExpBuffer previous_buf)
320 {
321 backslashResult status;
322 bool active_branch = conditional_active(cstack);
323
324 /*
325 * In interactive mode, warn when we're ignoring a command within a false
326 * \if-branch. But we continue on, so as to parse and discard the right
327 * amount of parameter text. Each individual backslash command subroutine
328 * is responsible for doing nothing after discarding appropriate
329 * arguments, if !active_branch.
330 */
331 if (pset.cur_cmd_interactive && !active_branch &&
332 !is_branching_command(cmd))
333 {
334 pg_log_warning("\\%s command ignored; use \\endif or Ctrl-C to exit current \\if block",
335 cmd);
336 }
337
338 if (strcmp(cmd, "a") == 0)
339 status = exec_command_a(scan_state, active_branch);
340 else if (strcmp(cmd, "bind") == 0)
341 status = exec_command_bind(scan_state, active_branch);
342 else if (strcmp(cmd, "bind_named") == 0)
343 status = exec_command_bind_named(scan_state, active_branch, cmd);
344 else if (strcmp(cmd, "C") == 0)
345 status = exec_command_C(scan_state, active_branch);
346 else if (strcmp(cmd, "c") == 0 || strcmp(cmd, "connect") == 0)
347 status = exec_command_connect(scan_state, active_branch);
348 else if (strcmp(cmd, "cd") == 0)
349 status = exec_command_cd(scan_state, active_branch, cmd);
350 else if (strcmp(cmd, "close_prepared") == 0)
351 status = exec_command_close_prepared(scan_state, active_branch, cmd);
352 else if (strcmp(cmd, "conninfo") == 0)
353 status = exec_command_conninfo(scan_state, active_branch);
354 else if (pg_strcasecmp(cmd, "copy") == 0)
355 status = exec_command_copy(scan_state, active_branch);
356 else if (strcmp(cmd, "copyright") == 0)
357 status = exec_command_copyright(scan_state, active_branch);
358 else if (strcmp(cmd, "crosstabview") == 0)
359 status = exec_command_crosstabview(scan_state, active_branch);
360 else if (cmd[0] == 'd')
361 status = exec_command_d(scan_state, active_branch, cmd);
362 else if (strcmp(cmd, "e") == 0 || strcmp(cmd, "edit") == 0)
363 status = exec_command_edit(scan_state, active_branch,
364 query_buf, previous_buf);
365 else if (strcmp(cmd, "ef") == 0)
366 status = exec_command_ef_ev(scan_state, active_branch, query_buf, true);
367 else if (strcmp(cmd, "ev") == 0)
368 status = exec_command_ef_ev(scan_state, active_branch, query_buf, false);
369 else if (strcmp(cmd, "echo") == 0 || strcmp(cmd, "qecho") == 0 ||
370 strcmp(cmd, "warn") == 0)
371 status = exec_command_echo(scan_state, active_branch, cmd);
372 else if (strcmp(cmd, "elif") == 0)
373 status = exec_command_elif(scan_state, cstack, query_buf);
374 else if (strcmp(cmd, "else") == 0)
375 status = exec_command_else(scan_state, cstack, query_buf);
376 else if (strcmp(cmd, "endif") == 0)
377 status = exec_command_endif(scan_state, cstack, query_buf);
378 else if (strcmp(cmd, "endpipeline") == 0)
379 status = exec_command_endpipeline(scan_state, active_branch);
380 else if (strcmp(cmd, "encoding") == 0)
381 status = exec_command_encoding(scan_state, active_branch);
382 else if (strcmp(cmd, "errverbose") == 0)
383 status = exec_command_errverbose(scan_state, active_branch);
384 else if (strcmp(cmd, "f") == 0)
385 status = exec_command_f(scan_state, active_branch);
386 else if (strcmp(cmd, "flush") == 0)
387 status = exec_command_flush(scan_state, active_branch);
388 else if (strcmp(cmd, "flushrequest") == 0)
389 status = exec_command_flushrequest(scan_state, active_branch);
390 else if (strcmp(cmd, "g") == 0 || strcmp(cmd, "gx") == 0)
391 status = exec_command_g(scan_state, active_branch, cmd);
392 else if (strcmp(cmd, "gdesc") == 0)
393 status = exec_command_gdesc(scan_state, active_branch);
394 else if (strcmp(cmd, "getenv") == 0)
395 status = exec_command_getenv(scan_state, active_branch, cmd);
396 else if (strcmp(cmd, "getresults") == 0)
397 status = exec_command_getresults(scan_state, active_branch);
398 else if (strcmp(cmd, "gexec") == 0)
399 status = exec_command_gexec(scan_state, active_branch);
400 else if (strcmp(cmd, "gset") == 0)
401 status = exec_command_gset(scan_state, active_branch);
402 else if (strcmp(cmd, "h") == 0 || strcmp(cmd, "help") == 0)
403 status = exec_command_help(scan_state, active_branch);
404 else if (strcmp(cmd, "H") == 0 || strcmp(cmd, "html") == 0)
405 status = exec_command_html(scan_state, active_branch);
406 else if (strcmp(cmd, "i") == 0 || strcmp(cmd, "include") == 0 ||
407 strcmp(cmd, "ir") == 0 || strcmp(cmd, "include_relative") == 0)
408 status = exec_command_include(scan_state, active_branch, cmd);
409 else if (strcmp(cmd, "if") == 0)
410 status = exec_command_if(scan_state, cstack, query_buf);
411 else if (strcmp(cmd, "l") == 0 || strcmp(cmd, "list") == 0 ||
412 strcmp(cmd, "lx") == 0 || strcmp(cmd, "listx") == 0 ||
413 strcmp(cmd, "l+") == 0 || strcmp(cmd, "list+") == 0 ||
414 strcmp(cmd, "lx+") == 0 || strcmp(cmd, "listx+") == 0 ||
415 strcmp(cmd, "l+x") == 0 || strcmp(cmd, "list+x") == 0)
416 status = exec_command_list(scan_state, active_branch, cmd);
417 else if (strncmp(cmd, "lo_", 3) == 0)
418 status = exec_command_lo(scan_state, active_branch, cmd);
419 else if (strcmp(cmd, "o") == 0 || strcmp(cmd, "out") == 0)
420 status = exec_command_out(scan_state, active_branch);
421 else if (strcmp(cmd, "p") == 0 || strcmp(cmd, "print") == 0)
422 status = exec_command_print(scan_state, active_branch,
423 query_buf, previous_buf);
424 else if (strcmp(cmd, "parse") == 0)
425 status = exec_command_parse(scan_state, active_branch, cmd);
426 else if (strcmp(cmd, "password") == 0)
427 status = exec_command_password(scan_state, active_branch);
428 else if (strcmp(cmd, "prompt") == 0)
429 status = exec_command_prompt(scan_state, active_branch, cmd);
430 else if (strcmp(cmd, "pset") == 0)
431 status = exec_command_pset(scan_state, active_branch);
432 else if (strcmp(cmd, "q") == 0 || strcmp(cmd, "quit") == 0)
433 status = exec_command_quit(scan_state, active_branch);
434 else if (strcmp(cmd, "r") == 0 || strcmp(cmd, "reset") == 0)
435 status = exec_command_reset(scan_state, active_branch, query_buf);
436 else if (strcmp(cmd, "restrict") == 0)
437 status = exec_command_restrict(scan_state, active_branch, cmd);
438 else if (strcmp(cmd, "s") == 0)
439 status = exec_command_s(scan_state, active_branch);
440 else if (strcmp(cmd, "sendpipeline") == 0)
441 status = exec_command_sendpipeline(scan_state, active_branch);
442 else if (strcmp(cmd, "set") == 0)
443 status = exec_command_set(scan_state, active_branch);
444 else if (strcmp(cmd, "setenv") == 0)
445 status = exec_command_setenv(scan_state, active_branch, cmd);
446 else if (strcmp(cmd, "sf") == 0 || strcmp(cmd, "sf+") == 0)
447 status = exec_command_sf_sv(scan_state, active_branch, cmd, true);
448 else if (strcmp(cmd, "sv") == 0 || strcmp(cmd, "sv+") == 0)
449 status = exec_command_sf_sv(scan_state, active_branch, cmd, false);
450 else if (strcmp(cmd, "startpipeline") == 0)
451 status = exec_command_startpipeline(scan_state, active_branch);
452 else if (strcmp(cmd, "syncpipeline") == 0)
453 status = exec_command_syncpipeline(scan_state, active_branch);
454 else if (strcmp(cmd, "t") == 0)
455 status = exec_command_t(scan_state, active_branch);
456 else if (strcmp(cmd, "T") == 0)
457 status = exec_command_T(scan_state, active_branch);
458 else if (strcmp(cmd, "timing") == 0)
459 status = exec_command_timing(scan_state, active_branch);
460 else if (strcmp(cmd, "unrestrict") == 0)
461 status = exec_command_unrestrict(scan_state, active_branch, cmd);
462 else if (strcmp(cmd, "unset") == 0)
463 status = exec_command_unset(scan_state, active_branch, cmd);
464 else if (strcmp(cmd, "w") == 0 || strcmp(cmd, "write") == 0)
465 status = exec_command_write(scan_state, active_branch, cmd,
466 query_buf, previous_buf);
467 else if (strcmp(cmd, "watch") == 0)
468 status = exec_command_watch(scan_state, active_branch,
469 query_buf, previous_buf);
470 else if (strcmp(cmd, "x") == 0)
471 status = exec_command_x(scan_state, active_branch);
472 else if (strcmp(cmd, "z") == 0 ||
473 strcmp(cmd, "zS") == 0 || strcmp(cmd, "zx") == 0 ||
474 strcmp(cmd, "zSx") == 0 || strcmp(cmd, "zxS") == 0)
475 status = exec_command_z(scan_state, active_branch, cmd);
476 else if (strcmp(cmd, "!") == 0)
477 status = exec_command_shell_escape(scan_state, active_branch);
478 else if (strcmp(cmd, "?") == 0)
479 status = exec_command_slash_command_help(scan_state, active_branch);
480 else
481 status = PSQL_CMD_UNKNOWN;
482
483 /*
484 * All the commands that return PSQL_CMD_SEND want to execute previous_buf
485 * if query_buf is empty. For convenience we implement that here, not in
486 * the individual command subroutines.
487 */
488 if (status == PSQL_CMD_SEND)
489 (void) copy_previous_query(query_buf, previous_buf);
490
491 return status;
492 }
493
494
495 /*
496 * \a -- toggle field alignment
497 *
498 * This makes little sense but we keep it around.
499 */
500 static backslashResult
501 exec_command_a(PsqlScanState scan_state, bool active_branch)
502 {
503 bool success = true;
504
505 if (active_branch)
506 {
507 if (pset.popt.topt.format != PRINT_ALIGNED)
508 success = do_pset("format", "aligned", &pset.popt, pset.quiet);
509 else
510 success = do_pset("format", "unaligned", &pset.popt, pset.quiet);
511 }
512
513 return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
514 }
515
516 /*
517 * \bind -- set query parameters
518 */
519 static backslashResult
520 exec_command_bind(PsqlScanState scan_state, bool active_branch)
521 {
522 backslashResult status = PSQL_CMD_SKIP_LINE;
523
524 if (active_branch)
525 {
526 char *opt;
527 int nparams = 0;
528 int nalloc = 0;
529
530 clean_extended_state();
531
532 while ((opt = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false)))
533 {
534 nparams++;
535 if (nparams > nalloc)
536 {
537 nalloc = nalloc ? nalloc * 2 : 1;
538 pset.bind_params = pg_realloc_array(pset.bind_params, char *, nalloc);
539 }
540 pset.bind_params[nparams - 1] = opt;
541 }
542
543 pset.bind_nparams = nparams;
544 pset.send_mode = PSQL_SEND_EXTENDED_QUERY_PARAMS;
545 }
546 else
547 ignore_slash_options(scan_state);
548
549 return status;
550 }
551
552 /*
553 * \bind_named -- set query parameters for an existing prepared statement
554 */
555 static backslashResult
556 exec_command_bind_named(PsqlScanState scan_state, bool active_branch,
557 const char *cmd)
558 {
559 backslashResult status = PSQL_CMD_SKIP_LINE;
560
561 if (active_branch)
562 {
563 char *opt;
564 int nparams = 0;
565 int nalloc = 0;
566
567 clean_extended_state();
568
569 /* get the mandatory prepared statement name */
570 opt = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false);
571 if (!opt)
572 {
573 pg_log_error("\\%s: missing required argument", cmd);
574 status = PSQL_CMD_ERROR;
575 }
576 else
577 {
578 pset.stmtName = opt;
579 pset.send_mode = PSQL_SEND_EXTENDED_QUERY_PREPARED;
580
581 /* set of parameters */
582 while ((opt = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false)))
583 {
584 nparams++;
585 if (nparams > nalloc)
586 {
587 nalloc = nalloc ? nalloc * 2 : 1;
588 pset.bind_params = pg_realloc_array(pset.bind_params, char *, nalloc);
589 }
590 pset.bind_params[nparams - 1] = opt;
591 }
592 pset.bind_nparams = nparams;
593 }
594 }
595 else
596 ignore_slash_options(scan_state);
597
598 return status;
599 }
600
601 /*
602 * \C -- override table title (formerly change HTML caption)
603 */
604 static backslashResult
605 exec_command_C(PsqlScanState scan_state, bool active_branch)
606 {
607 bool success = true;
608
609 if (active_branch)
610 {
611 char *opt = psql_scan_slash_option(scan_state,
612 OT_NORMAL, NULL, true);
613
614 success = do_pset("title", opt, &pset.popt, pset.quiet);
615 free(opt);
616 }
617 else
618 ignore_slash_options(scan_state);
619
620 return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
621 }
622
623 /*
624 * \c or \connect -- connect to database using the specified parameters.
625 *
626 * \c [-reuse-previous=BOOL] dbname user host port
627 *
628 * Specifying a parameter as '-' is equivalent to omitting it. Examples:
629 *
630 * \c - - hst Connect to current database on current port of
631 * host "hst" as current user.
632 * \c - usr - prt Connect to current database on port "prt" of current host
633 * as user "usr".
634 * \c dbs Connect to database "dbs" on current port of current host
635 * as current user.
636 */
637 static backslashResult
638 exec_command_connect(PsqlScanState scan_state, bool active_branch)
639 {
640 bool success = true;
641
642 if (active_branch)
643 {
644 static const char prefix[] = "-reuse-previous=";
645 char *opt1,
646 *opt2,
647 *opt3,
648 *opt4;
649 enum trivalue reuse_previous = TRI_DEFAULT;
650
651 opt1 = read_connect_arg(scan_state);
652 if (opt1 != NULL && strncmp(opt1, prefix, sizeof(prefix) - 1) == 0)
653 {
654 bool on_off;
655
656 success = ParseVariableBool(opt1 + sizeof(prefix) - 1,
657 "-reuse-previous",
658 &on_off);
659 if (success)
660 {
661 reuse_previous = on_off ? TRI_YES : TRI_NO;
662 free(opt1);
663 opt1 = read_connect_arg(scan_state);
664 }
665 }
666
667 if (success) /* give up if reuse_previous was invalid */
668 {
669 opt2 = read_connect_arg(scan_state);
670 opt3 = read_connect_arg(scan_state);
671 opt4 = read_connect_arg(scan_state);
672
673 success = do_connect(reuse_previous, opt1, opt2, opt3, opt4);
674
675 free(opt2);
676 free(opt3);
677 free(opt4);
678 }
679 free(opt1);
680 }
681 else
682 ignore_slash_options(scan_state);
683
684 return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
685 }
686
687 /*
688 * \cd -- change directory
689 */
690 static backslashResult
691 exec_command_cd(PsqlScanState scan_state, bool active_branch, const char *cmd)
692 {
693 bool success = true;
694
695 if (active_branch)
696 {
697 char *opt = psql_scan_slash_option(scan_state,
698 OT_NORMAL, NULL, true);
699 char *dir;
700
701 if (opt)
702 dir = opt;
703 else
704 {
705 #ifndef WIN32
706 /* This should match get_home_path() */
707 dir = getenv("HOME");
708 if (dir == NULL || dir[0] == '\0')
709 {
710 uid_t user_id = geteuid();
711 struct passwd *pw;
712
713 errno = 0; /* clear errno before call */
714 pw = getpwuid(user_id);
715 if (pw)
716 dir = pw->pw_dir;
717 else
718 {
719 pg_log_error("could not get home directory for user ID %ld: %s",
720 (long) user_id,
721 errno ? strerror(errno) : _("user does not exist"));
722 success = false;
723 }
724 }
725 #else /* WIN32 */
726
727 /*
728 * On Windows, 'cd' without arguments prints the current
729 * directory, so if someone wants to code this here instead...
730 */
731 dir = "/";
732 #endif /* WIN32 */
733 }
734
735 if (success &&
736 chdir(dir) < 0)
737 {
738 pg_log_error("\\%s: could not change directory to \"%s\": %m",
739 cmd, dir);
740 success = false;
741 }
742
743 free(opt);
744 }
745 else
746 ignore_slash_options(scan_state);
747
748 return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
749 }
750
751 /*
752 * \close_prepared -- close a previously prepared statement
753 */
754 static backslashResult
755 exec_command_close_prepared(PsqlScanState scan_state, bool active_branch, const char *cmd)
756 {
757 backslashResult status = PSQL_CMD_SKIP_LINE;
758
759 if (active_branch)
760 {
761 char *opt = psql_scan_slash_option(scan_state,
762 OT_NORMAL, NULL, false);
763
764 clean_extended_state();
765
766 if (!opt)
767 {
768 pg_log_error("\\%s: missing required argument", cmd);
769 status = PSQL_CMD_ERROR;
770 }
771 else
772 {
773 pset.stmtName = opt;
774 pset.send_mode = PSQL_SEND_EXTENDED_CLOSE;
775 status = PSQL_CMD_SEND;
776 }
777 }
778 else
779 ignore_slash_options(scan_state);
780
781 return status;
782 }
783
784 /*
785 * \conninfo -- display information about the current connection
786 */
787 static backslashResult
788 exec_command_conninfo(PsqlScanState scan_state, bool active_branch)
789 {
790 printTableContent cont;
791 int rows,
792 cols;
793 char *db;
794 char *host;
795 bool print_hostaddr;
796 char *hostaddr;
797 char *protocol_version,
798 *backend_pid;
799 int ssl_in_use,
800 password_used,
801 gssapi_used;
802 int version_num;
803 char *paramval;
804
805 if (!active_branch)
806 return PSQL_CMD_SKIP_LINE;
807
808 db = PQdb(pset.db);
809 if (db == NULL)
810 {
811 printf(_("You are currently not connected to a database.\n"));
812 return PSQL_CMD_SKIP_LINE;
813 }
814
815 /* Get values for the parameters */
816 host = PQhost(pset.db);
817 hostaddr = PQhostaddr(pset.db);
818 version_num = PQfullProtocolVersion(pset.db);
819 protocol_version = psprintf("%d.%d", version_num / 10000,
820 version_num % 10000);
821 ssl_in_use = PQsslInUse(pset.db);
822 password_used = PQconnectionUsedPassword(pset.db);
823 gssapi_used = PQconnectionUsedGSSAPI(pset.db);
824 backend_pid = psprintf("%d", PQbackendPID(pset.db));
825
826 /* Only print hostaddr if it differs from host, and not if unixsock */
827 print_hostaddr = (!is_unixsock_path(host) &&
828 hostaddr && *hostaddr && strcmp(host, hostaddr) != 0);
829
830 /* Determine the exact number of rows to print */
831 rows = 12;
832 cols = 2;
833 if (ssl_in_use)
834 rows += 6;
835 if (print_hostaddr)
836 rows++;
837
838 /* Set it all up */
839 printTableInit(&cont, &pset.popt.topt, _("Connection Information"), cols, rows);
840 printTableAddHeader(&cont, _("Parameter"), true, 'l');
841 printTableAddHeader(&cont, _("Value"), true, 'l');
842
843 /* Database */
844 printTableAddCell(&cont, _("Database"), false, false);
845 printTableAddCell(&cont, db, false, false);
846
847 /* Client User */
848 printTableAddCell(&cont, _("Client User"), false, false);
849 printTableAddCell(&cont, PQuser(pset.db), false, false);
850
851 /* Host/hostaddr/socket */
852 if (is_unixsock_path(host))
853 {
854 /* hostaddr if specified overrides socket, so suppress the latter */
855 if (hostaddr && *hostaddr)
856 {
857 printTableAddCell(&cont, _("Host Address"), false, false);
858 printTableAddCell(&cont, hostaddr, false, false);
859 }
860 else
861 {
862 printTableAddCell(&cont, _("Socket Directory"), false, false);
863 printTableAddCell(&cont, host, false, false);
864 }
865 }
866 else
867 {
868 printTableAddCell(&cont, _("Host"), false, false);
869 printTableAddCell(&cont, host, false, false);
870 if (print_hostaddr)
871 {
872 printTableAddCell(&cont, _("Host Address"), false, false);
873 printTableAddCell(&cont, hostaddr, false, false);
874 }
875 }
876
877 /* Server Port */
878 printTableAddCell(&cont, _("Server Port"), false, false);
879 printTableAddCell(&cont, PQport(pset.db), false, false);
880
881 /* Options */
882 printTableAddCell(&cont, _("Options"), false, false);
883 printTableAddCell(&cont, PQoptions(pset.db), false, false);
884
885 /* Protocol Version */
886 printTableAddCell(&cont, _("Protocol Version"), false, false);
887 printTableAddCell(&cont, protocol_version, false, false);
888
889 /* Password Used */
890 printTableAddCell(&cont, _("Password Used"), false, false);
891 printTableAddCell(&cont, password_used ? _("true") : _("false"), false, false);
892
893 /* GSSAPI Authenticated */
894 printTableAddCell(&cont, _("GSSAPI Authenticated"), false, false);
895 printTableAddCell(&cont, gssapi_used ? _("true") : _("false"), false, false);
896
897 /* Backend PID */
898 printTableAddCell(&cont, _("Backend PID"), false, false);
899 printTableAddCell(&cont, backend_pid, false, false);
900
901 /* SSL Connection */
902 printTableAddCell(&cont, _("SSL Connection"), false, false);
903 printTableAddCell(&cont, ssl_in_use ? _("true") : _("false"), false, false);
904
905 /* SSL Information */
906 if (ssl_in_use)
907 {
908 char *library,
909 *protocol,
910 *key_bits,
911 *cipher,
912 *compression,
913 *alpn;
914
915 library = (char *) PQsslAttribute(pset.db, "library");
916 protocol = (char *) PQsslAttribute(pset.db, "protocol");
917 key_bits = (char *) PQsslAttribute(pset.db, "key_bits");
918 cipher = (char *) PQsslAttribute(pset.db, "cipher");
919 compression = (char *) PQsslAttribute(pset.db, "compression");
920 alpn = (char *) PQsslAttribute(pset.db, "alpn");
921
922 printTableAddCell(&cont, _("SSL Library"), false, false);
923 printTableAddCell(&cont, library ? library : _("unknown"), false, false);
924
925 printTableAddCell(&cont, _("SSL Protocol"), false, false);
926 printTableAddCell(&cont, protocol ? protocol : _("unknown"), false, false);
927
928 printTableAddCell(&cont, _("SSL Key Bits"), false, false);
929 printTableAddCell(&cont, key_bits ? key_bits : _("unknown"), false, false);
930
931 printTableAddCell(&cont, _("SSL Cipher"), false, false);
932 printTableAddCell(&cont, cipher ? cipher : _("unknown"), false, false);
933
934 printTableAddCell(&cont, _("SSL Compression"), false, false);
935 printTableAddCell(&cont, (compression && strcmp(compression, "off") != 0) ?
936 _("true") : _("false"), false, false);
937
938 printTableAddCell(&cont, _("ALPN"), false, false);
939 printTableAddCell(&cont, (alpn && alpn[0] != '\0') ? alpn : _("none"), false, false);
940 }
941
942 paramval = (char *) PQparameterStatus(pset.db, "is_superuser");
943 printTableAddCell(&cont, "Superuser", false, false);
944 printTableAddCell(&cont, paramval ? paramval : _("unknown"), false, false);
945
946 paramval = (char *) PQparameterStatus(pset.db, "in_hot_standby");
947 printTableAddCell(&cont, "Hot Standby", false, false);
948 printTableAddCell(&cont, paramval ? paramval : _("unknown"), false, false);
949
950 printTable(&cont, pset.queryFout, false, pset.logfile);
951 printTableCleanup(&cont);
952
953 pfree(protocol_version);
954 pfree(backend_pid);
955
956 return PSQL_CMD_SKIP_LINE;
957 }
958
959 /*
960 * \copy -- run a COPY command
961 */
962 static backslashResult
963 exec_command_copy(PsqlScanState scan_state, bool active_branch)
964 {
965 bool success = true;
966
967 if (active_branch)
968 {
969 char *opt = psql_scan_slash_option(scan_state,
970 OT_WHOLE_LINE, NULL, false);
971
972 success = do_copy(opt);
973 free(opt);
974 }
975 else
976 ignore_slash_whole_line(scan_state);
977
978 return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
979 }
980
981 /*
982 * \copyright -- print copyright notice
983 */
984 static backslashResult
985 exec_command_copyright(PsqlScanState scan_state, bool active_branch)
986 {
987 if (active_branch)
988 print_copyright();
989
990 return PSQL_CMD_SKIP_LINE;
991 }
992
993 /*
994 * \crosstabview -- execute a query and display result in crosstab
995 */
996 static backslashResult
997 exec_command_crosstabview(PsqlScanState scan_state, bool active_branch)
998 {
999 backslashResult status = PSQL_CMD_SKIP_LINE;
1000
1001 if (active_branch)
1002 {
1003 int i;
1004
1005 for (i = 0; i < lengthof(pset.ctv_args); i++)
1006 pset.ctv_args[i] = psql_scan_slash_option(scan_state,
1007 OT_NORMAL, NULL, true);
1008 pset.crosstab_flag = true;
1009 status = PSQL_CMD_SEND;
1010 }
1011 else
1012 ignore_slash_options(scan_state);
1013
1014 return status;
1015 }
1016
1017 /*
1018 * \d* commands
1019 */
1020 static backslashResult
1021 exec_command_d(PsqlScanState scan_state, bool active_branch, const char *cmd)
1022 {
1023 backslashResult status = PSQL_CMD_SKIP_LINE;
1024 bool success = true;
1025
1026 if (active_branch)
1027 {
1028 char *pattern;
1029 bool show_verbose,
1030 show_system;
1031 unsigned short int save_expanded;
1032
1033 /* We don't do SQLID reduction on the pattern yet */
1034 pattern = psql_scan_slash_option(scan_state,
1035 OT_NORMAL, NULL, true);
1036
1037 show_verbose = strchr(cmd, '+') ? true : false;
1038 show_system = strchr(cmd, 'S') ? true : false;
1039
1040 /*
1041 * The 'x' option turns expanded mode on for this command only. This
1042 * is allowed in all \d* commands, except \d by itself, since \dx is a
1043 * separate command. So the 'x' option cannot appear immediately after
1044 * \d, but it can appear after \d followed by other options.
1045 */
1046 save_expanded = pset.popt.topt.expanded;
1047 if (cmd[1] != '\0' && strchr(&cmd[2], 'x'))
1048 pset.popt.topt.expanded = 1;
1049
1050 switch (cmd[1])
1051 {
1052 case '\0':
1053 case '+':
1054 case 'S':
1055 if (pattern)
1056 success = describeTableDetails(pattern, show_verbose, show_system);
1057 else
1058 /* standard listing of interesting things */
1059 success = listTables("tvmsE", NULL, show_verbose, show_system);
1060 break;
1061 case 'A':
1062 {
1063 char *pattern2 = NULL;
1064
1065 if (pattern && cmd[2] != '\0' && cmd[2] != '+' && cmd[2] != 'x')
1066 pattern2 = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, true);
1067
1068 switch (cmd[2])
1069 {
1070 case '\0':
1071 case '+':
1072 case 'x':
1073 success = describeAccessMethods(pattern, show_verbose);
1074 break;
1075 case 'c':
1076 success = listOperatorClasses(pattern, pattern2, show_verbose);
1077 break;
1078 case 'f':
1079 success = listOperatorFamilies(pattern, pattern2, show_verbose);
1080 break;
1081 case 'o':
1082 success = listOpFamilyOperators(pattern, pattern2, show_verbose);
1083 break;
1084 case 'p':
1085 success = listOpFamilyFunctions(pattern, pattern2, show_verbose);
1086 break;
1087 default:
1088 status = PSQL_CMD_UNKNOWN;
1089 break;
1090 }
1091
1092 free(pattern2);
1093 }
1094 break;
1095 case 'a':
1096 success = describeAggregates(pattern, show_verbose, show_system);
1097 break;
1098 case 'b':
1099 success = describeTablespaces(pattern, show_verbose);
1100 break;
1101 case 'c':
1102 if (strncmp(cmd, "dconfig", 7) == 0)
1103 success = describeConfigurationParameters(pattern,
1104 show_verbose,
1105 show_system);
1106 else
1107 success = listConversions(pattern,
1108 show_verbose,
1109 show_system);
1110 break;
1111 case 'C':
1112 success = listCasts(pattern, show_verbose);
1113 break;
1114 case 'd':
1115 if (strncmp(cmd, "ddp", 3) == 0)
1116 success = listDefaultACLs(pattern);
1117 else
1118 success = objectDescription(pattern, show_system);
1119 break;
1120 case 'D':
1121 success = listDomains(pattern, show_verbose, show_system);
1122 break;
1123 case 'f': /* function subsystem */
1124 switch (cmd[2])
1125 {
1126 case '\0':
1127 case '+':
1128 case 'S':
1129 case 'a':
1130 case 'n':
1131 case 'p':
1132 case 't':
1133 case 'w':
1134 case 'x':
1135 success = exec_command_dfo(scan_state, cmd, pattern,
1136 show_verbose, show_system);
1137 break;
1138 default:
1139 status = PSQL_CMD_UNKNOWN;
1140 break;
1141 }
1142 break;
1143 case 'g':
1144 /* no longer distinct from \du */
1145 success = describeRoles(pattern, show_verbose, show_system);
1146 break;
1147 case 'l':
1148 success = listLargeObjects(show_verbose);
1149 break;
1150 case 'L':
1151 success = listLanguages(pattern, show_verbose, show_system);
1152 break;
1153 case 'n':
1154 success = listSchemas(pattern, show_verbose, show_system);
1155 break;
1156 case 'o':
1157 success = exec_command_dfo(scan_state, cmd, pattern,
1158 show_verbose, show_system);
1159 break;
1160 case 'O':
1161 success = listCollations(pattern, show_verbose, show_system);
1162 break;
1163 case 'p':
1164 success = permissionsList(pattern, show_system);
1165 break;
1166 case 'P':
1167 {
1168 switch (cmd[2])
1169 {
1170 case '\0':
1171 case '+':
1172 case 't':
1173 case 'i':
1174 case 'n':
1175 case 'x':
1176 success = listPartitionedTables(&cmd[2], pattern, show_verbose);
1177 break;
1178 default:
1179 status = PSQL_CMD_UNKNOWN;
1180 break;
1181 }
1182 }
1183 break;
1184 case 'T':
1185 success = describeTypes(pattern, show_verbose, show_system);
1186 break;
1187 case 't':
1188 case 'v':
1189 case 'm':
1190 case 'i':
1191 case 's':
1192 case 'E':
1193 success = listTables(&cmd[1], pattern, show_verbose, show_system);
1194 break;
1195 case 'r':
1196 if (cmd[2] == 'd' && cmd[3] == 's')
1197 {
1198 char *pattern2 = NULL;
1199
1200 if (pattern)
1201 pattern2 = psql_scan_slash_option(scan_state,
1202 OT_NORMAL, NULL, true);
1203 success = listDbRoleSettings(pattern, pattern2);
1204
1205 free(pattern2);
1206 }
1207 else if (cmd[2] == 'g')
1208 success = describeRoleGrants(pattern, show_system);
1209 else
1210 status = PSQL_CMD_UNKNOWN;
1211 break;
1212 case 'R':
1213 switch (cmd[2])
1214 {
1215 case 'p':
1216 if (show_verbose)
1217 success = describePublications(pattern);
1218 else
1219 success = listPublications(pattern);
1220 break;
1221 case 's':
1222 success = describeSubscriptions(pattern, show_verbose);
1223 break;
1224 default:
1225 status = PSQL_CMD_UNKNOWN;
1226 }
1227 break;
1228 case 'u':
1229 success = describeRoles(pattern, show_verbose, show_system);
1230 break;
1231 case 'F': /* text search subsystem */
1232 switch (cmd[2])
1233 {
1234 case '\0':
1235 case '+':
1236 case 'x':
1237 success = listTSConfigs(pattern, show_verbose);
1238 break;
1239 case 'p':
1240 success = listTSParsers(pattern, show_verbose);
1241 break;
1242 case 'd':
1243 success = listTSDictionaries(pattern, show_verbose);
1244 break;
1245 case 't':
1246 success = listTSTemplates(pattern, show_verbose);
1247 break;
1248 default:
1249 status = PSQL_CMD_UNKNOWN;
1250 break;
1251 }
1252 break;
1253 case 'e': /* SQL/MED subsystem */
1254 switch (cmd[2])
1255 {
1256 case 's':
1257 success = listForeignServers(pattern, show_verbose);
1258 break;
1259 case 'u':
1260 success = listUserMappings(pattern, show_verbose);
1261 break;
1262 case 'w':
1263 success = listForeignDataWrappers(pattern, show_verbose);
1264 break;
1265 case 't':
1266 success = listForeignTables(pattern, show_verbose);
1267 break;
1268 default:
1269 status = PSQL_CMD_UNKNOWN;
1270 break;
1271 }
1272 break;
1273 case 'x': /* Extensions */
1274 if (show_verbose)
1275 success = listExtensionContents(pattern);
1276 else
1277 success = listExtensions(pattern);
1278 break;
1279 case 'X': /* Extended Statistics */
1280 success = listExtendedStats(pattern);
1281 break;
1282 case 'y': /* Event Triggers */
1283 success = listEventTriggers(pattern, show_verbose);
1284 break;
1285 default:
1286 status = PSQL_CMD_UNKNOWN;
1287 }
1288
1289 /* Restore original expanded mode */
1290 pset.popt.topt.expanded = save_expanded;
1291
1292 free(pattern);
1293 }
1294 else
1295 ignore_slash_options(scan_state);
1296
1297 if (!success)
1298 status = PSQL_CMD_ERROR;
1299
1300 return status;
1301 }
1302
1303 /* \df and \do; messy enough to split out of exec_command_d */
1304 static bool
1305 exec_command_dfo(PsqlScanState scan_state, const char *cmd,
1306 const char *pattern,
1307 bool show_verbose, bool show_system)
1308 {
1309 bool success;
1310 char *arg_patterns[FUNC_MAX_ARGS];
1311 int num_arg_patterns = 0;
1312
1313 /* Collect argument-type patterns too */
1314 if (pattern) /* otherwise it was just \df or \do */
1315 {
1316 char *ap;
1317
1318 while ((ap = psql_scan_slash_option(scan_state,
1319 OT_NORMAL, NULL, true)) != NULL)
1320 {
1321 arg_patterns[num_arg_patterns++] = ap;
1322 if (num_arg_patterns >= FUNC_MAX_ARGS)
1323 break; /* protect limited-size array */
1324 }
1325 }
1326
1327 if (cmd[1] == 'f')
1328 success = describeFunctions(&cmd[2], pattern,
1329 arg_patterns, num_arg_patterns,
1330 show_verbose, show_system);
1331 else
1332 success = describeOperators(pattern,
1333 arg_patterns, num_arg_patterns,
1334 show_verbose, show_system);
1335
1336 while (--num_arg_patterns >= 0)
1337 free(arg_patterns[num_arg_patterns]);
1338
1339 return success;
1340 }
1341
1342 /*
1343 * \e or \edit -- edit the current query buffer, or edit a file and
1344 * make it the query buffer
1345 */
1346 static backslashResult
1347 exec_command_edit(PsqlScanState scan_state, bool active_branch,
1348 PQExpBuffer query_buf, PQExpBuffer previous_buf)
1349 {
1350 backslashResult status = PSQL_CMD_SKIP_LINE;
1351
1352 if (active_branch)
1353 {
1354 if (!query_buf)
1355 {
1356 pg_log_error("no query buffer");
1357 status = PSQL_CMD_ERROR;
1358 }
1359 else
1360 {
1361 char *fname;
1362 char *ln = NULL;
1363 int lineno = -1;
1364
1365 fname = psql_scan_slash_option(scan_state,
1366 OT_NORMAL, NULL, true);
1367 if (fname)
1368 {
1369 /* try to get separate lineno arg */
1370 ln = psql_scan_slash_option(scan_state,
1371 OT_NORMAL, NULL, true);
1372 if (ln == NULL)
1373 {
1374 /* only one arg; maybe it is lineno not fname */
1375 if (fname[0] &&
1376 strspn(fname, "0123456789") == strlen(fname))
1377 {
1378 /* all digits, so assume it is lineno */
1379 ln = fname;
1380 fname = NULL;
1381 }
1382 }
1383 }
1384 if (ln)
1385 {
1386 lineno = atoi(ln);
1387 if (lineno < 1)
1388 {
1389 pg_log_error("invalid line number: %s", ln);
1390 status = PSQL_CMD_ERROR;
1391 }
1392 }
1393 if (status != PSQL_CMD_ERROR)
1394 {
1395 bool discard_on_quit;
1396
1397 expand_tilde(&fname);
1398 if (fname)
1399 {
1400 canonicalize_path_enc(fname, pset.encoding);
1401 /* Always clear buffer if the file isn't modified */
1402 discard_on_quit = true;
1403 }
1404 else
1405 {
1406 /*
1407 * If query_buf is empty, recall previous query for
1408 * editing. But in that case, the query buffer should be
1409 * emptied if editing doesn't modify the file.
1410 */
1411 discard_on_quit = copy_previous_query(query_buf,
1412 previous_buf);
1413 }
1414
1415 if (do_edit(fname, query_buf, lineno, discard_on_quit, NULL))
1416 status = PSQL_CMD_NEWEDIT;
1417 else
1418 status = PSQL_CMD_ERROR;
1419 }
1420
1421 /*
1422 * On error while editing or if specifying an incorrect line
1423 * number, reset the query buffer.
1424 */
1425 if (status == PSQL_CMD_ERROR)
1426 resetPQExpBuffer(query_buf);
1427
1428 free(fname);
1429 free(ln);
1430 }
1431 }
1432 else
1433 ignore_slash_options(scan_state);
1434
1435 return status;
1436 }
1437
1438 /*
1439 * \ef/\ev -- edit the named function/view, or
1440 * present a blank CREATE FUNCTION/VIEW template if no argument is given
1441 */
1442 static backslashResult
1443 exec_command_ef_ev(PsqlScanState scan_state, bool active_branch,
1444 PQExpBuffer query_buf, bool is_func)
1445 {
1446 backslashResult status = PSQL_CMD_SKIP_LINE;
1447
1448 if (active_branch)
1449 {
1450 char *obj_desc = psql_scan_slash_option(scan_state,
1451 OT_WHOLE_LINE,
1452 NULL, true);
1453 int lineno = -1;
1454
1455 if (!query_buf)
1456 {
1457 pg_log_error("no query buffer");
1458 status = PSQL_CMD_ERROR;
1459 }
1460 else
1461 {
1462 Oid obj_oid = InvalidOid;
1463 EditableObjectType eot = is_func ? EditableFunction : EditableView;
1464
1465 lineno = strip_lineno_from_objdesc(obj_desc);
1466 if (lineno == 0)
1467 {
1468 /* error already reported */
1469 status = PSQL_CMD_ERROR;
1470 }
1471 else if (!obj_desc)
1472 {
1473 /* set up an empty command to fill in */
1474 resetPQExpBuffer(query_buf);
1475 if (is_func)
1476 appendPQExpBufferStr(query_buf,
1477 "CREATE FUNCTION ( )\n"
1478 " RETURNS \n"
1479 " LANGUAGE \n"
1480 " -- common options: IMMUTABLE STABLE STRICT SECURITY DEFINER\n"
1481 "AS $function$\n"
1482 "\n$function$\n");
1483 else
1484 appendPQExpBufferStr(query_buf,
1485 "CREATE VIEW AS\n"
1486 " SELECT \n"
1487 " -- something...\n");
1488 }
1489 else if (!lookup_object_oid(eot, obj_desc, &obj_oid))
1490 {
1491 /* error already reported */
1492 status = PSQL_CMD_ERROR;
1493 }
1494 else if (!get_create_object_cmd(eot, obj_oid, query_buf))
1495 {
1496 /* error already reported */
1497 status = PSQL_CMD_ERROR;
1498 }
1499 else if (is_func && lineno > 0)
1500 {
1501 /*
1502 * lineno "1" should correspond to the first line of the
1503 * function body. We expect that pg_get_functiondef() will
1504 * emit that on a line beginning with "AS ", "BEGIN ", or
1505 * "RETURN ", and that there can be no such line before the
1506 * real start of the function body. Increment lineno by the
1507 * number of lines before that line, so that it becomes
1508 * relative to the first line of the function definition.
1509 */
1510 const char *lines = query_buf->data;
1511
1512 while (*lines != '\0')
1513 {
1514 if (strncmp(lines, "AS ", 3) == 0 ||
1515 strncmp(lines, "BEGIN ", 6) == 0 ||
1516 strncmp(lines, "RETURN ", 7) == 0)
1517 break;
1518 lineno++;
1519 /* find start of next line */
1520 lines = strchr(lines, '\n');
1521 if (!lines)
1522 break;
1523 lines++;
1524 }
1525 }
1526 }
1527
1528 if (status != PSQL_CMD_ERROR)
1529 {
1530 bool edited = false;
1531
1532 if (!do_edit(NULL, query_buf, lineno, true, &edited))
1533 status = PSQL_CMD_ERROR;
1534 else if (!edited)
1535 puts(_("No changes"));
1536 else
1537 status = PSQL_CMD_NEWEDIT;
1538 }
1539
1540 /*
1541 * On error while doing object lookup or while editing, or if
1542 * specifying an incorrect line number, reset the query buffer.
1543 */
1544 if (status == PSQL_CMD_ERROR)
1545 resetPQExpBuffer(query_buf);
1546
1547 free(obj_desc);
1548 }
1549 else
1550 ignore_slash_whole_line(scan_state);
1551
1552 return status;
1553 }
1554
1555 /*
1556 * \echo, \qecho, and \warn -- echo arguments to stdout, query output, or stderr
1557 */
1558 static backslashResult
1559 exec_command_echo(PsqlScanState scan_state, bool active_branch, const char *cmd)
1560 {
1561 if (active_branch)
1562 {
1563 char *value;
1564 char quoted;
1565 bool no_newline = false;
1566 bool first = true;
1567 FILE *fout;
1568
1569 if (strcmp(cmd, "qecho") == 0)
1570 fout = pset.queryFout;
1571 else if (strcmp(cmd, "warn") == 0)
1572 fout = stderr;
1573 else
1574 fout = stdout;
1575
1576 while ((value = psql_scan_slash_option(scan_state,
1577 OT_NORMAL, &quoted, false)))
1578 {
1579 if (first && !no_newline && !quoted && strcmp(value, "-n") == 0)
1580 no_newline = true;
1581 else
1582 {
1583 if (first)
1584 first = false;
1585 else
1586 fputc(' ', fout);
1587 fputs(value, fout);
1588 }
1589 free(value);
1590 }
1591 if (!no_newline)
1592 fputs("\n", fout);
1593 }
1594 else
1595 ignore_slash_options(scan_state);
1596
1597 return PSQL_CMD_SKIP_LINE;
1598 }
1599
1600 /*
1601 * \encoding -- set/show client side encoding
1602 */
1603 static backslashResult
1604 exec_command_encoding(PsqlScanState scan_state, bool active_branch)
1605 {
1606 if (active_branch)
1607 {
1608 char *encoding = psql_scan_slash_option(scan_state,
1609 OT_NORMAL, NULL, false);
1610
1611 if (!encoding)
1612 {
1613 /* show encoding */
1614 puts(pg_encoding_to_char(pset.encoding));
1615 }
1616 else
1617 {
1618 /* set encoding */
1619 if (PQsetClientEncoding(pset.db, encoding) == -1)
1620 pg_log_error("%s: invalid encoding name or conversion procedure not found", encoding);
1621 else
1622 {
1623 /* save encoding info into psql internal data */
1624 pset.encoding = PQclientEncoding(pset.db);
1625 pset.popt.topt.encoding = pset.encoding;
1626 setFmtEncoding(pset.encoding);
1627 SetVariable(pset.vars, "ENCODING",
1628 pg_encoding_to_char(pset.encoding));
1629 }
1630 free(encoding);
1631 }
1632 }
1633 else
1634 ignore_slash_options(scan_state);
1635
1636 return PSQL_CMD_SKIP_LINE;
1637 }
1638
1639 /*
1640 * \errverbose -- display verbose message from last failed query
1641 */
1642 static backslashResult
1643 exec_command_errverbose(PsqlScanState scan_state, bool active_branch)
1644 {
1645 if (active_branch)
1646 {
1647 if (pset.last_error_result)
1648 {
1649 char *msg;
1650
1651 msg = PQresultVerboseErrorMessage(pset.last_error_result,
1652 PQERRORS_VERBOSE,
1653 PQSHOW_CONTEXT_ALWAYS);
1654 if (msg)
1655 {
1656 pg_log_error("%s", msg);
1657 PQfreemem(msg);
1658 }
1659 else
1660 puts(_("out of memory"));
1661 }
1662 else
1663 puts(_("There is no previous error."));
1664 }
1665
1666 return PSQL_CMD_SKIP_LINE;
1667 }
1668
1669 /*
1670 * \f -- change field separator
1671 */
1672 static backslashResult
1673 exec_command_f(PsqlScanState scan_state, bool active_branch)
1674 {
1675 bool success = true;
1676
1677 if (active_branch)
1678 {
1679 char *fname = psql_scan_slash_option(scan_state,
1680 OT_NORMAL, NULL, false);
1681
1682 success = do_pset("fieldsep", fname, &pset.popt, pset.quiet);
1683 free(fname);
1684 }
1685 else
1686 ignore_slash_options(scan_state);
1687
1688 return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
1689 }
1690
1691 /*
1692 * \flush -- call PQflush() on the connection
1693 */
1694 static backslashResult
1695 exec_command_flush(PsqlScanState scan_state, bool active_branch)
1696 {
1697 backslashResult status = PSQL_CMD_SKIP_LINE;
1698
1699 if (active_branch)
1700 {
1701 pset.send_mode = PSQL_SEND_FLUSH;
1702 status = PSQL_CMD_SEND;
1703 }
1704 else
1705 ignore_slash_options(scan_state);
1706
1707 return status;
1708 }
1709
1710 /*
1711 * \flushrequest -- call PQsendFlushRequest() on the connection
1712 */
1713 static backslashResult
1714 exec_command_flushrequest(PsqlScanState scan_state, bool active_branch)
1715 {
1716 backslashResult status = PSQL_CMD_SKIP_LINE;
1717
1718 if (active_branch)
1719 {
1720 pset.send_mode = PSQL_SEND_FLUSH_REQUEST;
1721 status = PSQL_CMD_SEND;
1722 }
1723 else
1724 ignore_slash_options(scan_state);
1725
1726 return status;
1727 }
1728
1729 /*
1730 * \g [(pset-option[=pset-value] ...)] [filename/shell-command]
1731 * \gx [(pset-option[=pset-value] ...)] [filename/shell-command]
1732 *
1733 * Send the current query. If pset options are specified, they are made
1734 * active just for this query. If a filename or pipe command is given,
1735 * the query output goes there. \gx implicitly sets "expanded=on" along
1736 * with any other pset options that are specified.
1737 */
1738 static backslashResult
1739 exec_command_g(PsqlScanState scan_state, bool active_branch, const char *cmd)
1740 {
1741 backslashResult status = PSQL_CMD_SKIP_LINE;
1742 char *fname;
1743
1744 /*
1745 * Because the option processing for this is fairly complicated, we do it
1746 * and then decide whether the branch is active.
1747 */
1748 fname = psql_scan_slash_option(scan_state,
1749 OT_FILEPIPE, NULL, false);
1750
1751 if (fname && fname[0] == '(')
1752 {
1753 /* Consume pset options through trailing ')' ... */
1754 status = process_command_g_options(fname + 1, scan_state,
1755 active_branch, cmd);
1756 free(fname);
1757 /* ... and again attempt to scan the filename. */
1758 fname = psql_scan_slash_option(scan_state,
1759 OT_FILEPIPE, NULL, false);
1760 }
1761
1762 if (status == PSQL_CMD_SKIP_LINE && active_branch)
1763 {
1764 if (PQpipelineStatus(pset.db) != PQ_PIPELINE_OFF)
1765 {
1766 pg_log_error("\\%s not allowed in pipeline mode", cmd);
1767 clean_extended_state();
1768 free(fname);
1769 return PSQL_CMD_ERROR;
1770 }
1771
1772 if (!fname)
1773 pset.gfname = NULL;
1774 else
1775 {
1776 expand_tilde(&fname);
1777 pset.gfname = pg_strdup(fname);
1778 }
1779 if (strcmp(cmd, "gx") == 0)
1780 {
1781 /* save settings if not done already, then force expanded=on */
1782 if (pset.gsavepopt == NULL)
1783 pset.gsavepopt = savePsetInfo(&pset.popt);
1784 pset.popt.topt.expanded = 1;
1785 }
1786 status = PSQL_CMD_SEND;
1787 }
1788
1789 free(fname);
1790
1791 return status;
1792 }
1793
1794 /*
1795 * Process parenthesized pset options for \g
1796 *
1797 * Note: okay to modify first_option, but not to free it; caller does that
1798 */
1799 static backslashResult
1800 process_command_g_options(char *first_option, PsqlScanState scan_state,
1801 bool active_branch, const char *cmd)
1802 {
1803 bool success = true;
1804 bool found_r_paren = false;
1805
1806 do
1807 {
1808 char *option;
1809 size_t optlen;
1810
1811 /* If not first time through, collect a new option */
1812 if (first_option)
1813 option = first_option;
1814 else
1815 {
1816 option = psql_scan_slash_option(scan_state,
1817 OT_NORMAL, NULL, false);
1818 if (!option)
1819 {
1820 if (active_branch)
1821 {
1822 pg_log_error("\\%s: missing right parenthesis", cmd);
1823 success = false;
1824 }
1825 break;
1826 }
1827 }
1828
1829 /* Check for terminating right paren, and remove it from string */
1830 optlen = strlen(option);
1831 if (optlen > 0 && option[optlen - 1] == ')')
1832 {
1833 option[--optlen] = '\0';
1834 found_r_paren = true;
1835 }
1836
1837 /* If there was anything besides parentheses, parse/execute it */
1838 if (optlen > 0)
1839 {
1840 /* We can have either "name" or "name=value" */
1841 char *valptr = strchr(option, '=');
1842
1843 if (valptr)
1844 *valptr++ = '\0';
1845 if (active_branch)
1846 {
1847 /* save settings if not done already, then apply option */
1848 if (pset.gsavepopt == NULL)
1849 pset.gsavepopt = savePsetInfo(&pset.popt);
1850 success &= do_pset(option, valptr, &pset.popt, true);
1851 }
1852 }
1853
1854 /* Clean up after this option. We should not free first_option. */
1855 if (first_option)
1856 first_option = NULL;
1857 else
1858 free(option);
1859 } while (!found_r_paren);
1860
1861 /* If we failed after already changing some options, undo side-effects */
1862 if (!success && active_branch && pset.gsavepopt)
1863 {
1864 restorePsetInfo(&pset.popt, pset.gsavepopt);
1865 pset.gsavepopt = NULL;
1866 }
1867
1868 return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
1869 }
1870
1871 /*
1872 * \gdesc -- describe query result
1873 */
1874 static backslashResult
1875 exec_command_gdesc(PsqlScanState scan_state, bool active_branch)
1876 {
1877 backslashResult status = PSQL_CMD_SKIP_LINE;
1878
1879 if (active_branch)
1880 {
1881 pset.gdesc_flag = true;
1882 status = PSQL_CMD_SEND;
1883 }
1884
1885 return status;
1886 }
1887
1888 /*
1889 * \getenv -- set variable from environment variable
1890 */
1891 static backslashResult
1892 exec_command_getenv(PsqlScanState scan_state, bool active_branch,
1893 const char *cmd)
1894 {
1895 bool success = true;
1896
1897 if (active_branch)
1898 {
1899 char *myvar = psql_scan_slash_option(scan_state,
1900 OT_NORMAL, NULL, false);
1901 char *envvar = psql_scan_slash_option(scan_state,
1902 OT_NORMAL, NULL, false);
1903
1904 if (!myvar || !envvar)
1905 {
1906 pg_log_error("\\%s: missing required argument", cmd);
1907 success = false;
1908 }
1909 else
1910 {
1911 char *envval = getenv(envvar);
1912
1913 if (envval && !SetVariable(pset.vars, myvar, envval))
1914 success = false;
1915 }
1916 free(myvar);
1917 free(envvar);
1918 }
1919 else
1920 ignore_slash_options(scan_state);
1921
1922 return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
1923 }
1924
1925 /*
1926 * \getresults -- read results
1927 */
1928 static backslashResult
1929 exec_command_getresults(PsqlScanState scan_state, bool active_branch)
1930 {
1931 backslashResult status = PSQL_CMD_SKIP_LINE;
1932
1933 if (active_branch)
1934 {
1935 char *opt;
1936 int num_results;
1937
1938 pset.send_mode = PSQL_SEND_GET_RESULTS;
1939 status = PSQL_CMD_SEND;
1940 opt = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false);
1941
1942 pset.requested_results = 0;
1943 if (opt != NULL)
1944 {
1945 num_results = atoi(opt);
1946 if (num_results < 0)
1947 {
1948 pg_log_error("\\getresults: invalid number of requested results");
1949 return PSQL_CMD_ERROR;
1950 }
1951 pset.requested_results = num_results;
1952 }
1953 }
1954 else
1955 ignore_slash_options(scan_state);
1956
1957 return status;
1958 }
1959
1960
1961 /*
1962 * \gexec -- send query and execute each field of result
1963 */
1964 static backslashResult
1965 exec_command_gexec(PsqlScanState scan_state, bool active_branch)
1966 {
1967 backslashResult status = PSQL_CMD_SKIP_LINE;
1968
1969 if (active_branch)
1970 {
1971 if (PQpipelineStatus(pset.db) != PQ_PIPELINE_OFF)
1972 {
1973 pg_log_error("\\%s not allowed in pipeline mode", "gexec");
1974 clean_extended_state();
1975 return PSQL_CMD_ERROR;
1976 }
1977 pset.gexec_flag = true;
1978 status = PSQL_CMD_SEND;
1979 }
1980
1981 return status;
1982 }
1983
1984 /*
1985 * \gset [prefix] -- send query and store result into variables
1986 */
1987 static backslashResult
1988 exec_command_gset(PsqlScanState scan_state, bool active_branch)
1989 {
1990 backslashResult status = PSQL_CMD_SKIP_LINE;
1991
1992 if (active_branch)
1993 {
1994 char *prefix = psql_scan_slash_option(scan_state,
1995 OT_NORMAL, NULL, false);
1996
1997 if (PQpipelineStatus(pset.db) != PQ_PIPELINE_OFF)
1998 {
1999 pg_log_error("\\%s not allowed in pipeline mode", "gset");
2000 clean_extended_state();
2001 return PSQL_CMD_ERROR;
2002 }
2003
2004 if (prefix)
2005 pset.gset_prefix = prefix;
2006 else
2007 {
2008 /* we must set a non-NULL prefix to trigger storing */
2009 pset.gset_prefix = pg_strdup("");
2010 }
2011 /* gset_prefix is freed later */
2012 status = PSQL_CMD_SEND;
2013 }
2014 else
2015 ignore_slash_options(scan_state);
2016
2017 return status;
2018 }
2019
2020 /*
2021 * \help [topic] -- print help about SQL commands
2022 */
2023 static backslashResult
2024 exec_command_help(PsqlScanState scan_state, bool active_branch)
2025 {
2026 if (active_branch)
2027 {
2028 char *opt = psql_scan_slash_option(scan_state,
2029 OT_WHOLE_LINE, NULL, true);
2030
2031 helpSQL(opt, pset.popt.topt.pager);
2032 free(opt);
2033 }
2034 else
2035 ignore_slash_whole_line(scan_state);
2036
2037 return PSQL_CMD_SKIP_LINE;
2038 }
2039
2040 /*
2041 * \H and \html -- toggle HTML formatting
2042 */
2043 static backslashResult
2044 exec_command_html(PsqlScanState scan_state, bool active_branch)
2045 {
2046 bool success = true;
2047
2048 if (active_branch)
2049 {
2050 if (pset.popt.topt.format != PRINT_HTML)
2051 success = do_pset("format", "html", &pset.popt, pset.quiet);
2052 else
2053 success = do_pset("format", "aligned", &pset.popt, pset.quiet);
2054 }
2055
2056 return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
2057 }
2058
2059 /*
2060 * \i and \ir -- include a file
2061 */
2062 static backslashResult
2063 exec_command_include(PsqlScanState scan_state, bool active_branch, const char *cmd)
2064 {
2065 bool success = true;
2066
2067 if (active_branch)
2068 {
2069 char *fname = psql_scan_slash_option(scan_state,
2070 OT_NORMAL, NULL, true);
2071
2072 if (!fname)
2073 {
2074 pg_log_error("\\%s: missing required argument", cmd);
2075 success = false;
2076 }
2077 else
2078 {
2079 bool include_relative;
2080
2081 include_relative = (strcmp(cmd, "ir") == 0
2082 || strcmp(cmd, "include_relative") == 0);
2083 expand_tilde(&fname);
2084 success = (process_file(fname, include_relative) == EXIT_SUCCESS);
2085 free(fname);
2086 }
2087 }
2088 else
2089 ignore_slash_options(scan_state);
2090
2091 return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
2092 }
2093
2094 /*
2095 * \if <expr> -- beginning of an \if..\endif block
2096 *
2097 * <expr> is parsed as a boolean expression. Invalid expressions will emit a
2098 * warning and be treated as false. Statements that follow a false expression
2099 * will be parsed but ignored. Note that in the case where an \if statement
2100 * is itself within an inactive section of a block, then the entire inner
2101 * \if..\endif block will be parsed but ignored.
2102 */
2103 static backslashResult
2104 exec_command_if(PsqlScanState scan_state, ConditionalStack cstack,
2105 PQExpBuffer query_buf)
2106 {
2107 if (conditional_active(cstack))
2108 {
2109 /*
2110 * First, push a new active stack entry; this ensures that the lexer
2111 * will perform variable substitution and backtick evaluation while
2112 * scanning the expression. (That should happen anyway, since we know
2113 * we're in an active outer branch, but let's be sure.)
2114 */
2115 conditional_stack_push(cstack, IFSTATE_TRUE);
2116
2117 /* Remember current query state in case we need to restore later */
2118 save_query_text_state(scan_state, cstack, query_buf);
2119
2120 /*
2121 * Evaluate the expression; if it's false, change to inactive state.
2122 */
2123 if (!is_true_boolean_expression(scan_state, "\\if expression"))
2124 conditional_stack_poke(cstack, IFSTATE_FALSE);
2125 }
2126 else
2127 {
2128 /*
2129 * We're within an inactive outer branch, so this entire \if block
2130 * will be ignored. We don't want to evaluate the expression, so push
2131 * the "ignored" stack state before scanning it.
2132 */
2133 conditional_stack_push(cstack, IFSTATE_IGNORED);
2134
2135 /* Remember current query state in case we need to restore later */
2136 save_query_text_state(scan_state, cstack, query_buf);
2137
2138 ignore_boolean_expression(scan_state);
2139 }
2140
2141 return PSQL_CMD_SKIP_LINE;
2142 }
2143
2144 /*
2145 * \elif <expr> -- alternative branch in an \if..\endif block
2146 *
2147 * <expr> is evaluated the same as in \if <expr>.
2148 */
2149 static backslashResult
2150 exec_command_elif(PsqlScanState scan_state, ConditionalStack cstack,
2151 PQExpBuffer query_buf)
2152 {
2153 bool success = true;
2154
2155 switch (conditional_stack_peek(cstack))
2156 {
2157 case IFSTATE_TRUE:
2158
2159 /*
2160 * Just finished active branch of this \if block. Update saved
2161 * state so we will keep whatever data was put in query_buf by the
2162 * active branch.
2163 */
2164 save_query_text_state(scan_state, cstack, query_buf);
2165
2166 /*
2167 * Discard \elif expression and ignore the rest until \endif.
2168 * Switch state before reading expression to ensure proper lexer
2169 * behavior.
2170 */
2171 conditional_stack_poke(cstack, IFSTATE_IGNORED);
2172 ignore_boolean_expression(scan_state);
2173 break;
2174 case IFSTATE_FALSE:
2175
2176 /*
2177 * Discard any query text added by the just-skipped branch.
2178 */
2179 discard_query_text(scan_state, cstack, query_buf);
2180
2181 /*
2182 * Have not yet found a true expression in this \if block, so this
2183 * might be the first. We have to change state before examining
2184 * the expression, or the lexer won't do the right thing.
2185 */
2186 conditional_stack_poke(cstack, IFSTATE_TRUE);
2187 if (!is_true_boolean_expression(scan_state, "\\elif expression"))
2188 conditional_stack_poke(cstack, IFSTATE_FALSE);
2189 break;
2190 case IFSTATE_IGNORED:
2191
2192 /*
2193 * Discard any query text added by the just-skipped branch.
2194 */
2195 discard_query_text(scan_state, cstack, query_buf);
2196
2197 /*
2198 * Skip expression and move on. Either the \if block already had
2199 * an active section, or whole block is being skipped.
2200 */
2201 ignore_boolean_expression(scan_state);
2202 break;
2203 case IFSTATE_ELSE_TRUE:
2204 case IFSTATE_ELSE_FALSE:
2205 pg_log_error("\\elif: cannot occur after \\else");
2206 success = false;
2207 break;
2208 case IFSTATE_NONE:
2209 /* no \if to elif from */
2210 pg_log_error("\\elif: no matching \\if");
2211 success = false;
2212 break;
2213 }
2214
2215 return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
2216 }
2217
2218 /*
2219 * \else -- final alternative in an \if..\endif block
2220 *
2221 * Statements within an \else branch will only be executed if
2222 * all previous \if and \elif expressions evaluated to false
2223 * and the block was not itself being ignored.
2224 */
2225 static backslashResult
2226 exec_command_else(PsqlScanState scan_state, ConditionalStack cstack,
2227 PQExpBuffer query_buf)
2228 {
2229 bool success = true;
2230
2231 switch (conditional_stack_peek(cstack))
2232 {
2233 case IFSTATE_TRUE:
2234
2235 /*
2236 * Just finished active branch of this \if block. Update saved
2237 * state so we will keep whatever data was put in query_buf by the
2238 * active branch.
2239 */
2240 save_query_text_state(scan_state, cstack, query_buf);
2241
2242 /* Now skip the \else branch */
2243 conditional_stack_poke(cstack, IFSTATE_ELSE_FALSE);
2244 break;
2245 case IFSTATE_FALSE:
2246
2247 /*
2248 * Discard any query text added by the just-skipped branch.
2249 */
2250 discard_query_text(scan_state, cstack, query_buf);
2251
2252 /*
2253 * We've not found any true \if or \elif expression, so execute
2254 * the \else branch.
2255 */
2256 conditional_stack_poke(cstack, IFSTATE_ELSE_TRUE);
2257 break;
2258 case IFSTATE_IGNORED:
2259
2260 /*
2261 * Discard any query text added by the just-skipped branch.
2262 */
2263 discard_query_text(scan_state, cstack, query_buf);
2264
2265 /*
2266 * Either we previously processed the active branch of this \if,
2267 * or the whole \if block is being skipped. Either way, skip the
2268 * \else branch.
2269 */
2270 conditional_stack_poke(cstack, IFSTATE_ELSE_FALSE);
2271 break;
2272 case IFSTATE_ELSE_TRUE:
2273 case IFSTATE_ELSE_FALSE:
2274 pg_log_error("\\else: cannot occur after \\else");
2275 success = false;
2276 break;
2277 case IFSTATE_NONE:
2278 /* no \if to else from */
2279 pg_log_error("\\else: no matching \\if");
2280 success = false;
2281 break;
2282 }
2283
2284 return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
2285 }
2286
2287 /*
2288 * \endif -- ends an \if...\endif block
2289 */
2290 static backslashResult
2291 exec_command_endif(PsqlScanState scan_state, ConditionalStack cstack,
2292 PQExpBuffer query_buf)
2293 {
2294 bool success = true;
2295
2296 switch (conditional_stack_peek(cstack))
2297 {
2298 case IFSTATE_TRUE:
2299 case IFSTATE_ELSE_TRUE:
2300 /* Close the \if block, keeping the query text */
2301 success = conditional_stack_pop(cstack);
2302 Assert(success);
2303 break;
2304 case IFSTATE_FALSE:
2305 case IFSTATE_IGNORED:
2306 case IFSTATE_ELSE_FALSE:
2307
2308 /*
2309 * Discard any query text added by the just-skipped branch.
2310 */
2311 discard_query_text(scan_state, cstack, query_buf);
2312
2313 /* Close the \if block */
2314 success = conditional_stack_pop(cstack);
2315 Assert(success);
2316 break;
2317 case IFSTATE_NONE:
2318 /* no \if to end */
2319 pg_log_error("\\endif: no matching \\if");
2320 success = false;
2321 break;
2322 }
2323
2324 return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
2325 }
2326
2327 /*
2328 * \l -- list databases
2329 */
2330 static backslashResult
2331 exec_command_list(PsqlScanState scan_state, bool active_branch, const char *cmd)
2332 {
2333 bool success = true;
2334
2335 if (active_branch)
2336 {
2337 char *pattern;
2338 bool show_verbose;
2339 unsigned short int save_expanded;
2340
2341 pattern = psql_scan_slash_option(scan_state,
2342 OT_NORMAL, NULL, true);
2343
2344 show_verbose = strchr(cmd, '+') ? true : false;
2345
2346 /* if 'x' option specified, force expanded mode */
2347 save_expanded = pset.popt.topt.expanded;
2348 if (strchr(cmd, 'x'))
2349 pset.popt.topt.expanded = 1;
2350
2351 success = listAllDbs(pattern, show_verbose);
2352
2353 /* restore original expanded mode */
2354 pset.popt.topt.expanded = save_expanded;
2355
2356 free(pattern);
2357 }
2358 else
2359 ignore_slash_options(scan_state);
2360
2361 return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
2362 }
2363
2364 /*
2365 * \lo_* -- large object operations
2366 */
2367 static backslashResult
2368 exec_command_lo(PsqlScanState scan_state, bool active_branch, const char *cmd)
2369 {
2370 backslashResult status = PSQL_CMD_SKIP_LINE;
2371 bool success = true;
2372
2373 if (active_branch)
2374 {
2375 char *opt1,
2376 *opt2;
2377
2378 opt1 = psql_scan_slash_option(scan_state,
2379 OT_NORMAL, NULL, true);
2380 opt2 = psql_scan_slash_option(scan_state,
2381 OT_NORMAL, NULL, true);
2382
2383 if (strcmp(cmd + 3, "export") == 0)
2384 {
2385 if (!opt2)
2386 {
2387 pg_log_error("\\%s: missing required argument", cmd);
2388 success = false;
2389 }
2390 else
2391 {
2392 expand_tilde(&opt2);
2393 success = do_lo_export(opt1, opt2);
2394 }
2395 }
2396
2397 else if (strcmp(cmd + 3, "import") == 0)
2398 {
2399 if (!opt1)
2400 {
2401 pg_log_error("\\%s: missing required argument", cmd);
2402 success = false;
2403 }
2404 else
2405 {
2406 expand_tilde(&opt1);
2407 success = do_lo_import(opt1, opt2);
2408 }
2409 }
2410
2411 else if (strncmp(cmd + 3, "list", 4) == 0)
2412 {
2413 bool show_verbose;
2414 unsigned short int save_expanded;
2415
2416 show_verbose = strchr(cmd, '+') ? true : false;
2417
2418 /* if 'x' option specified, force expanded mode */
2419 save_expanded = pset.popt.topt.expanded;
2420 if (strchr(cmd, 'x'))
2421 pset.popt.topt.expanded = 1;
2422
2423 success = listLargeObjects(show_verbose);
2424
2425 /* restore original expanded mode */
2426 pset.popt.topt.expanded = save_expanded;
2427 }
2428
2429 else if (strcmp(cmd + 3, "unlink") == 0)
2430 {
2431 if (!opt1)
2432 {
2433 pg_log_error("\\%s: missing required argument", cmd);
2434 success = false;
2435 }
2436 else
2437 success = do_lo_unlink(opt1);
2438 }
2439
2440 else
2441 status = PSQL_CMD_UNKNOWN;
2442
2443 free(opt1);
2444 free(opt2);
2445 }
2446 else
2447 ignore_slash_options(scan_state);
2448
2449 if (!success)
2450 status = PSQL_CMD_ERROR;
2451
2452 return status;
2453 }
2454
2455 /*
2456 * \o -- set query output
2457 */
2458 static backslashResult
2459 exec_command_out(PsqlScanState scan_state, bool active_branch)
2460 {
2461 bool success = true;
2462
2463 if (active_branch)
2464 {
2465 char *fname = psql_scan_slash_option(scan_state,
2466 OT_FILEPIPE, NULL, true);
2467
2468 expand_tilde(&fname);
2469 success = setQFout(fname);
2470 free(fname);
2471 }
2472 else
2473 ignore_slash_filepipe(scan_state);
2474
2475 return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
2476 }
2477
2478 /*
2479 * \p -- print the current query buffer
2480 */
2481 static backslashResult
2482 exec_command_print(PsqlScanState scan_state, bool active_branch,
2483 PQExpBuffer query_buf, PQExpBuffer previous_buf)
2484 {
2485 if (active_branch)
2486 {
2487 /*
2488 * We want to print the same thing \g would execute, but not to change
2489 * the query buffer state; so we can't use copy_previous_query().
2490 * Also, beware of possibility that buffer pointers are NULL.
2491 */
2492 if (query_buf && query_buf->len > 0)
2493 puts(query_buf->data);
2494 else if (previous_buf && previous_buf->len > 0)
2495 puts(previous_buf->data);
2496 else if (!pset.quiet)
2497 puts(_("Query buffer is empty."));
2498 fflush(stdout);
2499 }
2500
2501 return PSQL_CMD_SKIP_LINE;
2502 }
2503
2504 /*
2505 * \parse -- parse query
2506 */
2507 static backslashResult
2508 exec_command_parse(PsqlScanState scan_state, bool active_branch,
2509 const char *cmd)
2510 {
2511 backslashResult status = PSQL_CMD_SKIP_LINE;
2512
2513 if (active_branch)
2514 {
2515 char *opt = psql_scan_slash_option(scan_state,
2516 OT_NORMAL, NULL, false);
2517
2518 clean_extended_state();
2519
2520 if (!opt)
2521 {
2522 pg_log_error("\\%s: missing required argument", cmd);
2523 status = PSQL_CMD_ERROR;
2524 }
2525 else
2526 {
2527 pset.stmtName = opt;
2528 pset.send_mode = PSQL_SEND_EXTENDED_PARSE;
2529 status = PSQL_CMD_SEND;
2530 }
2531 }
2532 else
2533 ignore_slash_options(scan_state);
2534
2535 return status;
2536 }
2537
2538 /*
2539 * \password -- set user password
2540 */
2541 static backslashResult
2542 exec_command_password(PsqlScanState scan_state, bool active_branch)
2543 {
2544 bool success = true;
2545
2546 if (active_branch)
2547 {
2548 char *user = psql_scan_slash_option(scan_state,
2549 OT_SQLID, NULL, true);
2550 char *pw1 = NULL;
2551 char *pw2 = NULL;
2552 PQExpBufferData buf;
2553 PromptInterruptContext prompt_ctx;
2554
2555 if (user == NULL)
2556 {
2557 /* By default, the command applies to CURRENT_USER */
2558 PGresult *res;
2559
2560 res = PSQLexec("SELECT CURRENT_USER");
2561 if (!res)
2562 return PSQL_CMD_ERROR;
2563
2564 user = pg_strdup(PQgetvalue(res, 0, 0));
2565 PQclear(res);
2566 }
2567
2568 /* Set up to let SIGINT cancel simple_prompt_extended() */
2569 prompt_ctx.jmpbuf = sigint_interrupt_jmp;
2570 prompt_ctx.enabled = &sigint_interrupt_enabled;
2571 prompt_ctx.canceled = false;
2572
2573 initPQExpBuffer(&buf);
2574 printfPQExpBuffer(&buf, _("Enter new password for user \"%s\": "), user);
2575
2576 pw1 = simple_prompt_extended(buf.data, false, &prompt_ctx);
2577 if (!prompt_ctx.canceled)
2578 pw2 = simple_prompt_extended("Enter it again: ", false, &prompt_ctx);
2579
2580 if (prompt_ctx.canceled)
2581 {
2582 /* fail silently */
2583 success = false;
2584 }
2585 else if (strcmp(pw1, pw2) != 0)
2586 {
2587 pg_log_error("Passwords didn't match.");
2588 success = false;
2589 }
2590 else
2591 {
2592 PGresult *res = PQchangePassword(pset.db, user, pw1);
2593
2594 if (PQresultStatus(res) != PGRES_COMMAND_OK)
2595 {
2596 pg_log_info("%s", PQerrorMessage(pset.db));
2597 success = false;
2598 }
2599
2600 PQclear(res);
2601 }
2602
2603 free(user);
2604 free(pw1);
2605 free(pw2);
2606 termPQExpBuffer(&buf);
2607 }
2608 else
2609 ignore_slash_options(scan_state);
2610
2611 return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
2612 }
2613
2614 /*
2615 * \prompt -- prompt and set variable
2616 */
2617 static backslashResult
2618 exec_command_prompt(PsqlScanState scan_state, bool active_branch,
2619 const char *cmd)
2620 {
2621 bool success = true;
2622
2623 if (active_branch)
2624 {
2625 char *opt,
2626 *prompt_text = NULL;
2627 char *arg1,
2628 *arg2;
2629
2630 arg1 = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false);
2631 arg2 = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false);
2632
2633 if (!arg1)
2634 {
2635 pg_log_error("\\%s: missing required argument", cmd);
2636 success = false;
2637 }
2638 else
2639 {
2640 char *result;
2641 PromptInterruptContext prompt_ctx;
2642
2643 /* Set up to let SIGINT cancel simple_prompt_extended() */
2644 prompt_ctx.jmpbuf = sigint_interrupt_jmp;
2645 prompt_ctx.enabled = &sigint_interrupt_enabled;
2646 prompt_ctx.canceled = false;
2647
2648 if (arg2)
2649 {
2650 prompt_text = arg1;
2651 opt = arg2;
2652 }
2653 else
2654 opt = arg1;
2655
2656 if (!pset.inputfile)
2657 {
2658 result = simple_prompt_extended(prompt_text, true, &prompt_ctx);
2659 }
2660 else
2661 {
2662 if (prompt_text)
2663 {
2664 fputs(prompt_text, stdout);
2665 fflush(stdout);
2666 }
2667 result = gets_fromFile(stdin);
2668 if (!result)
2669 {
2670 pg_log_error("\\%s: could not read value for variable",
2671 cmd);
2672 success = false;
2673 }
2674 }
2675
2676 if (prompt_ctx.canceled ||
2677 (result && !SetVariable(pset.vars, opt, result)))
2678 success = false;
2679
2680 free(result);
2681 free(prompt_text);
2682 free(opt);
2683 }
2684 }
2685 else
2686 ignore_slash_options(scan_state);
2687
2688 return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
2689 }
2690
2691 /*
2692 * \pset -- set printing parameters
2693 */
2694 static backslashResult
2695 exec_command_pset(PsqlScanState scan_state, bool active_branch)
2696 {
2697 bool success = true;
2698
2699 if (active_branch)
2700 {
2701 char *opt0 = psql_scan_slash_option(scan_state,
2702 OT_NORMAL, NULL, false);
2703 char *opt1 = psql_scan_slash_option(scan_state,
2704 OT_NORMAL, NULL, false);
2705
2706 if (!opt0)
2707 {
2708 /* list all variables */
2709
2710 int i;
2711 static const char *const my_list[] = {
2712 "border", "columns", "csv_fieldsep", "expanded", "fieldsep",
2713 "fieldsep_zero", "footer", "format", "linestyle", "null",
2714 "numericlocale", "pager", "pager_min_lines",
2715 "recordsep", "recordsep_zero",
2716 "tableattr", "title", "tuples_only",
2717 "unicode_border_linestyle",
2718 "unicode_column_linestyle",
2719 "unicode_header_linestyle",
2720 "xheader_width",
2721 NULL
2722 };
2723
2724 for (i = 0; my_list[i] != NULL; i++)
2725 {
2726 char *val = pset_value_string(my_list[i], &pset.popt);
2727
2728 printf("%-24s %s\n", my_list[i], val);
2729 free(val);
2730 }
2731
2732 success = true;
2733 }
2734 else
2735 success = do_pset(opt0, opt1, &pset.popt, pset.quiet);
2736
2737 free(opt0);
2738 free(opt1);
2739 }
2740 else
2741 ignore_slash_options(scan_state);
2742
2743 return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
2744 }
2745
2746 /*
2747 * \q or \quit -- exit psql
2748 */
2749 static backslashResult
2750 exec_command_quit(PsqlScanState scan_state, bool active_branch)
2751 {
2752 backslashResult status = PSQL_CMD_SKIP_LINE;
2753
2754 if (active_branch)
2755 status = PSQL_CMD_TERMINATE;
2756
2757 return status;
2758 }
2759
2760 /*
2761 * \r -- reset (clear) the query buffer
2762 */
2763 static backslashResult
2764 exec_command_reset(PsqlScanState scan_state, bool active_branch,
2765 PQExpBuffer query_buf)
2766 {
2767 if (active_branch)
2768 {
2769 resetPQExpBuffer(query_buf);
2770 psql_scan_reset(scan_state);
2771 if (!pset.quiet)
2772 puts(_("Query buffer reset (cleared)."));
2773 }
2774
2775 return PSQL_CMD_SKIP_LINE;
2776 }
2777
2778 /*
2779 * \restrict -- enter "restricted mode" with the provided key
2780 */
2781 static backslashResult
2782 exec_command_restrict(PsqlScanState scan_state, bool active_branch,
2783 const char *cmd)
2784 {
2785 if (active_branch)
2786 {
2787 char *opt;
2788
2789 Assert(!restricted);
2790
2791 /*
2792 * Unlike \unrestrict, this argument may safely undergo backquote and
2793 * variable expansion: HandleSlashCmds() rejects \restrict in
2794 * restricted mode before its argument is scanned, so we only get here
2795 * when the input could execute such things anyway.
2796 */
2797 opt = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, true);
2798 if (opt == NULL || opt[0] == '\0')
2799 {
2800 pg_log_error("\\%s: missing required argument", cmd);
2801 return PSQL_CMD_ERROR;
2802 }
2803
2804 restrict_key = pstrdup(opt);
2805 restricted = true;
2806 }
2807 else
2808 ignore_slash_options(scan_state);
2809
2810 return PSQL_CMD_SKIP_LINE;
2811 }
2812
2813 /*
2814 * \s -- save history in a file or show it on the screen
2815 */
2816 static backslashResult
2817 exec_command_s(PsqlScanState scan_state, bool active_branch)
2818 {
2819 bool success = true;
2820
2821 if (active_branch)
2822 {
2823 char *fname = psql_scan_slash_option(scan_state,
2824 OT_NORMAL, NULL, true);
2825
2826 expand_tilde(&fname);
2827 success = printHistory(fname, pset.popt.topt.pager);
2828 if (success && !pset.quiet && fname)
2829 printf(_("Wrote history to file \"%s\".\n"), fname);
2830 if (!fname)
2831 putchar('\n');
2832 free(fname);
2833 }
2834 else
2835 ignore_slash_options(scan_state);
2836
2837 return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
2838 }
2839
2840 /*
2841 * \sendpipeline -- send an extended query to an ongoing pipeline
2842 */
2843 static backslashResult
2844 exec_command_sendpipeline(PsqlScanState scan_state, bool active_branch)
2845 {
2846 backslashResult status = PSQL_CMD_SKIP_LINE;
2847
2848 if (active_branch)
2849 {
2850 if (PQpipelineStatus(pset.db) != PQ_PIPELINE_OFF)
2851 {
2852 if (pset.send_mode == PSQL_SEND_EXTENDED_QUERY_PREPARED ||
2853 pset.send_mode == PSQL_SEND_EXTENDED_QUERY_PARAMS)
2854 {
2855 status = PSQL_CMD_SEND;
2856 }
2857 else
2858 {
2859 pg_log_error("\\sendpipeline must be used after \\bind or \\bind_named");
2860 clean_extended_state();
2861 return PSQL_CMD_ERROR;
2862 }
2863 }
2864 else
2865 {
2866 pg_log_error("\\sendpipeline not allowed outside of pipeline mode");
2867 clean_extended_state();
2868 return PSQL_CMD_ERROR;
2869 }
2870 }
2871 else
2872 ignore_slash_options(scan_state);
2873
2874 return status;
2875 }
2876
2877 /*
2878 * \set -- set variable
2879 */
2880 static backslashResult
2881 exec_command_set(PsqlScanState scan_state, bool active_branch)
2882 {
2883 bool success = true;
2884
2885 if (active_branch)
2886 {
2887 char *opt0 = psql_scan_slash_option(scan_state,
2888 OT_NORMAL, NULL, false);
2889
2890 if (!opt0)
2891 {
2892 /* list all variables */
2893 PrintVariables(pset.vars);
2894 success = true;
2895 }
2896 else
2897 {
2898 /*
2899 * Set variable to the concatenation of the arguments.
2900 */
2901 char *newval;
2902 char *opt;
2903
2904 opt = psql_scan_slash_option(scan_state,
2905 OT_NORMAL, NULL, false);
2906 newval = pg_strdup(opt ? opt : "");
2907 free(opt);
2908
2909 while ((opt = psql_scan_slash_option(scan_state,
2910 OT_NORMAL, NULL, false)))
2911 {
2912 newval = pg_realloc(newval, strlen(newval) + strlen(opt) + 1);
2913 strcat(newval, opt);
2914 free(opt);
2915 }
2916
2917 if (!SetVariable(pset.vars, opt0, newval))
2918 success = false;
2919
2920 free(newval);
2921 }
2922 free(opt0);
2923 }
2924 else
2925 ignore_slash_options(scan_state);
2926
2927 return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
2928 }
2929
2930 /*
2931 * \setenv -- set environment variable
2932 */
2933 static backslashResult
2934 exec_command_setenv(PsqlScanState scan_state, bool active_branch,
2935 const char *cmd)
2936 {
2937 bool success = true;
2938
2939 if (active_branch)
2940 {
2941 char *envvar = psql_scan_slash_option(scan_state,
2942 OT_NORMAL, NULL, false);
2943 char *envval = psql_scan_slash_option(scan_state,
2944 OT_NORMAL, NULL, false);
2945
2946 if (!envvar)
2947 {
2948 pg_log_error("\\%s: missing required argument", cmd);
2949 success = false;
2950 }
2951 else if (strchr(envvar, '=') != NULL)
2952 {
2953 pg_log_error("\\%s: environment variable name must not contain \"=\"",
2954 cmd);
2955 success = false;
2956 }
2957 else if (!envval)
2958 {
2959 /* No argument - unset the environment variable */
2960 unsetenv(envvar);
2961 success = true;
2962 }
2963 else
2964 {
2965 /* Set variable to the value of the next argument */
2966 setenv(envvar, envval, 1);
2967 success = true;
2968 }
2969 free(envvar);
2970 free(envval);
2971 }
2972 else
2973 ignore_slash_options(scan_state);
2974
2975 return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
2976 }
2977
2978 /*
2979 * \sf/\sv -- show a function/view's source code
2980 */
2981 static backslashResult
2982 exec_command_sf_sv(PsqlScanState scan_state, bool active_branch,
2983 const char *cmd, bool is_func)
2984 {
2985 backslashResult status = PSQL_CMD_SKIP_LINE;
2986
2987 if (active_branch)
2988 {
2989 bool show_linenumbers = (strchr(cmd, '+') != NULL);
2990 PQExpBuffer buf;
2991 char *obj_desc;
2992 Oid obj_oid = InvalidOid;
2993 EditableObjectType eot = is_func ? EditableFunction : EditableView;
2994
2995 buf = createPQExpBuffer();
2996 obj_desc = psql_scan_slash_option(scan_state,
2997 OT_WHOLE_LINE, NULL, true);
2998 if (!obj_desc)
2999 {
3000 if (is_func)
3001 pg_log_error("function name is required");
3002 else
3003 pg_log_error("view name is required");
3004 status = PSQL_CMD_ERROR;
3005 }
3006 else if (!lookup_object_oid(eot, obj_desc, &obj_oid))
3007 {
3008 /* error already reported */
3009 status = PSQL_CMD_ERROR;
3010 }
3011 else if (!get_create_object_cmd(eot, obj_oid, buf))
3012 {
3013 /* error already reported */
3014 status = PSQL_CMD_ERROR;
3015 }
3016 else
3017 {
3018 FILE *output;
3019 bool is_pager;
3020
3021 /* Select output stream: stdout, pager, or file */
3022 if (pset.queryFout == stdout)
3023 {
3024 /* count lines in function to see if pager is needed */
3025 int lineno = count_lines_in_buf(buf);
3026
3027 output = PageOutput(lineno, &(pset.popt.topt));
3028 is_pager = true;
3029 }
3030 else
3031 {
3032 /* use previously set output file, without pager */
3033 output = pset.queryFout;
3034 is_pager = false;
3035 }
3036
3037 if (show_linenumbers)
3038 {
3039 /* add line numbers */
3040 print_with_linenumbers(output, buf->data, is_func);
3041 }
3042 else
3043 {
3044 /* just send the definition to output */
3045 fputs(buf->data, output);
3046 }
3047
3048 if (is_pager)
3049 ClosePager(output);
3050 }
3051
3052 free(obj_desc);
3053 destroyPQExpBuffer(buf);
3054 }
3055 else
3056 ignore_slash_whole_line(scan_state);
3057
3058 return status;
3059 }
3060
3061 /*
3062 * \startpipeline -- enter pipeline mode
3063 */
3064 static backslashResult
3065 exec_command_startpipeline(PsqlScanState scan_state, bool active_branch)
3066 {
3067 backslashResult status = PSQL_CMD_SKIP_LINE;
3068
3069 if (active_branch)
3070 {
3071 pset.send_mode = PSQL_SEND_START_PIPELINE_MODE;
3072 status = PSQL_CMD_SEND;
3073 }
3074 else
3075 ignore_slash_options(scan_state);
3076
3077 return status;
3078 }
3079
3080 /*
3081 * \syncpipeline -- send a sync message to an active pipeline
3082 */
3083 static backslashResult
3084 exec_command_syncpipeline(PsqlScanState scan_state, bool active_branch)
3085 {
3086 backslashResult status = PSQL_CMD_SKIP_LINE;
3087
3088 if (active_branch)
3089 {
3090 pset.send_mode = PSQL_SEND_PIPELINE_SYNC;
3091 status = PSQL_CMD_SEND;
3092 }
3093 else
3094 ignore_slash_options(scan_state);
3095
3096 return status;
3097 }
3098
3099 /*
3100 * \endpipeline -- end pipeline mode
3101 */
3102 static backslashResult
3103 exec_command_endpipeline(PsqlScanState scan_state, bool active_branch)
3104 {
3105 backslashResult status = PSQL_CMD_SKIP_LINE;
3106
3107 if (active_branch)
3108 {
3109 pset.send_mode = PSQL_SEND_END_PIPELINE_MODE;
3110 status = PSQL_CMD_SEND;
3111 }
3112 else
3113 ignore_slash_options(scan_state);
3114
3115 return status;
3116 }
3117
3118 /*
3119 * \t -- turn off table headers and row count
3120 */
3121 static backslashResult
3122 exec_command_t(PsqlScanState scan_state, bool active_branch)
3123 {
3124 bool success = true;
3125
3126 if (active_branch)
3127 {
3128 char *opt = psql_scan_slash_option(scan_state,
3129 OT_NORMAL, NULL, true);
3130
3131 success = do_pset("tuples_only", opt, &pset.popt, pset.quiet);
3132 free(opt);
3133 }
3134 else
3135 ignore_slash_options(scan_state);
3136
3137 return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
3138 }
3139
3140 /*
3141 * \T -- define html <table ...> attributes
3142 */
3143 static backslashResult
3144 exec_command_T(PsqlScanState scan_state, bool active_branch)
3145 {
3146 bool success = true;
3147
3148 if (active_branch)
3149 {
3150 char *value = psql_scan_slash_option(scan_state,
3151 OT_NORMAL, NULL, false);
3152
3153 success = do_pset("tableattr", value, &pset.popt, pset.quiet);
3154 free(value);
3155 }
3156 else
3157 ignore_slash_options(scan_state);
3158
3159 return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
3160 }
3161
3162 /*
3163 * \timing -- enable/disable timing of queries
3164 */
3165 static backslashResult
3166 exec_command_timing(PsqlScanState scan_state, bool active_branch)
3167 {
3168 bool success = true;
3169
3170 if (active_branch)
3171 {
3172 char *opt = psql_scan_slash_option(scan_state,
3173 OT_NORMAL, NULL, false);
3174
3175 if (opt)
3176 success = ParseVariableBool(opt, "\\timing", &pset.timing);
3177 else
3178 pset.timing = !pset.timing;
3179 if (!pset.quiet)
3180 {
3181 if (pset.timing)
3182 puts(_("Timing is on."));
3183 else
3184 puts(_("Timing is off."));
3185 }
3186 free(opt);
3187 }
3188 else
3189 ignore_slash_options(scan_state);
3190
3191 return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
3192 }
3193
3194 /*
3195 * \unrestrict -- exit "restricted mode" if provided key matches
3196 */
3197 static backslashResult
3198 exec_command_unrestrict(PsqlScanState scan_state, bool active_branch,
3199 const char *cmd)
3200 {
3201 if (active_branch)
3202 {
3203 char *opt;
3204
3205 opt = psql_scan_slash_option(scan_state, OT_WHOLE_LINE, NULL, true);
3206 if (opt == NULL || opt[0] == '\0')
3207 {
3208 pg_log_error("\\%s: missing required argument", cmd);
3209 return PSQL_CMD_ERROR;
3210 }
3211
3212 if (!restricted)
3213 {
3214 pg_log_error("\\%s: not currently in restricted mode", cmd);
3215 return PSQL_CMD_ERROR;
3216 }
3217 else if (strcmp(opt, restrict_key) == 0)
3218 {
3219 pfree(restrict_key);
3220 restricted = false;
3221 }
3222 else
3223 {
3224 pg_log_error("\\%s: wrong key", cmd);
3225 return PSQL_CMD_ERROR;
3226 }
3227 }
3228 else
3229 ignore_slash_whole_line(scan_state);
3230
3231 return PSQL_CMD_SKIP_LINE;
3232 }
3233
3234 /*
3235 * \unset -- unset variable
3236 */
3237 static backslashResult
3238 exec_command_unset(PsqlScanState scan_state, bool active_branch,
3239 const char *cmd)
3240 {
3241 bool success = true;
3242
3243 if (active_branch)
3244 {
3245 char *opt = psql_scan_slash_option(scan_state,
3246 OT_NORMAL, NULL, false);
3247
3248 if (!opt)
3249 {
3250 pg_log_error("\\%s: missing required argument", cmd);
3251 success = false;
3252 }
3253 else if (!SetVariable(pset.vars, opt, NULL))
3254 success = false;
3255
3256 free(opt);
3257 }
3258 else
3259 ignore_slash_options(scan_state);
3260
3261 return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
3262 }
3263
3264 /*
3265 * \w -- write query buffer to file
3266 */
3267 static backslashResult
3268 exec_command_write(PsqlScanState scan_state, bool active_branch,
3269 const char *cmd,
3270 PQExpBuffer query_buf, PQExpBuffer previous_buf)
3271 {
3272 backslashResult status = PSQL_CMD_SKIP_LINE;
3273
3274 if (active_branch)
3275 {
3276 char *fname = psql_scan_slash_option(scan_state,
3277 OT_FILEPIPE, NULL, true);
3278 FILE *fd = NULL;
3279 bool is_pipe = false;
3280
3281 if (!query_buf)
3282 {
3283 pg_log_error("no query buffer");
3284 status = PSQL_CMD_ERROR;
3285 }
3286 else
3287 {
3288 if (!fname)
3289 {
3290 pg_log_error("\\%s: missing required argument", cmd);
3291 status = PSQL_CMD_ERROR;
3292 }
3293 else
3294 {
3295 expand_tilde(&fname);
3296 if (fname[0] == '|')
3297 {
3298 is_pipe = true;
3299 fflush(NULL);
3300 disable_sigpipe_trap();
3301 fd = popen(&fname[1], "w");
3302 }
3303 else
3304 {
3305 canonicalize_path_enc(fname, pset.encoding);
3306 fd = fopen(fname, "w");
3307 }
3308 if (!fd)
3309 {
3310 pg_log_error("%s: %m", fname);
3311 status = PSQL_CMD_ERROR;
3312 }
3313 }
3314 }
3315
3316 if (fd)
3317 {
3318 int result;
3319
3320 /*
3321 * We want to print the same thing \g would execute, but not to
3322 * change the query buffer state; so we can't use
3323 * copy_previous_query(). Also, beware of possibility that buffer
3324 * pointers are NULL.
3325 */
3326 if (query_buf && query_buf->len > 0)
3327 fprintf(fd, "%s\n", query_buf->data);
3328 else if (previous_buf && previous_buf->len > 0)
3329 fprintf(fd, "%s\n", previous_buf->data);
3330
3331 if (is_pipe)
3332 {
3333 result = pclose(fd);
3334
3335 if (result != 0)
3336 {
3337 pg_log_error("%s: %s", fname, wait_result_to_str(result));
3338 status = PSQL_CMD_ERROR;
3339 }
3340 SetShellResultVariables(result);
3341 }
3342 else
3343 {
3344 result = fclose(fd);
3345
3346 if (result == EOF)
3347 {
3348 pg_log_error("%s: %m", fname);
3349 status = PSQL_CMD_ERROR;
3350 }
3351 }
3352 }
3353
3354 if (is_pipe)
3355 restore_sigpipe_trap();
3356
3357 free(fname);
3358 }
3359 else
3360 ignore_slash_filepipe(scan_state);
3361
3362 return status;
3363 }
3364
3365 /*
3366 * \watch -- execute a query every N seconds.
3367 * Optionally, stop after M iterations.
3368 */
3369 static backslashResult
3370 exec_command_watch(PsqlScanState scan_state, bool active_branch,
3371 PQExpBuffer query_buf, PQExpBuffer previous_buf)
3372 {
3373 bool success = true;
3374
3375 if (active_branch)
3376 {
3377 bool have_sleep = false;
3378 bool have_iter = false;
3379 bool have_min_rows = false;
3380 double sleep = pset.watch_interval;
3381 int iter = 0;
3382 int min_rows = 0;
3383
3384 if (PQpipelineStatus(pset.db) != PQ_PIPELINE_OFF)
3385 {
3386 pg_log_error("\\%s not allowed in pipeline mode", "watch");
3387 clean_extended_state();
3388 success = false;
3389 }
3390
3391 /*
3392 * Parse arguments. We allow either an unlabeled interval or
3393 * "name=value", where name is from the set ('i', 'interval', 'c',
3394 * 'count', 'm', 'min_rows'). The parsing of interval value should be
3395 * kept in sync with ParseVariableDouble which is used for setting the
3396 * default interval value.
3397 */
3398 while (success)
3399 {
3400 char *opt = psql_scan_slash_option(scan_state,
3401 OT_NORMAL, NULL, true);
3402 char *valptr;
3403 char *opt_end;
3404
3405 if (!opt)
3406 break; /* no more arguments */
3407
3408 valptr = strchr(opt, '=');
3409 if (valptr)
3410 {
3411 /* Labeled argument */
3412 valptr++;
3413 if (strncmp("i=", opt, strlen("i=")) == 0 ||
3414 strncmp("interval=", opt, strlen("interval=")) == 0)
3415 {
3416 if (have_sleep)
3417 {
3418 pg_log_error("\\watch: interval value is specified more than once");
3419 success = false;
3420 }
3421 else
3422 {
3423 have_sleep = true;
3424 errno = 0;
3425 sleep = strtod(valptr, &opt_end);
3426 if (sleep < 0 || *opt_end || errno == ERANGE)
3427 {
3428 pg_log_error("\\watch: incorrect interval value \"%s\"", valptr);
3429 success = false;
3430 }
3431 }
3432 }
3433 else if (strncmp("c=", opt, strlen("c=")) == 0 ||
3434 strncmp("count=", opt, strlen("count=")) == 0)
3435 {
3436 if (have_iter)
3437 {
3438 pg_log_error("\\watch: iteration count is specified more than once");
3439 success = false;
3440 }
3441 else
3442 {
3443 have_iter = true;
3444 errno = 0;
3445 iter = strtoint(valptr, &opt_end, 10);
3446 if (iter <= 0 || *opt_end || errno == ERANGE)
3447 {
3448 pg_log_error("\\watch: incorrect iteration count \"%s\"", valptr);
3449 success = false;
3450 }
3451 }
3452 }
3453 else if (strncmp("m=", opt, strlen("m=")) == 0 ||
3454 strncmp("min_rows=", opt, strlen("min_rows=")) == 0)
3455 {
3456 if (have_min_rows)
3457 {
3458 pg_log_error("\\watch: minimum row count specified more than once");
3459 success = false;
3460 }
3461 else
3462 {
3463 have_min_rows = true;
3464 errno = 0;
3465 min_rows = strtoint(valptr, &opt_end, 10);
3466 if (min_rows <= 0 || *opt_end || errno == ERANGE)
3467 {
3468 pg_log_error("\\watch: incorrect minimum row count \"%s\"", valptr);
3469 success = false;
3470 }
3471 }
3472 }
3473 else
3474 {
3475 pg_log_error("\\watch: unrecognized parameter \"%s\"", opt);
3476 success = false;
3477 }
3478 }
3479 else
3480 {
3481 /* Unlabeled argument: take it as interval */
3482 if (have_sleep)
3483 {
3484 pg_log_error("\\watch: interval value is specified more than once");
3485 success = false;
3486 }
3487 else
3488 {
3489 have_sleep = true;
3490 errno = 0;
3491 sleep = strtod(opt, &opt_end);
3492 if (sleep < 0 || *opt_end || errno == ERANGE)
3493 {
3494 pg_log_error("\\watch: incorrect interval value \"%s\"", opt);
3495 success = false;
3496 }
3497 }
3498 }
3499
3500 free(opt);
3501 }
3502
3503 /* If we parsed arguments successfully, do the command */
3504 if (success)
3505 {
3506 /* If query_buf is empty, recall and execute previous query */
3507 (void) copy_previous_query(query_buf, previous_buf);
3508
3509 success = do_watch(query_buf, sleep, iter, min_rows);
3510 }
3511
3512 /* Reset the query buffer as though for \r */
3513 resetPQExpBuffer(query_buf);
3514 psql_scan_reset(scan_state);
3515 }
3516 else
3517 ignore_slash_options(scan_state);
3518
3519 return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
3520 }
3521
3522 /*
3523 * \x -- set or toggle expanded table representation
3524 */
3525 static backslashResult
3526 exec_command_x(PsqlScanState scan_state, bool active_branch)
3527 {
3528 bool success = true;
3529
3530 if (active_branch)
3531 {
3532 char *opt = psql_scan_slash_option(scan_state,
3533 OT_NORMAL, NULL, true);
3534
3535 success = do_pset("expanded", opt, &pset.popt, pset.quiet);
3536 free(opt);
3537 }
3538 else
3539 ignore_slash_options(scan_state);
3540
3541 return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
3542 }
3543
3544 /*
3545 * \z -- list table privileges (equivalent to \dp)
3546 */
3547 static backslashResult
3548 exec_command_z(PsqlScanState scan_state, bool active_branch, const char *cmd)
3549 {
3550 bool success = true;
3551
3552 if (active_branch)
3553 {
3554 char *pattern;
3555 bool show_system;
3556 unsigned short int save_expanded;
3557
3558 pattern = psql_scan_slash_option(scan_state,
3559 OT_NORMAL, NULL, true);
3560
3561 show_system = strchr(cmd, 'S') ? true : false;
3562
3563 /* if 'x' option specified, force expanded mode */
3564 save_expanded = pset.popt.topt.expanded;
3565 if (strchr(cmd, 'x'))
3566 pset.popt.topt.expanded = 1;
3567
3568 success = permissionsList(pattern, show_system);
3569
3570 /* restore original expanded mode */
3571 pset.popt.topt.expanded = save_expanded;
3572
3573 free(pattern);
3574 }
3575 else
3576 ignore_slash_options(scan_state);
3577
3578 return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
3579 }
3580
3581 /*
3582 * \! -- execute shell command
3583 */
3584 static backslashResult
3585 exec_command_shell_escape(PsqlScanState scan_state, bool active_branch)
3586 {
3587 bool success = true;
3588
3589 if (active_branch)
3590 {
3591 char *opt = psql_scan_slash_option(scan_state,
3592 OT_WHOLE_LINE, NULL, false);
3593
3594 success = do_shell(opt);
3595 free(opt);
3596 }
3597 else
3598 ignore_slash_whole_line(scan_state);
3599
3600 return success ? PSQL_CMD_SKIP_LINE : PSQL_CMD_ERROR;
3601 }
3602
3603 /*
3604 * \? -- print help about backslash commands
3605 */
3606 static backslashResult
3607 exec_command_slash_command_help(PsqlScanState scan_state, bool active_branch)
3608 {
3609 if (active_branch)
3610 {
3611 char *opt0 = psql_scan_slash_option(scan_state,
3612 OT_NORMAL, NULL, false);
3613
3614 if (!opt0 || strcmp(opt0, "commands") == 0)
3615 slashUsage(pset.popt.topt.pager);
3616 else if (strcmp(opt0, "options") == 0)
3617 usage(pset.popt.topt.pager);
3618 else if (strcmp(opt0, "variables") == 0)
3619 helpVariables(pset.popt.topt.pager);
3620 else
3621 slashUsage(pset.popt.topt.pager);
3622
3623 free(opt0);
3624 }
3625 else
3626 ignore_slash_options(scan_state);
3627
3628 return PSQL_CMD_SKIP_LINE;
3629 }
3630
3631
3632 /*
3633 * Read and interpret an argument to the \connect slash command.
3634 *
3635 * Returns a malloc'd string, or NULL if no/empty argument.
3636 */
3637 static char *
3638 read_connect_arg(PsqlScanState scan_state)
3639 {
3640 char *result;
3641 char quote;
3642
3643 /*
3644 * Ideally we should treat the arguments as SQL identifiers. But for
3645 * backwards compatibility with 7.2 and older pg_dump files, we have to
3646 * take unquoted arguments verbatim (don't downcase them). For now,
3647 * double-quoted arguments may be stripped of double quotes (as if SQL
3648 * identifiers). By 7.4 or so, pg_dump files can be expected to
3649 * double-quote all mixed-case \connect arguments, and then we can get rid
3650 * of OT_SQLIDHACK.
3651 */
3652 result = psql_scan_slash_option(scan_state, OT_SQLIDHACK, &quote, true);
3653
3654 if (!result)
3655 return NULL;
3656
3657 if (quote)
3658 return result;
3659
3660 if (*result == '\0' || strcmp(result, "-") == 0)
3661 {
3662 free(result);
3663 return NULL;
3664 }
3665
3666 return result;
3667 }
3668
3669 /*
3670 * Read a boolean expression, return it as a PQExpBuffer string.
3671 *
3672 * Note: anything more or less than one token will certainly fail to be
3673 * parsed by ParseVariableBool, so we don't worry about complaining here.
3674 * This routine's return data structure will need to be rethought anyway
3675 * to support likely future extensions such as "\if defined VARNAME".
3676 */
3677 static PQExpBuffer
3678 gather_boolean_expression(PsqlScanState scan_state)
3679 {
3680 PQExpBuffer exp_buf = createPQExpBuffer();
3681 int num_options = 0;
3682 char *value;
3683
3684 /* collect all arguments for the conditional command into exp_buf */
3685 while ((value = psql_scan_slash_option(scan_state,
3686 OT_NORMAL, NULL, false)) != NULL)
3687 {
3688 /* add spaces between tokens */
3689 if (num_options > 0)
3690 appendPQExpBufferChar(exp_buf, ' ');
3691 appendPQExpBufferStr(exp_buf, value);
3692 num_options++;
3693 free(value);
3694 }
3695
3696 return exp_buf;
3697 }
3698
3699 /*
3700 * Read a boolean expression, return true if the expression
3701 * was a valid boolean expression that evaluated to true.
3702 * Otherwise return false.
3703 *
3704 * Note: conditional stack's top state must be active, else lexer will
3705 * fail to expand variables and backticks.
3706 */
3707 static bool
3708 is_true_boolean_expression(PsqlScanState scan_state, const char *name)
3709 {
3710 PQExpBuffer buf = gather_boolean_expression(scan_state);
3711 bool value = false;
3712 bool success = ParseVariableBool(buf->data, name, &value);
3713
3714 destroyPQExpBuffer(buf);
3715 return success && value;
3716 }
3717
3718 /*
3719 * Read a boolean expression, but do nothing with it.
3720 *
3721 * Note: conditional stack's top state must be INACTIVE, else lexer will
3722 * expand variables and backticks, which we do not want here.
3723 */
3724 static void
3725 ignore_boolean_expression(PsqlScanState scan_state)
3726 {
3727 PQExpBuffer buf = gather_boolean_expression(scan_state);
3728
3729 destroyPQExpBuffer(buf);
3730 }
3731
3732 /*
3733 * Read and discard "normal" slash command options.
3734 *
3735 * This should be used for inactive-branch processing of any slash command
3736 * that eats one or more OT_NORMAL, OT_SQLID, or OT_SQLIDHACK parameters.
3737 * We don't need to worry about exactly how many it would eat, since the
3738 * cleanup logic in HandleSlashCmds would silently discard any extras anyway.
3739 */
3740 static void
3741 ignore_slash_options(PsqlScanState scan_state)
3742 {
3743 char *arg;
3744
3745 while ((arg = psql_scan_slash_option(scan_state,
3746 OT_NORMAL, NULL, false)) != NULL)
3747 free(arg);
3748 }
3749
3750 /*
3751 * Read and discard FILEPIPE slash command argument.
3752 *
3753 * This *MUST* be used for inactive-branch processing of any slash command
3754 * that takes an OT_FILEPIPE option. Otherwise we might consume a different
3755 * amount of option text in active and inactive cases.
3756 */
3757 static void
3758 ignore_slash_filepipe(PsqlScanState scan_state)
3759 {
3760 char *arg = psql_scan_slash_option(scan_state,
3761 OT_FILEPIPE, NULL, false);
3762
3763 free(arg);
3764 }
3765
3766 /*
3767 * Read and discard whole-line slash command argument.
3768 *
3769 * This *MUST* be used for inactive-branch processing of any slash command
3770 * that takes an OT_WHOLE_LINE option. Otherwise we might consume a different
3771 * amount of option text in active and inactive cases.
3772 *
3773 * Note: although callers might pass "semicolon" as either true or false,
3774 * we need not duplicate that here, since it doesn't affect the amount of
3775 * input text consumed.
3776 */
3777 static void
3778 ignore_slash_whole_line(PsqlScanState scan_state)
3779 {
3780 char *arg = psql_scan_slash_option(scan_state,
3781 OT_WHOLE_LINE, NULL, false);
3782
3783 free(arg);
3784 }
3785
3786 /*
3787 * Return true if the command given is a branching command.
3788 */
3789 static bool
3790 is_branching_command(const char *cmd)
3791 {
3792 return (strcmp(cmd, "if") == 0 ||
3793 strcmp(cmd, "elif") == 0 ||
3794 strcmp(cmd, "else") == 0 ||
3795 strcmp(cmd, "endif") == 0);
3796 }
3797
3798 /*
3799 * Prepare to possibly restore query buffer to its current state
3800 * (cf. discard_query_text).
3801 *
3802 * We need to remember the length of the query buffer, and assorted
3803 * lexer internal state such as parenthesis nesting depth.
3804 */
3805 static void
3806 save_query_text_state(PsqlScanState scan_state, ConditionalStack cstack,
3807 PQExpBuffer query_buf)
3808 {
3809 if (query_buf)
3810 conditional_stack_set_query_len(cstack, query_buf->len);
3811 conditional_stack_set_lex_state(cstack,
3812 psql_scan_get_lex_state(scan_state));
3813 }
3814
3815 /*
3816 * Discard any query text absorbed during an inactive conditional branch.
3817 *
3818 * We must discard data that was appended to query_buf during an inactive
3819 * \if branch. We don't have to do anything there if there's no query_buf.
3820 *
3821 * Also, reset the lexer's state to what it was before.
3822 */
3823 static void
3824 discard_query_text(PsqlScanState scan_state, ConditionalStack cstack,
3825 PQExpBuffer query_buf)
3826 {
3827 if (query_buf)
3828 {
3829 int new_len = conditional_stack_get_query_len(cstack);
3830
3831 Assert(new_len >= 0 && new_len <= query_buf->len);
3832 query_buf->len = new_len;
3833 query_buf->data[new_len] = '\0';
3834 }
3835 psql_scan_set_lex_state(scan_state,
3836 conditional_stack_get_lex_state(cstack));
3837 }
3838
3839 /*
3840 * If query_buf is empty, copy previous_buf into it.
3841 *
3842 * This is used by various slash commands for which re-execution of a
3843 * previous query is a common usage. For convenience, we allow the
3844 * case of query_buf == NULL (and do nothing).
3845 *
3846 * Returns "true" if the previous query was copied into the query
3847 * buffer, else "false".
3848 */
3849 static bool
3850 copy_previous_query(PQExpBuffer query_buf, PQExpBuffer previous_buf)
3851 {
3852 if (query_buf && query_buf->len == 0)
3853 {
3854 appendPQExpBufferStr(query_buf, previous_buf->data);
3855 return true;
3856 }
3857 return false;
3858 }
3859
3860 /*
3861 * Ask the user for a password; 'username' is the username the
3862 * password is for, if one has been explicitly specified.
3863 * Returns a malloc'd string.
3864 * If 'canceled' is provided, *canceled will be set to true if the prompt
3865 * is canceled via SIGINT, and to false otherwise.
3866 */
3867 static char *
3868 prompt_for_password(const char *username, bool *canceled)
3869 {
3870 char *result;
3871 PromptInterruptContext prompt_ctx;
3872
3873 /* Set up to let SIGINT cancel simple_prompt_extended() */
3874 prompt_ctx.jmpbuf = sigint_interrupt_jmp;
3875 prompt_ctx.enabled = &sigint_interrupt_enabled;
3876 prompt_ctx.canceled = false;
3877
3878 if (username == NULL || username[0] == '\0')
3879 result = simple_prompt_extended("Password: ", false, &prompt_ctx);
3880 else
3881 {
3882 char *prompt_text;
3883
3884 prompt_text = psprintf(_("Password for user %s: "), username);
3885 result = simple_prompt_extended(prompt_text, false, &prompt_ctx);
3886 free(prompt_text);
3887 }
3888
3889 if (canceled)
3890 *canceled = prompt_ctx.canceled;
3891
3892 return result;
3893 }
3894
3895 static bool
3896 param_is_newly_set(const char *old_val, const char *new_val)
3897 {
3898 if (new_val == NULL)
3899 return false;
3900
3901 if (old_val == NULL || strcmp(old_val, new_val) != 0)
3902 return true;
3903
3904 return false;
3905 }
3906
3907 /*
3908 * do_connect -- handler for \connect
3909 *
3910 * Connects to a database with given parameters. If we are told to re-use
3911 * parameters, parameters from the previous connection are used where the
3912 * command's own options do not supply a value. Otherwise, libpq defaults
3913 * are used.
3914 *
3915 * In interactive mode, if connection fails with the given parameters,
3916 * the old connection will be kept.
3917 */
3918 static bool
3919 do_connect(enum trivalue reuse_previous_specification,
3920 char *dbname, char *user, char *host, char *port)
3921 {
3922 PGconn *o_conn = pset.db,
3923 *n_conn = NULL;
3924 PQconninfoOption *cinfo;
3925 int nconnopts = 0;
3926 bool same_host = false;
3927 char *password = NULL;
3928 char *client_encoding;
3929 bool success = true;
3930 bool keep_password = true;
3931 bool has_connection_string;
3932 bool reuse_previous;
3933
3934 has_connection_string = dbname ?
3935 recognized_connection_string(dbname) : false;
3936
3937 /* Complain if we have additional arguments after a connection string. */
3938 if (has_connection_string && (user || host || port))
3939 {
3940 pg_log_error("Do not give user, host, or port separately when using a connection string");
3941 return false;
3942 }
3943
3944 switch (reuse_previous_specification)
3945 {
3946 case TRI_YES:
3947 reuse_previous = true;
3948 break;
3949 case TRI_NO:
3950 reuse_previous = false;
3951 break;
3952 default:
3953 reuse_previous = !has_connection_string;
3954 break;
3955 }
3956
3957 /*
3958 * If we intend to re-use connection parameters, collect them out of the
3959 * old connection, then replace individual values as necessary. (We may
3960 * need to resort to looking at pset.dead_conn, if the connection died
3961 * previously.) Otherwise, obtain a PQconninfoOption array containing
3962 * libpq's defaults, and modify that. Note this function assumes that
3963 * PQconninfo, PQconndefaults, and PQconninfoParse will all produce arrays
3964 * containing the same options in the same order.
3965 */
3966 if (reuse_previous)
3967 {
3968 if (o_conn)
3969 cinfo = PQconninfo(o_conn);
3970 else if (pset.dead_conn)
3971 cinfo = PQconninfo(pset.dead_conn);
3972 else
3973 {
3974 /* This is reachable after a non-interactive \connect failure */
3975 pg_log_error("No database connection exists to re-use parameters from");
3976 return false;
3977 }
3978 }
3979 else
3980 cinfo = PQconndefaults();
3981
3982 if (cinfo)
3983 {
3984 if (has_connection_string)
3985 {
3986 /* Parse the connstring and insert values into cinfo */
3987 PQconninfoOption *replcinfo;
3988 char *errmsg;
3989
3990 replcinfo = PQconninfoParse(dbname, &errmsg);
3991 if (replcinfo)
3992 {
3993 PQconninfoOption *ci;
3994 PQconninfoOption *replci;
3995 bool have_password = false;
3996
3997 for (ci = cinfo, replci = replcinfo;
3998 ci->keyword && replci->keyword;
3999 ci++, replci++)
4000 {
4001 Assert(strcmp(ci->keyword, replci->keyword) == 0);
4002 /* Insert value from connstring if one was provided */
4003 if (replci->val)
4004 {
4005 /*
4006 * We know that both val strings were allocated by
4007 * libpq, so the least messy way to avoid memory leaks
4008 * is to swap them.
4009 */
4010 char *swap = replci->val;
4011
4012 replci->val = ci->val;
4013 ci->val = swap;
4014
4015 /*
4016 * Check whether connstring provides options affecting
4017 * password re-use. While any change in user, host,
4018 * hostaddr, or port causes us to ignore the old
4019 * connection's password, we don't force that for
4020 * dbname, since passwords aren't database-specific.
4021 */
4022 if (replci->val == NULL ||
4023 strcmp(ci->val, replci->val) != 0)
4024 {
4025 if (strcmp(replci->keyword, "user") == 0 ||
4026 strcmp(replci->keyword, "host") == 0 ||
4027 strcmp(replci->keyword, "hostaddr") == 0 ||
4028 strcmp(replci->keyword, "port") == 0)
4029 keep_password = false;
4030 }
4031 /* Also note whether connstring contains a password. */
4032 if (strcmp(replci->keyword, "password") == 0)
4033 have_password = true;
4034 }
4035 else if (!reuse_previous)
4036 {
4037 /*
4038 * When we have a connstring and are not re-using
4039 * parameters, swap *all* entries, even those not set
4040 * by the connstring. This avoids absorbing
4041 * environment-dependent defaults from the result of
4042 * PQconndefaults(). We don't want to do that because
4043 * they'd override service-file entries if the
4044 * connstring specifies a service parameter, whereas
4045 * the priority should be the other way around. libpq
4046 * can certainly recompute any defaults we don't pass
4047 * here. (In this situation, it's a bit wasteful to
4048 * have called PQconndefaults() at all, but not doing
4049 * so would require yet another major code path here.)
4050 */
4051 replci->val = ci->val;
4052 ci->val = NULL;
4053 }
4054 }
4055 Assert(ci->keyword == NULL && replci->keyword == NULL);
4056
4057 /* While here, determine how many option slots there are */
4058 nconnopts = ci - cinfo;
4059
4060 PQconninfoFree(replcinfo);
4061
4062 /*
4063 * If the connstring contains a password, tell the loop below
4064 * that we may use it, regardless of other settings (i.e.,
4065 * cinfo's password is no longer an "old" password).
4066 */
4067 if (have_password)
4068 keep_password = true;
4069
4070 /* Don't let code below try to inject dbname into params. */
4071 dbname = NULL;
4072 }
4073 else
4074 {
4075 /* PQconninfoParse failed */
4076 if (errmsg)
4077 {
4078 pg_log_error("%s", errmsg);
4079 PQfreemem(errmsg);
4080 }
4081 else
4082 pg_log_error("out of memory");
4083 success = false;
4084 }
4085 }
4086 else
4087 {
4088 /*
4089 * If dbname isn't a connection string, then we'll inject it and
4090 * the other parameters into the keyword array below. (We can't
4091 * easily insert them into the cinfo array because of memory
4092 * management issues: PQconninfoFree would misbehave on Windows.)
4093 * However, to avoid dependencies on the order in which parameters
4094 * appear in the array, make a preliminary scan to set
4095 * keep_password and same_host correctly.
4096 *
4097 * While any change in user, host, or port causes us to ignore the
4098 * old connection's password, we don't force that for dbname,
4099 * since passwords aren't database-specific.
4100 */
4101 PQconninfoOption *ci;
4102
4103 for (ci = cinfo; ci->keyword; ci++)
4104 {
4105 if (user && strcmp(ci->keyword, "user") == 0)
4106 {
4107 if (!(ci->val && strcmp(user, ci->val) == 0))
4108 keep_password = false;
4109 }
4110 else if (host && strcmp(ci->keyword, "host") == 0)
4111 {
4112 if (ci->val && strcmp(host, ci->val) == 0)
4113 same_host = true;
4114 else
4115 keep_password = false;
4116 }
4117 else if (port && strcmp(ci->keyword, "port") == 0)
4118 {
4119 if (!(ci->val && strcmp(port, ci->val) == 0))
4120 keep_password = false;
4121 }
4122 }
4123
4124 /* While here, determine how many option slots there are */
4125 nconnopts = ci - cinfo;
4126 }
4127 }
4128 else
4129 {
4130 /* We failed to create the cinfo structure */
4131 pg_log_error("out of memory");
4132 success = false;
4133 }
4134
4135 /*
4136 * If the user asked to be prompted for a password, ask for one now. If
4137 * not, use the password from the old connection, provided the username
4138 * etc have not changed. Otherwise, try to connect without a password
4139 * first, and then ask for a password if needed.
4140 *
4141 * XXX: this behavior leads to spurious connection attempts recorded in
4142 * the postmaster's log. But libpq offers no API that would let us obtain
4143 * a password and then continue with the first connection attempt.
4144 */
4145 if (pset.getPassword == TRI_YES && success)
4146 {
4147 bool canceled = false;
4148
4149 /*
4150 * If a connstring or URI is provided, we don't know which username
4151 * will be used, since we haven't dug that out of the connstring.
4152 * Don't risk issuing a misleading prompt. As in startup.c, it does
4153 * not seem worth working harder, since this getPassword setting is
4154 * normally only used in noninteractive cases.
4155 */
4156 password = prompt_for_password(has_connection_string ? NULL : user,
4157 &canceled);
4158 success = !canceled;
4159 }
4160
4161 /*
4162 * Consider whether to force client_encoding to "auto" (overriding
4163 * anything in the connection string). We do so if we have a terminal
4164 * connection and there is no PGCLIENTENCODING environment setting.
4165 */
4166 if (pset.notty || getenv("PGCLIENTENCODING"))
4167 client_encoding = NULL;
4168 else
4169 client_encoding = "auto";
4170
4171 /* Loop till we have a connection or fail, which we might've already */
4172 while (success)
4173 {
4174 const char **keywords = pg_malloc((nconnopts + 1) * sizeof(*keywords));
4175 const char **values = pg_malloc((nconnopts + 1) * sizeof(*values));
4176 int paramnum = 0;
4177 PQconninfoOption *ci;
4178
4179 /*
4180 * Copy non-default settings into the PQconnectdbParams parameter
4181 * arrays; but inject any values specified old-style, as well as any
4182 * interactively-obtained password, and a couple of fields we want to
4183 * set forcibly.
4184 *
4185 * If you change this code, see also the initial-connection code in
4186 * main().
4187 */
4188 for (ci = cinfo; ci->keyword; ci++)
4189 {
4190 keywords[paramnum] = ci->keyword;
4191
4192 if (dbname && strcmp(ci->keyword, "dbname") == 0)
4193 values[paramnum++] = dbname;
4194 else if (user && strcmp(ci->keyword, "user") == 0)
4195 values[paramnum++] = user;
4196 else if (host && strcmp(ci->keyword, "host") == 0)
4197 values[paramnum++] = host;
4198 else if (host && !same_host && strcmp(ci->keyword, "hostaddr") == 0)
4199 {
4200 /* If we're changing the host value, drop any old hostaddr */
4201 values[paramnum++] = NULL;
4202 }
4203 else if (port && strcmp(ci->keyword, "port") == 0)
4204 values[paramnum++] = port;
4205 /* If !keep_password, we unconditionally drop old password */
4206 else if ((password || !keep_password) &&
4207 strcmp(ci->keyword, "password") == 0)
4208 values[paramnum++] = password;
4209 else if (strcmp(ci->keyword, "fallback_application_name") == 0)
4210 values[paramnum++] = pset.progname;
4211 else if (client_encoding &&
4212 strcmp(ci->keyword, "client_encoding") == 0)
4213 values[paramnum++] = client_encoding;
4214 else if (ci->val)
4215 values[paramnum++] = ci->val;
4216 /* else, don't bother making libpq parse this keyword */
4217 }
4218 /* add array terminator */
4219 keywords[paramnum] = NULL;
4220 values[paramnum] = NULL;
4221
4222 /* Note we do not want libpq to re-expand the dbname parameter */
4223 n_conn = PQconnectStartParams(keywords, values, false);
4224
4225 pg_free(keywords);
4226 pg_free(values);
4227
4228 wait_until_connected(n_conn);
4229 if (PQstatus(n_conn) == CONNECTION_OK)
4230 break;
4231
4232 /*
4233 * Connection attempt failed; either retry the connection attempt with
4234 * a new password, or give up.
4235 */
4236 if (!password && PQconnectionNeedsPassword(n_conn) && pset.getPassword != TRI_NO)
4237 {
4238 bool canceled = false;
4239
4240 /*
4241 * Prompt for password using the username we actually connected
4242 * with --- it might've come out of "dbname" rather than "user".
4243 */
4244 password = prompt_for_password(PQuser(n_conn), &canceled);
4245 PQfinish(n_conn);
4246 n_conn = NULL;
4247 success = !canceled;
4248 continue;
4249 }
4250
4251 /*
4252 * We'll report the error below ... unless n_conn is NULL, indicating
4253 * that libpq didn't have enough memory to make a PGconn.
4254 */
4255 if (n_conn == NULL)
4256 pg_log_error("out of memory");
4257
4258 success = false;
4259 } /* end retry loop */
4260
4261 /* Release locally allocated data, whether we succeeded or not */
4262 pg_free(password);
4263 PQconninfoFree(cinfo);
4264
4265 if (!success)
4266 {
4267 /*
4268 * Failed to connect to the database. In interactive mode, keep the
4269 * previous connection to the DB; in scripting mode, close our
4270 * previous connection as well.
4271 */
4272 if (pset.cur_cmd_interactive)
4273 {
4274 if (n_conn)
4275 {
4276 pg_log_info("%s", PQerrorMessage(n_conn));
4277 PQfinish(n_conn);
4278 }
4279
4280 /* pset.db is left unmodified */
4281 if (o_conn)
4282 pg_log_info("Previous connection kept");
4283 }
4284 else
4285 {
4286 if (n_conn)
4287 {
4288 pg_log_error("\\connect: %s", PQerrorMessage(n_conn));
4289 PQfinish(n_conn);
4290 }
4291
4292 if (o_conn)
4293 {
4294 /*
4295 * Transition to having no connection.
4296 *
4297 * Unlike CheckConnection(), we close the old connection
4298 * immediately to prevent its parameters from being re-used.
4299 * This is so that a script cannot accidentally reuse
4300 * parameters it did not expect to. Otherwise, the state
4301 * cleanup should be the same as in CheckConnection().
4302 */
4303 PQfinish(o_conn);
4304 pset.db = NULL;
4305 ResetCancelConn();
4306 UnsyncVariables();
4307 }
4308
4309 /* On the same reasoning, release any dead_conn to prevent reuse */
4310 if (pset.dead_conn)
4311 {
4312 PQfinish(pset.dead_conn);
4313 pset.dead_conn = NULL;
4314 }
4315 }
4316
4317 return false;
4318 }
4319
4320 /*
4321 * Replace the old connection with the new one, and update
4322 * connection-dependent variables. Keep the resynchronization logic in
4323 * sync with CheckConnection().
4324 */
4325 PQsetNoticeProcessor(n_conn, NoticeProcessor, NULL);
4326 pset.db = n_conn;
4327 SyncVariables();
4328 connection_warnings(false); /* Must be after SyncVariables */
4329
4330 /* Tell the user about the new connection */
4331 if (!pset.quiet)
4332 {
4333 if (!o_conn ||
4334 param_is_newly_set(PQhost(o_conn), PQhost(pset.db)) ||
4335 param_is_newly_set(PQport(o_conn), PQport(pset.db)))
4336 {
4337 char *connhost = PQhost(pset.db);
4338 char *hostaddr = PQhostaddr(pset.db);
4339
4340 if (is_unixsock_path(connhost))
4341 {
4342 /* hostaddr overrides connhost */
4343 if (hostaddr && *hostaddr)
4344 printf(_("You are now connected to database \"%s\" as user \"%s\" on address \"%s\" at port \"%s\".\n"),
4345 PQdb(pset.db), PQuser(pset.db), hostaddr, PQport(pset.db));
4346 else
4347 printf(_("You are now connected to database \"%s\" as user \"%s\" via socket in \"%s\" at port \"%s\".\n"),
4348 PQdb(pset.db), PQuser(pset.db), connhost, PQport(pset.db));
4349 }
4350 else
4351 {
4352 if (hostaddr && *hostaddr && strcmp(connhost, hostaddr) != 0)
4353 printf(_("You are now connected to database \"%s\" as user \"%s\" on host \"%s\" (address \"%s\") at port \"%s\".\n"),
4354 PQdb(pset.db), PQuser(pset.db), connhost, hostaddr, PQport(pset.db));
4355 else
4356 printf(_("You are now connected to database \"%s\" as user \"%s\" on host \"%s\" at port \"%s\".\n"),
4357 PQdb(pset.db), PQuser(pset.db), connhost, PQport(pset.db));
4358 }
4359 }
4360 else
4361 printf(_("You are now connected to database \"%s\" as user \"%s\".\n"),
4362 PQdb(pset.db), PQuser(pset.db));
4363 }
4364
4365 /* Drop no-longer-needed connection(s) */
4366 if (o_conn)
4367 PQfinish(o_conn);
4368 if (pset.dead_conn)
4369 {
4370 PQfinish(pset.dead_conn);
4371 pset.dead_conn = NULL;
4372 }
4373
4374 return true;
4375 }
4376
4377 /*
4378 * Processes the connection sequence described by PQconnectStartParams(). Don't
4379 * worry about reporting errors in this function. Our caller will check the
4380 * connection's status, and report appropriately.
4381 */
4382 static void
4383 wait_until_connected(PGconn *conn)
4384 {
4385 bool forRead = false;
4386
4387 while (true)
4388 {
4389 int rc;
4390 int sock;
4391 pg_usec_time_t end_time;
4392
4393 /*
4394 * On every iteration of the connection sequence, let's check if the
4395 * user has requested a cancellation.
4396 */
4397 if (cancel_pressed)
4398 break;
4399
4400 /*
4401 * Do not assume that the socket remains the same across
4402 * PQconnectPoll() calls.
4403 */
4404 sock = PQsocket(conn);
4405 if (sock == -1)
4406 break;
4407
4408 /*
4409 * If the user sends SIGINT between the cancel_pressed check, and
4410 * polling of the socket, it will not be recognized. Instead, we will
4411 * just wait until the next step in the connection sequence or
4412 * forever, which might require users to send SIGTERM or SIGQUIT.
4413 *
4414 * Some solutions would include the "self-pipe trick," using
4415 * pselect(2) and ppoll(2), or using a timeout.
4416 *
4417 * The self-pipe trick requires a bit of code to setup. pselect(2) and
4418 * ppoll(2) are not on all the platforms we support. The simplest
4419 * solution happens to just be adding a timeout, so let's wait for 1
4420 * second and check cancel_pressed again.
4421 */
4422 end_time = PQgetCurrentTimeUSec() + 1000000;
4423 rc = PQsocketPoll(sock, forRead, !forRead, end_time);
4424 if (rc == -1)
4425 return;
4426
4427 switch (PQconnectPoll(conn))
4428 {
4429 case PGRES_POLLING_OK:
4430 case PGRES_POLLING_FAILED:
4431 return;
4432 case PGRES_POLLING_READING:
4433 forRead = true;
4434 continue;
4435 case PGRES_POLLING_WRITING:
4436 forRead = false;
4437 continue;
4438 case PGRES_POLLING_ACTIVE:
4439 pg_unreachable();
4440 }
4441 }
4442 }
4443
4444 void
4445 connection_warnings(bool in_startup)
4446 {
4447 if (!pset.quiet && !pset.notty)
4448 {
4449 int client_ver = PG_VERSION_NUM;
4450 char cverbuf[32];
4451 char sverbuf[32];
4452
4453 if (pset.sversion != client_ver)
4454 {
4455 const char *server_version;
4456
4457 /* Try to get full text form, might include "devel" etc */
4458 server_version = PQparameterStatus(pset.db, "server_version");
4459 /* Otherwise fall back on pset.sversion */
4460 if (!server_version)
4461 {
4462 formatPGVersionNumber(pset.sversion, true,
4463 sverbuf, sizeof(sverbuf));
4464 server_version = sverbuf;
4465 }
4466
4467 printf(_("%s (%s, server %s)\n"),
4468 pset.progname, PG_VERSION, server_version);
4469 }
4470 /* For version match, only print psql banner on startup. */
4471 else if (in_startup)
4472 printf("%s (%s)\n", pset.progname, PG_VERSION);
4473
4474 /*
4475 * Warn if server's major version is newer than ours, or if server
4476 * predates our support cutoff (currently 9.2).
4477 */
4478 if (pset.sversion / 100 > client_ver / 100 ||
4479 pset.sversion < 90200)
4480 printf(_("WARNING: %s major version %s, server major version %s.\n"
4481 " Some psql features might not work.\n"),
4482 pset.progname,
4483 formatPGVersionNumber(client_ver, false,
4484 cverbuf, sizeof(cverbuf)),
4485 formatPGVersionNumber(pset.sversion, false,
4486 sverbuf, sizeof(sverbuf)));
4487
4488 #ifdef WIN32
4489 if (in_startup)
4490 checkWin32Codepage();
4491 #endif
4492 printSSLInfo();
4493 printGSSInfo();
4494 }
4495 }
4496
4497
4498 /*
4499 * printSSLInfo
4500 *
4501 * Prints information about the current SSL connection, if SSL is in use
4502 */
4503 static void
4504 printSSLInfo(void)
4505 {
4506 const char *protocol;
4507 const char *cipher;
4508 const char *compression;
4509 const char *alpn;
4510
4511 if (!PQsslInUse(pset.db))
4512 return; /* no SSL */
4513
4514 protocol = PQsslAttribute(pset.db, "protocol");
4515 cipher = PQsslAttribute(pset.db, "cipher");
4516 compression = PQsslAttribute(pset.db, "compression");
4517 alpn = PQsslAttribute(pset.db, "alpn");
4518
4519 printf(_("SSL connection (protocol: %s, cipher: %s, compression: %s, ALPN: %s)\n"),
4520 protocol ? protocol : _("unknown"),
4521 cipher ? cipher : _("unknown"),
4522 (compression && strcmp(compression, "off") != 0) ? _("on") : _("off"),
4523 (alpn && alpn[0] != '\0') ? alpn : _("none"));
4524 }
4525
4526 /*
4527 * printGSSInfo
4528 *
4529 * Prints information about the current GSSAPI connection, if GSSAPI encryption is in use
4530 */
4531 static void
4532 printGSSInfo(void)
4533 {
4534 if (!PQgssEncInUse(pset.db))
4535 return; /* no GSSAPI encryption in use */
4536
4537 printf(_("GSSAPI-encrypted connection\n"));
4538 }
4539
4540
4541 /*
4542 * checkWin32Codepage
4543 *
4544 * Prints a warning when win32 console codepage differs from Windows codepage
4545 */
4546 #ifdef WIN32
4547 static void
4548 checkWin32Codepage(void)
4549 {
4550 unsigned int wincp,
4551 concp;
4552
4553 wincp = GetACP();
4554 concp = GetConsoleCP();
4555 if (wincp != concp)
4556 {
4557 printf(_("WARNING: Console code page (%u) differs from Windows code page (%u)\n"
4558 " 8-bit characters might not work correctly. See psql reference\n"
4559 " page \"Notes for Windows users\" for details.\n"),
4560 concp, wincp);
4561 }
4562 }
4563 #endif
4564
4565
4566 /*
4567 * SyncVariables
4568 *
4569 * Make psql's internal variables agree with connection state upon
4570 * establishing a new connection.
4571 */
4572 void
4573 SyncVariables(void)
4574 {
4575 char vbuf[32];
4576 const char *server_version;
4577 char *service_name;
4578
4579 /* get stuff from connection */
4580 pset.encoding = PQclientEncoding(pset.db);
4581 pset.popt.topt.encoding = pset.encoding;
4582 pset.sversion = PQserverVersion(pset.db);
4583
4584 setFmtEncoding(pset.encoding);
4585
4586 SetVariable(pset.vars, "DBNAME", PQdb(pset.db));
4587 SetVariable(pset.vars, "USER", PQuser(pset.db));
4588 SetVariable(pset.vars, "HOST", PQhost(pset.db));
4589 SetVariable(pset.vars, "PORT", PQport(pset.db));
4590 SetVariable(pset.vars, "ENCODING", pg_encoding_to_char(pset.encoding));
4591
4592 service_name = get_conninfo_value("service");
4593 SetVariable(pset.vars, "SERVICE", service_name);
4594 if (service_name)
4595 pg_free(service_name);
4596
4597 /* this bit should match connection_warnings(): */
4598 /* Try to get full text form of version, might include "devel" etc */
4599 server_version = PQparameterStatus(pset.db, "server_version");
4600 /* Otherwise fall back on pset.sversion */
4601 if (!server_version)
4602 {
4603 formatPGVersionNumber(pset.sversion, true, vbuf, sizeof(vbuf));
4604 server_version = vbuf;
4605 }
4606 SetVariable(pset.vars, "SERVER_VERSION_NAME", server_version);
4607
4608 snprintf(vbuf, sizeof(vbuf), "%d", pset.sversion);
4609 SetVariable(pset.vars, "SERVER_VERSION_NUM", vbuf);
4610
4611 /* send stuff to it, too */
4612 PQsetErrorVerbosity(pset.db, pset.verbosity);
4613 PQsetErrorContextVisibility(pset.db, pset.show_context);
4614 }
4615
4616 /*
4617 * UnsyncVariables
4618 *
4619 * Clear variables that should be not be set when there is no connection.
4620 */
4621 void
4622 UnsyncVariables(void)
4623 {
4624 SetVariable(pset.vars, "DBNAME", NULL);
4625 SetVariable(pset.vars, "SERVICE", NULL);
4626 SetVariable(pset.vars, "USER", NULL);
4627 SetVariable(pset.vars, "HOST", NULL);
4628 SetVariable(pset.vars, "PORT", NULL);
4629 SetVariable(pset.vars, "ENCODING", NULL);
4630 SetVariable(pset.vars, "SERVER_VERSION_NAME", NULL);
4631 SetVariable(pset.vars, "SERVER_VERSION_NUM", NULL);
4632 }
4633
4634
4635 /*
4636 * helper for do_edit(): actually invoke the editor
4637 *
4638 * Returns true on success, false if we failed to invoke the editor or
4639 * it returned nonzero status. (An error message is printed for failed-
4640 * to-invoke cases, but not if the editor returns nonzero status.)
4641 */
4642 static bool
4643 editFile(const char *fname, int lineno)
4644 {
4645 const char *editorName;
4646 const char *editor_lineno_arg = NULL;
4647 char *sys;
4648 int result;
4649
4650 Assert(fname != NULL);
4651
4652 /* Find an editor to use */
4653 editorName = getenv("PSQL_EDITOR");
4654 if (!editorName)
4655 editorName = getenv("EDITOR");
4656 if (!editorName)
4657 editorName = getenv("VISUAL");
4658 if (!editorName)
4659 editorName = DEFAULT_EDITOR;
4660
4661 /* Get line number argument, if we need it. */
4662 if (lineno > 0)
4663 {
4664 editor_lineno_arg = getenv("PSQL_EDITOR_LINENUMBER_ARG");
4665 #ifdef DEFAULT_EDITOR_LINENUMBER_ARG
4666 if (!editor_lineno_arg)
4667 editor_lineno_arg = DEFAULT_EDITOR_LINENUMBER_ARG;
4668 #endif
4669 if (!editor_lineno_arg)
4670 {
4671 pg_log_error("environment variable PSQL_EDITOR_LINENUMBER_ARG must be set to specify a line number");
4672 return false;
4673 }
4674 }
4675
4676 /*
4677 * On Unix the EDITOR value should *not* be quoted, since it might include
4678 * switches, eg, EDITOR="pico -t"; it's up to the user to put quotes in it
4679 * if necessary. But this policy is not very workable on Windows, due to
4680 * severe brain damage in their command shell plus the fact that standard
4681 * program paths include spaces.
4682 */
4683 #ifndef WIN32
4684 if (lineno > 0)
4685 sys = psprintf("exec %s %s%d '%s'",
4686 editorName, editor_lineno_arg, lineno, fname);
4687 else
4688 sys = psprintf("exec %s '%s'",
4689 editorName, fname);
4690 #else
4691 if (lineno > 0)
4692 sys = psprintf("\"%s\" %s%d \"%s\"",
4693 editorName, editor_lineno_arg, lineno, fname);
4694 else
4695 sys = psprintf("\"%s\" \"%s\"",
4696 editorName, fname);
4697 #endif
4698 fflush(NULL);
4699 result = system(sys);
4700 if (result == -1)
4701 pg_log_error("could not start editor \"%s\"", editorName);
4702 else if (result == 127)
4703 pg_log_error("could not start /bin/sh");
4704 free(sys);
4705
4706 return result == 0;
4707 }
4708
4709
4710 /*
4711 * do_edit -- handler for \e
4712 *
4713 * If you do not specify a filename, the current query buffer will be copied
4714 * into a temporary file.
4715 *
4716 * After this function is done, the resulting file will be copied back into the
4717 * query buffer. As an exception to this, the query buffer will be emptied
4718 * if the file was not modified (or the editor failed) and the caller passes
4719 * "discard_on_quit" = true.
4720 *
4721 * If "edited" isn't NULL, *edited will be set to true if the query buffer
4722 * is successfully replaced.
4723 */
4724 static bool
4725 do_edit(const char *filename_arg, PQExpBuffer query_buf,
4726 int lineno, bool discard_on_quit, bool *edited)
4727 {
4728 char fnametmp[MAXPGPATH];
4729 FILE *stream = NULL;
4730 const char *fname;
4731 bool error = false;
4732 int fd;
4733 struct stat before,
4734 after;
4735
4736 if (filename_arg)
4737 fname = filename_arg;
4738 else
4739 {
4740 /* make a temp file to edit */
4741 #ifndef WIN32
4742 const char *tmpdir = getenv("TMPDIR");
4743
4744 if (!tmpdir)
4745 tmpdir = "/tmp";
4746 #else
4747 char tmpdir[MAXPGPATH];
4748 int ret;
4749
4750 ret = GetTempPath(MAXPGPATH, tmpdir);
4751 if (ret == 0 || ret > MAXPGPATH)
4752 {
4753 pg_log_error("could not locate temporary directory: %s",
4754 !ret ? strerror(errno) : "");
4755 return false;
4756 }
4757 #endif
4758
4759 /*
4760 * No canonicalize_path() here. EDIT.EXE run from CMD.EXE prepends the
4761 * current directory to the supplied path unless we use only
4762 * backslashes, so we do that.
4763 */
4764 #ifndef WIN32
4765 snprintf(fnametmp, sizeof(fnametmp), "%s%spsql.edit.%d.sql", tmpdir,
4766 "/", (int) getpid());
4767 #else
4768 snprintf(fnametmp, sizeof(fnametmp), "%s%spsql.edit.%d.sql", tmpdir,
4769 "" /* trailing separator already present */ , (int) getpid());
4770 #endif
4771
4772 fname = (const char *) fnametmp;
4773
4774 fd = open(fname, O_WRONLY | O_CREAT | O_EXCL, 0600);
4775 if (fd != -1)
4776 stream = fdopen(fd, "w");
4777
4778 if (fd == -1 || !stream)
4779 {
4780 pg_log_error("could not open temporary file \"%s\": %m", fname);
4781 error = true;
4782 }
4783 else
4784 {
4785 unsigned int ql = query_buf->len;
4786
4787 /* force newline-termination of what we send to editor */
4788 if (ql > 0 && query_buf->data[ql - 1] != '\n')
4789 {
4790 appendPQExpBufferChar(query_buf, '\n');
4791 ql++;
4792 }
4793
4794 if (fwrite(query_buf->data, 1, ql, stream) != ql)
4795 {
4796 pg_log_error("%s: %m", fname);
4797
4798 if (fclose(stream) != 0)
4799 pg_log_error("%s: %m", fname);
4800
4801 if (remove(fname) != 0)
4802 pg_log_error("%s: %m", fname);
4803
4804 error = true;
4805 }
4806 else if (fclose(stream) != 0)
4807 {
4808 pg_log_error("%s: %m", fname);
4809 if (remove(fname) != 0)
4810 pg_log_error("%s: %m", fname);
4811 error = true;
4812 }
4813 else
4814 {
4815 struct utimbuf ut;
4816
4817 /*
4818 * Try to set the file modification time of the temporary file
4819 * a few seconds in the past. Otherwise, the low granularity
4820 * (one second, or even worse on some filesystems) that we can
4821 * portably measure with stat(2) could lead us to not
4822 * recognize a modification, if the user typed very quickly.
4823 *
4824 * This is a rather unlikely race condition, so don't error
4825 * out if the utime(2) call fails --- that would make the cure
4826 * worse than the disease.
4827 */
4828 ut.modtime = ut.actime = time(NULL) - 2;
4829 (void) utime(fname, &ut);
4830 }
4831 }
4832 }
4833
4834 if (!error && stat(fname, &before) != 0)
4835 {
4836 pg_log_error("%s: %m", fname);
4837 error = true;
4838 }
4839
4840 /* call editor */
4841 if (!error)
4842 error = !editFile(fname, lineno);
4843
4844 if (!error && stat(fname, &after) != 0)
4845 {
4846 pg_log_error("%s: %m", fname);
4847 error = true;
4848 }
4849
4850 /* file was edited if the size or modification time has changed */
4851 if (!error &&
4852 (before.st_size != after.st_size ||
4853 before.st_mtime != after.st_mtime))
4854 {
4855 stream = fopen(fname, PG_BINARY_R);
4856 if (!stream)
4857 {
4858 pg_log_error("%s: %m", fname);
4859 error = true;
4860 }
4861 else
4862 {
4863 /* read file back into query_buf */
4864 char line[1024];
4865
4866 resetPQExpBuffer(query_buf);
4867 while (fgets(line, sizeof(line), stream) != NULL)
4868 appendPQExpBufferStr(query_buf, line);
4869
4870 if (ferror(stream))
4871 {
4872 pg_log_error("%s: %m", fname);
4873 error = true;
4874 resetPQExpBuffer(query_buf);
4875 }
4876 else if (edited)
4877 {
4878 *edited = true;
4879 }
4880
4881 fclose(stream);
4882 }
4883 }
4884 else
4885 {
4886 /*
4887 * If the file was not modified, and the caller requested it, discard
4888 * the query buffer.
4889 */
4890 if (discard_on_quit)
4891 resetPQExpBuffer(query_buf);
4892 }
4893
4894 /* remove temp file */
4895 if (!filename_arg)
4896 {
4897 if (remove(fname) == -1)
4898 {
4899 pg_log_error("%s: %m", fname);
4900 error = true;
4901 }
4902 }
4903
4904 return !error;
4905 }
4906
4907
4908
4909 /*
4910 * process_file
4911 *
4912 * Reads commands from filename and passes them to the main processing loop.
4913 * Handler for \i and \ir, but can be used for other things as well. Returns
4914 * MainLoop() error code.
4915 *
4916 * If use_relative_path is true and filename is not an absolute path, then open
4917 * the file from where the currently processed file (if any) is located.
4918 */
4919 int
4920 process_file(char *filename, bool use_relative_path)
4921 {
4922 FILE *fd;
4923 int result;
4924 char *oldfilename;
4925 char relpath[MAXPGPATH];
4926
4927 if (!filename)
4928 {
4929 fd = stdin;
4930 filename = NULL;
4931 }
4932 else if (strcmp(filename, "-") != 0)
4933 {
4934 canonicalize_path_enc(filename, pset.encoding);
4935
4936 /*
4937 * If we were asked to resolve the pathname relative to the location
4938 * of the currently executing script, and there is one, and this is a
4939 * relative pathname, then prepend all but the last pathname component
4940 * of the current script to this pathname.
4941 */
4942 if (use_relative_path && pset.inputfile &&
4943 !is_absolute_path(filename) && !has_drive_prefix(filename))
4944 {
4945 strlcpy(relpath, pset.inputfile, sizeof(relpath));
4946 get_parent_directory(relpath);
4947 join_path_components(relpath, relpath, filename);
4948 canonicalize_path_enc(relpath, pset.encoding);
4949
4950 filename = relpath;
4951 }
4952
4953 fd = fopen(filename, PG_BINARY_R);
4954
4955 if (!fd)
4956 {
4957 pg_log_error("%s: %m", filename);
4958 return EXIT_FAILURE;
4959 }
4960 }
4961 else
4962 {
4963 fd = stdin;
4964 filename = "<stdin>"; /* for future error messages */
4965 }
4966
4967 oldfilename = pset.inputfile;
4968 pset.inputfile = filename;
4969
4970 pg_logging_config(pset.inputfile ? 0 : PG_LOG_FLAG_TERSE);
4971
4972 result = MainLoop(fd);
4973
4974 if (fd != stdin)
4975 fclose(fd);
4976
4977 pset.inputfile = oldfilename;
4978
4979 pg_logging_config(pset.inputfile ? 0 : PG_LOG_FLAG_TERSE);
4980
4981 return result;
4982 }
4983
4984
4985
4986 static const char *
4987 _align2string(enum printFormat in)
4988 {
4989 switch (in)
4990 {
4991 case PRINT_NOTHING:
4992 return "nothing";
4993 break;
4994 case PRINT_ALIGNED:
4995 return "aligned";
4996 break;
4997 case PRINT_ASCIIDOC:
4998 return "asciidoc";
4999 break;
5000 case PRINT_CSV:
5001 return "csv";
5002 break;
5003 case PRINT_HTML:
5004 return "html";
5005 break;
5006 case PRINT_LATEX:
5007 return "latex";
5008 break;
5009 case PRINT_LATEX_LONGTABLE:
5010 return "latex-longtable";
5011 break;
5012 case PRINT_TROFF_MS:
5013 return "troff-ms";
5014 break;
5015 case PRINT_UNALIGNED:
5016 return "unaligned";
5017 break;
5018 case PRINT_WRAPPED:
5019 return "wrapped";
5020 break;
5021 }
5022 return "unknown";
5023 }
5024
5025 /*
5026 * Parse entered Unicode linestyle. If ok, update *linestyle and return
5027 * true, else return false.
5028 */
5029 static bool
5030 set_unicode_line_style(const char *value, size_t vallen,
5031 unicode_linestyle *linestyle)
5032 {
5033 if (pg_strncasecmp("single", value, vallen) == 0)
5034 *linestyle = UNICODE_LINESTYLE_SINGLE;
5035 else if (pg_strncasecmp("double", value, vallen) == 0)
5036 *linestyle = UNICODE_LINESTYLE_DOUBLE;
5037 else
5038 return false;
5039 return true;
5040 }
5041
5042 static const char *
5043 _unicode_linestyle2string(int linestyle)
5044 {
5045 switch (linestyle)
5046 {
5047 case UNICODE_LINESTYLE_SINGLE:
5048 return "single";
5049 break;
5050 case UNICODE_LINESTYLE_DOUBLE:
5051 return "double";
5052 break;
5053 }
5054 return "unknown";
5055 }
5056
5057 /*
5058 * do_pset
5059 *
5060 * Performs the assignment "param = value", where value could be NULL;
5061 * for some params that has an effect such as inversion, for others
5062 * it does nothing.
5063 *
5064 * Adjusts the state of the formatting options at *popt. (In practice that
5065 * is always pset.popt, but maybe someday it could be different.)
5066 *
5067 * If successful and quiet is false, then invokes printPsetInfo() to report
5068 * the change.
5069 *
5070 * Returns true if successful, else false (eg for invalid param or value).
5071 */
5072 bool
5073 do_pset(const char *param, const char *value, printQueryOpt *popt, bool quiet)
5074 {
5075 size_t vallen = 0;
5076
5077 Assert(param != NULL);
5078
5079 if (value)
5080 vallen = strlen(value);
5081
5082 /* set format */
5083 if (strcmp(param, "format") == 0)
5084 {
5085 static const struct fmt
5086 {
5087 const char *name;
5088 enum printFormat number;
5089 } formats[] =
5090 {
5091 /* remember to update error message below when adding more */
5092 {"aligned", PRINT_ALIGNED},
5093 {"asciidoc", PRINT_ASCIIDOC},
5094 {"csv", PRINT_CSV},
5095 {"html", PRINT_HTML},
5096 {"latex", PRINT_LATEX},
5097 {"troff-ms", PRINT_TROFF_MS},
5098 {"unaligned", PRINT_UNALIGNED},
5099 {"wrapped", PRINT_WRAPPED}
5100 };
5101
5102 if (!value)
5103 ;
5104 else
5105 {
5106 int match_pos = -1;
5107
5108 for (int i = 0; i < lengthof(formats); i++)
5109 {
5110 if (pg_strncasecmp(formats[i].name, value, vallen) == 0)
5111 {
5112 if (match_pos < 0)
5113 match_pos = i;
5114 else
5115 {
5116 pg_log_error("\\pset: ambiguous abbreviation \"%s\" matches both \"%s\" and \"%s\"",
5117 value,
5118 formats[match_pos].name, formats[i].name);
5119 return false;
5120 }
5121 }
5122 }
5123 if (match_pos >= 0)
5124 popt->topt.format = formats[match_pos].number;
5125 else if (pg_strncasecmp("latex-longtable", value, vallen) == 0)
5126 {
5127 /*
5128 * We must treat latex-longtable specially because latex is a
5129 * prefix of it; if both were in the table above, we'd think
5130 * "latex" is ambiguous.
5131 */
5132 popt->topt.format = PRINT_LATEX_LONGTABLE;
5133 }
5134 else
5135 {
5136 pg_log_error("\\pset: allowed formats are aligned, asciidoc, csv, html, latex, latex-longtable, troff-ms, unaligned, wrapped");
5137 return false;
5138 }
5139 }
5140 }
5141
5142 /* set table line style */
5143 else if (strcmp(param, "linestyle") == 0)
5144 {
5145 if (!value)
5146 ;
5147 else if (pg_strncasecmp("ascii", value, vallen) == 0)
5148 popt->topt.line_style = &pg_asciiformat;
5149 else if (pg_strncasecmp("old-ascii", value, vallen) == 0)
5150 popt->topt.line_style = &pg_asciiformat_old;
5151 else if (pg_strncasecmp("unicode", value, vallen) == 0)
5152 popt->topt.line_style = &pg_utf8format;
5153 else
5154 {
5155 pg_log_error("\\pset: allowed line styles are ascii, old-ascii, unicode");
5156 return false;
5157 }
5158 }
5159
5160 /* set unicode border line style */
5161 else if (strcmp(param, "unicode_border_linestyle") == 0)
5162 {
5163 if (!value)
5164 ;
5165 else if (set_unicode_line_style(value, vallen,
5166 &popt->topt.unicode_border_linestyle))
5167 refresh_utf8format(&(popt->topt));
5168 else
5169 {
5170 pg_log_error("\\pset: allowed Unicode border line styles are single, double");
5171 return false;
5172 }
5173 }
5174
5175 /* set unicode column line style */
5176 else if (strcmp(param, "unicode_column_linestyle") == 0)
5177 {
5178 if (!value)
5179 ;
5180 else if (set_unicode_line_style(value, vallen,
5181 &popt->topt.unicode_column_linestyle))
5182 refresh_utf8format(&(popt->topt));
5183 else
5184 {
5185 pg_log_error("\\pset: allowed Unicode column line styles are single, double");
5186 return false;
5187 }
5188 }
5189
5190 /* set unicode header line style */
5191 else if (strcmp(param, "unicode_header_linestyle") == 0)
5192 {
5193 if (!value)
5194 ;
5195 else if (set_unicode_line_style(value, vallen,
5196 &popt->topt.unicode_header_linestyle))
5197 refresh_utf8format(&(popt->topt));
5198 else
5199 {
5200 pg_log_error("\\pset: allowed Unicode header line styles are single, double");
5201 return false;
5202 }
5203 }
5204
5205 /* set border style/width */
5206 else if (strcmp(param, "border") == 0)
5207 {
5208 if (value)
5209 popt->topt.border = atoi(value);
5210 }
5211
5212 /* set expanded/vertical mode */
5213 else if (strcmp(param, "x") == 0 ||
5214 strcmp(param, "expanded") == 0 ||
5215 strcmp(param, "vertical") == 0)
5216 {
5217 if (value && pg_strcasecmp(value, "auto") == 0)
5218 popt->topt.expanded = 2;
5219 else if (value)
5220 {
5221 bool on_off;
5222
5223 if (ParseVariableBool(value, NULL, &on_off))
5224 popt->topt.expanded = on_off ? 1 : 0;
5225 else
5226 {
5227 PsqlVarEnumError(param, value, "on, off, auto");
5228 return false;
5229 }
5230 }
5231 else
5232 popt->topt.expanded = !popt->topt.expanded;
5233 }
5234
5235 /* header line width in expanded mode */
5236 else if (strcmp(param, "xheader_width") == 0)
5237 {
5238 if (!value)
5239 ;
5240 else if (pg_strcasecmp(value, "full") == 0)
5241 popt->topt.expanded_header_width_type = PRINT_XHEADER_FULL;
5242 else if (pg_strcasecmp(value, "column") == 0)
5243 popt->topt.expanded_header_width_type = PRINT_XHEADER_COLUMN;
5244 else if (pg_strcasecmp(value, "page") == 0)
5245 popt->topt.expanded_header_width_type = PRINT_XHEADER_PAGE;
5246 else
5247 {
5248 int intval = atoi(value);
5249
5250 if (intval == 0)
5251 {
5252 pg_log_error("\\pset: allowed xheader_width values are \"%s\" (default), \"%s\", \"%s\", or a number specifying the exact width", "full", "column", "page");
5253 return false;
5254 }
5255
5256 popt->topt.expanded_header_width_type = PRINT_XHEADER_EXACT_WIDTH;
5257 popt->topt.expanded_header_exact_width = intval;
5258 }
5259 }
5260
5261 /* field separator for CSV format */
5262 else if (strcmp(param, "csv_fieldsep") == 0)
5263 {
5264 if (value)
5265 {
5266 /* CSV separator has to be a one-byte character */
5267 if (strlen(value) != 1)
5268 {
5269 pg_log_error("\\pset: csv_fieldsep must be a single one-byte character");
5270 return false;
5271 }
5272 if (value[0] == '"' || value[0] == '\n' || value[0] == '\r')
5273 {
5274 pg_log_error("\\pset: csv_fieldsep cannot be a double quote, a newline, or a carriage return");
5275 return false;
5276 }
5277 popt->topt.csvFieldSep[0] = value[0];
5278 }
5279 }
5280
5281 /* locale-aware numeric output */
5282 else if (strcmp(param, "numericlocale") == 0)
5283 {
5284 if (value)
5285 return ParseVariableBool(value, param, &popt->topt.numericLocale);
5286 else
5287 popt->topt.numericLocale = !popt->topt.numericLocale;
5288 }
5289
5290 /* null display */
5291 else if (strcmp(param, "null") == 0)
5292 {
5293 if (value)
5294 {
5295 free(popt->nullPrint);
5296 popt->nullPrint = pg_strdup(value);
5297 }
5298 }
5299
5300 /* field separator for unaligned text */
5301 else if (strcmp(param, "fieldsep") == 0)
5302 {
5303 if (value)
5304 {
5305 free(popt->topt.fieldSep.separator);
5306 popt->topt.fieldSep.separator = pg_strdup(value);
5307 popt->topt.fieldSep.separator_zero = false;
5308 }
5309 }
5310
5311 else if (strcmp(param, "fieldsep_zero") == 0)
5312 {
5313 free(popt->topt.fieldSep.separator);
5314 popt->topt.fieldSep.separator = NULL;
5315 popt->topt.fieldSep.separator_zero = true;
5316 }
5317
5318 /* record separator for unaligned text */
5319 else if (strcmp(param, "recordsep") == 0)
5320 {
5321 if (value)
5322 {
5323 free(popt->topt.recordSep.separator);
5324 popt->topt.recordSep.separator = pg_strdup(value);
5325 popt->topt.recordSep.separator_zero = false;
5326 }
5327 }
5328
5329 else if (strcmp(param, "recordsep_zero") == 0)
5330 {
5331 free(popt->topt.recordSep.separator);
5332 popt->topt.recordSep.separator = NULL;
5333 popt->topt.recordSep.separator_zero = true;
5334 }
5335
5336 /* toggle between full and tuples-only format */
5337 else if (strcmp(param, "t") == 0 || strcmp(param, "tuples_only") == 0)
5338 {
5339 if (value)
5340 return ParseVariableBool(value, param, &popt->topt.tuples_only);
5341 else
5342 popt->topt.tuples_only = !popt->topt.tuples_only;
5343 }
5344
5345 /* set title override */
5346 else if (strcmp(param, "C") == 0 || strcmp(param, "title") == 0)
5347 {
5348 free(popt->title);
5349 if (!value)
5350 popt->title = NULL;
5351 else
5352 popt->title = pg_strdup(value);
5353 }
5354
5355 /* set HTML table tag options */
5356 else if (strcmp(param, "T") == 0 || strcmp(param, "tableattr") == 0)
5357 {
5358 free(popt->topt.tableAttr);
5359 if (!value)
5360 popt->topt.tableAttr = NULL;
5361 else
5362 popt->topt.tableAttr = pg_strdup(value);
5363 }
5364
5365 /* toggle use of pager */
5366 else if (strcmp(param, "pager") == 0)
5367 {
5368 if (value && pg_strcasecmp(value, "always") == 0)
5369 popt->topt.pager = 2;
5370 else if (value)
5371 {
5372 bool on_off;
5373
5374 if (!ParseVariableBool(value, NULL, &on_off))
5375 {
5376 PsqlVarEnumError(param, value, "on, off, always");
5377 return false;
5378 }
5379 popt->topt.pager = on_off ? 1 : 0;
5380 }
5381 else if (popt->topt.pager == 1)
5382 popt->topt.pager = 0;
5383 else
5384 popt->topt.pager = 1;
5385 }
5386
5387 /* set minimum lines for pager use */
5388 else if (strcmp(param, "pager_min_lines") == 0)
5389 {
5390 if (value &&
5391 !ParseVariableNum(value, "pager_min_lines", &popt->topt.pager_min_lines))
5392 return false;
5393 }
5394
5395 /* disable "(x rows)" footer */
5396 else if (strcmp(param, "footer") == 0)
5397 {
5398 if (value)
5399 return ParseVariableBool(value, param, &popt->topt.default_footer);
5400 else
5401 popt->topt.default_footer = !popt->topt.default_footer;
5402 }
5403
5404 /* set border style/width */
5405 else if (strcmp(param, "columns") == 0)
5406 {
5407 if (value)
5408 popt->topt.columns = atoi(value);
5409 }
5410 else
5411 {
5412 pg_log_error("\\pset: unknown option: %s", param);
5413 return false;
5414 }
5415
5416 if (!quiet)
5417 printPsetInfo(param, &pset.popt);
5418
5419 return true;
5420 }
5421
5422 /*
5423 * printPsetInfo: print the state of the "param" formatting parameter in popt.
5424 */
5425 static bool
5426 printPsetInfo(const char *param, printQueryOpt *popt)
5427 {
5428 Assert(param != NULL);
5429
5430 /* show border style/width */
5431 if (strcmp(param, "border") == 0)
5432 printf(_("Border style is %d.\n"), popt->topt.border);
5433
5434 /* show the target width for the wrapped format */
5435 else if (strcmp(param, "columns") == 0)
5436 {
5437 if (!popt->topt.columns)
5438 printf(_("Target width is unset.\n"));
5439 else
5440 printf(_("Target width is %d.\n"), popt->topt.columns);
5441 }
5442
5443 /* show expanded/vertical mode */
5444 else if (strcmp(param, "x") == 0 || strcmp(param, "expanded") == 0 || strcmp(param, "vertical") == 0)
5445 {
5446 if (popt->topt.expanded == 1)
5447 printf(_("Expanded display is on.\n"));
5448 else if (popt->topt.expanded == 2)
5449 printf(_("Expanded display is used automatically.\n"));
5450 else
5451 printf(_("Expanded display is off.\n"));
5452 }
5453
5454 /* show xheader width value */
5455 else if (strcmp(param, "xheader_width") == 0)
5456 {
5457 if (popt->topt.expanded_header_width_type == PRINT_XHEADER_FULL)
5458 printf(_("Expanded header width is \"%s\".\n"), "full");
5459 else if (popt->topt.expanded_header_width_type == PRINT_XHEADER_COLUMN)
5460 printf(_("Expanded header width is \"%s\".\n"), "column");
5461 else if (popt->topt.expanded_header_width_type == PRINT_XHEADER_PAGE)
5462 printf(_("Expanded header width is \"%s\".\n"), "page");
5463 else if (popt->topt.expanded_header_width_type == PRINT_XHEADER_EXACT_WIDTH)
5464 printf(_("Expanded header width is %d.\n"), popt->topt.expanded_header_exact_width);
5465 }
5466
5467 /* show field separator for CSV format */
5468 else if (strcmp(param, "csv_fieldsep") == 0)
5469 {
5470 printf(_("Field separator for CSV is \"%s\".\n"),
5471 popt->topt.csvFieldSep);
5472 }
5473
5474 /* show field separator for unaligned text */
5475 else if (strcmp(param, "fieldsep") == 0)
5476 {
5477 if (popt->topt.fieldSep.separator_zero)
5478 printf(_("Field separator is zero byte.\n"));
5479 else
5480 printf(_("Field separator is \"%s\".\n"),
5481 popt->topt.fieldSep.separator);
5482 }
5483
5484 else if (strcmp(param, "fieldsep_zero") == 0)
5485 {
5486 printf(_("Field separator is zero byte.\n"));
5487 }
5488
5489 /* show disable "(x rows)" footer */
5490 else if (strcmp(param, "footer") == 0)
5491 {
5492 if (popt->topt.default_footer)
5493 printf(_("Default footer is on.\n"));
5494 else
5495 printf(_("Default footer is off.\n"));
5496 }
5497
5498 /* show format */
5499 else if (strcmp(param, "format") == 0)
5500 {
5501 printf(_("Output format is %s.\n"), _align2string(popt->topt.format));
5502 }
5503
5504 /* show table line style */
5505 else if (strcmp(param, "linestyle") == 0)
5506 {
5507 printf(_("Line style is %s.\n"),
5508 get_line_style(&popt->topt)->name);
5509 }
5510
5511 /* show null display */
5512 else if (strcmp(param, "null") == 0)
5513 {
5514 printf(_("Null display is \"%s\".\n"),
5515 popt->nullPrint ? popt->nullPrint : "");
5516 }
5517
5518 /* show locale-aware numeric output */
5519 else if (strcmp(param, "numericlocale") == 0)
5520 {
5521 if (popt->topt.numericLocale)
5522 printf(_("Locale-adjusted numeric output is on.\n"));
5523 else
5524 printf(_("Locale-adjusted numeric output is off.\n"));
5525 }
5526
5527 /* show toggle use of pager */
5528 else if (strcmp(param, "pager") == 0)
5529 {
5530 if (popt->topt.pager == 1)
5531 printf(_("Pager is used for long output.\n"));
5532 else if (popt->topt.pager == 2)
5533 printf(_("Pager is always used.\n"));
5534 else
5535 printf(_("Pager usage is off.\n"));
5536 }
5537
5538 /* show minimum lines for pager use */
5539 else if (strcmp(param, "pager_min_lines") == 0)
5540 {
5541 printf(ngettext("Pager won't be used for less than %d line.\n",
5542 "Pager won't be used for less than %d lines.\n",
5543 popt->topt.pager_min_lines),
5544 popt->topt.pager_min_lines);
5545 }
5546
5547 /* show record separator for unaligned text */
5548 else if (strcmp(param, "recordsep") == 0)
5549 {
5550 if (popt->topt.recordSep.separator_zero)
5551 printf(_("Record separator is zero byte.\n"));
5552 else if (strcmp(popt->topt.recordSep.separator, "\n") == 0)
5553 printf(_("Record separator is <newline>.\n"));
5554 else
5555 printf(_("Record separator is \"%s\".\n"),
5556 popt->topt.recordSep.separator);
5557 }
5558
5559 else if (strcmp(param, "recordsep_zero") == 0)
5560 {
5561 printf(_("Record separator is zero byte.\n"));
5562 }
5563
5564 /* show HTML table tag options */
5565 else if (strcmp(param, "T") == 0 || strcmp(param, "tableattr") == 0)
5566 {
5567 if (popt->topt.tableAttr)
5568 printf(_("Table attributes are \"%s\".\n"),
5569 popt->topt.tableAttr);
5570 else
5571 printf(_("Table attributes unset.\n"));
5572 }
5573
5574 /* show title override */
5575 else if (strcmp(param, "C") == 0 || strcmp(param, "title") == 0)
5576 {
5577 if (popt->title)
5578 printf(_("Title is \"%s\".\n"), popt->title);
5579 else
5580 printf(_("Title is unset.\n"));
5581 }
5582
5583 /* show toggle between full and tuples-only format */
5584 else if (strcmp(param, "t") == 0 || strcmp(param, "tuples_only") == 0)
5585 {
5586 if (popt->topt.tuples_only)
5587 printf(_("Tuples only is on.\n"));
5588 else
5589 printf(_("Tuples only is off.\n"));
5590 }
5591
5592 /* Unicode style formatting */
5593 else if (strcmp(param, "unicode_border_linestyle") == 0)
5594 {
5595 printf(_("Unicode border line style is \"%s\".\n"),
5596 _unicode_linestyle2string(popt->topt.unicode_border_linestyle));
5597 }
5598
5599 else if (strcmp(param, "unicode_column_linestyle") == 0)
5600 {
5601 printf(_("Unicode column line style is \"%s\".\n"),
5602 _unicode_linestyle2string(popt->topt.unicode_column_linestyle));
5603 }
5604
5605 else if (strcmp(param, "unicode_header_linestyle") == 0)
5606 {
5607 printf(_("Unicode header line style is \"%s\".\n"),
5608 _unicode_linestyle2string(popt->topt.unicode_header_linestyle));
5609 }
5610
5611 else
5612 {
5613 pg_log_error("\\pset: unknown option: %s", param);
5614 return false;
5615 }
5616
5617 return true;
5618 }
5619
5620 /*
5621 * savePsetInfo: make a malloc'd copy of the data in *popt.
5622 *
5623 * Possibly this should be somewhere else, but it's a bit specific to psql.
5624 */
5625 printQueryOpt *
5626 savePsetInfo(const printQueryOpt *popt)
5627 {
5628 printQueryOpt *save;
5629
5630 save = (printQueryOpt *) pg_malloc(sizeof(printQueryOpt));
5631
5632 /* Flat-copy all the scalar fields, then duplicate sub-structures. */
5633 memcpy(save, popt, sizeof(printQueryOpt));
5634
5635 /* topt.line_style points to const data that need not be duplicated */
5636 if (popt->topt.fieldSep.separator)
5637 save->topt.fieldSep.separator = pg_strdup(popt->topt.fieldSep.separator);
5638 if (popt->topt.recordSep.separator)
5639 save->topt.recordSep.separator = pg_strdup(popt->topt.recordSep.separator);
5640 if (popt->topt.tableAttr)
5641 save->topt.tableAttr = pg_strdup(popt->topt.tableAttr);
5642 if (popt->nullPrint)
5643 save->nullPrint = pg_strdup(popt->nullPrint);
5644 if (popt->title)
5645 save->title = pg_strdup(popt->title);
5646
5647 /*
5648 * footers and translate_columns are never set in psql's print settings,
5649 * so we needn't write code to duplicate them.
5650 */
5651 Assert(popt->footers == NULL);
5652 Assert(popt->translate_columns == NULL);
5653
5654 return save;
5655 }
5656
5657 /*
5658 * restorePsetInfo: restore *popt from the previously-saved copy *save,
5659 * then free *save.
5660 */
5661 void
5662 restorePsetInfo(printQueryOpt *popt, printQueryOpt *save)
5663 {
5664 /* Free all the old data we're about to overwrite the pointers to. */
5665
5666 /* topt.line_style points to const data that need not be duplicated */
5667 free(popt->topt.fieldSep.separator);
5668 free(popt->topt.recordSep.separator);
5669 free(popt->topt.tableAttr);
5670 free(popt->nullPrint);
5671 free(popt->title);
5672
5673 /*
5674 * footers and translate_columns are never set in psql's print settings,
5675 * so we needn't write code to duplicate them.
5676 */
5677 Assert(popt->footers == NULL);
5678 Assert(popt->translate_columns == NULL);
5679
5680 /* Now we may flat-copy all the fields, including pointers. */
5681 memcpy(popt, save, sizeof(printQueryOpt));
5682
5683 /* Lastly, free "save" ... but its sub-structures now belong to popt. */
5684 free(save);
5685 }
5686
5687 static const char *
5688 pset_bool_string(bool val)
5689 {
5690 return val ? "on" : "off";
5691 }
5692
5693
5694 static char *
5695 pset_quoted_string(const char *str)
5696 {
5697 char *ret = pg_malloc(strlen(str) * 2 + 3);
5698 char *r = ret;
5699
5700 *r++ = '\'';
5701
5702 for (; *str; str++)
5703 {
5704 if (*str == '\n')
5705 {
5706 *r++ = '\\';
5707 *r++ = 'n';
5708 }
5709 else if (*str == '\'')
5710 {
5711 *r++ = '\\';
5712 *r++ = '\'';
5713 }
5714 else
5715 *r++ = *str;
5716 }
5717
5718 *r++ = '\'';
5719 *r = '\0';
5720
5721 return ret;
5722 }
5723
5724
5725 /*
5726 * Return a malloc'ed string for the \pset value.
5727 *
5728 * Note that for some string parameters, print.c distinguishes between unset
5729 * and empty string, but for others it doesn't. This function should produce
5730 * output that produces the correct setting when fed back into \pset.
5731 */
5732 static char *
5733 pset_value_string(const char *param, printQueryOpt *popt)
5734 {
5735 Assert(param != NULL);
5736
5737 if (strcmp(param, "border") == 0)
5738 return psprintf("%d", popt->topt.border);
5739 else if (strcmp(param, "columns") == 0)
5740 return psprintf("%d", popt->topt.columns);
5741 else if (strcmp(param, "csv_fieldsep") == 0)
5742 return pset_quoted_string(popt->topt.csvFieldSep);
5743 else if (strcmp(param, "expanded") == 0)
5744 return pstrdup(popt->topt.expanded == 2
5745 ? "auto"
5746 : pset_bool_string(popt->topt.expanded));
5747 else if (strcmp(param, "fieldsep") == 0)
5748 return pset_quoted_string(popt->topt.fieldSep.separator
5749 ? popt->topt.fieldSep.separator
5750 : "");
5751 else if (strcmp(param, "fieldsep_zero") == 0)
5752 return pstrdup(pset_bool_string(popt->topt.fieldSep.separator_zero));
5753 else if (strcmp(param, "footer") == 0)
5754 return pstrdup(pset_bool_string(popt->topt.default_footer));
5755 else if (strcmp(param, "format") == 0)
5756 return pstrdup(_align2string(popt->topt.format));
5757 else if (strcmp(param, "linestyle") == 0)
5758 return pstrdup(get_line_style(&popt->topt)->name);
5759 else if (strcmp(param, "null") == 0)
5760 return pset_quoted_string(popt->nullPrint
5761 ? popt->nullPrint
5762 : "");
5763 else if (strcmp(param, "numericlocale") == 0)
5764 return pstrdup(pset_bool_string(popt->topt.numericLocale));
5765 else if (strcmp(param, "pager") == 0)
5766 return psprintf("%d", popt->topt.pager);
5767 else if (strcmp(param, "pager_min_lines") == 0)
5768 return psprintf("%d", popt->topt.pager_min_lines);
5769 else if (strcmp(param, "recordsep") == 0)
5770 return pset_quoted_string(popt->topt.recordSep.separator
5771 ? popt->topt.recordSep.separator
5772 : "");
5773 else if (strcmp(param, "recordsep_zero") == 0)
5774 return pstrdup(pset_bool_string(popt->topt.recordSep.separator_zero));
5775 else if (strcmp(param, "tableattr") == 0)
5776 return popt->topt.tableAttr ? pset_quoted_string(popt->topt.tableAttr) : pstrdup("");
5777 else if (strcmp(param, "title") == 0)
5778 return popt->title ? pset_quoted_string(popt->title) : pstrdup("");
5779 else if (strcmp(param, "tuples_only") == 0)
5780 return pstrdup(pset_bool_string(popt->topt.tuples_only));
5781 else if (strcmp(param, "unicode_border_linestyle") == 0)
5782 return pstrdup(_unicode_linestyle2string(popt->topt.unicode_border_linestyle));
5783 else if (strcmp(param, "unicode_column_linestyle") == 0)
5784 return pstrdup(_unicode_linestyle2string(popt->topt.unicode_column_linestyle));
5785 else if (strcmp(param, "unicode_header_linestyle") == 0)
5786 return pstrdup(_unicode_linestyle2string(popt->topt.unicode_header_linestyle));
5787 else if (strcmp(param, "xheader_width") == 0)
5788 {
5789 if (popt->topt.expanded_header_width_type == PRINT_XHEADER_FULL)
5790 return pstrdup("full");
5791 else if (popt->topt.expanded_header_width_type == PRINT_XHEADER_COLUMN)
5792 return pstrdup("column");
5793 else if (popt->topt.expanded_header_width_type == PRINT_XHEADER_PAGE)
5794 return pstrdup("page");
5795 else
5796 {
5797 /* must be PRINT_XHEADER_EXACT_WIDTH */
5798 char wbuff[32];
5799
5800 snprintf(wbuff, sizeof(wbuff), "%d",
5801 popt->topt.expanded_header_exact_width);
5802 return pstrdup(wbuff);
5803 }
5804 }
5805 else
5806 return pstrdup("ERROR");
5807 }
5808
5809
5810
5811 #ifndef WIN32
5812 #define DEFAULT_SHELL "/bin/sh"
5813 #else
5814 /*
5815 * CMD.EXE is in different places in different Win32 releases so we
5816 * have to rely on the path to find it.
5817 */
5818 #define DEFAULT_SHELL "cmd.exe"
5819 #endif
5820
5821 static bool
5822 do_shell(const char *command)
5823 {
5824 int result;
5825
5826 fflush(NULL);
5827 if (!command)
5828 {
5829 char *sys;
5830 const char *shellName;
5831
5832 shellName = getenv("SHELL");
5833 #ifdef WIN32
5834 if (shellName == NULL)
5835 shellName = getenv("COMSPEC");
5836 #endif
5837 if (shellName == NULL)
5838 shellName = DEFAULT_SHELL;
5839
5840 /* See EDITOR handling comment for an explanation */
5841 #ifndef WIN32
5842 sys = psprintf("exec %s", shellName);
5843 #else
5844 sys = psprintf("\"%s\"", shellName);
5845 #endif
5846 result = system(sys);
5847 free(sys);
5848 }
5849 else
5850 result = system(command);
5851
5852 SetShellResultVariables(result);
5853
5854 if (result == 127 || result == -1)
5855 {
5856 pg_log_error("\\!: failed");
5857 return false;
5858 }
5859 return true;
5860 }
5861
5862 /*
5863 * do_watch -- handler for \watch
5864 *
5865 * We break this out of exec_command to avoid having to plaster "volatile"
5866 * onto a bunch of exec_command's variables to silence stupider compilers.
5867 *
5868 * "sleep" is the amount of time to sleep during each loop, measured in
5869 * seconds. The internals of this function should use "sleep_ms" for
5870 * precise sleep time calculations.
5871 */
5872 static bool
5873 do_watch(PQExpBuffer query_buf, double sleep, int iter, int min_rows)
5874 {
5875 long sleep_ms = (long) (sleep * 1000);
5876 printQueryOpt myopt = pset.popt;
5877 const char *strftime_fmt;
5878 const char *user_title;
5879 char *title;
5880 const char *pagerprog = NULL;
5881 FILE *pagerpipe = NULL;
5882 int title_len;
5883 int res = 0;
5884 bool done = false;
5885 #ifndef WIN32
5886 sigset_t sigalrm_sigchld_sigint;
5887 sigset_t sigalrm_sigchld;
5888 sigset_t sigint;
5889 struct itimerval interval;
5890 #endif
5891
5892 if (!query_buf || query_buf->len <= 0)
5893 {
5894 pg_log_error("\\watch cannot be used with an empty query");
5895 return false;
5896 }
5897
5898 #ifndef WIN32
5899 sigemptyset(&sigalrm_sigchld_sigint);
5900 sigaddset(&sigalrm_sigchld_sigint, SIGCHLD);
5901 sigaddset(&sigalrm_sigchld_sigint, SIGALRM);
5902 sigaddset(&sigalrm_sigchld_sigint, SIGINT);
5903
5904 sigemptyset(&sigalrm_sigchld);
5905 sigaddset(&sigalrm_sigchld, SIGCHLD);
5906 sigaddset(&sigalrm_sigchld, SIGALRM);
5907
5908 sigemptyset(&sigint);
5909 sigaddset(&sigint, SIGINT);
5910
5911 /*
5912 * Block SIGALRM and SIGCHLD before we start the timer and the pager (if
5913 * configured), to avoid races. sigwait() will receive them.
5914 */
5915 sigprocmask(SIG_BLOCK, &sigalrm_sigchld, NULL);
5916
5917 /*
5918 * Set a timer to interrupt sigwait() so we can run the query at the
5919 * requested intervals.
5920 */
5921 interval.it_value.tv_sec = sleep_ms / 1000;
5922 interval.it_value.tv_usec = (sleep_ms % 1000) * 1000;
5923 interval.it_interval = interval.it_value;
5924 if (setitimer(ITIMER_REAL, &interval, NULL) < 0)
5925 {
5926 pg_log_error("could not set timer: %m");
5927 done = true;
5928 }
5929 #endif
5930
5931 /*
5932 * For \watch, we ignore the size of the result and always use the pager
5933 * as long as we're talking to a terminal and "\pset pager" is enabled.
5934 * However, we'll only use the pager identified by PSQL_WATCH_PAGER. We
5935 * ignore the regular PSQL_PAGER or PAGER environment variables, because
5936 * traditional pagers probably won't be very useful for showing a stream
5937 * of results.
5938 */
5939 #ifndef WIN32
5940 pagerprog = getenv("PSQL_WATCH_PAGER");
5941 /* if variable is empty or all-white-space, don't use pager */
5942 if (pagerprog && strspn(pagerprog, " \t\r\n") == strlen(pagerprog))
5943 pagerprog = NULL;
5944 #endif
5945 if (pagerprog && myopt.topt.pager &&
5946 isatty(fileno(stdin)) && isatty(fileno(stdout)))
5947 {
5948 fflush(NULL);
5949 disable_sigpipe_trap();
5950 pagerpipe = popen(pagerprog, "w");
5951
5952 if (!pagerpipe)
5953 /* silently proceed without pager */
5954 restore_sigpipe_trap();
5955 }
5956
5957 /*
5958 * Choose format for timestamps. We might eventually make this a \pset
5959 * option. In the meantime, using a variable for the format suppresses
5960 * overly-anal-retentive gcc warnings about %c being Y2K sensitive.
5961 */
5962 strftime_fmt = "%c";
5963
5964 /*
5965 * Set up rendering options, in particular, disable the pager unless
5966 * PSQL_WATCH_PAGER was successfully launched.
5967 */
5968 if (!pagerpipe)
5969 myopt.topt.pager = 0;
5970
5971 /*
5972 * If there's a title in the user configuration, make sure we have room
5973 * for it in the title buffer. Allow 128 bytes for the timestamp plus 128
5974 * bytes for the rest.
5975 */
5976 user_title = myopt.title;
5977 title_len = (user_title ? strlen(user_title) : 0) + 256;
5978 title = pg_malloc(title_len);
5979
5980 /* Loop to run query and then sleep awhile */
5981 while (!done)
5982 {
5983 time_t timer;
5984 char timebuf[128];
5985
5986 /*
5987 * Prepare title for output. Note that we intentionally include a
5988 * newline at the end of the title; this is somewhat historical but it
5989 * makes for reasonably nicely formatted output in simple cases.
5990 */
5991 timer = time(NULL);
5992 strftime(timebuf, sizeof(timebuf), strftime_fmt, localtime(&timer));
5993
5994 if (user_title)
5995 snprintf(title, title_len, _("%s\t%s (every %gs)\n"),
5996 user_title, timebuf, sleep_ms / 1000.0);
5997 else
5998 snprintf(title, title_len, _("%s (every %gs)\n"),
5999 timebuf, sleep_ms / 1000.0);
6000 myopt.title = title;
6001
6002 /* Run the query and print out the result */
6003 res = PSQLexecWatch(query_buf->data, &myopt, pagerpipe, min_rows);
6004
6005 /*
6006 * PSQLexecWatch handles the case where we can no longer repeat the
6007 * query, and returns 0 or -1.
6008 */
6009 if (res <= 0)
6010 break;
6011
6012 /* If we have iteration count, check that it's not exceeded yet */
6013 if (iter && (--iter <= 0))
6014 break;
6015
6016 /* Quit if error on pager pipe (probably pager has quit) */
6017 if (pagerpipe && ferror(pagerpipe))
6018 break;
6019
6020 /* Tight loop, no wait needed */
6021 if (sleep_ms == 0)
6022 continue;
6023
6024 #ifdef WIN32
6025
6026 /*
6027 * Wait a while before running the query again. Break the sleep into
6028 * short intervals (at most 1s); that's probably unnecessary since
6029 * pg_usleep is interruptible on Windows, but it's cheap insurance.
6030 */
6031 for (long i = sleep_ms; i > 0;)
6032 {
6033 long s = Min(i, 1000L);
6034
6035 pg_usleep(s * 1000L);
6036 if (cancel_pressed)
6037 {
6038 done = true;
6039 break;
6040 }
6041 i -= s;
6042 }
6043 #else
6044 /* sigwait() will handle SIGINT. */
6045 sigprocmask(SIG_BLOCK, &sigint, NULL);
6046 if (cancel_pressed)
6047 done = true;
6048
6049 /* Wait for SIGINT, SIGCHLD or SIGALRM. */
6050 while (!done)
6051 {
6052 int signal_received;
6053
6054 errno = sigwait(&sigalrm_sigchld_sigint, &signal_received);
6055 if (errno != 0)
6056 {
6057 /* Some other signal arrived? */
6058 if (errno == EINTR)
6059 continue;
6060 else
6061 {
6062 pg_log_error("could not wait for signals: %m");
6063 done = true;
6064 break;
6065 }
6066 }
6067 /* On ^C or pager exit, it's time to stop running the query. */
6068 if (signal_received == SIGINT || signal_received == SIGCHLD)
6069 done = true;
6070 /* Otherwise, we must have SIGALRM. Time to run the query again. */
6071 break;
6072 }
6073
6074 /* Unblock SIGINT so that slow queries can be interrupted. */
6075 sigprocmask(SIG_UNBLOCK, &sigint, NULL);
6076 #endif
6077 }
6078
6079 if (pagerpipe)
6080 {
6081 pclose(pagerpipe);
6082 restore_sigpipe_trap();
6083 }
6084 else
6085 {
6086 /*
6087 * If the terminal driver echoed "^C", libedit/libreadline might be
6088 * confused about the cursor position. Therefore, inject a newline
6089 * before the next prompt is displayed. We only do this when not
6090 * using a pager, because pagers are expected to restore the screen to
6091 * a sane state on exit.
6092 */
6093 fprintf(stdout, "\n");
6094 fflush(stdout);
6095 }
6096
6097 #ifndef WIN32
6098 /* Disable the interval timer. */
6099 memset(&interval, 0, sizeof(interval));
6100 setitimer(ITIMER_REAL, &interval, NULL);
6101 /* Unblock SIGINT, SIGCHLD and SIGALRM. */
6102 sigprocmask(SIG_UNBLOCK, &sigalrm_sigchld_sigint, NULL);
6103 #endif
6104
6105 pg_free(title);
6106 return (res >= 0);
6107 }
6108
6109 /*
6110 * a little code borrowed from PSQLexec() to manage ECHO_HIDDEN output.
6111 * returns true unless we have ECHO_HIDDEN_NOEXEC.
6112 */
6113 static bool
6114 echo_hidden_command(const char *query)
6115 {
6116 if (pset.echo_hidden != PSQL_ECHO_HIDDEN_OFF)
6117 {
6118 printf(_("/******** QUERY *********/\n"
6119 "%s\n"
6120 "/************************/\n\n"), query);
6121 fflush(stdout);
6122 if (pset.logfile)
6123 {
6124 fprintf(pset.logfile,
6125 _("/******** QUERY *********/\n"
6126 "%s\n"
6127 "/************************/\n\n"), query);
6128 fflush(pset.logfile);
6129 }
6130
6131 if (pset.echo_hidden == PSQL_ECHO_HIDDEN_NOEXEC)
6132 return false;
6133 }
6134 return true;
6135 }
6136
6137 /*
6138 * Look up the object identified by obj_type and desc. If successful,
6139 * store its OID in *obj_oid and return true, else return false.
6140 *
6141 * Note that we'll fail if the object doesn't exist OR if there are multiple
6142 * matching candidates OR if there's something syntactically wrong with the
6143 * object description; unfortunately it can be hard to tell the difference.
6144 */
6145 static bool
6146 lookup_object_oid(EditableObjectType obj_type, const char *desc,
6147 Oid *obj_oid)
6148 {
6149 bool result = true;
6150 PQExpBuffer query = createPQExpBuffer();
6151 PGresult *res;
6152
6153 switch (obj_type)
6154 {
6155 case EditableFunction:
6156
6157 /*
6158 * We have a function description, e.g. "x" or "x(int)". Issue a
6159 * query to retrieve the function's OID using a cast to regproc or
6160 * regprocedure (as appropriate).
6161 */
6162 appendPQExpBufferStr(query, "SELECT ");
6163 appendStringLiteralConn(query, desc, pset.db);
6164 appendPQExpBuffer(query, "::pg_catalog.%s::pg_catalog.oid",
6165 strchr(desc, '(') ? "regprocedure" : "regproc");
6166 break;
6167
6168 case EditableView:
6169
6170 /*
6171 * Convert view name (possibly schema-qualified) to OID. Note:
6172 * this code doesn't check if the relation is actually a view.
6173 * We'll detect that in get_create_object_cmd().
6174 */
6175 appendPQExpBufferStr(query, "SELECT ");
6176 appendStringLiteralConn(query, desc, pset.db);
6177 appendPQExpBufferStr(query, "::pg_catalog.regclass::pg_catalog.oid");
6178 break;
6179 }
6180
6181 if (!echo_hidden_command(query->data))
6182 {
6183 destroyPQExpBuffer(query);
6184 return false;
6185 }
6186 res = PQexec(pset.db, query->data);
6187 if (PQresultStatus(res) == PGRES_TUPLES_OK && PQntuples(res) == 1)
6188 *obj_oid = atooid(PQgetvalue(res, 0, 0));
6189 else
6190 {
6191 minimal_error_message(res);
6192 result = false;
6193 }
6194
6195 PQclear(res);
6196 destroyPQExpBuffer(query);
6197
6198 return result;
6199 }
6200
6201 /*
6202 * Construct a "CREATE OR REPLACE ..." command that describes the specified
6203 * database object. If successful, the result is stored in buf.
6204 */
6205 static bool
6206 get_create_object_cmd(EditableObjectType obj_type, Oid oid,
6207 PQExpBuffer buf)
6208 {
6209 bool result = true;
6210 PQExpBuffer query = createPQExpBuffer();
6211 PGresult *res;
6212
6213 switch (obj_type)
6214 {
6215 case EditableFunction:
6216 printfPQExpBuffer(query,
6217 "SELECT pg_catalog.pg_get_functiondef(%u)",
6218 oid);
6219 break;
6220
6221 case EditableView:
6222
6223 /*
6224 * pg_get_viewdef() just prints the query, so we must prepend
6225 * CREATE for ourselves. We must fully qualify the view name to
6226 * ensure the right view gets replaced. Also, check relation kind
6227 * to be sure it's a view.
6228 *
6229 * Starting with PG 9.4, views may have WITH [LOCAL|CASCADED]
6230 * CHECK OPTION. These are not part of the view definition
6231 * returned by pg_get_viewdef() and so need to be retrieved
6232 * separately. Materialized views (introduced in 9.3) may have
6233 * arbitrary storage parameter reloptions.
6234 */
6235 if (pset.sversion >= 90400)
6236 {
6237 printfPQExpBuffer(query,
6238 "SELECT nspname, relname, relkind, "
6239 "pg_catalog.pg_get_viewdef(c.oid, true), "
6240 "pg_catalog.array_remove(pg_catalog.array_remove(c.reloptions,'check_option=local'),'check_option=cascaded') AS reloptions, "
6241 "CASE WHEN 'check_option=local' = ANY (c.reloptions) THEN 'LOCAL'::text "
6242 "WHEN 'check_option=cascaded' = ANY (c.reloptions) THEN 'CASCADED'::text ELSE NULL END AS checkoption "
6243 "FROM pg_catalog.pg_class c "
6244 "LEFT JOIN pg_catalog.pg_namespace n "
6245 "ON c.relnamespace = n.oid WHERE c.oid = %u",
6246 oid);
6247 }
6248 else
6249 {
6250 printfPQExpBuffer(query,
6251 "SELECT nspname, relname, relkind, "
6252 "pg_catalog.pg_get_viewdef(c.oid, true), "
6253 "c.reloptions AS reloptions, "
6254 "NULL AS checkoption "
6255 "FROM pg_catalog.pg_class c "
6256 "LEFT JOIN pg_catalog.pg_namespace n "
6257 "ON c.relnamespace = n.oid WHERE c.oid = %u",
6258 oid);
6259 }
6260 break;
6261 }
6262
6263 if (!echo_hidden_command(query->data))
6264 {
6265 destroyPQExpBuffer(query);
6266 return false;
6267 }
6268 res = PQexec(pset.db, query->data);
6269 if (PQresultStatus(res) == PGRES_TUPLES_OK && PQntuples(res) == 1)
6270 {
6271 resetPQExpBuffer(buf);
6272 switch (obj_type)
6273 {
6274 case EditableFunction:
6275 appendPQExpBufferStr(buf, PQgetvalue(res, 0, 0));
6276 break;
6277
6278 case EditableView:
6279 {
6280 char *nspname = PQgetvalue(res, 0, 0);
6281 char *relname = PQgetvalue(res, 0, 1);
6282 char *relkind = PQgetvalue(res, 0, 2);
6283 char *viewdef = PQgetvalue(res, 0, 3);
6284 char *reloptions = PQgetvalue(res, 0, 4);
6285 char *checkoption = PQgetvalue(res, 0, 5);
6286
6287 /*
6288 * If the backend ever supports CREATE OR REPLACE
6289 * MATERIALIZED VIEW, allow that here; but as of today it
6290 * does not, so editing a matview definition in this way
6291 * is impossible.
6292 */
6293 switch (relkind[0])
6294 {
6295 #ifdef NOT_USED
6296 case RELKIND_MATVIEW:
6297 appendPQExpBufferStr(buf, "CREATE OR REPLACE MATERIALIZED VIEW ");
6298 break;
6299 #endif
6300 case RELKIND_VIEW:
6301 appendPQExpBufferStr(buf, "CREATE OR REPLACE VIEW ");
6302 break;
6303 default:
6304 pg_log_error("\"%s.%s\" is not a view",
6305 nspname, relname);
6306 result = false;
6307 break;
6308 }
6309 appendPQExpBuffer(buf, "%s.", fmtId(nspname));
6310 appendPQExpBufferStr(buf, fmtId(relname));
6311
6312 /* reloptions, if not an empty array "{}" */
6313 if (reloptions != NULL && strlen(reloptions) > 2)
6314 {
6315 appendPQExpBufferStr(buf, "\n WITH (");
6316 if (!appendReloptionsArray(buf, reloptions, "",
6317 pset.encoding,
6318 standard_strings()))
6319 {
6320 pg_log_error("could not parse reloptions array");
6321 result = false;
6322 }
6323 appendPQExpBufferChar(buf, ')');
6324 }
6325
6326 /* View definition from pg_get_viewdef (a SELECT query) */
6327 appendPQExpBuffer(buf, " AS\n%s", viewdef);
6328
6329 /* Get rid of the semicolon that pg_get_viewdef appends */
6330 if (buf->len > 0 && buf->data[buf->len - 1] == ';')
6331 buf->data[--(buf->len)] = '\0';
6332
6333 /* WITH [LOCAL|CASCADED] CHECK OPTION */
6334 if (checkoption && checkoption[0] != '\0')
6335 appendPQExpBuffer(buf, "\n WITH %s CHECK OPTION",
6336 checkoption);
6337 }
6338 break;
6339 }
6340 /* Make sure result ends with a newline */
6341 if (buf->len > 0 && buf->data[buf->len - 1] != '\n')
6342 appendPQExpBufferChar(buf, '\n');
6343 }
6344 else
6345 {
6346 minimal_error_message(res);
6347 result = false;
6348 }
6349
6350 PQclear(res);
6351 destroyPQExpBuffer(query);
6352
6353 return result;
6354 }
6355
6356 /*
6357 * If the given argument of \ef or \ev ends with a line number, delete the line
6358 * number from the argument string and return it as an integer. (We need
6359 * this kluge because we're too lazy to parse \ef's function or \ev's view
6360 * argument carefully --- we just slop it up in OT_WHOLE_LINE mode.)
6361 *
6362 * Returns -1 if no line number is present, 0 on error, or a positive value
6363 * on success.
6364 */
6365 static int
6366 strip_lineno_from_objdesc(char *obj)
6367 {
6368 char *c;
6369 int lineno;
6370
6371 if (!obj || obj[0] == '\0')
6372 return -1;
6373
6374 c = obj + strlen(obj) - 1;
6375
6376 /*
6377 * This business of parsing backwards is dangerous as can be in a
6378 * multibyte environment: there is no reason to believe that we are
6379 * looking at the first byte of a character, nor are we necessarily
6380 * working in a "safe" encoding. Fortunately the bitpatterns we are
6381 * looking for are unlikely to occur as non-first bytes, but beware of
6382 * trying to expand the set of cases that can be recognized. We must
6383 * guard the <ctype.h> macros by using isascii() first, too.
6384 */
6385
6386 /* skip trailing whitespace */
6387 while (c > obj && isascii((unsigned char) *c) && isspace((unsigned char) *c))
6388 c--;
6389
6390 /* must have a digit as last non-space char */
6391 if (c == obj || !isascii((unsigned char) *c) || !isdigit((unsigned char) *c))
6392 return -1;
6393
6394 /* find start of digit string */
6395 while (c > obj && isascii((unsigned char) *c) && isdigit((unsigned char) *c))
6396 c--;
6397
6398 /* digits must be separated from object name by space or closing paren */
6399 /* notice also that we are not allowing an empty object name ... */
6400 if (c == obj || !isascii((unsigned char) *c) ||
6401 !(isspace((unsigned char) *c) || *c == ')'))
6402 return -1;
6403
6404 /* parse digit string */
6405 c++;
6406 lineno = atoi(c);
6407 if (lineno < 1)
6408 {
6409 pg_log_error("invalid line number: %s", c);
6410 return 0;
6411 }
6412
6413 /* strip digit string from object name */
6414 *c = '\0';
6415
6416 return lineno;
6417 }
6418
6419 /*
6420 * Count number of lines in the buffer.
6421 * This is used to test if pager is needed or not.
6422 */
6423 static int
6424 count_lines_in_buf(PQExpBuffer buf)
6425 {
6426 int lineno = 0;
6427 const char *lines = buf->data;
6428
6429 while (*lines != '\0')
6430 {
6431 lineno++;
6432 /* find start of next line */
6433 lines = strchr(lines, '\n');
6434 if (!lines)
6435 break;
6436 lines++;
6437 }
6438
6439 return lineno;
6440 }
6441
6442 /*
6443 * Write text at *lines to output with line numbers.
6444 *
6445 * For functions, lineno "1" should correspond to the first line of the
6446 * function body; lines before that are unnumbered. We expect that
6447 * pg_get_functiondef() will emit that on a line beginning with "AS ",
6448 * "BEGIN ", or "RETURN ", and that there can be no such line before
6449 * the real start of the function body.
6450 *
6451 * Caution: this scribbles on *lines.
6452 */
6453 static void
6454 print_with_linenumbers(FILE *output, char *lines, bool is_func)
6455 {
6456 bool in_header = is_func;
6457 int lineno = 0;
6458
6459 while (*lines != '\0')
6460 {
6461 char *eol;
6462
6463 if (in_header &&
6464 (strncmp(lines, "AS ", 3) == 0 ||
6465 strncmp(lines, "BEGIN ", 6) == 0 ||
6466 strncmp(lines, "RETURN ", 7) == 0))
6467 in_header = false;
6468
6469 /* increment lineno only for body's lines */
6470 if (!in_header)
6471 lineno++;
6472
6473 /* find and mark end of current line */
6474 eol = strchr(lines, '\n');
6475 if (eol != NULL)
6476 *eol = '\0';
6477
6478 /* show current line as appropriate */
6479 if (in_header)
6480 fprintf(output, " %s\n", lines);
6481 else
6482 fprintf(output, "%-7d %s\n", lineno, lines);
6483
6484 /* advance to next line, if any */
6485 if (eol == NULL)
6486 break;
6487 lines = ++eol;
6488 }
6489 }
6490
6491 /*
6492 * Report just the primary error; this is to avoid cluttering the output
6493 * with, for instance, a redisplay of the internally generated query
6494 */
6495 static void
6496 minimal_error_message(PGresult *res)
6497 {
6498 PQExpBuffer msg;
6499 const char *fld;
6500
6501 msg = createPQExpBuffer();
6502
6503 fld = PQresultErrorField(res, PG_DIAG_SEVERITY);
6504 if (fld)
6505 printfPQExpBuffer(msg, "%s: ", fld);
6506 else
6507 printfPQExpBuffer(msg, "ERROR: ");
6508 fld = PQresultErrorField(res, PG_DIAG_MESSAGE_PRIMARY);
6509 if (fld)
6510 appendPQExpBufferStr(msg, fld);
6511 else
6512 appendPQExpBufferStr(msg, "(not available)");
6513 appendPQExpBufferChar(msg, '\n');
6514
6515 pg_log_error("%s", msg->data);
6516
6517 destroyPQExpBuffer(msg);
6518 }