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