2 * psql - the PostgreSQL interactive terminal
4 * Copyright (c) 2000-2019, PostgreSQL Global Development Group
6 * src/bin/psql/common.c
8 #include "postgres_fe.h"
15 #include <unistd.h> /* for write() */
17 #include <io.h> /* for _write() */
23 #include "common/logging.h"
25 #include "crosstabview.h"
26 #include "fe_utils/mbprint.h"
27 #include "fe_utils/string_utils.h"
28 #include "portability/instr_time.h"
31 static bool DescribeQuery(const char *query, double *elapsed_msec);
32 static bool ExecQueryUsingCursor(const char *query, double *elapsed_msec);
33 static bool command_no_begin(const char *query);
34 static bool is_select_command(const char *query);
38 * openQueryOutputFile --- attempt to open a query output file
40 * fname == NULL selects stdout, else an initial '|' selects a pipe,
43 * Returns output file pointer into *fout, and is-a-pipe flag into *is_pipe.
44 * Caller is responsible for adjusting SIGPIPE state if it's a pipe.
46 * On error, reports suitable error message and returns false.
49 openQueryOutputFile(const char *fname, FILE **fout, bool *is_pipe)
51 if (!fname || fname[0] == '\0')
56 else if (*fname == '|')
58 *fout = popen(fname + 1, "w");
63 *fout = fopen(fname, "w");
69 pg_log_error("%s: %m", fname);
78 * -- handler for -o command line option and \o command
80 * On success, updates pset with the new output file and returns true.
81 * On failure, returns false without changing pset state.
84 setQFout(const char *fname)
89 /* First make sure we can open the new output file/pipe */
90 if (!openQueryOutputFile(fname, &fout, &is_pipe))
93 /* Close old file/pipe */
94 if (pset.queryFout && pset.queryFout != stdout && pset.queryFout != stderr)
96 if (pset.queryFoutPipe)
97 pclose(pset.queryFout);
99 fclose(pset.queryFout);
102 pset.queryFout = fout;
103 pset.queryFoutPipe = is_pipe;
105 /* Adjust SIGPIPE handling appropriately: ignore signal if is_pipe */
106 set_sigpipe_trap_state(is_pipe);
107 restore_sigpipe_trap();
114 * Variable-fetching callback for flex lexer
116 * If the specified variable exists, return its value as a string (malloc'd
117 * and expected to be freed by the caller); else return NULL.
119 * If "quote" isn't PQUOTE_PLAIN, then return the value suitably quoted and
120 * escaped for the specified quoting requirement. (Failure in escaping
121 * should lead to printing an error and returning NULL.)
123 * "passthrough" is the pointer previously given to psql_scan_set_passthrough.
124 * In psql, passthrough points to a ConditionalStack, which we check to
125 * determine whether variable expansion is allowed.
128 psql_get_variable(const char *varname, PsqlScanQuoteType quote,
134 /* In an inactive \if branch, suppress all variable substitutions */
135 if (passthrough && !conditional_active((ConditionalStack) passthrough))
138 value = GetVariable(pset.vars, varname);
145 result = pg_strdup(value);
147 case PQUOTE_SQL_LITERAL:
148 case PQUOTE_SQL_IDENT:
151 * For these cases, we use libpq's quoting functions, which
152 * assume the string is in the connection's client encoding.
158 pg_log_error("cannot escape without active connection");
162 if (quote == PQUOTE_SQL_LITERAL)
164 PQescapeLiteral(pset.db, value, strlen(value));
167 PQescapeIdentifier(pset.db, value, strlen(value));
169 if (escaped_value == NULL)
171 const char *error = PQerrorMessage(pset.db);
173 pg_log_info("%s", error);
178 * Rather than complicate the lexer's API with a notion of
179 * which free() routine to use, just pay the price of an extra
182 result = pg_strdup(escaped_value);
183 PQfreemem(escaped_value);
186 case PQUOTE_SHELL_ARG:
189 * For this we use appendShellStringNoError, which is
190 * encoding-agnostic, which is fine since the shell probably
191 * is too. In any case, the only special character is "'",
192 * which is not known to appear in valid multibyte characters.
196 initPQExpBuffer(&buf);
197 if (!appendShellStringNoError(&buf, value))
199 pg_log_error("shell command argument contains a newline or carriage return: \"%s\"",
208 /* No default: we want a compiler warning for missing cases */
216 * for backend Notice messages (INFO, WARNING, etc)
219 NoticeProcessor(void *arg, const char *message)
221 (void) arg; /* not used */
222 pg_log_info("%s", message);
228 * Code to support query cancellation
230 * Before we start a query, we enable the SIGINT signal catcher to send a
231 * cancel request to the backend. Note that sending the cancel directly from
232 * the signal handler is safe because PQcancel() is written to make it
233 * so. We use write() to report to stderr because it's better to use simple
234 * facilities in a signal handler.
236 * On win32, the signal canceling happens on a separate thread, because
237 * that's how SetConsoleCtrlHandler works. The PQcancel function is safe
238 * for this (unlike PQrequestCancel). However, a CRITICAL_SECTION is required
239 * to protect the PGcancel structure against being changed while the signal
240 * thread is using it.
242 * SIGINT is supposed to abort all long-running psql operations, not only
243 * database queries. In most places, this is accomplished by checking
244 * cancel_pressed during long-running loops. However, that won't work when
245 * blocked on user input (in readline() or fgets()). In those places, we
246 * set sigint_interrupt_enabled true while blocked, instructing the signal
247 * catcher to longjmp through sigint_interrupt_jmp. We assume readline and
248 * fgets are coded to handle possible interruption. (XXX currently this does
249 * not work on win32, so control-C is less useful there)
251 volatile bool sigint_interrupt_enabled = false;
253 sigjmp_buf sigint_interrupt_jmp;
255 static PGcancel *volatile cancelConn = NULL;
258 static CRITICAL_SECTION cancelConnLock;
262 * Write a simple string to stderr --- must be safe in a signal handler.
263 * We ignore the write() result since there's not much we could do about it.
264 * Certain compilers make that harder than it ought to be.
266 #define write_stderr(str) \
268 const char *str_ = (str); \
270 rc_ = write(fileno(stderr), str_, strlen(str_)); \
278 handle_sigint(SIGNAL_ARGS)
280 int save_errno = errno;
283 /* if we are waiting for input, longjmp out of it */
284 if (sigint_interrupt_enabled)
286 sigint_interrupt_enabled = false;
287 siglongjmp(sigint_interrupt_jmp, 1);
290 /* else, set cancel flag to stop any long-running loops */
291 cancel_pressed = true;
293 /* and send QueryCancel if we are processing a database query */
294 if (cancelConn != NULL)
296 if (PQcancel(cancelConn, errbuf, sizeof(errbuf)))
297 write_stderr("Cancel request sent\n");
300 write_stderr("Could not send cancel request: ");
301 write_stderr(errbuf);
305 errno = save_errno; /* just in case the write changed it */
309 setup_cancel_handler(void)
311 pqsignal(SIGINT, handle_sigint);
316 consoleHandler(DWORD dwCtrlType)
320 if (dwCtrlType == CTRL_C_EVENT ||
321 dwCtrlType == CTRL_BREAK_EVENT)
324 * Can't longjmp here, because we are in wrong thread :-(
327 /* set cancel flag to stop any long-running loops */
328 cancel_pressed = true;
330 /* and send QueryCancel if we are processing a database query */
331 EnterCriticalSection(&cancelConnLock);
332 if (cancelConn != NULL)
334 if (PQcancel(cancelConn, errbuf, sizeof(errbuf)))
335 write_stderr("Cancel request sent\n");
338 write_stderr("Could not send cancel request: ");
339 write_stderr(errbuf);
342 LeaveCriticalSection(&cancelConnLock);
347 /* Return FALSE for any signals not being handled */
352 setup_cancel_handler(void)
354 InitializeCriticalSection(&cancelConnLock);
356 SetConsoleCtrlHandler(consoleHandler, TRUE);
363 * Returns whether our backend connection is still there.
368 return PQstatus(pset.db) != CONNECTION_BAD;
375 * Verify that we still have a good connection to the backend, and if not,
376 * see if it can be restored.
378 * Returns true if either the connection was still there, or it could be
379 * restored successfully; false otherwise. If, however, there was no
380 * connection and the session is non-interactive, this will exit the program
381 * with a code of EXIT_BADCONN.
384 CheckConnection(void)
391 if (!pset.cur_cmd_interactive)
393 pg_log_fatal("connection to server was lost");
397 fprintf(stderr, _("The connection to the server was lost. Attempting reset: "));
402 fprintf(stderr, _("Failed.\n"));
405 * Transition to having no connection. Keep this bit in sync with
415 fprintf(stderr, _("Succeeded.\n"));
418 * Re-sync, just in case anything changed. Keep this in sync with
422 connection_warnings(false); /* Must be after SyncVariables */
434 * Set cancelConn to point to the current database connection.
439 PGcancel *oldCancelConn;
442 EnterCriticalSection(&cancelConnLock);
445 /* Free the old one if we have one */
446 oldCancelConn = cancelConn;
447 /* be sure handle_sigint doesn't use pointer while freeing */
450 if (oldCancelConn != NULL)
451 PQfreeCancel(oldCancelConn);
453 cancelConn = PQgetCancel(pset.db);
456 LeaveCriticalSection(&cancelConnLock);
464 * Free the current cancel connection, if any, and set to NULL.
467 ResetCancelConn(void)
469 PGcancel *oldCancelConn;
472 EnterCriticalSection(&cancelConnLock);
475 oldCancelConn = cancelConn;
476 /* be sure handle_sigint doesn't use pointer while freeing */
479 if (oldCancelConn != NULL)
480 PQfreeCancel(oldCancelConn);
483 LeaveCriticalSection(&cancelConnLock);
491 * Checks whether a result is valid, giving an error message if necessary;
492 * and ensures that the connection to the backend is still up.
494 * Returns true for valid result, false for error state.
497 AcceptResult(const PGresult *result)
504 switch (PQresultStatus(result))
506 case PGRES_COMMAND_OK:
507 case PGRES_TUPLES_OK:
508 case PGRES_EMPTY_QUERY:
511 /* Fine, do nothing */
515 case PGRES_BAD_RESPONSE:
516 case PGRES_NONFATAL_ERROR:
517 case PGRES_FATAL_ERROR:
523 pg_log_error("unexpected PQresultStatus: %d",
524 PQresultStatus(result));
530 const char *error = PQerrorMessage(pset.db);
533 pg_log_info("%s", error);
543 * Set special variables from a query result
544 * - ERROR: true/false, whether an error occurred on this query
545 * - SQLSTATE: code of error, or "00000" if no error, or "" if unknown
546 * - ROW_COUNT: how many rows were returned or affected, or "0"
547 * - LAST_ERROR_SQLSTATE: same for last error
548 * - LAST_ERROR_MESSAGE: message of last error
550 * Note: current policy is to apply this only to the results of queries
551 * entered by the user, not queries generated by slash commands.
554 SetResultVariables(PGresult *results, bool success)
558 const char *ntuples = PQcmdTuples(results);
560 SetVariable(pset.vars, "ERROR", "false");
561 SetVariable(pset.vars, "SQLSTATE", "00000");
562 SetVariable(pset.vars, "ROW_COUNT", *ntuples ? ntuples : "0");
566 const char *code = PQresultErrorField(results, PG_DIAG_SQLSTATE);
567 const char *mesg = PQresultErrorField(results, PG_DIAG_MESSAGE_PRIMARY);
569 SetVariable(pset.vars, "ERROR", "true");
572 * If there is no SQLSTATE code, use an empty string. This can happen
573 * for libpq-detected errors (e.g., lost connection, ENOMEM).
577 SetVariable(pset.vars, "SQLSTATE", code);
578 SetVariable(pset.vars, "ROW_COUNT", "0");
579 SetVariable(pset.vars, "LAST_ERROR_SQLSTATE", code);
580 SetVariable(pset.vars, "LAST_ERROR_MESSAGE", mesg ? mesg : "");
588 * If the result represents an error, remember it for possible display by
589 * \errverbose. Otherwise, just PQclear() it.
591 * Note: current policy is to apply this to the results of all queries,
592 * including "back door" queries, for debugging's sake. It's OK to use
593 * PQclear() directly on results known to not be error results, however.
596 ClearOrSaveResult(PGresult *result)
600 switch (PQresultStatus(result))
602 case PGRES_NONFATAL_ERROR:
603 case PGRES_FATAL_ERROR:
604 if (pset.last_error_result)
605 PQclear(pset.last_error_result);
606 pset.last_error_result = result;
618 * Print microtiming output. Always print raw milliseconds; if the interval
619 * is >= 1 second, also break it down into days/hours/minutes/seconds.
622 PrintTiming(double elapsed_msec)
629 if (elapsed_msec < 1000.0)
631 /* This is the traditional (pre-v10) output format */
632 printf(_("Time: %.3f ms\n"), elapsed_msec);
637 * Note: we could print just seconds, in a format like %06.3f, when the
638 * total is less than 1min. But that's hard to interpret unless we tack
639 * on "s" or otherwise annotate it. Forcing the display to include
640 * minutes seems like a better solution.
642 seconds = elapsed_msec / 1000.0;
643 minutes = floor(seconds / 60.0);
644 seconds -= 60.0 * minutes;
647 printf(_("Time: %.3f ms (%02d:%06.3f)\n"),
648 elapsed_msec, (int) minutes, seconds);
652 hours = floor(minutes / 60.0);
653 minutes -= 60.0 * hours;
656 printf(_("Time: %.3f ms (%02d:%02d:%06.3f)\n"),
657 elapsed_msec, (int) hours, (int) minutes, seconds);
661 days = floor(hours / 24.0);
662 hours -= 24.0 * days;
663 printf(_("Time: %.3f ms (%.0f d %02d:%02d:%06.3f)\n"),
664 elapsed_msec, days, (int) hours, (int) minutes, seconds);
671 * This is the way to send "backdoor" queries (those not directly entered
672 * by the user). It is subject to -E but not -e.
674 * Caller is responsible for handling the ensuing processing if a COPY
677 * Note: we don't bother to check PQclientEncoding; it is assumed that no
678 * caller uses this path to issue "SET CLIENT_ENCODING".
681 PSQLexec(const char *query)
687 pg_log_error("You are currently not connected to a database.");
691 if (pset.echo_hidden != PSQL_ECHO_HIDDEN_OFF)
693 printf(_("********* QUERY **********\n"
695 "**************************\n\n"), query);
699 fprintf(pset.logfile,
700 _("********* QUERY **********\n"
702 "**************************\n\n"), query);
703 fflush(pset.logfile);
706 if (pset.echo_hidden == PSQL_ECHO_HIDDEN_NOEXEC)
712 res = PQexec(pset.db, query);
716 if (!AcceptResult(res))
718 ClearOrSaveResult(res);
729 * This function is used for \watch command to send the query to
730 * the server and print out the results.
732 * Returns 1 if the query executed successfully, 0 if it cannot be repeated,
733 * e.g., because of the interrupt, -1 on error.
736 PSQLexecWatch(const char *query, const printQueryOpt *opt)
739 double elapsed_msec = 0;
745 pg_log_error("You are currently not connected to a database.");
752 INSTR_TIME_SET_CURRENT(before);
754 res = PQexec(pset.db, query);
758 if (!AcceptResult(res))
760 ClearOrSaveResult(res);
766 INSTR_TIME_SET_CURRENT(after);
767 INSTR_TIME_SUBTRACT(after, before);
768 elapsed_msec = INSTR_TIME_GET_MILLISEC(after);
772 * If SIGINT is sent while the query is processing, the interrupt will be
773 * consumed. The user's intention, though, is to cancel the entire watch
774 * process, so detect a sent cancellation request and exit in this case.
782 switch (PQresultStatus(res))
784 case PGRES_TUPLES_OK:
785 printQuery(res, opt, pset.queryFout, false, pset.logfile);
788 case PGRES_COMMAND_OK:
789 fprintf(pset.queryFout, "%s\n%s\n\n", opt->title, PQcmdStatus(res));
792 case PGRES_EMPTY_QUERY:
793 pg_log_error("\\watch cannot be used with an empty query");
799 case PGRES_COPY_BOTH:
800 pg_log_error("\\watch cannot be used with COPY");
805 pg_log_error("unexpected result status for \\watch");
812 fflush(pset.queryFout);
814 /* Possible microtiming output */
816 PrintTiming(elapsed_msec);
823 * PrintNotifications: check for asynchronous notifications, and print them out
826 PrintNotifications(void)
830 PQconsumeInput(pset.db);
831 while ((notify = PQnotifies(pset.db)) != NULL)
833 /* for backward compatibility, only show payload if nonempty */
834 if (notify->extra[0])
835 fprintf(pset.queryFout, _("Asynchronous notification \"%s\" with payload \"%s\" received from server process with PID %d.\n"),
836 notify->relname, notify->extra, notify->be_pid);
838 fprintf(pset.queryFout, _("Asynchronous notification \"%s\" received from server process with PID %d.\n"),
839 notify->relname, notify->be_pid);
840 fflush(pset.queryFout);
842 PQconsumeInput(pset.db);
848 * PrintQueryTuples: assuming query result is OK, print its tuples
850 * Returns true if successful, false otherwise.
853 PrintQueryTuples(const PGresult *results)
855 printQueryOpt my_popt = pset.popt;
857 /* one-shot expanded output requested via \gx */
859 my_popt.topt.expanded = 1;
861 /* write output to \g argument, if any */
867 if (!openQueryOutputFile(pset.gfname, &fout, &is_pipe))
870 disable_sigpipe_trap();
872 printQuery(results, &my_popt, fout, false, pset.logfile);
877 restore_sigpipe_trap();
883 printQuery(results, &my_popt, pset.queryFout, false, pset.logfile);
890 * StoreQueryTuple: assuming query result is OK, save data into variables
892 * Returns true if successful, false otherwise.
895 StoreQueryTuple(const PGresult *result)
899 if (PQntuples(result) < 1)
901 pg_log_error("no rows returned for \\gset");
904 else if (PQntuples(result) > 1)
906 pg_log_error("more than one row returned for \\gset");
913 for (i = 0; i < PQnfields(result); i++)
915 char *colname = PQfname(result, i);
919 /* concatenate prefix and column name */
920 varname = psprintf("%s%s", pset.gset_prefix, colname);
922 if (!PQgetisnull(result, 0, i))
923 value = PQgetvalue(result, 0, i);
926 /* for NULL value, unset rather than set the variable */
930 if (!SetVariable(pset.vars, varname, value))
946 * ExecQueryTuples: assuming query result is OK, execute each query
947 * result field as a SQL statement
949 * Returns true if successful, false otherwise.
952 ExecQueryTuples(const PGresult *result)
955 int nrows = PQntuples(result);
956 int ncolumns = PQnfields(result);
961 * We must turn off gexec_flag to avoid infinite recursion. Note that
962 * this allows ExecQueryUsingCursor to be applied to the individual query
963 * results. SendQuery prevents it from being applied when fetching the
964 * queries-to-execute, because it can't handle recursion either.
966 pset.gexec_flag = false;
968 for (r = 0; r < nrows; r++)
970 for (c = 0; c < ncolumns; c++)
972 if (!PQgetisnull(result, r, c))
974 const char *query = PQgetvalue(result, r, c);
976 /* Abandon execution if cancel_pressed */
981 * ECHO_ALL mode should echo these queries, but SendQuery
982 * assumes that MainLoop did that, so we have to do it here.
984 if (pset.echo == PSQL_ECHO_ALL && !pset.singlestep)
990 if (!SendQuery(query))
992 /* Error - abandon execution if ON_ERROR_STOP */
994 if (pset.on_error_stop)
1004 * Restore state. We know gexec_flag was on, else we'd not be here. (We
1005 * also know it'll get turned off at end of command, but that's not ours
1008 pset.gexec_flag = true;
1010 /* Return true if all queries were successful */
1016 * ProcessResult: utility function for use by SendQuery() only
1018 * When our command string contained a COPY FROM STDIN or COPY TO STDOUT,
1019 * PQexec() has stopped at the PGresult associated with the first such
1020 * command. In that event, we'll marshal data for the COPY and then cycle
1021 * through any subsequent PGresult objects.
1023 * When the command string contained no such COPY command, this function
1024 * degenerates to an AcceptResult() call.
1026 * Changes its argument to point to the last PGresult of the command string,
1027 * or NULL if that result was for a COPY TO STDOUT. (Returning NULL prevents
1028 * the command status from being printed, which we want in that case so that
1029 * the status line doesn't get taken as part of the COPY data.)
1031 * Returns true on complete success, false otherwise. Possible failure modes
1032 * include purely client-side problems; check the transaction status for the
1033 * server-side opinion.
1036 ProcessResult(PGresult **results)
1038 bool success = true;
1039 bool first_cycle = true;
1043 ExecStatusType result_status;
1045 PGresult *next_result;
1047 if (!AcceptResult(*results))
1050 * Failure at this point is always a server-side failure or a
1051 * failure to submit the command string. Either way, we're
1052 * finished with this command string.
1058 result_status = PQresultStatus(*results);
1059 switch (result_status)
1061 case PGRES_EMPTY_QUERY:
1062 case PGRES_COMMAND_OK:
1063 case PGRES_TUPLES_OK:
1067 case PGRES_COPY_OUT:
1073 /* AcceptResult() should have caught anything else. */
1075 pg_log_error("unexpected PQresultStatus: %d", result_status);
1082 * Marshal the COPY data. Either subroutine will get the
1083 * connection out of its COPY state, then call PQresultStatus()
1084 * once and report any error.
1086 * For COPY OUT, direct the output to pset.copyStream if it's set,
1087 * otherwise to pset.gfname if it's set, otherwise to queryFout.
1088 * For COPY IN, use pset.copyStream as data source if it's set,
1089 * otherwise cur_cmd_source.
1092 PGresult *copy_result;
1095 if (result_status == PGRES_COPY_OUT)
1097 bool need_close = false;
1098 bool is_pipe = false;
1100 if (pset.copyStream)
1102 /* invoked by \copy */
1103 copystream = pset.copyStream;
1105 else if (pset.gfname)
1108 if (openQueryOutputFile(pset.gfname,
1109 ©stream, &is_pipe))
1113 disable_sigpipe_trap();
1116 copystream = NULL; /* discard COPY data entirely */
1120 /* fall back to the generic query output stream */
1121 copystream = pset.queryFout;
1124 success = handleCopyOut(pset.db,
1128 && (copystream != NULL);
1131 * Suppress status printing if the report would go to the same
1132 * place as the COPY data just went. Note this doesn't
1133 * prevent error reporting, since handleCopyOut did that.
1135 if (copystream == pset.queryFout)
1137 PQclear(copy_result);
1143 /* close \g argument file/pipe */
1147 restore_sigpipe_trap();
1158 copystream = pset.copyStream ? pset.copyStream : pset.cur_cmd_source;
1159 success = handleCopyIn(pset.db,
1161 PQbinaryTuples(*results),
1162 ©_result) && success;
1167 * Replace the PGRES_COPY_OUT/IN result with COPY command's exit
1168 * status, or with NULL if we want to suppress printing anything.
1171 *results = copy_result;
1173 else if (first_cycle)
1175 /* fast path: no COPY commands; PQexec visited all results */
1180 * Check PQgetResult() again. In the typical case of a single-command
1181 * string, it will return NULL. Otherwise, we'll have other results
1182 * to process that may include other COPYs. We keep the last result.
1184 next_result = PQgetResult(pset.db);
1189 *results = next_result;
1190 first_cycle = false;
1193 SetResultVariables(*results, success);
1195 /* may need this to recover from conn loss during COPY */
1196 if (!first_cycle && !CheckConnection())
1204 * PrintQueryStatus: report command status as required
1206 * Note: Utility function for use by PrintQueryResults() only.
1209 PrintQueryStatus(PGresult *results)
1215 if (pset.popt.topt.format == PRINT_HTML)
1217 fputs("<p>", pset.queryFout);
1218 html_escaped_print(PQcmdStatus(results), pset.queryFout);
1219 fputs("</p>\n", pset.queryFout);
1222 fprintf(pset.queryFout, "%s\n", PQcmdStatus(results));
1226 fprintf(pset.logfile, "%s\n", PQcmdStatus(results));
1228 snprintf(buf, sizeof(buf), "%u", (unsigned int) PQoidValue(results));
1229 SetVariable(pset.vars, "LASTOID", buf);
1234 * PrintQueryResults: print out (or store or execute) query results as required
1236 * Note: Utility function for use by SendQuery() only.
1238 * Returns true if the query executed successfully, false otherwise.
1241 PrintQueryResults(PGresult *results)
1244 const char *cmdstatus;
1249 switch (PQresultStatus(results))
1251 case PGRES_TUPLES_OK:
1252 /* store or execute or print the data ... */
1253 if (pset.gset_prefix)
1254 success = StoreQueryTuple(results);
1255 else if (pset.gexec_flag)
1256 success = ExecQueryTuples(results);
1257 else if (pset.crosstab_flag)
1258 success = PrintResultsInCrosstab(results);
1260 success = PrintQueryTuples(results);
1261 /* if it's INSERT/UPDATE/DELETE RETURNING, also print status */
1262 cmdstatus = PQcmdStatus(results);
1263 if (strncmp(cmdstatus, "INSERT", 6) == 0 ||
1264 strncmp(cmdstatus, "UPDATE", 6) == 0 ||
1265 strncmp(cmdstatus, "DELETE", 6) == 0)
1266 PrintQueryStatus(results);
1269 case PGRES_COMMAND_OK:
1270 PrintQueryStatus(results);
1274 case PGRES_EMPTY_QUERY:
1278 case PGRES_COPY_OUT:
1280 /* nothing to do here */
1284 case PGRES_BAD_RESPONSE:
1285 case PGRES_NONFATAL_ERROR:
1286 case PGRES_FATAL_ERROR:
1292 pg_log_error("unexpected PQresultStatus: %d",
1293 PQresultStatus(results));
1297 fflush(pset.queryFout);
1304 * SendQuery: send the query string to the backend
1305 * (and print out results)
1307 * Note: This is the "front door" way to send a query. That is, use it to
1308 * send queries actually entered by the user. These queries will be subject to
1310 * To send "back door" queries (generated by slash commands, etc.) in a
1311 * controlled way, use PSQLexec().
1313 * Returns true if the query executed successfully, false otherwise.
1316 SendQuery(const char *query)
1319 PGTransactionStatusType transaction_status;
1320 double elapsed_msec = 0;
1323 bool on_error_rollback_savepoint = false;
1324 static bool on_error_rollback_warning = false;
1328 pg_log_error("You are currently not connected to a database.");
1329 goto sendquery_cleanup;
1332 if (pset.singlestep)
1337 printf(_("***(Single step mode: verify command)*******************************************\n"
1339 "***(press return to proceed or enter x and return to cancel)********************\n"),
1342 if (fgets(buf, sizeof(buf), stdin) != NULL)
1344 goto sendquery_cleanup;
1346 goto sendquery_cleanup;
1348 else if (pset.echo == PSQL_ECHO_QUERIES)
1356 fprintf(pset.logfile,
1357 _("********* QUERY **********\n"
1359 "**************************\n\n"), query);
1360 fflush(pset.logfile);
1365 transaction_status = PQtransactionStatus(pset.db);
1367 if (transaction_status == PQTRANS_IDLE &&
1369 !command_no_begin(query))
1371 results = PQexec(pset.db, "BEGIN");
1372 if (PQresultStatus(results) != PGRES_COMMAND_OK)
1374 pg_log_info("%s", PQerrorMessage(pset.db));
1375 ClearOrSaveResult(results);
1377 goto sendquery_cleanup;
1379 ClearOrSaveResult(results);
1380 transaction_status = PQtransactionStatus(pset.db);
1383 if (transaction_status == PQTRANS_INTRANS &&
1384 pset.on_error_rollback != PSQL_ERROR_ROLLBACK_OFF &&
1385 (pset.cur_cmd_interactive ||
1386 pset.on_error_rollback == PSQL_ERROR_ROLLBACK_ON))
1388 if (on_error_rollback_warning == false && pset.sversion < 80000)
1392 pg_log_warning("The server (version %s) does not support savepoints for ON_ERROR_ROLLBACK.",
1393 formatPGVersionNumber(pset.sversion, false,
1394 sverbuf, sizeof(sverbuf)));
1395 on_error_rollback_warning = true;
1399 results = PQexec(pset.db, "SAVEPOINT pg_psql_temporary_savepoint");
1400 if (PQresultStatus(results) != PGRES_COMMAND_OK)
1402 pg_log_info("%s", PQerrorMessage(pset.db));
1403 ClearOrSaveResult(results);
1405 goto sendquery_cleanup;
1407 ClearOrSaveResult(results);
1408 on_error_rollback_savepoint = true;
1412 if (pset.gdesc_flag)
1414 /* Describe query's result columns, without executing it */
1415 OK = DescribeQuery(query, &elapsed_msec);
1417 results = NULL; /* PQclear(NULL) does nothing */
1419 else if (pset.fetch_count <= 0 || pset.gexec_flag ||
1420 pset.crosstab_flag || !is_select_command(query))
1422 /* Default fetch-it-all-and-print mode */
1427 INSTR_TIME_SET_CURRENT(before);
1429 results = PQexec(pset.db, query);
1431 /* these operations are included in the timing result: */
1433 OK = ProcessResult(&results);
1437 INSTR_TIME_SET_CURRENT(after);
1438 INSTR_TIME_SUBTRACT(after, before);
1439 elapsed_msec = INSTR_TIME_GET_MILLISEC(after);
1442 /* but printing results isn't: */
1444 OK = PrintQueryResults(results);
1448 /* Fetch-in-segments mode */
1449 OK = ExecQueryUsingCursor(query, &elapsed_msec);
1451 results = NULL; /* PQclear(NULL) does nothing */
1454 if (!OK && pset.echo == PSQL_ECHO_ERRORS)
1455 pg_log_info("STATEMENT: %s", query);
1457 /* If we made a temporary savepoint, possibly release/rollback */
1458 if (on_error_rollback_savepoint)
1460 const char *svptcmd = NULL;
1462 transaction_status = PQtransactionStatus(pset.db);
1464 switch (transaction_status)
1466 case PQTRANS_INERROR:
1467 /* We always rollback on an error */
1468 svptcmd = "ROLLBACK TO pg_psql_temporary_savepoint";
1472 /* If they are no longer in a transaction, then do nothing */
1475 case PQTRANS_INTRANS:
1478 * Do nothing if they are messing with savepoints themselves:
1479 * If the user did RELEASE or ROLLBACK, our savepoint is gone.
1480 * If they issued a SAVEPOINT, releasing ours would remove
1484 (strcmp(PQcmdStatus(results), "SAVEPOINT") == 0 ||
1485 strcmp(PQcmdStatus(results), "RELEASE") == 0 ||
1486 strcmp(PQcmdStatus(results), "ROLLBACK") == 0))
1489 svptcmd = "RELEASE pg_psql_temporary_savepoint";
1492 case PQTRANS_ACTIVE:
1493 case PQTRANS_UNKNOWN:
1496 /* PQTRANS_UNKNOWN is expected given a broken connection. */
1497 if (transaction_status != PQTRANS_UNKNOWN || ConnectionUp())
1498 pg_log_error("unexpected transaction status (%d)",
1499 transaction_status);
1507 svptres = PQexec(pset.db, svptcmd);
1508 if (PQresultStatus(svptres) != PGRES_COMMAND_OK)
1510 pg_log_info("%s", PQerrorMessage(pset.db));
1511 ClearOrSaveResult(svptres);
1516 goto sendquery_cleanup;
1522 ClearOrSaveResult(results);
1524 /* Possible microtiming output */
1526 PrintTiming(elapsed_msec);
1528 /* check for events that may occur during query execution */
1530 if (pset.encoding != PQclientEncoding(pset.db) &&
1531 PQclientEncoding(pset.db) >= 0)
1533 /* track effects of SET CLIENT_ENCODING */
1534 pset.encoding = PQclientEncoding(pset.db);
1535 pset.popt.topt.encoding = pset.encoding;
1536 SetVariable(pset.vars, "ENCODING",
1537 pg_encoding_to_char(pset.encoding));
1540 PrintNotifications();
1542 /* perform cleanup that should occur after any attempted query */
1546 /* reset \g's output-to-filename trigger */
1553 /* reset \gx's expanded-mode flag */
1554 pset.g_expanded = false;
1556 /* reset \gset trigger */
1557 if (pset.gset_prefix)
1559 free(pset.gset_prefix);
1560 pset.gset_prefix = NULL;
1563 /* reset \gdesc trigger */
1564 pset.gdesc_flag = false;
1566 /* reset \gexec trigger */
1567 pset.gexec_flag = false;
1569 /* reset \crosstabview trigger */
1570 pset.crosstab_flag = false;
1571 for (i = 0; i < lengthof(pset.ctv_args); i++)
1573 pg_free(pset.ctv_args[i]);
1574 pset.ctv_args[i] = NULL;
1582 * DescribeQuery: describe the result columns of a query, without executing it
1584 * Returns true if the operation executed successfully, false otherwise.
1586 * If pset.timing is on, total query time (exclusive of result-printing) is
1587 * stored into *elapsed_msec.
1590 DescribeQuery(const char *query, double *elapsed_msec)
1600 INSTR_TIME_SET_CURRENT(before);
1603 * To parse the query but not execute it, we prepare it, using the unnamed
1604 * prepared statement. This is invisible to psql users, since there's no
1605 * way to access the unnamed prepared statement from psql user space. The
1606 * next Parse or Query protocol message would overwrite the statement
1607 * anyway. (So there's no great need to clear it when done, which is a
1608 * good thing because libpq provides no easy way to do that.)
1610 results = PQprepare(pset.db, "", query, 0, NULL);
1611 if (PQresultStatus(results) != PGRES_COMMAND_OK)
1613 pg_log_info("%s", PQerrorMessage(pset.db));
1614 SetResultVariables(results, false);
1615 ClearOrSaveResult(results);
1620 results = PQdescribePrepared(pset.db, "");
1621 OK = AcceptResult(results) &&
1622 (PQresultStatus(results) == PGRES_COMMAND_OK);
1625 if (PQnfields(results) > 0)
1627 PQExpBufferData buf;
1630 initPQExpBuffer(&buf);
1632 printfPQExpBuffer(&buf,
1633 "SELECT name AS \"%s\", pg_catalog.format_type(tp, tpm) AS \"%s\"\n"
1635 gettext_noop("Column"),
1636 gettext_noop("Type"));
1638 for (i = 0; i < PQnfields(results); i++)
1644 appendPQExpBufferStr(&buf, ",");
1646 name = PQfname(results, i);
1647 escname = PQescapeLiteral(pset.db, name, strlen(name));
1649 if (escname == NULL)
1651 pg_log_info("%s", PQerrorMessage(pset.db));
1653 termPQExpBuffer(&buf);
1657 appendPQExpBuffer(&buf, "(%s, '%u'::pg_catalog.oid, %d)",
1659 PQftype(results, i),
1660 PQfmod(results, i));
1665 appendPQExpBufferStr(&buf, ") s(name, tp, tpm)");
1668 results = PQexec(pset.db, buf.data);
1669 OK = AcceptResult(results);
1673 INSTR_TIME_SET_CURRENT(after);
1674 INSTR_TIME_SUBTRACT(after, before);
1675 *elapsed_msec += INSTR_TIME_GET_MILLISEC(after);
1679 OK = PrintQueryResults(results);
1681 termPQExpBuffer(&buf);
1684 fprintf(pset.queryFout,
1685 _("The command has no result, or the result has no columns.\n"));
1688 SetResultVariables(results, OK);
1689 ClearOrSaveResult(results);
1696 * ExecQueryUsingCursor: run a SELECT-like query using a cursor
1698 * This feature allows result sets larger than RAM to be dealt with.
1700 * Returns true if the query executed successfully, false otherwise.
1702 * If pset.timing is on, total query time (exclusive of result-printing) is
1703 * stored into *elapsed_msec.
1706 ExecQueryUsingCursor(const char *query, double *elapsed_msec)
1710 PQExpBufferData buf;
1711 printQueryOpt my_popt = pset.popt;
1714 bool is_pager = false;
1715 bool started_txn = false;
1716 int64 total_tuples = 0;
1726 /* initialize print options for partial table output */
1727 my_popt.topt.start_table = true;
1728 my_popt.topt.stop_table = false;
1729 my_popt.topt.prior_records = 0;
1732 INSTR_TIME_SET_CURRENT(before);
1734 /* if we're not in a transaction, start one */
1735 if (PQtransactionStatus(pset.db) == PQTRANS_IDLE)
1737 results = PQexec(pset.db, "BEGIN");
1738 OK = AcceptResult(results) &&
1739 (PQresultStatus(results) == PGRES_COMMAND_OK);
1740 ClearOrSaveResult(results);
1746 /* Send DECLARE CURSOR */
1747 initPQExpBuffer(&buf);
1748 appendPQExpBuffer(&buf, "DECLARE _psql_cursor NO SCROLL CURSOR FOR\n%s",
1751 results = PQexec(pset.db, buf.data);
1752 OK = AcceptResult(results) &&
1753 (PQresultStatus(results) == PGRES_COMMAND_OK);
1755 SetResultVariables(results, OK);
1756 ClearOrSaveResult(results);
1757 termPQExpBuffer(&buf);
1763 INSTR_TIME_SET_CURRENT(after);
1764 INSTR_TIME_SUBTRACT(after, before);
1765 *elapsed_msec += INSTR_TIME_GET_MILLISEC(after);
1769 * In \gset mode, we force the fetch count to be 2, so that we will throw
1770 * the appropriate error if the query returns more than one row.
1772 if (pset.gset_prefix)
1775 fetch_count = pset.fetch_count;
1777 snprintf(fetch_cmd, sizeof(fetch_cmd),
1778 "FETCH FORWARD %d FROM _psql_cursor",
1781 /* one-shot expanded output requested via \gx */
1782 if (pset.g_expanded)
1783 my_popt.topt.expanded = 1;
1785 /* prepare to write output to \g argument, if any */
1788 if (!openQueryOutputFile(pset.gfname, &fout, &is_pipe))
1794 disable_sigpipe_trap();
1798 fout = pset.queryFout;
1799 is_pipe = false; /* doesn't matter */
1802 /* clear any pre-existing error indication on the output stream */
1808 INSTR_TIME_SET_CURRENT(before);
1810 /* get fetch_count tuples at a time */
1811 results = PQexec(pset.db, fetch_cmd);
1815 INSTR_TIME_SET_CURRENT(after);
1816 INSTR_TIME_SUBTRACT(after, before);
1817 *elapsed_msec += INSTR_TIME_GET_MILLISEC(after);
1820 if (PQresultStatus(results) != PGRES_TUPLES_OK)
1822 /* shut down pager before printing error message */
1829 OK = AcceptResult(results);
1831 SetResultVariables(results, OK);
1832 ClearOrSaveResult(results);
1836 if (pset.gset_prefix)
1838 /* StoreQueryTuple will complain if not exactly one row */
1839 OK = StoreQueryTuple(results);
1840 ClearOrSaveResult(results);
1845 * Note we do not deal with \gdesc, \gexec or \crosstabview modes here
1848 ntuples = PQntuples(results);
1849 total_tuples += ntuples;
1851 if (ntuples < fetch_count)
1853 /* this is the last result set, so allow footer decoration */
1854 my_popt.topt.stop_table = true;
1856 else if (fout == stdout && !is_pager)
1859 * If query requires multiple result sets, hack to ensure that
1860 * only one pager instance is used for the whole mess
1862 fout = PageOutput(INT_MAX, &(my_popt.topt));
1866 printQuery(results, &my_popt, fout, is_pager, pset.logfile);
1868 ClearOrSaveResult(results);
1870 /* after the first result set, disallow header decoration */
1871 my_popt.topt.start_table = false;
1872 my_popt.topt.prior_records += ntuples;
1875 * Make sure to flush the output stream, so intermediate results are
1876 * visible to the client immediately. We check the results because if
1877 * the pager dies/exits/etc, there's no sense throwing more data at
1880 flush_error = fflush(fout);
1883 * Check if we are at the end, if a cancel was pressed, or if there
1884 * were any errors either trying to flush out the results, or more
1885 * generally on the output stream at all. If we hit any errors
1886 * writing things to the stream, we presume $PAGER has disappeared and
1887 * stop bothering to pull down more data.
1889 if (ntuples < fetch_count || cancel_pressed || flush_error ||
1896 /* close \g argument file/pipe */
1900 restore_sigpipe_trap();
1907 /* close transient pager */
1914 * We don't have a PGresult here, and even if we did it wouldn't have
1915 * the right row count, so fake SetResultVariables(). In error cases,
1916 * we already set the result variables above.
1920 SetVariable(pset.vars, "ERROR", "false");
1921 SetVariable(pset.vars, "SQLSTATE", "00000");
1922 snprintf(buf, sizeof(buf), INT64_FORMAT, total_tuples);
1923 SetVariable(pset.vars, "ROW_COUNT", buf);
1928 INSTR_TIME_SET_CURRENT(before);
1931 * We try to close the cursor on either success or failure, but on failure
1932 * ignore the result (it's probably just a bleat about being in an aborted
1935 results = PQexec(pset.db, "CLOSE _psql_cursor");
1938 OK = AcceptResult(results) &&
1939 (PQresultStatus(results) == PGRES_COMMAND_OK);
1940 ClearOrSaveResult(results);
1947 results = PQexec(pset.db, OK ? "COMMIT" : "ROLLBACK");
1948 OK &= AcceptResult(results) &&
1949 (PQresultStatus(results) == PGRES_COMMAND_OK);
1950 ClearOrSaveResult(results);
1955 INSTR_TIME_SET_CURRENT(after);
1956 INSTR_TIME_SUBTRACT(after, before);
1957 *elapsed_msec += INSTR_TIME_GET_MILLISEC(after);
1965 * Advance the given char pointer over white space and SQL comments.
1968 skip_white_space(const char *query)
1970 int cnestlevel = 0; /* slash-star comment nest level */
1974 int mblen = PQmblen(query, pset.encoding);
1977 * Note: we assume the encoding is a superset of ASCII, so that for
1978 * example "query[0] == '/'" is meaningful. However, we do NOT assume
1979 * that the second and subsequent bytes of a multibyte character
1980 * couldn't look like ASCII characters; so it is critical to advance
1981 * by mblen, not 1, whenever we haven't exactly identified the
1982 * character we are skipping over.
1984 if (isspace((unsigned char) *query))
1986 else if (query[0] == '/' && query[1] == '*')
1991 else if (cnestlevel > 0 && query[0] == '*' && query[1] == '/')
1996 else if (cnestlevel == 0 && query[0] == '-' && query[1] == '-')
2001 * We have to skip to end of line since any slash-star inside the
2002 * -- comment does NOT start a slash-star comment.
2011 query += PQmblen(query, pset.encoding);
2014 else if (cnestlevel > 0)
2017 break; /* found first token */
2025 * Check whether a command is one of those for which we should NOT start
2026 * a new transaction block (ie, send a preceding BEGIN).
2028 * These include the transaction control statements themselves, plus
2029 * certain statements that the backend disallows inside transaction blocks.
2032 command_no_begin(const char *query)
2037 * First we must advance over any whitespace and comments.
2039 query = skip_white_space(query);
2042 * Check word length (since "beginx" is not "begin").
2045 while (isalpha((unsigned char) query[wordlen]))
2046 wordlen += PQmblen(&query[wordlen], pset.encoding);
2049 * Transaction control commands. These should include every keyword that
2050 * gives rise to a TransactionStmt in the backend grammar, except for the
2051 * savepoint-related commands.
2053 * (We assume that START must be START TRANSACTION, since there is
2054 * presently no other "START foo" command.)
2056 if (wordlen == 5 && pg_strncasecmp(query, "abort", 5) == 0)
2058 if (wordlen == 5 && pg_strncasecmp(query, "begin", 5) == 0)
2060 if (wordlen == 5 && pg_strncasecmp(query, "start", 5) == 0)
2062 if (wordlen == 6 && pg_strncasecmp(query, "commit", 6) == 0)
2064 if (wordlen == 3 && pg_strncasecmp(query, "end", 3) == 0)
2066 if (wordlen == 8 && pg_strncasecmp(query, "rollback", 8) == 0)
2068 if (wordlen == 7 && pg_strncasecmp(query, "prepare", 7) == 0)
2070 /* PREPARE TRANSACTION is a TC command, PREPARE foo is not */
2073 query = skip_white_space(query);
2076 while (isalpha((unsigned char) query[wordlen]))
2077 wordlen += PQmblen(&query[wordlen], pset.encoding);
2079 if (wordlen == 11 && pg_strncasecmp(query, "transaction", 11) == 0)
2085 * Commands not allowed within transactions. The statements checked for
2086 * here should be exactly those that call PreventInTransactionBlock() in
2089 if (wordlen == 6 && pg_strncasecmp(query, "vacuum", 6) == 0)
2091 if (wordlen == 7 && pg_strncasecmp(query, "cluster", 7) == 0)
2093 /* CLUSTER with any arguments is allowed in transactions */
2096 query = skip_white_space(query);
2098 if (isalpha((unsigned char) query[0]))
2099 return false; /* has additional words */
2100 return true; /* it's CLUSTER without arguments */
2103 if (wordlen == 6 && pg_strncasecmp(query, "create", 6) == 0)
2107 query = skip_white_space(query);
2110 while (isalpha((unsigned char) query[wordlen]))
2111 wordlen += PQmblen(&query[wordlen], pset.encoding);
2113 if (wordlen == 8 && pg_strncasecmp(query, "database", 8) == 0)
2115 if (wordlen == 10 && pg_strncasecmp(query, "tablespace", 10) == 0)
2118 /* CREATE [UNIQUE] INDEX CONCURRENTLY isn't allowed in xacts */
2119 if (wordlen == 6 && pg_strncasecmp(query, "unique", 6) == 0)
2123 query = skip_white_space(query);
2126 while (isalpha((unsigned char) query[wordlen]))
2127 wordlen += PQmblen(&query[wordlen], pset.encoding);
2130 if (wordlen == 5 && pg_strncasecmp(query, "index", 5) == 0)
2134 query = skip_white_space(query);
2137 while (isalpha((unsigned char) query[wordlen]))
2138 wordlen += PQmblen(&query[wordlen], pset.encoding);
2140 if (wordlen == 12 && pg_strncasecmp(query, "concurrently", 12) == 0)
2147 if (wordlen == 5 && pg_strncasecmp(query, "alter", 5) == 0)
2151 query = skip_white_space(query);
2154 while (isalpha((unsigned char) query[wordlen]))
2155 wordlen += PQmblen(&query[wordlen], pset.encoding);
2157 /* ALTER SYSTEM isn't allowed in xacts */
2158 if (wordlen == 6 && pg_strncasecmp(query, "system", 6) == 0)
2165 * Note: these tests will match DROP SYSTEM and REINDEX TABLESPACE, which
2166 * aren't really valid commands so we don't care much. The other four
2167 * possible matches are correct.
2169 if ((wordlen == 4 && pg_strncasecmp(query, "drop", 4) == 0) ||
2170 (wordlen == 7 && pg_strncasecmp(query, "reindex", 7) == 0))
2174 query = skip_white_space(query);
2177 while (isalpha((unsigned char) query[wordlen]))
2178 wordlen += PQmblen(&query[wordlen], pset.encoding);
2180 if (wordlen == 8 && pg_strncasecmp(query, "database", 8) == 0)
2182 if (wordlen == 6 && pg_strncasecmp(query, "system", 6) == 0)
2184 if (wordlen == 10 && pg_strncasecmp(query, "tablespace", 10) == 0)
2186 if (wordlen == 5 && (pg_strncasecmp(query, "index", 5) == 0 ||
2187 pg_strncasecmp(query, "table", 5) == 0))
2190 query = skip_white_space(query);
2192 while (isalpha((unsigned char) query[wordlen]))
2193 wordlen += PQmblen(&query[wordlen], pset.encoding);
2196 * REINDEX [ TABLE | INDEX ] CONCURRENTLY are not allowed in
2199 if (wordlen == 12 && pg_strncasecmp(query, "concurrently", 12) == 0)
2203 /* DROP INDEX CONCURRENTLY isn't allowed in xacts */
2204 if (wordlen == 5 && pg_strncasecmp(query, "index", 5) == 0)
2208 query = skip_white_space(query);
2211 while (isalpha((unsigned char) query[wordlen]))
2212 wordlen += PQmblen(&query[wordlen], pset.encoding);
2214 if (wordlen == 12 && pg_strncasecmp(query, "concurrently", 12) == 0)
2223 /* DISCARD ALL isn't allowed in xacts, but other variants are allowed. */
2224 if (wordlen == 7 && pg_strncasecmp(query, "discard", 7) == 0)
2228 query = skip_white_space(query);
2231 while (isalpha((unsigned char) query[wordlen]))
2232 wordlen += PQmblen(&query[wordlen], pset.encoding);
2234 if (wordlen == 3 && pg_strncasecmp(query, "all", 3) == 0)
2244 * Check whether the specified command is a SELECT (or VALUES).
2247 is_select_command(const char *query)
2252 * First advance over any whitespace, comments and left parentheses.
2256 query = skip_white_space(query);
2257 if (query[0] == '(')
2264 * Check word length (since "selectx" is not "select").
2267 while (isalpha((unsigned char) query[wordlen]))
2268 wordlen += PQmblen(&query[wordlen], pset.encoding);
2270 if (wordlen == 6 && pg_strncasecmp(query, "select", 6) == 0)
2273 if (wordlen == 6 && pg_strncasecmp(query, "values", 6) == 0)
2281 * Test if the current user is a database superuser.
2283 * Note: this will correctly detect superuserness only with a protocol-3.0
2284 * or newer backend; otherwise it will always say "false".
2294 val = PQparameterStatus(pset.db, "is_superuser");
2296 if (val && strcmp(val, "on") == 0)
2304 * Test if the current session uses standard string literals.
2306 * Note: With a pre-protocol-3.0 connection this will always say "false",
2307 * which should be the right answer.
2310 standard_strings(void)
2317 val = PQparameterStatus(pset.db, "standard_conforming_strings");
2319 if (val && strcmp(val, "on") == 0)
2327 * Return the session user of the current connection.
2329 * Note: this will correctly detect the session user only with a
2330 * protocol-3.0 or newer backend; otherwise it will return the
2334 session_username(void)
2341 val = PQparameterStatus(pset.db, "session_authorization");
2345 return PQuser(pset.db);
2351 * substitute '~' with HOME or '~username' with username's home dir
2355 expand_tilde(char **filename)
2357 if (!filename || !(*filename))
2361 * WIN32 doesn't use tilde expansion for file names. Also, it uses tilde
2362 * for short versions of long file names, though the tilde is usually
2363 * toward the end, not at the beginning.
2367 /* try tilde expansion */
2368 if (**filename == '~')
2374 char home[MAXPGPATH];
2380 while (*p != '/' && *p != '\0')
2386 if (*(fn + 1) == '\0')
2387 get_home_path(home); /* ~ or ~/ only */
2388 else if ((pw = getpwnam(fn + 1)) != NULL)
2389 strlcpy(home, pw->pw_dir, sizeof(home)); /* ~user */
2392 if (strlen(home) != 0)
2396 newfn = psprintf("%s%s", home, p);
2407 * Checks if connection string starts with either of the valid URI prefix
2410 * Returns the URI prefix length, 0 if the string doesn't contain a URI prefix.
2412 * XXX This is a duplicate of the eponymous libpq function.
2415 uri_prefix_length(const char *connstr)
2417 /* The connection URI must start with either of the following designators: */
2418 static const char uri_designator[] = "postgresql://";
2419 static const char short_uri_designator[] = "postgres://";
2421 if (strncmp(connstr, uri_designator,
2422 sizeof(uri_designator) - 1) == 0)
2423 return sizeof(uri_designator) - 1;
2425 if (strncmp(connstr, short_uri_designator,
2426 sizeof(short_uri_designator) - 1) == 0)
2427 return sizeof(short_uri_designator) - 1;
2433 * Recognized connection string either starts with a valid URI prefix or
2434 * contains a "=" in it.
2436 * Must be consistent with parse_connection_string: anything for which this
2437 * returns true should at least look like it's parseable by that routine.
2439 * XXX This is a duplicate of the eponymous libpq function.
2442 recognized_connection_string(const char *connstr)
2444 return uri_prefix_length(connstr) != 0 || strchr(connstr, '=') != NULL;