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.186 2008/01/01 19:45:55 momjian Exp $
8 #include "postgres_fe.h"
11 #ifdef __BORLANDC__ /* needed for BCC */
20 #include <sys/types.h> /* for umask() */
21 #include <sys/stat.h> /* for stat() */
22 #include <fcntl.h> /* open() flags */
23 #include <unistd.h> /* for geteuid(), getpid(), stat() */
29 #include <sys/types.h> /* for umask() */
30 #include <sys/stat.h> /* for stat() */
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) + 100);
1085 snprintf(prompt_text, strlen(username) + 100,
1086 _("Password for user %s: "), username);
1087 result = simple_prompt(prompt_text, 100, false);
1095 param_is_newly_set(const char *old_val, const char *new_val)
1097 if (new_val == NULL)
1100 if (old_val == NULL || strcmp(old_val, new_val) != 0)
1107 * do_connect -- handler for \connect
1109 * Connects to a database with given parameters. If there exists an
1110 * established connection, NULL values will be replaced with the ones
1111 * in the current connection. Otherwise NULL will be passed for that
1112 * parameter to PQsetdbLogin(), so the libpq defaults will be used.
1114 * In interactive mode, if connection fails with the given parameters,
1115 * the old connection will be kept.
1118 do_connect(char *dbname, char *user, char *host, char *port)
1120 PGconn *o_conn = pset.db,
1122 char *password = NULL;
1125 dbname = PQdb(o_conn);
1127 user = PQuser(o_conn);
1129 host = PQhost(o_conn);
1131 port = PQport(o_conn);
1134 * If the user asked to be prompted for a password, ask for one now. If
1135 * not, use the password from the old connection, provided the username
1136 * has not changed. Otherwise, try to connect without a password first,
1137 * and then ask for a password if needed.
1139 * XXX: this behavior leads to spurious connection attempts recorded in
1140 * the postmaster's log. But libpq offers no API that would let us obtain
1141 * a password and then continue with the first connection attempt.
1143 if (pset.getPassword)
1145 password = prompt_for_password(user);
1147 else if (o_conn && user && strcmp(PQuser(o_conn), user) == 0)
1149 password = strdup(PQpass(o_conn));
1154 n_conn = PQsetdbLogin(host, port, NULL, NULL,
1155 dbname, user, password);
1157 /* We can immediately discard the password -- no longer needed */
1161 if (PQstatus(n_conn) == CONNECTION_OK)
1165 * Connection attempt failed; either retry the connection attempt with
1166 * a new password, or give up.
1168 if (!password && PQconnectionNeedsPassword(n_conn))
1171 password = prompt_for_password(user);
1176 * Failed to connect to the database. In interactive mode, keep the
1177 * previous connection to the DB; in scripting mode, close our
1178 * previous connection as well.
1180 if (pset.cur_cmd_interactive)
1182 psql_error("%s", PQerrorMessage(n_conn));
1184 /* pset.db is left unmodified */
1186 fputs(_("Previous connection kept\n"), stderr);
1190 psql_error("\\connect: %s", PQerrorMessage(n_conn));
1203 * Replace the old connection with the new one, and update
1204 * connection-dependent variables.
1206 PQsetNoticeProcessor(n_conn, NoticeProcessor, NULL);
1210 /* Tell the user about the new connection */
1213 printf(_("You are now connected to database \"%s\""), PQdb(pset.db));
1215 if (param_is_newly_set(PQhost(o_conn), PQhost(pset.db)))
1216 printf(_(" on host \"%s\""), PQhost(pset.db));
1218 if (param_is_newly_set(PQport(o_conn), PQport(pset.db)))
1219 printf(_(" at port \"%s\""), PQport(pset.db));
1221 if (param_is_newly_set(PQuser(o_conn), PQuser(pset.db)))
1222 printf(_(" as user \"%s\""), PQuser(pset.db));
1236 * Make psql's internal variables agree with connection state upon
1237 * establishing a new connection.
1242 /* get stuff from connection */
1243 pset.encoding = PQclientEncoding(pset.db);
1244 pset.popt.topt.encoding = pset.encoding;
1245 pset.sversion = PQserverVersion(pset.db);
1247 SetVariable(pset.vars, "DBNAME", PQdb(pset.db));
1248 SetVariable(pset.vars, "USER", PQuser(pset.db));
1249 SetVariable(pset.vars, "HOST", PQhost(pset.db));
1250 SetVariable(pset.vars, "PORT", PQport(pset.db));
1251 SetVariable(pset.vars, "ENCODING", pg_encoding_to_char(pset.encoding));
1253 /* send stuff to it, too */
1254 PQsetErrorVerbosity(pset.db, pset.verbosity);
1260 * Clear variables that should be not be set when there is no connection.
1263 UnsyncVariables(void)
1265 SetVariable(pset.vars, "DBNAME", NULL);
1266 SetVariable(pset.vars, "USER", NULL);
1267 SetVariable(pset.vars, "HOST", NULL);
1268 SetVariable(pset.vars, "PORT", NULL);
1269 SetVariable(pset.vars, "ENCODING", NULL);
1274 * do_edit -- handler for \e
1276 * If you do not specify a filename, the current query buffer will be copied
1277 * into a temporary one.
1281 editFile(const char *fname)
1283 const char *editorName;
1289 /* Find an editor to use */
1290 editorName = getenv("PSQL_EDITOR");
1292 editorName = getenv("EDITOR");
1294 editorName = getenv("VISUAL");
1296 editorName = DEFAULT_EDITOR;
1299 * On Unix the EDITOR value should *not* be quoted, since it might include
1300 * switches, eg, EDITOR="pico -t"; it's up to the user to put quotes in it
1301 * if necessary. But this policy is not very workable on Windows, due to
1302 * severe brain damage in their command shell plus the fact that standard
1303 * program paths include spaces.
1305 sys = pg_malloc(strlen(editorName) + strlen(fname) + 10 + 1);
1307 sprintf(sys, "exec %s '%s'", editorName, fname);
1309 sprintf(sys, "%s\"%s\" \"%s\"%s",
1310 SYSTEMQUOTE, editorName, fname, SYSTEMQUOTE);
1312 result = system(sys);
1314 psql_error("could not start editor \"%s\"\n", editorName);
1315 else if (result == 127)
1316 psql_error("could not start /bin/sh\n");
1325 do_edit(const char *filename_arg, PQExpBuffer query_buf)
1327 char fnametmp[MAXPGPATH];
1328 FILE *stream = NULL;
1337 fname = filename_arg;
1340 /* make a temp file to edit */
1342 const char *tmpdir = getenv("TMPDIR");
1347 char tmpdir[MAXPGPATH];
1350 ret = GetTempPath(MAXPGPATH, tmpdir);
1351 if (ret == 0 || ret > MAXPGPATH)
1353 psql_error("cannot locate temporary directory: %s",
1354 !ret ? strerror(errno) : "");
1359 * No canonicalize_path() here. EDIT.EXE run from CMD.EXE prepends the
1360 * current directory to the supplied path unless we use only
1361 * backslashes, so we do that.
1365 snprintf(fnametmp, sizeof(fnametmp), "%s%spsql.edit.%d", tmpdir,
1366 "/", (int) getpid());
1368 snprintf(fnametmp, sizeof(fnametmp), "%s%spsql.edit.%d", tmpdir,
1369 "" /* trailing separator already present */ , (int) getpid());
1372 fname = (const char *) fnametmp;
1374 fd = open(fname, O_WRONLY | O_CREAT | O_EXCL, 0600);
1376 stream = fdopen(fd, "w");
1378 if (fd == -1 || !stream)
1380 psql_error("could not open temporary file \"%s\": %s\n", fname, strerror(errno));
1385 unsigned int ql = query_buf->len;
1387 if (ql == 0 || query_buf->data[ql - 1] != '\n')
1389 appendPQExpBufferChar(query_buf, '\n');
1393 if (fwrite(query_buf->data, 1, ql, stream) != ql)
1395 psql_error("%s: %s\n", fname, strerror(errno));
1400 else if (fclose(stream) != 0)
1402 psql_error("%s: %s\n", fname, strerror(errno));
1409 if (!error && stat(fname, &before) != 0)
1411 psql_error("%s: %s\n", fname, strerror(errno));
1417 error = !editFile(fname);
1419 if (!error && stat(fname, &after) != 0)
1421 psql_error("%s: %s\n", fname, strerror(errno));
1425 if (!error && before.st_mtime != after.st_mtime)
1427 stream = fopen(fname, PG_BINARY_R);
1430 psql_error("%s: %s\n", fname, strerror(errno));
1435 /* read file back into query_buf */
1438 resetPQExpBuffer(query_buf);
1439 while (fgets(line, sizeof(line), stream) != NULL)
1440 appendPQExpBufferStr(query_buf, line);
1444 psql_error("%s: %s\n", fname, strerror(errno));
1453 /* remove temp file */
1456 if (remove(fname) == -1)
1458 psql_error("%s: %s\n", fname, strerror(errno));
1471 * Read commands from filename and then them to the main processing loop
1472 * Handler for \i, but can be used for other things as well. Returns
1473 * MainLoop() error code.
1476 process_file(char *filename, bool single_txn)
1484 return EXIT_FAILURE;
1486 canonicalize_path(filename);
1487 fd = fopen(filename, PG_BINARY_R);
1491 psql_error("%s: %s\n", filename, strerror(errno));
1492 return EXIT_FAILURE;
1495 oldfilename = pset.inputfile;
1496 pset.inputfile = filename;
1499 res = PSQLexec("BEGIN", false);
1500 result = MainLoop(fd);
1502 res = PSQLexec("COMMIT", false);
1505 pset.inputfile = oldfilename;
1516 _align2string(enum printFormat in)
1523 case PRINT_UNALIGNED:
1535 case PRINT_TROFF_MS:
1544 do_pset(const char *param, const char *value, printQueryOpt *popt, bool quiet)
1551 vallen = strlen(value);
1554 if (strcmp(param, "format") == 0)
1558 else if (pg_strncasecmp("unaligned", value, vallen) == 0)
1559 popt->topt.format = PRINT_UNALIGNED;
1560 else if (pg_strncasecmp("aligned", value, vallen) == 0)
1561 popt->topt.format = PRINT_ALIGNED;
1562 else if (pg_strncasecmp("html", value, vallen) == 0)
1563 popt->topt.format = PRINT_HTML;
1564 else if (pg_strncasecmp("latex", value, vallen) == 0)
1565 popt->topt.format = PRINT_LATEX;
1566 else if (pg_strncasecmp("troff-ms", value, vallen) == 0)
1567 popt->topt.format = PRINT_TROFF_MS;
1570 psql_error("\\pset: allowed formats are unaligned, aligned, html, latex, troff-ms\n");
1575 printf(_("Output format is %s.\n"), _align2string(popt->topt.format));
1578 /* set border style/width */
1579 else if (strcmp(param, "border") == 0)
1582 popt->topt.border = atoi(value);
1585 printf(_("Border style is %d.\n"), popt->topt.border);
1588 /* set expanded/vertical mode */
1589 else if (strcmp(param, "x") == 0 || strcmp(param, "expanded") == 0 || strcmp(param, "vertical") == 0)
1592 popt->topt.expanded = ParseVariableBool(value);
1594 popt->topt.expanded = !popt->topt.expanded;
1596 printf(popt->topt.expanded
1597 ? _("Expanded display is on.\n")
1598 : _("Expanded display is off.\n"));
1601 /* locale-aware numeric output */
1602 else if (strcmp(param, "numericlocale") == 0)
1605 popt->topt.numericLocale = ParseVariableBool(value);
1607 popt->topt.numericLocale = !popt->topt.numericLocale;
1610 if (popt->topt.numericLocale)
1611 puts(_("Showing locale-adjusted numeric output."));
1613 puts(_("Locale-adjusted numeric output is off."));
1618 else if (strcmp(param, "null") == 0)
1622 free(popt->nullPrint);
1623 popt->nullPrint = pg_strdup(value);
1626 printf(_("Null display is \"%s\".\n"), popt->nullPrint ? popt->nullPrint : "");
1629 /* field separator for unaligned text */
1630 else if (strcmp(param, "fieldsep") == 0)
1634 free(popt->topt.fieldSep);
1635 popt->topt.fieldSep = pg_strdup(value);
1638 printf(_("Field separator is \"%s\".\n"), popt->topt.fieldSep);
1641 /* record separator for unaligned text */
1642 else if (strcmp(param, "recordsep") == 0)
1646 free(popt->topt.recordSep);
1647 popt->topt.recordSep = pg_strdup(value);
1651 if (strcmp(popt->topt.recordSep, "\n") == 0)
1652 printf(_("Record separator is <newline>."));
1654 printf(_("Record separator is \"%s\".\n"), popt->topt.recordSep);
1658 /* toggle between full and tuples-only format */
1659 else if (strcmp(param, "t") == 0 || strcmp(param, "tuples_only") == 0)
1662 popt->topt.tuples_only = ParseVariableBool(value);
1664 popt->topt.tuples_only = !popt->topt.tuples_only;
1667 if (popt->topt.tuples_only)
1668 puts(_("Showing only tuples."));
1670 puts(_("Tuples only is off."));
1674 /* set title override */
1675 else if (strcmp(param, "title") == 0)
1681 popt->title = pg_strdup(value);
1686 printf(_("Title is \"%s\".\n"), popt->title);
1688 printf(_("Title is unset.\n"));
1692 /* set HTML table tag options */
1693 else if (strcmp(param, "T") == 0 || strcmp(param, "tableattr") == 0)
1695 free(popt->topt.tableAttr);
1697 popt->topt.tableAttr = NULL;
1699 popt->topt.tableAttr = pg_strdup(value);
1703 if (popt->topt.tableAttr)
1704 printf(_("Table attribute is \"%s\".\n"), popt->topt.tableAttr);
1706 printf(_("Table attributes unset.\n"));
1710 /* toggle use of pager */
1711 else if (strcmp(param, "pager") == 0)
1713 if (value && pg_strcasecmp(value, "always") == 0)
1714 popt->topt.pager = 2;
1716 if (ParseVariableBool(value))
1717 popt->topt.pager = 1;
1719 popt->topt.pager = 0;
1720 else if (popt->topt.pager == 1)
1721 popt->topt.pager = 0;
1723 popt->topt.pager = 1;
1726 if (popt->topt.pager == 1)
1727 puts(_("Pager is used for long output."));
1728 else if (popt->topt.pager == 2)
1729 puts(_("Pager is always used."));
1731 puts(_("Pager usage is off."));
1735 /* disable "(x rows)" footer */
1736 else if (strcmp(param, "footer") == 0)
1739 popt->default_footer = ParseVariableBool(value);
1741 popt->default_footer = !popt->default_footer;
1744 if (popt->default_footer)
1745 puts(_("Default footer is on."));
1747 puts(_("Default footer is off."));
1753 psql_error("\\pset: unknown option: %s\n", param);
1763 #define DEFAULT_SHELL "/bin/sh"
1766 * CMD.EXE is in different places in different Win32 releases so we
1767 * have to rely on the path to find it.
1769 #define DEFAULT_SHELL "cmd.exe"
1773 do_shell(const char *command)
1780 const char *shellName;
1782 shellName = getenv("SHELL");
1784 if (shellName == NULL)
1785 shellName = getenv("COMSPEC");
1787 if (shellName == NULL)
1788 shellName = DEFAULT_SHELL;
1790 sys = pg_malloc(strlen(shellName) + 16);
1793 /* See EDITOR handling comment for an explaination */
1794 "exec %s", shellName);
1797 /* See EDITOR handling comment for an explaination */
1798 "%s\"%s\"%s", SYSTEMQUOTE, shellName, SYSTEMQUOTE);
1800 result = system(sys);
1804 result = system(command);
1806 if (result == 127 || result == -1)
1808 psql_error("\\!: failed\n");