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