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