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.222 2010/07/20 03:54:19 rhaas 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);
297 /* \conninfo -- display information about the current connection */
298 else if (strcmp(cmd, "conninfo") == 0)
300 char *db = PQdb(pset.db);
301 char *host = PQhost(pset.db);
304 printf("You are not connected.\n");
306 printf("You are connected to database \"%s\" on host \"%s\" at port \"%s\" as user \"%s\".\n",
307 db, host, PQport(pset.db), PQuser(pset.db));
309 printf("You are connected to database \"%s\" via local socket as user \"%s\".\n",
310 db, PQuser(pset.db));
314 else if (pg_strcasecmp(cmd, "copy") == 0)
316 /* Default fetch-it-all-and-print mode */
320 char *opt = psql_scan_slash_option(scan_state,
321 OT_WHOLE_LINE, NULL, false);
324 INSTR_TIME_SET_CURRENT(before);
326 success = do_copy(opt);
328 if (pset.timing && success)
330 INSTR_TIME_SET_CURRENT(after);
331 INSTR_TIME_SUBTRACT(after, before);
332 printf(_("Time: %.3f ms\n"), INSTR_TIME_GET_MILLISEC(after));
339 else if (strcmp(cmd, "copyright") == 0)
343 else if (cmd[0] == 'd')
349 /* We don't do SQLID reduction on the pattern yet */
350 pattern = psql_scan_slash_option(scan_state,
351 OT_NORMAL, NULL, true);
353 show_verbose = strchr(cmd, '+') ? true : false;
354 show_system = strchr(cmd, 'S') ? true : false;
362 success = describeTableDetails(pattern, show_verbose, show_system);
364 /* standard listing of interesting things */
365 success = listTables("tvs", NULL, show_verbose, show_system);
368 success = describeAggregates(pattern, show_verbose, show_system);
371 success = describeTablespaces(pattern, show_verbose);
374 success = listConversions(pattern, show_system);
377 success = listCasts(pattern);
380 if (strncmp(cmd, "ddp", 3) == 0)
381 success = listDefaultACLs(pattern);
383 success = objectDescription(pattern, show_system);
386 success = listDomains(pattern, show_system);
388 case 'f': /* function subsystem */
398 success = describeFunctions(&cmd[2], pattern, show_verbose, show_system);
401 status = PSQL_CMD_UNKNOWN;
406 /* no longer distinct from \du */
407 success = describeRoles(pattern, show_verbose);
410 success = do_lo_list();
413 success = listSchemas(pattern, show_verbose);
416 success = describeOperators(pattern, show_system);
419 success = permissionsList(pattern);
422 success = describeTypes(pattern, show_verbose, show_system);
428 success = listTables(&cmd[1], pattern, show_verbose, show_system);
431 if (cmd[2] == 'd' && cmd[3] == 's')
433 char *pattern2 = NULL;
436 pattern2 = psql_scan_slash_option(scan_state,
437 OT_NORMAL, NULL, true);
438 success = listDbRoleSettings(pattern, pattern2);
441 success = PSQL_CMD_UNKNOWN;
444 success = describeRoles(pattern, show_verbose);
446 case 'F': /* text search subsystem */
451 success = listTSConfigs(pattern, show_verbose);
454 success = listTSParsers(pattern, show_verbose);
457 success = listTSDictionaries(pattern, show_verbose);
460 success = listTSTemplates(pattern, show_verbose);
463 status = PSQL_CMD_UNKNOWN;
467 case 'e': /* SQL/MED subsystem */
471 success = listForeignServers(pattern, show_verbose);
474 success = listUserMappings(pattern, show_verbose);
477 success = listForeignDataWrappers(pattern, show_verbose);
480 status = PSQL_CMD_UNKNOWN;
485 status = PSQL_CMD_UNKNOWN;
494 * \e or \edit -- edit the current query buffer (or a file and make it the
497 else if (strcmp(cmd, "e") == 0 || strcmp(cmd, "edit") == 0)
501 psql_error("no query buffer\n");
502 status = PSQL_CMD_ERROR;
508 fname = psql_scan_slash_option(scan_state,
509 OT_NORMAL, NULL, true);
510 expand_tilde(&fname);
512 canonicalize_path(fname);
513 if (do_edit(fname, query_buf, NULL))
514 status = PSQL_CMD_NEWEDIT;
516 status = PSQL_CMD_ERROR;
522 * \ef -- edit the named function, or present a blank CREATE FUNCTION
523 * template if no argument is given
525 else if (strcmp(cmd, "ef") == 0)
529 psql_error("no query buffer\n");
530 status = PSQL_CMD_ERROR;
535 Oid foid = InvalidOid;
537 func = psql_scan_slash_option(scan_state,
538 OT_WHOLE_LINE, NULL, true);
541 /* set up an empty command to fill in */
542 printfPQExpBuffer(query_buf,
543 "CREATE FUNCTION ( )\n"
546 " -- common options: IMMUTABLE STABLE STRICT SECURITY DEFINER\n"
550 else if (!lookup_function_oid(pset.db, func, &foid))
552 /* error already reported */
553 status = PSQL_CMD_ERROR;
555 else if (!get_create_function_cmd(pset.db, foid, query_buf))
557 /* error already reported */
558 status = PSQL_CMD_ERROR;
564 if (status != PSQL_CMD_ERROR)
568 if (!do_edit(0, query_buf, &edited))
569 status = PSQL_CMD_ERROR;
571 puts(_("No changes"));
573 status = PSQL_CMD_NEWEDIT;
577 /* \echo and \qecho */
578 else if (strcmp(cmd, "echo") == 0 || strcmp(cmd, "qecho") == 0)
582 bool no_newline = false;
586 if (strcmp(cmd, "qecho") == 0)
587 fout = pset.queryFout;
591 while ((value = psql_scan_slash_option(scan_state,
592 OT_NORMAL, "ed, false)))
594 if (!quoted && strcmp(value, "-n") == 0)
610 /* \encoding -- set/show client side encoding */
611 else if (strcmp(cmd, "encoding") == 0)
613 char *encoding = psql_scan_slash_option(scan_state,
614 OT_NORMAL, NULL, false);
619 puts(pg_encoding_to_char(pset.encoding));
624 if (PQsetClientEncoding(pset.db, encoding) == -1)
625 psql_error("%s: invalid encoding name or conversion procedure not found\n", encoding);
628 /* save encoding info into psql internal data */
629 pset.encoding = PQclientEncoding(pset.db);
630 pset.popt.topt.encoding = pset.encoding;
631 SetVariable(pset.vars, "ENCODING",
632 pg_encoding_to_char(pset.encoding));
638 /* \f -- change field separator */
639 else if (strcmp(cmd, "f") == 0)
641 char *fname = psql_scan_slash_option(scan_state,
642 OT_NORMAL, NULL, false);
644 success = do_pset("fieldsep", fname, &pset.popt, pset.quiet);
648 /* \g means send query */
649 else if (strcmp(cmd, "g") == 0)
651 char *fname = psql_scan_slash_option(scan_state,
652 OT_FILEPIPE, NULL, false);
658 expand_tilde(&fname);
659 pset.gfname = pg_strdup(fname);
662 status = PSQL_CMD_SEND;
666 else if (strcmp(cmd, "h") == 0 || strcmp(cmd, "help") == 0)
668 char *opt = psql_scan_slash_option(scan_state,
669 OT_WHOLE_LINE, NULL, false);
672 /* strip any trailing spaces and semicolons */
677 (isspace((unsigned char) opt[len - 1])
678 || opt[len - 1] == ';'))
682 helpSQL(opt, pset.popt.topt.pager);
687 else if (strcmp(cmd, "H") == 0 || strcmp(cmd, "html") == 0)
689 if (pset.popt.topt.format != PRINT_HTML)
690 success = do_pset("format", "html", &pset.popt, pset.quiet);
692 success = do_pset("format", "aligned", &pset.popt, pset.quiet);
696 /* \i is include file */
697 else if (strcmp(cmd, "i") == 0 || strcmp(cmd, "include") == 0)
699 char *fname = psql_scan_slash_option(scan_state,
700 OT_NORMAL, NULL, true);
704 psql_error("\\%s: missing required argument\n", cmd);
709 expand_tilde(&fname);
710 success = (process_file(fname, false) == EXIT_SUCCESS);
715 /* \l is list databases */
716 else if (strcmp(cmd, "l") == 0 || strcmp(cmd, "list") == 0)
717 success = listAllDbs(false);
718 else if (strcmp(cmd, "l+") == 0 || strcmp(cmd, "list+") == 0)
719 success = listAllDbs(true);
722 * large object things
724 else if (strncmp(cmd, "lo_", 3) == 0)
729 opt1 = psql_scan_slash_option(scan_state,
730 OT_NORMAL, NULL, true);
731 opt2 = psql_scan_slash_option(scan_state,
732 OT_NORMAL, NULL, true);
734 if (strcmp(cmd + 3, "export") == 0)
738 psql_error("\\%s: missing required argument\n", cmd);
744 success = do_lo_export(opt1, opt2);
748 else if (strcmp(cmd + 3, "import") == 0)
752 psql_error("\\%s: missing required argument\n", cmd);
758 success = do_lo_import(opt1, opt2);
762 else if (strcmp(cmd + 3, "list") == 0)
763 success = do_lo_list();
765 else if (strcmp(cmd + 3, "unlink") == 0)
769 psql_error("\\%s: missing required argument\n", cmd);
773 success = do_lo_unlink(opt1);
777 status = PSQL_CMD_UNKNOWN;
784 /* \o -- set query output */
785 else if (strcmp(cmd, "o") == 0 || strcmp(cmd, "out") == 0)
787 char *fname = psql_scan_slash_option(scan_state,
788 OT_FILEPIPE, NULL, true);
790 expand_tilde(&fname);
791 success = setQFout(fname);
795 /* \p prints the current query buffer */
796 else if (strcmp(cmd, "p") == 0 || strcmp(cmd, "print") == 0)
798 if (query_buf && query_buf->len > 0)
799 puts(query_buf->data);
800 else if (!pset.quiet)
801 puts(_("Query buffer is empty."));
805 /* \password -- set user password */
806 else if (strcmp(cmd, "password") == 0)
811 pw1 = simple_prompt("Enter new password: ", 100, false);
812 pw2 = simple_prompt("Enter it again: ", 100, false);
814 if (strcmp(pw1, pw2) != 0)
816 fprintf(stderr, _("Passwords didn't match.\n"));
821 char *opt0 = psql_scan_slash_option(scan_state, OT_SQLID, NULL, true);
823 char *encrypted_password;
828 user = PQuser(pset.db);
830 encrypted_password = PQencryptPassword(pw1, user);
832 if (!encrypted_password)
834 fprintf(stderr, _("Password encryption failed.\n"));
842 initPQExpBuffer(&buf);
843 printfPQExpBuffer(&buf, "ALTER USER %s PASSWORD ",
845 appendStringLiteralConn(&buf, encrypted_password, pset.db);
846 res = PSQLexec(buf.data, false);
847 termPQExpBuffer(&buf);
852 PQfreemem(encrypted_password);
860 /* \prompt -- prompt and set variable */
861 else if (strcmp(cmd, "prompt") == 0)
868 arg1 = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false);
869 arg2 = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false);
873 psql_error("\\%s: missing required argument\n", cmd);
889 result = simple_prompt(prompt_text, 4096, true);
894 fputs(prompt_text, stdout);
897 result = gets_fromFile(stdin);
900 if (!SetVariable(pset.vars, opt, result))
902 psql_error("\\%s: error\n", cmd);
913 /* \pset -- set printing parameters */
914 else if (strcmp(cmd, "pset") == 0)
916 char *opt0 = psql_scan_slash_option(scan_state,
917 OT_NORMAL, NULL, false);
918 char *opt1 = psql_scan_slash_option(scan_state,
919 OT_NORMAL, NULL, false);
923 psql_error("\\%s: missing required argument\n", cmd);
927 success = do_pset(opt0, opt1, &pset.popt, pset.quiet);
934 else if (strcmp(cmd, "q") == 0 || strcmp(cmd, "quit") == 0)
935 status = PSQL_CMD_TERMINATE;
937 /* reset(clear) the buffer */
938 else if (strcmp(cmd, "r") == 0 || strcmp(cmd, "reset") == 0)
940 resetPQExpBuffer(query_buf);
941 psql_scan_reset(scan_state);
943 puts(_("Query buffer reset (cleared)."));
946 /* \s save history in a file or show it on the screen */
947 else if (strcmp(cmd, "s") == 0)
949 char *fname = psql_scan_slash_option(scan_state,
950 OT_NORMAL, NULL, true);
952 expand_tilde(&fname);
953 /* This scrolls off the screen when using /dev/tty */
954 success = saveHistory(fname ? fname : DEVTTY, -1, false, false);
955 if (success && !pset.quiet && fname)
956 printf(gettext("Wrote history to file \"%s/%s\".\n"),
957 pset.dirname ? pset.dirname : ".", fname);
963 /* \set -- generalized set variable/option command */
964 else if (strcmp(cmd, "set") == 0)
966 char *opt0 = psql_scan_slash_option(scan_state,
967 OT_NORMAL, NULL, false);
971 /* list all variables */
972 PrintVariables(pset.vars);
978 * Set variable to the concatenation of the arguments.
983 opt = psql_scan_slash_option(scan_state,
984 OT_NORMAL, NULL, false);
985 newval = pg_strdup(opt ? opt : "");
988 while ((opt = psql_scan_slash_option(scan_state,
989 OT_NORMAL, NULL, false)))
991 newval = realloc(newval, strlen(newval) + strlen(opt) + 1);
994 psql_error("out of memory\n");
1001 if (!SetVariable(pset.vars, opt0, newval))
1003 psql_error("\\%s: error\n", cmd);
1011 /* \t -- turn off headers and row count */
1012 else if (strcmp(cmd, "t") == 0)
1014 char *opt = psql_scan_slash_option(scan_state,
1015 OT_NORMAL, NULL, true);
1017 success = do_pset("tuples_only", opt, &pset.popt, pset.quiet);
1022 /* \T -- define html <table ...> attributes */
1023 else if (strcmp(cmd, "T") == 0)
1025 char *value = psql_scan_slash_option(scan_state,
1026 OT_NORMAL, NULL, false);
1028 success = do_pset("tableattr", value, &pset.popt, pset.quiet);
1032 /* \timing -- toggle timing of queries */
1033 else if (strcmp(cmd, "timing") == 0)
1035 char *opt = psql_scan_slash_option(scan_state,
1036 OT_NORMAL, NULL, false);
1039 pset.timing = ParseVariableBool(opt);
1041 pset.timing = !pset.timing;
1045 puts(_("Timing is on."));
1047 puts(_("Timing is off."));
1053 else if (strcmp(cmd, "unset") == 0)
1055 char *opt = psql_scan_slash_option(scan_state,
1056 OT_NORMAL, NULL, false);
1060 psql_error("\\%s: missing required argument\n", cmd);
1063 else if (!SetVariable(pset.vars, opt, NULL))
1065 psql_error("\\%s: error\n", cmd);
1071 /* \w -- write query buffer to file */
1072 else if (strcmp(cmd, "w") == 0 || strcmp(cmd, "write") == 0)
1075 bool is_pipe = false;
1080 psql_error("no query buffer\n");
1081 status = PSQL_CMD_ERROR;
1085 fname = psql_scan_slash_option(scan_state,
1086 OT_FILEPIPE, NULL, true);
1087 expand_tilde(&fname);
1091 psql_error("\\%s: missing required argument\n", cmd);
1096 if (fname[0] == '|')
1099 fd = popen(&fname[1], "w");
1103 canonicalize_path(fname);
1104 fd = fopen(fname, "w");
1108 psql_error("%s: %s\n", fname, strerror(errno));
1118 if (query_buf && query_buf->len > 0)
1119 fprintf(fd, "%s\n", query_buf->data);
1122 result = pclose(fd);
1124 result = fclose(fd);
1128 psql_error("%s: %s\n", fname, strerror(errno));
1136 /* \x -- toggle expanded table representation */
1137 else if (strcmp(cmd, "x") == 0)
1139 char *opt = psql_scan_slash_option(scan_state,
1140 OT_NORMAL, NULL, true);
1142 success = do_pset("expanded", opt, &pset.popt, pset.quiet);
1146 /* \z -- list table rights (equivalent to \dp) */
1147 else if (strcmp(cmd, "z") == 0)
1149 char *pattern = psql_scan_slash_option(scan_state,
1150 OT_NORMAL, NULL, true);
1152 success = permissionsList(pattern);
1157 /* \! -- shell escape */
1158 else if (strcmp(cmd, "!") == 0)
1160 char *opt = psql_scan_slash_option(scan_state,
1161 OT_WHOLE_LINE, NULL, false);
1163 success = do_shell(opt);
1167 /* \? -- slash command help */
1168 else if (strcmp(cmd, "?") == 0)
1169 slashUsage(pset.popt.topt.pager);
1174 * These commands don't do anything. I just use them to test the parser.
1176 else if (strcmp(cmd, "void") == 0 || strcmp(cmd, "#") == 0)
1181 while ((value = psql_scan_slash_option(scan_state,
1182 OT_NORMAL, NULL, true)))
1184 fprintf(stderr, "+ opt(%d) = |%s|\n", i++, value);
1191 status = PSQL_CMD_UNKNOWN;
1194 status = PSQL_CMD_ERROR;
1200 * Ask the user for a password; 'username' is the username the
1201 * password is for, if one has been explicitly specified. Returns a
1205 prompt_for_password(const char *username)
1209 if (username == NULL)
1210 result = simple_prompt("Password: ", 100, false);
1215 prompt_text = malloc(strlen(username) + 100);
1216 snprintf(prompt_text, strlen(username) + 100,
1217 _("Password for user %s: "), username);
1218 result = simple_prompt(prompt_text, 100, false);
1226 param_is_newly_set(const char *old_val, const char *new_val)
1228 if (new_val == NULL)
1231 if (old_val == NULL || strcmp(old_val, new_val) != 0)
1238 * do_connect -- handler for \connect
1240 * Connects to a database with given parameters. If there exists an
1241 * established connection, NULL values will be replaced with the ones
1242 * in the current connection. Otherwise NULL will be passed for that
1243 * parameter to PQconnectdbParams(), so the libpq defaults will be used.
1245 * In interactive mode, if connection fails with the given parameters,
1246 * the old connection will be kept.
1249 do_connect(char *dbname, char *user, char *host, char *port)
1251 PGconn *o_conn = pset.db,
1253 char *password = NULL;
1256 dbname = PQdb(o_conn);
1258 user = PQuser(o_conn);
1260 host = PQhost(o_conn);
1262 port = PQport(o_conn);
1265 * If the user asked to be prompted for a password, ask for one now. If
1266 * not, use the password from the old connection, provided the username
1267 * has not changed. Otherwise, try to connect without a password first,
1268 * and then ask for a password if needed.
1270 * XXX: this behavior leads to spurious connection attempts recorded in
1271 * the postmaster's log. But libpq offers no API that would let us obtain
1272 * a password and then continue with the first connection attempt.
1274 if (pset.getPassword == TRI_YES)
1276 password = prompt_for_password(user);
1278 else if (o_conn && user && strcmp(PQuser(o_conn), user) == 0)
1280 password = strdup(PQpass(o_conn));
1285 #define PARAMS_ARRAY_SIZE 7
1286 const char **keywords = pg_malloc(PARAMS_ARRAY_SIZE * sizeof(*keywords));
1287 const char **values = pg_malloc(PARAMS_ARRAY_SIZE * sizeof(*values));
1289 keywords[0] = "host";
1291 keywords[1] = "port";
1293 keywords[2] = "user";
1295 keywords[3] = "password";
1296 values[3] = password;
1297 keywords[4] = "dbname";
1299 keywords[5] = "fallback_application_name";
1300 values[5] = pset.progname;
1304 n_conn = PQconnectdbParams(keywords, values, true);
1309 /* We can immediately discard the password -- no longer needed */
1313 if (PQstatus(n_conn) == CONNECTION_OK)
1317 * Connection attempt failed; either retry the connection attempt with
1318 * a new password, or give up.
1320 if (!password && PQconnectionNeedsPassword(n_conn) && pset.getPassword != TRI_NO)
1323 password = prompt_for_password(user);
1328 * Failed to connect to the database. In interactive mode, keep the
1329 * previous connection to the DB; in scripting mode, close our
1330 * previous connection as well.
1332 if (pset.cur_cmd_interactive)
1334 psql_error("%s", PQerrorMessage(n_conn));
1336 /* pset.db is left unmodified */
1338 fputs(_("Previous connection kept\n"), stderr);
1342 psql_error("\\connect: %s", PQerrorMessage(n_conn));
1355 * Replace the old connection with the new one, and update
1356 * connection-dependent variables.
1358 PQsetNoticeProcessor(n_conn, NoticeProcessor, NULL);
1361 connection_warnings(false); /* Must be after SyncVariables */
1363 /* Tell the user about the new connection */
1366 printf(_("You are now connected to database \"%s\""), PQdb(pset.db));
1368 if (param_is_newly_set(PQhost(o_conn), PQhost(pset.db)))
1369 printf(_(" on host \"%s\""), PQhost(pset.db));
1371 if (param_is_newly_set(PQport(o_conn), PQport(pset.db)))
1372 printf(_(" at port \"%s\""), PQport(pset.db));
1374 if (param_is_newly_set(PQuser(o_conn), PQuser(pset.db)))
1375 printf(_(" as user \"%s\""), PQuser(pset.db));
1387 connection_warnings(bool in_startup)
1389 if (!pset.quiet && !pset.notty)
1391 int client_ver = parse_version(PG_VERSION);
1393 if (pset.sversion != client_ver)
1395 const char *server_version;
1396 char server_ver_str[16];
1398 /* Try to get full text form, might include "devel" etc */
1399 server_version = PQparameterStatus(pset.db, "server_version");
1400 if (!server_version)
1402 snprintf(server_ver_str, sizeof(server_ver_str),
1404 pset.sversion / 10000,
1405 (pset.sversion / 100) % 100,
1406 pset.sversion % 100);
1407 server_version = server_ver_str;
1410 printf(_("%s (%s, server %s)\n"),
1411 pset.progname, PG_VERSION, server_version);
1413 /* For version match, only print psql banner on startup. */
1414 else if (in_startup)
1415 printf("%s (%s)\n", pset.progname, PG_VERSION);
1417 if (pset.sversion / 100 != client_ver / 100)
1418 printf(_("WARNING: %s version %d.%d, server version %d.%d.\n"
1419 " Some psql features might not work.\n"),
1420 pset.progname, client_ver / 10000, (client_ver / 100) % 100,
1421 pset.sversion / 10000, (pset.sversion / 100) % 100);
1424 checkWin32Codepage();
1434 * Prints information about the current SSL connection, if SSL is in use
1443 ssl = PQgetssl(pset.db);
1445 return; /* no SSL */
1447 SSL_get_cipher_bits(ssl, &sslbits);
1448 printf(_("SSL connection (cipher: %s, bits: %i)\n"),
1449 SSL_get_cipher(ssl), sslbits);
1453 * If psql is compiled without SSL but is using a libpq with SSL, we
1454 * cannot figure out the specifics about the connection. But we know it's
1457 if (PQgetssl(pset.db))
1458 printf(_("SSL connection (unknown cipher)\n"));
1464 * checkWin32Codepage
1466 * Prints a warning when win32 console codepage differs from Windows codepage
1470 checkWin32Codepage(void)
1476 concp = GetConsoleCP();
1479 printf(_("WARNING: Console code page (%u) differs from Windows code page (%u)\n"
1480 " 8-bit characters might not work correctly. See psql reference\n"
1481 " page \"Notes for Windows users\" for details.\n"),
1491 * Make psql's internal variables agree with connection state upon
1492 * establishing a new connection.
1497 /* get stuff from connection */
1498 pset.encoding = PQclientEncoding(pset.db);
1499 pset.popt.topt.encoding = pset.encoding;
1500 pset.sversion = PQserverVersion(pset.db);
1502 SetVariable(pset.vars, "DBNAME", PQdb(pset.db));
1503 SetVariable(pset.vars, "USER", PQuser(pset.db));
1504 SetVariable(pset.vars, "HOST", PQhost(pset.db));
1505 SetVariable(pset.vars, "PORT", PQport(pset.db));
1506 SetVariable(pset.vars, "ENCODING", pg_encoding_to_char(pset.encoding));
1508 /* send stuff to it, too */
1509 PQsetErrorVerbosity(pset.db, pset.verbosity);
1515 * Clear variables that should be not be set when there is no connection.
1518 UnsyncVariables(void)
1520 SetVariable(pset.vars, "DBNAME", NULL);
1521 SetVariable(pset.vars, "USER", NULL);
1522 SetVariable(pset.vars, "HOST", NULL);
1523 SetVariable(pset.vars, "PORT", NULL);
1524 SetVariable(pset.vars, "ENCODING", NULL);
1529 * do_edit -- handler for \e
1531 * If you do not specify a filename, the current query buffer will be copied
1532 * into a temporary one.
1536 editFile(const char *fname)
1538 const char *editorName;
1544 /* Find an editor to use */
1545 editorName = getenv("PSQL_EDITOR");
1547 editorName = getenv("EDITOR");
1549 editorName = getenv("VISUAL");
1551 editorName = DEFAULT_EDITOR;
1554 * On Unix the EDITOR value should *not* be quoted, since it might include
1555 * switches, eg, EDITOR="pico -t"; it's up to the user to put quotes in it
1556 * if necessary. But this policy is not very workable on Windows, due to
1557 * severe brain damage in their command shell plus the fact that standard
1558 * program paths include spaces.
1560 sys = pg_malloc(strlen(editorName) + strlen(fname) + 10 + 1);
1562 sprintf(sys, "exec %s '%s'", editorName, fname);
1564 sprintf(sys, SYSTEMQUOTE "\"%s\" \"%s\"" SYSTEMQUOTE, editorName, fname);
1566 result = system(sys);
1568 psql_error("could not start editor \"%s\"\n", editorName);
1569 else if (result == 127)
1570 psql_error("could not start /bin/sh\n");
1579 do_edit(const char *filename_arg, PQExpBuffer query_buf, bool *edited)
1581 char fnametmp[MAXPGPATH];
1582 FILE *stream = NULL;
1591 fname = filename_arg;
1594 /* make a temp file to edit */
1596 const char *tmpdir = getenv("TMPDIR");
1601 char tmpdir[MAXPGPATH];
1604 ret = GetTempPath(MAXPGPATH, tmpdir);
1605 if (ret == 0 || ret > MAXPGPATH)
1607 psql_error("cannot locate temporary directory: %s",
1608 !ret ? strerror(errno) : "");
1613 * No canonicalize_path() here. EDIT.EXE run from CMD.EXE prepends the
1614 * current directory to the supplied path unless we use only
1615 * backslashes, so we do that.
1619 snprintf(fnametmp, sizeof(fnametmp), "%s%spsql.edit.%d", tmpdir,
1620 "/", (int) getpid());
1622 snprintf(fnametmp, sizeof(fnametmp), "%s%spsql.edit.%d", tmpdir,
1623 "" /* trailing separator already present */ , (int) getpid());
1626 fname = (const char *) fnametmp;
1628 fd = open(fname, O_WRONLY | O_CREAT | O_EXCL, 0600);
1630 stream = fdopen(fd, "w");
1632 if (fd == -1 || !stream)
1634 psql_error("could not open temporary file \"%s\": %s\n", fname, strerror(errno));
1639 unsigned int ql = query_buf->len;
1641 if (ql == 0 || query_buf->data[ql - 1] != '\n')
1643 appendPQExpBufferChar(query_buf, '\n');
1647 if (fwrite(query_buf->data, 1, ql, stream) != ql)
1649 psql_error("%s: %s\n", fname, strerror(errno));
1654 else if (fclose(stream) != 0)
1656 psql_error("%s: %s\n", fname, strerror(errno));
1663 if (!error && stat(fname, &before) != 0)
1665 psql_error("%s: %s\n", fname, strerror(errno));
1671 error = !editFile(fname);
1673 if (!error && stat(fname, &after) != 0)
1675 psql_error("%s: %s\n", fname, strerror(errno));
1679 if (!error && before.st_mtime != after.st_mtime)
1681 stream = fopen(fname, PG_BINARY_R);
1684 psql_error("%s: %s\n", fname, strerror(errno));
1689 /* read file back into query_buf */
1692 resetPQExpBuffer(query_buf);
1693 while (fgets(line, sizeof(line), stream) != NULL)
1694 appendPQExpBufferStr(query_buf, line);
1698 psql_error("%s: %s\n", fname, strerror(errno));
1710 /* remove temp file */
1713 if (remove(fname) == -1)
1715 psql_error("%s: %s\n", fname, strerror(errno));
1728 * Read commands from filename and then them to the main processing loop
1729 * Handler for \i, but can be used for other things as well. Returns
1730 * MainLoop() error code.
1733 process_file(char *filename, bool single_txn)
1741 return EXIT_FAILURE;
1743 if (strcmp(filename, "-") != 0)
1745 canonicalize_path(filename);
1746 fd = fopen(filename, PG_BINARY_R);
1753 psql_error("%s: %s\n", filename, strerror(errno));
1754 return EXIT_FAILURE;
1757 oldfilename = pset.inputfile;
1758 pset.inputfile = filename;
1762 if ((res = PSQLexec("BEGIN", false)) == NULL)
1764 if (pset.on_error_stop)
1771 result = MainLoop(fd);
1775 if ((res = PSQLexec("COMMIT", false)) == NULL)
1777 if (pset.on_error_stop)
1785 pset.inputfile = oldfilename;
1796 _align2string(enum printFormat in)
1803 case PRINT_UNALIGNED:
1818 case PRINT_TROFF_MS:
1827 do_pset(const char *param, const char *value, printQueryOpt *popt, bool quiet)
1834 vallen = strlen(value);
1837 if (strcmp(param, "format") == 0)
1841 else if (pg_strncasecmp("unaligned", value, vallen) == 0)
1842 popt->topt.format = PRINT_UNALIGNED;
1843 else if (pg_strncasecmp("aligned", value, vallen) == 0)
1844 popt->topt.format = PRINT_ALIGNED;
1845 else if (pg_strncasecmp("wrapped", value, vallen) == 0)
1846 popt->topt.format = PRINT_WRAPPED;
1847 else if (pg_strncasecmp("html", value, vallen) == 0)
1848 popt->topt.format = PRINT_HTML;
1849 else if (pg_strncasecmp("latex", value, vallen) == 0)
1850 popt->topt.format = PRINT_LATEX;
1851 else if (pg_strncasecmp("troff-ms", value, vallen) == 0)
1852 popt->topt.format = PRINT_TROFF_MS;
1855 psql_error("\\pset: allowed formats are unaligned, aligned, wrapped, html, latex, troff-ms\n");
1860 printf(_("Output format is %s.\n"), _align2string(popt->topt.format));
1863 /* set table line style */
1864 else if (strcmp(param, "linestyle") == 0)
1868 else if (pg_strncasecmp("ascii", value, vallen) == 0)
1869 popt->topt.line_style = &pg_asciiformat;
1870 else if (pg_strncasecmp("old-ascii", value, vallen) == 0)
1871 popt->topt.line_style = &pg_asciiformat_old;
1872 else if (pg_strncasecmp("unicode", value, vallen) == 0)
1873 popt->topt.line_style = &pg_utf8format;
1876 psql_error("\\pset: allowed line styles are ascii, old-ascii, unicode\n");
1881 printf(_("Line style is %s.\n"),
1882 get_line_style(&popt->topt)->name);
1885 /* set border style/width */
1886 else if (strcmp(param, "border") == 0)
1889 popt->topt.border = atoi(value);
1892 printf(_("Border style is %d.\n"), popt->topt.border);
1895 /* set expanded/vertical mode */
1896 else if (strcmp(param, "x") == 0 || strcmp(param, "expanded") == 0 || strcmp(param, "vertical") == 0)
1899 popt->topt.expanded = ParseVariableBool(value);
1901 popt->topt.expanded = !popt->topt.expanded;
1903 printf(popt->topt.expanded
1904 ? _("Expanded display is on.\n")
1905 : _("Expanded display is off.\n"));
1908 /* locale-aware numeric output */
1909 else if (strcmp(param, "numericlocale") == 0)
1912 popt->topt.numericLocale = ParseVariableBool(value);
1914 popt->topt.numericLocale = !popt->topt.numericLocale;
1917 if (popt->topt.numericLocale)
1918 puts(_("Showing locale-adjusted numeric output."));
1920 puts(_("Locale-adjusted numeric output is off."));
1925 else if (strcmp(param, "null") == 0)
1929 free(popt->nullPrint);
1930 popt->nullPrint = pg_strdup(value);
1933 printf(_("Null display is \"%s\".\n"), popt->nullPrint ? popt->nullPrint : "");
1936 /* field separator for unaligned text */
1937 else if (strcmp(param, "fieldsep") == 0)
1941 free(popt->topt.fieldSep);
1942 popt->topt.fieldSep = pg_strdup(value);
1945 printf(_("Field separator is \"%s\".\n"), popt->topt.fieldSep);
1948 /* record separator for unaligned text */
1949 else if (strcmp(param, "recordsep") == 0)
1953 free(popt->topt.recordSep);
1954 popt->topt.recordSep = pg_strdup(value);
1958 if (strcmp(popt->topt.recordSep, "\n") == 0)
1959 printf(_("Record separator is <newline>."));
1961 printf(_("Record separator is \"%s\".\n"), popt->topt.recordSep);
1965 /* toggle between full and tuples-only format */
1966 else if (strcmp(param, "t") == 0 || strcmp(param, "tuples_only") == 0)
1969 popt->topt.tuples_only = ParseVariableBool(value);
1971 popt->topt.tuples_only = !popt->topt.tuples_only;
1974 if (popt->topt.tuples_only)
1975 puts(_("Showing only tuples."));
1977 puts(_("Tuples only is off."));
1981 /* set title override */
1982 else if (strcmp(param, "title") == 0)
1988 popt->title = pg_strdup(value);
1993 printf(_("Title is \"%s\".\n"), popt->title);
1995 printf(_("Title is unset.\n"));
1999 /* set HTML table tag options */
2000 else if (strcmp(param, "T") == 0 || strcmp(param, "tableattr") == 0)
2002 free(popt->topt.tableAttr);
2004 popt->topt.tableAttr = NULL;
2006 popt->topt.tableAttr = pg_strdup(value);
2010 if (popt->topt.tableAttr)
2011 printf(_("Table attribute is \"%s\".\n"), popt->topt.tableAttr);
2013 printf(_("Table attributes unset.\n"));
2017 /* toggle use of pager */
2018 else if (strcmp(param, "pager") == 0)
2020 if (value && pg_strcasecmp(value, "always") == 0)
2021 popt->topt.pager = 2;
2023 if (ParseVariableBool(value))
2024 popt->topt.pager = 1;
2026 popt->topt.pager = 0;
2027 else if (popt->topt.pager == 1)
2028 popt->topt.pager = 0;
2030 popt->topt.pager = 1;
2033 if (popt->topt.pager == 1)
2034 puts(_("Pager is used for long output."));
2035 else if (popt->topt.pager == 2)
2036 puts(_("Pager is always used."));
2038 puts(_("Pager usage is off."));
2042 /* disable "(x rows)" footer */
2043 else if (strcmp(param, "footer") == 0)
2046 popt->default_footer = ParseVariableBool(value);
2048 popt->default_footer = !popt->default_footer;
2051 if (popt->default_footer)
2052 puts(_("Default footer is on."));
2054 puts(_("Default footer is off."));
2058 /* set border style/width */
2059 else if (strcmp(param, "columns") == 0)
2062 popt->topt.columns = atoi(value);
2065 printf(_("Target width for \"wrapped\" format is %d.\n"), popt->topt.columns);
2070 psql_error("\\pset: unknown option: %s\n", param);
2080 #define DEFAULT_SHELL "/bin/sh"
2083 * CMD.EXE is in different places in different Win32 releases so we
2084 * have to rely on the path to find it.
2086 #define DEFAULT_SHELL "cmd.exe"
2090 do_shell(const char *command)
2097 const char *shellName;
2099 shellName = getenv("SHELL");
2101 if (shellName == NULL)
2102 shellName = getenv("COMSPEC");
2104 if (shellName == NULL)
2105 shellName = DEFAULT_SHELL;
2107 sys = pg_malloc(strlen(shellName) + 16);
2110 /* See EDITOR handling comment for an explaination */
2111 "exec %s", shellName);
2113 /* See EDITOR handling comment for an explaination */
2114 sprintf(sys, SYSTEMQUOTE "\"%s\"" SYSTEMQUOTE, shellName);
2116 result = system(sys);
2120 result = system(command);
2122 if (result == 127 || result == -1)
2124 psql_error("\\!: failed\n");
2131 * This function takes a function description, e.g. "x" or "x(int)", and
2132 * issues a query on the given connection to retrieve the function's OID
2133 * using a cast to regproc or regprocedure (as appropriate). The result,
2134 * if there is one, is returned at *foid. Note that we'll fail if the
2135 * function doesn't exist OR if there are multiple matching candidates
2136 * OR if there's something syntactically wrong with the function description;
2137 * unfortunately it can be hard to tell the difference.
2140 lookup_function_oid(PGconn *conn, const char *desc, Oid *foid)
2146 query = createPQExpBuffer();
2147 printfPQExpBuffer(query, "SELECT ");
2148 appendStringLiteralConn(query, desc, conn);
2149 appendPQExpBuffer(query, "::pg_catalog.%s::pg_catalog.oid",
2150 strchr(desc, '(') ? "regprocedure" : "regproc");
2152 res = PQexec(conn, query->data);
2153 if (PQresultStatus(res) == PGRES_TUPLES_OK && PQntuples(res) == 1)
2154 *foid = atooid(PQgetvalue(res, 0, 0));
2157 minimal_error_message(res);
2162 destroyPQExpBuffer(query);
2168 * Fetches the "CREATE OR REPLACE FUNCTION ..." command that describes the
2169 * function with the given OID. If successful, the result is stored in buf.
2172 get_create_function_cmd(PGconn *conn, Oid oid, PQExpBuffer buf)
2178 query = createPQExpBuffer();
2179 printfPQExpBuffer(query, "SELECT pg_catalog.pg_get_functiondef(%u)", oid);
2181 res = PQexec(conn, query->data);
2182 if (PQresultStatus(res) == PGRES_TUPLES_OK && PQntuples(res) == 1)
2184 resetPQExpBuffer(buf);
2185 appendPQExpBufferStr(buf, PQgetvalue(res, 0, 0));
2189 minimal_error_message(res);
2194 destroyPQExpBuffer(query);
2200 * Report just the primary error; this is to avoid cluttering the output
2201 * with, for instance, a redisplay of the internally generated query
2204 minimal_error_message(PGresult *res)
2209 msg = createPQExpBuffer();
2211 fld = PQresultErrorField(res, PG_DIAG_SEVERITY);
2213 printfPQExpBuffer(msg, "%s: ", fld);
2215 printfPQExpBuffer(msg, "ERROR: ");
2216 fld = PQresultErrorField(res, PG_DIAG_MESSAGE_PRIMARY);
2218 appendPQExpBufferStr(msg, fld);
2220 appendPQExpBufferStr(msg, "(not available)");
2221 appendPQExpBufferStr(msg, "\n");
2223 psql_error("%s", msg->data);
2225 destroyPQExpBuffer(msg);