PostgreSQL Source Code  git master
startup.c
Go to the documentation of this file.
1 /*
2  * psql - the PostgreSQL interactive terminal
3  *
4  * Copyright (c) 2000-2021, PostgreSQL Global Development Group
5  *
6  * src/bin/psql/startup.c
7  */
8 #include "postgres_fe.h"
9 
10 #ifndef WIN32
11 #include <unistd.h>
12 #else /* WIN32 */
13 #include <io.h>
14 #include <win32.h>
15 #endif /* WIN32 */
16 
17 #include "command.h"
18 #include "common.h"
19 #include "common/logging.h"
20 #include "common/string.h"
21 #include "describe.h"
22 #include "fe_utils/print.h"
23 #include "getopt_long.h"
24 #include "help.h"
25 #include "input.h"
26 #include "mainloop.h"
27 #include "settings.h"
28 
29 /*
30  * Global psql options
31  */
33 
34 #ifndef WIN32
35 #define SYSPSQLRC "psqlrc"
36 #define PSQLRC ".psqlrc"
37 #else
38 #define SYSPSQLRC "psqlrc"
39 #define PSQLRC "psqlrc.conf"
40 #endif
41 
42 /*
43  * Structures to pass information between the option parsing routine
44  * and the main function
45  */
47 {
51 };
52 
53 typedef struct SimpleActionListCell
54 {
57  char *val;
59 
60 typedef struct SimpleActionList
61 {
65 
66 struct adhoc_opts
67 {
68  char *dbname;
69  char *host;
70  char *port;
71  char *username;
72  char *logfilename;
74  bool no_psqlrc;
75  bool single_txn;
76  bool list_dbs;
78 };
79 
80 static void parse_psql_options(int argc, char *argv[],
81  struct adhoc_opts *options);
83  enum _actions action, const char *val);
84 static void process_psqlrc(char *argv0);
85 static void process_psqlrc_file(char *filename);
86 static void showVersion(void);
87 static void EstablishVariableSpace(void);
88 
89 #define NOPAGER 0
90 
91 static void
93 {
94  if (pset.queryFout && pset.queryFout != stdout)
95  fflush(pset.queryFout);
96 }
97 
98 static void
99 log_locus_callback(const char **filename, uint64 *lineno)
100 {
101  if (pset.inputfile)
102  {
103  *filename = pset.inputfile;
104  *lineno = pset.lineno;
105  }
106  else
107  {
108  *filename = NULL;
109  *lineno = 0;
110  }
111 }
112 
113 #ifdef HAVE_POSIX_DECL_SIGWAIT
114 static void
115 empty_signal_handler(SIGNAL_ARGS)
116 {
117 }
118 #endif
119 
120 /*
121  *
122  * main
123  *
124  */
125 int
126 main(int argc, char *argv[])
127 {
128  struct adhoc_opts options;
129  int successResult;
130  char *password = NULL;
131  bool new_pass;
132 
133  pg_logging_init(argv[0]);
136  set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("psql"));
137 
138  if (argc > 1)
139  {
140  if ((strcmp(argv[1], "-?") == 0) || (argc == 2 && (strcmp(argv[1], "--help") == 0)))
141  {
142  usage(NOPAGER);
143  exit(EXIT_SUCCESS);
144  }
145  if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
146  {
147  showVersion();
148  exit(EXIT_SUCCESS);
149  }
150  }
151 
152  pset.progname = get_progname(argv[0]);
153 
154  pset.db = NULL;
155  pset.dead_conn = NULL;
157  pset.encoding = PQenv2encoding();
158  pset.queryFout = stdout;
159  pset.queryFoutPipe = false;
160  pset.copyStream = NULL;
161  pset.last_error_result = NULL;
162  pset.cur_cmd_source = stdin;
163  pset.cur_cmd_interactive = false;
164 
165  /* We rely on unmentioned fields of pset.popt to start out 0/false/NULL */
166  pset.popt.topt.format = PRINT_ALIGNED;
167  pset.popt.topt.border = 1;
168  pset.popt.topt.pager = 1;
169  pset.popt.topt.pager_min_lines = 0;
170  pset.popt.topt.start_table = true;
171  pset.popt.topt.stop_table = true;
172  pset.popt.topt.default_footer = true;
173 
175  pset.popt.topt.csvFieldSep[1] = '\0';
176 
180 
181  refresh_utf8format(&(pset.popt.topt));
182 
183  /* We must get COLUMNS here before readline() sets it */
184  pset.popt.topt.env_columns = getenv("COLUMNS") ? atoi(getenv("COLUMNS")) : 0;
185 
186  pset.notty = (!isatty(fileno(stdin)) || !isatty(fileno(stdout)));
187 
188  pset.getPassword = TRI_DEFAULT;
189 
191 
192  /* Create variables showing psql version number */
193  SetVariable(pset.vars, "VERSION", PG_VERSION_STR);
194  SetVariable(pset.vars, "VERSION_NAME", PG_VERSION);
195  SetVariable(pset.vars, "VERSION_NUM", CppAsString2(PG_VERSION_NUM));
196 
197  /* Initialize variables for last error */
198  SetVariable(pset.vars, "LAST_ERROR_MESSAGE", "");
199  SetVariable(pset.vars, "LAST_ERROR_SQLSTATE", "00000");
200 
201  /* Default values for variables (that don't match the result of \unset) */
202  SetVariableBool(pset.vars, "AUTOCOMMIT");
203  SetVariable(pset.vars, "PROMPT1", DEFAULT_PROMPT1);
204  SetVariable(pset.vars, "PROMPT2", DEFAULT_PROMPT2);
205  SetVariable(pset.vars, "PROMPT3", DEFAULT_PROMPT3);
206 
207  parse_psql_options(argc, argv, &options);
208 
209  /*
210  * If no action was specified and we're in non-interactive mode, treat it
211  * as if the user had specified "-f -". This lets single-transaction mode
212  * work in this case.
213  */
214  if (options.actions.head == NULL && pset.notty)
215  simple_action_list_append(&options.actions, ACT_FILE, NULL);
216 
217  /* Bail out if -1 was specified but will be ignored. */
218  if (options.single_txn && options.actions.head == NULL)
219  {
220  pg_log_fatal("-1 can only be used in non-interactive mode");
221  exit(EXIT_FAILURE);
222  }
223 
224  if (!pset.popt.topt.fieldSep.separator &&
226  {
228  pset.popt.topt.fieldSep.separator_zero = false;
229  }
230  if (!pset.popt.topt.recordSep.separator &&
232  {
234  pset.popt.topt.recordSep.separator_zero = false;
235  }
236 
237  if (pset.getPassword == TRI_YES)
238  {
239  /*
240  * We can't be sure yet of the username that will be used, so don't
241  * offer a potentially wrong one. Typical uses of this option are
242  * noninteractive anyway.
243  */
244  password = simple_prompt("Password: ", false);
245  }
246 
247  /* loop until we have a password if requested by backend */
248  do
249  {
250 #define PARAMS_ARRAY_SIZE 8
251  const char **keywords = pg_malloc(PARAMS_ARRAY_SIZE * sizeof(*keywords));
252  const char **values = pg_malloc(PARAMS_ARRAY_SIZE * sizeof(*values));
253 
254  keywords[0] = "host";
255  values[0] = options.host;
256  keywords[1] = "port";
257  values[1] = options.port;
258  keywords[2] = "user";
259  values[2] = options.username;
260  keywords[3] = "password";
261  values[3] = password;
262  keywords[4] = "dbname"; /* see do_connect() */
263  values[4] = (options.list_dbs && options.dbname == NULL) ?
264  "postgres" : options.dbname;
265  keywords[5] = "fallback_application_name";
266  values[5] = pset.progname;
267  keywords[6] = "client_encoding";
268  values[6] = (pset.notty || getenv("PGCLIENTENCODING")) ? NULL : "auto";
269  keywords[7] = NULL;
270  values[7] = NULL;
271 
272  new_pass = false;
273  pset.db = PQconnectdbParams(keywords, values, true);
274  free(keywords);
275  free(values);
276 
277  if (PQstatus(pset.db) == CONNECTION_BAD &&
279  !password &&
280  pset.getPassword != TRI_NO)
281  {
282  /*
283  * Before closing the old PGconn, extract the user name that was
284  * actually connected with --- it might've come out of a URI or
285  * connstring "database name" rather than options.username.
286  */
287  const char *realusername = PQuser(pset.db);
288  char *password_prompt;
289 
290  if (realusername && realusername[0])
291  password_prompt = psprintf(_("Password for user %s: "),
292  realusername);
293  else
294  password_prompt = pg_strdup(_("Password: "));
295  PQfinish(pset.db);
296 
297  password = simple_prompt(password_prompt, false);
298  free(password_prompt);
299  new_pass = true;
300  }
301  } while (new_pass);
302 
303  if (PQstatus(pset.db) == CONNECTION_BAD)
304  {
305  pg_log_error("%s", PQerrorMessage(pset.db));
306  PQfinish(pset.db);
307  exit(EXIT_BADCONN);
308  }
309 
311 
312 #ifdef HAVE_POSIX_DECL_SIGWAIT
313 
314  /*
315  * do_watch() needs signal handlers installed (otherwise sigwait() will
316  * filter them out on some platforms), but doesn't need them to do
317  * anything, and they shouldn't ever run (unless perhaps a stray SIGALRM
318  * arrives due to a race when do_watch() cancels an itimer).
319  */
320  pqsignal(SIGCHLD, empty_signal_handler);
321  pqsignal(SIGALRM, empty_signal_handler);
322 #endif
323 
325 
326  SyncVariables();
327 
328  if (options.list_dbs)
329  {
330  int success;
331 
332  if (!options.no_psqlrc)
333  process_psqlrc(argv[0]);
334 
335  success = listAllDbs(NULL, false);
336  PQfinish(pset.db);
337  exit(success ? EXIT_SUCCESS : EXIT_FAILURE);
338  }
339 
340  if (options.logfilename)
341  {
342  pset.logfile = fopen(options.logfilename, "a");
343  if (!pset.logfile)
344  {
345  pg_log_fatal("could not open log file \"%s\": %m",
346  options.logfilename);
347  exit(EXIT_FAILURE);
348  }
349  }
350 
351  if (!options.no_psqlrc)
352  process_psqlrc(argv[0]);
353 
354  /*
355  * If any actions were given by user, process them in the order in which
356  * they were specified. Note single_txn is only effective in this mode.
357  */
358  if (options.actions.head != NULL)
359  {
360  PGresult *res;
361  SimpleActionListCell *cell;
362 
363  successResult = EXIT_SUCCESS; /* silence compiler */
364 
365  if (options.single_txn)
366  {
367  if ((res = PSQLexec("BEGIN")) == NULL)
368  {
369  if (pset.on_error_stop)
370  {
371  successResult = EXIT_USER;
372  goto error;
373  }
374  }
375  else
376  PQclear(res);
377  }
378 
379  for (cell = options.actions.head; cell; cell = cell->next)
380  {
381  if (cell->action == ACT_SINGLE_QUERY)
382  {
384 
385  if (pset.echo == PSQL_ECHO_ALL)
386  puts(cell->val);
387 
388  successResult = SendQuery(cell->val)
390  }
391  else if (cell->action == ACT_SINGLE_SLASH)
392  {
393  PsqlScanState scan_state;
394  ConditionalStack cond_stack;
395 
397 
398  if (pset.echo == PSQL_ECHO_ALL)
399  puts(cell->val);
400 
401  scan_state = psql_scan_create(&psqlscan_callbacks);
402  psql_scan_setup(scan_state,
403  cell->val, strlen(cell->val),
404  pset.encoding, standard_strings());
405  cond_stack = conditional_stack_create();
406  psql_scan_set_passthrough(scan_state, (void *) cond_stack);
407 
408  successResult = HandleSlashCmds(scan_state,
409  cond_stack,
410  NULL,
411  NULL) != PSQL_CMD_ERROR
413 
414  psql_scan_destroy(scan_state);
415  conditional_stack_destroy(cond_stack);
416  }
417  else if (cell->action == ACT_FILE)
418  {
419  successResult = process_file(cell->val, false);
420  }
421  else
422  {
423  /* should never come here */
424  Assert(false);
425  }
426 
427  if (successResult != EXIT_SUCCESS && pset.on_error_stop)
428  break;
429  }
430 
431  if (options.single_txn)
432  {
433  if ((res = PSQLexec("COMMIT")) == NULL)
434  {
435  if (pset.on_error_stop)
436  {
437  successResult = EXIT_USER;
438  goto error;
439  }
440  }
441  else
442  PQclear(res);
443  }
444 
445 error:
446  ;
447  }
448 
449  /*
450  * or otherwise enter interactive main loop
451  */
452  else
453  {
455  connection_warnings(true);
456  if (!pset.quiet)
457  printf(_("Type \"help\" for help.\n\n"));
458  initializeInput(options.no_readline ? 0 : 1);
459  successResult = MainLoop(stdin);
460  }
461 
462  /* clean up */
463  if (pset.logfile)
464  fclose(pset.logfile);
465  if (pset.db)
466  PQfinish(pset.db);
467  if (pset.dead_conn)
468  PQfinish(pset.dead_conn);
469  setQFout(NULL);
470 
471  return successResult;
472 }
473 
474 
475 /*
476  * Parse command line options
477  */
478 
479 static void
480 parse_psql_options(int argc, char *argv[], struct adhoc_opts *options)
481 {
482  static struct option long_options[] =
483  {
484  {"echo-all", no_argument, NULL, 'a'},
485  {"no-align", no_argument, NULL, 'A'},
486  {"command", required_argument, NULL, 'c'},
487  {"dbname", required_argument, NULL, 'd'},
488  {"echo-queries", no_argument, NULL, 'e'},
489  {"echo-errors", no_argument, NULL, 'b'},
490  {"echo-hidden", no_argument, NULL, 'E'},
491  {"file", required_argument, NULL, 'f'},
492  {"field-separator", required_argument, NULL, 'F'},
493  {"field-separator-zero", no_argument, NULL, 'z'},
494  {"host", required_argument, NULL, 'h'},
495  {"html", no_argument, NULL, 'H'},
496  {"list", no_argument, NULL, 'l'},
497  {"log-file", required_argument, NULL, 'L'},
498  {"no-readline", no_argument, NULL, 'n'},
499  {"single-transaction", no_argument, NULL, '1'},
500  {"output", required_argument, NULL, 'o'},
501  {"port", required_argument, NULL, 'p'},
502  {"pset", required_argument, NULL, 'P'},
503  {"quiet", no_argument, NULL, 'q'},
504  {"record-separator", required_argument, NULL, 'R'},
505  {"record-separator-zero", no_argument, NULL, '0'},
506  {"single-step", no_argument, NULL, 's'},
507  {"single-line", no_argument, NULL, 'S'},
508  {"tuples-only", no_argument, NULL, 't'},
509  {"table-attr", required_argument, NULL, 'T'},
510  {"username", required_argument, NULL, 'U'},
511  {"set", required_argument, NULL, 'v'},
512  {"variable", required_argument, NULL, 'v'},
513  {"version", no_argument, NULL, 'V'},
514  {"no-password", no_argument, NULL, 'w'},
515  {"password", no_argument, NULL, 'W'},
516  {"expanded", no_argument, NULL, 'x'},
517  {"no-psqlrc", no_argument, NULL, 'X'},
518  {"help", optional_argument, NULL, 1},
519  {"csv", no_argument, NULL, 2},
520  {NULL, 0, NULL, 0}
521  };
522 
523  int optindex;
524  int c;
525 
526  memset(options, 0, sizeof *options);
527 
528  while ((c = getopt_long(argc, argv, "aAbc:d:eEf:F:h:HlL:no:p:P:qR:sStT:U:v:VwWxXz?01",
529  long_options, &optindex)) != -1)
530  {
531  switch (c)
532  {
533  case 'a':
534  SetVariable(pset.vars, "ECHO", "all");
535  break;
536  case 'A':
538  break;
539  case 'b':
540  SetVariable(pset.vars, "ECHO", "errors");
541  break;
542  case 'c':
543  if (optarg[0] == '\\')
546  optarg + 1);
547  else
550  optarg);
551  break;
552  case 'd':
553  options->dbname = pg_strdup(optarg);
554  break;
555  case 'e':
556  SetVariable(pset.vars, "ECHO", "queries");
557  break;
558  case 'E':
559  SetVariableBool(pset.vars, "ECHO_HIDDEN");
560  break;
561  case 'f':
563  ACT_FILE,
564  optarg);
565  break;
566  case 'F':
568  pset.popt.topt.fieldSep.separator_zero = false;
569  break;
570  case 'h':
571  options->host = pg_strdup(optarg);
572  break;
573  case 'H':
574  pset.popt.topt.format = PRINT_HTML;
575  break;
576  case 'l':
577  options->list_dbs = true;
578  break;
579  case 'L':
580  options->logfilename = pg_strdup(optarg);
581  break;
582  case 'n':
583  options->no_readline = true;
584  break;
585  case 'o':
586  if (!setQFout(optarg))
587  exit(EXIT_FAILURE);
588  break;
589  case 'p':
590  options->port = pg_strdup(optarg);
591  break;
592  case 'P':
593  {
594  char *value;
595  char *equal_loc;
596  bool result;
597 
598  value = pg_strdup(optarg);
599  equal_loc = strchr(value, '=');
600  if (!equal_loc)
601  result = do_pset(value, NULL, &pset.popt, true);
602  else
603  {
604  *equal_loc = '\0';
605  result = do_pset(value, equal_loc + 1, &pset.popt, true);
606  }
607 
608  if (!result)
609  {
610  pg_log_fatal("could not set printing parameter \"%s\"", value);
611  exit(EXIT_FAILURE);
612  }
613 
614  free(value);
615  break;
616  }
617  case 'q':
618  SetVariableBool(pset.vars, "QUIET");
619  break;
620  case 'R':
622  pset.popt.topt.recordSep.separator_zero = false;
623  break;
624  case 's':
625  SetVariableBool(pset.vars, "SINGLESTEP");
626  break;
627  case 'S':
628  SetVariableBool(pset.vars, "SINGLELINE");
629  break;
630  case 't':
631  pset.popt.topt.tuples_only = true;
632  break;
633  case 'T':
635  break;
636  case 'U':
637  options->username = pg_strdup(optarg);
638  break;
639  case 'v':
640  {
641  char *value;
642  char *equal_loc;
643 
644  value = pg_strdup(optarg);
645  equal_loc = strchr(value, '=');
646  if (!equal_loc)
647  {
648  if (!DeleteVariable(pset.vars, value))
649  exit(EXIT_FAILURE); /* error already printed */
650  }
651  else
652  {
653  *equal_loc = '\0';
654  if (!SetVariable(pset.vars, value, equal_loc + 1))
655  exit(EXIT_FAILURE); /* error already printed */
656  }
657 
658  free(value);
659  break;
660  }
661  case 'V':
662  showVersion();
663  exit(EXIT_SUCCESS);
664  case 'w':
665  pset.getPassword = TRI_NO;
666  break;
667  case 'W':
668  pset.getPassword = TRI_YES;
669  break;
670  case 'x':
671  pset.popt.topt.expanded = true;
672  break;
673  case 'X':
674  options->no_psqlrc = true;
675  break;
676  case 'z':
677  pset.popt.topt.fieldSep.separator_zero = true;
678  break;
679  case '0':
680  pset.popt.topt.recordSep.separator_zero = true;
681  break;
682  case '1':
683  options->single_txn = true;
684  break;
685  case '?':
686  if (optind <= argc &&
687  strcmp(argv[optind - 1], "-?") == 0)
688  {
689  /* actual help option given */
690  usage(NOPAGER);
691  exit(EXIT_SUCCESS);
692  }
693  else
694  {
695  /* getopt error (unknown option or missing argument) */
696  goto unknown_option;
697  }
698  break;
699  case 1:
700  {
701  if (!optarg || strcmp(optarg, "options") == 0)
702  usage(NOPAGER);
703  else if (optarg && strcmp(optarg, "commands") == 0)
705  else if (optarg && strcmp(optarg, "variables") == 0)
707  else
708  goto unknown_option;
709 
710  exit(EXIT_SUCCESS);
711  }
712  break;
713  case 2:
714  pset.popt.topt.format = PRINT_CSV;
715  break;
716  default:
717  unknown_option:
718  fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
719  pset.progname);
720  exit(EXIT_FAILURE);
721  break;
722  }
723  }
724 
725  /*
726  * if we still have arguments, use it as the database name and username
727  */
728  while (argc - optind >= 1)
729  {
730  if (!options->dbname)
731  options->dbname = argv[optind];
732  else if (!options->username)
733  options->username = argv[optind];
734  else if (!pset.quiet)
735  pg_log_warning("extra command-line argument \"%s\" ignored",
736  argv[optind]);
737 
738  optind++;
739  }
740 }
741 
742 
743 /*
744  * Append a new item to the end of the SimpleActionList.
745  * Note that "val" is copied if it's not NULL.
746  */
747 static void
749  enum _actions action, const char *val)
750 {
751  SimpleActionListCell *cell;
752 
754 
755  cell->next = NULL;
756  cell->action = action;
757  if (val)
758  cell->val = pg_strdup(val);
759  else
760  cell->val = NULL;
761 
762  if (list->tail)
763  list->tail->next = cell;
764  else
765  list->head = cell;
766  list->tail = cell;
767 }
768 
769 
770 /*
771  * Load .psqlrc file, if found.
772  */
773 static void
775 {
776  char home[MAXPGPATH];
777  char rc_file[MAXPGPATH];
778  char my_exec_path[MAXPGPATH];
779  char etc_path[MAXPGPATH];
780  char *envrc = getenv("PSQLRC");
781 
782  if (find_my_exec(argv0, my_exec_path) < 0)
783  {
784  pg_log_fatal("could not find own program executable");
785  exit(EXIT_FAILURE);
786  }
787 
788  get_etc_path(my_exec_path, etc_path);
789 
790  snprintf(rc_file, MAXPGPATH, "%s/%s", etc_path, SYSPSQLRC);
791  process_psqlrc_file(rc_file);
792 
793  if (envrc != NULL && strlen(envrc) > 0)
794  {
795  /* might need to free() this */
796  char *envrc_alloc = pstrdup(envrc);
797 
798  expand_tilde(&envrc_alloc);
799  process_psqlrc_file(envrc_alloc);
800  }
801  else if (get_home_path(home))
802  {
803  snprintf(rc_file, MAXPGPATH, "%s/%s", home, PSQLRC);
804  process_psqlrc_file(rc_file);
805  }
806 }
807 
808 
809 
810 static void
812 {
813  char *psqlrc_minor,
814  *psqlrc_major;
815 
816 #if defined(WIN32) && (!defined(__MINGW32__))
817 #define R_OK 4
818 #endif
819 
820  psqlrc_minor = psprintf("%s-%s", filename, PG_VERSION);
821  psqlrc_major = psprintf("%s-%s", filename, PG_MAJORVERSION);
822 
823  /* check for minor version first, then major, then no version */
824  if (access(psqlrc_minor, R_OK) == 0)
825  (void) process_file(psqlrc_minor, false);
826  else if (access(psqlrc_major, R_OK) == 0)
827  (void) process_file(psqlrc_major, false);
828  else if (access(filename, R_OK) == 0)
829  (void) process_file(filename, false);
830 
831  free(psqlrc_minor);
832  free(psqlrc_major);
833 }
834 
835 
836 
837 /* showVersion
838  *
839  * This output format is intended to match GNU standards.
840  */
841 static void
843 {
844  puts("psql (PostgreSQL) " PG_VERSION);
845 }
846 
847 
848 
849 /*
850  * Substitute hooks and assign hooks for psql variables.
851  *
852  * This isn't an amazingly good place for them, but neither is anywhere else.
853  *
854  * By policy, every special variable that controls any psql behavior should
855  * have one or both hooks, even if they're just no-ops. This ensures that
856  * the variable will remain present in variables.c's list even when unset,
857  * which ensures that it's known to tab completion.
858  */
859 
860 static char *
862 {
863  if (newval == NULL)
864  {
865  /* "\unset FOO" becomes "\set FOO off" */
866  newval = pg_strdup("off");
867  }
868  else if (newval[0] == '\0')
869  {
870  /* "\set FOO" becomes "\set FOO on" */
871  pg_free(newval);
872  newval = pg_strdup("on");
873  }
874  return newval;
875 }
876 
877 static bool
879 {
880  return ParseVariableBool(newval, "AUTOCOMMIT", &pset.autocommit);
881 }
882 
883 static bool
885 {
886  return ParseVariableBool(newval, "ON_ERROR_STOP", &pset.on_error_stop);
887 }
888 
889 static bool
890 quiet_hook(const char *newval)
891 {
892  return ParseVariableBool(newval, "QUIET", &pset.quiet);
893 }
894 
895 static bool
897 {
898  return ParseVariableBool(newval, "SINGLELINE", &pset.singleline);
899 }
900 
901 static bool
903 {
904  return ParseVariableBool(newval, "SINGLESTEP", &pset.singlestep);
905 }
906 
907 static char *
909 {
910  if (newval == NULL)
911  newval = pg_strdup("0");
912  return newval;
913 }
914 
915 static bool
917 {
918  return ParseVariableNum(newval, "FETCH_COUNT", &pset.fetch_count);
919 }
920 
921 static bool
922 histfile_hook(const char *newval)
923 {
924  /*
925  * Someday we might try to validate the filename, but for now, this is
926  * just a placeholder to ensure HISTFILE is known to tab completion.
927  */
928  return true;
929 }
930 
931 static char *
933 {
934  if (newval == NULL)
935  newval = pg_strdup("500");
936  return newval;
937 }
938 
939 static bool
940 histsize_hook(const char *newval)
941 {
942  return ParseVariableNum(newval, "HISTSIZE", &pset.histsize);
943 }
944 
945 static char *
947 {
948  int dummy;
949 
950  /*
951  * This tries to mimic the behavior of bash, to wit "If set, the value is
952  * the number of consecutive EOF characters which must be typed as the
953  * first characters on an input line before bash exits. If the variable
954  * exists but does not have a numeric value, or has no value, the default
955  * value is 10. If it does not exist, EOF signifies the end of input to
956  * the shell." Unlike bash, however, we insist on the stored value
957  * actually being a valid integer.
958  */
959  if (newval == NULL)
960  newval = pg_strdup("0");
961  else if (!ParseVariableNum(newval, NULL, &dummy))
962  newval = pg_strdup("10");
963  return newval;
964 }
965 
966 static bool
967 ignoreeof_hook(const char *newval)
968 {
969  return ParseVariableNum(newval, "IGNOREEOF", &pset.ignoreeof);
970 }
971 
972 static char *
974 {
975  if (newval == NULL)
976  newval = pg_strdup("none");
977  return newval;
978 }
979 
980 static bool
981 echo_hook(const char *newval)
982 {
983  Assert(newval != NULL); /* else substitute hook messed up */
984  if (pg_strcasecmp(newval, "queries") == 0)
985  pset.echo = PSQL_ECHO_QUERIES;
986  else if (pg_strcasecmp(newval, "errors") == 0)
987  pset.echo = PSQL_ECHO_ERRORS;
988  else if (pg_strcasecmp(newval, "all") == 0)
989  pset.echo = PSQL_ECHO_ALL;
990  else if (pg_strcasecmp(newval, "none") == 0)
991  pset.echo = PSQL_ECHO_NONE;
992  else
993  {
994  PsqlVarEnumError("ECHO", newval, "none, errors, queries, all");
995  return false;
996  }
997  return true;
998 }
999 
1000 static bool
1002 {
1003  Assert(newval != NULL); /* else substitute hook messed up */
1004  if (pg_strcasecmp(newval, "noexec") == 0)
1006  else
1007  {
1008  bool on_off;
1009 
1010  if (ParseVariableBool(newval, NULL, &on_off))
1012  else
1013  {
1014  PsqlVarEnumError("ECHO_HIDDEN", newval, "on, off, noexec");
1015  return false;
1016  }
1017  }
1018  return true;
1019 }
1020 
1021 static bool
1023 {
1024  Assert(newval != NULL); /* else substitute hook messed up */
1025  if (pg_strcasecmp(newval, "interactive") == 0)
1027  else
1028  {
1029  bool on_off;
1030 
1031  if (ParseVariableBool(newval, NULL, &on_off))
1033  else
1034  {
1035  PsqlVarEnumError("ON_ERROR_ROLLBACK", newval, "on, off, interactive");
1036  return false;
1037  }
1038  }
1039  return true;
1040 }
1041 
1042 static char *
1044 {
1045  if (newval == NULL)
1046  newval = pg_strdup("preserve-upper");
1047  return newval;
1048 }
1049 
1050 static bool
1052 {
1053  Assert(newval != NULL); /* else substitute hook messed up */
1054  if (pg_strcasecmp(newval, "preserve-upper") == 0)
1056  else if (pg_strcasecmp(newval, "preserve-lower") == 0)
1058  else if (pg_strcasecmp(newval, "upper") == 0)
1060  else if (pg_strcasecmp(newval, "lower") == 0)
1062  else
1063  {
1064  PsqlVarEnumError("COMP_KEYWORD_CASE", newval,
1065  "lower, upper, preserve-lower, preserve-upper");
1066  return false;
1067  }
1068  return true;
1069 }
1070 
1071 static char *
1073 {
1074  if (newval == NULL)
1075  newval = pg_strdup("none");
1076  return newval;
1077 }
1078 
1079 static bool
1081 {
1082  Assert(newval != NULL); /* else substitute hook messed up */
1083  if (pg_strcasecmp(newval, "ignorespace") == 0)
1085  else if (pg_strcasecmp(newval, "ignoredups") == 0)
1087  else if (pg_strcasecmp(newval, "ignoreboth") == 0)
1089  else if (pg_strcasecmp(newval, "none") == 0)
1090  pset.histcontrol = hctl_none;
1091  else
1092  {
1093  PsqlVarEnumError("HISTCONTROL", newval,
1094  "none, ignorespace, ignoredups, ignoreboth");
1095  return false;
1096  }
1097  return true;
1098 }
1099 
1100 static bool
1101 prompt1_hook(const char *newval)
1102 {
1103  pset.prompt1 = newval ? newval : "";
1104  return true;
1105 }
1106 
1107 static bool
1108 prompt2_hook(const char *newval)
1109 {
1110  pset.prompt2 = newval ? newval : "";
1111  return true;
1112 }
1113 
1114 static bool
1115 prompt3_hook(const char *newval)
1116 {
1117  pset.prompt3 = newval ? newval : "";
1118  return true;
1119 }
1120 
1121 static char *
1123 {
1124  if (newval == NULL)
1125  newval = pg_strdup("default");
1126  return newval;
1127 }
1128 
1129 static bool
1131 {
1132  Assert(newval != NULL); /* else substitute hook messed up */
1133  if (pg_strcasecmp(newval, "default") == 0)
1134  pset.verbosity = PQERRORS_DEFAULT;
1135  else if (pg_strcasecmp(newval, "verbose") == 0)
1136  pset.verbosity = PQERRORS_VERBOSE;
1137  else if (pg_strcasecmp(newval, "terse") == 0)
1138  pset.verbosity = PQERRORS_TERSE;
1139  else if (pg_strcasecmp(newval, "sqlstate") == 0)
1141  else
1142  {
1143  PsqlVarEnumError("VERBOSITY", newval, "default, verbose, terse, sqlstate");
1144  return false;
1145  }
1146 
1147  if (pset.db)
1148  PQsetErrorVerbosity(pset.db, pset.verbosity);
1149  return true;
1150 }
1151 
1152 static char *
1154 {
1155  if (newval == NULL)
1156  newval = pg_strdup("errors");
1157  return newval;
1158 }
1159 
1160 static bool
1162 {
1163  Assert(newval != NULL); /* else substitute hook messed up */
1164  if (pg_strcasecmp(newval, "never") == 0)
1166  else if (pg_strcasecmp(newval, "errors") == 0)
1168  else if (pg_strcasecmp(newval, "always") == 0)
1170  else
1171  {
1172  PsqlVarEnumError("SHOW_CONTEXT", newval, "never, errors, always");
1173  return false;
1174  }
1175 
1176  if (pset.db)
1178  return true;
1179 }
1180 
1181 static bool
1183 {
1184  return ParseVariableBool(newval, "HIDE_TOAST_COMPRESSION",
1185  &pset.hide_compression);
1186 }
1187 
1188 static bool
1190 {
1191  return ParseVariableBool(newval, "HIDE_TABLEAM", &pset.hide_tableam);
1192 }
1193 
1194 static void
1196 {
1197  pset.vars = CreateVariableSpace();
1198 
1199  SetVariableHooks(pset.vars, "AUTOCOMMIT",
1201  autocommit_hook);
1202  SetVariableHooks(pset.vars, "ON_ERROR_STOP",
1205  SetVariableHooks(pset.vars, "QUIET",
1207  quiet_hook);
1208  SetVariableHooks(pset.vars, "SINGLELINE",
1210  singleline_hook);
1211  SetVariableHooks(pset.vars, "SINGLESTEP",
1213  singlestep_hook);
1214  SetVariableHooks(pset.vars, "FETCH_COUNT",
1217  SetVariableHooks(pset.vars, "HISTFILE",
1218  NULL,
1219  histfile_hook);
1220  SetVariableHooks(pset.vars, "HISTSIZE",
1222  histsize_hook);
1223  SetVariableHooks(pset.vars, "IGNOREEOF",
1225  ignoreeof_hook);
1226  SetVariableHooks(pset.vars, "ECHO",
1228  echo_hook);
1229  SetVariableHooks(pset.vars, "ECHO_HIDDEN",
1232  SetVariableHooks(pset.vars, "ON_ERROR_ROLLBACK",
1235  SetVariableHooks(pset.vars, "COMP_KEYWORD_CASE",
1238  SetVariableHooks(pset.vars, "HISTCONTROL",
1241  SetVariableHooks(pset.vars, "PROMPT1",
1242  NULL,
1243  prompt1_hook);
1244  SetVariableHooks(pset.vars, "PROMPT2",
1245  NULL,
1246  prompt2_hook);
1247  SetVariableHooks(pset.vars, "PROMPT3",
1248  NULL,
1249  prompt3_hook);
1250  SetVariableHooks(pset.vars, "VERBOSITY",
1252  verbosity_hook);
1253  SetVariableHooks(pset.vars, "SHOW_CONTEXT",
1256  SetVariableHooks(pset.vars, "HIDE_TOAST_COMPRESSION",
1259  SetVariableHooks(pset.vars, "HIDE_TABLEAM",
1262 }
static void parse_psql_options(int argc, char *argv[], struct adhoc_opts *options)
Definition: startup.c:480
bool ParseVariableNum(const char *value, const char *name, int *result)
Definition: variables.c:156
int env_columns
Definition: print.h:123
#define NOPAGER
Definition: startup.c:89
PSQL_ECHO echo
Definition: settings.h:142
bool singlestep
Definition: settings.h:136
static void process_psqlrc(char *argv0)
Definition: startup.c:774
SimpleActionList actions
Definition: startup.c:77
PGconn * db
Definition: settings.h:82
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6744
static char * argv0
Definition: pg_ctl.c:97
static char * verbosity_substitute_hook(char *newval)
Definition: startup.c:1122
char * username
Definition: startup.c:71
static void log_pre_callback(void)
Definition: startup.c:92
#define EXIT_SUCCESS
Definition: settings.h:158
PQnoticeProcessor PQsetNoticeProcessor(PGconn *conn, PQnoticeProcessor proc, void *arg)
Definition: fe-connect.c:6912
void SyncVariables(void)
Definition: command.c:3661
static void error(void)
Definition: sql-dyntest.c:147
static void EstablishVariableSpace(void)
Definition: startup.c:1195
void * pg_malloc(size_t size)
Definition: fe_memutils.c:47
enum _actions action
Definition: startup.c:56
const char * get_progname(const char *argv0)
Definition: path.c:453
#define SIGCHLD
Definition: win32_port.h:169
#define pg_log_error(...)
Definition: logging.h:80
PsqlScanState psql_scan_create(const PsqlScanCallbacks *callbacks)
int getopt_long(int argc, char *const argv[], const char *optstring, const struct option *longopts, int *longindex)
Definition: getopt_long.c:57
void initializeInput(int flags)
Definition: input.c:346
static bool on_error_stop_hook(const char *newval)
Definition: startup.c:884
const char * prompt3
Definition: settings.h:149
char * pstrdup(const char *in)
Definition: mcxt.c:1299
void pg_logging_init(const char *argv0)
Definition: logging.c:81
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
bool start_table
Definition: print.h:111
enum printFormat format
Definition: print.h:101
void PsqlVarEnumError(const char *name, const char *value, const char *suggestions)
Definition: variables.c:417
printTableOpt topt
Definition: print.h:169
#define DEFAULT_PROMPT3
Definition: settings.h:28
bool queryFoutPipe
Definition: settings.h:85
static bool echo_hook(const char *newval)
Definition: startup.c:981
#define SYSPSQLRC
Definition: startup.c:35
void pg_logging_set_pre_callback(void(*cb)(void))
Definition: logging.c:185
PSQL_COMP_CASE comp_case
Definition: settings.h:145
FILE * queryFout
Definition: settings.h:84
bool no_readline
Definition: startup.c:73
unicode_linestyle unicode_header_linestyle
Definition: print.h:127
void PQfinish(PGconn *conn)
Definition: fe-connect.c:4231
static bool quiet_hook(const char *newval)
Definition: startup.c:890
bool SetVariableBool(VariableSpace space, const char *name)
Definition: variables.c:393
#define printf(...)
Definition: port.h:222
char * simple_prompt(const char *prompt, bool echo)
Definition: sprompt.c:38
char * inputfile
Definition: settings.h:110
bool on_error_stop
Definition: settings.h:133
bool autocommit
Definition: settings.h:132
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
#define DEFAULT_PROMPT2
Definition: settings.h:27
#define fprintf
Definition: port.h:220
static void simple_action_list_append(SimpleActionList *list, enum _actions action, const char *val)
Definition: startup.c:748
static void log_locus_callback(const char **filename, uint64 *lineno)
Definition: startup.c:99
bool separator_zero
Definition: print.h:96
FILE * copyStream
Definition: settings.h:87
PSQL_ERROR_ROLLBACK on_error_rollback
Definition: settings.h:144
unicode_linestyle unicode_border_linestyle
Definition: print.h:125
static void showVersion(void)
Definition: startup.c:842
static void process_file(const char *filename, int weight)
Definition: pgbench.c:5300
FILE * cur_cmd_source
Definition: settings.h:105
PGconn * PQconnectdbParams(const char *const *keywords, const char *const *values, int expand_dbname)
Definition: fe-connect.c:657
static bool histcontrol_hook(const char *newval)
Definition: startup.c:1080
char * PQuser(const PGconn *conn)
Definition: fe-connect.c:6598
#define EXIT_BADCONN
Definition: settings.h:165
static char * bool_substitute_hook(char *newval)
Definition: startup.c:861
#define PSQLRC
Definition: startup.c:36
int main(int argc, char *argv[])
Definition: startup.c:126
VariableSpace CreateVariableSpace(void)
Definition: variables.c:51
unsigned short int border
Definition: print.h:104
static bool prompt2_hook(const char *newval)
Definition: startup.c:1108
static bool hide_tableam_hook(const char *newval)
Definition: startup.c:1189
#define required_argument
Definition: getopt_long.h:25
unsigned short int expanded
Definition: print.h:102
int optind
Definition: getopt.c:50
SimpleActionListCell * head
Definition: startup.c:62
bool cur_cmd_interactive
Definition: settings.h:107
PSQL_ECHO_HIDDEN echo_hidden
Definition: settings.h:143
SimpleActionListCell * tail
Definition: startup.c:63
void expand_tilde(char **filename)
Definition: common.c:2223
#define MAXPGPATH
unicode_linestyle unicode_column_linestyle
Definition: print.h:126
bool DeleteVariable(VariableSpace space, const char *name)
Definition: variables.c:405
static bool singleline_hook(const char *newval)
Definition: startup.c:896
int find_my_exec(const char *argv0, char *retpath)
Definition: exec.c:127
bool tuples_only
Definition: print.h:110
char * c
static char * echo_substitute_hook(char *newval)
Definition: startup.c:973
const PsqlScanCallbacks psqlscan_callbacks
Definition: mainloop.c:20
char * port
Definition: startup.c:70
#define DEFAULT_RECORD_SEP
Definition: settings.h:16
int fetch_count
Definition: settings.h:139
#define EXIT_USER
Definition: settings.h:167
static bool autocommit_hook(const char *newval)
Definition: startup.c:878
char * pg_strdup(const char *in)
Definition: fe_memutils.c:85
static char * password
Definition: streamutil.c:53
bool do_pset(const char *param, const char *value, printQueryOpt *popt, bool quiet)
Definition: command.c:4151
static char * comp_keyword_case_substitute_hook(char *newval)
Definition: startup.c:1043
static bool fetch_count_hook(const char *newval)
Definition: startup.c:916
void pg_logging_set_locus_callback(void(*cb)(const char **filename, uint64 *lineno))
Definition: logging.c:191
char * tableAttr
Definition: print.h:121
static bool singlestep_hook(const char *newval)
Definition: startup.c:902
static bool show_context_hook(const char *newval)
Definition: startup.c:1161
_actions
Definition: startup.c:46
bool singleline
Definition: settings.h:135
char * dbname
Definition: startup.c:68
struct SimpleActionListCell * next
Definition: startup.c:55
char * logfilename
Definition: startup.c:72
char csvFieldSep[2]
Definition: print.h:118
static bool on_error_rollback_hook(const char *newval)
Definition: startup.c:1022
static char * show_context_substitute_hook(char *newval)
Definition: startup.c:1153
static bool histsize_hook(const char *newval)
Definition: startup.c:940
int PQenv2encoding(void)
Definition: fe-misc.c:1221
#define CppAsString2(x)
Definition: c.h:289
#define no_argument
Definition: getopt_long.h:24
char my_exec_path[MAXPGPATH]
Definition: globals.c:75
#define PG_TEXTDOMAIN(domain)
Definition: c.h:1215
ConditionalStack conditional_stack_create(void)
Definition: conditional.c:18
PGContextVisibility show_context
Definition: settings.h:151
void helpVariables(unsigned short int pager)
Definition: help.c:340
static void process_psqlrc_file(char *filename)
Definition: startup.c:811
#define DEFAULT_CSV_FIELD_SEP
Definition: settings.h:14
bool setQFout(const char *fname)
Definition: common.c:85
PsqlSettings pset
Definition: startup.c:32
void psql_scan_destroy(PsqlScanState state)
PGresult * last_error_result
Definition: settings.h:89
FILE * logfile
Definition: settings.h:116
PGContextVisibility PQsetErrorContextVisibility(PGconn *conn, PGContextVisibility show_context)
Definition: fe-connect.c:6883
static char * histsize_substitute_hook(char *newval)
Definition: startup.c:932
unsigned short int pager
Definition: print.h:106
void get_etc_path(const char *my_exec_path, char *ret_path)
Definition: path.c:713
static struct @143 value
void SetVariableHooks(VariableSpace space, const char *name, VariableSubstituteHook shook, VariableAssignHook ahook)
Definition: variables.c:315
PGVerbosity verbosity
Definition: settings.h:150
struct SimpleActionList SimpleActionList
void PQclear(PGresult *res)
Definition: fe-exec.c:694
bool stop_table
Definition: print.h:112
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:170
bool standard_strings(void)
Definition: common.c:2182
#define free(a)
Definition: header.h:65
struct separator fieldSep
Definition: print.h:116
void NoticeProcessor(void *arg, const char *message)
Definition: common.c:220
struct SimpleActionListCell SimpleActionListCell
int pager_min_lines
Definition: print.h:108
#define SIGNAL_ARGS
Definition: c.h:1333
bool default_footer
Definition: print.h:113
#define Assert(condition)
Definition: c.h:804
bool SetVariable(VariableSpace space, const char *name, const char *value)
Definition: variables.c:211
#define PARAMS_ARRAY_SIZE
const char * progname
Definition: settings.h:109
int MainLoop(FILE *source)
Definition: mainloop.c:33
printQueryOpt popt
Definition: settings.h:91
bool single_txn
Definition: startup.c:75
static bool comp_keyword_case_hook(const char *newval)
Definition: startup.c:1051
void pg_logging_config(int new_flags)
Definition: logging.c:155
enum trivalue getPassword
Definition: settings.h:104
const char * prompt2
Definition: settings.h:148
#define SIGALRM
Definition: win32_port.h:165
void setDecimalLocale(void)
Definition: print.c:3512
#define newval
static char * histcontrol_substitute_hook(char *newval)
Definition: startup.c:1072
#define optional_argument
Definition: getopt_long.h:26
PGconn * dead_conn
Definition: settings.h:125
static bool ignoreeof_hook(const char *newval)
Definition: startup.c:967
bool no_psqlrc
Definition: startup.c:74
const char * prompt1
Definition: settings.h:147
void pg_free(void *ptr)
Definition: fe_memutils.c:105
#define DEFAULT_PROMPT1
Definition: settings.h:26
bool list_dbs
Definition: startup.c:76
static char * ignoreeof_substitute_hook(char *newval)
Definition: startup.c:946
void conditional_stack_destroy(ConditionalStack cstack)
Definition: conditional.c:30
static bool prompt1_hook(const char *newval)
Definition: startup.c:1101
bool ParseVariableBool(const char *value, const char *name, bool *result)
Definition: variables.c:107
static Datum values[MAXATTR]
Definition: bootstrap.c:156
static char * filename
Definition: pg_dumpall.c:92
int PQconnectionNeedsPassword(const PGconn *conn)
Definition: fe-connect.c:6795
#define PG_LOG_FLAG_TERSE
Definition: logging.h:64
void set_pglocale_pgservice(const char *argv0, const char *app)
Definition: exec.c:433
char * host
Definition: startup.c:69
void psql_scan_set_passthrough(PsqlScanState state, void *passthrough)
void psql_setup_cancel_handler(void)
Definition: common.c:266
uint64 lineno
Definition: settings.h:111
char * optarg
Definition: getopt.c:52
static bool histfile_hook(const char *newval)
Definition: startup.c:922
static bool hide_compression_hook(const char *newval)
Definition: startup.c:1182
void refresh_utf8format(const printTableOpt *opt)
Definition: print.c:3562
#define EXIT_FAILURE
Definition: settings.h:162
void psql_scan_setup(PsqlScanState state, const char *line, int line_len, int encoding, bool std_strings)
static void usage(const char *progname)
Definition: vacuumlo.c:417
char * separator
Definition: print.h:95
bool hide_tableam
Definition: settings.h:138
bool SendQuery(const char *query)
Definition: common.c:1193
void connection_warnings(bool in_startup)
Definition: command.c:3538
static bool verbosity_hook(const char *newval)
Definition: startup.c:1130
static char * fetch_count_substitute_hook(char *newval)
Definition: startup.c:908
static bool prompt3_hook(const char *newval)
Definition: startup.c:1115
struct separator recordSep
Definition: print.h:117
#define pg_log_warning(...)
Definition: pgfnames.c:24
backslashResult HandleSlashCmds(PsqlScanState scan_state, ConditionalStack cstack, PQExpBuffer query_buf, PQExpBuffer previous_buf)
Definition: command.c:211
int encoding
Definition: settings.h:83
static bool echo_hidden_hook(const char *newval)
Definition: startup.c:1001
ConnStatusType PQstatus(const PGconn *conn)
Definition: fe-connect.c:6691
static bool success
Definition: initdb.c:165
#define DEFAULT_FIELD_SEP
Definition: settings.h:15
#define snprintf
Definition: port.h:216
PGVerbosity PQsetErrorVerbosity(PGconn *conn, PGVerbosity verbosity)
Definition: fe-connect.c:6871
#define _(x)
Definition: elog.c:89
void slashUsage(unsigned short int pager)
Definition: help.c:157
bool listAllDbs(const char *pattern, bool verbose)
Definition: describe.c:1026
bool get_home_path(char *ret_path)
Definition: path.c:807
HistControl histcontrol
Definition: settings.h:146
PGresult * PSQLexec(const char *query)
Definition: common.c:540
VariableSpace vars
Definition: settings.h:118
bool hide_compression
Definition: settings.h:137
#define pg_log_fatal(...)
Definition: logging.h:76