2 * psql - the PostgreSQL interactive terminal
4 * Copyright (c) 2000-2014, PostgreSQL Global Development Group
6 * src/bin/psql/startup.c
8 #include "postgres_fe.h"
10 #include <sys/types.h>
19 #include "getopt_long.h"
39 #define SYSPSQLRC "psqlrc"
40 #define PSQLRC ".psqlrc"
42 #define SYSPSQLRC "psqlrc"
43 #define PSQLRC "psqlrc.conf"
47 * Structures to pass information between the option parsing routine
48 * and the main function
73 static void parse_psql_options(int argc, char *argv[],
74 struct adhoc_opts * options);
75 static void process_psqlrc(char *argv0);
76 static void process_psqlrc_file(char *filename);
77 static void showVersion(void);
78 static void EstablishVariableSpace(void);
86 main(int argc, char *argv[])
88 struct adhoc_opts options;
90 char *password = NULL;
91 char *password_prompt = NULL;
94 set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("psql"));
98 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
103 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
111 setvbuf(stderr, NULL, _IONBF, 0);
114 pset.progname = get_progname(argv[0]);
118 pset.encoding = PQenv2encoding();
119 pset.queryFout = stdout;
120 pset.queryFoutPipe = false;
121 pset.cur_cmd_source = stdin;
122 pset.cur_cmd_interactive = false;
124 /* We rely on unmentioned fields of pset.popt to start out 0/false/NULL */
125 pset.popt.topt.format = PRINT_ALIGNED;
126 pset.popt.topt.border = 1;
127 pset.popt.topt.pager = 1;
128 pset.popt.topt.start_table = true;
129 pset.popt.topt.stop_table = true;
130 pset.popt.topt.default_footer = true;
131 /* We must get COLUMNS here before readline() sets it */
132 pset.popt.topt.env_columns = getenv("COLUMNS") ? atoi(getenv("COLUMNS")) : 0;
134 pset.notty = (!isatty(fileno(stdin)) || !isatty(fileno(stdout)));
136 pset.getPassword = TRI_DEFAULT;
138 EstablishVariableSpace();
140 SetVariable(pset.vars, "VERSION", PG_VERSION_STR);
142 /* Default values for variables */
143 SetVariableBool(pset.vars, "AUTOCOMMIT");
144 SetVariable(pset.vars, "VERBOSITY", "default");
145 SetVariable(pset.vars, "PROMPT1", DEFAULT_PROMPT1);
146 SetVariable(pset.vars, "PROMPT2", DEFAULT_PROMPT2);
147 SetVariable(pset.vars, "PROMPT3", DEFAULT_PROMPT3);
149 parse_psql_options(argc, argv, &options);
152 * If no action was specified and we're in non-interactive mode, treat it
153 * as if the user had specified "-f -". This lets single-transaction mode
156 if (options.action == ACT_NOTHING && pset.notty)
158 options.action = ACT_FILE;
159 options.action_string = NULL;
162 /* Bail out if -1 was specified but will be ignored. */
163 if (options.single_txn && options.action != ACT_FILE && options.action == ACT_NOTHING)
165 fprintf(stderr, _("%s: -1 can only be used in non-interactive mode\n"), pset.progname);
169 if (!pset.popt.topt.fieldSep.separator &&
170 !pset.popt.topt.fieldSep.separator_zero)
172 pset.popt.topt.fieldSep.separator = pg_strdup(DEFAULT_FIELD_SEP);
173 pset.popt.topt.fieldSep.separator_zero = false;
175 if (!pset.popt.topt.recordSep.separator &&
176 !pset.popt.topt.recordSep.separator_zero)
178 pset.popt.topt.recordSep.separator = pg_strdup(DEFAULT_RECORD_SEP);
179 pset.popt.topt.recordSep.separator_zero = false;
182 if (options.username == NULL)
183 password_prompt = pg_strdup(_("Password: "));
185 password_prompt = psprintf(_("Password for user %s: "),
188 if (pset.getPassword == TRI_YES)
189 password = simple_prompt(password_prompt, 100, false);
191 /* loop until we have a password if requested by backend */
194 #define PARAMS_ARRAY_SIZE 8
195 const char **keywords = pg_malloc(PARAMS_ARRAY_SIZE * sizeof(*keywords));
196 const char **values = pg_malloc(PARAMS_ARRAY_SIZE * sizeof(*values));
198 keywords[0] = "host";
199 values[0] = options.host;
200 keywords[1] = "port";
201 values[1] = options.port;
202 keywords[2] = "user";
203 values[2] = options.username;
204 keywords[3] = "password";
205 values[3] = password;
206 keywords[4] = "dbname";
207 values[4] = (options.action == ACT_LIST_DB &&
208 options.dbname == NULL) ?
209 "postgres" : options.dbname;
210 keywords[5] = "fallback_application_name";
211 values[5] = pset.progname;
212 keywords[6] = "client_encoding";
213 values[6] = (pset.notty || getenv("PGCLIENTENCODING")) ? NULL : "auto";
218 pset.db = PQconnectdbParams(keywords, values, true);
222 if (PQstatus(pset.db) == CONNECTION_BAD &&
223 PQconnectionNeedsPassword(pset.db) &&
225 pset.getPassword != TRI_NO)
228 password = simple_prompt(password_prompt, 100, false);
234 free(password_prompt);
236 if (PQstatus(pset.db) == CONNECTION_BAD)
238 fprintf(stderr, "%s: %s", pset.progname, PQerrorMessage(pset.db));
243 setup_cancel_handler();
245 PQsetNoticeProcessor(pset.db, NoticeProcessor, NULL);
249 if (options.action == ACT_LIST_DB)
253 if (!options.no_psqlrc)
254 process_psqlrc(argv[0]);
256 success = listAllDbs(NULL, false);
258 exit(success ? EXIT_SUCCESS : EXIT_FAILURE);
261 if (options.logfilename)
263 pset.logfile = fopen(options.logfilename, "a");
265 fprintf(stderr, _("%s: could not open log file \"%s\": %s\n"),
266 pset.progname, options.logfilename, strerror(errno));
270 * Now find something to do
274 * process file given by -f
276 if (options.action == ACT_FILE)
278 if (!options.no_psqlrc)
279 process_psqlrc(argv[0]);
281 successResult = process_file(options.action_string, options.single_txn, false);
285 * process slash command if one was given to -c
287 else if (options.action == ACT_SINGLE_SLASH)
289 PsqlScanState scan_state;
291 if (pset.echo == PSQL_ECHO_ALL)
292 puts(options.action_string);
294 scan_state = psql_scan_create();
295 psql_scan_setup(scan_state,
296 options.action_string,
297 strlen(options.action_string));
299 successResult = HandleSlashCmds(scan_state, NULL) != PSQL_CMD_ERROR
300 ? EXIT_SUCCESS : EXIT_FAILURE;
302 psql_scan_destroy(scan_state);
306 * If the query given to -c was a normal one, send it
308 else if (options.action == ACT_SINGLE_QUERY)
310 if (pset.echo == PSQL_ECHO_ALL)
311 puts(options.action_string);
313 successResult = SendQuery(options.action_string)
314 ? EXIT_SUCCESS : EXIT_FAILURE;
318 * or otherwise enter interactive main loop
322 if (!options.no_psqlrc)
323 process_psqlrc(argv[0]);
325 connection_warnings(true);
327 printf(_("Type \"help\" for help.\n\n"));
328 initializeInput(options.no_readline ? 0 : 1);
329 successResult = MainLoop(stdin);
334 fclose(pset.logfile);
338 return successResult;
343 * Parse command line options
347 parse_psql_options(int argc, char *argv[], struct adhoc_opts * options)
349 static struct option long_options[] =
351 {"echo-all", no_argument, NULL, 'a'},
352 {"no-align", no_argument, NULL, 'A'},
353 {"command", required_argument, NULL, 'c'},
354 {"dbname", required_argument, NULL, 'd'},
355 {"echo-queries", no_argument, NULL, 'e'},
356 {"echo-hidden", no_argument, NULL, 'E'},
357 {"file", required_argument, NULL, 'f'},
358 {"field-separator", required_argument, NULL, 'F'},
359 {"field-separator-zero", no_argument, NULL, 'z'},
360 {"host", required_argument, NULL, 'h'},
361 {"html", no_argument, NULL, 'H'},
362 {"list", no_argument, NULL, 'l'},
363 {"log-file", required_argument, NULL, 'L'},
364 {"no-readline", no_argument, NULL, 'n'},
365 {"single-transaction", no_argument, NULL, '1'},
366 {"output", required_argument, NULL, 'o'},
367 {"port", required_argument, NULL, 'p'},
368 {"pset", required_argument, NULL, 'P'},
369 {"quiet", no_argument, NULL, 'q'},
370 {"record-separator", required_argument, NULL, 'R'},
371 {"record-separator-zero", no_argument, NULL, '0'},
372 {"single-step", no_argument, NULL, 's'},
373 {"single-line", no_argument, NULL, 'S'},
374 {"tuples-only", no_argument, NULL, 't'},
375 {"table-attr", required_argument, NULL, 'T'},
376 {"username", required_argument, NULL, 'U'},
377 {"set", required_argument, NULL, 'v'},
378 {"variable", required_argument, NULL, 'v'},
379 {"version", no_argument, NULL, 'V'},
380 {"no-password", no_argument, NULL, 'w'},
381 {"password", no_argument, NULL, 'W'},
382 {"expanded", no_argument, NULL, 'x'},
383 {"no-psqlrc", no_argument, NULL, 'X'},
384 {"help", no_argument, NULL, '?'},
393 memset(options, 0, sizeof *options);
395 while ((c = getopt_long(argc, argv, "aAc:d:eEf:F:h:HlL:no:p:P:qR:sStT:U:v:VwWxXz?01",
396 long_options, &optindex)) != -1)
401 SetVariable(pset.vars, "ECHO", "all");
404 pset.popt.topt.format = PRINT_UNALIGNED;
407 options->action_string = pg_strdup(optarg);
408 if (optarg[0] == '\\')
410 options->action = ACT_SINGLE_SLASH;
411 options->action_string++;
414 options->action = ACT_SINGLE_QUERY;
417 options->dbname = pg_strdup(optarg);
420 SetVariable(pset.vars, "ECHO", "queries");
423 SetVariableBool(pset.vars, "ECHO_HIDDEN");
426 options->action = ACT_FILE;
427 options->action_string = pg_strdup(optarg);
430 pset.popt.topt.fieldSep.separator = pg_strdup(optarg);
431 pset.popt.topt.fieldSep.separator_zero = false;
434 options->host = pg_strdup(optarg);
437 pset.popt.topt.format = PRINT_HTML;
440 options->action = ACT_LIST_DB;
443 options->logfilename = pg_strdup(optarg);
446 options->no_readline = true;
452 options->port = pg_strdup(optarg);
460 value = pg_strdup(optarg);
461 equal_loc = strchr(value, '=');
463 result = do_pset(value, NULL, &pset.popt, true);
467 result = do_pset(value, equal_loc + 1, &pset.popt, true);
472 fprintf(stderr, _("%s: could not set printing parameter \"%s\"\n"), pset.progname, value);
480 SetVariableBool(pset.vars, "QUIET");
483 pset.popt.topt.recordSep.separator = pg_strdup(optarg);
484 pset.popt.topt.recordSep.separator_zero = false;
487 SetVariableBool(pset.vars, "SINGLESTEP");
490 SetVariableBool(pset.vars, "SINGLELINE");
493 pset.popt.topt.tuples_only = true;
496 pset.popt.topt.tableAttr = pg_strdup(optarg);
499 options->username = pg_strdup(optarg);
506 value = pg_strdup(optarg);
507 equal_loc = strchr(value, '=');
510 if (!DeleteVariable(pset.vars, value))
512 fprintf(stderr, _("%s: could not delete variable \"%s\"\n"),
513 pset.progname, value);
520 if (!SetVariable(pset.vars, value, equal_loc + 1))
522 fprintf(stderr, _("%s: could not set variable \"%s\"\n"),
523 pset.progname, value);
535 pset.getPassword = TRI_NO;
538 pset.getPassword = TRI_YES;
541 pset.popt.topt.expanded = true;
544 options->no_psqlrc = true;
547 pset.popt.topt.fieldSep.separator_zero = true;
550 pset.popt.topt.recordSep.separator_zero = true;
553 options->single_txn = true;
556 /* Actual help option given */
557 if (strcmp(argv[optind - 1], "--help") == 0 || strcmp(argv[optind - 1], "-?") == 0)
562 /* unknown option reported by getopt */
565 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
571 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
579 * if we still have arguments, use it as the database name and username
581 while (argc - optind >= 1)
583 if (!options->dbname)
584 options->dbname = argv[optind];
585 else if (!options->username)
586 options->username = argv[optind];
587 else if (!pset.quiet)
588 fprintf(stderr, _("%s: warning: extra command-line argument \"%s\" ignored\n"),
589 pset.progname, argv[optind]);
597 * Load .psqlrc file, if found.
600 process_psqlrc(char *argv0)
602 char home[MAXPGPATH];
603 char rc_file[MAXPGPATH];
604 char my_exec_path[MAXPGPATH];
605 char etc_path[MAXPGPATH];
606 char *envrc = getenv("PSQLRC");
608 find_my_exec(argv0, my_exec_path);
609 get_etc_path(my_exec_path, etc_path);
611 snprintf(rc_file, MAXPGPATH, "%s/%s", etc_path, SYSPSQLRC);
612 process_psqlrc_file(rc_file);
614 if (envrc != NULL && strlen(envrc) > 0)
616 /* might need to free() this */
617 char *envrc_alloc = pstrdup(envrc);
619 expand_tilde(&envrc_alloc);
620 process_psqlrc_file(envrc_alloc);
622 else if (get_home_path(home))
624 snprintf(rc_file, MAXPGPATH, "%s/%s", home, PSQLRC);
625 process_psqlrc_file(rc_file);
632 process_psqlrc_file(char *filename)
637 #if defined(WIN32) && (!defined(__MINGW32__))
641 psqlrc_minor = psprintf("%s-%s", filename, PG_VERSION);
642 psqlrc_major = psprintf("%s-%s", filename, PG_MAJORVERSION);
644 /* check for minor version first, then major, then no version */
645 if (access(psqlrc_minor, R_OK) == 0)
646 (void) process_file(psqlrc_minor, false, false);
647 else if (access(psqlrc_major, R_OK) == 0)
648 (void) process_file(psqlrc_major, false, false);
649 else if (access(filename, R_OK) == 0)
650 (void) process_file(filename, false, false);
660 * This output format is intended to match GNU standards.
665 puts("psql (PostgreSQL) " PG_VERSION);
671 * Assign hooks for psql variables.
673 * This isn't an amazingly good place for them, but neither is anywhere else.
677 autocommit_hook(const char *newval)
679 pset.autocommit = ParseVariableBool(newval);
683 on_error_stop_hook(const char *newval)
685 pset.on_error_stop = ParseVariableBool(newval);
689 quiet_hook(const char *newval)
691 pset.quiet = ParseVariableBool(newval);
695 singleline_hook(const char *newval)
697 pset.singleline = ParseVariableBool(newval);
701 singlestep_hook(const char *newval)
703 pset.singlestep = ParseVariableBool(newval);
707 fetch_count_hook(const char *newval)
709 pset.fetch_count = ParseVariableNum(newval, -1, -1, false);
713 echo_hook(const char *newval)
716 pset.echo = PSQL_ECHO_NONE;
717 else if (strcmp(newval, "queries") == 0)
718 pset.echo = PSQL_ECHO_QUERIES;
719 else if (strcmp(newval, "all") == 0)
720 pset.echo = PSQL_ECHO_ALL;
722 pset.echo = PSQL_ECHO_NONE;
726 echo_hidden_hook(const char *newval)
729 pset.echo_hidden = PSQL_ECHO_HIDDEN_OFF;
730 else if (strcmp(newval, "noexec") == 0)
731 pset.echo_hidden = PSQL_ECHO_HIDDEN_NOEXEC;
732 else if (pg_strcasecmp(newval, "off") == 0)
733 pset.echo_hidden = PSQL_ECHO_HIDDEN_OFF;
735 pset.echo_hidden = PSQL_ECHO_HIDDEN_ON;
739 on_error_rollback_hook(const char *newval)
742 pset.on_error_rollback = PSQL_ERROR_ROLLBACK_OFF;
743 else if (pg_strcasecmp(newval, "interactive") == 0)
744 pset.on_error_rollback = PSQL_ERROR_ROLLBACK_INTERACTIVE;
745 else if (pg_strcasecmp(newval, "off") == 0)
746 pset.on_error_rollback = PSQL_ERROR_ROLLBACK_OFF;
748 pset.on_error_rollback = PSQL_ERROR_ROLLBACK_ON;
752 histcontrol_hook(const char *newval)
755 pset.histcontrol = hctl_none;
756 else if (strcmp(newval, "ignorespace") == 0)
757 pset.histcontrol = hctl_ignorespace;
758 else if (strcmp(newval, "ignoredups") == 0)
759 pset.histcontrol = hctl_ignoredups;
760 else if (strcmp(newval, "ignoreboth") == 0)
761 pset.histcontrol = hctl_ignoreboth;
763 pset.histcontrol = hctl_none;
767 prompt1_hook(const char *newval)
769 pset.prompt1 = newval ? newval : "";
773 prompt2_hook(const char *newval)
775 pset.prompt2 = newval ? newval : "";
779 prompt3_hook(const char *newval)
781 pset.prompt3 = newval ? newval : "";
785 verbosity_hook(const char *newval)
788 pset.verbosity = PQERRORS_DEFAULT;
789 else if (strcmp(newval, "default") == 0)
790 pset.verbosity = PQERRORS_DEFAULT;
791 else if (strcmp(newval, "terse") == 0)
792 pset.verbosity = PQERRORS_TERSE;
793 else if (strcmp(newval, "verbose") == 0)
794 pset.verbosity = PQERRORS_VERBOSE;
796 pset.verbosity = PQERRORS_DEFAULT;
799 PQsetErrorVerbosity(pset.db, pset.verbosity);
804 EstablishVariableSpace(void)
806 pset.vars = CreateVariableSpace();
808 SetVariableAssignHook(pset.vars, "AUTOCOMMIT", autocommit_hook);
809 SetVariableAssignHook(pset.vars, "ON_ERROR_STOP", on_error_stop_hook);
810 SetVariableAssignHook(pset.vars, "QUIET", quiet_hook);
811 SetVariableAssignHook(pset.vars, "SINGLELINE", singleline_hook);
812 SetVariableAssignHook(pset.vars, "SINGLESTEP", singlestep_hook);
813 SetVariableAssignHook(pset.vars, "FETCH_COUNT", fetch_count_hook);
814 SetVariableAssignHook(pset.vars, "ECHO", echo_hook);
815 SetVariableAssignHook(pset.vars, "ECHO_HIDDEN", echo_hidden_hook);
816 SetVariableAssignHook(pset.vars, "ON_ERROR_ROLLBACK", on_error_rollback_hook);
817 SetVariableAssignHook(pset.vars, "HISTCONTROL", histcontrol_hook);
818 SetVariableAssignHook(pset.vars, "PROMPT1", prompt1_hook);
819 SetVariableAssignHook(pset.vars, "PROMPT2", prompt2_hook);
820 SetVariableAssignHook(pset.vars, "PROMPT3", prompt3_hook);
821 SetVariableAssignHook(pset.vars, "VERBOSITY", verbosity_hook);