2 * psql - the PostgreSQL interactive terminal
4 * Copyright (c) 2000-2009, PostgreSQL Global Development Group
6 * $PostgreSQL: pgsql/src/bin/psql/command.c,v 1.203 2009/02/26 16:02:38 petere Exp $
8 #include "postgres_fe.h"
11 #ifdef __BORLANDC__ /* needed for BCC */
20 #include <sys/types.h> /* for umask() */
21 #include <sys/stat.h> /* for stat() */
22 #include <fcntl.h> /* open() flags */
23 #include <unistd.h> /* for geteuid(), getpid(), stat() */
29 #include <sys/types.h> /* for umask() */
30 #include <sys/stat.h> /* for stat() */
33 #include <openssl/ssl.h>
36 #include "portability/instr_time.h"
39 #include "pqexpbuffer.h"
40 #include "dumputils.h"
47 #include "large_obj.h"
52 #include "variables.h"
55 /* functions for use in this file */
56 static backslashResult exec_command(const char *cmd,
57 PsqlScanState scan_state,
58 PQExpBuffer query_buf);
59 static bool do_edit(const char *filename_arg, PQExpBuffer query_buf,
61 static bool do_connect(char *dbname, char *user, char *host, char *port);
62 static bool do_shell(const char *command);
63 static bool lookup_function_oid(PGconn *conn, const char *desc, Oid *foid);
64 static bool get_create_function_cmd(PGconn *conn, Oid oid, PQExpBuffer buf);
65 static void minimal_error_message(PGresult *res);
67 static void printSSLInfo(void);
70 static void checkWin32Codepage(void);
78 * Handles all the different commands that start with '\'.
79 * Ordinarily called by MainLoop().
81 * scan_state is a lexer working state that is set to continue scanning
82 * just after the '\'. The lexer is advanced past the command and all
83 * arguments on return.
85 * 'query_buf' contains the query-so-far, which may be modified by
86 * execution of the backslash command (for example, \r clears it).
87 * query_buf can be NULL if there is no query so far.
89 * Returns a status code indicating what action is desired, see command.h.
94 HandleSlashCmds(PsqlScanState scan_state,
95 PQExpBuffer query_buf)
97 backslashResult status = PSQL_CMD_SKIP_LINE;
101 psql_assert(scan_state);
103 /* Parse off the command name */
104 cmd = psql_scan_slash_command(scan_state);
106 /* And try to execute it */
107 status = exec_command(cmd, scan_state, query_buf);
109 if (status == PSQL_CMD_UNKNOWN)
111 if (pset.cur_cmd_interactive)
112 fprintf(stderr, _("Invalid command \\%s. Try \\? for help.\n"), cmd);
114 psql_error("invalid command \\%s\n", cmd);
115 status = PSQL_CMD_ERROR;
118 if (status != PSQL_CMD_ERROR)
120 /* eat any remaining arguments after a valid command */
121 /* note we suppress evaluation of backticks here */
122 while ((arg = psql_scan_slash_option(scan_state,
123 OT_VERBATIM, NULL, false)))
125 psql_error("\\%s: extra argument \"%s\" ignored\n", cmd, arg);
131 /* silently throw away rest of line after an erroneous command */
132 while ((arg = psql_scan_slash_option(scan_state,
133 OT_WHOLE_LINE, NULL, false)))
137 /* if there is a trailing \\, swallow it */
138 psql_scan_slash_command_end(scan_state);
142 /* some commands write to queryFout, so make sure output is sent */
143 fflush(pset.queryFout);
149 * Read and interpret an argument to the \connect slash command.
152 read_connect_arg(PsqlScanState scan_state)
158 * Ideally we should treat the arguments as SQL identifiers. But for
159 * backwards compatibility with 7.2 and older pg_dump files, we have to
160 * take unquoted arguments verbatim (don't downcase them). For now,
161 * double-quoted arguments may be stripped of double quotes (as if SQL
162 * identifiers). By 7.4 or so, pg_dump files can be expected to
163 * double-quote all mixed-case \connect arguments, and then we can get rid
166 result = psql_scan_slash_option(scan_state, OT_SQLIDHACK, "e, true);
174 if (*result == '\0' || strcmp(result, "-") == 0)
182 * Subroutine to actually try to execute a backslash command.
184 static backslashResult
185 exec_command(const char *cmd,
186 PsqlScanState scan_state,
187 PQExpBuffer query_buf)
189 bool success = true; /* indicate here if the command ran ok or
191 backslashResult status = PSQL_CMD_SKIP_LINE;
194 * \a -- toggle field alignment This makes little sense but we keep it
197 if (strcmp(cmd, "a") == 0)
199 if (pset.popt.topt.format != PRINT_ALIGNED)
200 success = do_pset("format", "aligned", &pset.popt, pset.quiet);
202 success = do_pset("format", "unaligned", &pset.popt, pset.quiet);
205 /* \C -- override table title (formerly change HTML caption) */
206 else if (strcmp(cmd, "C") == 0)
208 char *opt = psql_scan_slash_option(scan_state,
209 OT_NORMAL, NULL, true);
211 success = do_pset("title", opt, &pset.popt, pset.quiet);
216 * \c or \connect -- connect to database using the specified parameters.
218 * \c dbname user host port
220 * If any of these parameters are omitted or specified as '-', the current
221 * value of the parameter will be used instead. If the parameter has no
222 * current value, the default value for that parameter will be used. Some
225 * \c - - hst Connect to current database on current port of host
226 * "hst" as current user. \c - usr - prt Connect to current database on
227 * "prt" port of current host as user "usr". \c dbs Connect to
228 * "dbs" database on current port of current host as current user.
230 else if (strcmp(cmd, "c") == 0 || strcmp(cmd, "connect") == 0)
237 opt1 = read_connect_arg(scan_state);
238 opt2 = read_connect_arg(scan_state);
239 opt3 = read_connect_arg(scan_state);
240 opt4 = read_connect_arg(scan_state);
242 success = do_connect(opt1, opt2, opt3, opt4);
251 else if (strcmp(cmd, "cd") == 0)
253 char *opt = psql_scan_slash_option(scan_state,
254 OT_NORMAL, NULL, true);
264 pw = getpwuid(geteuid());
267 psql_error("could not get home directory: %s\n", strerror(errno));
274 * On Windows, 'cd' without arguments prints the current
275 * directory, so if someone wants to code this here instead...
281 if (chdir(dir) == -1)
283 psql_error("\\%s: could not change directory to \"%s\": %s\n",
284 cmd, dir, strerror(errno));
290 pset.dirname = pg_strdup(dir);
291 canonicalize_path(pset.dirname);
298 else if (pg_strcasecmp(cmd, "copy") == 0)
300 /* Default fetch-it-all-and-print mode */
304 char *opt = psql_scan_slash_option(scan_state,
305 OT_WHOLE_LINE, NULL, false);
308 INSTR_TIME_SET_CURRENT(before);
310 success = do_copy(opt);
312 if (pset.timing && success)
314 INSTR_TIME_SET_CURRENT(after);
315 INSTR_TIME_SUBTRACT(after, before);
316 printf(_("Time: %.3f ms\n"), INSTR_TIME_GET_MILLISEC(after));
323 else if (strcmp(cmd, "copyright") == 0)
327 else if (cmd[0] == 'd')
330 bool show_verbose, show_system;
332 /* We don't do SQLID reduction on the pattern yet */
333 pattern = psql_scan_slash_option(scan_state,
334 OT_NORMAL, NULL, true);
336 show_verbose = strchr(cmd, '+') ? true : false;
337 show_system = strchr(cmd, 'S') ? true : false;
345 success = describeTableDetails(pattern, show_verbose, show_system);
347 /* standard listing of interesting things */
348 success = listTables("tvs", NULL, show_verbose, show_system);
351 success = describeAggregates(pattern, show_verbose, show_system);
354 success = describeTablespaces(pattern, show_verbose);
357 success = listConversions(pattern, show_system);
360 success = listCasts(pattern);
363 success = objectDescription(pattern, show_system);
366 success = listDomains(pattern, show_system);
369 success = describeFunctions(pattern, show_verbose, show_system);
372 /* no longer distinct from \du */
373 success = describeRoles(pattern, show_verbose);
376 success = do_lo_list();
379 success = listSchemas(pattern, show_verbose);
382 success = describeOperators(pattern, show_system);
385 success = permissionsList(pattern);
388 success = describeTypes(pattern, show_verbose, show_system);
394 success = listTables(&cmd[1], pattern, show_verbose, show_system);
397 success = describeRoles(pattern, show_verbose);
399 case 'F': /* text search subsystem */
404 success = listTSConfigs(pattern, show_verbose);
407 success = listTSParsers(pattern, show_verbose);
410 success = listTSDictionaries(pattern, show_verbose);
413 success = listTSTemplates(pattern, show_verbose);
416 status = PSQL_CMD_UNKNOWN;
420 case 'e': /* SQL/MED subsystem */
424 success = listForeignServers(pattern, show_verbose);
427 success = listUserMappings(pattern, show_verbose);
430 success = listForeignDataWrappers(pattern, show_verbose);
433 status = PSQL_CMD_UNKNOWN;
438 status = PSQL_CMD_UNKNOWN;
447 * \e or \edit -- edit the current query buffer (or a file and make it the
450 else if (strcmp(cmd, "e") == 0 || strcmp(cmd, "edit") == 0)
454 psql_error("no query buffer\n");
455 status = PSQL_CMD_ERROR;
461 fname = psql_scan_slash_option(scan_state,
462 OT_NORMAL, NULL, true);
463 expand_tilde(&fname);
465 canonicalize_path(fname);
466 if (do_edit(fname, query_buf, NULL))
467 status = PSQL_CMD_NEWEDIT;
469 status = PSQL_CMD_ERROR;
475 * \ef -- edit the named function, or present a blank CREATE FUNCTION
476 * template if no argument is given
478 else if (strcmp(cmd, "ef") == 0)
482 psql_error("no query buffer\n");
483 status = PSQL_CMD_ERROR;
488 Oid foid = InvalidOid;
490 func = psql_scan_slash_option(scan_state,
491 OT_WHOLE_LINE, NULL, true);
494 /* set up an empty command to fill in */
495 printfPQExpBuffer(query_buf,
496 "CREATE FUNCTION ( )\n"
499 " -- common options: IMMUTABLE STABLE STRICT SECURITY DEFINER\n"
503 else if (!lookup_function_oid(pset.db, func, &foid))
505 /* error already reported */
506 status = PSQL_CMD_ERROR;
508 else if (!get_create_function_cmd(pset.db, foid, query_buf))
510 /* error already reported */
511 status = PSQL_CMD_ERROR;
517 if (status != PSQL_CMD_ERROR)
521 if (!do_edit(0, query_buf, &edited))
522 status = PSQL_CMD_ERROR;
524 puts(_("No changes."));
526 status = PSQL_CMD_NEWEDIT;
530 /* \echo and \qecho */
531 else if (strcmp(cmd, "echo") == 0 || strcmp(cmd, "qecho") == 0)
535 bool no_newline = false;
539 if (strcmp(cmd, "qecho") == 0)
540 fout = pset.queryFout;
544 while ((value = psql_scan_slash_option(scan_state,
545 OT_NORMAL, "ed, false)))
547 if (!quoted && strcmp(value, "-n") == 0)
563 /* \encoding -- set/show client side encoding */
564 else if (strcmp(cmd, "encoding") == 0)
566 char *encoding = psql_scan_slash_option(scan_state,
567 OT_NORMAL, NULL, false);
572 puts(pg_encoding_to_char(pset.encoding));
577 if (PQsetClientEncoding(pset.db, encoding) == -1)
578 psql_error("%s: invalid encoding name or conversion procedure not found\n", encoding);
581 /* save encoding info into psql internal data */
582 pset.encoding = PQclientEncoding(pset.db);
583 pset.popt.topt.encoding = pset.encoding;
584 SetVariable(pset.vars, "ENCODING",
585 pg_encoding_to_char(pset.encoding));
591 /* \f -- change field separator */
592 else if (strcmp(cmd, "f") == 0)
594 char *fname = psql_scan_slash_option(scan_state,
595 OT_NORMAL, NULL, false);
597 success = do_pset("fieldsep", fname, &pset.popt, pset.quiet);
601 /* \g means send query */
602 else if (strcmp(cmd, "g") == 0)
604 char *fname = psql_scan_slash_option(scan_state,
605 OT_FILEPIPE, NULL, false);
611 expand_tilde(&fname);
612 pset.gfname = pg_strdup(fname);
615 status = PSQL_CMD_SEND;
619 else if (strcmp(cmd, "h") == 0 || strcmp(cmd, "help") == 0)
621 char *opt = psql_scan_slash_option(scan_state,
622 OT_WHOLE_LINE, NULL, false);
624 helpSQL(opt, pset.popt.topt.pager);
629 else if (strcmp(cmd, "H") == 0 || strcmp(cmd, "html") == 0)
631 if (pset.popt.topt.format != PRINT_HTML)
632 success = do_pset("format", "html", &pset.popt, pset.quiet);
634 success = do_pset("format", "aligned", &pset.popt, pset.quiet);
638 /* \i is include file */
639 else if (strcmp(cmd, "i") == 0 || strcmp(cmd, "include") == 0)
641 char *fname = psql_scan_slash_option(scan_state,
642 OT_NORMAL, NULL, true);
646 psql_error("\\%s: missing required argument\n", cmd);
651 expand_tilde(&fname);
652 success = (process_file(fname, false) == EXIT_SUCCESS);
657 /* \l is list databases */
658 else if (strcmp(cmd, "l") == 0 || strcmp(cmd, "list") == 0)
659 success = listAllDbs(false);
660 else if (strcmp(cmd, "l+") == 0 || strcmp(cmd, "list+") == 0)
661 success = listAllDbs(true);
664 * large object things
666 else if (strncmp(cmd, "lo_", 3) == 0)
671 opt1 = psql_scan_slash_option(scan_state,
672 OT_NORMAL, NULL, true);
673 opt2 = psql_scan_slash_option(scan_state,
674 OT_NORMAL, NULL, true);
676 if (strcmp(cmd + 3, "export") == 0)
680 psql_error("\\%s: missing required argument\n", cmd);
686 success = do_lo_export(opt1, opt2);
690 else if (strcmp(cmd + 3, "import") == 0)
694 psql_error("\\%s: missing required argument\n", cmd);
700 success = do_lo_import(opt1, opt2);
704 else if (strcmp(cmd + 3, "list") == 0)
705 success = do_lo_list();
707 else if (strcmp(cmd + 3, "unlink") == 0)
711 psql_error("\\%s: missing required argument\n", cmd);
715 success = do_lo_unlink(opt1);
719 status = PSQL_CMD_UNKNOWN;
726 /* \o -- set query output */
727 else if (strcmp(cmd, "o") == 0 || strcmp(cmd, "out") == 0)
729 char *fname = psql_scan_slash_option(scan_state,
730 OT_FILEPIPE, NULL, true);
732 expand_tilde(&fname);
733 success = setQFout(fname);
737 /* \p prints the current query buffer */
738 else if (strcmp(cmd, "p") == 0 || strcmp(cmd, "print") == 0)
740 if (query_buf && query_buf->len > 0)
741 puts(query_buf->data);
742 else if (!pset.quiet)
743 puts(_("Query buffer is empty."));
747 /* \password -- set user password */
748 else if (strcmp(cmd, "password") == 0)
753 pw1 = simple_prompt("Enter new password: ", 100, false);
754 pw2 = simple_prompt("Enter it again: ", 100, false);
756 if (strcmp(pw1, pw2) != 0)
758 fprintf(stderr, _("Passwords didn't match.\n"));
763 char *opt0 = psql_scan_slash_option(scan_state, OT_SQLID, NULL, true);
765 char *encrypted_password;
770 user = PQuser(pset.db);
772 encrypted_password = PQencryptPassword(pw1, user);
774 if (!encrypted_password)
776 fprintf(stderr, _("Password encryption failed.\n"));
784 initPQExpBuffer(&buf);
785 printfPQExpBuffer(&buf, "ALTER USER %s PASSWORD ",
787 appendStringLiteralConn(&buf, encrypted_password, pset.db);
788 res = PSQLexec(buf.data, false);
789 termPQExpBuffer(&buf);
794 PQfreemem(encrypted_password);
802 /* \prompt -- prompt and set variable */
803 else if (strcmp(cmd, "prompt") == 0)
810 arg1 = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false);
811 arg2 = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false);
815 psql_error("\\%s: missing required argument\n", cmd);
831 result = simple_prompt(prompt_text, 4096, true);
836 fputs(prompt_text, stdout);
839 result = gets_fromFile(stdin);
842 if (!SetVariable(pset.vars, opt, result))
844 psql_error("\\%s: error\n", cmd);
855 /* \pset -- set printing parameters */
856 else if (strcmp(cmd, "pset") == 0)
858 char *opt0 = psql_scan_slash_option(scan_state,
859 OT_NORMAL, NULL, false);
860 char *opt1 = psql_scan_slash_option(scan_state,
861 OT_NORMAL, NULL, false);
865 psql_error("\\%s: missing required argument\n", cmd);
869 success = do_pset(opt0, opt1, &pset.popt, pset.quiet);
876 else if (strcmp(cmd, "q") == 0 || strcmp(cmd, "quit") == 0)
877 status = PSQL_CMD_TERMINATE;
879 /* reset(clear) the buffer */
880 else if (strcmp(cmd, "r") == 0 || strcmp(cmd, "reset") == 0)
882 resetPQExpBuffer(query_buf);
883 psql_scan_reset(scan_state);
885 puts(_("Query buffer reset (cleared)."));
888 /* \s save history in a file or show it on the screen */
889 else if (strcmp(cmd, "s") == 0)
891 char *fname = psql_scan_slash_option(scan_state,
892 OT_NORMAL, NULL, true);
894 expand_tilde(&fname);
895 /* This scrolls off the screen when using /dev/tty */
896 success = saveHistory(fname ? fname : DEVTTY, false);
897 if (success && !pset.quiet && fname)
898 printf(gettext("Wrote history to file \"%s/%s\".\n"),
899 pset.dirname ? pset.dirname : ".", fname);
905 /* \set -- generalized set variable/option command */
906 else if (strcmp(cmd, "set") == 0)
908 char *opt0 = psql_scan_slash_option(scan_state,
909 OT_NORMAL, NULL, false);
913 /* list all variables */
914 PrintVariables(pset.vars);
920 * Set variable to the concatenation of the arguments.
925 opt = psql_scan_slash_option(scan_state,
926 OT_NORMAL, NULL, false);
927 newval = pg_strdup(opt ? opt : "");
930 while ((opt = psql_scan_slash_option(scan_state,
931 OT_NORMAL, NULL, false)))
933 newval = realloc(newval, strlen(newval) + strlen(opt) + 1);
936 psql_error("out of memory\n");
943 if (!SetVariable(pset.vars, opt0, newval))
945 psql_error("\\%s: error\n", cmd);
953 /* \t -- turn off headers and row count */
954 else if (strcmp(cmd, "t") == 0)
956 char *opt = psql_scan_slash_option(scan_state,
957 OT_NORMAL, NULL, true);
959 success = do_pset("tuples_only", opt, &pset.popt, pset.quiet);
964 /* \T -- define html <table ...> attributes */
965 else if (strcmp(cmd, "T") == 0)
967 char *value = psql_scan_slash_option(scan_state,
968 OT_NORMAL, NULL, false);
970 success = do_pset("tableattr", value, &pset.popt, pset.quiet);
974 /* \timing -- toggle timing of queries */
975 else if (strcmp(cmd, "timing") == 0)
977 char *opt = psql_scan_slash_option(scan_state,
978 OT_NORMAL, NULL, false);
980 pset.timing = ParseVariableBool(opt);
982 pset.timing = !pset.timing;
986 puts(_("Timing is on."));
988 puts(_("Timing is off."));
994 else if (strcmp(cmd, "unset") == 0)
996 char *opt = psql_scan_slash_option(scan_state,
997 OT_NORMAL, NULL, false);
1001 psql_error("\\%s: missing required argument\n", cmd);
1004 else if (!SetVariable(pset.vars, opt, NULL))
1006 psql_error("\\%s: error\n", cmd);
1012 /* \w -- write query buffer to file */
1013 else if (strcmp(cmd, "w") == 0 || strcmp(cmd, "write") == 0)
1016 bool is_pipe = false;
1021 psql_error("no query buffer\n");
1022 status = PSQL_CMD_ERROR;
1026 fname = psql_scan_slash_option(scan_state,
1027 OT_FILEPIPE, NULL, true);
1028 expand_tilde(&fname);
1032 psql_error("\\%s: missing required argument\n", cmd);
1037 if (fname[0] == '|')
1040 fd = popen(&fname[1], "w");
1044 canonicalize_path(fname);
1045 fd = fopen(fname, "w");
1049 psql_error("%s: %s\n", fname, strerror(errno));
1059 if (query_buf && query_buf->len > 0)
1060 fprintf(fd, "%s\n", query_buf->data);
1063 result = pclose(fd);
1065 result = fclose(fd);
1069 psql_error("%s: %s\n", fname, strerror(errno));
1077 /* \x -- toggle expanded table representation */
1078 else if (strcmp(cmd, "x") == 0)
1080 char *opt = psql_scan_slash_option(scan_state,
1081 OT_NORMAL, NULL, true);
1083 success = do_pset("expanded", opt, &pset.popt, pset.quiet);
1087 /* \z -- list table rights (equivalent to \dp) */
1088 else if (strcmp(cmd, "z") == 0)
1090 char *pattern = psql_scan_slash_option(scan_state,
1091 OT_NORMAL, NULL, true);
1093 success = permissionsList(pattern);
1098 /* \! -- shell escape */
1099 else if (strcmp(cmd, "!") == 0)
1101 char *opt = psql_scan_slash_option(scan_state,
1102 OT_WHOLE_LINE, NULL, false);
1104 success = do_shell(opt);
1108 /* \? -- slash command help */
1109 else if (strcmp(cmd, "?") == 0)
1110 slashUsage(pset.popt.topt.pager);
1115 * These commands don't do anything. I just use them to test the parser.
1117 else if (strcmp(cmd, "void") == 0 || strcmp(cmd, "#") == 0)
1122 while ((value = psql_scan_slash_option(scan_state,
1123 OT_NORMAL, NULL, true)))
1125 fprintf(stderr, "+ opt(%d) = |%s|\n", i++, value);
1132 status = PSQL_CMD_UNKNOWN;
1135 status = PSQL_CMD_ERROR;
1141 * Ask the user for a password; 'username' is the username the
1142 * password is for, if one has been explicitly specified. Returns a
1146 prompt_for_password(const char *username)
1150 if (username == NULL)
1151 result = simple_prompt("Password: ", 100, false);
1156 prompt_text = malloc(strlen(username) + 100);
1157 snprintf(prompt_text, strlen(username) + 100,
1158 _("Password for user %s: "), username);
1159 result = simple_prompt(prompt_text, 100, false);
1167 param_is_newly_set(const char *old_val, const char *new_val)
1169 if (new_val == NULL)
1172 if (old_val == NULL || strcmp(old_val, new_val) != 0)
1179 * do_connect -- handler for \connect
1181 * Connects to a database with given parameters. If there exists an
1182 * established connection, NULL values will be replaced with the ones
1183 * in the current connection. Otherwise NULL will be passed for that
1184 * parameter to PQsetdbLogin(), so the libpq defaults will be used.
1186 * In interactive mode, if connection fails with the given parameters,
1187 * the old connection will be kept.
1190 do_connect(char *dbname, char *user, char *host, char *port)
1192 PGconn *o_conn = pset.db,
1194 char *password = NULL;
1197 dbname = PQdb(o_conn);
1199 user = PQuser(o_conn);
1201 host = PQhost(o_conn);
1203 port = PQport(o_conn);
1206 * If the user asked to be prompted for a password, ask for one now. If
1207 * not, use the password from the old connection, provided the username
1208 * has not changed. Otherwise, try to connect without a password first,
1209 * and then ask for a password if needed.
1211 * XXX: this behavior leads to spurious connection attempts recorded in
1212 * the postmaster's log. But libpq offers no API that would let us obtain
1213 * a password and then continue with the first connection attempt.
1215 if (pset.getPassword == TRI_YES)
1217 password = prompt_for_password(user);
1219 else if (o_conn && user && strcmp(PQuser(o_conn), user) == 0)
1221 password = strdup(PQpass(o_conn));
1226 n_conn = PQsetdbLogin(host, port, NULL, NULL,
1227 dbname, user, password);
1229 /* We can immediately discard the password -- no longer needed */
1233 if (PQstatus(n_conn) == CONNECTION_OK)
1237 * Connection attempt failed; either retry the connection attempt with
1238 * a new password, or give up.
1240 if (!password && PQconnectionNeedsPassword(n_conn) && pset.getPassword != TRI_NO)
1243 password = prompt_for_password(user);
1248 * Failed to connect to the database. In interactive mode, keep the
1249 * previous connection to the DB; in scripting mode, close our
1250 * previous connection as well.
1252 if (pset.cur_cmd_interactive)
1254 psql_error("%s", PQerrorMessage(n_conn));
1256 /* pset.db is left unmodified */
1258 fputs(_("Previous connection kept\n"), stderr);
1262 psql_error("\\connect: %s", PQerrorMessage(n_conn));
1275 * Replace the old connection with the new one, and update
1276 * connection-dependent variables.
1278 PQsetNoticeProcessor(n_conn, NoticeProcessor, NULL);
1281 connection_warnings(); /* Must be after SyncVariables */
1283 /* Tell the user about the new connection */
1286 printf(_("You are now connected to database \"%s\""), PQdb(pset.db));
1288 if (param_is_newly_set(PQhost(o_conn), PQhost(pset.db)))
1289 printf(_(" on host \"%s\""), PQhost(pset.db));
1291 if (param_is_newly_set(PQport(o_conn), PQport(pset.db)))
1292 printf(_(" at port \"%s\""), PQport(pset.db));
1294 if (param_is_newly_set(PQuser(o_conn), PQuser(pset.db)))
1295 printf(_(" as user \"%s\""), PQuser(pset.db));
1307 connection_warnings(void)
1309 if (!pset.quiet && !pset.notty)
1311 int client_ver = parse_version(PG_VERSION);
1313 if (pset.sversion != client_ver)
1315 const char *server_version;
1316 char server_ver_str[16];
1318 /* Try to get full text form, might include "devel" etc */
1319 server_version = PQparameterStatus(pset.db, "server_version");
1320 if (!server_version)
1322 snprintf(server_ver_str, sizeof(server_ver_str),
1324 pset.sversion / 10000,
1325 (pset.sversion / 100) % 100,
1326 pset.sversion % 100);
1327 server_version = server_ver_str;
1330 printf(_("%s (%s, server %s)\n"),
1331 pset.progname, PG_VERSION, server_version);
1334 printf("%s (%s)\n", pset.progname, PG_VERSION);
1336 if (pset.sversion / 100 != client_ver / 100)
1337 printf(_("WARNING: %s version %d.%d, server version %d.%d.\n"
1338 " Some psql features might not work.\n"),
1339 pset.progname, client_ver / 10000, (client_ver / 100) % 100,
1340 pset.sversion / 10000, (pset.sversion / 100) % 100);
1343 checkWin32Codepage();
1353 * Prints information about the current SSL connection, if SSL is in use
1362 ssl = PQgetssl(pset.db);
1364 return; /* no SSL */
1366 SSL_get_cipher_bits(ssl, &sslbits);
1367 printf(_("SSL connection (cipher: %s, bits: %i)\n"),
1368 SSL_get_cipher(ssl), sslbits);
1371 * If psql is compiled without SSL but is using a libpq with SSL,
1372 * we cannot figure out the specifics about the connection. But
1373 * we know it's SSL secured.
1375 if (PQgetssl(pset.db))
1376 printf(_("SSL connection (unknown cipher)\n"));
1382 * checkWin32Codepage
1384 * Prints a warning when win32 console codepage differs from Windows codepage
1388 checkWin32Codepage(void)
1394 concp = GetConsoleCP();
1397 printf(_("WARNING: Console code page (%u) differs from Windows code page (%u)\n"
1398 " 8-bit characters might not work correctly. See psql reference\n"
1399 " page \"Notes for Windows users\" for details.\n"),
1409 * Make psql's internal variables agree with connection state upon
1410 * establishing a new connection.
1415 /* get stuff from connection */
1416 pset.encoding = PQclientEncoding(pset.db);
1417 pset.popt.topt.encoding = pset.encoding;
1418 pset.sversion = PQserverVersion(pset.db);
1420 SetVariable(pset.vars, "DBNAME", PQdb(pset.db));
1421 SetVariable(pset.vars, "USER", PQuser(pset.db));
1422 SetVariable(pset.vars, "HOST", PQhost(pset.db));
1423 SetVariable(pset.vars, "PORT", PQport(pset.db));
1424 SetVariable(pset.vars, "ENCODING", pg_encoding_to_char(pset.encoding));
1426 /* send stuff to it, too */
1427 PQsetErrorVerbosity(pset.db, pset.verbosity);
1433 * Clear variables that should be not be set when there is no connection.
1436 UnsyncVariables(void)
1438 SetVariable(pset.vars, "DBNAME", NULL);
1439 SetVariable(pset.vars, "USER", NULL);
1440 SetVariable(pset.vars, "HOST", NULL);
1441 SetVariable(pset.vars, "PORT", NULL);
1442 SetVariable(pset.vars, "ENCODING", NULL);
1447 * do_edit -- handler for \e
1449 * If you do not specify a filename, the current query buffer will be copied
1450 * into a temporary one.
1454 editFile(const char *fname)
1456 const char *editorName;
1462 /* Find an editor to use */
1463 editorName = getenv("PSQL_EDITOR");
1465 editorName = getenv("EDITOR");
1467 editorName = getenv("VISUAL");
1469 editorName = DEFAULT_EDITOR;
1472 * On Unix the EDITOR value should *not* be quoted, since it might include
1473 * switches, eg, EDITOR="pico -t"; it's up to the user to put quotes in it
1474 * if necessary. But this policy is not very workable on Windows, due to
1475 * severe brain damage in their command shell plus the fact that standard
1476 * program paths include spaces.
1478 sys = pg_malloc(strlen(editorName) + strlen(fname) + 10 + 1);
1480 sprintf(sys, "exec %s '%s'", editorName, fname);
1482 sprintf(sys, SYSTEMQUOTE "\"%s\" \"%s\"" SYSTEMQUOTE, editorName, fname);
1484 result = system(sys);
1486 psql_error("could not start editor \"%s\"\n", editorName);
1487 else if (result == 127)
1488 psql_error("could not start /bin/sh\n");
1497 do_edit(const char *filename_arg, PQExpBuffer query_buf, bool *edited)
1499 char fnametmp[MAXPGPATH];
1500 FILE *stream = NULL;
1509 fname = filename_arg;
1512 /* make a temp file to edit */
1514 const char *tmpdir = getenv("TMPDIR");
1519 char tmpdir[MAXPGPATH];
1522 ret = GetTempPath(MAXPGPATH, tmpdir);
1523 if (ret == 0 || ret > MAXPGPATH)
1525 psql_error("cannot locate temporary directory: %s",
1526 !ret ? strerror(errno) : "");
1531 * No canonicalize_path() here. EDIT.EXE run from CMD.EXE prepends the
1532 * current directory to the supplied path unless we use only
1533 * backslashes, so we do that.
1537 snprintf(fnametmp, sizeof(fnametmp), "%s%spsql.edit.%d", tmpdir,
1538 "/", (int) getpid());
1540 snprintf(fnametmp, sizeof(fnametmp), "%s%spsql.edit.%d", tmpdir,
1541 "" /* trailing separator already present */ , (int) getpid());
1544 fname = (const char *) fnametmp;
1546 fd = open(fname, O_WRONLY | O_CREAT | O_EXCL, 0600);
1548 stream = fdopen(fd, "w");
1550 if (fd == -1 || !stream)
1552 psql_error("could not open temporary file \"%s\": %s\n", fname, strerror(errno));
1557 unsigned int ql = query_buf->len;
1559 if (ql == 0 || query_buf->data[ql - 1] != '\n')
1561 appendPQExpBufferChar(query_buf, '\n');
1565 if (fwrite(query_buf->data, 1, ql, stream) != ql)
1567 psql_error("%s: %s\n", fname, strerror(errno));
1572 else if (fclose(stream) != 0)
1574 psql_error("%s: %s\n", fname, strerror(errno));
1581 if (!error && stat(fname, &before) != 0)
1583 psql_error("%s: %s\n", fname, strerror(errno));
1589 error = !editFile(fname);
1591 if (!error && stat(fname, &after) != 0)
1593 psql_error("%s: %s\n", fname, strerror(errno));
1597 if (!error && before.st_mtime != after.st_mtime)
1599 stream = fopen(fname, PG_BINARY_R);
1602 psql_error("%s: %s\n", fname, strerror(errno));
1607 /* read file back into query_buf */
1610 resetPQExpBuffer(query_buf);
1611 while (fgets(line, sizeof(line), stream) != NULL)
1612 appendPQExpBufferStr(query_buf, line);
1616 psql_error("%s: %s\n", fname, strerror(errno));
1628 /* remove temp file */
1631 if (remove(fname) == -1)
1633 psql_error("%s: %s\n", fname, strerror(errno));
1646 * Read commands from filename and then them to the main processing loop
1647 * Handler for \i, but can be used for other things as well. Returns
1648 * MainLoop() error code.
1651 process_file(char *filename, bool single_txn)
1659 return EXIT_FAILURE;
1661 canonicalize_path(filename);
1662 fd = fopen(filename, PG_BINARY_R);
1666 psql_error("%s: %s\n", filename, strerror(errno));
1667 return EXIT_FAILURE;
1670 oldfilename = pset.inputfile;
1671 pset.inputfile = filename;
1674 res = PSQLexec("BEGIN", false);
1675 result = MainLoop(fd);
1677 res = PSQLexec("COMMIT", false);
1680 pset.inputfile = oldfilename;
1691 _align2string(enum printFormat in)
1698 case PRINT_UNALIGNED:
1713 case PRINT_TROFF_MS:
1722 do_pset(const char *param, const char *value, printQueryOpt *popt, bool quiet)
1729 vallen = strlen(value);
1732 if (strcmp(param, "format") == 0)
1736 else if (pg_strncasecmp("unaligned", value, vallen) == 0)
1737 popt->topt.format = PRINT_UNALIGNED;
1738 else if (pg_strncasecmp("aligned", value, vallen) == 0)
1739 popt->topt.format = PRINT_ALIGNED;
1740 else if (pg_strncasecmp("wrapped", value, vallen) == 0)
1741 popt->topt.format = PRINT_WRAPPED;
1742 else if (pg_strncasecmp("html", value, vallen) == 0)
1743 popt->topt.format = PRINT_HTML;
1744 else if (pg_strncasecmp("latex", value, vallen) == 0)
1745 popt->topt.format = PRINT_LATEX;
1746 else if (pg_strncasecmp("troff-ms", value, vallen) == 0)
1747 popt->topt.format = PRINT_TROFF_MS;
1750 psql_error("\\pset: allowed formats are unaligned, aligned, wrapped, html, latex, troff-ms\n");
1755 printf(_("Output format is %s.\n"), _align2string(popt->topt.format));
1758 /* set border style/width */
1759 else if (strcmp(param, "border") == 0)
1762 popt->topt.border = atoi(value);
1765 printf(_("Border style is %d.\n"), popt->topt.border);
1768 /* set expanded/vertical mode */
1769 else if (strcmp(param, "x") == 0 || strcmp(param, "expanded") == 0 || strcmp(param, "vertical") == 0)
1772 popt->topt.expanded = ParseVariableBool(value);
1774 popt->topt.expanded = !popt->topt.expanded;
1776 printf(popt->topt.expanded
1777 ? _("Expanded display is on.\n")
1778 : _("Expanded display is off.\n"));
1781 /* locale-aware numeric output */
1782 else if (strcmp(param, "numericlocale") == 0)
1785 popt->topt.numericLocale = ParseVariableBool(value);
1787 popt->topt.numericLocale = !popt->topt.numericLocale;
1790 if (popt->topt.numericLocale)
1791 puts(_("Showing locale-adjusted numeric output."));
1793 puts(_("Locale-adjusted numeric output is off."));
1798 else if (strcmp(param, "null") == 0)
1802 free(popt->nullPrint);
1803 popt->nullPrint = pg_strdup(value);
1806 printf(_("Null display is \"%s\".\n"), popt->nullPrint ? popt->nullPrint : "");
1809 /* field separator for unaligned text */
1810 else if (strcmp(param, "fieldsep") == 0)
1814 free(popt->topt.fieldSep);
1815 popt->topt.fieldSep = pg_strdup(value);
1818 printf(_("Field separator is \"%s\".\n"), popt->topt.fieldSep);
1821 /* record separator for unaligned text */
1822 else if (strcmp(param, "recordsep") == 0)
1826 free(popt->topt.recordSep);
1827 popt->topt.recordSep = pg_strdup(value);
1831 if (strcmp(popt->topt.recordSep, "\n") == 0)
1832 printf(_("Record separator is <newline>."));
1834 printf(_("Record separator is \"%s\".\n"), popt->topt.recordSep);
1838 /* toggle between full and tuples-only format */
1839 else if (strcmp(param, "t") == 0 || strcmp(param, "tuples_only") == 0)
1842 popt->topt.tuples_only = ParseVariableBool(value);
1844 popt->topt.tuples_only = !popt->topt.tuples_only;
1847 if (popt->topt.tuples_only)
1848 puts(_("Showing only tuples."));
1850 puts(_("Tuples only is off."));
1854 /* set title override */
1855 else if (strcmp(param, "title") == 0)
1861 popt->title = pg_strdup(value);
1866 printf(_("Title is \"%s\".\n"), popt->title);
1868 printf(_("Title is unset.\n"));
1872 /* set HTML table tag options */
1873 else if (strcmp(param, "T") == 0 || strcmp(param, "tableattr") == 0)
1875 free(popt->topt.tableAttr);
1877 popt->topt.tableAttr = NULL;
1879 popt->topt.tableAttr = pg_strdup(value);
1883 if (popt->topt.tableAttr)
1884 printf(_("Table attribute is \"%s\".\n"), popt->topt.tableAttr);
1886 printf(_("Table attributes unset.\n"));
1890 /* toggle use of pager */
1891 else if (strcmp(param, "pager") == 0)
1893 if (value && pg_strcasecmp(value, "always") == 0)
1894 popt->topt.pager = 2;
1896 if (ParseVariableBool(value))
1897 popt->topt.pager = 1;
1899 popt->topt.pager = 0;
1900 else if (popt->topt.pager == 1)
1901 popt->topt.pager = 0;
1903 popt->topt.pager = 1;
1906 if (popt->topt.pager == 1)
1907 puts(_("Pager is used for long output."));
1908 else if (popt->topt.pager == 2)
1909 puts(_("Pager is always used."));
1911 puts(_("Pager usage is off."));
1915 /* disable "(x rows)" footer */
1916 else if (strcmp(param, "footer") == 0)
1919 popt->default_footer = ParseVariableBool(value);
1921 popt->default_footer = !popt->default_footer;
1924 if (popt->default_footer)
1925 puts(_("Default footer is on."));
1927 puts(_("Default footer is off."));
1931 /* set border style/width */
1932 else if (strcmp(param, "columns") == 0)
1935 popt->topt.columns = atoi(value);
1938 printf(_("Target width for \"wrapped\" format is %d.\n"), popt->topt.columns);
1943 psql_error("\\pset: unknown option: %s\n", param);
1953 #define DEFAULT_SHELL "/bin/sh"
1956 * CMD.EXE is in different places in different Win32 releases so we
1957 * have to rely on the path to find it.
1959 #define DEFAULT_SHELL "cmd.exe"
1963 do_shell(const char *command)
1970 const char *shellName;
1972 shellName = getenv("SHELL");
1974 if (shellName == NULL)
1975 shellName = getenv("COMSPEC");
1977 if (shellName == NULL)
1978 shellName = DEFAULT_SHELL;
1980 sys = pg_malloc(strlen(shellName) + 16);
1983 /* See EDITOR handling comment for an explaination */
1984 "exec %s", shellName);
1986 /* See EDITOR handling comment for an explaination */
1987 sprintf(sys, SYSTEMQUOTE "\"%s\"" SYSTEMQUOTE, shellName);
1989 result = system(sys);
1993 result = system(command);
1995 if (result == 127 || result == -1)
1997 psql_error("\\!: failed\n");
2004 * This function takes a function description, e.g. "x" or "x(int)", and
2005 * issues a query on the given connection to retrieve the function's OID
2006 * using a cast to regproc or regprocedure (as appropriate). The result,
2007 * if there is one, is returned at *foid. Note that we'll fail if the
2008 * function doesn't exist OR if there are multiple matching candidates
2009 * OR if there's something syntactically wrong with the function description;
2010 * unfortunately it can be hard to tell the difference.
2013 lookup_function_oid(PGconn *conn, const char *desc, Oid *foid)
2019 query = createPQExpBuffer();
2020 printfPQExpBuffer(query, "SELECT ");
2021 appendStringLiteralConn(query, desc, conn);
2022 appendPQExpBuffer(query, "::pg_catalog.%s::pg_catalog.oid",
2023 strchr(desc, '(') ? "regprocedure" : "regproc");
2025 res = PQexec(conn, query->data);
2026 if (PQresultStatus(res) == PGRES_TUPLES_OK && PQntuples(res) == 1)
2027 *foid = atooid(PQgetvalue(res, 0, 0));
2030 minimal_error_message(res);
2035 destroyPQExpBuffer(query);
2041 * Fetches the "CREATE OR REPLACE FUNCTION ..." command that describes the
2042 * function with the given OID. If successful, the result is stored in buf.
2045 get_create_function_cmd(PGconn *conn, Oid oid, PQExpBuffer buf)
2051 query = createPQExpBuffer();
2052 printfPQExpBuffer(query, "SELECT pg_catalog.pg_get_functiondef(%u)", oid);
2054 res = PQexec(conn, query->data);
2055 if (PQresultStatus(res) == PGRES_TUPLES_OK && PQntuples(res) == 1)
2057 resetPQExpBuffer(buf);
2058 appendPQExpBufferStr(buf, PQgetvalue(res, 0, 0));
2062 minimal_error_message(res);
2067 destroyPQExpBuffer(query);
2073 * Report just the primary error; this is to avoid cluttering the output
2074 * with, for instance, a redisplay of the internally generated query
2077 minimal_error_message(PGresult *res)
2082 msg = createPQExpBuffer();
2084 fld = PQresultErrorField(res, PG_DIAG_SEVERITY);
2086 printfPQExpBuffer(msg, "%s: ", fld);
2088 printfPQExpBuffer(msg, "ERROR: ");
2089 fld = PQresultErrorField(res, PG_DIAG_MESSAGE_PRIMARY);
2091 appendPQExpBufferStr(msg, fld);
2093 appendPQExpBufferStr(msg, "(not available)");
2094 appendPQExpBufferStr(msg, "\n");
2096 psql_error("%s", msg->data);
2098 destroyPQExpBuffer(msg);