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