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