2 * psql - the PostgreSQL interactive terminal
4 * Copyright (c) 2000-2010, PostgreSQL Global Development Group
6 * $PostgreSQL: pgsql/src/bin/psql/startup.c,v 1.161 2010/02/16 21:07:01 momjian Exp $
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 setup_cancel_handler();
116 pset.progname = get_progname(argv[0]);
120 pset.encoding = PQenv2encoding();
121 pset.queryFout = stdout;
122 pset.queryFoutPipe = false;
123 pset.cur_cmd_source = stdin;
124 pset.cur_cmd_interactive = false;
126 /* We rely on unmentioned fields of pset.popt to start out 0/false/NULL */
127 pset.popt.topt.format = PRINT_ALIGNED;
128 pset.popt.topt.border = 1;
129 pset.popt.topt.pager = 1;
130 pset.popt.topt.start_table = true;
131 pset.popt.topt.stop_table = true;
132 pset.popt.default_footer = true;
133 /* We must get COLUMNS here before readline() sets it */
134 pset.popt.topt.env_columns = getenv("COLUMNS") ? atoi(getenv("COLUMNS")) : 0;
136 pset.notty = (!isatty(fileno(stdin)) || !isatty(fileno(stdout)));
138 pset.getPassword = TRI_DEFAULT;
140 EstablishVariableSpace();
142 SetVariable(pset.vars, "VERSION", PG_VERSION_STR);
144 /* Default values for variables */
145 SetVariableBool(pset.vars, "AUTOCOMMIT");
146 SetVariable(pset.vars, "VERBOSITY", "default");
147 SetVariable(pset.vars, "PROMPT1", DEFAULT_PROMPT1);
148 SetVariable(pset.vars, "PROMPT2", DEFAULT_PROMPT2);
149 SetVariable(pset.vars, "PROMPT3", DEFAULT_PROMPT3);
151 parse_psql_options(argc, argv, &options);
153 if (!pset.popt.topt.fieldSep)
154 pset.popt.topt.fieldSep = pg_strdup(DEFAULT_FIELD_SEP);
155 if (!pset.popt.topt.recordSep)
156 pset.popt.topt.recordSep = pg_strdup(DEFAULT_RECORD_SEP);
158 if (options.username == NULL)
159 password_prompt = pg_strdup(_("Password: "));
162 password_prompt = malloc(strlen(_("Password for user %s: ")) - 2 +
163 strlen(options.username) + 1);
164 sprintf(password_prompt, _("Password for user %s: "),
168 if (pset.getPassword == TRI_YES)
169 password = simple_prompt(password_prompt, 100, false);
171 /* loop until we have a password if requested by backend */
174 #define PARAMS_ARRAY_SIZE 7
175 const char **keywords = pg_malloc(PARAMS_ARRAY_SIZE * sizeof(*keywords));
176 const char **values = pg_malloc(PARAMS_ARRAY_SIZE * sizeof(*values));
178 keywords[0] = "host";
179 values[0] = options.host;
180 keywords[1] = "port";
181 values[1] = options.port;
182 keywords[2] = "user";
183 values[2] = options.username;
184 keywords[3] = "password";
185 values[3] = password;
186 keywords[4] = "dbname";
187 values[4] = (options.action == ACT_LIST_DB &&
188 options.dbname == NULL) ?
189 "postgres" : options.dbname;
190 keywords[5] = "fallback_application_name";
191 values[5] = pset.progname;
196 pset.db = PQconnectdbParams(keywords, values, true);
200 if (PQstatus(pset.db) == CONNECTION_BAD &&
201 PQconnectionNeedsPassword(pset.db) &&
203 pset.getPassword != TRI_NO)
206 password = simple_prompt(password_prompt, 100, false);
212 free(password_prompt);
214 if (PQstatus(pset.db) == CONNECTION_BAD)
216 fprintf(stderr, "%s: %s", pset.progname, PQerrorMessage(pset.db));
221 PQsetNoticeProcessor(pset.db, NoticeProcessor, NULL);
225 if (options.action == ACT_LIST_DB)
227 int success = listAllDbs(false);
230 exit(success ? EXIT_SUCCESS : EXIT_FAILURE);
233 if (options.logfilename)
235 pset.logfile = fopen(options.logfilename, "a");
237 fprintf(stderr, _("%s: could not open log file \"%s\": %s\n"),
238 pset.progname, options.logfilename, strerror(errno));
242 * Now find something to do
246 * process file given by -f
248 if (options.action == ACT_FILE)
250 if (!options.no_psqlrc)
251 process_psqlrc(argv[0]);
253 successResult = process_file(options.action_string, options.single_txn);
257 * process slash command if one was given to -c
259 else if (options.action == ACT_SINGLE_SLASH)
261 PsqlScanState scan_state;
263 if (pset.echo == PSQL_ECHO_ALL)
264 puts(options.action_string);
266 scan_state = psql_scan_create();
267 psql_scan_setup(scan_state,
268 options.action_string,
269 strlen(options.action_string));
271 successResult = HandleSlashCmds(scan_state, NULL) != PSQL_CMD_ERROR
272 ? EXIT_SUCCESS : EXIT_FAILURE;
274 psql_scan_destroy(scan_state);
278 * If the query given to -c was a normal one, send it
280 else if (options.action == ACT_SINGLE_QUERY)
282 if (pset.echo == PSQL_ECHO_ALL)
283 puts(options.action_string);
285 successResult = SendQuery(options.action_string)
286 ? EXIT_SUCCESS : EXIT_FAILURE;
290 * or otherwise enter interactive main loop
294 if (!options.no_psqlrc)
295 process_psqlrc(argv[0]);
297 connection_warnings(true);
298 if (!pset.quiet && !pset.notty)
299 printf(_("Type \"help\" for help.\n\n"));
301 initializeInput(options.no_readline ? 0 : 1);
302 if (options.action_string) /* -f - was used */
303 pset.inputfile = "<stdin>";
305 successResult = MainLoop(stdin);
310 fclose(pset.logfile);
314 return successResult;
319 * Parse command line options
323 parse_psql_options(int argc, char *argv[], struct adhoc_opts * options)
325 static struct option long_options[] =
327 {"echo-all", no_argument, NULL, 'a'},
328 {"no-align", no_argument, NULL, 'A'},
329 {"command", required_argument, NULL, 'c'},
330 {"dbname", required_argument, NULL, 'd'},
331 {"echo-queries", no_argument, NULL, 'e'},
332 {"echo-hidden", no_argument, NULL, 'E'},
333 {"file", required_argument, NULL, 'f'},
334 {"field-separator", required_argument, NULL, 'F'},
335 {"host", required_argument, NULL, 'h'},
336 {"html", no_argument, NULL, 'H'},
337 {"list", no_argument, NULL, 'l'},
338 {"log-file", required_argument, NULL, 'L'},
339 {"no-readline", no_argument, NULL, 'n'},
340 {"single-transaction", no_argument, NULL, '1'},
341 {"output", required_argument, NULL, 'o'},
342 {"port", required_argument, NULL, 'p'},
343 {"pset", required_argument, NULL, 'P'},
344 {"quiet", no_argument, NULL, 'q'},
345 {"record-separator", required_argument, NULL, 'R'},
346 {"single-step", no_argument, NULL, 's'},
347 {"single-line", no_argument, NULL, 'S'},
348 {"tuples-only", no_argument, NULL, 't'},
349 {"table-attr", required_argument, NULL, 'T'},
350 {"username", required_argument, NULL, 'U'},
351 {"set", required_argument, NULL, 'v'},
352 {"variable", required_argument, NULL, 'v'},
353 {"version", no_argument, NULL, 'V'},
354 {"no-password", no_argument, NULL, 'w'},
355 {"password", no_argument, NULL, 'W'},
356 {"expanded", no_argument, NULL, 'x'},
357 {"no-psqlrc", no_argument, NULL, 'X'},
358 {"help", no_argument, NULL, '?'},
367 memset(options, 0, sizeof *options);
369 while ((c = getopt_long(argc, argv, "aAc:d:eEf:F:h:HlL:no:p:P:qR:sStT:U:v:VwWxX?1",
370 long_options, &optindex)) != -1)
375 SetVariable(pset.vars, "ECHO", "all");
378 pset.popt.topt.format = PRINT_UNALIGNED;
381 options->action_string = optarg;
382 if (optarg[0] == '\\')
384 options->action = ACT_SINGLE_SLASH;
385 options->action_string++;
388 options->action = ACT_SINGLE_QUERY;
391 options->dbname = optarg;
394 SetVariable(pset.vars, "ECHO", "queries");
397 SetVariableBool(pset.vars, "ECHO_HIDDEN");
400 options->action = ACT_FILE;
401 options->action_string = optarg;
404 pset.popt.topt.fieldSep = pg_strdup(optarg);
407 options->host = optarg;
410 pset.popt.topt.format = PRINT_HTML;
413 options->action = ACT_LIST_DB;
416 options->logfilename = optarg;
419 options->no_readline = true;
425 options->port = optarg;
433 value = pg_strdup(optarg);
434 equal_loc = strchr(value, '=');
436 result = do_pset(value, NULL, &pset.popt, true);
440 result = do_pset(value, equal_loc + 1, &pset.popt, true);
445 fprintf(stderr, _("%s: could not set printing parameter \"%s\"\n"), pset.progname, value);
453 SetVariableBool(pset.vars, "QUIET");
456 pset.popt.topt.recordSep = pg_strdup(optarg);
459 SetVariableBool(pset.vars, "SINGLESTEP");
462 SetVariableBool(pset.vars, "SINGLELINE");
465 pset.popt.topt.tuples_only = true;
468 pset.popt.topt.tableAttr = pg_strdup(optarg);
471 options->username = optarg;
478 value = pg_strdup(optarg);
479 equal_loc = strchr(value, '=');
482 if (!DeleteVariable(pset.vars, value))
484 fprintf(stderr, _("%s: could not delete variable \"%s\"\n"),
485 pset.progname, value);
492 if (!SetVariable(pset.vars, value, equal_loc + 1))
494 fprintf(stderr, _("%s: could not set variable \"%s\"\n"),
495 pset.progname, value);
507 pset.getPassword = TRI_NO;
510 pset.getPassword = TRI_YES;
513 pset.popt.topt.expanded = true;
516 options->no_psqlrc = true;
519 options->single_txn = true;
522 /* Actual help option given */
523 if (strcmp(argv[optind - 1], "-?") == 0 || strcmp(argv[optind - 1], "--help") == 0)
528 /* unknown option reported by getopt */
531 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
537 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
545 * if we still have arguments, use it as the database name and username
547 while (argc - optind >= 1)
549 if (!options->dbname)
550 options->dbname = argv[optind];
551 else if (!options->username)
552 options->username = argv[optind];
553 else if (!pset.quiet)
554 fprintf(stderr, _("%s: warning: extra command-line argument \"%s\" ignored\n"),
555 pset.progname, argv[optind]);
563 * Load .psqlrc file, if found.
566 process_psqlrc(char *argv0)
568 char home[MAXPGPATH];
569 char rc_file[MAXPGPATH];
570 char my_exec_path[MAXPGPATH];
571 char etc_path[MAXPGPATH];
573 find_my_exec(argv0, my_exec_path);
574 get_etc_path(my_exec_path, etc_path);
576 snprintf(rc_file, MAXPGPATH, "%s/%s", etc_path, SYSPSQLRC);
577 process_psqlrc_file(rc_file);
579 if (get_home_path(home))
581 snprintf(rc_file, MAXPGPATH, "%s/%s", home, PSQLRC);
582 process_psqlrc_file(rc_file);
589 process_psqlrc_file(char *filename)
593 #if defined(WIN32) && (!defined(__MINGW32__))
597 psqlrc = pg_malloc(strlen(filename) + 1 + strlen(PG_VERSION) + 1);
598 sprintf(psqlrc, "%s-%s", filename, PG_VERSION);
600 if (access(psqlrc, R_OK) == 0)
601 (void) process_file(psqlrc, false);
602 else if (access(filename, R_OK) == 0)
603 (void) process_file(filename, false);
611 * This output format is intended to match GNU standards.
616 puts("psql (PostgreSQL) " PG_VERSION);
618 #if defined(USE_READLINE)
619 puts(_("contains support for command-line editing"));
626 * Assign hooks for psql variables.
628 * This isn't an amazingly good place for them, but neither is anywhere else.
632 autocommit_hook(const char *newval)
634 pset.autocommit = ParseVariableBool(newval);
638 on_error_stop_hook(const char *newval)
640 pset.on_error_stop = ParseVariableBool(newval);
644 quiet_hook(const char *newval)
646 pset.quiet = ParseVariableBool(newval);
650 singleline_hook(const char *newval)
652 pset.singleline = ParseVariableBool(newval);
656 singlestep_hook(const char *newval)
658 pset.singlestep = ParseVariableBool(newval);
662 fetch_count_hook(const char *newval)
664 pset.fetch_count = ParseVariableNum(newval, -1, -1, false);
668 echo_hook(const char *newval)
671 pset.echo = PSQL_ECHO_NONE;
672 else if (strcmp(newval, "queries") == 0)
673 pset.echo = PSQL_ECHO_QUERIES;
674 else if (strcmp(newval, "all") == 0)
675 pset.echo = PSQL_ECHO_ALL;
677 pset.echo = PSQL_ECHO_NONE;
681 echo_hidden_hook(const char *newval)
684 pset.echo_hidden = PSQL_ECHO_HIDDEN_OFF;
685 else if (strcmp(newval, "noexec") == 0)
686 pset.echo_hidden = PSQL_ECHO_HIDDEN_NOEXEC;
687 else if (pg_strcasecmp(newval, "off") == 0)
688 pset.echo_hidden = PSQL_ECHO_HIDDEN_OFF;
690 pset.echo_hidden = PSQL_ECHO_HIDDEN_ON;
694 on_error_rollback_hook(const char *newval)
697 pset.on_error_rollback = PSQL_ERROR_ROLLBACK_OFF;
698 else if (pg_strcasecmp(newval, "interactive") == 0)
699 pset.on_error_rollback = PSQL_ERROR_ROLLBACK_INTERACTIVE;
700 else if (pg_strcasecmp(newval, "off") == 0)
701 pset.on_error_rollback = PSQL_ERROR_ROLLBACK_OFF;
703 pset.on_error_rollback = PSQL_ERROR_ROLLBACK_ON;
707 histcontrol_hook(const char *newval)
710 pset.histcontrol = hctl_none;
711 else if (strcmp(newval, "ignorespace") == 0)
712 pset.histcontrol = hctl_ignorespace;
713 else if (strcmp(newval, "ignoredups") == 0)
714 pset.histcontrol = hctl_ignoredups;
715 else if (strcmp(newval, "ignoreboth") == 0)
716 pset.histcontrol = hctl_ignoreboth;
718 pset.histcontrol = hctl_none;
722 prompt1_hook(const char *newval)
724 pset.prompt1 = newval ? newval : "";
728 prompt2_hook(const char *newval)
730 pset.prompt2 = newval ? newval : "";
734 prompt3_hook(const char *newval)
736 pset.prompt3 = newval ? newval : "";
740 verbosity_hook(const char *newval)
743 pset.verbosity = PQERRORS_DEFAULT;
744 else if (strcmp(newval, "default") == 0)
745 pset.verbosity = PQERRORS_DEFAULT;
746 else if (strcmp(newval, "terse") == 0)
747 pset.verbosity = PQERRORS_TERSE;
748 else if (strcmp(newval, "verbose") == 0)
749 pset.verbosity = PQERRORS_VERBOSE;
751 pset.verbosity = PQERRORS_DEFAULT;
754 PQsetErrorVerbosity(pset.db, pset.verbosity);
759 EstablishVariableSpace(void)
761 pset.vars = CreateVariableSpace();
763 SetVariableAssignHook(pset.vars, "AUTOCOMMIT", autocommit_hook);
764 SetVariableAssignHook(pset.vars, "ON_ERROR_STOP", on_error_stop_hook);
765 SetVariableAssignHook(pset.vars, "QUIET", quiet_hook);
766 SetVariableAssignHook(pset.vars, "SINGLELINE", singleline_hook);
767 SetVariableAssignHook(pset.vars, "SINGLESTEP", singlestep_hook);
768 SetVariableAssignHook(pset.vars, "FETCH_COUNT", fetch_count_hook);
769 SetVariableAssignHook(pset.vars, "ECHO", echo_hook);
770 SetVariableAssignHook(pset.vars, "ECHO_HIDDEN", echo_hidden_hook);
771 SetVariableAssignHook(pset.vars, "ON_ERROR_ROLLBACK", on_error_rollback_hook);
772 SetVariableAssignHook(pset.vars, "HISTCONTROL", histcontrol_hook);
773 SetVariableAssignHook(pset.vars, "PROMPT1", prompt1_hook);
774 SetVariableAssignHook(pset.vars, "PROMPT2", prompt2_hook);
775 SetVariableAssignHook(pset.vars, "PROMPT3", prompt3_hook);
776 SetVariableAssignHook(pset.vars, "VERBOSITY", verbosity_hook);