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 */
33 PsqlSettings pset;
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 */
47 enum _actions
48 {
49 ACT_SINGLE_QUERY,
50 ACT_SINGLE_SLASH,
51 ACT_FILE
52 };
53
54 typedef struct SimpleActionListCell
55 {
56 struct SimpleActionListCell *next;
57 enum _actions action;
58 char *val;
59 } SimpleActionListCell;
60
61 typedef struct SimpleActionList
62 {
63 SimpleActionListCell *head;
64 SimpleActionListCell *tail;
65 } SimpleActionList;
66
67 struct adhoc_opts
68 {
69 char *dbname;
70 char *host;
71 char *port;
72 char *username;
73 char *logfilename;
74 bool no_readline;
75 bool no_psqlrc;
76 bool single_txn;
77 bool list_dbs;
78 SimpleActionList actions;
79 };
80
81 static void parse_psql_options(int argc, char *argv[],
82 struct adhoc_opts *options);
83 static void simple_action_list_append(SimpleActionList *list,
84 enum _actions action, const char *val);
SQLSetConfigMode(UWORD wConfigMode)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;
129 setDecimalLocale();
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
147 pset.popt.topt.unicode_border_linestyle = UNICODE_LINESTYLE_SINGLE;
148 pset.popt.topt.unicode_column_linestyle = UNICODE_LINESTYLE_SINGLE;
149 pset.popt.topt.unicode_header_linestyle = UNICODE_LINESTYLE_SINGLE;
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
160 EstablishVariableSpace();
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 &&
195 !pset.popt.topt.fieldSep.separator_zero)
196 {
197 pset.popt.topt.fieldSep.separator = pg_strdup(DEFAULT_FIELD_SEP);
198 pset.popt.topt.fieldSep.separator_zero = false;
199 }
200 if (!pset.popt.topt.recordSep.separator &&
201 !pset.popt.topt.recordSep.separator_zero)
202 {
203 pset.popt.topt.recordSep.separator = pg_strdup(DEFAULT_RECORD_SEP);
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 &&
249 PQconnectionNeedsPassword(pset.db) &&
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
282 setup_cancel_handler();
283
284 PQsetNoticeProcessor(pset.db, NoticeProcessor, NULL);
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)
347 ? EXIT_SUCCESS : EXIT_FAILURE;
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
368 ? EXIT_SUCCESS : EXIT_FAILURE;
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':
488 pset.popt.topt.format = PRINT_UNALIGNED;
489 break;
490 case 'b':
491 SetVariable(pset.vars, "ECHO", "errors");
492 break;
493 case 'c':
494 if (optarg[0] == '\\')
495 simple_action_list_append(&options->actions,
496 ACT_SINGLE_SLASH,
497 optarg + 1);
498 else
499 simple_action_list_append(&options->actions,
500 ACT_SINGLE_QUERY,
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':
513 simple_action_list_append(&options->actions,
514 ACT_FILE,
515 optarg);
516 break;
517 case 'F':
518 pset.popt.topt.fieldSep.separator = pg_strdup(optarg);
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':
572 pset.popt.topt.recordSep.separator = pg_strdup(optarg);
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':
585 pset.popt.topt.tableAttr = pg_strdup(optarg);
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 if (optind <= argc &&
638 strcmp(argv[optind - 1], "-?") == 0)
639 {
640 /* actual help option given */
641 usage(NOPAGER);
642 exit(EXIT_SUCCESS);
643 }
644 else
645 {
646 /* getopt error (unknown option or missing argument) */
647 goto unknown_option;
648 }
649 break;
650 case 1:
651 {
652 if (!optarg || strcmp(optarg, "options") == 0)
653 usage(NOPAGER);
654 else if (optarg && strcmp(optarg, "commands") == 0)
655 slashUsage(NOPAGER);
656 else if (optarg && strcmp(optarg, "variables") == 0)
657 helpVariables(NOPAGER);
658 else
659 goto unknown_option;
660
661 exit(EXIT_SUCCESS);
662 }
663 break;
664 default:
665 unknown_option:
666 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
667 pset.progname);
668 exit(EXIT_FAILURE);
669 break;
670 }
671 }
672
673 /*
674 * if we still have arguments, use it as the database name and username
675 */
676 while (argc - optind >= 1)
677 {
678 if (!options->dbname)
679 options->dbname = argv[optind];
680 else if (!options->username)
681 options->username = argv[optind];
682 else if (!pset.quiet)
683 fprintf(stderr, _("%s: warning: extra command-line argument \"%s\" ignored\n"),
684 pset.progname, argv[optind]);
685
686 optind++;
687 }
688 }
689
690
691 /*
692 * Append a new item to the end of the SimpleActionList.
693 * Note that "val" is copied if it's not NULL.
694 */
695 static void
696 simple_action_list_append(SimpleActionList *list,
697 enum _actions action, const char *val)
698 {
699 SimpleActionListCell *cell;
700
701 cell = (SimpleActionListCell *) pg_malloc(sizeof(SimpleActionListCell));
702
703 cell->next = NULL;
704 cell->action = action;
705 if (val)
706 cell->val = pg_strdup(val);
707 else
708 cell->val = NULL;
709
710 if (list->tail)
711 list->tail->next = cell;
712 else
713 list->head = cell;
714 list->tail = cell;
715 }
716
717
718 /*
719 * Load .psqlrc file, if found.
720 */
721 static void
722 process_psqlrc(char *argv0)
723 {
724 char home[MAXPGPATH];
725 char rc_file[MAXPGPATH];
726 char my_exec_path[MAXPGPATH];
727 char etc_path[MAXPGPATH];
728 char *envrc = getenv("PSQLRC");
729
730 if (find_my_exec(argv0, my_exec_path) < 0)
731 {
732 fprintf(stderr, _("%s: could not find own program executable\n"), argv0);
733 exit(EXIT_FAILURE);
734 }
735
736 get_etc_path(my_exec_path, etc_path);
737
738 snprintf(rc_file, MAXPGPATH, "%s/%s", etc_path, SYSPSQLRC);
739 process_psqlrc_file(rc_file);
740
741 if (envrc != NULL && strlen(envrc) > 0)
742 {
743 /* might need to free() this */
744 char *envrc_alloc = pstrdup(envrc);
745
746 expand_tilde(&envrc_alloc);
747 process_psqlrc_file(envrc_alloc);
748 }
749 else if (get_home_path(home))
750 {
751 snprintf(rc_file, MAXPGPATH, "%s/%s", home, PSQLRC);
752 process_psqlrc_file(rc_file);
753 }
754 }
755
756
757
758 static void
759 process_psqlrc_file(char *filename)
760 {
761 char *psqlrc_minor,
762 *psqlrc_major;
763
764 #if defined(WIN32) && (!defined(__MINGW32__))
765 #define R_OK 4
766 #endif
767
768 psqlrc_minor = psprintf("%s-%s", filename, PG_VERSION);
769 psqlrc_major = psprintf("%s-%s", filename, PG_MAJORVERSION);
770
771 /* check for minor version first, then major, then no version */
772 if (access(psqlrc_minor, R_OK) == 0)
773 (void) process_file(psqlrc_minor, false);
774 else if (access(psqlrc_major, R_OK) == 0)
775 (void) process_file(psqlrc_major, false);
776 else if (access(filename, R_OK) == 0)
777 (void) process_file(filename, false);
778
779 free(psqlrc_minor);
780 free(psqlrc_major);
781 }
782
783
784
785 /* showVersion
786 *
787 * This output format is intended to match GNU standards.
788 */
789 static void
790 showVersion(void)
791 {
792 puts("psql (PostgreSQL) " PG_VERSION);
793 }
794
795
796
797 /*
798 * Substitute hooks and assign hooks for psql variables.
799 *
800 * This isn't an amazingly good place for them, but neither is anywhere else.
801 *
802 * By policy, every special variable that controls any psql behavior should
803 * have one or both hooks, even if they're just no-ops. This ensures that
804 * the variable will remain present in variables.c's list even when unset,
805 * which ensures that it's known to tab completion.
806 */
807
808 static char *
809 bool_substitute_hook(char *newval)
810 {
811 if (newval == NULL)
812 {
813 /* "\unset FOO" becomes "\set FOO off" */
814 newval = pg_strdup("off");
815 }
816 else if (newval[0] == '\0')
817 {
818 /* "\set FOO" becomes "\set FOO on" */
819 pg_free(newval);
820 newval = pg_strdup("on");
821 }
822 return newval;
823 }
824
825 static bool
826 autocommit_hook(const char *newval)
827 {
828 return ParseVariableBool(newval, "AUTOCOMMIT", &pset.autocommit);
829 }
830
831 static bool
832 on_error_stop_hook(const char *newval)
833 {
834 return ParseVariableBool(newval, "ON_ERROR_STOP", &pset.on_error_stop);
835 }
836
837 static bool
838 quiet_hook(const char *newval)
839 {
840 return ParseVariableBool(newval, "QUIET", &pset.quiet);
841 }
842
843 static bool
844 singleline_hook(const char *newval)
845 {
846 return ParseVariableBool(newval, "SINGLELINE", &pset.singleline);
847 }
848
849 static bool
850 singlestep_hook(const char *newval)
851 {
852 return ParseVariableBool(newval, "SINGLESTEP", &pset.singlestep);
853 }
854
855 static char *
856 fetch_count_substitute_hook(char *newval)
857 {
858 if (newval == NULL)
859 newval = pg_strdup("0");
860 return newval;
861 }
862
863 static bool
864 fetch_count_hook(const char *newval)
865 {
866 return ParseVariableNum(newval, "FETCH_COUNT", &pset.fetch_count);
867 }
868
869 static bool
870 histfile_hook(const char *newval)
871 {
872 /*
873 * Someday we might try to validate the filename, but for now, this is
874 * just a placeholder to ensure HISTFILE is known to tab completion.
875 */
876 return true;
877 }
878
879 static char *
880 histsize_substitute_hook(char *newval)
881 {
882 if (newval == NULL)
883 newval = pg_strdup("500");
884 return newval;
885 }
886
887 static bool
888 histsize_hook(const char *newval)
889 {
890 return ParseVariableNum(newval, "HISTSIZE", &pset.histsize);
891 }
892
893 static char *
894 ignoreeof_substitute_hook(char *newval)
895 {
896 int dummy;
897
898 /*
899 * This tries to mimic the behavior of bash, to wit "If set, the value is
900 * the number of consecutive EOF characters which must be typed as the
901 * first characters on an input line before bash exits. If the variable
902 * exists but does not have a numeric value, or has no value, the default
903 * value is 10. If it does not exist, EOF signifies the end of input to
904 * the shell." Unlike bash, however, we insist on the stored value
905 * actually being a valid integer.
906 */
907 if (newval == NULL)
908 newval = pg_strdup("0");
909 else if (!ParseVariableNum(newval, NULL, &dummy))
910 newval = pg_strdup("10");
911 return newval;
912 }
913
914 static bool
915 ignoreeof_hook(const char *newval)
916 {
917 return ParseVariableNum(newval, "IGNOREEOF", &pset.ignoreeof);
918 }
919
920 static char *
921 echo_substitute_hook(char *newval)
922 {
923 if (newval == NULL)
924 newval = pg_strdup("none");
925 return newval;
926 }
927
928 static bool
929 echo_hook(const char *newval)
930 {
931 Assert(newval != NULL); /* else substitute hook messed up */
932 if (pg_strcasecmp(newval, "queries") == 0)
933 pset.echo = PSQL_ECHO_QUERIES;
934 else if (pg_strcasecmp(newval, "errors") == 0)
935 pset.echo = PSQL_ECHO_ERRORS;
936 else if (pg_strcasecmp(newval, "all") == 0)
937 pset.echo = PSQL_ECHO_ALL;
938 else if (pg_strcasecmp(newval, "none") == 0)
939 pset.echo = PSQL_ECHO_NONE;
940 else
941 {
942 PsqlVarEnumError("ECHO", newval, "none, errors, queries, all");
943 return false;
944 }
945 return true;
946 }
947
948 static bool
949 echo_hidden_hook(const char *newval)
950 {
951 Assert(newval != NULL); /* else substitute hook messed up */
952 if (pg_strcasecmp(newval, "noexec") == 0)
953 pset.echo_hidden = PSQL_ECHO_HIDDEN_NOEXEC;
954 else
955 {
956 bool on_off;
957
958 if (ParseVariableBool(newval, NULL, &on_off))
959 pset.echo_hidden = on_off ? PSQL_ECHO_HIDDEN_ON : PSQL_ECHO_HIDDEN_OFF;
960 else
961 {
962 PsqlVarEnumError("ECHO_HIDDEN", newval, "on, off, noexec");
963 return false;
964 }
965 }
966 return true;
967 }
968
969 static bool
970 on_error_rollback_hook(const char *newval)
971 {
972 Assert(newval != NULL); /* else substitute hook messed up */
973 if (pg_strcasecmp(newval, "interactive") == 0)
974 pset.on_error_rollback = PSQL_ERROR_ROLLBACK_INTERACTIVE;
975 else
976 {
977 bool on_off;
978
979 if (ParseVariableBool(newval, NULL, &on_off))
980 pset.on_error_rollback = on_off ? PSQL_ERROR_ROLLBACK_ON : PSQL_ERROR_ROLLBACK_OFF;
981 else
982 {
983 PsqlVarEnumError("ON_ERROR_ROLLBACK", newval, "on, off, interactive");
984 return false;
985 }
986 }
987 return true;
988 }
989
990 static char *
991 comp_keyword_case_substitute_hook(char *newval)
992 {
993 if (newval == NULL)
994 newval = pg_strdup("preserve-upper");
995 return newval;
996 }
997
998 static bool
999 comp_keyword_case_hook(const char *newval)
1000 {
1001 Assert(newval != NULL); /* else substitute hook messed up */
1002 if (pg_strcasecmp(newval, "preserve-upper") == 0)
1003 pset.comp_case = PSQL_COMP_CASE_PRESERVE_UPPER;
1004 else if (pg_strcasecmp(newval, "preserve-lower") == 0)
1005 pset.comp_case = PSQL_COMP_CASE_PRESERVE_LOWER;
1006 else if (pg_strcasecmp(newval, "upper") == 0)
1007 pset.comp_case = PSQL_COMP_CASE_UPPER;
1008 else if (pg_strcasecmp(newval, "lower") == 0)
1009 pset.comp_case = PSQL_COMP_CASE_LOWER;
1010 else
1011 {
1012 PsqlVarEnumError("COMP_KEYWORD_CASE", newval,
1013 "lower, upper, preserve-lower, preserve-upper");
1014 return false;
1015 }
1016 return true;
1017 }
1018
1019 static char *
1020 histcontrol_substitute_hook(char *newval)
1021 {
1022 if (newval == NULL)
1023 newval = pg_strdup("none");
1024 return newval;
1025 }
1026
1027 static bool
1028 histcontrol_hook(const char *newval)
1029 {
1030 Assert(newval != NULL); /* else substitute hook messed up */
1031 if (pg_strcasecmp(newval, "ignorespace") == 0)
1032 pset.histcontrol = hctl_ignorespace;
1033 else if (pg_strcasecmp(newval, "ignoredups") == 0)
1034 pset.histcontrol = hctl_ignoredups;
1035 else if (pg_strcasecmp(newval, "ignoreboth") == 0)
1036 pset.histcontrol = hctl_ignoreboth;
1037 else if (pg_strcasecmp(newval, "none") == 0)
1038 pset.histcontrol = hctl_none;
1039 else
1040 {
1041 PsqlVarEnumError("HISTCONTROL", newval,
1042 "none, ignorespace, ignoredups, ignoreboth");
1043 return false;
1044 }
1045 return true;
1046 }
1047
1048 static bool
1049 prompt1_hook(const char *newval)
1050 {
1051 pset.prompt1 = newval ? newval : "";
1052 return true;
1053 }
1054
1055 static bool
1056 prompt2_hook(const char *newval)
1057 {
1058 pset.prompt2 = newval ? newval : "";
1059 return true;
1060 }
1061
1062 static bool
1063 prompt3_hook(const char *newval)
1064 {
1065 pset.prompt3 = newval ? newval : "";
1066 return true;
1067 }
1068
1069 static char *
1070 verbosity_substitute_hook(char *newval)
1071 {
1072 if (newval == NULL)
1073 newval = pg_strdup("default");
1074 return newval;
1075 }
1076
1077 static bool
1078 verbosity_hook(const char *newval)
1079 {
1080 Assert(newval != NULL); /* else substitute hook messed up */
1081 if (pg_strcasecmp(newval, "default") == 0)
1082 pset.verbosity = PQERRORS_DEFAULT;
1083 else if (pg_strcasecmp(newval, "terse") == 0)
1084 pset.verbosity = PQERRORS_TERSE;
1085 else if (pg_strcasecmp(newval, "verbose") == 0)
1086 pset.verbosity = PQERRORS_VERBOSE;
1087 else
1088 {
1089 PsqlVarEnumError("VERBOSITY", newval, "default, terse, verbose");
1090 return false;
1091 }
1092
1093 if (pset.db)
1094 PQsetErrorVerbosity(pset.db, pset.verbosity);
1095 return true;
1096 }
1097
1098 static char *
1099 show_context_substitute_hook(char *newval)
1100 {
1101 if (newval == NULL)
1102 newval = pg_strdup("errors");
1103 return newval;
1104 }
1105
1106 static bool
1107 show_context_hook(const char *newval)
1108 {
1109 Assert(newval != NULL); /* else substitute hook messed up */
1110 if (pg_strcasecmp(newval, "never") == 0)
1111 pset.show_context = PQSHOW_CONTEXT_NEVER;
1112 else if (pg_strcasecmp(newval, "errors") == 0)
1113 pset.show_context = PQSHOW_CONTEXT_ERRORS;
1114 else if (pg_strcasecmp(newval, "always") == 0)
1115 pset.show_context = PQSHOW_CONTEXT_ALWAYS;
1116 else
1117 {
1118 PsqlVarEnumError("SHOW_CONTEXT", newval, "never, errors, always");
1119 return false;
1120 }
1121
1122 if (pset.db)
1123 PQsetErrorContextVisibility(pset.db, pset.show_context);
1124 return true;
1125 }
1126
1127
1128 static void
1129 EstablishVariableSpace(void)
1130 {
1131 pset.vars = CreateVariableSpace();
1132
1133 SetVariableHooks(pset.vars, "AUTOCOMMIT",
1134 bool_substitute_hook,
1135 autocommit_hook);
1136 SetVariableHooks(pset.vars, "ON_ERROR_STOP",
1137 bool_substitute_hook,
1138 on_error_stop_hook);
1139 SetVariableHooks(pset.vars, "QUIET",
1140 bool_substitute_hook,
1141 quiet_hook);
1142 SetVariableHooks(pset.vars, "SINGLELINE",
1143 bool_substitute_hook,
1144 singleline_hook);
1145 SetVariableHooks(pset.vars, "SINGLESTEP",
1146 bool_substitute_hook,
1147 singlestep_hook);
1148 SetVariableHooks(pset.vars, "FETCH_COUNT",
1149 fetch_count_substitute_hook,
1150 fetch_count_hook);
1151 SetVariableHooks(pset.vars, "HISTFILE",
1152 NULL,
1153 histfile_hook);
1154 SetVariableHooks(pset.vars, "HISTSIZE",
1155 histsize_substitute_hook,
1156 histsize_hook);
1157 SetVariableHooks(pset.vars, "IGNOREEOF",
1158 ignoreeof_substitute_hook,
1159 ignoreeof_hook);
1160 SetVariableHooks(pset.vars, "ECHO",
1161 echo_substitute_hook,
1162 echo_hook);
1163 SetVariableHooks(pset.vars, "ECHO_HIDDEN",
1164 bool_substitute_hook,
1165 echo_hidden_hook);
1166 SetVariableHooks(pset.vars, "ON_ERROR_ROLLBACK",
1167 bool_substitute_hook,
1168 on_error_rollback_hook);
1169 SetVariableHooks(pset.vars, "COMP_KEYWORD_CASE",
1170 comp_keyword_case_substitute_hook,
1171 comp_keyword_case_hook);
1172 SetVariableHooks(pset.vars, "HISTCONTROL",
1173 histcontrol_substitute_hook,
1174 histcontrol_hook);
1175 SetVariableHooks(pset.vars, "PROMPT1",
1176 NULL,
1177 prompt1_hook);
1178 SetVariableHooks(pset.vars, "PROMPT2",
1179 NULL,
1180 prompt2_hook);
1181 SetVariableHooks(pset.vars, "PROMPT3",
1182 NULL,
1183 prompt3_hook);
1184 SetVariableHooks(pset.vars, "VERBOSITY",
1185 verbosity_substitute_hook,
1186 verbosity_hook);
1187 SetVariableHooks(pset.vars, "SHOW_CONTEXT",
1188 show_context_substitute_hook,
1189 show_context_hook);
1190 }
1191