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