2 * psql - the PostgreSQL interactive terminal
4 * Copyright (c) 2000-2010, PostgreSQL Global Development Group
6 * $PostgreSQL: pgsql/src/bin/psql/command.c,v 1.217 2010/03/08 23:03:00 momjian 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')
333 /* We don't do SQLID reduction on the pattern yet */
334 pattern = psql_scan_slash_option(scan_state,
335 OT_NORMAL, NULL, true);
337 show_verbose = strchr(cmd, '+') ? true : false;
338 show_system = strchr(cmd, 'S') ? true : false;
346 success = describeTableDetails(pattern, show_verbose, show_system);
348 /* standard listing of interesting things */
349 success = listTables("tvs", NULL, show_verbose, show_system);
352 success = describeAggregates(pattern, show_verbose, show_system);
355 success = describeTablespaces(pattern, show_verbose);
358 success = listConversions(pattern, show_system);
361 success = listCasts(pattern);
364 if (strcmp(cmd, "ddp") == 0)
365 success = listDefaultACLs(pattern);
367 success = objectDescription(pattern, show_system);
370 success = listDomains(pattern, show_system);
372 case 'f': /* function subsystem */
382 success = describeFunctions(&cmd[2], pattern, show_verbose, show_system);
385 status = PSQL_CMD_UNKNOWN;
390 /* no longer distinct from \du */
391 success = describeRoles(pattern, show_verbose);
394 success = do_lo_list();
397 success = listSchemas(pattern, show_verbose);
400 success = describeOperators(pattern, show_system);
403 success = permissionsList(pattern);
406 success = describeTypes(pattern, show_verbose, show_system);
412 success = listTables(&cmd[1], pattern, show_verbose, show_system);
415 if (cmd[2] == 'd' && cmd[3] == 's')
417 char *pattern2 = NULL;
420 pattern2 = psql_scan_slash_option(scan_state,
421 OT_NORMAL, NULL, true);
422 success = listDbRoleSettings(pattern, pattern2);
425 success = PSQL_CMD_UNKNOWN;
428 success = describeRoles(pattern, show_verbose);
430 case 'F': /* text search subsystem */
435 success = listTSConfigs(pattern, show_verbose);
438 success = listTSParsers(pattern, show_verbose);
441 success = listTSDictionaries(pattern, show_verbose);
444 success = listTSTemplates(pattern, show_verbose);
447 status = PSQL_CMD_UNKNOWN;
451 case 'e': /* SQL/MED subsystem */
455 success = listForeignServers(pattern, show_verbose);
458 success = listUserMappings(pattern, show_verbose);
461 success = listForeignDataWrappers(pattern, show_verbose);
464 status = PSQL_CMD_UNKNOWN;
469 status = PSQL_CMD_UNKNOWN;
478 * \e or \edit -- edit the current query buffer (or a file and make it the
481 else if (strcmp(cmd, "e") == 0 || strcmp(cmd, "edit") == 0)
485 psql_error("no query buffer\n");
486 status = PSQL_CMD_ERROR;
492 fname = psql_scan_slash_option(scan_state,
493 OT_NORMAL, NULL, true);
494 expand_tilde(&fname);
496 canonicalize_path(fname);
497 if (do_edit(fname, query_buf, NULL))
498 status = PSQL_CMD_NEWEDIT;
500 status = PSQL_CMD_ERROR;
506 * \ef -- edit the named function, or present a blank CREATE FUNCTION
507 * template if no argument is given
509 else if (strcmp(cmd, "ef") == 0)
513 psql_error("no query buffer\n");
514 status = PSQL_CMD_ERROR;
519 Oid foid = InvalidOid;
521 func = psql_scan_slash_option(scan_state,
522 OT_WHOLE_LINE, NULL, true);
525 /* set up an empty command to fill in */
526 printfPQExpBuffer(query_buf,
527 "CREATE FUNCTION ( )\n"
530 " -- common options: IMMUTABLE STABLE STRICT SECURITY DEFINER\n"
534 else if (!lookup_function_oid(pset.db, func, &foid))
536 /* error already reported */
537 status = PSQL_CMD_ERROR;
539 else if (!get_create_function_cmd(pset.db, foid, query_buf))
541 /* error already reported */
542 status = PSQL_CMD_ERROR;
548 if (status != PSQL_CMD_ERROR)
552 if (!do_edit(0, query_buf, &edited))
553 status = PSQL_CMD_ERROR;
555 puts(_("No changes"));
557 status = PSQL_CMD_NEWEDIT;
561 /* \echo and \qecho */
562 else if (strcmp(cmd, "echo") == 0 || strcmp(cmd, "qecho") == 0)
566 bool no_newline = false;
570 if (strcmp(cmd, "qecho") == 0)
571 fout = pset.queryFout;
575 while ((value = psql_scan_slash_option(scan_state,
576 OT_NORMAL, "ed, false)))
578 if (!quoted && strcmp(value, "-n") == 0)
594 /* \encoding -- set/show client side encoding */
595 else if (strcmp(cmd, "encoding") == 0)
597 char *encoding = psql_scan_slash_option(scan_state,
598 OT_NORMAL, NULL, false);
603 puts(pg_encoding_to_char(pset.encoding));
608 if (PQsetClientEncoding(pset.db, encoding) == -1)
609 psql_error("%s: invalid encoding name or conversion procedure not found\n", encoding);
612 /* save encoding info into psql internal data */
613 pset.encoding = PQclientEncoding(pset.db);
614 pset.popt.topt.encoding = pset.encoding;
615 SetVariable(pset.vars, "ENCODING",
616 pg_encoding_to_char(pset.encoding));
622 /* \f -- change field separator */
623 else if (strcmp(cmd, "f") == 0)
625 char *fname = psql_scan_slash_option(scan_state,
626 OT_NORMAL, NULL, false);
628 success = do_pset("fieldsep", fname, &pset.popt, pset.quiet);
632 /* \g means send query */
633 else if (strcmp(cmd, "g") == 0)
635 char *fname = psql_scan_slash_option(scan_state,
636 OT_FILEPIPE, NULL, false);
642 expand_tilde(&fname);
643 pset.gfname = pg_strdup(fname);
646 status = PSQL_CMD_SEND;
650 else if (strcmp(cmd, "h") == 0 || strcmp(cmd, "help") == 0)
652 char *opt = psql_scan_slash_option(scan_state,
653 OT_WHOLE_LINE, NULL, false);
655 helpSQL(opt, pset.popt.topt.pager);
660 else if (strcmp(cmd, "H") == 0 || strcmp(cmd, "html") == 0)
662 if (pset.popt.topt.format != PRINT_HTML)
663 success = do_pset("format", "html", &pset.popt, pset.quiet);
665 success = do_pset("format", "aligned", &pset.popt, pset.quiet);
669 /* \i is include file */
670 else if (strcmp(cmd, "i") == 0 || strcmp(cmd, "include") == 0)
672 char *fname = psql_scan_slash_option(scan_state,
673 OT_NORMAL, NULL, true);
677 psql_error("\\%s: missing required argument\n", cmd);
682 expand_tilde(&fname);
683 success = (process_file(fname, false) == EXIT_SUCCESS);
688 /* \l is list databases */
689 else if (strcmp(cmd, "l") == 0 || strcmp(cmd, "list") == 0)
690 success = listAllDbs(false);
691 else if (strcmp(cmd, "l+") == 0 || strcmp(cmd, "list+") == 0)
692 success = listAllDbs(true);
695 * large object things
697 else if (strncmp(cmd, "lo_", 3) == 0)
702 opt1 = psql_scan_slash_option(scan_state,
703 OT_NORMAL, NULL, true);
704 opt2 = psql_scan_slash_option(scan_state,
705 OT_NORMAL, NULL, true);
707 if (strcmp(cmd + 3, "export") == 0)
711 psql_error("\\%s: missing required argument\n", cmd);
717 success = do_lo_export(opt1, opt2);
721 else if (strcmp(cmd + 3, "import") == 0)
725 psql_error("\\%s: missing required argument\n", cmd);
731 success = do_lo_import(opt1, opt2);
735 else if (strcmp(cmd + 3, "list") == 0)
736 success = do_lo_list();
738 else if (strcmp(cmd + 3, "unlink") == 0)
742 psql_error("\\%s: missing required argument\n", cmd);
746 success = do_lo_unlink(opt1);
750 status = PSQL_CMD_UNKNOWN;
757 /* \o -- set query output */
758 else if (strcmp(cmd, "o") == 0 || strcmp(cmd, "out") == 0)
760 char *fname = psql_scan_slash_option(scan_state,
761 OT_FILEPIPE, NULL, true);
763 expand_tilde(&fname);
764 success = setQFout(fname);
768 /* \p prints the current query buffer */
769 else if (strcmp(cmd, "p") == 0 || strcmp(cmd, "print") == 0)
771 if (query_buf && query_buf->len > 0)
772 puts(query_buf->data);
773 else if (!pset.quiet)
774 puts(_("Query buffer is empty."));
778 /* \password -- set user password */
779 else if (strcmp(cmd, "password") == 0)
784 pw1 = simple_prompt("Enter new password: ", 100, false);
785 pw2 = simple_prompt("Enter it again: ", 100, false);
787 if (strcmp(pw1, pw2) != 0)
789 fprintf(stderr, _("Passwords didn't match.\n"));
794 char *opt0 = psql_scan_slash_option(scan_state, OT_SQLID, NULL, true);
796 char *encrypted_password;
801 user = PQuser(pset.db);
803 encrypted_password = PQencryptPassword(pw1, user);
805 if (!encrypted_password)
807 fprintf(stderr, _("Password encryption failed.\n"));
815 initPQExpBuffer(&buf);
816 printfPQExpBuffer(&buf, "ALTER USER %s PASSWORD ",
818 appendStringLiteralConn(&buf, encrypted_password, pset.db);
819 res = PSQLexec(buf.data, false);
820 termPQExpBuffer(&buf);
825 PQfreemem(encrypted_password);
833 /* \prompt -- prompt and set variable */
834 else if (strcmp(cmd, "prompt") == 0)
841 arg1 = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false);
842 arg2 = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false);
846 psql_error("\\%s: missing required argument\n", cmd);
862 result = simple_prompt(prompt_text, 4096, true);
867 fputs(prompt_text, stdout);
870 result = gets_fromFile(stdin);
873 if (!SetVariable(pset.vars, opt, result))
875 psql_error("\\%s: error\n", cmd);
886 /* \pset -- set printing parameters */
887 else if (strcmp(cmd, "pset") == 0)
889 char *opt0 = psql_scan_slash_option(scan_state,
890 OT_NORMAL, NULL, false);
891 char *opt1 = psql_scan_slash_option(scan_state,
892 OT_NORMAL, NULL, false);
896 psql_error("\\%s: missing required argument\n", cmd);
900 success = do_pset(opt0, opt1, &pset.popt, pset.quiet);
907 else if (strcmp(cmd, "q") == 0 || strcmp(cmd, "quit") == 0)
908 status = PSQL_CMD_TERMINATE;
910 /* reset(clear) the buffer */
911 else if (strcmp(cmd, "r") == 0 || strcmp(cmd, "reset") == 0)
913 resetPQExpBuffer(query_buf);
914 psql_scan_reset(scan_state);
916 puts(_("Query buffer reset (cleared)."));
919 /* \s save history in a file or show it on the screen */
920 else if (strcmp(cmd, "s") == 0)
922 char *fname = psql_scan_slash_option(scan_state,
923 OT_NORMAL, NULL, true);
925 expand_tilde(&fname);
926 /* This scrolls off the screen when using /dev/tty */
927 success = saveHistory(fname ? fname : DEVTTY, -1, false, false);
928 if (success && !pset.quiet && fname)
929 printf(gettext("Wrote history to file \"%s/%s\".\n"),
930 pset.dirname ? pset.dirname : ".", fname);
936 /* \set -- generalized set variable/option command */
937 else if (strcmp(cmd, "set") == 0)
939 char *opt0 = psql_scan_slash_option(scan_state,
940 OT_NORMAL, NULL, false);
944 /* list all variables */
945 PrintVariables(pset.vars);
951 * Set variable to the concatenation of the arguments.
956 opt = psql_scan_slash_option(scan_state,
957 OT_NORMAL, NULL, false);
958 newval = pg_strdup(opt ? opt : "");
961 while ((opt = psql_scan_slash_option(scan_state,
962 OT_NORMAL, NULL, false)))
964 newval = realloc(newval, strlen(newval) + strlen(opt) + 1);
967 psql_error("out of memory\n");
974 if (!SetVariable(pset.vars, opt0, newval))
976 psql_error("\\%s: error\n", cmd);
984 /* \t -- turn off headers and row count */
985 else if (strcmp(cmd, "t") == 0)
987 char *opt = psql_scan_slash_option(scan_state,
988 OT_NORMAL, NULL, true);
990 success = do_pset("tuples_only", opt, &pset.popt, pset.quiet);
995 /* \T -- define html <table ...> attributes */
996 else if (strcmp(cmd, "T") == 0)
998 char *value = psql_scan_slash_option(scan_state,
999 OT_NORMAL, NULL, false);
1001 success = do_pset("tableattr", value, &pset.popt, pset.quiet);
1005 /* \timing -- toggle timing of queries */
1006 else if (strcmp(cmd, "timing") == 0)
1008 char *opt = psql_scan_slash_option(scan_state,
1009 OT_NORMAL, NULL, false);
1012 pset.timing = ParseVariableBool(opt);
1014 pset.timing = !pset.timing;
1018 puts(_("Timing is on."));
1020 puts(_("Timing is off."));
1026 else if (strcmp(cmd, "unset") == 0)
1028 char *opt = psql_scan_slash_option(scan_state,
1029 OT_NORMAL, NULL, false);
1033 psql_error("\\%s: missing required argument\n", cmd);
1036 else if (!SetVariable(pset.vars, opt, NULL))
1038 psql_error("\\%s: error\n", cmd);
1044 /* \w -- write query buffer to file */
1045 else if (strcmp(cmd, "w") == 0 || strcmp(cmd, "write") == 0)
1048 bool is_pipe = false;
1053 psql_error("no query buffer\n");
1054 status = PSQL_CMD_ERROR;
1058 fname = psql_scan_slash_option(scan_state,
1059 OT_FILEPIPE, NULL, true);
1060 expand_tilde(&fname);
1064 psql_error("\\%s: missing required argument\n", cmd);
1069 if (fname[0] == '|')
1072 fd = popen(&fname[1], "w");
1076 canonicalize_path(fname);
1077 fd = fopen(fname, "w");
1081 psql_error("%s: %s\n", fname, strerror(errno));
1091 if (query_buf && query_buf->len > 0)
1092 fprintf(fd, "%s\n", query_buf->data);
1095 result = pclose(fd);
1097 result = fclose(fd);
1101 psql_error("%s: %s\n", fname, strerror(errno));
1109 /* \x -- toggle expanded table representation */
1110 else if (strcmp(cmd, "x") == 0)
1112 char *opt = psql_scan_slash_option(scan_state,
1113 OT_NORMAL, NULL, true);
1115 success = do_pset("expanded", opt, &pset.popt, pset.quiet);
1119 /* \z -- list table rights (equivalent to \dp) */
1120 else if (strcmp(cmd, "z") == 0)
1122 char *pattern = psql_scan_slash_option(scan_state,
1123 OT_NORMAL, NULL, true);
1125 success = permissionsList(pattern);
1130 /* \! -- shell escape */
1131 else if (strcmp(cmd, "!") == 0)
1133 char *opt = psql_scan_slash_option(scan_state,
1134 OT_WHOLE_LINE, NULL, false);
1136 success = do_shell(opt);
1140 /* \? -- slash command help */
1141 else if (strcmp(cmd, "?") == 0)
1142 slashUsage(pset.popt.topt.pager);
1147 * These commands don't do anything. I just use them to test the parser.
1149 else if (strcmp(cmd, "void") == 0 || strcmp(cmd, "#") == 0)
1154 while ((value = psql_scan_slash_option(scan_state,
1155 OT_NORMAL, NULL, true)))
1157 fprintf(stderr, "+ opt(%d) = |%s|\n", i++, value);
1164 status = PSQL_CMD_UNKNOWN;
1167 status = PSQL_CMD_ERROR;
1173 * Ask the user for a password; 'username' is the username the
1174 * password is for, if one has been explicitly specified. Returns a
1178 prompt_for_password(const char *username)
1182 if (username == NULL)
1183 result = simple_prompt("Password: ", 100, false);
1188 prompt_text = malloc(strlen(username) + 100);
1189 snprintf(prompt_text, strlen(username) + 100,
1190 _("Password for user %s: "), username);
1191 result = simple_prompt(prompt_text, 100, false);
1199 param_is_newly_set(const char *old_val, const char *new_val)
1201 if (new_val == NULL)
1204 if (old_val == NULL || strcmp(old_val, new_val) != 0)
1211 * do_connect -- handler for \connect
1213 * Connects to a database with given parameters. If there exists an
1214 * established connection, NULL values will be replaced with the ones
1215 * in the current connection. Otherwise NULL will be passed for that
1216 * parameter to PQconnectdbParams(), so the libpq defaults will be used.
1218 * In interactive mode, if connection fails with the given parameters,
1219 * the old connection will be kept.
1222 do_connect(char *dbname, char *user, char *host, char *port)
1224 PGconn *o_conn = pset.db,
1226 char *password = NULL;
1229 dbname = PQdb(o_conn);
1231 user = PQuser(o_conn);
1233 host = PQhost(o_conn);
1235 port = PQport(o_conn);
1238 * If the user asked to be prompted for a password, ask for one now. If
1239 * not, use the password from the old connection, provided the username
1240 * has not changed. Otherwise, try to connect without a password first,
1241 * and then ask for a password if needed.
1243 * XXX: this behavior leads to spurious connection attempts recorded in
1244 * the postmaster's log. But libpq offers no API that would let us obtain
1245 * a password and then continue with the first connection attempt.
1247 if (pset.getPassword == TRI_YES)
1249 password = prompt_for_password(user);
1251 else if (o_conn && user && strcmp(PQuser(o_conn), user) == 0)
1253 password = strdup(PQpass(o_conn));
1258 #define PARAMS_ARRAY_SIZE 7
1259 const char **keywords = pg_malloc(PARAMS_ARRAY_SIZE * sizeof(*keywords));
1260 const char **values = pg_malloc(PARAMS_ARRAY_SIZE * sizeof(*values));
1262 keywords[0] = "host";
1264 keywords[1] = "port";
1266 keywords[2] = "user";
1268 keywords[3] = "password";
1269 values[3] = password;
1270 keywords[4] = "dbname";
1272 keywords[5] = "fallback_application_name";
1273 values[5] = pset.progname;
1277 n_conn = PQconnectdbParams(keywords, values, true);
1282 /* We can immediately discard the password -- no longer needed */
1286 if (PQstatus(n_conn) == CONNECTION_OK)
1290 * Connection attempt failed; either retry the connection attempt with
1291 * a new password, or give up.
1293 if (!password && PQconnectionNeedsPassword(n_conn) && pset.getPassword != TRI_NO)
1296 password = prompt_for_password(user);
1301 * Failed to connect to the database. In interactive mode, keep the
1302 * previous connection to the DB; in scripting mode, close our
1303 * previous connection as well.
1305 if (pset.cur_cmd_interactive)
1307 psql_error("%s", PQerrorMessage(n_conn));
1309 /* pset.db is left unmodified */
1311 fputs(_("Previous connection kept\n"), stderr);
1315 psql_error("\\connect: %s", PQerrorMessage(n_conn));
1328 * Replace the old connection with the new one, and update
1329 * connection-dependent variables.
1331 PQsetNoticeProcessor(n_conn, NoticeProcessor, NULL);
1334 connection_warnings(false); /* Must be after SyncVariables */
1336 /* Tell the user about the new connection */
1339 printf(_("You are now connected to database \"%s\""), PQdb(pset.db));
1341 if (param_is_newly_set(PQhost(o_conn), PQhost(pset.db)))
1342 printf(_(" on host \"%s\""), PQhost(pset.db));
1344 if (param_is_newly_set(PQport(o_conn), PQport(pset.db)))
1345 printf(_(" at port \"%s\""), PQport(pset.db));
1347 if (param_is_newly_set(PQuser(o_conn), PQuser(pset.db)))
1348 printf(_(" as user \"%s\""), PQuser(pset.db));
1360 connection_warnings(bool in_startup)
1362 if (!pset.quiet && !pset.notty)
1364 int client_ver = parse_version(PG_VERSION);
1366 if (pset.sversion != client_ver)
1368 const char *server_version;
1369 char server_ver_str[16];
1371 /* Try to get full text form, might include "devel" etc */
1372 server_version = PQparameterStatus(pset.db, "server_version");
1373 if (!server_version)
1375 snprintf(server_ver_str, sizeof(server_ver_str),
1377 pset.sversion / 10000,
1378 (pset.sversion / 100) % 100,
1379 pset.sversion % 100);
1380 server_version = server_ver_str;
1383 printf(_("%s (%s, server %s)\n"),
1384 pset.progname, PG_VERSION, server_version);
1386 /* For version match, only print psql banner on startup. */
1387 else if (in_startup)
1388 printf("%s (%s)\n", pset.progname, PG_VERSION);
1390 if (pset.sversion / 100 != client_ver / 100)
1391 printf(_("WARNING: %s version %d.%d, server version %d.%d.\n"
1392 " Some psql features might not work.\n"),
1393 pset.progname, client_ver / 10000, (client_ver / 100) % 100,
1394 pset.sversion / 10000, (pset.sversion / 100) % 100);
1397 checkWin32Codepage();
1407 * Prints information about the current SSL connection, if SSL is in use
1416 ssl = PQgetssl(pset.db);
1418 return; /* no SSL */
1420 SSL_get_cipher_bits(ssl, &sslbits);
1421 printf(_("SSL connection (cipher: %s, bits: %i)\n"),
1422 SSL_get_cipher(ssl), sslbits);
1426 * If psql is compiled without SSL but is using a libpq with SSL, we
1427 * cannot figure out the specifics about the connection. But we know it's
1430 if (PQgetssl(pset.db))
1431 printf(_("SSL connection (unknown cipher)\n"));
1437 * checkWin32Codepage
1439 * Prints a warning when win32 console codepage differs from Windows codepage
1443 checkWin32Codepage(void)
1449 concp = GetConsoleCP();
1452 printf(_("WARNING: Console code page (%u) differs from Windows code page (%u)\n"
1453 " 8-bit characters might not work correctly. See psql reference\n"
1454 " page \"Notes for Windows users\" for details.\n"),
1464 * Make psql's internal variables agree with connection state upon
1465 * establishing a new connection.
1470 /* get stuff from connection */
1471 pset.encoding = PQclientEncoding(pset.db);
1472 pset.popt.topt.encoding = pset.encoding;
1473 pset.sversion = PQserverVersion(pset.db);
1475 SetVariable(pset.vars, "DBNAME", PQdb(pset.db));
1476 SetVariable(pset.vars, "USER", PQuser(pset.db));
1477 SetVariable(pset.vars, "HOST", PQhost(pset.db));
1478 SetVariable(pset.vars, "PORT", PQport(pset.db));
1479 SetVariable(pset.vars, "ENCODING", pg_encoding_to_char(pset.encoding));
1481 /* send stuff to it, too */
1482 PQsetErrorVerbosity(pset.db, pset.verbosity);
1488 * Clear variables that should be not be set when there is no connection.
1491 UnsyncVariables(void)
1493 SetVariable(pset.vars, "DBNAME", NULL);
1494 SetVariable(pset.vars, "USER", NULL);
1495 SetVariable(pset.vars, "HOST", NULL);
1496 SetVariable(pset.vars, "PORT", NULL);
1497 SetVariable(pset.vars, "ENCODING", NULL);
1502 * do_edit -- handler for \e
1504 * If you do not specify a filename, the current query buffer will be copied
1505 * into a temporary one.
1509 editFile(const char *fname)
1511 const char *editorName;
1517 /* Find an editor to use */
1518 editorName = getenv("PSQL_EDITOR");
1520 editorName = getenv("EDITOR");
1522 editorName = getenv("VISUAL");
1524 editorName = DEFAULT_EDITOR;
1527 * On Unix the EDITOR value should *not* be quoted, since it might include
1528 * switches, eg, EDITOR="pico -t"; it's up to the user to put quotes in it
1529 * if necessary. But this policy is not very workable on Windows, due to
1530 * severe brain damage in their command shell plus the fact that standard
1531 * program paths include spaces.
1533 sys = pg_malloc(strlen(editorName) + strlen(fname) + 10 + 1);
1535 sprintf(sys, "exec %s '%s'", editorName, fname);
1537 sprintf(sys, SYSTEMQUOTE "\"%s\" \"%s\"" SYSTEMQUOTE, editorName, fname);
1539 result = system(sys);
1541 psql_error("could not start editor \"%s\"\n", editorName);
1542 else if (result == 127)
1543 psql_error("could not start /bin/sh\n");
1552 do_edit(const char *filename_arg, PQExpBuffer query_buf, bool *edited)
1554 char fnametmp[MAXPGPATH];
1555 FILE *stream = NULL;
1564 fname = filename_arg;
1567 /* make a temp file to edit */
1569 const char *tmpdir = getenv("TMPDIR");
1574 char tmpdir[MAXPGPATH];
1577 ret = GetTempPath(MAXPGPATH, tmpdir);
1578 if (ret == 0 || ret > MAXPGPATH)
1580 psql_error("cannot locate temporary directory: %s",
1581 !ret ? strerror(errno) : "");
1586 * No canonicalize_path() here. EDIT.EXE run from CMD.EXE prepends the
1587 * current directory to the supplied path unless we use only
1588 * backslashes, so we do that.
1592 snprintf(fnametmp, sizeof(fnametmp), "%s%spsql.edit.%d", tmpdir,
1593 "/", (int) getpid());
1595 snprintf(fnametmp, sizeof(fnametmp), "%s%spsql.edit.%d", tmpdir,
1596 "" /* trailing separator already present */ , (int) getpid());
1599 fname = (const char *) fnametmp;
1601 fd = open(fname, O_WRONLY | O_CREAT | O_EXCL, 0600);
1603 stream = fdopen(fd, "w");
1605 if (fd == -1 || !stream)
1607 psql_error("could not open temporary file \"%s\": %s\n", fname, strerror(errno));
1612 unsigned int ql = query_buf->len;
1614 if (ql == 0 || query_buf->data[ql - 1] != '\n')
1616 appendPQExpBufferChar(query_buf, '\n');
1620 if (fwrite(query_buf->data, 1, ql, stream) != ql)
1622 psql_error("%s: %s\n", fname, strerror(errno));
1627 else if (fclose(stream) != 0)
1629 psql_error("%s: %s\n", fname, strerror(errno));
1636 if (!error && stat(fname, &before) != 0)
1638 psql_error("%s: %s\n", fname, strerror(errno));
1644 error = !editFile(fname);
1646 if (!error && stat(fname, &after) != 0)
1648 psql_error("%s: %s\n", fname, strerror(errno));
1652 if (!error && before.st_mtime != after.st_mtime)
1654 stream = fopen(fname, PG_BINARY_R);
1657 psql_error("%s: %s\n", fname, strerror(errno));
1662 /* read file back into query_buf */
1665 resetPQExpBuffer(query_buf);
1666 while (fgets(line, sizeof(line), stream) != NULL)
1667 appendPQExpBufferStr(query_buf, line);
1671 psql_error("%s: %s\n", fname, strerror(errno));
1683 /* remove temp file */
1686 if (remove(fname) == -1)
1688 psql_error("%s: %s\n", fname, strerror(errno));
1701 * Read commands from filename and then them to the main processing loop
1702 * Handler for \i, but can be used for other things as well. Returns
1703 * MainLoop() error code.
1706 process_file(char *filename, bool single_txn)
1714 return EXIT_FAILURE;
1716 if (strcmp(filename, "-") != 0)
1718 canonicalize_path(filename);
1719 fd = fopen(filename, PG_BINARY_R);
1726 psql_error("%s: %s\n", filename, strerror(errno));
1727 return EXIT_FAILURE;
1730 oldfilename = pset.inputfile;
1731 pset.inputfile = filename;
1735 if ((res = PSQLexec("BEGIN", false)) == NULL)
1737 if (pset.on_error_stop)
1744 result = MainLoop(fd);
1748 if ((res = PSQLexec("COMMIT", false)) == NULL)
1750 if (pset.on_error_stop)
1758 pset.inputfile = oldfilename;
1769 _align2string(enum printFormat in)
1776 case PRINT_UNALIGNED:
1791 case PRINT_TROFF_MS:
1800 do_pset(const char *param, const char *value, printQueryOpt *popt, bool quiet)
1807 vallen = strlen(value);
1810 if (strcmp(param, "format") == 0)
1814 else if (pg_strncasecmp("unaligned", value, vallen) == 0)
1815 popt->topt.format = PRINT_UNALIGNED;
1816 else if (pg_strncasecmp("aligned", value, vallen) == 0)
1817 popt->topt.format = PRINT_ALIGNED;
1818 else if (pg_strncasecmp("wrapped", value, vallen) == 0)
1819 popt->topt.format = PRINT_WRAPPED;
1820 else if (pg_strncasecmp("html", value, vallen) == 0)
1821 popt->topt.format = PRINT_HTML;
1822 else if (pg_strncasecmp("latex", value, vallen) == 0)
1823 popt->topt.format = PRINT_LATEX;
1824 else if (pg_strncasecmp("troff-ms", value, vallen) == 0)
1825 popt->topt.format = PRINT_TROFF_MS;
1828 psql_error("\\pset: allowed formats are unaligned, aligned, wrapped, html, latex, troff-ms\n");
1833 printf(_("Output format is %s.\n"), _align2string(popt->topt.format));
1836 /* set table line style */
1837 else if (strcmp(param, "linestyle") == 0)
1841 else if (pg_strncasecmp("ascii", value, vallen) == 0)
1842 popt->topt.line_style = &pg_asciiformat;
1843 else if (pg_strncasecmp("old-ascii", value, vallen) == 0)
1844 popt->topt.line_style = &pg_asciiformat_old;
1845 else if (pg_strncasecmp("unicode", value, vallen) == 0)
1846 popt->topt.line_style = &pg_utf8format;
1849 psql_error("\\pset: allowed line styles are ascii, old-ascii, unicode\n");
1854 printf(_("Line style is %s.\n"),
1855 get_line_style(&popt->topt)->name);
1858 /* set border style/width */
1859 else if (strcmp(param, "border") == 0)
1862 popt->topt.border = atoi(value);
1865 printf(_("Border style is %d.\n"), popt->topt.border);
1868 /* set expanded/vertical mode */
1869 else if (strcmp(param, "x") == 0 || strcmp(param, "expanded") == 0 || strcmp(param, "vertical") == 0)
1872 popt->topt.expanded = ParseVariableBool(value);
1874 popt->topt.expanded = !popt->topt.expanded;
1876 printf(popt->topt.expanded
1877 ? _("Expanded display is on.\n")
1878 : _("Expanded display is off.\n"));
1881 /* locale-aware numeric output */
1882 else if (strcmp(param, "numericlocale") == 0)
1885 popt->topt.numericLocale = ParseVariableBool(value);
1887 popt->topt.numericLocale = !popt->topt.numericLocale;
1890 if (popt->topt.numericLocale)
1891 puts(_("Showing locale-adjusted numeric output."));
1893 puts(_("Locale-adjusted numeric output is off."));
1898 else if (strcmp(param, "null") == 0)
1902 free(popt->nullPrint);
1903 popt->nullPrint = pg_strdup(value);
1906 printf(_("Null display is \"%s\".\n"), popt->nullPrint ? popt->nullPrint : "");
1909 /* field separator for unaligned text */
1910 else if (strcmp(param, "fieldsep") == 0)
1914 free(popt->topt.fieldSep);
1915 popt->topt.fieldSep = pg_strdup(value);
1918 printf(_("Field separator is \"%s\".\n"), popt->topt.fieldSep);
1921 /* record separator for unaligned text */
1922 else if (strcmp(param, "recordsep") == 0)
1926 free(popt->topt.recordSep);
1927 popt->topt.recordSep = pg_strdup(value);
1931 if (strcmp(popt->topt.recordSep, "\n") == 0)
1932 printf(_("Record separator is <newline>."));
1934 printf(_("Record separator is \"%s\".\n"), popt->topt.recordSep);
1938 /* toggle between full and tuples-only format */
1939 else if (strcmp(param, "t") == 0 || strcmp(param, "tuples_only") == 0)
1942 popt->topt.tuples_only = ParseVariableBool(value);
1944 popt->topt.tuples_only = !popt->topt.tuples_only;
1947 if (popt->topt.tuples_only)
1948 puts(_("Showing only tuples."));
1950 puts(_("Tuples only is off."));
1954 /* set title override */
1955 else if (strcmp(param, "title") == 0)
1961 popt->title = pg_strdup(value);
1966 printf(_("Title is \"%s\".\n"), popt->title);
1968 printf(_("Title is unset.\n"));
1972 /* set HTML table tag options */
1973 else if (strcmp(param, "T") == 0 || strcmp(param, "tableattr") == 0)
1975 free(popt->topt.tableAttr);
1977 popt->topt.tableAttr = NULL;
1979 popt->topt.tableAttr = pg_strdup(value);
1983 if (popt->topt.tableAttr)
1984 printf(_("Table attribute is \"%s\".\n"), popt->topt.tableAttr);
1986 printf(_("Table attributes unset.\n"));
1990 /* toggle use of pager */
1991 else if (strcmp(param, "pager") == 0)
1993 if (value && pg_strcasecmp(value, "always") == 0)
1994 popt->topt.pager = 2;
1996 if (ParseVariableBool(value))
1997 popt->topt.pager = 1;
1999 popt->topt.pager = 0;
2000 else if (popt->topt.pager == 1)
2001 popt->topt.pager = 0;
2003 popt->topt.pager = 1;
2006 if (popt->topt.pager == 1)
2007 puts(_("Pager is used for long output."));
2008 else if (popt->topt.pager == 2)
2009 puts(_("Pager is always used."));
2011 puts(_("Pager usage is off."));
2015 /* disable "(x rows)" footer */
2016 else if (strcmp(param, "footer") == 0)
2019 popt->default_footer = ParseVariableBool(value);
2021 popt->default_footer = !popt->default_footer;
2024 if (popt->default_footer)
2025 puts(_("Default footer is on."));
2027 puts(_("Default footer is off."));
2031 /* set border style/width */
2032 else if (strcmp(param, "columns") == 0)
2035 popt->topt.columns = atoi(value);
2038 printf(_("Target width for \"wrapped\" format is %d.\n"), popt->topt.columns);
2043 psql_error("\\pset: unknown option: %s\n", param);
2053 #define DEFAULT_SHELL "/bin/sh"
2056 * CMD.EXE is in different places in different Win32 releases so we
2057 * have to rely on the path to find it.
2059 #define DEFAULT_SHELL "cmd.exe"
2063 do_shell(const char *command)
2070 const char *shellName;
2072 shellName = getenv("SHELL");
2074 if (shellName == NULL)
2075 shellName = getenv("COMSPEC");
2077 if (shellName == NULL)
2078 shellName = DEFAULT_SHELL;
2080 sys = pg_malloc(strlen(shellName) + 16);
2083 /* See EDITOR handling comment for an explaination */
2084 "exec %s", shellName);
2086 /* See EDITOR handling comment for an explaination */
2087 sprintf(sys, SYSTEMQUOTE "\"%s\"" SYSTEMQUOTE, shellName);
2089 result = system(sys);
2093 result = system(command);
2095 if (result == 127 || result == -1)
2097 psql_error("\\!: failed\n");
2104 * This function takes a function description, e.g. "x" or "x(int)", and
2105 * issues a query on the given connection to retrieve the function's OID
2106 * using a cast to regproc or regprocedure (as appropriate). The result,
2107 * if there is one, is returned at *foid. Note that we'll fail if the
2108 * function doesn't exist OR if there are multiple matching candidates
2109 * OR if there's something syntactically wrong with the function description;
2110 * unfortunately it can be hard to tell the difference.
2113 lookup_function_oid(PGconn *conn, const char *desc, Oid *foid)
2119 query = createPQExpBuffer();
2120 printfPQExpBuffer(query, "SELECT ");
2121 appendStringLiteralConn(query, desc, conn);
2122 appendPQExpBuffer(query, "::pg_catalog.%s::pg_catalog.oid",
2123 strchr(desc, '(') ? "regprocedure" : "regproc");
2125 res = PQexec(conn, query->data);
2126 if (PQresultStatus(res) == PGRES_TUPLES_OK && PQntuples(res) == 1)
2127 *foid = atooid(PQgetvalue(res, 0, 0));
2130 minimal_error_message(res);
2135 destroyPQExpBuffer(query);
2141 * Fetches the "CREATE OR REPLACE FUNCTION ..." command that describes the
2142 * function with the given OID. If successful, the result is stored in buf.
2145 get_create_function_cmd(PGconn *conn, Oid oid, PQExpBuffer buf)
2151 query = createPQExpBuffer();
2152 printfPQExpBuffer(query, "SELECT pg_catalog.pg_get_functiondef(%u)", oid);
2154 res = PQexec(conn, query->data);
2155 if (PQresultStatus(res) == PGRES_TUPLES_OK && PQntuples(res) == 1)
2157 resetPQExpBuffer(buf);
2158 appendPQExpBufferStr(buf, PQgetvalue(res, 0, 0));
2162 minimal_error_message(res);
2167 destroyPQExpBuffer(query);
2173 * Report just the primary error; this is to avoid cluttering the output
2174 * with, for instance, a redisplay of the internally generated query
2177 minimal_error_message(PGresult *res)
2182 msg = createPQExpBuffer();
2184 fld = PQresultErrorField(res, PG_DIAG_SEVERITY);
2186 printfPQExpBuffer(msg, "%s: ", fld);
2188 printfPQExpBuffer(msg, "ERROR: ");
2189 fld = PQresultErrorField(res, PG_DIAG_MESSAGE_PRIMARY);
2191 appendPQExpBufferStr(msg, fld);
2193 appendPQExpBufferStr(msg, "(not available)");
2194 appendPQExpBufferStr(msg, "\n");
2196 psql_error("%s", msg->data);
2198 destroyPQExpBuffer(msg);