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