2 * psql - the PostgreSQL interactive terminal
4 * Copyright (c) 2000-2006, PostgreSQL Global Development Group
6 * $PostgreSQL: pgsql/src/bin/psql/common.c,v 1.124 2006/08/13 21:10:04 tgl Exp $
8 #include "postgres_fe.h"
18 #include <unistd.h> /* for write() */
20 #include <io.h> /* for _write() */
22 #include <sys/timeb.h> /* for _ftime() */
30 #include "mb/pg_wchar.h"
33 /* Workarounds for Windows */
34 /* Probably to be moved up the source tree in the future, perhaps to be replaced by
35 * more specific checks like configure-style HAVE_GETTIMEOFDAY macros.
39 typedef struct timeval TimevalStruct;
41 #define GETTIMEOFDAY(T) gettimeofday(T, NULL)
42 #define DIFF_MSEC(T, U) \
43 ((((int) ((T)->tv_sec - (U)->tv_sec)) * 1000000.0 + \
44 ((int) ((T)->tv_usec - (U)->tv_usec))) / 1000.0)
47 typedef struct _timeb TimevalStruct;
49 #define GETTIMEOFDAY(T) _ftime(T)
50 #define DIFF_MSEC(T, U) \
51 (((T)->time - (U)->time) * 1000.0 + \
52 ((T)->millitm - (U)->millitm))
56 static bool command_no_begin(const char *query);
59 * "Safe" wrapper around strdup()
62 pg_strdup(const char *string)
68 fprintf(stderr, _("%s: pg_strdup: cannot duplicate null pointer (internal error)\n"),
75 psql_error("out of memory\n");
82 pg_malloc(size_t size)
89 psql_error("out of memory\n");
96 pg_malloc_zero(size_t size)
100 tmp = pg_malloc(size);
101 memset(tmp, 0, size);
106 pg_calloc(size_t nmemb, size_t size)
110 tmp = calloc(nmemb, size);
113 psql_error("out of memory");
121 * -- handler for -o command line option and \o command
123 * Tries to open file fname (or pipe if fname starts with '|')
124 * and stores the file handle in pset)
125 * Upon failure, sets stdout and returns false.
128 setQFout(const char *fname)
132 /* Close old file/pipe */
133 if (pset.queryFout && pset.queryFout != stdout && pset.queryFout != stderr)
135 if (pset.queryFoutPipe)
136 pclose(pset.queryFout);
138 fclose(pset.queryFout);
141 /* If no filename, set stdout */
142 if (!fname || fname[0] == '\0')
144 pset.queryFout = stdout;
145 pset.queryFoutPipe = false;
147 else if (*fname == '|')
149 pset.queryFout = popen(fname + 1, "w");
150 pset.queryFoutPipe = true;
154 pset.queryFout = fopen(fname, "w");
155 pset.queryFoutPipe = false;
158 if (!(pset.queryFout))
160 psql_error("%s: %s\n", fname, strerror(errno));
161 pset.queryFout = stdout;
162 pset.queryFoutPipe = false;
168 pqsignal(SIGPIPE, pset.queryFoutPipe ? SIG_IGN : SIG_DFL);
177 * Error reporting for scripts. Errors should look like
178 * psql:filename:lineno: message
182 psql_error(const char *fmt,...)
187 if (pset.queryFout != stdout)
188 fflush(pset.queryFout);
191 fprintf(stderr, "%s:%s:" UINT64_FORMAT ": ", pset.progname, pset.inputfile, pset.lineno);
193 vfprintf(stderr, _(fmt), ap);
200 * for backend Notice messages (INFO, WARNING, etc)
203 NoticeProcessor(void *arg, const char *message)
205 (void) arg; /* not used */
206 psql_error("%s", message);
212 * Code to support query cancellation
214 * Before we start a query, we enable the SIGINT signal catcher to send a
215 * cancel request to the backend. Note that sending the cancel directly from
216 * the signal handler is safe because PQcancel() is written to make it
217 * so. We use write() to report to stderr because it's better to use simple
218 * facilities in a signal handler.
220 * On win32, the signal cancelling happens on a separate thread, because
221 * that's how SetConsoleCtrlHandler works. The PQcancel function is safe
222 * for this (unlike PQrequestCancel). However, a CRITICAL_SECTION is required
223 * to protect the PGcancel structure against being changed while the signal
224 * thread is using it.
226 * SIGINT is supposed to abort all long-running psql operations, not only
227 * database queries. In most places, this is accomplished by checking
228 * cancel_pressed during long-running loops. However, that won't work when
229 * blocked on user input (in readline() or fgets()). In those places, we
230 * set sigint_interrupt_enabled TRUE while blocked, instructing the signal
231 * catcher to longjmp through sigint_interrupt_jmp. We assume readline and
232 * fgets are coded to handle possible interruption. (XXX currently this does
233 * not work on win32, so control-C is less useful there)
235 volatile bool sigint_interrupt_enabled = false;
237 sigjmp_buf sigint_interrupt_jmp;
239 static PGcancel * volatile cancelConn = NULL;
242 static CRITICAL_SECTION cancelConnLock;
245 #define write_stderr(str) write(fileno(stderr), str, strlen(str))
251 handle_sigint(SIGNAL_ARGS)
253 int save_errno = errno;
256 /* if we are waiting for input, longjmp out of it */
257 if (sigint_interrupt_enabled)
259 sigint_interrupt_enabled = false;
260 siglongjmp(sigint_interrupt_jmp, 1);
263 /* else, set cancel flag to stop any long-running loops */
264 cancel_pressed = true;
266 /* and send QueryCancel if we are processing a database query */
267 if (cancelConn != NULL)
269 if (PQcancel(cancelConn, errbuf, sizeof(errbuf)))
270 write_stderr("Cancel request sent\n");
273 write_stderr("Could not send cancel request: ");
274 write_stderr(errbuf);
278 errno = save_errno; /* just in case the write changed it */
282 setup_cancel_handler(void)
284 pqsignal(SIGINT, handle_sigint);
290 consoleHandler(DWORD dwCtrlType)
294 if (dwCtrlType == CTRL_C_EVENT ||
295 dwCtrlType == CTRL_BREAK_EVENT)
298 * Can't longjmp here, because we are in wrong thread :-(
301 /* set cancel flag to stop any long-running loops */
302 cancel_pressed = true;
304 /* and send QueryCancel if we are processing a database query */
305 EnterCriticalSection(&cancelConnLock);
306 if (cancelConn != NULL)
308 if (PQcancel(cancelConn, errbuf, sizeof(errbuf)))
309 write_stderr("Cancel request sent\n");
312 write_stderr("Could not send cancel request: ");
313 write_stderr(errbuf);
316 LeaveCriticalSection(&cancelConnLock);
321 /* Return FALSE for any signals not being handled */
326 setup_cancel_handler(void)
328 InitializeCriticalSection(&cancelConnLock);
330 SetConsoleCtrlHandler(consoleHandler, TRUE);
338 * Returns whether our backend connection is still there.
343 return PQstatus(pset.db) != CONNECTION_BAD;
350 * Verify that we still have a good connection to the backend, and if not,
351 * see if it can be restored.
353 * Returns true if either the connection was still there, or it could be
354 * restored successfully; false otherwise. If, however, there was no
355 * connection and the session is non-interactive, this will exit the program
356 * with a code of EXIT_BADCONN.
359 CheckConnection(void)
366 if (!pset.cur_cmd_interactive)
368 psql_error("connection to server was lost\n");
372 fputs(_("The connection to the server was lost. Attempting reset: "), stderr);
377 fputs(_("Failed.\n"), stderr);
384 fputs(_("Succeeded.\n"), stderr);
395 * Set cancelConn to point to the current database connection.
400 PGcancel *oldCancelConn;
403 EnterCriticalSection(&cancelConnLock);
406 /* Free the old one if we have one */
407 oldCancelConn = cancelConn;
408 /* be sure handle_sigint doesn't use pointer while freeing */
411 if (oldCancelConn != NULL)
412 PQfreeCancel(oldCancelConn);
414 cancelConn = PQgetCancel(pset.db);
417 LeaveCriticalSection(&cancelConnLock);
425 * Free the current cancel connection, if any, and set to NULL.
428 ResetCancelConn(void)
430 PGcancel *oldCancelConn;
433 EnterCriticalSection(&cancelConnLock);
436 oldCancelConn = cancelConn;
437 /* be sure handle_sigint doesn't use pointer while freeing */
440 if (oldCancelConn != NULL)
441 PQfreeCancel(oldCancelConn);
444 LeaveCriticalSection(&cancelConnLock);
452 * Checks whether a result is valid, giving an error message if necessary;
453 * resets cancelConn as needed, and ensures that the connection to the backend
456 * Returns true for valid result, false for error state.
459 AcceptResult(const PGresult *result, const char *query)
468 switch (PQresultStatus(result))
470 case PGRES_COMMAND_OK:
471 case PGRES_TUPLES_OK:
472 case PGRES_EMPTY_QUERY:
475 /* Fine, do nothing */
485 const char *error = PQerrorMessage(pset.db);
488 psql_error("%s", error);
501 * This is the way to send "backdoor" queries (those not directly entered
502 * by the user). It is subject to -E but not -e.
504 * In autocommit-off mode, a new transaction block is started if start_xact
505 * is true; nothing special is done when start_xact is false. Typically,
506 * start_xact = false is used for SELECTs and explicit BEGIN/COMMIT commands.
508 * Caller is responsible for handling the ensuing processing if a COPY
511 * Note: we don't bother to check PQclientEncoding; it is assumed that no
512 * caller uses this path to issue "SET CLIENT_ENCODING".
515 PSQLexec(const char *query, bool start_xact)
522 psql_error("You are currently not connected to a database.\n");
526 echo_hidden = SwitchVariable(pset.vars, "ECHO_HIDDEN", "noexec", NULL);
527 if (echo_hidden != VAR_NOTSET)
529 printf(_("********* QUERY **********\n"
531 "**************************\n\n"), query);
535 fprintf(pset.logfile,
536 _("********* QUERY **********\n"
538 "**************************\n\n"), query);
539 fflush(pset.logfile);
542 if (echo_hidden == 1) /* noexec? */
548 if (start_xact && PQtransactionStatus(pset.db) == PQTRANS_IDLE &&
549 !GetVariableBool(pset.vars, "AUTOCOMMIT"))
551 res = PQexec(pset.db, "BEGIN");
552 if (PQresultStatus(res) != PGRES_COMMAND_OK)
554 psql_error("%s", PQerrorMessage(pset.db));
562 res = PQexec(pset.db, query);
564 if (!AcceptResult(res, query) && res)
576 * PrintNotifications: check for asynchronous notifications, and print them out
579 PrintNotifications(void)
583 while ((notify = PQnotifies(pset.db)))
585 fprintf(pset.queryFout, _("Asynchronous notification \"%s\" received from server process with PID %d.\n"),
586 notify->relname, notify->be_pid);
587 fflush(pset.queryFout);
594 * PrintQueryTuples: assuming query result is OK, print its tuples
596 * Returns true if successful, false otherwise.
599 PrintQueryTuples(const PGresult *results)
601 printQueryOpt my_popt = pset.popt;
603 /* write output to \g argument, if any */
606 FILE *queryFout_copy = pset.queryFout;
607 bool queryFoutPipe_copy = pset.queryFoutPipe;
609 pset.queryFout = stdout; /* so it doesn't get closed */
612 if (!setQFout(pset.gfname))
614 pset.queryFout = queryFout_copy;
615 pset.queryFoutPipe = queryFoutPipe_copy;
619 printQuery(results, &my_popt, pset.queryFout, pset.logfile);
621 /* close file/pipe, restore old setting */
624 pset.queryFout = queryFout_copy;
625 pset.queryFoutPipe = queryFoutPipe_copy;
631 printQuery(results, &my_popt, pset.queryFout, pset.logfile);
638 * ProcessCopyResult: if command was a COPY FROM STDIN/TO STDOUT, handle it
640 * Note: Utility function for use by SendQuery() only.
642 * Returns true if the query executed successfully, false otherwise.
645 ProcessCopyResult(PGresult *results)
647 bool success = false;
652 switch (PQresultStatus(results))
654 case PGRES_TUPLES_OK:
655 case PGRES_COMMAND_OK:
656 case PGRES_EMPTY_QUERY:
657 /* nothing to do here */
663 success = handleCopyOut(pset.db, pset.queryFout);
669 success = handleCopyIn(pset.db, pset.cur_cmd_source,
670 PQbinaryTuples(results));
678 /* may need this to recover from conn loss during COPY */
679 if (!CheckConnection())
687 * PrintQueryStatus: report command status as required
689 * Note: Utility function for use by PrintQueryResults() only.
692 PrintQueryStatus(PGresult *results)
698 if (pset.popt.topt.format == PRINT_HTML)
700 fputs("<p>", pset.queryFout);
701 html_escaped_print(PQcmdStatus(results), pset.queryFout);
702 fputs("</p>\n", pset.queryFout);
705 fprintf(pset.queryFout, "%s\n", PQcmdStatus(results));
709 fprintf(pset.logfile, "%s\n", PQcmdStatus(results));
711 snprintf(buf, sizeof(buf), "%u", (unsigned int) PQoidValue(results));
712 SetVariable(pset.vars, "LASTOID", buf);
717 * PrintQueryResults: print out query results as required
719 * Note: Utility function for use by SendQuery() only.
721 * Returns true if the query executed successfully, false otherwise.
724 PrintQueryResults(PGresult *results)
726 bool success = false;
727 const char *cmdstatus;
732 switch (PQresultStatus(results))
734 case PGRES_TUPLES_OK:
735 /* print the data ... */
736 success = PrintQueryTuples(results);
737 /* if it's INSERT/UPDATE/DELETE RETURNING, also print status */
738 cmdstatus = PQcmdStatus(results);
739 if (strncmp(cmdstatus, "INSERT", 6) == 0 ||
740 strncmp(cmdstatus, "UPDATE", 6) == 0 ||
741 strncmp(cmdstatus, "DELETE", 6) == 0)
742 PrintQueryStatus(results);
745 case PGRES_COMMAND_OK:
746 PrintQueryStatus(results);
750 case PGRES_EMPTY_QUERY:
756 /* nothing to do here */
764 fflush(pset.queryFout);
771 * SendQuery: send the query string to the backend
772 * (and print out results)
774 * Note: This is the "front door" way to send a query. That is, use it to
775 * send queries actually entered by the user. These queries will be subject to
777 * To send "back door" queries (generated by slash commands, etc.) in a
778 * controlled way, use PSQLexec().
780 * Returns true if the query executed successfully, false otherwise.
783 SendQuery(const char *query)
786 TimevalStruct before,
789 on_error_rollback_savepoint = false;
790 PGTransactionStatusType transaction_status;
791 static bool on_error_rollback_warning = false;
792 const char *rollback_str;
796 psql_error("You are currently not connected to a database.\n");
800 if (GetVariableBool(pset.vars, "SINGLESTEP"))
804 printf(_("***(Single step mode: verify command)*******************************************\n"
806 "***(press return to proceed or enter x and return to cancel)********************\n"),
809 if (fgets(buf, sizeof(buf), stdin) != NULL)
813 else if (VariableEquals(pset.vars, "ECHO", "queries"))
821 fprintf(pset.logfile,
822 _("********* QUERY **********\n"
824 "**************************\n\n"), query);
825 fflush(pset.logfile);
830 transaction_status = PQtransactionStatus(pset.db);
832 if (transaction_status == PQTRANS_IDLE &&
833 !GetVariableBool(pset.vars, "AUTOCOMMIT") &&
834 !command_no_begin(query))
836 results = PQexec(pset.db, "BEGIN");
837 if (PQresultStatus(results) != PGRES_COMMAND_OK)
839 psql_error("%s", PQerrorMessage(pset.db));
845 transaction_status = PQtransactionStatus(pset.db);
848 if (transaction_status == PQTRANS_INTRANS &&
849 (rollback_str = GetVariable(pset.vars, "ON_ERROR_ROLLBACK")) != NULL &&
850 /* !off and !interactive is 'on' */
851 pg_strcasecmp(rollback_str, "off") != 0 &&
852 (pset.cur_cmd_interactive ||
853 pg_strcasecmp(rollback_str, "interactive") != 0))
855 if (on_error_rollback_warning == false && pset.sversion < 80000)
857 fprintf(stderr, _("The server version (%d) does not support savepoints for ON_ERROR_ROLLBACK.\n"),
859 on_error_rollback_warning = true;
863 results = PQexec(pset.db, "SAVEPOINT pg_psql_temporary_savepoint");
864 if (PQresultStatus(results) != PGRES_COMMAND_OK)
866 psql_error("%s", PQerrorMessage(pset.db));
872 on_error_rollback_savepoint = true;
877 GETTIMEOFDAY(&before);
879 results = PQexec(pset.db, query);
881 /* these operations are included in the timing result: */
882 OK = (AcceptResult(results, query) && ProcessCopyResult(results));
885 GETTIMEOFDAY(&after);
887 /* but printing results isn't: */
889 OK = PrintQueryResults(results);
891 /* If we made a temporary savepoint, possibly release/rollback */
892 if (on_error_rollback_savepoint)
896 transaction_status = PQtransactionStatus(pset.db);
898 /* We always rollback on an error */
899 if (transaction_status == PQTRANS_INERROR)
900 svptres = PQexec(pset.db, "ROLLBACK TO pg_psql_temporary_savepoint");
901 /* If they are no longer in a transaction, then do nothing */
902 else if (transaction_status != PQTRANS_INTRANS)
907 * Do nothing if they are messing with savepoints themselves: If
908 * the user did RELEASE or ROLLBACK, our savepoint is gone. If
909 * they issued a SAVEPOINT, releasing ours would remove theirs.
911 if (strcmp(PQcmdStatus(results), "SAVEPOINT") == 0 ||
912 strcmp(PQcmdStatus(results), "RELEASE") == 0 ||
913 strcmp(PQcmdStatus(results), "ROLLBACK") == 0)
916 svptres = PQexec(pset.db, "RELEASE pg_psql_temporary_savepoint");
918 if (svptres && PQresultStatus(svptres) != PGRES_COMMAND_OK)
920 psql_error("%s", PQerrorMessage(pset.db));
932 /* Possible microtiming output */
933 if (OK && pset.timing)
934 printf(_("Time: %.3f ms\n"), DIFF_MSEC(&after, &before));
936 /* check for events that may occur during query execution */
938 if (pset.encoding != PQclientEncoding(pset.db) &&
939 PQclientEncoding(pset.db) >= 0)
941 /* track effects of SET CLIENT_ENCODING */
942 pset.encoding = PQclientEncoding(pset.db);
943 pset.popt.topt.encoding = pset.encoding;
944 SetVariable(pset.vars, "ENCODING",
945 pg_encoding_to_char(pset.encoding));
948 PrintNotifications();
955 * Advance the given char pointer over white space and SQL comments.
958 skip_white_space(const char *query)
960 int cnestlevel = 0; /* slash-star comment nest level */
964 int mblen = PQmblen(query, pset.encoding);
967 * Note: we assume the encoding is a superset of ASCII, so that for
968 * example "query[0] == '/'" is meaningful. However, we do NOT assume
969 * that the second and subsequent bytes of a multibyte character
970 * couldn't look like ASCII characters; so it is critical to advance
971 * by mblen, not 1, whenever we haven't exactly identified the
972 * character we are skipping over.
974 if (isspace((unsigned char) *query))
976 else if (query[0] == '/' && query[1] == '*')
981 else if (cnestlevel > 0 && query[0] == '*' && query[1] == '/')
986 else if (cnestlevel == 0 && query[0] == '-' && query[1] == '-')
991 * We have to skip to end of line since any slash-star inside the
992 * -- comment does NOT start a slash-star comment.
1001 query += PQmblen(query, pset.encoding);
1004 else if (cnestlevel > 0)
1007 break; /* found first token */
1015 * Check whether a command is one of those for which we should NOT start
1016 * a new transaction block (ie, send a preceding BEGIN).
1018 * These include the transaction control statements themselves, plus
1019 * certain statements that the backend disallows inside transaction blocks.
1022 command_no_begin(const char *query)
1027 * First we must advance over any whitespace and comments.
1029 query = skip_white_space(query);
1032 * Check word length (since "beginx" is not "begin").
1035 while (isalpha((unsigned char) query[wordlen]))
1036 wordlen += PQmblen(&query[wordlen], pset.encoding);
1039 * Transaction control commands. These should include every keyword that
1040 * gives rise to a TransactionStmt in the backend grammar, except for the
1041 * savepoint-related commands.
1043 * (We assume that START must be START TRANSACTION, since there is
1044 * presently no other "START foo" command.)
1046 if (wordlen == 5 && pg_strncasecmp(query, "abort", 5) == 0)
1048 if (wordlen == 5 && pg_strncasecmp(query, "begin", 5) == 0)
1050 if (wordlen == 5 && pg_strncasecmp(query, "start", 5) == 0)
1052 if (wordlen == 6 && pg_strncasecmp(query, "commit", 6) == 0)
1054 if (wordlen == 3 && pg_strncasecmp(query, "end", 3) == 0)
1056 if (wordlen == 8 && pg_strncasecmp(query, "rollback", 8) == 0)
1058 if (wordlen == 7 && pg_strncasecmp(query, "prepare", 7) == 0)
1060 /* PREPARE TRANSACTION is a TC command, PREPARE foo is not */
1063 query = skip_white_space(query);
1066 while (isalpha((unsigned char) query[wordlen]))
1067 wordlen += PQmblen(&query[wordlen], pset.encoding);
1069 if (wordlen == 11 && pg_strncasecmp(query, "transaction", 11) == 0)
1075 * Commands not allowed within transactions. The statements checked for
1076 * here should be exactly those that call PreventTransactionChain() in the
1079 * Note: we are a bit sloppy about CLUSTER, which is transactional in some
1080 * variants but not others.
1082 if (wordlen == 6 && pg_strncasecmp(query, "vacuum", 6) == 0)
1084 if (wordlen == 7 && pg_strncasecmp(query, "cluster", 7) == 0)
1088 * Note: these tests will match CREATE SYSTEM, DROP SYSTEM, and REINDEX
1089 * TABLESPACE, which aren't really valid commands so we don't care much.
1090 * The other six possible matches are correct.
1092 if ((wordlen == 6 && pg_strncasecmp(query, "create", 6) == 0) ||
1093 (wordlen == 4 && pg_strncasecmp(query, "drop", 4) == 0) ||
1094 (wordlen == 7 && pg_strncasecmp(query, "reindex", 7) == 0))
1098 query = skip_white_space(query);
1101 while (isalpha((unsigned char) query[wordlen]))
1102 wordlen += PQmblen(&query[wordlen], pset.encoding);
1104 if (wordlen == 8 && pg_strncasecmp(query, "database", 8) == 0)
1106 if (wordlen == 6 && pg_strncasecmp(query, "system", 6) == 0)
1108 if (wordlen == 10 && pg_strncasecmp(query, "tablespace", 10) == 0)
1117 * Test if the current user is a database superuser.
1119 * Note: this will correctly detect superuserness only with a protocol-3.0
1120 * or newer backend; otherwise it will always say "false".
1130 val = PQparameterStatus(pset.db, "is_superuser");
1132 if (val && strcmp(val, "on") == 0)
1140 * Test if the current session uses standard string literals.
1142 * Note: With a pre-protocol-3.0 connection this will always say "false",
1143 * which should be the right answer.
1146 standard_strings(void)
1153 val = PQparameterStatus(pset.db, "standard_conforming_strings");
1155 if (val && strcmp(val, "on") == 0)
1163 * Return the session user of the current connection.
1165 * Note: this will correctly detect the session user only with a
1166 * protocol-3.0 or newer backend; otherwise it will return the
1170 session_username(void)
1177 val = PQparameterStatus(pset.db, "session_authorization");
1181 return PQuser(pset.db);
1187 * substitute '~' with HOME or '~username' with username's home dir
1191 expand_tilde(char **filename)
1193 if (!filename || !(*filename))
1197 * WIN32 doesn't use tilde expansion for file names. Also, it uses tilde
1198 * for short versions of long file names, though the tilde is usually
1199 * toward the end, not at the beginning.
1203 /* try tilde expansion */
1204 if (**filename == '~')
1210 char home[MAXPGPATH];
1216 while (*p != '/' && *p != '\0')
1222 if (*(fn + 1) == '\0')
1223 get_home_path(home); /* ~ or ~/ only */
1224 else if ((pw = getpwnam(fn + 1)) != NULL)
1225 StrNCpy(home, pw->pw_dir, MAXPGPATH); /* ~user */
1228 if (strlen(home) != 0)
1232 newfn = pg_malloc(strlen(home) + strlen(p) + 1);
1233 strcpy(newfn, home);