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