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() */
21 #include "common/logging.h"
22 #include "fe_utils/mbprint.h"
23 #include "fe_utils/string_utils.h"
24 #include "portability/instr_time.h"
29 #include "crosstabview.h"
33 static bool DescribeQuery(const char *query, double *elapsed_msec);
34 static bool ExecQueryUsingCursor(const char *query, double *elapsed_msec);
35 static bool command_no_begin(const char *query);
36 static bool is_select_command(const char *query);
40 * openQueryOutputFile --- attempt to open a query output file
42 * fname == NULL selects stdout, else an initial '|' selects a pipe,
45 * Returns output file pointer into *fout, and is-a-pipe flag into *is_pipe.
46 * Caller is responsible for adjusting SIGPIPE state if it's a pipe.
48 * On error, reports suitable error message and returns false.
51 openQueryOutputFile(const char *fname, FILE **fout, bool *is_pipe)
53 if (!fname || fname[0] == '\0')
58 else if (*fname == '|')
60 *fout = popen(fname + 1, "w");
65 *fout = fopen(fname, "w");
71 pg_log_error("%s: %m", fname);
80 * -- handler for -o command line option and \o command
82 * On success, updates pset with the new output file and returns true.
83 * On failure, returns false without changing pset state.
86 setQFout(const char *fname)
91 /* First make sure we can open the new output file/pipe */
92 if (!openQueryOutputFile(fname, &fout, &is_pipe))
95 /* Close old file/pipe */
96 if (pset.queryFout && pset.queryFout != stdout && pset.queryFout != stderr)
98 if (pset.queryFoutPipe)
99 pclose(pset.queryFout);
101 fclose(pset.queryFout);
104 pset.queryFout = fout;
105 pset.queryFoutPipe = is_pipe;
107 /* Adjust SIGPIPE handling appropriately: ignore signal if is_pipe */
108 set_sigpipe_trap_state(is_pipe);
109 restore_sigpipe_trap();
116 * Variable-fetching callback for flex lexer
118 * If the specified variable exists, return its value as a string (malloc'd
119 * and expected to be freed by the caller); else return NULL.
121 * If "quote" isn't PQUOTE_PLAIN, then return the value suitably quoted and
122 * escaped for the specified quoting requirement. (Failure in escaping
123 * should lead to printing an error and returning NULL.)
125 * "passthrough" is the pointer previously given to psql_scan_set_passthrough.
126 * In psql, passthrough points to a ConditionalStack, which we check to
127 * determine whether variable expansion is allowed.
130 psql_get_variable(const char *varname, PsqlScanQuoteType quote,
136 /* In an inactive \if branch, suppress all variable substitutions */
137 if (passthrough && !conditional_active((ConditionalStack) passthrough))
140 value = GetVariable(pset.vars, varname);
147 result = pg_strdup(value);
149 case PQUOTE_SQL_LITERAL:
150 case PQUOTE_SQL_IDENT:
153 * For these cases, we use libpq's quoting functions, which
154 * assume the string is in the connection's client encoding.
160 pg_log_error("cannot escape without active connection");
164 if (quote == PQUOTE_SQL_LITERAL)
166 PQescapeLiteral(pset.db, value, strlen(value));
169 PQescapeIdentifier(pset.db, value, strlen(value));
171 if (escaped_value == NULL)
173 const char *error = PQerrorMessage(pset.db);
175 pg_log_info("%s", error);
180 * Rather than complicate the lexer's API with a notion of
181 * which free() routine to use, just pay the price of an extra
184 result = pg_strdup(escaped_value);
185 PQfreemem(escaped_value);
188 case PQUOTE_SHELL_ARG:
191 * For this we use appendShellStringNoError, which is
192 * encoding-agnostic, which is fine since the shell probably
193 * is too. In any case, the only special character is "'",
194 * which is not known to appear in valid multibyte characters.
198 initPQExpBuffer(&buf);
199 if (!appendShellStringNoError(&buf, value))
201 pg_log_error("shell command argument contains a newline or carriage return: \"%s\"",
210 /* No default: we want a compiler warning for missing cases */
218 * for backend Notice messages (INFO, WARNING, etc)
221 NoticeProcessor(void *arg, const char *message)
223 (void) arg; /* not used */
224 pg_log_info("%s", message);
230 * Code to support query cancellation
232 * Before we start a query, we enable the SIGINT signal catcher to send a
233 * cancel request to the backend. Note that sending the cancel directly from
234 * the signal handler is safe because PQcancel() is written to make it
235 * so. We use write() to report to stderr because it's better to use simple
236 * facilities in a signal handler.
238 * On win32, the signal canceling happens on a separate thread, because
239 * that's how SetConsoleCtrlHandler works. The PQcancel function is safe
240 * for this (unlike PQrequestCancel). However, a CRITICAL_SECTION is required
241 * to protect the PGcancel structure against being changed while the signal
242 * thread is using it.
244 * SIGINT is supposed to abort all long-running psql operations, not only
245 * database queries. In most places, this is accomplished by checking
246 * cancel_pressed during long-running loops. However, that won't work when
247 * blocked on user input (in readline() or fgets()). In those places, we
248 * set sigint_interrupt_enabled true while blocked, instructing the signal
249 * catcher to longjmp through sigint_interrupt_jmp. We assume readline and
250 * fgets are coded to handle possible interruption. (XXX currently this does
251 * not work on win32, so control-C is less useful there)
253 volatile bool sigint_interrupt_enabled = false;
255 sigjmp_buf sigint_interrupt_jmp;
257 static PGcancel *volatile cancelConn = NULL;
260 static CRITICAL_SECTION cancelConnLock;
264 * Write a simple string to stderr --- must be safe in a signal handler.
265 * We ignore the write() result since there's not much we could do about it.
266 * Certain compilers make that harder than it ought to be.
268 #define write_stderr(str) \
270 const char *str_ = (str); \
272 rc_ = write(fileno(stderr), str_, strlen(str_)); \
280 handle_sigint(SIGNAL_ARGS)
282 int save_errno = errno;
285 /* if we are waiting for input, longjmp out of it */
286 if (sigint_interrupt_enabled)
288 sigint_interrupt_enabled = false;
289 siglongjmp(sigint_interrupt_jmp, 1);
292 /* else, set cancel flag to stop any long-running loops */
293 cancel_pressed = true;
295 /* and send QueryCancel if we are processing a database query */
296 if (cancelConn != NULL)
298 if (PQcancel(cancelConn, errbuf, sizeof(errbuf)))
299 write_stderr("Cancel request sent\n");
302 write_stderr("Could not send cancel request: ");
303 write_stderr(errbuf);
307 errno = save_errno; /* just in case the write changed it */
311 setup_cancel_handler(void)
313 pqsignal(SIGINT, handle_sigint);
318 consoleHandler(DWORD dwCtrlType)
322 if (dwCtrlType == CTRL_C_EVENT ||
323 dwCtrlType == CTRL_BREAK_EVENT)
326 * Can't longjmp here, because we are in wrong thread :-(
329 /* set cancel flag to stop any long-running loops */
330 cancel_pressed = true;
332 /* and send QueryCancel if we are processing a database query */
333 EnterCriticalSection(&cancelConnLock);
334 if (cancelConn != NULL)
336 if (PQcancel(cancelConn, errbuf, sizeof(errbuf)))
337 write_stderr("Cancel request sent\n");
340 write_stderr("Could not send cancel request: ");
341 write_stderr(errbuf);
344 LeaveCriticalSection(&cancelConnLock);
349 /* Return FALSE for any signals not being handled */
354 setup_cancel_handler(void)
356 InitializeCriticalSection(&cancelConnLock);
358 SetConsoleCtrlHandler(consoleHandler, TRUE);
365 * Returns whether our backend connection is still there.
370 return PQstatus(pset.db) != CONNECTION_BAD;
377 * Verify that we still have a good connection to the backend, and if not,
378 * see if it can be restored.
380 * Returns true if either the connection was still there, or it could be
381 * restored successfully; false otherwise. If, however, there was no
382 * connection and the session is non-interactive, this will exit the program
383 * with a code of EXIT_BADCONN.
386 CheckConnection(void)
393 if (!pset.cur_cmd_interactive)
395 pg_log_fatal("connection to server was lost");
399 fprintf(stderr, _("The connection to the server was lost. Attempting reset: "));
404 fprintf(stderr, _("Failed.\n"));
411 fprintf(stderr, _("Succeeded.\n"));
422 * Set cancelConn to point to the current database connection.
427 PGcancel *oldCancelConn;
430 EnterCriticalSection(&cancelConnLock);
433 /* Free the old one if we have one */
434 oldCancelConn = cancelConn;
435 /* be sure handle_sigint doesn't use pointer while freeing */
438 if (oldCancelConn != NULL)
439 PQfreeCancel(oldCancelConn);
441 cancelConn = PQgetCancel(pset.db);
444 LeaveCriticalSection(&cancelConnLock);
452 * Free the current cancel connection, if any, and set to NULL.
455 ResetCancelConn(void)
457 PGcancel *oldCancelConn;
460 EnterCriticalSection(&cancelConnLock);
463 oldCancelConn = cancelConn;
464 /* be sure handle_sigint doesn't use pointer while freeing */
467 if (oldCancelConn != NULL)
468 PQfreeCancel(oldCancelConn);
471 LeaveCriticalSection(&cancelConnLock);
479 * Checks whether a result is valid, giving an error message if necessary;
480 * and ensures that the connection to the backend is still up.
482 * Returns true for valid result, false for error state.
485 AcceptResult(const PGresult *result)
492 switch (PQresultStatus(result))
494 case PGRES_COMMAND_OK:
495 case PGRES_TUPLES_OK:
496 case PGRES_EMPTY_QUERY:
499 /* Fine, do nothing */
503 case PGRES_BAD_RESPONSE:
504 case PGRES_NONFATAL_ERROR:
505 case PGRES_FATAL_ERROR:
511 pg_log_error("unexpected PQresultStatus: %d",
512 PQresultStatus(result));
518 const char *error = PQerrorMessage(pset.db);
521 pg_log_info("%s", error);
531 * Set special variables from a query result
532 * - ERROR: true/false, whether an error occurred on this query
533 * - SQLSTATE: code of error, or "00000" if no error, or "" if unknown
534 * - ROW_COUNT: how many rows were returned or affected, or "0"
535 * - LAST_ERROR_SQLSTATE: same for last error
536 * - LAST_ERROR_MESSAGE: message of last error
538 * Note: current policy is to apply this only to the results of queries
539 * entered by the user, not queries generated by slash commands.
542 SetResultVariables(PGresult *results, bool success)
546 const char *ntuples = PQcmdTuples(results);
548 SetVariable(pset.vars, "ERROR", "false");
549 SetVariable(pset.vars, "SQLSTATE", "00000");
550 SetVariable(pset.vars, "ROW_COUNT", *ntuples ? ntuples : "0");
554 const char *code = PQresultErrorField(results, PG_DIAG_SQLSTATE);
555 const char *mesg = PQresultErrorField(results, PG_DIAG_MESSAGE_PRIMARY);
557 SetVariable(pset.vars, "ERROR", "true");
560 * If there is no SQLSTATE code, use an empty string. This can happen
561 * for libpq-detected errors (e.g., lost connection, ENOMEM).
565 SetVariable(pset.vars, "SQLSTATE", code);
566 SetVariable(pset.vars, "ROW_COUNT", "0");
567 SetVariable(pset.vars, "LAST_ERROR_SQLSTATE", code);
568 SetVariable(pset.vars, "LAST_ERROR_MESSAGE", mesg ? mesg : "");
576 * If the result represents an error, remember it for possible display by
577 * \errverbose. Otherwise, just PQclear() it.
579 * Note: current policy is to apply this to the results of all queries,
580 * including "back door" queries, for debugging's sake. It's OK to use
581 * PQclear() directly on results known to not be error results, however.
584 ClearOrSaveResult(PGresult *result)
588 switch (PQresultStatus(result))
590 case PGRES_NONFATAL_ERROR:
591 case PGRES_FATAL_ERROR:
592 if (pset.last_error_result)
593 PQclear(pset.last_error_result);
594 pset.last_error_result = result;
606 * Print microtiming output. Always print raw milliseconds; if the interval
607 * is >= 1 second, also break it down into days/hours/minutes/seconds.
610 PrintTiming(double elapsed_msec)
617 if (elapsed_msec < 1000.0)
619 /* This is the traditional (pre-v10) output format */
620 printf(_("Time: %.3f ms\n"), elapsed_msec);
625 * Note: we could print just seconds, in a format like %06.3f, when the
626 * total is less than 1min. But that's hard to interpret unless we tack
627 * on "s" or otherwise annotate it. Forcing the display to include
628 * minutes seems like a better solution.
630 seconds = elapsed_msec / 1000.0;
631 minutes = floor(seconds / 60.0);
632 seconds -= 60.0 * minutes;
635 printf(_("Time: %.3f ms (%02d:%06.3f)\n"),
636 elapsed_msec, (int) minutes, seconds);
640 hours = floor(minutes / 60.0);
641 minutes -= 60.0 * hours;
644 printf(_("Time: %.3f ms (%02d:%02d:%06.3f)\n"),
645 elapsed_msec, (int) hours, (int) minutes, seconds);
649 days = floor(hours / 24.0);
650 hours -= 24.0 * days;
651 printf(_("Time: %.3f ms (%.0f d %02d:%02d:%06.3f)\n"),
652 elapsed_msec, days, (int) hours, (int) minutes, seconds);
659 * This is the way to send "backdoor" queries (those not directly entered
660 * by the user). It is subject to -E but not -e.
662 * Caller is responsible for handling the ensuing processing if a COPY
665 * Note: we don't bother to check PQclientEncoding; it is assumed that no
666 * caller uses this path to issue "SET CLIENT_ENCODING".
669 PSQLexec(const char *query)
675 pg_log_error("You are currently not connected to a database.");
679 if (pset.echo_hidden != PSQL_ECHO_HIDDEN_OFF)
681 printf(_("********* QUERY **********\n"
683 "**************************\n\n"), query);
687 fprintf(pset.logfile,
688 _("********* QUERY **********\n"
690 "**************************\n\n"), query);
691 fflush(pset.logfile);
694 if (pset.echo_hidden == PSQL_ECHO_HIDDEN_NOEXEC)
700 res = PQexec(pset.db, query);
704 if (!AcceptResult(res))
706 ClearOrSaveResult(res);
717 * This function is used for \watch command to send the query to
718 * the server and print out the results.
720 * Returns 1 if the query executed successfully, 0 if it cannot be repeated,
721 * e.g., because of the interrupt, -1 on error.
724 PSQLexecWatch(const char *query, const printQueryOpt *opt)
727 double elapsed_msec = 0;
733 pg_log_error("You are currently not connected to a database.");
740 INSTR_TIME_SET_CURRENT(before);
742 res = PQexec(pset.db, query);
746 if (!AcceptResult(res))
748 ClearOrSaveResult(res);
754 INSTR_TIME_SET_CURRENT(after);
755 INSTR_TIME_SUBTRACT(after, before);
756 elapsed_msec = INSTR_TIME_GET_MILLISEC(after);
760 * If SIGINT is sent while the query is processing, the interrupt will be
761 * consumed. The user's intention, though, is to cancel the entire watch
762 * process, so detect a sent cancellation request and exit in this case.
770 switch (PQresultStatus(res))
772 case PGRES_TUPLES_OK:
773 printQuery(res, opt, pset.queryFout, false, pset.logfile);
776 case PGRES_COMMAND_OK:
777 fprintf(pset.queryFout, "%s\n%s\n\n", opt->title, PQcmdStatus(res));
780 case PGRES_EMPTY_QUERY:
781 pg_log_error("\\watch cannot be used with an empty query");
787 case PGRES_COPY_BOTH:
788 pg_log_error("\\watch cannot be used with COPY");
793 pg_log_error("unexpected result status for \\watch");
800 fflush(pset.queryFout);
802 /* Possible microtiming output */
804 PrintTiming(elapsed_msec);
811 * PrintNotifications: check for asynchronous notifications, and print them out
814 PrintNotifications(void)
818 PQconsumeInput(pset.db);
819 while ((notify = PQnotifies(pset.db)) != NULL)
821 /* for backward compatibility, only show payload if nonempty */
822 if (notify->extra[0])
823 fprintf(pset.queryFout, _("Asynchronous notification \"%s\" with payload \"%s\" received from server process with PID %d.\n"),
824 notify->relname, notify->extra, notify->be_pid);
826 fprintf(pset.queryFout, _("Asynchronous notification \"%s\" received from server process with PID %d.\n"),
827 notify->relname, notify->be_pid);
828 fflush(pset.queryFout);
830 PQconsumeInput(pset.db);
836 * PrintQueryTuples: assuming query result is OK, print its tuples
838 * Returns true if successful, false otherwise.
841 PrintQueryTuples(const PGresult *results)
843 printQueryOpt my_popt = pset.popt;
845 /* one-shot expanded output requested via \gx */
847 my_popt.topt.expanded = 1;
849 /* write output to \g argument, if any */
855 if (!openQueryOutputFile(pset.gfname, &fout, &is_pipe))
858 disable_sigpipe_trap();
860 printQuery(results, &my_popt, fout, false, pset.logfile);
865 restore_sigpipe_trap();
871 printQuery(results, &my_popt, pset.queryFout, false, pset.logfile);
878 * StoreQueryTuple: assuming query result is OK, save data into variables
880 * Returns true if successful, false otherwise.
883 StoreQueryTuple(const PGresult *result)
887 if (PQntuples(result) < 1)
889 pg_log_error("no rows returned for \\gset");
892 else if (PQntuples(result) > 1)
894 pg_log_error("more than one row returned for \\gset");
901 for (i = 0; i < PQnfields(result); i++)
903 char *colname = PQfname(result, i);
907 /* concatenate prefix and column name */
908 varname = psprintf("%s%s", pset.gset_prefix, colname);
910 if (!PQgetisnull(result, 0, i))
911 value = PQgetvalue(result, 0, i);
914 /* for NULL value, unset rather than set the variable */
918 if (!SetVariable(pset.vars, varname, value))
934 * ExecQueryTuples: assuming query result is OK, execute each query
935 * result field as a SQL statement
937 * Returns true if successful, false otherwise.
940 ExecQueryTuples(const PGresult *result)
943 int nrows = PQntuples(result);
944 int ncolumns = PQnfields(result);
949 * We must turn off gexec_flag to avoid infinite recursion. Note that
950 * this allows ExecQueryUsingCursor to be applied to the individual query
951 * results. SendQuery prevents it from being applied when fetching the
952 * queries-to-execute, because it can't handle recursion either.
954 pset.gexec_flag = false;
956 for (r = 0; r < nrows; r++)
958 for (c = 0; c < ncolumns; c++)
960 if (!PQgetisnull(result, r, c))
962 const char *query = PQgetvalue(result, r, c);
964 /* Abandon execution if cancel_pressed */
969 * ECHO_ALL mode should echo these queries, but SendQuery
970 * assumes that MainLoop did that, so we have to do it here.
972 if (pset.echo == PSQL_ECHO_ALL && !pset.singlestep)
978 if (!SendQuery(query))
980 /* Error - abandon execution if ON_ERROR_STOP */
982 if (pset.on_error_stop)
992 * Restore state. We know gexec_flag was on, else we'd not be here. (We
993 * also know it'll get turned off at end of command, but that's not ours
996 pset.gexec_flag = true;
998 /* Return true if all queries were successful */
1004 * ProcessResult: utility function for use by SendQuery() only
1006 * When our command string contained a COPY FROM STDIN or COPY TO STDOUT,
1007 * PQexec() has stopped at the PGresult associated with the first such
1008 * command. In that event, we'll marshal data for the COPY and then cycle
1009 * through any subsequent PGresult objects.
1011 * When the command string contained no such COPY command, this function
1012 * degenerates to an AcceptResult() call.
1014 * Changes its argument to point to the last PGresult of the command string,
1015 * or NULL if that result was for a COPY TO STDOUT. (Returning NULL prevents
1016 * the command status from being printed, which we want in that case so that
1017 * the status line doesn't get taken as part of the COPY data.)
1019 * Returns true on complete success, false otherwise. Possible failure modes
1020 * include purely client-side problems; check the transaction status for the
1021 * server-side opinion.
1024 ProcessResult(PGresult **results)
1026 bool success = true;
1027 bool first_cycle = true;
1031 ExecStatusType result_status;
1033 PGresult *next_result;
1035 if (!AcceptResult(*results))
1038 * Failure at this point is always a server-side failure or a
1039 * failure to submit the command string. Either way, we're
1040 * finished with this command string.
1046 result_status = PQresultStatus(*results);
1047 switch (result_status)
1049 case PGRES_EMPTY_QUERY:
1050 case PGRES_COMMAND_OK:
1051 case PGRES_TUPLES_OK:
1055 case PGRES_COPY_OUT:
1061 /* AcceptResult() should have caught anything else. */
1063 pg_log_error("unexpected PQresultStatus: %d", result_status);
1070 * Marshal the COPY data. Either subroutine will get the
1071 * connection out of its COPY state, then call PQresultStatus()
1072 * once and report any error.
1074 * For COPY OUT, direct the output to pset.copyStream if it's set,
1075 * otherwise to pset.gfname if it's set, otherwise to queryFout.
1076 * For COPY IN, use pset.copyStream as data source if it's set,
1077 * otherwise cur_cmd_source.
1080 PGresult *copy_result;
1083 if (result_status == PGRES_COPY_OUT)
1085 bool need_close = false;
1086 bool is_pipe = false;
1088 if (pset.copyStream)
1090 /* invoked by \copy */
1091 copystream = pset.copyStream;
1093 else if (pset.gfname)
1096 if (openQueryOutputFile(pset.gfname,
1097 ©stream, &is_pipe))
1101 disable_sigpipe_trap();
1104 copystream = NULL; /* discard COPY data entirely */
1108 /* fall back to the generic query output stream */
1109 copystream = pset.queryFout;
1112 success = handleCopyOut(pset.db,
1116 && (copystream != NULL);
1119 * Suppress status printing if the report would go to the same
1120 * place as the COPY data just went. Note this doesn't
1121 * prevent error reporting, since handleCopyOut did that.
1123 if (copystream == pset.queryFout)
1125 PQclear(copy_result);
1131 /* close \g argument file/pipe */
1135 restore_sigpipe_trap();
1146 copystream = pset.copyStream ? pset.copyStream : pset.cur_cmd_source;
1147 success = handleCopyIn(pset.db,
1149 PQbinaryTuples(*results),
1150 ©_result) && success;
1155 * Replace the PGRES_COPY_OUT/IN result with COPY command's exit
1156 * status, or with NULL if we want to suppress printing anything.
1159 *results = copy_result;
1161 else if (first_cycle)
1163 /* fast path: no COPY commands; PQexec visited all results */
1168 * Check PQgetResult() again. In the typical case of a single-command
1169 * string, it will return NULL. Otherwise, we'll have other results
1170 * to process that may include other COPYs. We keep the last result.
1172 next_result = PQgetResult(pset.db);
1177 *results = next_result;
1178 first_cycle = false;
1181 SetResultVariables(*results, success);
1183 /* may need this to recover from conn loss during COPY */
1184 if (!first_cycle && !CheckConnection())
1192 * PrintQueryStatus: report command status as required
1194 * Note: Utility function for use by PrintQueryResults() only.
1197 PrintQueryStatus(PGresult *results)
1203 if (pset.popt.topt.format == PRINT_HTML)
1205 fputs("<p>", pset.queryFout);
1206 html_escaped_print(PQcmdStatus(results), pset.queryFout);
1207 fputs("</p>\n", pset.queryFout);
1210 fprintf(pset.queryFout, "%s\n", PQcmdStatus(results));
1214 fprintf(pset.logfile, "%s\n", PQcmdStatus(results));
1216 snprintf(buf, sizeof(buf), "%u", (unsigned int) PQoidValue(results));
1217 SetVariable(pset.vars, "LASTOID", buf);
1222 * PrintQueryResults: print out (or store or execute) query results as required
1224 * Note: Utility function for use by SendQuery() only.
1226 * Returns true if the query executed successfully, false otherwise.
1229 PrintQueryResults(PGresult *results)
1232 const char *cmdstatus;
1237 switch (PQresultStatus(results))
1239 case PGRES_TUPLES_OK:
1240 /* store or execute or print the data ... */
1241 if (pset.gset_prefix)
1242 success = StoreQueryTuple(results);
1243 else if (pset.gexec_flag)
1244 success = ExecQueryTuples(results);
1245 else if (pset.crosstab_flag)
1246 success = PrintResultsInCrosstab(results);
1248 success = PrintQueryTuples(results);
1249 /* if it's INSERT/UPDATE/DELETE RETURNING, also print status */
1250 cmdstatus = PQcmdStatus(results);
1251 if (strncmp(cmdstatus, "INSERT", 6) == 0 ||
1252 strncmp(cmdstatus, "UPDATE", 6) == 0 ||
1253 strncmp(cmdstatus, "DELETE", 6) == 0)
1254 PrintQueryStatus(results);
1257 case PGRES_COMMAND_OK:
1258 PrintQueryStatus(results);
1262 case PGRES_EMPTY_QUERY:
1266 case PGRES_COPY_OUT:
1268 /* nothing to do here */
1272 case PGRES_BAD_RESPONSE:
1273 case PGRES_NONFATAL_ERROR:
1274 case PGRES_FATAL_ERROR:
1280 pg_log_error("unexpected PQresultStatus: %d",
1281 PQresultStatus(results));
1285 fflush(pset.queryFout);
1292 * SendQuery: send the query string to the backend
1293 * (and print out results)
1295 * Note: This is the "front door" way to send a query. That is, use it to
1296 * send queries actually entered by the user. These queries will be subject to
1298 * To send "back door" queries (generated by slash commands, etc.) in a
1299 * controlled way, use PSQLexec().
1301 * Returns true if the query executed successfully, false otherwise.
1304 SendQuery(const char *query)
1307 PGTransactionStatusType transaction_status;
1308 double elapsed_msec = 0;
1311 bool on_error_rollback_savepoint = false;
1312 static bool on_error_rollback_warning = false;
1316 pg_log_error("You are currently not connected to a database.");
1317 goto sendquery_cleanup;
1320 if (pset.singlestep)
1325 printf(_("***(Single step mode: verify command)*******************************************\n"
1327 "***(press return to proceed or enter x and return to cancel)********************\n"),
1330 if (fgets(buf, sizeof(buf), stdin) != NULL)
1332 goto sendquery_cleanup;
1334 goto sendquery_cleanup;
1336 else if (pset.echo == PSQL_ECHO_QUERIES)
1344 fprintf(pset.logfile,
1345 _("********* QUERY **********\n"
1347 "**************************\n\n"), query);
1348 fflush(pset.logfile);
1353 transaction_status = PQtransactionStatus(pset.db);
1355 if (transaction_status == PQTRANS_IDLE &&
1357 !command_no_begin(query))
1359 results = PQexec(pset.db, "BEGIN");
1360 if (PQresultStatus(results) != PGRES_COMMAND_OK)
1362 pg_log_info("%s", PQerrorMessage(pset.db));
1363 ClearOrSaveResult(results);
1365 goto sendquery_cleanup;
1367 ClearOrSaveResult(results);
1368 transaction_status = PQtransactionStatus(pset.db);
1371 if (transaction_status == PQTRANS_INTRANS &&
1372 pset.on_error_rollback != PSQL_ERROR_ROLLBACK_OFF &&
1373 (pset.cur_cmd_interactive ||
1374 pset.on_error_rollback == PSQL_ERROR_ROLLBACK_ON))
1376 if (on_error_rollback_warning == false && pset.sversion < 80000)
1380 pg_log_warning("The server (version %s) does not support savepoints for ON_ERROR_ROLLBACK.",
1381 formatPGVersionNumber(pset.sversion, false,
1382 sverbuf, sizeof(sverbuf)));
1383 on_error_rollback_warning = true;
1387 results = PQexec(pset.db, "SAVEPOINT pg_psql_temporary_savepoint");
1388 if (PQresultStatus(results) != PGRES_COMMAND_OK)
1390 pg_log_info("%s", PQerrorMessage(pset.db));
1391 ClearOrSaveResult(results);
1393 goto sendquery_cleanup;
1395 ClearOrSaveResult(results);
1396 on_error_rollback_savepoint = true;
1400 if (pset.gdesc_flag)
1402 /* Describe query's result columns, without executing it */
1403 OK = DescribeQuery(query, &elapsed_msec);
1405 results = NULL; /* PQclear(NULL) does nothing */
1407 else if (pset.fetch_count <= 0 || pset.gexec_flag ||
1408 pset.crosstab_flag || !is_select_command(query))
1410 /* Default fetch-it-all-and-print mode */
1415 INSTR_TIME_SET_CURRENT(before);
1417 results = PQexec(pset.db, query);
1419 /* these operations are included in the timing result: */
1421 OK = ProcessResult(&results);
1425 INSTR_TIME_SET_CURRENT(after);
1426 INSTR_TIME_SUBTRACT(after, before);
1427 elapsed_msec = INSTR_TIME_GET_MILLISEC(after);
1430 /* but printing results isn't: */
1432 OK = PrintQueryResults(results);
1436 /* Fetch-in-segments mode */
1437 OK = ExecQueryUsingCursor(query, &elapsed_msec);
1439 results = NULL; /* PQclear(NULL) does nothing */
1442 if (!OK && pset.echo == PSQL_ECHO_ERRORS)
1443 pg_log_info("STATEMENT: %s", query);
1445 /* If we made a temporary savepoint, possibly release/rollback */
1446 if (on_error_rollback_savepoint)
1448 const char *svptcmd = NULL;
1450 transaction_status = PQtransactionStatus(pset.db);
1452 switch (transaction_status)
1454 case PQTRANS_INERROR:
1455 /* We always rollback on an error */
1456 svptcmd = "ROLLBACK TO pg_psql_temporary_savepoint";
1460 /* If they are no longer in a transaction, then do nothing */
1463 case PQTRANS_INTRANS:
1466 * Do nothing if they are messing with savepoints themselves:
1467 * If the user did RELEASE or ROLLBACK, our savepoint is gone.
1468 * If they issued a SAVEPOINT, releasing ours would remove
1472 (strcmp(PQcmdStatus(results), "SAVEPOINT") == 0 ||
1473 strcmp(PQcmdStatus(results), "RELEASE") == 0 ||
1474 strcmp(PQcmdStatus(results), "ROLLBACK") == 0))
1477 svptcmd = "RELEASE pg_psql_temporary_savepoint";
1480 case PQTRANS_ACTIVE:
1481 case PQTRANS_UNKNOWN:
1484 /* PQTRANS_UNKNOWN is expected given a broken connection. */
1485 if (transaction_status != PQTRANS_UNKNOWN || ConnectionUp())
1486 pg_log_error("unexpected transaction status (%d)",
1487 transaction_status);
1495 svptres = PQexec(pset.db, svptcmd);
1496 if (PQresultStatus(svptres) != PGRES_COMMAND_OK)
1498 pg_log_info("%s", PQerrorMessage(pset.db));
1499 ClearOrSaveResult(svptres);
1504 goto sendquery_cleanup;
1510 ClearOrSaveResult(results);
1512 /* Possible microtiming output */
1514 PrintTiming(elapsed_msec);
1516 /* check for events that may occur during query execution */
1518 if (pset.encoding != PQclientEncoding(pset.db) &&
1519 PQclientEncoding(pset.db) >= 0)
1521 /* track effects of SET CLIENT_ENCODING */
1522 pset.encoding = PQclientEncoding(pset.db);
1523 pset.popt.topt.encoding = pset.encoding;
1524 SetVariable(pset.vars, "ENCODING",
1525 pg_encoding_to_char(pset.encoding));
1528 PrintNotifications();
1530 /* perform cleanup that should occur after any attempted query */
1534 /* reset \g's output-to-filename trigger */
1541 /* reset \gx's expanded-mode flag */
1542 pset.g_expanded = false;
1544 /* reset \gset trigger */
1545 if (pset.gset_prefix)
1547 free(pset.gset_prefix);
1548 pset.gset_prefix = NULL;
1551 /* reset \gdesc trigger */
1552 pset.gdesc_flag = false;
1554 /* reset \gexec trigger */
1555 pset.gexec_flag = false;
1557 /* reset \crosstabview trigger */
1558 pset.crosstab_flag = false;
1559 for (i = 0; i < lengthof(pset.ctv_args); i++)
1561 pg_free(pset.ctv_args[i]);
1562 pset.ctv_args[i] = NULL;
1570 * DescribeQuery: describe the result columns of a query, without executing it
1572 * Returns true if the operation executed successfully, false otherwise.
1574 * If pset.timing is on, total query time (exclusive of result-printing) is
1575 * stored into *elapsed_msec.
1578 DescribeQuery(const char *query, double *elapsed_msec)
1588 INSTR_TIME_SET_CURRENT(before);
1591 * To parse the query but not execute it, we prepare it, using the unnamed
1592 * prepared statement. This is invisible to psql users, since there's no
1593 * way to access the unnamed prepared statement from psql user space. The
1594 * next Parse or Query protocol message would overwrite the statement
1595 * anyway. (So there's no great need to clear it when done, which is a
1596 * good thing because libpq provides no easy way to do that.)
1598 results = PQprepare(pset.db, "", query, 0, NULL);
1599 if (PQresultStatus(results) != PGRES_COMMAND_OK)
1601 pg_log_info("%s", PQerrorMessage(pset.db));
1602 SetResultVariables(results, false);
1603 ClearOrSaveResult(results);
1608 results = PQdescribePrepared(pset.db, "");
1609 OK = AcceptResult(results) &&
1610 (PQresultStatus(results) == PGRES_COMMAND_OK);
1613 if (PQnfields(results) > 0)
1615 PQExpBufferData buf;
1618 initPQExpBuffer(&buf);
1620 printfPQExpBuffer(&buf,
1621 "SELECT name AS \"%s\", pg_catalog.format_type(tp, tpm) AS \"%s\"\n"
1623 gettext_noop("Column"),
1624 gettext_noop("Type"));
1626 for (i = 0; i < PQnfields(results); i++)
1632 appendPQExpBufferStr(&buf, ",");
1634 name = PQfname(results, i);
1635 escname = PQescapeLiteral(pset.db, name, strlen(name));
1637 if (escname == NULL)
1639 pg_log_info("%s", PQerrorMessage(pset.db));
1641 termPQExpBuffer(&buf);
1645 appendPQExpBuffer(&buf, "(%s, '%u'::pg_catalog.oid, %d)",
1647 PQftype(results, i),
1648 PQfmod(results, i));
1653 appendPQExpBufferStr(&buf, ") s(name, tp, tpm)");
1656 results = PQexec(pset.db, buf.data);
1657 OK = AcceptResult(results);
1661 INSTR_TIME_SET_CURRENT(after);
1662 INSTR_TIME_SUBTRACT(after, before);
1663 *elapsed_msec += INSTR_TIME_GET_MILLISEC(after);
1667 OK = PrintQueryResults(results);
1669 termPQExpBuffer(&buf);
1672 fprintf(pset.queryFout,
1673 _("The command has no result, or the result has no columns.\n"));
1676 SetResultVariables(results, OK);
1677 ClearOrSaveResult(results);
1684 * ExecQueryUsingCursor: run a SELECT-like query using a cursor
1686 * This feature allows result sets larger than RAM to be dealt with.
1688 * Returns true if the query executed successfully, false otherwise.
1690 * If pset.timing is on, total query time (exclusive of result-printing) is
1691 * stored into *elapsed_msec.
1694 ExecQueryUsingCursor(const char *query, double *elapsed_msec)
1698 PQExpBufferData buf;
1699 printQueryOpt my_popt = pset.popt;
1702 bool is_pager = false;
1703 bool started_txn = false;
1704 int64 total_tuples = 0;
1714 /* initialize print options for partial table output */
1715 my_popt.topt.start_table = true;
1716 my_popt.topt.stop_table = false;
1717 my_popt.topt.prior_records = 0;
1720 INSTR_TIME_SET_CURRENT(before);
1722 /* if we're not in a transaction, start one */
1723 if (PQtransactionStatus(pset.db) == PQTRANS_IDLE)
1725 results = PQexec(pset.db, "BEGIN");
1726 OK = AcceptResult(results) &&
1727 (PQresultStatus(results) == PGRES_COMMAND_OK);
1728 ClearOrSaveResult(results);
1734 /* Send DECLARE CURSOR */
1735 initPQExpBuffer(&buf);
1736 appendPQExpBuffer(&buf, "DECLARE _psql_cursor NO SCROLL CURSOR FOR\n%s",
1739 results = PQexec(pset.db, buf.data);
1740 OK = AcceptResult(results) &&
1741 (PQresultStatus(results) == PGRES_COMMAND_OK);
1743 SetResultVariables(results, OK);
1744 ClearOrSaveResult(results);
1745 termPQExpBuffer(&buf);
1751 INSTR_TIME_SET_CURRENT(after);
1752 INSTR_TIME_SUBTRACT(after, before);
1753 *elapsed_msec += INSTR_TIME_GET_MILLISEC(after);
1757 * In \gset mode, we force the fetch count to be 2, so that we will throw
1758 * the appropriate error if the query returns more than one row.
1760 if (pset.gset_prefix)
1763 fetch_count = pset.fetch_count;
1765 snprintf(fetch_cmd, sizeof(fetch_cmd),
1766 "FETCH FORWARD %d FROM _psql_cursor",
1769 /* one-shot expanded output requested via \gx */
1770 if (pset.g_expanded)
1771 my_popt.topt.expanded = 1;
1773 /* prepare to write output to \g argument, if any */
1776 if (!openQueryOutputFile(pset.gfname, &fout, &is_pipe))
1782 disable_sigpipe_trap();
1786 fout = pset.queryFout;
1787 is_pipe = false; /* doesn't matter */
1790 /* clear any pre-existing error indication on the output stream */
1796 INSTR_TIME_SET_CURRENT(before);
1798 /* get fetch_count tuples at a time */
1799 results = PQexec(pset.db, fetch_cmd);
1803 INSTR_TIME_SET_CURRENT(after);
1804 INSTR_TIME_SUBTRACT(after, before);
1805 *elapsed_msec += INSTR_TIME_GET_MILLISEC(after);
1808 if (PQresultStatus(results) != PGRES_TUPLES_OK)
1810 /* shut down pager before printing error message */
1817 OK = AcceptResult(results);
1819 SetResultVariables(results, OK);
1820 ClearOrSaveResult(results);
1824 if (pset.gset_prefix)
1826 /* StoreQueryTuple will complain if not exactly one row */
1827 OK = StoreQueryTuple(results);
1828 ClearOrSaveResult(results);
1833 * Note we do not deal with \gdesc, \gexec or \crosstabview modes here
1836 ntuples = PQntuples(results);
1837 total_tuples += ntuples;
1839 if (ntuples < fetch_count)
1841 /* this is the last result set, so allow footer decoration */
1842 my_popt.topt.stop_table = true;
1844 else if (fout == stdout && !is_pager)
1847 * If query requires multiple result sets, hack to ensure that
1848 * only one pager instance is used for the whole mess
1850 fout = PageOutput(INT_MAX, &(my_popt.topt));
1854 printQuery(results, &my_popt, fout, is_pager, pset.logfile);
1856 ClearOrSaveResult(results);
1858 /* after the first result set, disallow header decoration */
1859 my_popt.topt.start_table = false;
1860 my_popt.topt.prior_records += ntuples;
1863 * Make sure to flush the output stream, so intermediate results are
1864 * visible to the client immediately. We check the results because if
1865 * the pager dies/exits/etc, there's no sense throwing more data at
1868 flush_error = fflush(fout);
1871 * Check if we are at the end, if a cancel was pressed, or if there
1872 * were any errors either trying to flush out the results, or more
1873 * generally on the output stream at all. If we hit any errors
1874 * writing things to the stream, we presume $PAGER has disappeared and
1875 * stop bothering to pull down more data.
1877 if (ntuples < fetch_count || cancel_pressed || flush_error ||
1884 /* close \g argument file/pipe */
1888 restore_sigpipe_trap();
1895 /* close transient pager */
1902 * We don't have a PGresult here, and even if we did it wouldn't have
1903 * the right row count, so fake SetResultVariables(). In error cases,
1904 * we already set the result variables above.
1908 SetVariable(pset.vars, "ERROR", "false");
1909 SetVariable(pset.vars, "SQLSTATE", "00000");
1910 snprintf(buf, sizeof(buf), INT64_FORMAT, total_tuples);
1911 SetVariable(pset.vars, "ROW_COUNT", buf);
1916 INSTR_TIME_SET_CURRENT(before);
1919 * We try to close the cursor on either success or failure, but on failure
1920 * ignore the result (it's probably just a bleat about being in an aborted
1923 results = PQexec(pset.db, "CLOSE _psql_cursor");
1926 OK = AcceptResult(results) &&
1927 (PQresultStatus(results) == PGRES_COMMAND_OK);
1928 ClearOrSaveResult(results);
1935 results = PQexec(pset.db, OK ? "COMMIT" : "ROLLBACK");
1936 OK &= AcceptResult(results) &&
1937 (PQresultStatus(results) == PGRES_COMMAND_OK);
1938 ClearOrSaveResult(results);
1943 INSTR_TIME_SET_CURRENT(after);
1944 INSTR_TIME_SUBTRACT(after, before);
1945 *elapsed_msec += INSTR_TIME_GET_MILLISEC(after);
1953 * Advance the given char pointer over white space and SQL comments.
1956 skip_white_space(const char *query)
1958 int cnestlevel = 0; /* slash-star comment nest level */
1962 int mblen = PQmblen(query, pset.encoding);
1965 * Note: we assume the encoding is a superset of ASCII, so that for
1966 * example "query[0] == '/'" is meaningful. However, we do NOT assume
1967 * that the second and subsequent bytes of a multibyte character
1968 * couldn't look like ASCII characters; so it is critical to advance
1969 * by mblen, not 1, whenever we haven't exactly identified the
1970 * character we are skipping over.
1972 if (isspace((unsigned char) *query))
1974 else if (query[0] == '/' && query[1] == '*')
1979 else if (cnestlevel > 0 && query[0] == '*' && query[1] == '/')
1984 else if (cnestlevel == 0 && query[0] == '-' && query[1] == '-')
1989 * We have to skip to end of line since any slash-star inside the
1990 * -- comment does NOT start a slash-star comment.
1999 query += PQmblen(query, pset.encoding);
2002 else if (cnestlevel > 0)
2005 break; /* found first token */
2013 * Check whether a command is one of those for which we should NOT start
2014 * a new transaction block (ie, send a preceding BEGIN).
2016 * These include the transaction control statements themselves, plus
2017 * certain statements that the backend disallows inside transaction blocks.
2020 command_no_begin(const char *query)
2025 * First we must advance over any whitespace and comments.
2027 query = skip_white_space(query);
2030 * Check word length (since "beginx" is not "begin").
2033 while (isalpha((unsigned char) query[wordlen]))
2034 wordlen += PQmblen(&query[wordlen], pset.encoding);
2037 * Transaction control commands. These should include every keyword that
2038 * gives rise to a TransactionStmt in the backend grammar, except for the
2039 * savepoint-related commands.
2041 * (We assume that START must be START TRANSACTION, since there is
2042 * presently no other "START foo" command.)
2044 if (wordlen == 5 && pg_strncasecmp(query, "abort", 5) == 0)
2046 if (wordlen == 5 && pg_strncasecmp(query, "begin", 5) == 0)
2048 if (wordlen == 5 && pg_strncasecmp(query, "start", 5) == 0)
2050 if (wordlen == 6 && pg_strncasecmp(query, "commit", 6) == 0)
2052 if (wordlen == 3 && pg_strncasecmp(query, "end", 3) == 0)
2054 if (wordlen == 8 && pg_strncasecmp(query, "rollback", 8) == 0)
2056 if (wordlen == 7 && pg_strncasecmp(query, "prepare", 7) == 0)
2058 /* PREPARE TRANSACTION is a TC command, PREPARE foo is not */
2061 query = skip_white_space(query);
2064 while (isalpha((unsigned char) query[wordlen]))
2065 wordlen += PQmblen(&query[wordlen], pset.encoding);
2067 if (wordlen == 11 && pg_strncasecmp(query, "transaction", 11) == 0)
2073 * Commands not allowed within transactions. The statements checked for
2074 * here should be exactly those that call PreventInTransactionBlock() in
2077 if (wordlen == 6 && pg_strncasecmp(query, "vacuum", 6) == 0)
2079 if (wordlen == 7 && pg_strncasecmp(query, "cluster", 7) == 0)
2081 /* CLUSTER with any arguments is allowed in transactions */
2084 query = skip_white_space(query);
2086 if (isalpha((unsigned char) query[0]))
2087 return false; /* has additional words */
2088 return true; /* it's CLUSTER without arguments */
2091 if (wordlen == 6 && pg_strncasecmp(query, "create", 6) == 0)
2095 query = skip_white_space(query);
2098 while (isalpha((unsigned char) query[wordlen]))
2099 wordlen += PQmblen(&query[wordlen], pset.encoding);
2101 if (wordlen == 8 && pg_strncasecmp(query, "database", 8) == 0)
2103 if (wordlen == 10 && pg_strncasecmp(query, "tablespace", 10) == 0)
2106 /* CREATE [UNIQUE] INDEX CONCURRENTLY isn't allowed in xacts */
2107 if (wordlen == 6 && pg_strncasecmp(query, "unique", 6) == 0)
2111 query = skip_white_space(query);
2114 while (isalpha((unsigned char) query[wordlen]))
2115 wordlen += PQmblen(&query[wordlen], pset.encoding);
2118 if (wordlen == 5 && pg_strncasecmp(query, "index", 5) == 0)
2122 query = skip_white_space(query);
2125 while (isalpha((unsigned char) query[wordlen]))
2126 wordlen += PQmblen(&query[wordlen], pset.encoding);
2128 if (wordlen == 12 && pg_strncasecmp(query, "concurrently", 12) == 0)
2135 if (wordlen == 5 && pg_strncasecmp(query, "alter", 5) == 0)
2139 query = skip_white_space(query);
2142 while (isalpha((unsigned char) query[wordlen]))
2143 wordlen += PQmblen(&query[wordlen], pset.encoding);
2145 /* ALTER SYSTEM isn't allowed in xacts */
2146 if (wordlen == 6 && pg_strncasecmp(query, "system", 6) == 0)
2153 * Note: these tests will match DROP SYSTEM and REINDEX TABLESPACE, which
2154 * aren't really valid commands so we don't care much. The other four
2155 * possible matches are correct.
2157 if ((wordlen == 4 && pg_strncasecmp(query, "drop", 4) == 0) ||
2158 (wordlen == 7 && pg_strncasecmp(query, "reindex", 7) == 0))
2162 query = skip_white_space(query);
2165 while (isalpha((unsigned char) query[wordlen]))
2166 wordlen += PQmblen(&query[wordlen], pset.encoding);
2168 if (wordlen == 8 && pg_strncasecmp(query, "database", 8) == 0)
2170 if (wordlen == 6 && pg_strncasecmp(query, "system", 6) == 0)
2172 if (wordlen == 10 && pg_strncasecmp(query, "tablespace", 10) == 0)
2174 if (wordlen == 5 && (pg_strncasecmp(query, "index", 5) == 0 ||
2175 pg_strncasecmp(query, "table", 5) == 0))
2178 query = skip_white_space(query);
2180 while (isalpha((unsigned char) query[wordlen]))
2181 wordlen += PQmblen(&query[wordlen], pset.encoding);
2184 * REINDEX [ TABLE | INDEX ] CONCURRENTLY are not allowed in
2187 if (wordlen == 12 && pg_strncasecmp(query, "concurrently", 12) == 0)
2191 /* DROP INDEX CONCURRENTLY isn't allowed in xacts */
2192 if (wordlen == 5 && pg_strncasecmp(query, "index", 5) == 0)
2196 query = skip_white_space(query);
2199 while (isalpha((unsigned char) query[wordlen]))
2200 wordlen += PQmblen(&query[wordlen], pset.encoding);
2202 if (wordlen == 12 && pg_strncasecmp(query, "concurrently", 12) == 0)
2211 /* DISCARD ALL isn't allowed in xacts, but other variants are allowed. */
2212 if (wordlen == 7 && pg_strncasecmp(query, "discard", 7) == 0)
2216 query = skip_white_space(query);
2219 while (isalpha((unsigned char) query[wordlen]))
2220 wordlen += PQmblen(&query[wordlen], pset.encoding);
2222 if (wordlen == 3 && pg_strncasecmp(query, "all", 3) == 0)
2232 * Check whether the specified command is a SELECT (or VALUES).
2235 is_select_command(const char *query)
2240 * First advance over any whitespace, comments and left parentheses.
2244 query = skip_white_space(query);
2245 if (query[0] == '(')
2252 * Check word length (since "selectx" is not "select").
2255 while (isalpha((unsigned char) query[wordlen]))
2256 wordlen += PQmblen(&query[wordlen], pset.encoding);
2258 if (wordlen == 6 && pg_strncasecmp(query, "select", 6) == 0)
2261 if (wordlen == 6 && pg_strncasecmp(query, "values", 6) == 0)
2269 * Test if the current user is a database superuser.
2271 * Note: this will correctly detect superuserness only with a protocol-3.0
2272 * or newer backend; otherwise it will always say "false".
2282 val = PQparameterStatus(pset.db, "is_superuser");
2284 if (val && strcmp(val, "on") == 0)
2292 * Test if the current session uses standard string literals.
2294 * Note: With a pre-protocol-3.0 connection this will always say "false",
2295 * which should be the right answer.
2298 standard_strings(void)
2305 val = PQparameterStatus(pset.db, "standard_conforming_strings");
2307 if (val && strcmp(val, "on") == 0)
2315 * Return the session user of the current connection.
2317 * Note: this will correctly detect the session user only with a
2318 * protocol-3.0 or newer backend; otherwise it will return the
2322 session_username(void)
2329 val = PQparameterStatus(pset.db, "session_authorization");
2333 return PQuser(pset.db);
2339 * substitute '~' with HOME or '~username' with username's home dir
2343 expand_tilde(char **filename)
2345 if (!filename || !(*filename))
2349 * WIN32 doesn't use tilde expansion for file names. Also, it uses tilde
2350 * for short versions of long file names, though the tilde is usually
2351 * toward the end, not at the beginning.
2355 /* try tilde expansion */
2356 if (**filename == '~')
2362 char home[MAXPGPATH];
2368 while (*p != '/' && *p != '\0')
2374 if (*(fn + 1) == '\0')
2375 get_home_path(home); /* ~ or ~/ only */
2376 else if ((pw = getpwnam(fn + 1)) != NULL)
2377 strlcpy(home, pw->pw_dir, sizeof(home)); /* ~user */
2380 if (strlen(home) != 0)
2384 newfn = psprintf("%s%s", home, p);
2395 * Checks if connection string starts with either of the valid URI prefix
2398 * Returns the URI prefix length, 0 if the string doesn't contain a URI prefix.
2400 * XXX This is a duplicate of the eponymous libpq function.
2403 uri_prefix_length(const char *connstr)
2405 /* The connection URI must start with either of the following designators: */
2406 static const char uri_designator[] = "postgresql://";
2407 static const char short_uri_designator[] = "postgres://";
2409 if (strncmp(connstr, uri_designator,
2410 sizeof(uri_designator) - 1) == 0)
2411 return sizeof(uri_designator) - 1;
2413 if (strncmp(connstr, short_uri_designator,
2414 sizeof(short_uri_designator) - 1) == 0)
2415 return sizeof(short_uri_designator) - 1;
2421 * Recognized connection string either starts with a valid URI prefix or
2422 * contains a "=" in it.
2424 * Must be consistent with parse_connection_string: anything for which this
2425 * returns true should at least look like it's parseable by that routine.
2427 * XXX This is a duplicate of the eponymous libpq function.
2430 recognized_connection_string(const char *connstr)
2432 return uri_prefix_length(connstr) != 0 || strchr(connstr, '=') != NULL;