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"
16 #include <unistd.h> /* for write() */
18 #include <io.h> /* for _write() */
22 #include "fe_utils/string_utils.h"
23 #include "portability/instr_time.h"
28 #include "crosstabview.h"
29 #include "fe_utils/mbprint.h"
32 static bool DescribeQuery(const char *query, double *elapsed_msec);
33 static bool ExecQueryUsingCursor(const char *query, double *elapsed_msec);
34 static bool command_no_begin(const char *query);
35 static bool is_select_command(const char *query);
39 * openQueryOutputFile --- attempt to open a query output file
41 * fname == NULL selects stdout, else an initial '|' selects a pipe,
44 * Returns output file pointer into *fout, and is-a-pipe flag into *is_pipe.
45 * Caller is responsible for adjusting SIGPIPE state if it's a pipe.
47 * On error, reports suitable error message and returns false.
50 openQueryOutputFile(const char *fname, FILE **fout, bool *is_pipe)
52 if (!fname || fname[0] == '\0')
57 else if (*fname == '|')
59 *fout = popen(fname + 1, "w");
64 *fout = fopen(fname, "w");
70 psql_error("%s: %s\n", fname, strerror(errno));
79 * -- handler for -o command line option and \o command
81 * On success, updates pset with the new output file and returns true.
82 * On failure, returns false without changing pset state.
85 setQFout(const char *fname)
90 /* First make sure we can open the new output file/pipe */
91 if (!openQueryOutputFile(fname, &fout, &is_pipe))
94 /* Close old file/pipe */
95 if (pset.queryFout && pset.queryFout != stdout && pset.queryFout != stderr)
97 if (pset.queryFoutPipe)
98 pclose(pset.queryFout);
100 fclose(pset.queryFout);
103 pset.queryFout = fout;
104 pset.queryFoutPipe = is_pipe;
106 /* Adjust SIGPIPE handling appropriately: ignore signal if is_pipe */
107 set_sigpipe_trap_state(is_pipe);
108 restore_sigpipe_trap();
115 * Variable-fetching callback for flex lexer
117 * If the specified variable exists, return its value as a string (malloc'd
118 * and expected to be freed by the caller); else return NULL.
120 * If "quote" isn't PQUOTE_PLAIN, then return the value suitably quoted and
121 * escaped for the specified quoting requirement. (Failure in escaping
122 * should lead to printing an error and returning NULL.)
124 * "passthrough" is the pointer previously given to psql_scan_set_passthrough.
125 * In psql, passthrough points to a ConditionalStack, which we check to
126 * determine whether variable expansion is allowed.
129 psql_get_variable(const char *varname, PsqlScanQuoteType quote,
135 /* In an inactive \if branch, suppress all variable substitutions */
136 if (passthrough && !conditional_active((ConditionalStack) passthrough))
139 value = GetVariable(pset.vars, varname);
146 result = pg_strdup(value);
148 case PQUOTE_SQL_LITERAL:
149 case PQUOTE_SQL_IDENT:
152 * For these cases, we use libpq's quoting functions, which
153 * assume the string is in the connection's client encoding.
159 psql_error("cannot escape without active connection\n");
163 if (quote == PQUOTE_SQL_LITERAL)
165 PQescapeLiteral(pset.db, value, strlen(value));
168 PQescapeIdentifier(pset.db, value, strlen(value));
170 if (escaped_value == NULL)
172 const char *error = PQerrorMessage(pset.db);
174 psql_error("%s", error);
179 * Rather than complicate the lexer's API with a notion of
180 * which free() routine to use, just pay the price of an extra
183 result = pg_strdup(escaped_value);
184 PQfreemem(escaped_value);
187 case PQUOTE_SHELL_ARG:
190 * For this we use appendShellStringNoError, which is
191 * encoding-agnostic, which is fine since the shell probably
192 * is too. In any case, the only special character is "'",
193 * which is not known to appear in valid multibyte characters.
197 initPQExpBuffer(&buf);
198 if (!appendShellStringNoError(&buf, value))
200 psql_error("shell command argument contains a newline or carriage return: \"%s\"\n",
209 /* No default: we want a compiler warning for missing cases */
217 * Error reporting for scripts. Errors should look like
218 * psql:filename:lineno: message
221 psql_error(const char *fmt,...)
226 if (pset.queryFout && pset.queryFout != stdout)
227 fflush(pset.queryFout);
230 fprintf(stderr, "%s:%s:" UINT64_FORMAT ": ", pset.progname, pset.inputfile, pset.lineno);
232 vfprintf(stderr, _(fmt), ap);
239 * for backend Notice messages (INFO, WARNING, etc)
242 NoticeProcessor(void *arg, const char *message)
244 (void) arg; /* not used */
245 psql_error("%s", message);
251 * Code to support query cancellation
253 * Before we start a query, we enable the SIGINT signal catcher to send a
254 * cancel request to the backend. Note that sending the cancel directly from
255 * the signal handler is safe because PQcancel() is written to make it
256 * so. We use write() to report to stderr because it's better to use simple
257 * facilities in a signal handler.
259 * On win32, the signal canceling happens on a separate thread, because
260 * that's how SetConsoleCtrlHandler works. The PQcancel function is safe
261 * for this (unlike PQrequestCancel). However, a CRITICAL_SECTION is required
262 * to protect the PGcancel structure against being changed while the signal
263 * thread is using it.
265 * SIGINT is supposed to abort all long-running psql operations, not only
266 * database queries. In most places, this is accomplished by checking
267 * cancel_pressed during long-running loops. However, that won't work when
268 * blocked on user input (in readline() or fgets()). In those places, we
269 * set sigint_interrupt_enabled true while blocked, instructing the signal
270 * catcher to longjmp through sigint_interrupt_jmp. We assume readline and
271 * fgets are coded to handle possible interruption. (XXX currently this does
272 * not work on win32, so control-C is less useful there)
274 volatile bool sigint_interrupt_enabled = false;
276 sigjmp_buf sigint_interrupt_jmp;
278 static PGcancel *volatile cancelConn = NULL;
281 static CRITICAL_SECTION cancelConnLock;
285 * Write a simple string to stderr --- must be safe in a signal handler.
286 * We ignore the write() result since there's not much we could do about it.
287 * Certain compilers make that harder than it ought to be.
289 #define write_stderr(str) \
291 const char *str_ = (str); \
293 rc_ = write(fileno(stderr), str_, strlen(str_)); \
301 handle_sigint(SIGNAL_ARGS)
303 int save_errno = errno;
306 /* if we are waiting for input, longjmp out of it */
307 if (sigint_interrupt_enabled)
309 sigint_interrupt_enabled = false;
310 siglongjmp(sigint_interrupt_jmp, 1);
313 /* else, set cancel flag to stop any long-running loops */
314 cancel_pressed = true;
316 /* and send QueryCancel if we are processing a database query */
317 if (cancelConn != NULL)
319 if (PQcancel(cancelConn, errbuf, sizeof(errbuf)))
320 write_stderr("Cancel request sent\n");
323 write_stderr("Could not send cancel request: ");
324 write_stderr(errbuf);
328 errno = save_errno; /* just in case the write changed it */
332 setup_cancel_handler(void)
334 pqsignal(SIGINT, handle_sigint);
339 consoleHandler(DWORD dwCtrlType)
343 if (dwCtrlType == CTRL_C_EVENT ||
344 dwCtrlType == CTRL_BREAK_EVENT)
347 * Can't longjmp here, because we are in wrong thread :-(
350 /* set cancel flag to stop any long-running loops */
351 cancel_pressed = true;
353 /* and send QueryCancel if we are processing a database query */
354 EnterCriticalSection(&cancelConnLock);
355 if (cancelConn != NULL)
357 if (PQcancel(cancelConn, errbuf, sizeof(errbuf)))
358 write_stderr("Cancel request sent\n");
361 write_stderr("Could not send cancel request: ");
362 write_stderr(errbuf);
365 LeaveCriticalSection(&cancelConnLock);
370 /* Return FALSE for any signals not being handled */
375 setup_cancel_handler(void)
377 InitializeCriticalSection(&cancelConnLock);
379 SetConsoleCtrlHandler(consoleHandler, TRUE);
386 * Returns whether our backend connection is still there.
391 return PQstatus(pset.db) != CONNECTION_BAD;
398 * Verify that we still have a good connection to the backend, and if not,
399 * see if it can be restored.
401 * Returns true if either the connection was still there, or it could be
402 * restored successfully; false otherwise. If, however, there was no
403 * connection and the session is non-interactive, this will exit the program
404 * with a code of EXIT_BADCONN.
407 CheckConnection(void)
414 if (!pset.cur_cmd_interactive)
416 psql_error("connection to server was lost\n");
420 psql_error("The connection to the server was lost. Attempting reset: ");
425 psql_error("Failed.\n");
432 psql_error("Succeeded.\n");
443 * Set cancelConn to point to the current database connection.
448 PGcancel *oldCancelConn;
451 EnterCriticalSection(&cancelConnLock);
454 /* Free the old one if we have one */
455 oldCancelConn = cancelConn;
456 /* be sure handle_sigint doesn't use pointer while freeing */
459 if (oldCancelConn != NULL)
460 PQfreeCancel(oldCancelConn);
462 cancelConn = PQgetCancel(pset.db);
465 LeaveCriticalSection(&cancelConnLock);
473 * Free the current cancel connection, if any, and set to NULL.
476 ResetCancelConn(void)
478 PGcancel *oldCancelConn;
481 EnterCriticalSection(&cancelConnLock);
484 oldCancelConn = cancelConn;
485 /* be sure handle_sigint doesn't use pointer while freeing */
488 if (oldCancelConn != NULL)
489 PQfreeCancel(oldCancelConn);
492 LeaveCriticalSection(&cancelConnLock);
500 * Checks whether a result is valid, giving an error message if necessary;
501 * and ensures that the connection to the backend is still up.
503 * Returns true for valid result, false for error state.
506 AcceptResult(const PGresult *result)
513 switch (PQresultStatus(result))
515 case PGRES_COMMAND_OK:
516 case PGRES_TUPLES_OK:
517 case PGRES_EMPTY_QUERY:
520 /* Fine, do nothing */
524 case PGRES_BAD_RESPONSE:
525 case PGRES_NONFATAL_ERROR:
526 case PGRES_FATAL_ERROR:
532 psql_error("unexpected PQresultStatus: %d\n",
533 PQresultStatus(result));
539 const char *error = PQerrorMessage(pset.db);
542 psql_error("%s", error);
552 * Set special variables from a query result
553 * - ERROR: true/false, whether an error occurred on this query
554 * - SQLSTATE: code of error, or "00000" if no error, or "" if unknown
555 * - ROW_COUNT: how many rows were returned or affected, or "0"
556 * - LAST_ERROR_SQLSTATE: same for last error
557 * - LAST_ERROR_MESSAGE: message of last error
559 * Note: current policy is to apply this only to the results of queries
560 * entered by the user, not queries generated by slash commands.
563 SetResultVariables(PGresult *results, bool success)
567 const char *ntuples = PQcmdTuples(results);
569 SetVariable(pset.vars, "ERROR", "false");
570 SetVariable(pset.vars, "SQLSTATE", "00000");
571 SetVariable(pset.vars, "ROW_COUNT", *ntuples ? ntuples : "0");
575 const char *code = PQresultErrorField(results, PG_DIAG_SQLSTATE);
576 const char *mesg = PQresultErrorField(results, PG_DIAG_MESSAGE_PRIMARY);
578 SetVariable(pset.vars, "ERROR", "true");
581 * If there is no SQLSTATE code, use an empty string. This can happen
582 * for libpq-detected errors (e.g., lost connection, ENOMEM).
586 SetVariable(pset.vars, "SQLSTATE", code);
587 SetVariable(pset.vars, "ROW_COUNT", "0");
588 SetVariable(pset.vars, "LAST_ERROR_SQLSTATE", code);
589 SetVariable(pset.vars, "LAST_ERROR_MESSAGE", mesg ? mesg : "");
597 * If the result represents an error, remember it for possible display by
598 * \errverbose. Otherwise, just PQclear() it.
600 * Note: current policy is to apply this to the results of all queries,
601 * including "back door" queries, for debugging's sake. It's OK to use
602 * PQclear() directly on results known to not be error results, however.
605 ClearOrSaveResult(PGresult *result)
609 switch (PQresultStatus(result))
611 case PGRES_NONFATAL_ERROR:
612 case PGRES_FATAL_ERROR:
613 if (pset.last_error_result)
614 PQclear(pset.last_error_result);
615 pset.last_error_result = result;
627 * Print microtiming output. Always print raw milliseconds; if the interval
628 * is >= 1 second, also break it down into days/hours/minutes/seconds.
631 PrintTiming(double elapsed_msec)
638 if (elapsed_msec < 1000.0)
640 /* This is the traditional (pre-v10) output format */
641 printf(_("Time: %.3f ms\n"), elapsed_msec);
646 * Note: we could print just seconds, in a format like %06.3f, when the
647 * total is less than 1min. But that's hard to interpret unless we tack
648 * on "s" or otherwise annotate it. Forcing the display to include
649 * minutes seems like a better solution.
651 seconds = elapsed_msec / 1000.0;
652 minutes = floor(seconds / 60.0);
653 seconds -= 60.0 * minutes;
656 printf(_("Time: %.3f ms (%02d:%06.3f)\n"),
657 elapsed_msec, (int) minutes, seconds);
661 hours = floor(minutes / 60.0);
662 minutes -= 60.0 * hours;
665 printf(_("Time: %.3f ms (%02d:%02d:%06.3f)\n"),
666 elapsed_msec, (int) hours, (int) minutes, seconds);
670 days = floor(hours / 24.0);
671 hours -= 24.0 * days;
672 printf(_("Time: %.3f ms (%.0f d %02d:%02d:%06.3f)\n"),
673 elapsed_msec, days, (int) hours, (int) minutes, seconds);
680 * This is the way to send "backdoor" queries (those not directly entered
681 * by the user). It is subject to -E but not -e.
683 * Caller is responsible for handling the ensuing processing if a COPY
686 * Note: we don't bother to check PQclientEncoding; it is assumed that no
687 * caller uses this path to issue "SET CLIENT_ENCODING".
690 PSQLexec(const char *query)
696 psql_error("You are currently not connected to a database.\n");
700 if (pset.echo_hidden != PSQL_ECHO_HIDDEN_OFF)
702 printf(_("********* QUERY **********\n"
704 "**************************\n\n"), query);
708 fprintf(pset.logfile,
709 _("********* QUERY **********\n"
711 "**************************\n\n"), query);
712 fflush(pset.logfile);
715 if (pset.echo_hidden == PSQL_ECHO_HIDDEN_NOEXEC)
721 res = PQexec(pset.db, query);
725 if (!AcceptResult(res))
727 ClearOrSaveResult(res);
738 * This function is used for \watch command to send the query to
739 * the server and print out the results.
741 * Returns 1 if the query executed successfully, 0 if it cannot be repeated,
742 * e.g., because of the interrupt, -1 on error.
745 PSQLexecWatch(const char *query, const printQueryOpt *opt)
748 double elapsed_msec = 0;
754 psql_error("You are currently not connected to a database.\n");
761 INSTR_TIME_SET_CURRENT(before);
763 res = PQexec(pset.db, query);
767 if (!AcceptResult(res))
769 ClearOrSaveResult(res);
775 INSTR_TIME_SET_CURRENT(after);
776 INSTR_TIME_SUBTRACT(after, before);
777 elapsed_msec = INSTR_TIME_GET_MILLISEC(after);
781 * If SIGINT is sent while the query is processing, the interrupt will be
782 * consumed. The user's intention, though, is to cancel the entire watch
783 * process, so detect a sent cancellation request and exit in this case.
791 switch (PQresultStatus(res))
793 case PGRES_TUPLES_OK:
794 printQuery(res, opt, pset.queryFout, false, pset.logfile);
797 case PGRES_COMMAND_OK:
798 fprintf(pset.queryFout, "%s\n%s\n\n", opt->title, PQcmdStatus(res));
801 case PGRES_EMPTY_QUERY:
802 psql_error("\\watch cannot be used with an empty query\n");
808 case PGRES_COPY_BOTH:
809 psql_error("\\watch cannot be used with COPY\n");
814 psql_error("unexpected result status for \\watch\n");
821 fflush(pset.queryFout);
823 /* Possible microtiming output */
825 PrintTiming(elapsed_msec);
832 * PrintNotifications: check for asynchronous notifications, and print them out
835 PrintNotifications(void)
839 PQconsumeInput(pset.db);
840 while ((notify = PQnotifies(pset.db)) != NULL)
842 /* for backward compatibility, only show payload if nonempty */
843 if (notify->extra[0])
844 fprintf(pset.queryFout, _("Asynchronous notification \"%s\" with payload \"%s\" received from server process with PID %d.\n"),
845 notify->relname, notify->extra, notify->be_pid);
847 fprintf(pset.queryFout, _("Asynchronous notification \"%s\" received from server process with PID %d.\n"),
848 notify->relname, notify->be_pid);
849 fflush(pset.queryFout);
851 PQconsumeInput(pset.db);
857 * PrintQueryTuples: assuming query result is OK, print its tuples
859 * Returns true if successful, false otherwise.
862 PrintQueryTuples(const PGresult *results)
864 printQueryOpt my_popt = pset.popt;
866 /* one-shot expanded output requested via \gx */
868 my_popt.topt.expanded = 1;
870 /* write output to \g argument, if any */
876 if (!openQueryOutputFile(pset.gfname, &fout, &is_pipe))
879 disable_sigpipe_trap();
881 printQuery(results, &my_popt, fout, false, pset.logfile);
886 restore_sigpipe_trap();
892 printQuery(results, &my_popt, pset.queryFout, false, pset.logfile);
899 * StoreQueryTuple: assuming query result is OK, save data into variables
901 * Returns true if successful, false otherwise.
904 StoreQueryTuple(const PGresult *result)
908 if (PQntuples(result) < 1)
910 psql_error("no rows returned for \\gset\n");
913 else if (PQntuples(result) > 1)
915 psql_error("more than one row returned for \\gset\n");
922 for (i = 0; i < PQnfields(result); i++)
924 char *colname = PQfname(result, i);
928 /* concatenate prefix and column name */
929 varname = psprintf("%s%s", pset.gset_prefix, colname);
931 if (!PQgetisnull(result, 0, i))
932 value = PQgetvalue(result, 0, i);
935 /* for NULL value, unset rather than set the variable */
939 if (!SetVariable(pset.vars, varname, value))
955 * ExecQueryTuples: assuming query result is OK, execute each query
956 * result field as a SQL statement
958 * Returns true if successful, false otherwise.
961 ExecQueryTuples(const PGresult *result)
964 int nrows = PQntuples(result);
965 int ncolumns = PQnfields(result);
970 * We must turn off gexec_flag to avoid infinite recursion. Note that
971 * this allows ExecQueryUsingCursor to be applied to the individual query
972 * results. SendQuery prevents it from being applied when fetching the
973 * queries-to-execute, because it can't handle recursion either.
975 pset.gexec_flag = false;
977 for (r = 0; r < nrows; r++)
979 for (c = 0; c < ncolumns; c++)
981 if (!PQgetisnull(result, r, c))
983 const char *query = PQgetvalue(result, r, c);
985 /* Abandon execution if cancel_pressed */
990 * ECHO_ALL mode should echo these queries, but SendQuery
991 * assumes that MainLoop did that, so we have to do it here.
993 if (pset.echo == PSQL_ECHO_ALL && !pset.singlestep)
999 if (!SendQuery(query))
1001 /* Error - abandon execution if ON_ERROR_STOP */
1003 if (pset.on_error_stop)
1013 * Restore state. We know gexec_flag was on, else we'd not be here. (We
1014 * also know it'll get turned off at end of command, but that's not ours
1017 pset.gexec_flag = true;
1019 /* Return true if all queries were successful */
1025 * ProcessResult: utility function for use by SendQuery() only
1027 * When our command string contained a COPY FROM STDIN or COPY TO STDOUT,
1028 * PQexec() has stopped at the PGresult associated with the first such
1029 * command. In that event, we'll marshal data for the COPY and then cycle
1030 * through any subsequent PGresult objects.
1032 * When the command string contained no such COPY command, this function
1033 * degenerates to an AcceptResult() call.
1035 * Changes its argument to point to the last PGresult of the command string,
1036 * or NULL if that result was for a COPY TO STDOUT. (Returning NULL prevents
1037 * the command status from being printed, which we want in that case so that
1038 * the status line doesn't get taken as part of the COPY data.)
1040 * Returns true on complete success, false otherwise. Possible failure modes
1041 * include purely client-side problems; check the transaction status for the
1042 * server-side opinion.
1045 ProcessResult(PGresult **results)
1047 bool success = true;
1048 bool first_cycle = true;
1052 ExecStatusType result_status;
1054 PGresult *next_result;
1056 if (!AcceptResult(*results))
1059 * Failure at this point is always a server-side failure or a
1060 * failure to submit the command string. Either way, we're
1061 * finished with this command string.
1067 result_status = PQresultStatus(*results);
1068 switch (result_status)
1070 case PGRES_EMPTY_QUERY:
1071 case PGRES_COMMAND_OK:
1072 case PGRES_TUPLES_OK:
1076 case PGRES_COPY_OUT:
1082 /* AcceptResult() should have caught anything else. */
1084 psql_error("unexpected PQresultStatus: %d\n", result_status);
1091 * Marshal the COPY data. Either subroutine will get the
1092 * connection out of its COPY state, then call PQresultStatus()
1093 * once and report any error.
1095 * For COPY OUT, direct the output to pset.copyStream if it's set,
1096 * otherwise to pset.gfname if it's set, otherwise to queryFout.
1097 * For COPY IN, use pset.copyStream as data source if it's set,
1098 * otherwise cur_cmd_source.
1101 PGresult *copy_result;
1104 if (result_status == PGRES_COPY_OUT)
1106 bool need_close = false;
1107 bool is_pipe = false;
1109 if (pset.copyStream)
1111 /* invoked by \copy */
1112 copystream = pset.copyStream;
1114 else if (pset.gfname)
1117 if (openQueryOutputFile(pset.gfname,
1118 ©stream, &is_pipe))
1122 disable_sigpipe_trap();
1125 copystream = NULL; /* discard COPY data entirely */
1129 /* fall back to the generic query output stream */
1130 copystream = pset.queryFout;
1133 success = handleCopyOut(pset.db,
1137 && (copystream != NULL);
1140 * Suppress status printing if the report would go to the same
1141 * place as the COPY data just went. Note this doesn't
1142 * prevent error reporting, since handleCopyOut did that.
1144 if (copystream == pset.queryFout)
1146 PQclear(copy_result);
1152 /* close \g argument file/pipe */
1156 restore_sigpipe_trap();
1167 copystream = pset.copyStream ? pset.copyStream : pset.cur_cmd_source;
1168 success = handleCopyIn(pset.db,
1170 PQbinaryTuples(*results),
1171 ©_result) && success;
1176 * Replace the PGRES_COPY_OUT/IN result with COPY command's exit
1177 * status, or with NULL if we want to suppress printing anything.
1180 *results = copy_result;
1182 else if (first_cycle)
1184 /* fast path: no COPY commands; PQexec visited all results */
1189 * Check PQgetResult() again. In the typical case of a single-command
1190 * string, it will return NULL. Otherwise, we'll have other results
1191 * to process that may include other COPYs. We keep the last result.
1193 next_result = PQgetResult(pset.db);
1198 *results = next_result;
1199 first_cycle = false;
1202 SetResultVariables(*results, success);
1204 /* may need this to recover from conn loss during COPY */
1205 if (!first_cycle && !CheckConnection())
1213 * PrintQueryStatus: report command status as required
1215 * Note: Utility function for use by PrintQueryResults() only.
1218 PrintQueryStatus(PGresult *results)
1224 if (pset.popt.topt.format == PRINT_HTML)
1226 fputs("<p>", pset.queryFout);
1227 html_escaped_print(PQcmdStatus(results), pset.queryFout);
1228 fputs("</p>\n", pset.queryFout);
1231 fprintf(pset.queryFout, "%s\n", PQcmdStatus(results));
1235 fprintf(pset.logfile, "%s\n", PQcmdStatus(results));
1237 snprintf(buf, sizeof(buf), "%u", (unsigned int) PQoidValue(results));
1238 SetVariable(pset.vars, "LASTOID", buf);
1243 * PrintQueryResults: print out (or store or execute) query results as required
1245 * Note: Utility function for use by SendQuery() only.
1247 * Returns true if the query executed successfully, false otherwise.
1250 PrintQueryResults(PGresult *results)
1253 const char *cmdstatus;
1258 switch (PQresultStatus(results))
1260 case PGRES_TUPLES_OK:
1261 /* store or execute or print the data ... */
1262 if (pset.gset_prefix)
1263 success = StoreQueryTuple(results);
1264 else if (pset.gexec_flag)
1265 success = ExecQueryTuples(results);
1266 else if (pset.crosstab_flag)
1267 success = PrintResultsInCrosstab(results);
1269 success = PrintQueryTuples(results);
1270 /* if it's INSERT/UPDATE/DELETE RETURNING, also print status */
1271 cmdstatus = PQcmdStatus(results);
1272 if (strncmp(cmdstatus, "INSERT", 6) == 0 ||
1273 strncmp(cmdstatus, "UPDATE", 6) == 0 ||
1274 strncmp(cmdstatus, "DELETE", 6) == 0)
1275 PrintQueryStatus(results);
1278 case PGRES_COMMAND_OK:
1279 PrintQueryStatus(results);
1283 case PGRES_EMPTY_QUERY:
1287 case PGRES_COPY_OUT:
1289 /* nothing to do here */
1293 case PGRES_BAD_RESPONSE:
1294 case PGRES_NONFATAL_ERROR:
1295 case PGRES_FATAL_ERROR:
1301 psql_error("unexpected PQresultStatus: %d\n",
1302 PQresultStatus(results));
1306 fflush(pset.queryFout);
1313 * SendQuery: send the query string to the backend
1314 * (and print out results)
1316 * Note: This is the "front door" way to send a query. That is, use it to
1317 * send queries actually entered by the user. These queries will be subject to
1319 * To send "back door" queries (generated by slash commands, etc.) in a
1320 * controlled way, use PSQLexec().
1322 * Returns true if the query executed successfully, false otherwise.
1325 SendQuery(const char *query)
1328 PGTransactionStatusType transaction_status;
1329 double elapsed_msec = 0;
1332 bool on_error_rollback_savepoint = false;
1333 static bool on_error_rollback_warning = false;
1337 psql_error("You are currently not connected to a database.\n");
1338 goto sendquery_cleanup;
1341 if (pset.singlestep)
1346 printf(_("***(Single step mode: verify command)*******************************************\n"
1348 "***(press return to proceed or enter x and return to cancel)********************\n"),
1351 if (fgets(buf, sizeof(buf), stdin) != NULL)
1353 goto sendquery_cleanup;
1355 goto sendquery_cleanup;
1357 else if (pset.echo == PSQL_ECHO_QUERIES)
1365 fprintf(pset.logfile,
1366 _("********* QUERY **********\n"
1368 "**************************\n\n"), query);
1369 fflush(pset.logfile);
1374 transaction_status = PQtransactionStatus(pset.db);
1376 if (transaction_status == PQTRANS_IDLE &&
1378 !command_no_begin(query))
1380 results = PQexec(pset.db, "BEGIN");
1381 if (PQresultStatus(results) != PGRES_COMMAND_OK)
1383 psql_error("%s", PQerrorMessage(pset.db));
1384 ClearOrSaveResult(results);
1386 goto sendquery_cleanup;
1388 ClearOrSaveResult(results);
1389 transaction_status = PQtransactionStatus(pset.db);
1392 if (transaction_status == PQTRANS_INTRANS &&
1393 pset.on_error_rollback != PSQL_ERROR_ROLLBACK_OFF &&
1394 (pset.cur_cmd_interactive ||
1395 pset.on_error_rollback == PSQL_ERROR_ROLLBACK_ON))
1397 if (on_error_rollback_warning == false && pset.sversion < 80000)
1401 psql_error("The server (version %s) does not support savepoints for ON_ERROR_ROLLBACK.\n",
1402 formatPGVersionNumber(pset.sversion, false,
1403 sverbuf, sizeof(sverbuf)));
1404 on_error_rollback_warning = true;
1408 results = PQexec(pset.db, "SAVEPOINT pg_psql_temporary_savepoint");
1409 if (PQresultStatus(results) != PGRES_COMMAND_OK)
1411 psql_error("%s", PQerrorMessage(pset.db));
1412 ClearOrSaveResult(results);
1414 goto sendquery_cleanup;
1416 ClearOrSaveResult(results);
1417 on_error_rollback_savepoint = true;
1421 if (pset.gdesc_flag)
1423 /* Describe query's result columns, without executing it */
1424 OK = DescribeQuery(query, &elapsed_msec);
1426 results = NULL; /* PQclear(NULL) does nothing */
1428 else if (pset.fetch_count <= 0 || pset.gexec_flag ||
1429 pset.crosstab_flag || !is_select_command(query))
1431 /* Default fetch-it-all-and-print mode */
1436 INSTR_TIME_SET_CURRENT(before);
1438 results = PQexec(pset.db, query);
1440 /* these operations are included in the timing result: */
1442 OK = ProcessResult(&results);
1446 INSTR_TIME_SET_CURRENT(after);
1447 INSTR_TIME_SUBTRACT(after, before);
1448 elapsed_msec = INSTR_TIME_GET_MILLISEC(after);
1451 /* but printing results isn't: */
1453 OK = PrintQueryResults(results);
1457 /* Fetch-in-segments mode */
1458 OK = ExecQueryUsingCursor(query, &elapsed_msec);
1460 results = NULL; /* PQclear(NULL) does nothing */
1463 if (!OK && pset.echo == PSQL_ECHO_ERRORS)
1464 psql_error("STATEMENT: %s\n", query);
1466 /* If we made a temporary savepoint, possibly release/rollback */
1467 if (on_error_rollback_savepoint)
1469 const char *svptcmd = NULL;
1471 transaction_status = PQtransactionStatus(pset.db);
1473 switch (transaction_status)
1475 case PQTRANS_INERROR:
1476 /* We always rollback on an error */
1477 svptcmd = "ROLLBACK TO pg_psql_temporary_savepoint";
1481 /* If they are no longer in a transaction, then do nothing */
1484 case PQTRANS_INTRANS:
1487 * Do nothing if they are messing with savepoints themselves:
1488 * If the user did RELEASE or ROLLBACK, our savepoint is gone.
1489 * If they issued a SAVEPOINT, releasing ours would remove
1493 (strcmp(PQcmdStatus(results), "SAVEPOINT") == 0 ||
1494 strcmp(PQcmdStatus(results), "RELEASE") == 0 ||
1495 strcmp(PQcmdStatus(results), "ROLLBACK") == 0))
1498 svptcmd = "RELEASE pg_psql_temporary_savepoint";
1501 case PQTRANS_ACTIVE:
1502 case PQTRANS_UNKNOWN:
1505 /* PQTRANS_UNKNOWN is expected given a broken connection. */
1506 if (transaction_status != PQTRANS_UNKNOWN || ConnectionUp())
1507 psql_error("unexpected transaction status (%d)\n",
1508 transaction_status);
1516 svptres = PQexec(pset.db, svptcmd);
1517 if (PQresultStatus(svptres) != PGRES_COMMAND_OK)
1519 psql_error("%s", PQerrorMessage(pset.db));
1520 ClearOrSaveResult(svptres);
1525 goto sendquery_cleanup;
1531 ClearOrSaveResult(results);
1533 /* Possible microtiming output */
1535 PrintTiming(elapsed_msec);
1537 /* check for events that may occur during query execution */
1539 if (pset.encoding != PQclientEncoding(pset.db) &&
1540 PQclientEncoding(pset.db) >= 0)
1542 /* track effects of SET CLIENT_ENCODING */
1543 pset.encoding = PQclientEncoding(pset.db);
1544 pset.popt.topt.encoding = pset.encoding;
1545 SetVariable(pset.vars, "ENCODING",
1546 pg_encoding_to_char(pset.encoding));
1549 PrintNotifications();
1551 /* perform cleanup that should occur after any attempted query */
1555 /* reset \g's output-to-filename trigger */
1562 /* reset \gx's expanded-mode flag */
1563 pset.g_expanded = false;
1565 /* reset \gset trigger */
1566 if (pset.gset_prefix)
1568 free(pset.gset_prefix);
1569 pset.gset_prefix = NULL;
1572 /* reset \gdesc trigger */
1573 pset.gdesc_flag = false;
1575 /* reset \gexec trigger */
1576 pset.gexec_flag = false;
1578 /* reset \crosstabview trigger */
1579 pset.crosstab_flag = false;
1580 for (i = 0; i < lengthof(pset.ctv_args); i++)
1582 pg_free(pset.ctv_args[i]);
1583 pset.ctv_args[i] = NULL;
1591 * DescribeQuery: describe the result columns of a query, without executing it
1593 * Returns true if the operation executed successfully, false otherwise.
1595 * If pset.timing is on, total query time (exclusive of result-printing) is
1596 * stored into *elapsed_msec.
1599 DescribeQuery(const char *query, double *elapsed_msec)
1609 INSTR_TIME_SET_CURRENT(before);
1612 * To parse the query but not execute it, we prepare it, using the unnamed
1613 * prepared statement. This is invisible to psql users, since there's no
1614 * way to access the unnamed prepared statement from psql user space. The
1615 * next Parse or Query protocol message would overwrite the statement
1616 * anyway. (So there's no great need to clear it when done, which is a
1617 * good thing because libpq provides no easy way to do that.)
1619 results = PQprepare(pset.db, "", query, 0, NULL);
1620 if (PQresultStatus(results) != PGRES_COMMAND_OK)
1622 psql_error("%s", PQerrorMessage(pset.db));
1623 SetResultVariables(results, false);
1624 ClearOrSaveResult(results);
1629 results = PQdescribePrepared(pset.db, "");
1630 OK = AcceptResult(results) &&
1631 (PQresultStatus(results) == PGRES_COMMAND_OK);
1634 if (PQnfields(results) > 0)
1636 PQExpBufferData buf;
1639 initPQExpBuffer(&buf);
1641 printfPQExpBuffer(&buf,
1642 "SELECT name AS \"%s\", pg_catalog.format_type(tp, tpm) AS \"%s\"\n"
1644 gettext_noop("Column"),
1645 gettext_noop("Type"));
1647 for (i = 0; i < PQnfields(results); i++)
1653 appendPQExpBufferStr(&buf, ",");
1655 name = PQfname(results, i);
1656 escname = PQescapeLiteral(pset.db, name, strlen(name));
1658 if (escname == NULL)
1660 psql_error("%s", PQerrorMessage(pset.db));
1662 termPQExpBuffer(&buf);
1666 appendPQExpBuffer(&buf, "(%s, '%u'::pg_catalog.oid, %d)",
1668 PQftype(results, i),
1669 PQfmod(results, i));
1674 appendPQExpBufferStr(&buf, ") s(name, tp, tpm)");
1677 results = PQexec(pset.db, buf.data);
1678 OK = AcceptResult(results);
1682 INSTR_TIME_SET_CURRENT(after);
1683 INSTR_TIME_SUBTRACT(after, before);
1684 *elapsed_msec += INSTR_TIME_GET_MILLISEC(after);
1688 OK = PrintQueryResults(results);
1690 termPQExpBuffer(&buf);
1693 fprintf(pset.queryFout,
1694 _("The command has no result, or the result has no columns.\n"));
1697 SetResultVariables(results, OK);
1698 ClearOrSaveResult(results);
1705 * ExecQueryUsingCursor: run a SELECT-like query using a cursor
1707 * This feature allows result sets larger than RAM to be dealt with.
1709 * Returns true if the query executed successfully, false otherwise.
1711 * If pset.timing is on, total query time (exclusive of result-printing) is
1712 * stored into *elapsed_msec.
1715 ExecQueryUsingCursor(const char *query, double *elapsed_msec)
1719 PQExpBufferData buf;
1720 printQueryOpt my_popt = pset.popt;
1723 bool is_pager = false;
1724 bool started_txn = false;
1725 int64 total_tuples = 0;
1735 /* initialize print options for partial table output */
1736 my_popt.topt.start_table = true;
1737 my_popt.topt.stop_table = false;
1738 my_popt.topt.prior_records = 0;
1741 INSTR_TIME_SET_CURRENT(before);
1743 /* if we're not in a transaction, start one */
1744 if (PQtransactionStatus(pset.db) == PQTRANS_IDLE)
1746 results = PQexec(pset.db, "BEGIN");
1747 OK = AcceptResult(results) &&
1748 (PQresultStatus(results) == PGRES_COMMAND_OK);
1749 ClearOrSaveResult(results);
1755 /* Send DECLARE CURSOR */
1756 initPQExpBuffer(&buf);
1757 appendPQExpBuffer(&buf, "DECLARE _psql_cursor NO SCROLL CURSOR FOR\n%s",
1760 results = PQexec(pset.db, buf.data);
1761 OK = AcceptResult(results) &&
1762 (PQresultStatus(results) == PGRES_COMMAND_OK);
1764 SetResultVariables(results, OK);
1765 ClearOrSaveResult(results);
1766 termPQExpBuffer(&buf);
1772 INSTR_TIME_SET_CURRENT(after);
1773 INSTR_TIME_SUBTRACT(after, before);
1774 *elapsed_msec += INSTR_TIME_GET_MILLISEC(after);
1778 * In \gset mode, we force the fetch count to be 2, so that we will throw
1779 * the appropriate error if the query returns more than one row.
1781 if (pset.gset_prefix)
1784 fetch_count = pset.fetch_count;
1786 snprintf(fetch_cmd, sizeof(fetch_cmd),
1787 "FETCH FORWARD %d FROM _psql_cursor",
1790 /* one-shot expanded output requested via \gx */
1791 if (pset.g_expanded)
1792 my_popt.topt.expanded = 1;
1794 /* prepare to write output to \g argument, if any */
1797 if (!openQueryOutputFile(pset.gfname, &fout, &is_pipe))
1803 disable_sigpipe_trap();
1807 fout = pset.queryFout;
1808 is_pipe = false; /* doesn't matter */
1811 /* clear any pre-existing error indication on the output stream */
1817 INSTR_TIME_SET_CURRENT(before);
1819 /* get fetch_count tuples at a time */
1820 results = PQexec(pset.db, fetch_cmd);
1824 INSTR_TIME_SET_CURRENT(after);
1825 INSTR_TIME_SUBTRACT(after, before);
1826 *elapsed_msec += INSTR_TIME_GET_MILLISEC(after);
1829 if (PQresultStatus(results) != PGRES_TUPLES_OK)
1831 /* shut down pager before printing error message */
1838 OK = AcceptResult(results);
1840 SetResultVariables(results, OK);
1841 ClearOrSaveResult(results);
1845 if (pset.gset_prefix)
1847 /* StoreQueryTuple will complain if not exactly one row */
1848 OK = StoreQueryTuple(results);
1849 ClearOrSaveResult(results);
1854 * Note we do not deal with \gdesc, \gexec or \crosstabview modes here
1857 ntuples = PQntuples(results);
1858 total_tuples += ntuples;
1860 if (ntuples < fetch_count)
1862 /* this is the last result set, so allow footer decoration */
1863 my_popt.topt.stop_table = true;
1865 else if (fout == stdout && !is_pager)
1868 * If query requires multiple result sets, hack to ensure that
1869 * only one pager instance is used for the whole mess
1871 fout = PageOutput(INT_MAX, &(my_popt.topt));
1875 printQuery(results, &my_popt, fout, is_pager, pset.logfile);
1877 ClearOrSaveResult(results);
1879 /* after the first result set, disallow header decoration */
1880 my_popt.topt.start_table = false;
1881 my_popt.topt.prior_records += ntuples;
1884 * Make sure to flush the output stream, so intermediate results are
1885 * visible to the client immediately. We check the results because if
1886 * the pager dies/exits/etc, there's no sense throwing more data at
1889 flush_error = fflush(fout);
1892 * Check if we are at the end, if a cancel was pressed, or if there
1893 * were any errors either trying to flush out the results, or more
1894 * generally on the output stream at all. If we hit any errors
1895 * writing things to the stream, we presume $PAGER has disappeared and
1896 * stop bothering to pull down more data.
1898 if (ntuples < fetch_count || cancel_pressed || flush_error ||
1905 /* close \g argument file/pipe */
1909 restore_sigpipe_trap();
1916 /* close transient pager */
1923 * We don't have a PGresult here, and even if we did it wouldn't have
1924 * the right row count, so fake SetResultVariables(). In error cases,
1925 * we already set the result variables above.
1929 SetVariable(pset.vars, "ERROR", "false");
1930 SetVariable(pset.vars, "SQLSTATE", "00000");
1931 snprintf(buf, sizeof(buf), INT64_FORMAT, total_tuples);
1932 SetVariable(pset.vars, "ROW_COUNT", buf);
1937 INSTR_TIME_SET_CURRENT(before);
1940 * We try to close the cursor on either success or failure, but on failure
1941 * ignore the result (it's probably just a bleat about being in an aborted
1944 results = PQexec(pset.db, "CLOSE _psql_cursor");
1947 OK = AcceptResult(results) &&
1948 (PQresultStatus(results) == PGRES_COMMAND_OK);
1949 ClearOrSaveResult(results);
1956 results = PQexec(pset.db, OK ? "COMMIT" : "ROLLBACK");
1957 OK &= AcceptResult(results) &&
1958 (PQresultStatus(results) == PGRES_COMMAND_OK);
1959 ClearOrSaveResult(results);
1964 INSTR_TIME_SET_CURRENT(after);
1965 INSTR_TIME_SUBTRACT(after, before);
1966 *elapsed_msec += INSTR_TIME_GET_MILLISEC(after);
1974 * Advance the given char pointer over white space and SQL comments.
1977 skip_white_space(const char *query)
1979 int cnestlevel = 0; /* slash-star comment nest level */
1983 int mblen = PQmblen(query, pset.encoding);
1986 * Note: we assume the encoding is a superset of ASCII, so that for
1987 * example "query[0] == '/'" is meaningful. However, we do NOT assume
1988 * that the second and subsequent bytes of a multibyte character
1989 * couldn't look like ASCII characters; so it is critical to advance
1990 * by mblen, not 1, whenever we haven't exactly identified the
1991 * character we are skipping over.
1993 if (isspace((unsigned char) *query))
1995 else if (query[0] == '/' && query[1] == '*')
2000 else if (cnestlevel > 0 && query[0] == '*' && query[1] == '/')
2005 else if (cnestlevel == 0 && query[0] == '-' && query[1] == '-')
2010 * We have to skip to end of line since any slash-star inside the
2011 * -- comment does NOT start a slash-star comment.
2020 query += PQmblen(query, pset.encoding);
2023 else if (cnestlevel > 0)
2026 break; /* found first token */
2034 * Check whether a command is one of those for which we should NOT start
2035 * a new transaction block (ie, send a preceding BEGIN).
2037 * These include the transaction control statements themselves, plus
2038 * certain statements that the backend disallows inside transaction blocks.
2041 command_no_begin(const char *query)
2046 * First we must advance over any whitespace and comments.
2048 query = skip_white_space(query);
2051 * Check word length (since "beginx" is not "begin").
2054 while (isalpha((unsigned char) query[wordlen]))
2055 wordlen += PQmblen(&query[wordlen], pset.encoding);
2058 * Transaction control commands. These should include every keyword that
2059 * gives rise to a TransactionStmt in the backend grammar, except for the
2060 * savepoint-related commands.
2062 * (We assume that START must be START TRANSACTION, since there is
2063 * presently no other "START foo" command.)
2065 if (wordlen == 5 && pg_strncasecmp(query, "abort", 5) == 0)
2067 if (wordlen == 5 && pg_strncasecmp(query, "begin", 5) == 0)
2069 if (wordlen == 5 && pg_strncasecmp(query, "start", 5) == 0)
2071 if (wordlen == 6 && pg_strncasecmp(query, "commit", 6) == 0)
2073 if (wordlen == 3 && pg_strncasecmp(query, "end", 3) == 0)
2075 if (wordlen == 8 && pg_strncasecmp(query, "rollback", 8) == 0)
2077 if (wordlen == 7 && pg_strncasecmp(query, "prepare", 7) == 0)
2079 /* PREPARE TRANSACTION is a TC command, PREPARE foo is not */
2082 query = skip_white_space(query);
2085 while (isalpha((unsigned char) query[wordlen]))
2086 wordlen += PQmblen(&query[wordlen], pset.encoding);
2088 if (wordlen == 11 && pg_strncasecmp(query, "transaction", 11) == 0)
2094 * Commands not allowed within transactions. The statements checked for
2095 * here should be exactly those that call PreventInTransactionBlock() in
2098 if (wordlen == 6 && pg_strncasecmp(query, "vacuum", 6) == 0)
2100 if (wordlen == 7 && pg_strncasecmp(query, "cluster", 7) == 0)
2102 /* CLUSTER with any arguments is allowed in transactions */
2105 query = skip_white_space(query);
2107 if (isalpha((unsigned char) query[0]))
2108 return false; /* has additional words */
2109 return true; /* it's CLUSTER without arguments */
2112 if (wordlen == 6 && pg_strncasecmp(query, "create", 6) == 0)
2116 query = skip_white_space(query);
2119 while (isalpha((unsigned char) query[wordlen]))
2120 wordlen += PQmblen(&query[wordlen], pset.encoding);
2122 if (wordlen == 8 && pg_strncasecmp(query, "database", 8) == 0)
2124 if (wordlen == 10 && pg_strncasecmp(query, "tablespace", 10) == 0)
2127 /* CREATE [UNIQUE] INDEX CONCURRENTLY isn't allowed in xacts */
2128 if (wordlen == 6 && pg_strncasecmp(query, "unique", 6) == 0)
2132 query = skip_white_space(query);
2135 while (isalpha((unsigned char) query[wordlen]))
2136 wordlen += PQmblen(&query[wordlen], pset.encoding);
2139 if (wordlen == 5 && pg_strncasecmp(query, "index", 5) == 0)
2143 query = skip_white_space(query);
2146 while (isalpha((unsigned char) query[wordlen]))
2147 wordlen += PQmblen(&query[wordlen], pset.encoding);
2149 if (wordlen == 12 && pg_strncasecmp(query, "concurrently", 12) == 0)
2156 if (wordlen == 5 && pg_strncasecmp(query, "alter", 5) == 0)
2160 query = skip_white_space(query);
2163 while (isalpha((unsigned char) query[wordlen]))
2164 wordlen += PQmblen(&query[wordlen], pset.encoding);
2166 /* ALTER SYSTEM isn't allowed in xacts */
2167 if (wordlen == 6 && pg_strncasecmp(query, "system", 6) == 0)
2174 * Note: these tests will match DROP SYSTEM and REINDEX TABLESPACE, which
2175 * aren't really valid commands so we don't care much. The other four
2176 * possible matches are correct.
2178 if ((wordlen == 4 && pg_strncasecmp(query, "drop", 4) == 0) ||
2179 (wordlen == 7 && pg_strncasecmp(query, "reindex", 7) == 0))
2183 query = skip_white_space(query);
2186 while (isalpha((unsigned char) query[wordlen]))
2187 wordlen += PQmblen(&query[wordlen], pset.encoding);
2189 if (wordlen == 8 && pg_strncasecmp(query, "database", 8) == 0)
2191 if (wordlen == 6 && pg_strncasecmp(query, "system", 6) == 0)
2193 if (wordlen == 10 && pg_strncasecmp(query, "tablespace", 10) == 0)
2196 /* DROP INDEX CONCURRENTLY isn't allowed in xacts */
2197 if (wordlen == 5 && pg_strncasecmp(query, "index", 5) == 0)
2201 query = skip_white_space(query);
2204 while (isalpha((unsigned char) query[wordlen]))
2205 wordlen += PQmblen(&query[wordlen], pset.encoding);
2207 if (wordlen == 12 && pg_strncasecmp(query, "concurrently", 12) == 0)
2216 /* DISCARD ALL isn't allowed in xacts, but other variants are allowed. */
2217 if (wordlen == 7 && pg_strncasecmp(query, "discard", 7) == 0)
2221 query = skip_white_space(query);
2224 while (isalpha((unsigned char) query[wordlen]))
2225 wordlen += PQmblen(&query[wordlen], pset.encoding);
2227 if (wordlen == 3 && pg_strncasecmp(query, "all", 3) == 0)
2237 * Check whether the specified command is a SELECT (or VALUES).
2240 is_select_command(const char *query)
2245 * First advance over any whitespace, comments and left parentheses.
2249 query = skip_white_space(query);
2250 if (query[0] == '(')
2257 * Check word length (since "selectx" is not "select").
2260 while (isalpha((unsigned char) query[wordlen]))
2261 wordlen += PQmblen(&query[wordlen], pset.encoding);
2263 if (wordlen == 6 && pg_strncasecmp(query, "select", 6) == 0)
2266 if (wordlen == 6 && pg_strncasecmp(query, "values", 6) == 0)
2274 * Test if the current user is a database superuser.
2276 * Note: this will correctly detect superuserness only with a protocol-3.0
2277 * or newer backend; otherwise it will always say "false".
2287 val = PQparameterStatus(pset.db, "is_superuser");
2289 if (val && strcmp(val, "on") == 0)
2297 * Test if the current session uses standard string literals.
2299 * Note: With a pre-protocol-3.0 connection this will always say "false",
2300 * which should be the right answer.
2303 standard_strings(void)
2310 val = PQparameterStatus(pset.db, "standard_conforming_strings");
2312 if (val && strcmp(val, "on") == 0)
2320 * Return the session user of the current connection.
2322 * Note: this will correctly detect the session user only with a
2323 * protocol-3.0 or newer backend; otherwise it will return the
2327 session_username(void)
2334 val = PQparameterStatus(pset.db, "session_authorization");
2338 return PQuser(pset.db);
2344 * substitute '~' with HOME or '~username' with username's home dir
2348 expand_tilde(char **filename)
2350 if (!filename || !(*filename))
2354 * WIN32 doesn't use tilde expansion for file names. Also, it uses tilde
2355 * for short versions of long file names, though the tilde is usually
2356 * toward the end, not at the beginning.
2360 /* try tilde expansion */
2361 if (**filename == '~')
2367 char home[MAXPGPATH];
2373 while (*p != '/' && *p != '\0')
2379 if (*(fn + 1) == '\0')
2380 get_home_path(home); /* ~ or ~/ only */
2381 else if ((pw = getpwnam(fn + 1)) != NULL)
2382 strlcpy(home, pw->pw_dir, sizeof(home)); /* ~user */
2385 if (strlen(home) != 0)
2389 newfn = psprintf("%s%s", home, p);
2400 * Checks if connection string starts with either of the valid URI prefix
2403 * Returns the URI prefix length, 0 if the string doesn't contain a URI prefix.
2405 * XXX This is a duplicate of the eponymous libpq function.
2408 uri_prefix_length(const char *connstr)
2410 /* The connection URI must start with either of the following designators: */
2411 static const char uri_designator[] = "postgresql://";
2412 static const char short_uri_designator[] = "postgres://";
2414 if (strncmp(connstr, uri_designator,
2415 sizeof(uri_designator) - 1) == 0)
2416 return sizeof(uri_designator) - 1;
2418 if (strncmp(connstr, short_uri_designator,
2419 sizeof(short_uri_designator) - 1) == 0)
2420 return sizeof(short_uri_designator) - 1;
2426 * Recognized connection string either starts with a valid URI prefix or
2427 * contains a "=" in it.
2429 * Must be consistent with parse_connection_string: anything for which this
2430 * returns true should at least look like it's parseable by that routine.
2432 * XXX This is a duplicate of the eponymous libpq function.
2435 recognized_connection_string(const char *connstr)
2437 return uri_prefix_length(connstr) != 0 || strchr(connstr, '=') != NULL;