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