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