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