2 * psql - the PostgreSQL interactive terminal
4 * Copyright (c) 2000-2007, PostgreSQL Global Development Group
6 * $PostgreSQL: pgsql/src/bin/psql/command.c,v 1.184 2007/12/09 19:01:40 tgl 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() */
34 #include "pqexpbuffer.h"
35 #include "dumputils.h"
42 #include "large_obj.h"
47 #include "variables.h"
50 /* functions for use in this file */
51 static backslashResult exec_command(const char *cmd,
52 PsqlScanState scan_state,
53 PQExpBuffer query_buf);
54 static bool do_edit(const char *filename_arg, PQExpBuffer query_buf);
55 static bool do_connect(char *dbname, char *user, char *host, char *port);
56 static bool do_shell(const char *command);
62 * Handles all the different commands that start with '\'.
63 * Ordinarily called by MainLoop().
65 * scan_state is a lexer working state that is set to continue scanning
66 * just after the '\'. The lexer is advanced past the command and all
67 * arguments on return.
69 * 'query_buf' contains the query-so-far, which may be modified by
70 * execution of the backslash command (for example, \r clears it).
71 * query_buf can be NULL if there is no query so far.
73 * Returns a status code indicating what action is desired, see command.h.
78 HandleSlashCmds(PsqlScanState scan_state,
79 PQExpBuffer query_buf)
81 backslashResult status = PSQL_CMD_SKIP_LINE;
85 psql_assert(scan_state);
87 /* Parse off the command name */
88 cmd = psql_scan_slash_command(scan_state);
90 /* And try to execute it */
91 status = exec_command(cmd, scan_state, query_buf);
93 if (status == PSQL_CMD_UNKNOWN && strlen(cmd) > 1)
96 * If the command was not recognized, try to parse it as a one-letter
97 * command with immediately following argument (a still-supported, but
98 * no longer encouraged, syntax).
102 /* don't change cmd until we know it's okay */
106 psql_scan_slash_pushback(scan_state, cmd + 1);
108 status = exec_command(new_cmd, scan_state, query_buf);
110 if (status != PSQL_CMD_UNKNOWN)
112 /* adjust cmd for possible messages below */
117 if (status == PSQL_CMD_UNKNOWN)
119 if (pset.cur_cmd_interactive)
120 fprintf(stderr, _("Invalid command \\%s. Try \\? for help.\n"), cmd);
122 psql_error("invalid command \\%s\n", cmd);
123 status = PSQL_CMD_ERROR;
126 if (status != PSQL_CMD_ERROR)
128 /* eat any remaining arguments after a valid command */
129 /* note we suppress evaluation of backticks here */
130 while ((arg = psql_scan_slash_option(scan_state,
131 OT_VERBATIM, NULL, false)))
133 psql_error("\\%s: extra argument \"%s\" ignored\n", cmd, arg);
139 /* silently throw away rest of line after an erroneous command */
140 while ((arg = psql_scan_slash_option(scan_state,
141 OT_WHOLE_LINE, NULL, false)))
145 /* if there is a trailing \\, swallow it */
146 psql_scan_slash_command_end(scan_state);
150 /* some commands write to queryFout, so make sure output is sent */
151 fflush(pset.queryFout);
157 * Read and interpret an argument to the \connect slash command.
160 read_connect_arg(PsqlScanState scan_state)
166 * Ideally we should treat the arguments as SQL identifiers. But for
167 * backwards compatibility with 7.2 and older pg_dump files, we have to
168 * take unquoted arguments verbatim (don't downcase them). For now,
169 * double-quoted arguments may be stripped of double quotes (as if SQL
170 * identifiers). By 7.4 or so, pg_dump files can be expected to
171 * double-quote all mixed-case \connect arguments, and then we can get rid
174 result = psql_scan_slash_option(scan_state, OT_SQLIDHACK, "e, true);
182 if (*result == '\0' || strcmp(result, "-") == 0)
190 * Subroutine to actually try to execute a backslash command.
192 static backslashResult
193 exec_command(const char *cmd,
194 PsqlScanState scan_state,
195 PQExpBuffer query_buf)
197 bool success = true; /* indicate here if the command ran ok or
199 backslashResult status = PSQL_CMD_SKIP_LINE;
202 * \a -- toggle field alignment This makes little sense but we keep it
205 if (strcmp(cmd, "a") == 0)
207 if (pset.popt.topt.format != PRINT_ALIGNED)
208 success = do_pset("format", "aligned", &pset.popt, pset.quiet);
210 success = do_pset("format", "unaligned", &pset.popt, pset.quiet);
213 /* \C -- override table title (formerly change HTML caption) */
214 else if (strcmp(cmd, "C") == 0)
216 char *opt = psql_scan_slash_option(scan_state,
217 OT_NORMAL, NULL, true);
219 success = do_pset("title", opt, &pset.popt, pset.quiet);
224 * \c or \connect -- connect to database using the specified parameters.
226 * \c dbname user host port
228 * If any of these parameters are omitted or specified as '-', the current
229 * value of the parameter will be used instead. If the parameter has no
230 * current value, the default value for that parameter will be used. Some
233 * \c - - hst Connect to current database on current port of host
234 * "hst" as current user. \c - usr - prt Connect to current database on
235 * "prt" port of current host as user "usr". \c dbs Connect to
236 * "dbs" database on current port of current host as current user.
238 else if (strcmp(cmd, "c") == 0 || strcmp(cmd, "connect") == 0)
245 opt1 = read_connect_arg(scan_state);
246 opt2 = read_connect_arg(scan_state);
247 opt3 = read_connect_arg(scan_state);
248 opt4 = read_connect_arg(scan_state);
250 success = do_connect(opt1, opt2, opt3, opt4);
259 else if (strcmp(cmd, "cd") == 0)
261 char *opt = psql_scan_slash_option(scan_state,
262 OT_NORMAL, NULL, true);
272 pw = getpwuid(geteuid());
275 psql_error("could not get home directory: %s\n", strerror(errno));
282 * On Windows, 'cd' without arguments prints the current
283 * directory, so if someone wants to code this here instead...
289 if (chdir(dir) == -1)
291 psql_error("\\%s: could not change directory to \"%s\": %s\n",
292 cmd, dir, strerror(errno));
298 pset.dirname = pg_strdup(dir);
299 canonicalize_path(pset.dirname);
306 else if (pg_strcasecmp(cmd, "copy") == 0)
308 /* Default fetch-it-all-and-print mode */
309 TimevalStruct before,
311 double elapsed_msec = 0;
313 char *opt = psql_scan_slash_option(scan_state,
314 OT_WHOLE_LINE, NULL, false);
317 GETTIMEOFDAY(&before);
319 success = do_copy(opt);
321 if (pset.timing && success)
323 GETTIMEOFDAY(&after);
324 elapsed_msec = DIFF_MSEC(&after, &before);
325 printf(_("Time: %.3f ms\n"), elapsed_msec);
333 else if (strcmp(cmd, "copyright") == 0)
337 else if (cmd[0] == 'd')
342 /* We don't do SQLID reduction on the pattern yet */
343 pattern = psql_scan_slash_option(scan_state,
344 OT_NORMAL, NULL, true);
346 show_verbose = strchr(cmd, '+') ? true : false;
353 success = describeTableDetails(pattern, show_verbose);
355 /* standard listing of interesting things */
356 success = listTables("tvs", NULL, show_verbose);
359 success = describeAggregates(pattern, show_verbose);
362 success = describeTablespaces(pattern, show_verbose);
365 success = listConversions(pattern);
368 success = listCasts(pattern);
371 success = objectDescription(pattern);
374 success = listDomains(pattern);
377 success = describeFunctions(pattern, show_verbose);
380 /* no longer distinct from \du */
381 success = describeRoles(pattern, show_verbose);
384 success = do_lo_list();
387 success = listSchemas(pattern, show_verbose);
390 success = describeOperators(pattern);
393 success = permissionsList(pattern);
396 success = describeTypes(pattern, show_verbose);
403 success = listTables(&cmd[1], pattern, show_verbose);
406 success = describeRoles(pattern, show_verbose);
408 case 'F': /* text search subsystem */
413 success = listTSConfigs(pattern, show_verbose);
416 success = listTSParsers(pattern, show_verbose);
419 success = listTSDictionaries(pattern, show_verbose);
422 success = listTSTemplates(pattern, show_verbose);
425 status = PSQL_CMD_UNKNOWN;
431 status = PSQL_CMD_UNKNOWN;
440 * \e or \edit -- edit the current query buffer (or a file and make it the
443 else if (strcmp(cmd, "e") == 0 || strcmp(cmd, "edit") == 0)
449 psql_error("no query buffer\n");
450 status = PSQL_CMD_ERROR;
454 fname = psql_scan_slash_option(scan_state,
455 OT_NORMAL, NULL, true);
456 expand_tilde(&fname);
458 canonicalize_path(fname);
459 status = do_edit(fname, query_buf) ? PSQL_CMD_NEWEDIT : PSQL_CMD_ERROR;
464 /* \echo and \qecho */
465 else if (strcmp(cmd, "echo") == 0 || strcmp(cmd, "qecho") == 0)
469 bool no_newline = false;
473 if (strcmp(cmd, "qecho") == 0)
474 fout = pset.queryFout;
478 while ((value = psql_scan_slash_option(scan_state,
479 OT_NORMAL, "ed, false)))
481 if (!quoted && strcmp(value, "-n") == 0)
497 /* \encoding -- set/show client side encoding */
498 else if (strcmp(cmd, "encoding") == 0)
500 char *encoding = psql_scan_slash_option(scan_state,
501 OT_NORMAL, NULL, false);
506 puts(pg_encoding_to_char(pset.encoding));
511 if (PQsetClientEncoding(pset.db, encoding) == -1)
512 psql_error("%s: invalid encoding name or conversion procedure not found\n", encoding);
515 /* save encoding info into psql internal data */
516 pset.encoding = PQclientEncoding(pset.db);
517 pset.popt.topt.encoding = pset.encoding;
518 SetVariable(pset.vars, "ENCODING",
519 pg_encoding_to_char(pset.encoding));
525 /* \f -- change field separator */
526 else if (strcmp(cmd, "f") == 0)
528 char *fname = psql_scan_slash_option(scan_state,
529 OT_NORMAL, NULL, false);
531 success = do_pset("fieldsep", fname, &pset.popt, pset.quiet);
535 /* \g means send query */
536 else if (strcmp(cmd, "g") == 0)
538 char *fname = psql_scan_slash_option(scan_state,
539 OT_FILEPIPE, NULL, false);
545 expand_tilde(&fname);
546 pset.gfname = pg_strdup(fname);
549 status = PSQL_CMD_SEND;
553 else if (strcmp(cmd, "h") == 0 || strcmp(cmd, "help") == 0)
555 char *opt = psql_scan_slash_option(scan_state,
556 OT_WHOLE_LINE, NULL, false);
558 helpSQL(opt, pset.popt.topt.pager);
563 else if (strcmp(cmd, "H") == 0 || strcmp(cmd, "html") == 0)
565 if (pset.popt.topt.format != PRINT_HTML)
566 success = do_pset("format", "html", &pset.popt, pset.quiet);
568 success = do_pset("format", "aligned", &pset.popt, pset.quiet);
572 /* \i is include file */
573 else if (strcmp(cmd, "i") == 0 || strcmp(cmd, "include") == 0)
575 char *fname = psql_scan_slash_option(scan_state,
576 OT_NORMAL, NULL, true);
580 psql_error("\\%s: missing required argument\n", cmd);
585 expand_tilde(&fname);
586 success = (process_file(fname, false) == EXIT_SUCCESS);
591 /* \l is list databases */
592 else if (strcmp(cmd, "l") == 0 || strcmp(cmd, "list") == 0)
593 success = listAllDbs(false);
594 else if (strcmp(cmd, "l+") == 0 || strcmp(cmd, "list+") == 0)
595 success = listAllDbs(true);
598 * large object things
600 else if (strncmp(cmd, "lo_", 3) == 0)
605 opt1 = psql_scan_slash_option(scan_state,
606 OT_NORMAL, NULL, true);
607 opt2 = psql_scan_slash_option(scan_state,
608 OT_NORMAL, NULL, true);
610 if (strcmp(cmd + 3, "export") == 0)
614 psql_error("\\%s: missing required argument\n", cmd);
620 success = do_lo_export(opt1, opt2);
624 else if (strcmp(cmd + 3, "import") == 0)
628 psql_error("\\%s: missing required argument\n", cmd);
634 success = do_lo_import(opt1, opt2);
638 else if (strcmp(cmd + 3, "list") == 0)
639 success = do_lo_list();
641 else if (strcmp(cmd + 3, "unlink") == 0)
645 psql_error("\\%s: missing required argument\n", cmd);
649 success = do_lo_unlink(opt1);
653 status = PSQL_CMD_UNKNOWN;
660 /* \o -- set query output */
661 else if (strcmp(cmd, "o") == 0 || strcmp(cmd, "out") == 0)
663 char *fname = psql_scan_slash_option(scan_state,
664 OT_FILEPIPE, NULL, true);
666 expand_tilde(&fname);
667 success = setQFout(fname);
671 /* \p prints the current query buffer */
672 else if (strcmp(cmd, "p") == 0 || strcmp(cmd, "print") == 0)
674 if (query_buf && query_buf->len > 0)
675 puts(query_buf->data);
676 else if (!pset.quiet)
677 puts(_("Query buffer is empty."));
681 /* \password -- set user password */
682 else if (strcmp(cmd, "password") == 0)
687 pw1 = simple_prompt("Enter new password: ", 100, false);
688 pw2 = simple_prompt("Enter it again: ", 100, false);
690 if (strcmp(pw1, pw2) != 0)
692 fprintf(stderr, _("Passwords didn't match.\n"));
697 char *opt0 = psql_scan_slash_option(scan_state, OT_SQLID, NULL, true);
699 char *encrypted_password;
704 user = PQuser(pset.db);
706 encrypted_password = PQencryptPassword(pw1, user);
708 if (!encrypted_password)
710 fprintf(stderr, _("Password encryption failed.\n"));
718 initPQExpBuffer(&buf);
719 printfPQExpBuffer(&buf, "ALTER USER %s PASSWORD ",
721 appendStringLiteralConn(&buf, encrypted_password, pset.db);
722 res = PSQLexec(buf.data, false);
723 termPQExpBuffer(&buf);
728 PQfreemem(encrypted_password);
736 /* \prompt -- prompt and set variable */
737 else if (strcmp(cmd, "prompt") == 0)
744 arg1 = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false);
745 arg2 = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false);
749 psql_error("\\%s: missing required argument\n", cmd);
765 result = simple_prompt(prompt_text, 4096, true);
770 fputs(prompt_text, stdout);
773 result = gets_fromFile(stdin);
776 if (!SetVariable(pset.vars, opt, result))
778 psql_error("\\%s: error\n", cmd);
789 /* \pset -- set printing parameters */
790 else if (strcmp(cmd, "pset") == 0)
792 char *opt0 = psql_scan_slash_option(scan_state,
793 OT_NORMAL, NULL, false);
794 char *opt1 = psql_scan_slash_option(scan_state,
795 OT_NORMAL, NULL, false);
799 psql_error("\\%s: missing required argument\n", cmd);
803 success = do_pset(opt0, opt1, &pset.popt, pset.quiet);
810 else if (strcmp(cmd, "q") == 0 || strcmp(cmd, "quit") == 0)
811 status = PSQL_CMD_TERMINATE;
813 /* reset(clear) the buffer */
814 else if (strcmp(cmd, "r") == 0 || strcmp(cmd, "reset") == 0)
816 resetPQExpBuffer(query_buf);
817 psql_scan_reset(scan_state);
819 puts(_("Query buffer reset (cleared)."));
822 /* \s save history in a file or show it on the screen */
823 else if (strcmp(cmd, "s") == 0)
825 char *fname = psql_scan_slash_option(scan_state,
826 OT_NORMAL, NULL, true);
828 expand_tilde(&fname);
829 /* This scrolls off the screen when using /dev/tty */
830 success = saveHistory(fname ? fname : DEVTTY, false);
831 if (success && !pset.quiet && fname)
832 printf(gettext("Wrote history to file \"%s/%s\".\n"),
833 pset.dirname ? pset.dirname : ".", fname);
839 /* \set -- generalized set variable/option command */
840 else if (strcmp(cmd, "set") == 0)
842 char *opt0 = psql_scan_slash_option(scan_state,
843 OT_NORMAL, NULL, false);
847 /* list all variables */
848 PrintVariables(pset.vars);
854 * Set variable to the concatenation of the arguments.
859 opt = psql_scan_slash_option(scan_state,
860 OT_NORMAL, NULL, false);
861 newval = pg_strdup(opt ? opt : "");
864 while ((opt = psql_scan_slash_option(scan_state,
865 OT_NORMAL, NULL, false)))
867 newval = realloc(newval, strlen(newval) + strlen(opt) + 1);
870 psql_error("out of memory\n");
877 if (!SetVariable(pset.vars, opt0, newval))
879 psql_error("\\%s: error\n", cmd);
887 /* \t -- turn off headers and row count */
888 else if (strcmp(cmd, "t") == 0)
890 char *opt = psql_scan_slash_option(scan_state,
891 OT_NORMAL, NULL, true);
893 success = do_pset("tuples_only", opt, &pset.popt, pset.quiet);
898 /* \T -- define html <table ...> attributes */
899 else if (strcmp(cmd, "T") == 0)
901 char *value = psql_scan_slash_option(scan_state,
902 OT_NORMAL, NULL, false);
904 success = do_pset("tableattr", value, &pset.popt, pset.quiet);
908 /* \timing -- toggle timing of queries */
909 else if (strcmp(cmd, "timing") == 0)
911 pset.timing = !pset.timing;
915 puts(_("Timing is on."));
917 puts(_("Timing is off."));
922 else if (strcmp(cmd, "unset") == 0)
924 char *opt = psql_scan_slash_option(scan_state,
925 OT_NORMAL, NULL, false);
929 psql_error("\\%s: missing required argument\n", cmd);
932 else if (!SetVariable(pset.vars, opt, NULL))
934 psql_error("\\%s: error\n", cmd);
940 /* \w -- write query buffer to file */
941 else if (strcmp(cmd, "w") == 0 || strcmp(cmd, "write") == 0)
944 bool is_pipe = false;
949 psql_error("no query buffer\n");
950 status = PSQL_CMD_ERROR;
954 fname = psql_scan_slash_option(scan_state,
955 OT_FILEPIPE, NULL, true);
956 expand_tilde(&fname);
960 psql_error("\\%s: missing required argument\n", cmd);
968 fd = popen(&fname[1], "w");
972 canonicalize_path(fname);
973 fd = fopen(fname, "w");
977 psql_error("%s: %s\n", fname, strerror(errno));
987 if (query_buf && query_buf->len > 0)
988 fprintf(fd, "%s\n", query_buf->data);
997 psql_error("%s: %s\n", fname, strerror(errno));
1005 /* \x -- toggle expanded table representation */
1006 else if (strcmp(cmd, "x") == 0)
1008 char *opt = psql_scan_slash_option(scan_state,
1009 OT_NORMAL, NULL, true);
1011 success = do_pset("expanded", opt, &pset.popt, pset.quiet);
1015 /* \z -- list table rights (equivalent to \dp) */
1016 else if (strcmp(cmd, "z") == 0)
1018 char *pattern = psql_scan_slash_option(scan_state,
1019 OT_NORMAL, NULL, true);
1021 success = permissionsList(pattern);
1026 /* \! -- shell escape */
1027 else if (strcmp(cmd, "!") == 0)
1029 char *opt = psql_scan_slash_option(scan_state,
1030 OT_WHOLE_LINE, NULL, false);
1032 success = do_shell(opt);
1036 /* \? -- slash command help */
1037 else if (strcmp(cmd, "?") == 0)
1038 slashUsage(pset.popt.topt.pager);
1043 * These commands don't do anything. I just use them to test the parser.
1045 else if (strcmp(cmd, "void") == 0 || strcmp(cmd, "#") == 0)
1050 while ((value = psql_scan_slash_option(scan_state,
1051 OT_NORMAL, NULL, true)))
1053 fprintf(stderr, "+ opt(%d) = |%s|\n", i++, value);
1060 status = PSQL_CMD_UNKNOWN;
1063 status = PSQL_CMD_ERROR;
1069 * Ask the user for a password; 'username' is the username the
1070 * password is for, if one has been explicitly specified. Returns a
1074 prompt_for_password(const char *username)
1078 if (username == NULL)
1079 result = simple_prompt("Password: ", 100, false);
1084 prompt_text = malloc(strlen(username) + 32);
1085 sprintf(prompt_text, "Password for user \"%s\": ", username);
1086 result = simple_prompt(prompt_text, 100, false);
1094 param_is_newly_set(const char *old_val, const char *new_val)
1096 if (new_val == NULL)
1099 if (old_val == NULL || strcmp(old_val, new_val) != 0)
1106 * do_connect -- handler for \connect
1108 * Connects to a database with given parameters. If there exists an
1109 * established connection, NULL values will be replaced with the ones
1110 * in the current connection. Otherwise NULL will be passed for that
1111 * parameter to PQsetdbLogin(), so the libpq defaults will be used.
1113 * In interactive mode, if connection fails with the given parameters,
1114 * the old connection will be kept.
1117 do_connect(char *dbname, char *user, char *host, char *port)
1119 PGconn *o_conn = pset.db,
1121 char *password = NULL;
1124 dbname = PQdb(o_conn);
1126 user = PQuser(o_conn);
1128 host = PQhost(o_conn);
1130 port = PQport(o_conn);
1133 * If the user asked to be prompted for a password, ask for one now. If
1134 * not, use the password from the old connection, provided the username
1135 * has not changed. Otherwise, try to connect without a password first,
1136 * and then ask for a password if needed.
1138 * XXX: this behavior leads to spurious connection attempts recorded in
1139 * the postmaster's log. But libpq offers no API that would let us obtain
1140 * a password and then continue with the first connection attempt.
1142 if (pset.getPassword)
1144 password = prompt_for_password(user);
1146 else if (o_conn && user && strcmp(PQuser(o_conn), user) == 0)
1148 password = strdup(PQpass(o_conn));
1153 n_conn = PQsetdbLogin(host, port, NULL, NULL,
1154 dbname, user, password);
1156 /* We can immediately discard the password -- no longer needed */
1160 if (PQstatus(n_conn) == CONNECTION_OK)
1164 * Connection attempt failed; either retry the connection attempt with
1165 * a new password, or give up.
1167 if (!password && PQconnectionNeedsPassword(n_conn))
1170 password = prompt_for_password(user);
1175 * Failed to connect to the database. In interactive mode, keep the
1176 * previous connection to the DB; in scripting mode, close our
1177 * previous connection as well.
1179 if (pset.cur_cmd_interactive)
1181 psql_error("%s", PQerrorMessage(n_conn));
1183 /* pset.db is left unmodified */
1185 fputs(_("Previous connection kept\n"), stderr);
1189 psql_error("\\connect: %s", PQerrorMessage(n_conn));
1202 * Replace the old connection with the new one, and update
1203 * connection-dependent variables.
1205 PQsetNoticeProcessor(n_conn, NoticeProcessor, NULL);
1209 /* Tell the user about the new connection */
1212 printf(_("You are now connected to database \"%s\""), PQdb(pset.db));
1214 if (param_is_newly_set(PQhost(o_conn), PQhost(pset.db)))
1215 printf(_(" on host \"%s\""), PQhost(pset.db));
1217 if (param_is_newly_set(PQport(o_conn), PQport(pset.db)))
1218 printf(_(" at port \"%s\""), PQport(pset.db));
1220 if (param_is_newly_set(PQuser(o_conn), PQuser(pset.db)))
1221 printf(_(" as user \"%s\""), PQuser(pset.db));
1235 * Make psql's internal variables agree with connection state upon
1236 * establishing a new connection.
1241 /* get stuff from connection */
1242 pset.encoding = PQclientEncoding(pset.db);
1243 pset.popt.topt.encoding = pset.encoding;
1244 pset.sversion = PQserverVersion(pset.db);
1246 SetVariable(pset.vars, "DBNAME", PQdb(pset.db));
1247 SetVariable(pset.vars, "USER", PQuser(pset.db));
1248 SetVariable(pset.vars, "HOST", PQhost(pset.db));
1249 SetVariable(pset.vars, "PORT", PQport(pset.db));
1250 SetVariable(pset.vars, "ENCODING", pg_encoding_to_char(pset.encoding));
1252 /* send stuff to it, too */
1253 PQsetErrorVerbosity(pset.db, pset.verbosity);
1259 * Clear variables that should be not be set when there is no connection.
1262 UnsyncVariables(void)
1264 SetVariable(pset.vars, "DBNAME", NULL);
1265 SetVariable(pset.vars, "USER", NULL);
1266 SetVariable(pset.vars, "HOST", NULL);
1267 SetVariable(pset.vars, "PORT", NULL);
1268 SetVariable(pset.vars, "ENCODING", NULL);
1273 * do_edit -- handler for \e
1275 * If you do not specify a filename, the current query buffer will be copied
1276 * into a temporary one.
1280 editFile(const char *fname)
1282 const char *editorName;
1288 /* Find an editor to use */
1289 editorName = getenv("PSQL_EDITOR");
1291 editorName = getenv("EDITOR");
1293 editorName = getenv("VISUAL");
1295 editorName = DEFAULT_EDITOR;
1298 * On Unix the EDITOR value should *not* be quoted, since it might include
1299 * switches, eg, EDITOR="pico -t"; it's up to the user to put quotes in it
1300 * if necessary. But this policy is not very workable on Windows, due to
1301 * severe brain damage in their command shell plus the fact that standard
1302 * program paths include spaces.
1304 sys = pg_malloc(strlen(editorName) + strlen(fname) + 10 + 1);
1306 sprintf(sys, "exec %s '%s'", editorName, fname);
1308 sprintf(sys, "%s\"%s\" \"%s\"%s",
1309 SYSTEMQUOTE, editorName, fname, SYSTEMQUOTE);
1311 result = system(sys);
1313 psql_error("could not start editor \"%s\"\n", editorName);
1314 else if (result == 127)
1315 psql_error("could not start /bin/sh\n");
1324 do_edit(const char *filename_arg, PQExpBuffer query_buf)
1326 char fnametmp[MAXPGPATH];
1327 FILE *stream = NULL;
1336 fname = filename_arg;
1339 /* make a temp file to edit */
1341 const char *tmpdir = getenv("TMPDIR");
1346 char tmpdir[MAXPGPATH];
1349 ret = GetTempPath(MAXPGPATH, tmpdir);
1350 if (ret == 0 || ret > MAXPGPATH)
1352 psql_error("cannot locate temporary directory: %s",
1353 !ret ? strerror(errno) : "");
1358 * No canonicalize_path() here. EDIT.EXE run from CMD.EXE prepends the
1359 * current directory to the supplied path unless we use only
1360 * backslashes, so we do that.
1364 snprintf(fnametmp, sizeof(fnametmp), "%s%spsql.edit.%d", tmpdir,
1365 "/", (int) getpid());
1367 snprintf(fnametmp, sizeof(fnametmp), "%s%spsql.edit.%d", tmpdir,
1368 "" /* trailing separator already present */ , (int) getpid());
1371 fname = (const char *) fnametmp;
1373 fd = open(fname, O_WRONLY | O_CREAT | O_EXCL, 0600);
1375 stream = fdopen(fd, "w");
1377 if (fd == -1 || !stream)
1379 psql_error("could not open temporary file \"%s\": %s\n", fname, strerror(errno));
1384 unsigned int ql = query_buf->len;
1386 if (ql == 0 || query_buf->data[ql - 1] != '\n')
1388 appendPQExpBufferChar(query_buf, '\n');
1392 if (fwrite(query_buf->data, 1, ql, stream) != ql)
1394 psql_error("%s: %s\n", fname, strerror(errno));
1399 else if (fclose(stream) != 0)
1401 psql_error("%s: %s\n", fname, strerror(errno));
1408 if (!error && stat(fname, &before) != 0)
1410 psql_error("%s: %s\n", fname, strerror(errno));
1416 error = !editFile(fname);
1418 if (!error && stat(fname, &after) != 0)
1420 psql_error("%s: %s\n", fname, strerror(errno));
1424 if (!error && before.st_mtime != after.st_mtime)
1426 stream = fopen(fname, PG_BINARY_R);
1429 psql_error("%s: %s\n", fname, strerror(errno));
1434 /* read file back into query_buf */
1437 resetPQExpBuffer(query_buf);
1438 while (fgets(line, sizeof(line), stream) != NULL)
1439 appendPQExpBufferStr(query_buf, line);
1443 psql_error("%s: %s\n", fname, strerror(errno));
1452 /* remove temp file */
1455 if (remove(fname) == -1)
1457 psql_error("%s: %s\n", fname, strerror(errno));
1470 * Read commands from filename and then them to the main processing loop
1471 * Handler for \i, but can be used for other things as well. Returns
1472 * MainLoop() error code.
1475 process_file(char *filename, bool single_txn)
1483 return EXIT_FAILURE;
1485 canonicalize_path(filename);
1486 fd = fopen(filename, PG_BINARY_R);
1490 psql_error("%s: %s\n", filename, strerror(errno));
1491 return EXIT_FAILURE;
1494 oldfilename = pset.inputfile;
1495 pset.inputfile = filename;
1498 res = PSQLexec("BEGIN", false);
1499 result = MainLoop(fd);
1501 res = PSQLexec("COMMIT", false);
1504 pset.inputfile = oldfilename;
1515 _align2string(enum printFormat in)
1522 case PRINT_UNALIGNED:
1534 case PRINT_TROFF_MS:
1543 do_pset(const char *param, const char *value, printQueryOpt *popt, bool quiet)
1550 vallen = strlen(value);
1553 if (strcmp(param, "format") == 0)
1557 else if (pg_strncasecmp("unaligned", value, vallen) == 0)
1558 popt->topt.format = PRINT_UNALIGNED;
1559 else if (pg_strncasecmp("aligned", value, vallen) == 0)
1560 popt->topt.format = PRINT_ALIGNED;
1561 else if (pg_strncasecmp("html", value, vallen) == 0)
1562 popt->topt.format = PRINT_HTML;
1563 else if (pg_strncasecmp("latex", value, vallen) == 0)
1564 popt->topt.format = PRINT_LATEX;
1565 else if (pg_strncasecmp("troff-ms", value, vallen) == 0)
1566 popt->topt.format = PRINT_TROFF_MS;
1569 psql_error("\\pset: allowed formats are unaligned, aligned, html, latex, troff-ms\n");
1574 printf(_("Output format is %s.\n"), _align2string(popt->topt.format));
1577 /* set border style/width */
1578 else if (strcmp(param, "border") == 0)
1581 popt->topt.border = atoi(value);
1584 printf(_("Border style is %d.\n"), popt->topt.border);
1587 /* set expanded/vertical mode */
1588 else if (strcmp(param, "x") == 0 || strcmp(param, "expanded") == 0 || strcmp(param, "vertical") == 0)
1591 popt->topt.expanded = ParseVariableBool(value);
1593 popt->topt.expanded = !popt->topt.expanded;
1595 printf(popt->topt.expanded
1596 ? _("Expanded display is on.\n")
1597 : _("Expanded display is off.\n"));
1600 /* locale-aware numeric output */
1601 else if (strcmp(param, "numericlocale") == 0)
1604 popt->topt.numericLocale = ParseVariableBool(value);
1606 popt->topt.numericLocale = !popt->topt.numericLocale;
1609 if (popt->topt.numericLocale)
1610 puts(_("Showing locale-adjusted numeric output."));
1612 puts(_("Locale-adjusted numeric output is off."));
1617 else if (strcmp(param, "null") == 0)
1621 free(popt->nullPrint);
1622 popt->nullPrint = pg_strdup(value);
1625 printf(_("Null display is \"%s\".\n"), popt->nullPrint ? popt->nullPrint : "");
1628 /* field separator for unaligned text */
1629 else if (strcmp(param, "fieldsep") == 0)
1633 free(popt->topt.fieldSep);
1634 popt->topt.fieldSep = pg_strdup(value);
1637 printf(_("Field separator is \"%s\".\n"), popt->topt.fieldSep);
1640 /* record separator for unaligned text */
1641 else if (strcmp(param, "recordsep") == 0)
1645 free(popt->topt.recordSep);
1646 popt->topt.recordSep = pg_strdup(value);
1650 if (strcmp(popt->topt.recordSep, "\n") == 0)
1651 printf(_("Record separator is <newline>."));
1653 printf(_("Record separator is \"%s\".\n"), popt->topt.recordSep);
1657 /* toggle between full and tuples-only format */
1658 else if (strcmp(param, "t") == 0 || strcmp(param, "tuples_only") == 0)
1661 popt->topt.tuples_only = ParseVariableBool(value);
1663 popt->topt.tuples_only = !popt->topt.tuples_only;
1666 if (popt->topt.tuples_only)
1667 puts(_("Showing only tuples."));
1669 puts(_("Tuples only is off."));
1673 /* set title override */
1674 else if (strcmp(param, "title") == 0)
1680 popt->title = pg_strdup(value);
1685 printf(_("Title is \"%s\".\n"), popt->title);
1687 printf(_("Title is unset.\n"));
1691 /* set HTML table tag options */
1692 else if (strcmp(param, "T") == 0 || strcmp(param, "tableattr") == 0)
1694 free(popt->topt.tableAttr);
1696 popt->topt.tableAttr = NULL;
1698 popt->topt.tableAttr = pg_strdup(value);
1702 if (popt->topt.tableAttr)
1703 printf(_("Table attribute is \"%s\".\n"), popt->topt.tableAttr);
1705 printf(_("Table attributes unset.\n"));
1709 /* toggle use of pager */
1710 else if (strcmp(param, "pager") == 0)
1712 if (value && pg_strcasecmp(value, "always") == 0)
1713 popt->topt.pager = 2;
1715 if (ParseVariableBool(value))
1716 popt->topt.pager = 1;
1718 popt->topt.pager = 0;
1719 else if (popt->topt.pager == 1)
1720 popt->topt.pager = 0;
1722 popt->topt.pager = 1;
1725 if (popt->topt.pager == 1)
1726 puts(_("Pager is used for long output."));
1727 else if (popt->topt.pager == 2)
1728 puts(_("Pager is always used."));
1730 puts(_("Pager usage is off."));
1734 /* disable "(x rows)" footer */
1735 else if (strcmp(param, "footer") == 0)
1738 popt->default_footer = ParseVariableBool(value);
1740 popt->default_footer = !popt->default_footer;
1743 if (popt->default_footer)
1744 puts(_("Default footer is on."));
1746 puts(_("Default footer is off."));
1752 psql_error("\\pset: unknown option: %s\n", param);
1762 #define DEFAULT_SHELL "/bin/sh"
1765 * CMD.EXE is in different places in different Win32 releases so we
1766 * have to rely on the path to find it.
1768 #define DEFAULT_SHELL "cmd.exe"
1772 do_shell(const char *command)
1779 const char *shellName;
1781 shellName = getenv("SHELL");
1783 if (shellName == NULL)
1784 shellName = getenv("COMSPEC");
1786 if (shellName == NULL)
1787 shellName = DEFAULT_SHELL;
1789 sys = pg_malloc(strlen(shellName) + 16);
1792 /* See EDITOR handling comment for an explaination */
1793 "exec %s", shellName);
1796 /* See EDITOR handling comment for an explaination */
1797 "%s\"%s\"%s", SYSTEMQUOTE, shellName, SYSTEMQUOTE);
1799 result = system(sys);
1803 result = system(command);
1805 if (result == 127 || result == -1)
1807 psql_error("\\!: failed\n");