2 * psql - the PostgreSQL interactive terminal
4 * Copyright (c) 2000-2008, PostgreSQL Global Development Group
6 * $PostgreSQL: pgsql/src/bin/psql/command.c,v 1.199 2008/12/19 16:25:18 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')
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;
343 success = describeTableDetails(pattern, show_verbose);
345 /* standard listing of interesting things */
346 success = listTables("tvs", NULL, show_verbose);
349 success = describeAggregates(pattern, show_verbose);
352 success = describeTablespaces(pattern, show_verbose);
355 success = listConversions(pattern);
358 success = listCasts(pattern);
361 success = objectDescription(pattern);
364 success = listDomains(pattern);
367 success = describeFunctions(pattern, show_verbose);
370 /* no longer distinct from \du */
371 success = describeRoles(pattern, show_verbose);
374 success = do_lo_list();
377 success = listSchemas(pattern, show_verbose);
380 success = describeOperators(pattern);
383 success = permissionsList(pattern);
386 success = describeTypes(pattern, show_verbose);
393 success = listTables(&cmd[1], pattern, show_verbose);
396 success = describeRoles(pattern, show_verbose);
398 case 'F': /* text search subsystem */
403 success = listTSConfigs(pattern, show_verbose);
406 success = listTSParsers(pattern, show_verbose);
409 success = listTSDictionaries(pattern, show_verbose);
412 success = listTSTemplates(pattern, show_verbose);
415 status = PSQL_CMD_UNKNOWN;
419 case 'e': /* SQL/MED subsystem */
423 success = listForeignServers(pattern, show_verbose);
426 success = listUserMappings(pattern, show_verbose);
429 success = listForeignDataWrappers(pattern, show_verbose);
432 status = PSQL_CMD_UNKNOWN;
437 status = PSQL_CMD_UNKNOWN;
446 * \e or \edit -- edit the current query buffer (or a file and make it the
449 else if (strcmp(cmd, "e") == 0 || strcmp(cmd, "edit") == 0)
453 psql_error("no query buffer\n");
454 status = PSQL_CMD_ERROR;
460 fname = psql_scan_slash_option(scan_state,
461 OT_NORMAL, NULL, true);
462 expand_tilde(&fname);
464 canonicalize_path(fname);
465 if (do_edit(fname, query_buf, NULL))
466 status = PSQL_CMD_NEWEDIT;
468 status = PSQL_CMD_ERROR;
474 * \ef -- edit the named function, or present a blank CREATE FUNCTION
475 * template if no argument is given
477 else if (strcmp(cmd, "ef") == 0)
481 psql_error("no query buffer\n");
482 status = PSQL_CMD_ERROR;
487 Oid foid = InvalidOid;
489 func = psql_scan_slash_option(scan_state,
490 OT_WHOLE_LINE, NULL, true);
493 /* set up an empty command to fill in */
494 printfPQExpBuffer(query_buf,
495 "CREATE FUNCTION ( )\n"
498 " -- common options: IMMUTABLE STABLE STRICT SECURITY DEFINER\n"
502 else if (!lookup_function_oid(pset.db, func, &foid))
504 /* error already reported */
505 status = PSQL_CMD_ERROR;
507 else if (!get_create_function_cmd(pset.db, foid, query_buf))
509 /* error already reported */
510 status = PSQL_CMD_ERROR;
516 if (status != PSQL_CMD_ERROR)
520 if (!do_edit(0, query_buf, &edited))
521 status = PSQL_CMD_ERROR;
523 puts(_("No changes."));
525 status = PSQL_CMD_NEWEDIT;
529 /* \echo and \qecho */
530 else if (strcmp(cmd, "echo") == 0 || strcmp(cmd, "qecho") == 0)
534 bool no_newline = false;
538 if (strcmp(cmd, "qecho") == 0)
539 fout = pset.queryFout;
543 while ((value = psql_scan_slash_option(scan_state,
544 OT_NORMAL, "ed, false)))
546 if (!quoted && strcmp(value, "-n") == 0)
562 /* \encoding -- set/show client side encoding */
563 else if (strcmp(cmd, "encoding") == 0)
565 char *encoding = psql_scan_slash_option(scan_state,
566 OT_NORMAL, NULL, false);
571 puts(pg_encoding_to_char(pset.encoding));
576 if (PQsetClientEncoding(pset.db, encoding) == -1)
577 psql_error("%s: invalid encoding name or conversion procedure not found\n", encoding);
580 /* save encoding info into psql internal data */
581 pset.encoding = PQclientEncoding(pset.db);
582 pset.popt.topt.encoding = pset.encoding;
583 SetVariable(pset.vars, "ENCODING",
584 pg_encoding_to_char(pset.encoding));
590 /* \f -- change field separator */
591 else if (strcmp(cmd, "f") == 0)
593 char *fname = psql_scan_slash_option(scan_state,
594 OT_NORMAL, NULL, false);
596 success = do_pset("fieldsep", fname, &pset.popt, pset.quiet);
600 /* \g means send query */
601 else if (strcmp(cmd, "g") == 0)
603 char *fname = psql_scan_slash_option(scan_state,
604 OT_FILEPIPE, NULL, false);
610 expand_tilde(&fname);
611 pset.gfname = pg_strdup(fname);
614 status = PSQL_CMD_SEND;
618 else if (strcmp(cmd, "h") == 0 || strcmp(cmd, "help") == 0)
620 char *opt = psql_scan_slash_option(scan_state,
621 OT_WHOLE_LINE, NULL, false);
623 helpSQL(opt, pset.popt.topt.pager);
628 else if (strcmp(cmd, "H") == 0 || strcmp(cmd, "html") == 0)
630 if (pset.popt.topt.format != PRINT_HTML)
631 success = do_pset("format", "html", &pset.popt, pset.quiet);
633 success = do_pset("format", "aligned", &pset.popt, pset.quiet);
637 /* \i is include file */
638 else if (strcmp(cmd, "i") == 0 || strcmp(cmd, "include") == 0)
640 char *fname = psql_scan_slash_option(scan_state,
641 OT_NORMAL, NULL, true);
645 psql_error("\\%s: missing required argument\n", cmd);
650 expand_tilde(&fname);
651 success = (process_file(fname, false) == EXIT_SUCCESS);
656 /* \l is list databases */
657 else if (strcmp(cmd, "l") == 0 || strcmp(cmd, "list") == 0)
658 success = listAllDbs(false);
659 else if (strcmp(cmd, "l+") == 0 || strcmp(cmd, "list+") == 0)
660 success = listAllDbs(true);
663 * large object things
665 else if (strncmp(cmd, "lo_", 3) == 0)
670 opt1 = psql_scan_slash_option(scan_state,
671 OT_NORMAL, NULL, true);
672 opt2 = psql_scan_slash_option(scan_state,
673 OT_NORMAL, NULL, true);
675 if (strcmp(cmd + 3, "export") == 0)
679 psql_error("\\%s: missing required argument\n", cmd);
685 success = do_lo_export(opt1, opt2);
689 else if (strcmp(cmd + 3, "import") == 0)
693 psql_error("\\%s: missing required argument\n", cmd);
699 success = do_lo_import(opt1, opt2);
703 else if (strcmp(cmd + 3, "list") == 0)
704 success = do_lo_list();
706 else if (strcmp(cmd + 3, "unlink") == 0)
710 psql_error("\\%s: missing required argument\n", cmd);
714 success = do_lo_unlink(opt1);
718 status = PSQL_CMD_UNKNOWN;
725 /* \o -- set query output */
726 else if (strcmp(cmd, "o") == 0 || strcmp(cmd, "out") == 0)
728 char *fname = psql_scan_slash_option(scan_state,
729 OT_FILEPIPE, NULL, true);
731 expand_tilde(&fname);
732 success = setQFout(fname);
736 /* \p prints the current query buffer */
737 else if (strcmp(cmd, "p") == 0 || strcmp(cmd, "print") == 0)
739 if (query_buf && query_buf->len > 0)
740 puts(query_buf->data);
741 else if (!pset.quiet)
742 puts(_("Query buffer is empty."));
746 /* \password -- set user password */
747 else if (strcmp(cmd, "password") == 0)
752 pw1 = simple_prompt("Enter new password: ", 100, false);
753 pw2 = simple_prompt("Enter it again: ", 100, false);
755 if (strcmp(pw1, pw2) != 0)
757 fprintf(stderr, _("Passwords didn't match.\n"));
762 char *opt0 = psql_scan_slash_option(scan_state, OT_SQLID, NULL, true);
764 char *encrypted_password;
769 user = PQuser(pset.db);
771 encrypted_password = PQencryptPassword(pw1, user);
773 if (!encrypted_password)
775 fprintf(stderr, _("Password encryption failed.\n"));
783 initPQExpBuffer(&buf);
784 printfPQExpBuffer(&buf, "ALTER USER %s PASSWORD ",
786 appendStringLiteralConn(&buf, encrypted_password, pset.db);
787 res = PSQLexec(buf.data, false);
788 termPQExpBuffer(&buf);
793 PQfreemem(encrypted_password);
801 /* \prompt -- prompt and set variable */
802 else if (strcmp(cmd, "prompt") == 0)
809 arg1 = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false);
810 arg2 = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false);
814 psql_error("\\%s: missing required argument\n", cmd);
830 result = simple_prompt(prompt_text, 4096, true);
835 fputs(prompt_text, stdout);
838 result = gets_fromFile(stdin);
841 if (!SetVariable(pset.vars, opt, result))
843 psql_error("\\%s: error\n", cmd);
854 /* \pset -- set printing parameters */
855 else if (strcmp(cmd, "pset") == 0)
857 char *opt0 = psql_scan_slash_option(scan_state,
858 OT_NORMAL, NULL, false);
859 char *opt1 = psql_scan_slash_option(scan_state,
860 OT_NORMAL, NULL, false);
864 psql_error("\\%s: missing required argument\n", cmd);
868 success = do_pset(opt0, opt1, &pset.popt, pset.quiet);
875 else if (strcmp(cmd, "q") == 0 || strcmp(cmd, "quit") == 0)
876 status = PSQL_CMD_TERMINATE;
878 /* reset(clear) the buffer */
879 else if (strcmp(cmd, "r") == 0 || strcmp(cmd, "reset") == 0)
881 resetPQExpBuffer(query_buf);
882 psql_scan_reset(scan_state);
884 puts(_("Query buffer reset (cleared)."));
887 /* \s save history in a file or show it on the screen */
888 else if (strcmp(cmd, "s") == 0)
890 char *fname = psql_scan_slash_option(scan_state,
891 OT_NORMAL, NULL, true);
893 expand_tilde(&fname);
894 /* This scrolls off the screen when using /dev/tty */
895 success = saveHistory(fname ? fname : DEVTTY, false);
896 if (success && !pset.quiet && fname)
897 printf(gettext("Wrote history to file \"%s/%s\".\n"),
898 pset.dirname ? pset.dirname : ".", fname);
904 /* \set -- generalized set variable/option command */
905 else if (strcmp(cmd, "set") == 0)
907 char *opt0 = psql_scan_slash_option(scan_state,
908 OT_NORMAL, NULL, false);
912 /* list all variables */
913 PrintVariables(pset.vars);
919 * Set variable to the concatenation of the arguments.
924 opt = psql_scan_slash_option(scan_state,
925 OT_NORMAL, NULL, false);
926 newval = pg_strdup(opt ? opt : "");
929 while ((opt = psql_scan_slash_option(scan_state,
930 OT_NORMAL, NULL, false)))
932 newval = realloc(newval, strlen(newval) + strlen(opt) + 1);
935 psql_error("out of memory\n");
942 if (!SetVariable(pset.vars, opt0, newval))
944 psql_error("\\%s: error\n", cmd);
952 /* \t -- turn off headers and row count */
953 else if (strcmp(cmd, "t") == 0)
955 char *opt = psql_scan_slash_option(scan_state,
956 OT_NORMAL, NULL, true);
958 success = do_pset("tuples_only", opt, &pset.popt, pset.quiet);
963 /* \T -- define html <table ...> attributes */
964 else if (strcmp(cmd, "T") == 0)
966 char *value = psql_scan_slash_option(scan_state,
967 OT_NORMAL, NULL, false);
969 success = do_pset("tableattr", value, &pset.popt, pset.quiet);
973 /* \timing -- toggle timing of queries */
974 else if (strcmp(cmd, "timing") == 0)
976 char *opt = psql_scan_slash_option(scan_state,
977 OT_NORMAL, NULL, false);
979 pset.timing = ParseVariableBool(opt);
981 pset.timing = !pset.timing;
985 puts(_("Timing is on."));
987 puts(_("Timing is off."));
993 else if (strcmp(cmd, "unset") == 0)
995 char *opt = psql_scan_slash_option(scan_state,
996 OT_NORMAL, NULL, false);
1000 psql_error("\\%s: missing required argument\n", cmd);
1003 else if (!SetVariable(pset.vars, opt, NULL))
1005 psql_error("\\%s: error\n", cmd);
1011 /* \w -- write query buffer to file */
1012 else if (strcmp(cmd, "w") == 0 || strcmp(cmd, "write") == 0)
1015 bool is_pipe = false;
1020 psql_error("no query buffer\n");
1021 status = PSQL_CMD_ERROR;
1025 fname = psql_scan_slash_option(scan_state,
1026 OT_FILEPIPE, NULL, true);
1027 expand_tilde(&fname);
1031 psql_error("\\%s: missing required argument\n", cmd);
1036 if (fname[0] == '|')
1039 fd = popen(&fname[1], "w");
1043 canonicalize_path(fname);
1044 fd = fopen(fname, "w");
1048 psql_error("%s: %s\n", fname, strerror(errno));
1058 if (query_buf && query_buf->len > 0)
1059 fprintf(fd, "%s\n", query_buf->data);
1062 result = pclose(fd);
1064 result = fclose(fd);
1068 psql_error("%s: %s\n", fname, strerror(errno));
1076 /* \x -- toggle expanded table representation */
1077 else if (strcmp(cmd, "x") == 0)
1079 char *opt = psql_scan_slash_option(scan_state,
1080 OT_NORMAL, NULL, true);
1082 success = do_pset("expanded", opt, &pset.popt, pset.quiet);
1086 /* \z -- list table rights (equivalent to \dp) */
1087 else if (strcmp(cmd, "z") == 0)
1089 char *pattern = psql_scan_slash_option(scan_state,
1090 OT_NORMAL, NULL, true);
1092 success = permissionsList(pattern);
1097 /* \! -- shell escape */
1098 else if (strcmp(cmd, "!") == 0)
1100 char *opt = psql_scan_slash_option(scan_state,
1101 OT_WHOLE_LINE, NULL, false);
1103 success = do_shell(opt);
1107 /* \? -- slash command help */
1108 else if (strcmp(cmd, "?") == 0)
1109 slashUsage(pset.popt.topt.pager);
1114 * These commands don't do anything. I just use them to test the parser.
1116 else if (strcmp(cmd, "void") == 0 || strcmp(cmd, "#") == 0)
1121 while ((value = psql_scan_slash_option(scan_state,
1122 OT_NORMAL, NULL, true)))
1124 fprintf(stderr, "+ opt(%d) = |%s|\n", i++, value);
1131 status = PSQL_CMD_UNKNOWN;
1134 status = PSQL_CMD_ERROR;
1140 * Ask the user for a password; 'username' is the username the
1141 * password is for, if one has been explicitly specified. Returns a
1145 prompt_for_password(const char *username)
1149 if (username == NULL)
1150 result = simple_prompt("Password: ", 100, false);
1155 prompt_text = malloc(strlen(username) + 100);
1156 snprintf(prompt_text, strlen(username) + 100,
1157 _("Password for user %s: "), username);
1158 result = simple_prompt(prompt_text, 100, false);
1166 param_is_newly_set(const char *old_val, const char *new_val)
1168 if (new_val == NULL)
1171 if (old_val == NULL || strcmp(old_val, new_val) != 0)
1178 * do_connect -- handler for \connect
1180 * Connects to a database with given parameters. If there exists an
1181 * established connection, NULL values will be replaced with the ones
1182 * in the current connection. Otherwise NULL will be passed for that
1183 * parameter to PQsetdbLogin(), so the libpq defaults will be used.
1185 * In interactive mode, if connection fails with the given parameters,
1186 * the old connection will be kept.
1189 do_connect(char *dbname, char *user, char *host, char *port)
1191 PGconn *o_conn = pset.db,
1193 char *password = NULL;
1196 dbname = PQdb(o_conn);
1198 user = PQuser(o_conn);
1200 host = PQhost(o_conn);
1202 port = PQport(o_conn);
1205 * If the user asked to be prompted for a password, ask for one now. If
1206 * not, use the password from the old connection, provided the username
1207 * has not changed. Otherwise, try to connect without a password first,
1208 * and then ask for a password if needed.
1210 * XXX: this behavior leads to spurious connection attempts recorded in
1211 * the postmaster's log. But libpq offers no API that would let us obtain
1212 * a password and then continue with the first connection attempt.
1214 if (pset.getPassword)
1216 password = prompt_for_password(user);
1218 else if (o_conn && user && strcmp(PQuser(o_conn), user) == 0)
1220 password = strdup(PQpass(o_conn));
1225 n_conn = PQsetdbLogin(host, port, NULL, NULL,
1226 dbname, user, password);
1228 /* We can immediately discard the password -- no longer needed */
1232 if (PQstatus(n_conn) == CONNECTION_OK)
1236 * Connection attempt failed; either retry the connection attempt with
1237 * a new password, or give up.
1239 if (!password && PQconnectionNeedsPassword(n_conn))
1242 password = prompt_for_password(user);
1247 * Failed to connect to the database. In interactive mode, keep the
1248 * previous connection to the DB; in scripting mode, close our
1249 * previous connection as well.
1251 if (pset.cur_cmd_interactive)
1253 psql_error("%s", PQerrorMessage(n_conn));
1255 /* pset.db is left unmodified */
1257 fputs(_("Previous connection kept\n"), stderr);
1261 psql_error("\\connect: %s", PQerrorMessage(n_conn));
1274 * Replace the old connection with the new one, and update
1275 * connection-dependent variables.
1277 PQsetNoticeProcessor(n_conn, NoticeProcessor, NULL);
1280 connection_warnings(); /* Must be after SyncVariables */
1282 /* Tell the user about the new connection */
1285 printf(_("You are now connected to database \"%s\""), PQdb(pset.db));
1287 if (param_is_newly_set(PQhost(o_conn), PQhost(pset.db)))
1288 printf(_(" on host \"%s\""), PQhost(pset.db));
1290 if (param_is_newly_set(PQport(o_conn), PQport(pset.db)))
1291 printf(_(" at port \"%s\""), PQport(pset.db));
1293 if (param_is_newly_set(PQuser(o_conn), PQuser(pset.db)))
1294 printf(_(" as user \"%s\""), PQuser(pset.db));
1306 connection_warnings(void)
1308 if (!pset.quiet && !pset.notty)
1310 int client_ver = parse_version(PG_VERSION);
1312 if (pset.sversion != client_ver)
1314 const char *server_version;
1315 char server_ver_str[16];
1317 /* Try to get full text form, might include "devel" etc */
1318 server_version = PQparameterStatus(pset.db, "server_version");
1319 if (!server_version)
1321 snprintf(server_ver_str, sizeof(server_ver_str),
1323 pset.sversion / 10000,
1324 (pset.sversion / 100) % 100,
1325 pset.sversion % 100);
1326 server_version = server_ver_str;
1329 printf(_("%s (%s, server %s)\n"),
1330 pset.progname, PG_VERSION, server_version);
1333 printf("%s (%s)\n", pset.progname, PG_VERSION);
1335 if (pset.sversion / 100 != client_ver / 100)
1336 printf(_("WARNING: %s version %d.%d, server version %d.%d.\n"
1337 " Some psql features might not work.\n"),
1338 pset.progname, client_ver / 10000, (client_ver / 100) % 100,
1339 pset.sversion / 10000, (pset.sversion / 100) % 100);
1342 checkWin32Codepage();
1352 * Prints information about the current SSL connection, if SSL is in use
1361 ssl = PQgetssl(pset.db);
1363 return; /* no SSL */
1365 SSL_get_cipher_bits(ssl, &sslbits);
1366 printf(_("SSL connection (cipher: %s, bits: %i)\n"),
1367 SSL_get_cipher(ssl), sslbits);
1370 * If psql is compiled without SSL but is using a libpq with SSL,
1371 * we cannot figure out the specifics about the connection. But
1372 * we know it's SSL secured.
1374 if (PQgetssl(pset.db))
1375 printf(_("SSL connection (unknown cipher)\n"));
1381 * checkWin32Codepage
1383 * Prints a warning when win32 console codepage differs from Windows codepage
1387 checkWin32Codepage(void)
1393 concp = GetConsoleCP();
1396 printf(_("WARNING: Console code page (%u) differs from Windows code page (%u)\n"
1397 " 8-bit characters might not work correctly. See psql reference\n"
1398 " page \"Notes for Windows users\" for details.\n"),
1408 * Make psql's internal variables agree with connection state upon
1409 * establishing a new connection.
1414 /* get stuff from connection */
1415 pset.encoding = PQclientEncoding(pset.db);
1416 pset.popt.topt.encoding = pset.encoding;
1417 pset.sversion = PQserverVersion(pset.db);
1419 SetVariable(pset.vars, "DBNAME", PQdb(pset.db));
1420 SetVariable(pset.vars, "USER", PQuser(pset.db));
1421 SetVariable(pset.vars, "HOST", PQhost(pset.db));
1422 SetVariable(pset.vars, "PORT", PQport(pset.db));
1423 SetVariable(pset.vars, "ENCODING", pg_encoding_to_char(pset.encoding));
1425 /* send stuff to it, too */
1426 PQsetErrorVerbosity(pset.db, pset.verbosity);
1432 * Clear variables that should be not be set when there is no connection.
1435 UnsyncVariables(void)
1437 SetVariable(pset.vars, "DBNAME", NULL);
1438 SetVariable(pset.vars, "USER", NULL);
1439 SetVariable(pset.vars, "HOST", NULL);
1440 SetVariable(pset.vars, "PORT", NULL);
1441 SetVariable(pset.vars, "ENCODING", NULL);
1446 * do_edit -- handler for \e
1448 * If you do not specify a filename, the current query buffer will be copied
1449 * into a temporary one.
1453 editFile(const char *fname)
1455 const char *editorName;
1461 /* Find an editor to use */
1462 editorName = getenv("PSQL_EDITOR");
1464 editorName = getenv("EDITOR");
1466 editorName = getenv("VISUAL");
1468 editorName = DEFAULT_EDITOR;
1471 * On Unix the EDITOR value should *not* be quoted, since it might include
1472 * switches, eg, EDITOR="pico -t"; it's up to the user to put quotes in it
1473 * if necessary. But this policy is not very workable on Windows, due to
1474 * severe brain damage in their command shell plus the fact that standard
1475 * program paths include spaces.
1477 sys = pg_malloc(strlen(editorName) + strlen(fname) + 10 + 1);
1479 sprintf(sys, "exec %s '%s'", editorName, fname);
1481 sprintf(sys, SYSTEMQUOTE "\"%s\" \"%s\"" SYSTEMQUOTE, editorName, fname);
1483 result = system(sys);
1485 psql_error("could not start editor \"%s\"\n", editorName);
1486 else if (result == 127)
1487 psql_error("could not start /bin/sh\n");
1496 do_edit(const char *filename_arg, PQExpBuffer query_buf, bool *edited)
1498 char fnametmp[MAXPGPATH];
1499 FILE *stream = NULL;
1508 fname = filename_arg;
1511 /* make a temp file to edit */
1513 const char *tmpdir = getenv("TMPDIR");
1518 char tmpdir[MAXPGPATH];
1521 ret = GetTempPath(MAXPGPATH, tmpdir);
1522 if (ret == 0 || ret > MAXPGPATH)
1524 psql_error("cannot locate temporary directory: %s",
1525 !ret ? strerror(errno) : "");
1530 * No canonicalize_path() here. EDIT.EXE run from CMD.EXE prepends the
1531 * current directory to the supplied path unless we use only
1532 * backslashes, so we do that.
1536 snprintf(fnametmp, sizeof(fnametmp), "%s%spsql.edit.%d", tmpdir,
1537 "/", (int) getpid());
1539 snprintf(fnametmp, sizeof(fnametmp), "%s%spsql.edit.%d", tmpdir,
1540 "" /* trailing separator already present */ , (int) getpid());
1543 fname = (const char *) fnametmp;
1545 fd = open(fname, O_WRONLY | O_CREAT | O_EXCL, 0600);
1547 stream = fdopen(fd, "w");
1549 if (fd == -1 || !stream)
1551 psql_error("could not open temporary file \"%s\": %s\n", fname, strerror(errno));
1556 unsigned int ql = query_buf->len;
1558 if (ql == 0 || query_buf->data[ql - 1] != '\n')
1560 appendPQExpBufferChar(query_buf, '\n');
1564 if (fwrite(query_buf->data, 1, ql, stream) != ql)
1566 psql_error("%s: %s\n", fname, strerror(errno));
1571 else if (fclose(stream) != 0)
1573 psql_error("%s: %s\n", fname, strerror(errno));
1580 if (!error && stat(fname, &before) != 0)
1582 psql_error("%s: %s\n", fname, strerror(errno));
1588 error = !editFile(fname);
1590 if (!error && stat(fname, &after) != 0)
1592 psql_error("%s: %s\n", fname, strerror(errno));
1596 if (!error && before.st_mtime != after.st_mtime)
1598 stream = fopen(fname, PG_BINARY_R);
1601 psql_error("%s: %s\n", fname, strerror(errno));
1606 /* read file back into query_buf */
1609 resetPQExpBuffer(query_buf);
1610 while (fgets(line, sizeof(line), stream) != NULL)
1611 appendPQExpBufferStr(query_buf, line);
1615 psql_error("%s: %s\n", fname, strerror(errno));
1627 /* remove temp file */
1630 if (remove(fname) == -1)
1632 psql_error("%s: %s\n", fname, strerror(errno));
1645 * Read commands from filename and then them to the main processing loop
1646 * Handler for \i, but can be used for other things as well. Returns
1647 * MainLoop() error code.
1650 process_file(char *filename, bool single_txn)
1658 return EXIT_FAILURE;
1660 canonicalize_path(filename);
1661 fd = fopen(filename, PG_BINARY_R);
1665 psql_error("%s: %s\n", filename, strerror(errno));
1666 return EXIT_FAILURE;
1669 oldfilename = pset.inputfile;
1670 pset.inputfile = filename;
1673 res = PSQLexec("BEGIN", false);
1674 result = MainLoop(fd);
1676 res = PSQLexec("COMMIT", false);
1679 pset.inputfile = oldfilename;
1690 _align2string(enum printFormat in)
1697 case PRINT_UNALIGNED:
1712 case PRINT_TROFF_MS:
1721 do_pset(const char *param, const char *value, printQueryOpt *popt, bool quiet)
1728 vallen = strlen(value);
1731 if (strcmp(param, "format") == 0)
1735 else if (pg_strncasecmp("unaligned", value, vallen) == 0)
1736 popt->topt.format = PRINT_UNALIGNED;
1737 else if (pg_strncasecmp("aligned", value, vallen) == 0)
1738 popt->topt.format = PRINT_ALIGNED;
1739 else if (pg_strncasecmp("wrapped", value, vallen) == 0)
1740 popt->topt.format = PRINT_WRAPPED;
1741 else if (pg_strncasecmp("html", value, vallen) == 0)
1742 popt->topt.format = PRINT_HTML;
1743 else if (pg_strncasecmp("latex", value, vallen) == 0)
1744 popt->topt.format = PRINT_LATEX;
1745 else if (pg_strncasecmp("troff-ms", value, vallen) == 0)
1746 popt->topt.format = PRINT_TROFF_MS;
1749 psql_error("\\pset: allowed formats are unaligned, aligned, wrapped, html, latex, troff-ms\n");
1754 printf(_("Output format is %s.\n"), _align2string(popt->topt.format));
1757 /* set border style/width */
1758 else if (strcmp(param, "border") == 0)
1761 popt->topt.border = atoi(value);
1764 printf(_("Border style is %d.\n"), popt->topt.border);
1767 /* set expanded/vertical mode */
1768 else if (strcmp(param, "x") == 0 || strcmp(param, "expanded") == 0 || strcmp(param, "vertical") == 0)
1771 popt->topt.expanded = ParseVariableBool(value);
1773 popt->topt.expanded = !popt->topt.expanded;
1775 printf(popt->topt.expanded
1776 ? _("Expanded display is on.\n")
1777 : _("Expanded display is off.\n"));
1780 /* locale-aware numeric output */
1781 else if (strcmp(param, "numericlocale") == 0)
1784 popt->topt.numericLocale = ParseVariableBool(value);
1786 popt->topt.numericLocale = !popt->topt.numericLocale;
1789 if (popt->topt.numericLocale)
1790 puts(_("Showing locale-adjusted numeric output."));
1792 puts(_("Locale-adjusted numeric output is off."));
1797 else if (strcmp(param, "null") == 0)
1801 free(popt->nullPrint);
1802 popt->nullPrint = pg_strdup(value);
1805 printf(_("Null display is \"%s\".\n"), popt->nullPrint ? popt->nullPrint : "");
1808 /* field separator for unaligned text */
1809 else if (strcmp(param, "fieldsep") == 0)
1813 free(popt->topt.fieldSep);
1814 popt->topt.fieldSep = pg_strdup(value);
1817 printf(_("Field separator is \"%s\".\n"), popt->topt.fieldSep);
1820 /* record separator for unaligned text */
1821 else if (strcmp(param, "recordsep") == 0)
1825 free(popt->topt.recordSep);
1826 popt->topt.recordSep = pg_strdup(value);
1830 if (strcmp(popt->topt.recordSep, "\n") == 0)
1831 printf(_("Record separator is <newline>."));
1833 printf(_("Record separator is \"%s\".\n"), popt->topt.recordSep);
1837 /* toggle between full and tuples-only format */
1838 else if (strcmp(param, "t") == 0 || strcmp(param, "tuples_only") == 0)
1841 popt->topt.tuples_only = ParseVariableBool(value);
1843 popt->topt.tuples_only = !popt->topt.tuples_only;
1846 if (popt->topt.tuples_only)
1847 puts(_("Showing only tuples."));
1849 puts(_("Tuples only is off."));
1853 /* set title override */
1854 else if (strcmp(param, "title") == 0)
1860 popt->title = pg_strdup(value);
1865 printf(_("Title is \"%s\".\n"), popt->title);
1867 printf(_("Title is unset.\n"));
1871 /* set HTML table tag options */
1872 else if (strcmp(param, "T") == 0 || strcmp(param, "tableattr") == 0)
1874 free(popt->topt.tableAttr);
1876 popt->topt.tableAttr = NULL;
1878 popt->topt.tableAttr = pg_strdup(value);
1882 if (popt->topt.tableAttr)
1883 printf(_("Table attribute is \"%s\".\n"), popt->topt.tableAttr);
1885 printf(_("Table attributes unset.\n"));
1889 /* toggle use of pager */
1890 else if (strcmp(param, "pager") == 0)
1892 if (value && pg_strcasecmp(value, "always") == 0)
1893 popt->topt.pager = 2;
1895 if (ParseVariableBool(value))
1896 popt->topt.pager = 1;
1898 popt->topt.pager = 0;
1899 else if (popt->topt.pager == 1)
1900 popt->topt.pager = 0;
1902 popt->topt.pager = 1;
1905 if (popt->topt.pager == 1)
1906 puts(_("Pager is used for long output."));
1907 else if (popt->topt.pager == 2)
1908 puts(_("Pager is always used."));
1910 puts(_("Pager usage is off."));
1914 /* disable "(x rows)" footer */
1915 else if (strcmp(param, "footer") == 0)
1918 popt->default_footer = ParseVariableBool(value);
1920 popt->default_footer = !popt->default_footer;
1923 if (popt->default_footer)
1924 puts(_("Default footer is on."));
1926 puts(_("Default footer is off."));
1930 /* set border style/width */
1931 else if (strcmp(param, "columns") == 0)
1934 popt->topt.columns = atoi(value);
1937 printf(_("Target width for \"wrapped\" format is %d.\n"), popt->topt.columns);
1942 psql_error("\\pset: unknown option: %s\n", param);
1952 #define DEFAULT_SHELL "/bin/sh"
1955 * CMD.EXE is in different places in different Win32 releases so we
1956 * have to rely on the path to find it.
1958 #define DEFAULT_SHELL "cmd.exe"
1962 do_shell(const char *command)
1969 const char *shellName;
1971 shellName = getenv("SHELL");
1973 if (shellName == NULL)
1974 shellName = getenv("COMSPEC");
1976 if (shellName == NULL)
1977 shellName = DEFAULT_SHELL;
1979 sys = pg_malloc(strlen(shellName) + 16);
1982 /* See EDITOR handling comment for an explaination */
1983 "exec %s", shellName);
1985 /* See EDITOR handling comment for an explaination */
1986 sprintf(sys, SYSTEMQUOTE "\"%s\"" SYSTEMQUOTE, shellName);
1988 result = system(sys);
1992 result = system(command);
1994 if (result == 127 || result == -1)
1996 psql_error("\\!: failed\n");
2003 * This function takes a function description, e.g. "x" or "x(int)", and
2004 * issues a query on the given connection to retrieve the function's OID
2005 * using a cast to regproc or regprocedure (as appropriate). The result,
2006 * if there is one, is returned at *foid. Note that we'll fail if the
2007 * function doesn't exist OR if there are multiple matching candidates
2008 * OR if there's something syntactically wrong with the function description;
2009 * unfortunately it can be hard to tell the difference.
2012 lookup_function_oid(PGconn *conn, const char *desc, Oid *foid)
2018 query = createPQExpBuffer();
2019 printfPQExpBuffer(query, "SELECT ");
2020 appendStringLiteralConn(query, desc, conn);
2021 appendPQExpBuffer(query, "::pg_catalog.%s::pg_catalog.oid",
2022 strchr(desc, '(') ? "regprocedure" : "regproc");
2024 res = PQexec(conn, query->data);
2025 if (PQresultStatus(res) == PGRES_TUPLES_OK && PQntuples(res) == 1)
2026 *foid = atooid(PQgetvalue(res, 0, 0));
2029 minimal_error_message(res);
2034 destroyPQExpBuffer(query);
2040 * Fetches the "CREATE OR REPLACE FUNCTION ..." command that describes the
2041 * function with the given OID. If successful, the result is stored in buf.
2044 get_create_function_cmd(PGconn *conn, Oid oid, PQExpBuffer buf)
2050 query = createPQExpBuffer();
2051 printfPQExpBuffer(query, "SELECT pg_catalog.pg_get_functiondef(%u)", oid);
2053 res = PQexec(conn, query->data);
2054 if (PQresultStatus(res) == PGRES_TUPLES_OK && PQntuples(res) == 1)
2056 resetPQExpBuffer(buf);
2057 appendPQExpBufferStr(buf, PQgetvalue(res, 0, 0));
2061 minimal_error_message(res);
2066 destroyPQExpBuffer(query);
2072 * Report just the primary error; this is to avoid cluttering the output
2073 * with, for instance, a redisplay of the internally generated query
2076 minimal_error_message(PGresult *res)
2081 msg = createPQExpBuffer();
2083 fld = PQresultErrorField(res, PG_DIAG_SEVERITY);
2085 printfPQExpBuffer(msg, "%s: ", fld);
2087 printfPQExpBuffer(msg, "ERROR: ");
2088 fld = PQresultErrorField(res, PG_DIAG_MESSAGE_PRIMARY);
2090 appendPQExpBufferStr(msg, fld);
2092 appendPQExpBufferStr(msg, "(not available)");
2093 appendPQExpBufferStr(msg, "\n");
2095 psql_error("%s", msg->data);
2097 destroyPQExpBuffer(msg);