2 * psql - the PostgreSQL interactive terminal
4 * Copyright (c) 2000-2006, PostgreSQL Global Development Group
6 * $PostgreSQL: pgsql/src/bin/psql/command.c,v 1.175 2006/12/16 00:38:43 adunstan 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"
48 #include "mb/pg_wchar.h"
51 /* functions for use in this file */
52 static backslashResult exec_command(const char *cmd,
53 PsqlScanState scan_state,
54 PQExpBuffer query_buf);
55 static bool do_edit(const char *filename_arg, PQExpBuffer query_buf);
56 static bool do_connect(char *dbname, char *user, char *host, char *port);
57 static bool do_shell(const char *command);
63 * Handles all the different commands that start with '\',
64 * ordinarily called by MainLoop().
66 * scan_state is a lexer working state that is set to continue scanning
67 * just after the '\'. The lexer is advanced past the command and all
68 * arguments on return.
70 * 'query_buf' contains the query-so-far, which may be modified by
71 * execution of the backslash command (for example, \r clears it).
72 * query_buf can be NULL if there is no query so far.
74 * Returns a status code indicating what action is desired, see command.h.
79 HandleSlashCmds(PsqlScanState scan_state,
80 PQExpBuffer query_buf)
82 backslashResult status = PSQL_CMD_SKIP_LINE;
86 psql_assert(scan_state);
88 /* Parse off the command name */
89 cmd = psql_scan_slash_command(scan_state);
91 /* And try to execute it */
92 status = exec_command(cmd, scan_state, query_buf);
94 if (status == PSQL_CMD_UNKNOWN && strlen(cmd) > 1)
97 * If the command was not recognized, try to parse it as a one-letter
98 * command with immediately following argument (a still-supported, but
99 * no longer encouraged, syntax).
103 /* don't change cmd until we know it's okay */
107 psql_scan_slash_pushback(scan_state, cmd + 1);
109 status = exec_command(new_cmd, scan_state, query_buf);
111 if (status != PSQL_CMD_UNKNOWN)
113 /* adjust cmd for possible messages below */
118 if (status == PSQL_CMD_UNKNOWN)
120 if (pset.cur_cmd_interactive)
121 fprintf(stderr, _("Invalid command \\%s. Try \\? for help.\n"), cmd);
123 psql_error("invalid command \\%s\n", cmd);
124 status = PSQL_CMD_ERROR;
127 if (status != PSQL_CMD_ERROR)
129 /* eat any remaining arguments after a valid command */
130 /* note we suppress evaluation of backticks here */
131 while ((arg = psql_scan_slash_option(scan_state,
132 OT_VERBATIM, NULL, false)))
134 psql_error("\\%s: extra argument \"%s\" ignored\n", cmd, arg);
140 /* silently throw away rest of line after an erroneous command */
141 while ((arg = psql_scan_slash_option(scan_state,
142 OT_WHOLE_LINE, NULL, false)))
146 /* if there is a trailing \\, swallow it */
147 psql_scan_slash_command_end(scan_state);
155 * Read and interpret an argument to the \connect slash command.
158 read_connect_arg(PsqlScanState scan_state)
164 * Ideally we should treat the arguments as SQL identifiers. But for
165 * backwards compatibility with 7.2 and older pg_dump files, we have to
166 * take unquoted arguments verbatim (don't downcase them). For now,
167 * double-quoted arguments may be stripped of double quotes (as if SQL
168 * identifiers). By 7.4 or so, pg_dump files can be expected to
169 * double-quote all mixed-case \connect arguments, and then we can get rid
172 result = psql_scan_slash_option(scan_state, OT_SQLIDHACK, "e, true);
180 if (*result == '\0' || strcmp(result, "-") == 0)
188 * Subroutine to actually try to execute a backslash command.
190 static backslashResult
191 exec_command(const char *cmd,
192 PsqlScanState scan_state,
193 PQExpBuffer query_buf)
195 bool success = true; /* indicate here if the command ran ok or
197 backslashResult status = PSQL_CMD_SKIP_LINE;
200 * \a -- toggle field alignment This makes little sense but we keep it
203 if (strcmp(cmd, "a") == 0)
205 if (pset.popt.topt.format != PRINT_ALIGNED)
206 success = do_pset("format", "aligned", &pset.popt, pset.quiet);
208 success = do_pset("format", "unaligned", &pset.popt, pset.quiet);
211 /* \C -- override table title (formerly change HTML caption) */
212 else if (strcmp(cmd, "C") == 0)
214 char *opt = psql_scan_slash_option(scan_state,
215 OT_NORMAL, NULL, true);
217 success = do_pset("title", opt, &pset.popt, pset.quiet);
222 * \c or \connect -- connect to database using the specified parameters.
224 * \c dbname user host port
226 * If any of these parameters are omitted or specified as '-', the current
227 * value of the parameter will be used instead. If the parameter has no
228 * current value, the default value for that parameter will be used. Some
231 * \c - - hst Connect to current database on current port of host
232 * "hst" as current user. \c - usr - prt Connect to current database on
233 * "prt" port of current host as user "usr". \c dbs Connect to
234 * "dbs" database on current port of current host as current user.
236 else if (strcmp(cmd, "c") == 0 || strcmp(cmd, "connect") == 0)
243 opt1 = read_connect_arg(scan_state);
244 opt2 = read_connect_arg(scan_state);
245 opt3 = read_connect_arg(scan_state);
246 opt4 = read_connect_arg(scan_state);
248 success = do_connect(opt1, opt2, opt3, opt4);
257 else if (strcmp(cmd, "cd") == 0)
259 char *opt = psql_scan_slash_option(scan_state,
260 OT_NORMAL, NULL, true);
270 pw = getpwuid(geteuid());
273 psql_error("could not get home directory: %s\n", strerror(errno));
280 * On Windows, 'cd' without arguments prints the current
281 * directory, so if someone wants to code this here instead...
287 if (chdir(dir) == -1)
289 psql_error("\\%s: could not change directory to \"%s\": %s\n",
290 cmd, dir, strerror(errno));
296 pset.dirname = pg_strdup(dir);
297 canonicalize_path(pset.dirname);
304 else if (pg_strcasecmp(cmd, "copy") == 0)
306 /* Default fetch-it-all-and-print mode */
307 TimevalStruct before,
309 double elapsed_msec = 0;
311 char *opt = psql_scan_slash_option(scan_state,
312 OT_WHOLE_LINE, NULL, false);
314 GETTIMEOFDAY(&before);
316 success = do_copy(opt);
318 if (pset.timing && success)
320 GETTIMEOFDAY(&after);
321 elapsed_msec = DIFF_MSEC(&after, &before);
322 printf(_("Time: %.3f ms\n"), elapsed_msec);
330 else if (strcmp(cmd, "copyright") == 0)
334 else if (cmd[0] == 'd')
339 /* We don't do SQLID reduction on the pattern yet */
340 pattern = psql_scan_slash_option(scan_state,
341 OT_NORMAL, NULL, true);
343 show_verbose = strchr(cmd, '+') ? true : false;
350 success = describeTableDetails(pattern, show_verbose);
352 /* standard listing of interesting things */
353 success = listTables("tvs", NULL, show_verbose);
356 success = describeAggregates(pattern, show_verbose);
359 success = describeTablespaces(pattern, show_verbose);
362 success = listConversions(pattern);
365 success = listCasts(pattern);
368 success = objectDescription(pattern);
371 success = listDomains(pattern);
374 success = describeFunctions(pattern, show_verbose);
377 /* no longer distinct from \du */
378 success = describeRoles(pattern, show_verbose);
381 success = do_lo_list();
384 success = listSchemas(pattern, show_verbose);
387 success = describeOperators(pattern);
390 success = permissionsList(pattern);
393 success = describeTypes(pattern, show_verbose);
400 success = listTables(&cmd[1], pattern, show_verbose);
403 success = describeRoles(pattern, show_verbose);
407 status = PSQL_CMD_UNKNOWN;
416 * \e or \edit -- edit the current query buffer (or a file and make it the
419 else if (strcmp(cmd, "e") == 0 || strcmp(cmd, "edit") == 0)
425 psql_error("no query buffer\n");
426 status = PSQL_CMD_ERROR;
430 fname = psql_scan_slash_option(scan_state,
431 OT_NORMAL, NULL, true);
432 expand_tilde(&fname);
434 canonicalize_path(fname);
435 status = do_edit(fname, query_buf) ? PSQL_CMD_NEWEDIT : PSQL_CMD_ERROR;
440 /* \echo and \qecho */
441 else if (strcmp(cmd, "echo") == 0 || strcmp(cmd, "qecho") == 0)
445 bool no_newline = false;
449 if (strcmp(cmd, "qecho") == 0)
450 fout = pset.queryFout;
454 while ((value = psql_scan_slash_option(scan_state,
455 OT_NORMAL, "ed, false)))
457 if (!quoted && strcmp(value, "-n") == 0)
473 /* \encoding -- set/show client side encoding */
474 else if (strcmp(cmd, "encoding") == 0)
476 char *encoding = psql_scan_slash_option(scan_state,
477 OT_NORMAL, NULL, false);
482 puts(pg_encoding_to_char(pset.encoding));
487 if (PQsetClientEncoding(pset.db, encoding) == -1)
488 psql_error("%s: invalid encoding name or conversion procedure not found\n", encoding);
491 /* save encoding info into psql internal data */
492 pset.encoding = PQclientEncoding(pset.db);
493 pset.popt.topt.encoding = pset.encoding;
494 SetVariable(pset.vars, "ENCODING",
495 pg_encoding_to_char(pset.encoding));
501 /* \f -- change field separator */
502 else if (strcmp(cmd, "f") == 0)
504 char *fname = psql_scan_slash_option(scan_state,
505 OT_NORMAL, NULL, false);
507 success = do_pset("fieldsep", fname, &pset.popt, pset.quiet);
511 /* \g means send query */
512 else if (strcmp(cmd, "g") == 0)
514 char *fname = psql_scan_slash_option(scan_state,
515 OT_FILEPIPE, NULL, false);
521 expand_tilde(&fname);
522 pset.gfname = pg_strdup(fname);
525 status = PSQL_CMD_SEND;
529 else if (strcmp(cmd, "h") == 0 || strcmp(cmd, "help") == 0)
531 char *opt = psql_scan_slash_option(scan_state,
532 OT_WHOLE_LINE, NULL, false);
534 helpSQL(opt, pset.popt.topt.pager);
539 else if (strcmp(cmd, "H") == 0 || strcmp(cmd, "html") == 0)
541 if (pset.popt.topt.format != PRINT_HTML)
542 success = do_pset("format", "html", &pset.popt, pset.quiet);
544 success = do_pset("format", "aligned", &pset.popt, pset.quiet);
548 /* \i is include file */
549 else if (strcmp(cmd, "i") == 0 || strcmp(cmd, "include") == 0)
551 char *fname = psql_scan_slash_option(scan_state,
552 OT_NORMAL, NULL, true);
556 psql_error("\\%s: missing required argument\n", cmd);
561 expand_tilde(&fname);
562 success = (process_file(fname, false) == EXIT_SUCCESS);
567 /* \l is list databases */
568 else if (strcmp(cmd, "l") == 0 || strcmp(cmd, "list") == 0)
569 success = listAllDbs(false);
570 else if (strcmp(cmd, "l+") == 0 || strcmp(cmd, "list+") == 0)
571 success = listAllDbs(true);
574 * large object things
576 else if (strncmp(cmd, "lo_", 3) == 0)
581 opt1 = psql_scan_slash_option(scan_state,
582 OT_NORMAL, NULL, true);
583 opt2 = psql_scan_slash_option(scan_state,
584 OT_NORMAL, NULL, true);
586 if (strcmp(cmd + 3, "export") == 0)
590 psql_error("\\%s: missing required argument\n", cmd);
596 success = do_lo_export(opt1, opt2);
600 else if (strcmp(cmd + 3, "import") == 0)
604 psql_error("\\%s: missing required argument\n", cmd);
610 success = do_lo_import(opt1, opt2);
614 else if (strcmp(cmd + 3, "list") == 0)
615 success = do_lo_list();
617 else if (strcmp(cmd + 3, "unlink") == 0)
621 psql_error("\\%s: missing required argument\n", cmd);
625 success = do_lo_unlink(opt1);
629 status = PSQL_CMD_UNKNOWN;
636 /* \o -- set query output */
637 else if (strcmp(cmd, "o") == 0 || strcmp(cmd, "out") == 0)
639 char *fname = psql_scan_slash_option(scan_state,
640 OT_FILEPIPE, NULL, true);
642 expand_tilde(&fname);
643 success = setQFout(fname);
647 /* \p prints the current query buffer */
648 else if (strcmp(cmd, "p") == 0 || strcmp(cmd, "print") == 0)
650 if (query_buf && query_buf->len > 0)
651 puts(query_buf->data);
652 else if (!pset.quiet)
653 puts(_("Query buffer is empty."));
657 /* \password -- set user password */
658 else if (strcmp(cmd, "password") == 0)
663 pw1 = simple_prompt("Enter new password: ", 100, false);
664 pw2 = simple_prompt("Enter it again: ", 100, false);
666 if (strcmp(pw1, pw2) != 0)
668 fprintf(stderr, _("Passwords didn't match.\n"));
673 char *opt0 = psql_scan_slash_option(scan_state, OT_SQLID, NULL, true);
675 char *encrypted_password;
680 user = PQuser(pset.db);
682 encrypted_password = PQencryptPassword(pw1, user);
684 if (!encrypted_password)
686 fprintf(stderr, _("Password encryption failed.\n"));
694 initPQExpBuffer(&buf);
695 printfPQExpBuffer(&buf, "ALTER USER %s PASSWORD ",
697 appendStringLiteralConn(&buf, encrypted_password, pset.db);
698 res = PSQLexec(buf.data, false);
699 termPQExpBuffer(&buf);
704 PQfreemem(encrypted_password);
712 /* \pset -- set printing parameters */
713 else if (strcmp(cmd, "pset") == 0)
715 char *opt0 = psql_scan_slash_option(scan_state,
716 OT_NORMAL, NULL, false);
717 char *opt1 = psql_scan_slash_option(scan_state,
718 OT_NORMAL, NULL, false);
722 psql_error("\\%s: missing required argument\n", cmd);
726 success = do_pset(opt0, opt1, &pset.popt, pset.quiet);
733 else if (strcmp(cmd, "q") == 0 || strcmp(cmd, "quit") == 0)
734 status = PSQL_CMD_TERMINATE;
736 /* reset(clear) the buffer */
737 else if (strcmp(cmd, "r") == 0 || strcmp(cmd, "reset") == 0)
739 resetPQExpBuffer(query_buf);
740 psql_scan_reset(scan_state);
742 puts(_("Query buffer reset (cleared)."));
745 /* \s save history in a file or show it on the screen */
746 else if (strcmp(cmd, "s") == 0)
748 char *fname = psql_scan_slash_option(scan_state,
749 OT_NORMAL, NULL, true);
751 expand_tilde(&fname);
752 /* This scrolls off the screen when using /dev/tty */
753 success = saveHistory(fname ? fname : DEVTTY, false);
754 if (success && !pset.quiet && fname)
755 printf(gettext("Wrote history to file \"%s/%s\".\n"),
756 pset.dirname ? pset.dirname : ".", fname);
762 /* \set -- generalized set variable/option command */
763 else if (strcmp(cmd, "set") == 0)
765 char *opt0 = psql_scan_slash_option(scan_state,
766 OT_NORMAL, NULL, false);
770 /* list all variables */
771 PrintVariables(pset.vars);
777 * Set variable to the concatenation of the arguments.
782 opt = psql_scan_slash_option(scan_state,
783 OT_NORMAL, NULL, false);
784 newval = pg_strdup(opt ? opt : "");
787 while ((opt = psql_scan_slash_option(scan_state,
788 OT_NORMAL, NULL, false)))
790 newval = realloc(newval, strlen(newval) + strlen(opt) + 1);
793 psql_error("out of memory\n");
800 if (!SetVariable(pset.vars, opt0, newval))
802 psql_error("\\%s: error\n", cmd);
810 /* \t -- turn off headers and row count */
811 else if (strcmp(cmd, "t") == 0)
812 success = do_pset("tuples_only", NULL, &pset.popt, pset.quiet);
815 /* \T -- define html <table ...> attributes */
816 else if (strcmp(cmd, "T") == 0)
818 char *value = psql_scan_slash_option(scan_state,
819 OT_NORMAL, NULL, false);
821 success = do_pset("tableattr", value, &pset.popt, pset.quiet);
825 /* \timing -- toggle timing of queries */
826 else if (strcmp(cmd, "timing") == 0)
828 pset.timing = !pset.timing;
832 puts(_("Timing is on."));
834 puts(_("Timing is off."));
839 else if (strcmp(cmd, "unset") == 0)
841 char *opt = psql_scan_slash_option(scan_state,
842 OT_NORMAL, NULL, false);
846 psql_error("\\%s: missing required argument\n", cmd);
849 else if (!SetVariable(pset.vars, opt, NULL))
851 psql_error("\\%s: error\n", cmd);
857 /* \w -- write query buffer to file */
858 else if (strcmp(cmd, "w") == 0 || strcmp(cmd, "write") == 0)
861 bool is_pipe = false;
866 psql_error("no query buffer\n");
867 status = PSQL_CMD_ERROR;
871 fname = psql_scan_slash_option(scan_state,
872 OT_FILEPIPE, NULL, true);
873 expand_tilde(&fname);
877 psql_error("\\%s: missing required argument\n", cmd);
885 fd = popen(&fname[1], "w");
889 canonicalize_path(fname);
890 fd = fopen(fname, "w");
894 psql_error("%s: %s\n", fname, strerror(errno));
904 if (query_buf && query_buf->len > 0)
905 fprintf(fd, "%s\n", query_buf->data);
914 psql_error("%s: %s\n", fname, strerror(errno));
922 /* \x -- toggle expanded table representation */
923 else if (strcmp(cmd, "x") == 0)
924 success = do_pset("expanded", NULL, &pset.popt, pset.quiet);
926 /* \z -- list table rights (equivalent to \dp) */
927 else if (strcmp(cmd, "z") == 0)
929 char *pattern = psql_scan_slash_option(scan_state,
930 OT_NORMAL, NULL, true);
932 success = permissionsList(pattern);
937 /* \! -- shell escape */
938 else if (strcmp(cmd, "!") == 0)
940 char *opt = psql_scan_slash_option(scan_state,
941 OT_WHOLE_LINE, NULL, false);
943 success = do_shell(opt);
947 /* \? -- slash command help */
948 else if (strcmp(cmd, "?") == 0)
949 slashUsage(pset.popt.topt.pager);
954 * These commands don't do anything. I just use them to test the parser.
956 else if (strcmp(cmd, "void") == 0 || strcmp(cmd, "#") == 0)
961 while ((value = psql_scan_slash_option(scan_state,
962 OT_NORMAL, NULL, true)))
964 fprintf(stderr, "+ opt(%d) = |%s|\n", i++, value);
971 status = PSQL_CMD_UNKNOWN;
974 status = PSQL_CMD_ERROR;
980 * Ask the user for a password; 'username' is the username the
981 * password is for, if one has been explicitly specified. Returns a
985 prompt_for_password(const char *username)
989 if (username == NULL)
990 result = simple_prompt("Password: ", 100, false);
995 prompt_text = malloc(strlen(username) + 32);
996 sprintf(prompt_text, "Password for user \"%s\": ", username);
997 result = simple_prompt(prompt_text, 100, false);
1005 param_is_newly_set(const char *old_val, const char *new_val)
1007 if (new_val == NULL)
1010 if (old_val == NULL || strcmp(old_val, new_val) != 0)
1017 * do_connect -- handler for \connect
1019 * Connects to a database with given parameters. If there exists an
1020 * established connection, NULL values will be replaced with the ones
1021 * in the current connection. Otherwise NULL will be passed for that
1022 * parameter to PQsetdbLogin(), so the libpq defaults will be used.
1024 * In interactive mode, if connection fails with the given parameters,
1025 * the old connection will be kept.
1028 do_connect(char *dbname, char *user, char *host, char *port)
1030 PGconn *o_conn = pset.db,
1032 char *password = NULL;
1035 dbname = PQdb(o_conn);
1037 user = PQuser(o_conn);
1039 host = PQhost(o_conn);
1041 port = PQport(o_conn);
1044 * If the user asked to be prompted for a password, ask for one now. If
1045 * not, use the password from the old connection, provided the username
1046 * has not changed. Otherwise, try to connect without a password first,
1047 * and then ask for a password if we got the appropriate error message.
1049 * XXX: this behavior is broken. It leads to spurious connection attempts
1050 * in the postmaster's log, and doing a string comparison against the
1051 * returned error message is pretty fragile.
1053 if (pset.getPassword)
1055 password = prompt_for_password(user);
1057 else if (o_conn && user && strcmp(PQuser(o_conn), user) == 0)
1059 password = strdup(PQpass(o_conn));
1064 n_conn = PQsetdbLogin(host, port, NULL, NULL,
1065 dbname, user, password);
1067 /* We can immediately discard the password -- no longer needed */
1071 if (PQstatus(n_conn) == CONNECTION_OK)
1075 * Connection attempt failed; either retry the connection attempt with
1076 * a new password, or give up.
1078 if (strcmp(PQerrorMessage(n_conn), PQnoPasswordSupplied) == 0)
1081 password = prompt_for_password(user);
1086 * Failed to connect to the database. In interactive mode, keep the
1087 * previous connection to the DB; in scripting mode, close our
1088 * previous connection as well.
1090 if (pset.cur_cmd_interactive)
1092 psql_error("%s", PQerrorMessage(n_conn));
1094 /* pset.db is left unmodified */
1096 fputs(_("Previous connection kept\n"), stderr);
1100 psql_error("\\connect: %s", PQerrorMessage(n_conn));
1113 * Replace the old connection with the new one, and update
1114 * connection-dependent variables.
1116 PQsetNoticeProcessor(n_conn, NoticeProcessor, NULL);
1120 /* Tell the user about the new connection */
1123 printf(_("You are now connected to database \"%s\""), PQdb(pset.db));
1125 if (param_is_newly_set(PQhost(o_conn), PQhost(pset.db)))
1126 printf(_(" on host \"%s\""), PQhost(pset.db));
1128 if (param_is_newly_set(PQport(o_conn), PQport(pset.db)))
1129 printf(_(" at port \"%s\""), PQport(pset.db));
1131 if (param_is_newly_set(PQuser(o_conn), PQuser(pset.db)))
1132 printf(_(" as user \"%s\""), PQuser(pset.db));
1146 * Make psql's internal variables agree with connection state upon
1147 * establishing a new connection.
1152 /* get stuff from connection */
1153 pset.encoding = PQclientEncoding(pset.db);
1154 pset.popt.topt.encoding = pset.encoding;
1155 pset.sversion = PQserverVersion(pset.db);
1157 SetVariable(pset.vars, "DBNAME", PQdb(pset.db));
1158 SetVariable(pset.vars, "USER", PQuser(pset.db));
1159 SetVariable(pset.vars, "HOST", PQhost(pset.db));
1160 SetVariable(pset.vars, "PORT", PQport(pset.db));
1161 SetVariable(pset.vars, "ENCODING", pg_encoding_to_char(pset.encoding));
1163 /* send stuff to it, too */
1164 PQsetErrorVerbosity(pset.db, pset.verbosity);
1170 * Clear variables that should be not be set when there is no connection.
1173 UnsyncVariables(void)
1175 SetVariable(pset.vars, "DBNAME", NULL);
1176 SetVariable(pset.vars, "USER", NULL);
1177 SetVariable(pset.vars, "HOST", NULL);
1178 SetVariable(pset.vars, "PORT", NULL);
1179 SetVariable(pset.vars, "ENCODING", NULL);
1184 * do_edit -- handler for \e
1186 * If you do not specify a filename, the current query buffer will be copied
1187 * into a temporary one.
1191 editFile(const char *fname)
1193 const char *editorName;
1199 /* Find an editor to use */
1200 editorName = getenv("PSQL_EDITOR");
1202 editorName = getenv("EDITOR");
1204 editorName = getenv("VISUAL");
1206 editorName = DEFAULT_EDITOR;
1209 * On Unix the EDITOR value should *not* be quoted, since it might include
1210 * switches, eg, EDITOR="pico -t"; it's up to the user to put quotes in it
1211 * if necessary. But this policy is not very workable on Windows, due to
1212 * severe brain damage in their command shell plus the fact that standard
1213 * program paths include spaces.
1215 sys = pg_malloc(strlen(editorName) + strlen(fname) + 10 + 1);
1217 sprintf(sys, "exec %s '%s'", editorName, fname);
1219 sprintf(sys, "%s\"%s\" \"%s\"%s",
1220 SYSTEMQUOTE, editorName, fname, SYSTEMQUOTE);
1222 result = system(sys);
1224 psql_error("could not start editor \"%s\"\n", editorName);
1225 else if (result == 127)
1226 psql_error("could not start /bin/sh\n");
1235 do_edit(const char *filename_arg, PQExpBuffer query_buf)
1237 char fnametmp[MAXPGPATH];
1238 FILE *stream = NULL;
1247 fname = filename_arg;
1250 /* make a temp file to edit */
1252 const char *tmpdir = getenv("TMPDIR");
1257 char tmpdir[MAXPGPATH];
1260 ret = GetTempPath(MAXPGPATH, tmpdir);
1261 if (ret == 0 || ret > MAXPGPATH)
1263 psql_error("cannot locate temporary directory: %s",
1264 !ret ? strerror(errno) : "");
1269 * No canonicalize_path() here. EDIT.EXE run from CMD.EXE prepends the
1270 * current directory to the supplied path unless we use only
1271 * backslashes, so we do that.
1275 snprintf(fnametmp, sizeof(fnametmp), "%s%spsql.edit.%d", tmpdir,
1276 "/", (int) getpid());
1278 snprintf(fnametmp, sizeof(fnametmp), "%s%spsql.edit.%d", tmpdir,
1279 "" /* trailing separator already present */ , (int) getpid());
1282 fname = (const char *) fnametmp;
1284 fd = open(fname, O_WRONLY | O_CREAT | O_EXCL, 0600);
1286 stream = fdopen(fd, "w");
1288 if (fd == -1 || !stream)
1290 psql_error("could not open temporary file \"%s\": %s\n", fname, strerror(errno));
1295 unsigned int ql = query_buf->len;
1297 if (ql == 0 || query_buf->data[ql - 1] != '\n')
1299 appendPQExpBufferChar(query_buf, '\n');
1303 if (fwrite(query_buf->data, 1, ql, stream) != ql)
1305 psql_error("%s: %s\n", fname, strerror(errno));
1310 else if (fclose(stream) != 0)
1312 psql_error("%s: %s\n", fname, strerror(errno));
1319 if (!error && stat(fname, &before) != 0)
1321 psql_error("%s: %s\n", fname, strerror(errno));
1327 error = !editFile(fname);
1329 if (!error && stat(fname, &after) != 0)
1331 psql_error("%s: %s\n", fname, strerror(errno));
1335 if (!error && before.st_mtime != after.st_mtime)
1337 stream = fopen(fname, PG_BINARY_R);
1340 psql_error("%s: %s\n", fname, strerror(errno));
1345 /* read file back into query_buf */
1348 resetPQExpBuffer(query_buf);
1349 while (fgets(line, sizeof(line), stream) != NULL)
1350 appendPQExpBufferStr(query_buf, line);
1354 psql_error("%s: %s\n", fname, strerror(errno));
1363 /* remove temp file */
1366 if (remove(fname) == -1)
1368 psql_error("%s: %s\n", fname, strerror(errno));
1381 * Read commands from filename and then them to the main processing loop
1382 * Handler for \i, but can be used for other things as well. Returns
1383 * MainLoop() error code.
1386 process_file(char *filename, bool single_txn)
1394 return EXIT_FAILURE;
1396 canonicalize_path(filename);
1397 fd = fopen(filename, PG_BINARY_R);
1401 psql_error("%s: %s\n", filename, strerror(errno));
1402 return EXIT_FAILURE;
1405 oldfilename = pset.inputfile;
1406 pset.inputfile = filename;
1409 res = PSQLexec("BEGIN", false);
1410 result = MainLoop(fd);
1412 res = PSQLexec("COMMIT", false);
1415 pset.inputfile = oldfilename;
1426 _align2string(enum printFormat in)
1433 case PRINT_UNALIGNED:
1445 case PRINT_TROFF_MS:
1454 do_pset(const char *param, const char *value, printQueryOpt *popt, bool quiet)
1461 vallen = strlen(value);
1464 if (strcmp(param, "format") == 0)
1468 else if (pg_strncasecmp("unaligned", value, vallen) == 0)
1469 popt->topt.format = PRINT_UNALIGNED;
1470 else if (pg_strncasecmp("aligned", value, vallen) == 0)
1471 popt->topt.format = PRINT_ALIGNED;
1472 else if (pg_strncasecmp("html", value, vallen) == 0)
1473 popt->topt.format = PRINT_HTML;
1474 else if (pg_strncasecmp("latex", value, vallen) == 0)
1475 popt->topt.format = PRINT_LATEX;
1476 else if (pg_strncasecmp("troff-ms", value, vallen) == 0)
1477 popt->topt.format = PRINT_TROFF_MS;
1480 psql_error("\\pset: allowed formats are unaligned, aligned, html, latex, troff-ms\n");
1485 printf(_("Output format is %s.\n"), _align2string(popt->topt.format));
1488 /* set border style/width */
1489 else if (strcmp(param, "border") == 0)
1492 popt->topt.border = atoi(value);
1495 printf(_("Border style is %d.\n"), popt->topt.border);
1498 /* set expanded/vertical mode */
1499 else if (strcmp(param, "x") == 0 || strcmp(param, "expanded") == 0 || strcmp(param, "vertical") == 0)
1501 popt->topt.expanded = !popt->topt.expanded;
1503 printf(popt->topt.expanded
1504 ? _("Expanded display is on.\n")
1505 : _("Expanded display is off.\n"));
1508 /* locale-aware numeric output */
1509 else if (strcmp(param, "numericlocale") == 0)
1511 popt->topt.numericLocale = !popt->topt.numericLocale;
1514 if (popt->topt.numericLocale)
1515 puts(_("Showing locale-adjusted numeric output."));
1517 puts(_("Locale-adjusted numeric output is off."));
1522 else if (strcmp(param, "null") == 0)
1526 free(popt->nullPrint);
1527 popt->nullPrint = pg_strdup(value);
1530 printf(_("Null display is \"%s\".\n"), popt->nullPrint ? popt->nullPrint : "");
1533 /* field separator for unaligned text */
1534 else if (strcmp(param, "fieldsep") == 0)
1538 free(popt->topt.fieldSep);
1539 popt->topt.fieldSep = pg_strdup(value);
1542 printf(_("Field separator is \"%s\".\n"), popt->topt.fieldSep);
1545 /* record separator for unaligned text */
1546 else if (strcmp(param, "recordsep") == 0)
1550 free(popt->topt.recordSep);
1551 popt->topt.recordSep = pg_strdup(value);
1555 if (strcmp(popt->topt.recordSep, "\n") == 0)
1556 printf(_("Record separator is <newline>."));
1558 printf(_("Record separator is \"%s\".\n"), popt->topt.recordSep);
1562 /* toggle between full and tuples-only format */
1563 else if (strcmp(param, "t") == 0 || strcmp(param, "tuples_only") == 0)
1565 popt->topt.tuples_only = !popt->topt.tuples_only;
1568 if (popt->topt.tuples_only)
1569 puts(_("Showing only tuples."));
1571 puts(_("Tuples only is off."));
1575 /* set title override */
1576 else if (strcmp(param, "title") == 0)
1582 popt->title = pg_strdup(value);
1587 printf(_("Title is \"%s\".\n"), popt->title);
1589 printf(_("Title is unset.\n"));
1593 /* set HTML table tag options */
1594 else if (strcmp(param, "T") == 0 || strcmp(param, "tableattr") == 0)
1596 free(popt->topt.tableAttr);
1598 popt->topt.tableAttr = NULL;
1600 popt->topt.tableAttr = pg_strdup(value);
1604 if (popt->topt.tableAttr)
1605 printf(_("Table attribute is \"%s\".\n"), popt->topt.tableAttr);
1607 printf(_("Table attributes unset.\n"));
1611 /* toggle use of pager */
1612 else if (strcmp(param, "pager") == 0)
1614 if (value && pg_strcasecmp(value, "always") == 0)
1615 popt->topt.pager = 2;
1616 else if (popt->topt.pager == 1)
1617 popt->topt.pager = 0;
1619 popt->topt.pager = 1;
1622 if (popt->topt.pager == 1)
1623 puts(_("Pager is used for long output."));
1624 else if (popt->topt.pager == 2)
1625 puts(_("Pager is always used."));
1627 puts(_("Pager usage is off."));
1631 /* disable "(x rows)" footer */
1632 else if (strcmp(param, "footer") == 0)
1634 popt->default_footer = !popt->default_footer;
1637 if (popt->default_footer)
1638 puts(_("Default footer is on."));
1640 puts(_("Default footer is off."));
1646 psql_error("\\pset: unknown option: %s\n", param);
1656 #define DEFAULT_SHELL "/bin/sh"
1659 * CMD.EXE is in different places in different Win32 releases so we
1660 * have to rely on the path to find it.
1662 #define DEFAULT_SHELL "cmd.exe"
1666 do_shell(const char *command)
1673 const char *shellName;
1675 shellName = getenv("SHELL");
1677 if (shellName == NULL)
1678 shellName = getenv("COMSPEC");
1680 if (shellName == NULL)
1681 shellName = DEFAULT_SHELL;
1683 sys = pg_malloc(strlen(shellName) + 16);
1686 /* See EDITOR handling comment for an explaination */
1687 "exec %s", shellName);
1690 /* See EDITOR handling comment for an explaination */
1691 "%s\"%s\"%s", SYSTEMQUOTE, shellName, SYSTEMQUOTE);
1693 result = system(sys);
1697 result = system(command);
1699 if (result == 127 || result == -1)
1701 psql_error("\\!: failed\n");