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