2 * psql - the PostgreSQL interactive terminal
4 * Copyright (c) 2000-2017, 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 while ((notify = PQnotifies(pset.db)))
841 /* for backward compatibility, only show payload if nonempty */
842 if (notify->extra[0])
843 fprintf(pset.queryFout, _("Asynchronous notification \"%s\" with payload \"%s\" received from server process with PID %d.\n"),
844 notify->relname, notify->extra, notify->be_pid);
846 fprintf(pset.queryFout, _("Asynchronous notification \"%s\" received from server process with PID %d.\n"),
847 notify->relname, notify->be_pid);
848 fflush(pset.queryFout);
855 * PrintQueryTuples: assuming query result is OK, print its tuples
857 * Returns true if successful, false otherwise.
860 PrintQueryTuples(const PGresult *results)
862 printQueryOpt my_popt = pset.popt;
864 /* one-shot expanded output requested via \gx */
866 my_popt.topt.expanded = 1;
868 /* write output to \g argument, if any */
874 if (!openQueryOutputFile(pset.gfname, &fout, &is_pipe))
877 disable_sigpipe_trap();
879 printQuery(results, &my_popt, fout, false, pset.logfile);
884 restore_sigpipe_trap();
890 printQuery(results, &my_popt, pset.queryFout, false, pset.logfile);
897 * StoreQueryTuple: assuming query result is OK, save data into variables
899 * Returns true if successful, false otherwise.
902 StoreQueryTuple(const PGresult *result)
906 if (PQntuples(result) < 1)
908 psql_error("no rows returned for \\gset\n");
911 else if (PQntuples(result) > 1)
913 psql_error("more than one row returned for \\gset\n");
920 for (i = 0; i < PQnfields(result); i++)
922 char *colname = PQfname(result, i);
926 /* concatenate prefix and column name */
927 varname = psprintf("%s%s", pset.gset_prefix, colname);
929 if (!PQgetisnull(result, 0, i))
930 value = PQgetvalue(result, 0, i);
933 /* for NULL value, unset rather than set the variable */
937 if (!SetVariable(pset.vars, varname, value))
953 * ExecQueryTuples: assuming query result is OK, execute each query
954 * result field as a SQL statement
956 * Returns true if successful, false otherwise.
959 ExecQueryTuples(const PGresult *result)
962 int nrows = PQntuples(result);
963 int ncolumns = PQnfields(result);
968 * We must turn off gexec_flag to avoid infinite recursion. Note that
969 * this allows ExecQueryUsingCursor to be applied to the individual query
970 * results. SendQuery prevents it from being applied when fetching the
971 * queries-to-execute, because it can't handle recursion either.
973 pset.gexec_flag = false;
975 for (r = 0; r < nrows; r++)
977 for (c = 0; c < ncolumns; c++)
979 if (!PQgetisnull(result, r, c))
981 const char *query = PQgetvalue(result, r, c);
983 /* Abandon execution if cancel_pressed */
988 * ECHO_ALL mode should echo these queries, but SendQuery
989 * assumes that MainLoop did that, so we have to do it here.
991 if (pset.echo == PSQL_ECHO_ALL && !pset.singlestep)
997 if (!SendQuery(query))
999 /* Error - abandon execution if ON_ERROR_STOP */
1001 if (pset.on_error_stop)
1011 * Restore state. We know gexec_flag was on, else we'd not be here. (We
1012 * also know it'll get turned off at end of command, but that's not ours
1015 pset.gexec_flag = true;
1017 /* Return true if all queries were successful */
1023 * ProcessResult: utility function for use by SendQuery() only
1025 * When our command string contained a COPY FROM STDIN or COPY TO STDOUT,
1026 * PQexec() has stopped at the PGresult associated with the first such
1027 * command. In that event, we'll marshal data for the COPY and then cycle
1028 * through any subsequent PGresult objects.
1030 * When the command string contained no such COPY command, this function
1031 * degenerates to an AcceptResult() call.
1033 * Changes its argument to point to the last PGresult of the command string,
1034 * or NULL if that result was for a COPY TO STDOUT. (Returning NULL prevents
1035 * the command status from being printed, which we want in that case so that
1036 * the status line doesn't get taken as part of the COPY data.)
1038 * Returns true on complete success, false otherwise. Possible failure modes
1039 * include purely client-side problems; check the transaction status for the
1040 * server-side opinion.
1043 ProcessResult(PGresult **results)
1045 bool success = true;
1046 bool first_cycle = true;
1050 ExecStatusType result_status;
1052 PGresult *next_result;
1054 if (!AcceptResult(*results))
1057 * Failure at this point is always a server-side failure or a
1058 * failure to submit the command string. Either way, we're
1059 * finished with this command string.
1065 result_status = PQresultStatus(*results);
1066 switch (result_status)
1068 case PGRES_EMPTY_QUERY:
1069 case PGRES_COMMAND_OK:
1070 case PGRES_TUPLES_OK:
1074 case PGRES_COPY_OUT:
1080 /* AcceptResult() should have caught anything else. */
1082 psql_error("unexpected PQresultStatus: %d\n", result_status);
1089 * Marshal the COPY data. Either subroutine will get the
1090 * connection out of its COPY state, then call PQresultStatus()
1091 * once and report any error.
1093 * If pset.copyStream is set, use that as data source/sink,
1094 * otherwise use queryFout or cur_cmd_source as appropriate.
1096 FILE *copystream = pset.copyStream;
1097 PGresult *copy_result;
1100 if (result_status == PGRES_COPY_OUT)
1103 copystream = pset.queryFout;
1104 success = handleCopyOut(pset.db,
1106 ©_result) && success;
1109 * Suppress status printing if the report would go to the same
1110 * place as the COPY data just went. Note this doesn't
1111 * prevent error reporting, since handleCopyOut did that.
1113 if (copystream == pset.queryFout)
1115 PQclear(copy_result);
1122 copystream = pset.cur_cmd_source;
1123 success = handleCopyIn(pset.db,
1125 PQbinaryTuples(*results),
1126 ©_result) && success;
1131 * Replace the PGRES_COPY_OUT/IN result with COPY command's exit
1132 * status, or with NULL if we want to suppress printing anything.
1135 *results = copy_result;
1137 else if (first_cycle)
1139 /* fast path: no COPY commands; PQexec visited all results */
1144 * Check PQgetResult() again. In the typical case of a single-command
1145 * string, it will return NULL. Otherwise, we'll have other results
1146 * to process that may include other COPYs. We keep the last result.
1148 next_result = PQgetResult(pset.db);
1153 *results = next_result;
1154 first_cycle = false;
1157 SetResultVariables(*results, success);
1159 /* may need this to recover from conn loss during COPY */
1160 if (!first_cycle && !CheckConnection())
1168 * PrintQueryStatus: report command status as required
1170 * Note: Utility function for use by PrintQueryResults() only.
1173 PrintQueryStatus(PGresult *results)
1179 if (pset.popt.topt.format == PRINT_HTML)
1181 fputs("<p>", pset.queryFout);
1182 html_escaped_print(PQcmdStatus(results), pset.queryFout);
1183 fputs("</p>\n", pset.queryFout);
1186 fprintf(pset.queryFout, "%s\n", PQcmdStatus(results));
1190 fprintf(pset.logfile, "%s\n", PQcmdStatus(results));
1192 snprintf(buf, sizeof(buf), "%u", (unsigned int) PQoidValue(results));
1193 SetVariable(pset.vars, "LASTOID", buf);
1198 * PrintQueryResults: print out (or store or execute) query results as required
1200 * Note: Utility function for use by SendQuery() only.
1202 * Returns true if the query executed successfully, false otherwise.
1205 PrintQueryResults(PGresult *results)
1208 const char *cmdstatus;
1213 switch (PQresultStatus(results))
1215 case PGRES_TUPLES_OK:
1216 /* store or execute or print the data ... */
1217 if (pset.gset_prefix)
1218 success = StoreQueryTuple(results);
1219 else if (pset.gexec_flag)
1220 success = ExecQueryTuples(results);
1221 else if (pset.crosstab_flag)
1222 success = PrintResultsInCrosstab(results);
1224 success = PrintQueryTuples(results);
1225 /* if it's INSERT/UPDATE/DELETE RETURNING, also print status */
1226 cmdstatus = PQcmdStatus(results);
1227 if (strncmp(cmdstatus, "INSERT", 6) == 0 ||
1228 strncmp(cmdstatus, "UPDATE", 6) == 0 ||
1229 strncmp(cmdstatus, "DELETE", 6) == 0)
1230 PrintQueryStatus(results);
1233 case PGRES_COMMAND_OK:
1234 PrintQueryStatus(results);
1238 case PGRES_EMPTY_QUERY:
1242 case PGRES_COPY_OUT:
1244 /* nothing to do here */
1248 case PGRES_BAD_RESPONSE:
1249 case PGRES_NONFATAL_ERROR:
1250 case PGRES_FATAL_ERROR:
1256 psql_error("unexpected PQresultStatus: %d\n",
1257 PQresultStatus(results));
1261 fflush(pset.queryFout);
1268 * SendQuery: send the query string to the backend
1269 * (and print out results)
1271 * Note: This is the "front door" way to send a query. That is, use it to
1272 * send queries actually entered by the user. These queries will be subject to
1274 * To send "back door" queries (generated by slash commands, etc.) in a
1275 * controlled way, use PSQLexec().
1277 * Returns true if the query executed successfully, false otherwise.
1280 SendQuery(const char *query)
1283 PGTransactionStatusType transaction_status;
1284 double elapsed_msec = 0;
1287 bool on_error_rollback_savepoint = false;
1288 static bool on_error_rollback_warning = false;
1292 psql_error("You are currently not connected to a database.\n");
1293 goto sendquery_cleanup;
1296 if (pset.singlestep)
1301 printf(_("***(Single step mode: verify command)*******************************************\n"
1303 "***(press return to proceed or enter x and return to cancel)********************\n"),
1306 if (fgets(buf, sizeof(buf), stdin) != NULL)
1308 goto sendquery_cleanup;
1310 goto sendquery_cleanup;
1312 else if (pset.echo == PSQL_ECHO_QUERIES)
1320 fprintf(pset.logfile,
1321 _("********* QUERY **********\n"
1323 "**************************\n\n"), query);
1324 fflush(pset.logfile);
1329 transaction_status = PQtransactionStatus(pset.db);
1331 if (transaction_status == PQTRANS_IDLE &&
1333 !command_no_begin(query))
1335 results = PQexec(pset.db, "BEGIN");
1336 if (PQresultStatus(results) != PGRES_COMMAND_OK)
1338 psql_error("%s", PQerrorMessage(pset.db));
1339 ClearOrSaveResult(results);
1341 goto sendquery_cleanup;
1343 ClearOrSaveResult(results);
1344 transaction_status = PQtransactionStatus(pset.db);
1347 if (transaction_status == PQTRANS_INTRANS &&
1348 pset.on_error_rollback != PSQL_ERROR_ROLLBACK_OFF &&
1349 (pset.cur_cmd_interactive ||
1350 pset.on_error_rollback == PSQL_ERROR_ROLLBACK_ON))
1352 if (on_error_rollback_warning == false && pset.sversion < 80000)
1356 psql_error("The server (version %s) does not support savepoints for ON_ERROR_ROLLBACK.\n",
1357 formatPGVersionNumber(pset.sversion, false,
1358 sverbuf, sizeof(sverbuf)));
1359 on_error_rollback_warning = true;
1363 results = PQexec(pset.db, "SAVEPOINT pg_psql_temporary_savepoint");
1364 if (PQresultStatus(results) != PGRES_COMMAND_OK)
1366 psql_error("%s", PQerrorMessage(pset.db));
1367 ClearOrSaveResult(results);
1369 goto sendquery_cleanup;
1371 ClearOrSaveResult(results);
1372 on_error_rollback_savepoint = true;
1376 if (pset.gdesc_flag)
1378 /* Describe query's result columns, without executing it */
1379 OK = DescribeQuery(query, &elapsed_msec);
1381 results = NULL; /* PQclear(NULL) does nothing */
1383 else if (pset.fetch_count <= 0 || pset.gexec_flag ||
1384 pset.crosstab_flag || !is_select_command(query))
1386 /* Default fetch-it-all-and-print mode */
1391 INSTR_TIME_SET_CURRENT(before);
1393 results = PQexec(pset.db, query);
1395 /* these operations are included in the timing result: */
1397 OK = ProcessResult(&results);
1401 INSTR_TIME_SET_CURRENT(after);
1402 INSTR_TIME_SUBTRACT(after, before);
1403 elapsed_msec = INSTR_TIME_GET_MILLISEC(after);
1406 /* but printing results isn't: */
1408 OK = PrintQueryResults(results);
1412 /* Fetch-in-segments mode */
1413 OK = ExecQueryUsingCursor(query, &elapsed_msec);
1415 results = NULL; /* PQclear(NULL) does nothing */
1418 if (!OK && pset.echo == PSQL_ECHO_ERRORS)
1419 psql_error("STATEMENT: %s\n", query);
1421 /* If we made a temporary savepoint, possibly release/rollback */
1422 if (on_error_rollback_savepoint)
1424 const char *svptcmd = NULL;
1426 transaction_status = PQtransactionStatus(pset.db);
1428 switch (transaction_status)
1430 case PQTRANS_INERROR:
1431 /* We always rollback on an error */
1432 svptcmd = "ROLLBACK TO pg_psql_temporary_savepoint";
1436 /* If they are no longer in a transaction, then do nothing */
1439 case PQTRANS_INTRANS:
1442 * Do nothing if they are messing with savepoints themselves:
1443 * If the user did RELEASE or ROLLBACK, our savepoint is gone.
1444 * If they issued a SAVEPOINT, releasing ours would remove
1448 (strcmp(PQcmdStatus(results), "SAVEPOINT") == 0 ||
1449 strcmp(PQcmdStatus(results), "RELEASE") == 0 ||
1450 strcmp(PQcmdStatus(results), "ROLLBACK") == 0))
1453 svptcmd = "RELEASE pg_psql_temporary_savepoint";
1456 case PQTRANS_ACTIVE:
1457 case PQTRANS_UNKNOWN:
1460 /* PQTRANS_UNKNOWN is expected given a broken connection. */
1461 if (transaction_status != PQTRANS_UNKNOWN || ConnectionUp())
1462 psql_error("unexpected transaction status (%d)\n",
1463 transaction_status);
1471 svptres = PQexec(pset.db, svptcmd);
1472 if (PQresultStatus(svptres) != PGRES_COMMAND_OK)
1474 psql_error("%s", PQerrorMessage(pset.db));
1475 ClearOrSaveResult(svptres);
1480 goto sendquery_cleanup;
1486 ClearOrSaveResult(results);
1488 /* Possible microtiming output */
1490 PrintTiming(elapsed_msec);
1492 /* check for events that may occur during query execution */
1494 if (pset.encoding != PQclientEncoding(pset.db) &&
1495 PQclientEncoding(pset.db) >= 0)
1497 /* track effects of SET CLIENT_ENCODING */
1498 pset.encoding = PQclientEncoding(pset.db);
1499 pset.popt.topt.encoding = pset.encoding;
1500 SetVariable(pset.vars, "ENCODING",
1501 pg_encoding_to_char(pset.encoding));
1504 PrintNotifications();
1506 /* perform cleanup that should occur after any attempted query */
1510 /* reset \g's output-to-filename trigger */
1517 /* reset \gx's expanded-mode flag */
1518 pset.g_expanded = false;
1520 /* reset \gset trigger */
1521 if (pset.gset_prefix)
1523 free(pset.gset_prefix);
1524 pset.gset_prefix = NULL;
1527 /* reset \gdesc trigger */
1528 pset.gdesc_flag = false;
1530 /* reset \gexec trigger */
1531 pset.gexec_flag = false;
1533 /* reset \crosstabview trigger */
1534 pset.crosstab_flag = false;
1535 for (i = 0; i < lengthof(pset.ctv_args); i++)
1537 pg_free(pset.ctv_args[i]);
1538 pset.ctv_args[i] = NULL;
1546 * DescribeQuery: describe the result columns of a query, without executing it
1548 * Returns true if the operation executed successfully, false otherwise.
1550 * If pset.timing is on, total query time (exclusive of result-printing) is
1551 * stored into *elapsed_msec.
1554 DescribeQuery(const char *query, double *elapsed_msec)
1564 INSTR_TIME_SET_CURRENT(before);
1567 * To parse the query but not execute it, we prepare it, using the unnamed
1568 * prepared statement. This is invisible to psql users, since there's no
1569 * way to access the unnamed prepared statement from psql user space. The
1570 * next Parse or Query protocol message would overwrite the statement
1571 * anyway. (So there's no great need to clear it when done, which is a
1572 * good thing because libpq provides no easy way to do that.)
1574 results = PQprepare(pset.db, "", query, 0, NULL);
1575 if (PQresultStatus(results) != PGRES_COMMAND_OK)
1577 psql_error("%s", PQerrorMessage(pset.db));
1578 SetResultVariables(results, false);
1579 ClearOrSaveResult(results);
1584 results = PQdescribePrepared(pset.db, "");
1585 OK = AcceptResult(results) &&
1586 (PQresultStatus(results) == PGRES_COMMAND_OK);
1589 if (PQnfields(results) > 0)
1591 PQExpBufferData buf;
1594 initPQExpBuffer(&buf);
1596 printfPQExpBuffer(&buf,
1597 "SELECT name AS \"%s\", pg_catalog.format_type(tp, tpm) AS \"%s\"\n"
1599 gettext_noop("Column"),
1600 gettext_noop("Type"));
1602 for (i = 0; i < PQnfields(results); i++)
1608 appendPQExpBufferStr(&buf, ",");
1610 name = PQfname(results, i);
1611 escname = PQescapeLiteral(pset.db, name, strlen(name));
1613 if (escname == NULL)
1615 psql_error("%s", PQerrorMessage(pset.db));
1617 termPQExpBuffer(&buf);
1621 appendPQExpBuffer(&buf, "(%s, '%u'::pg_catalog.oid, %d)",
1623 PQftype(results, i),
1624 PQfmod(results, i));
1629 appendPQExpBufferStr(&buf, ") s(name, tp, tpm)");
1632 results = PQexec(pset.db, buf.data);
1633 OK = AcceptResult(results);
1637 INSTR_TIME_SET_CURRENT(after);
1638 INSTR_TIME_SUBTRACT(after, before);
1639 *elapsed_msec += INSTR_TIME_GET_MILLISEC(after);
1643 OK = PrintQueryResults(results);
1645 termPQExpBuffer(&buf);
1648 fprintf(pset.queryFout,
1649 _("The command has no result, or the result has no columns.\n"));
1652 SetResultVariables(results, OK);
1653 ClearOrSaveResult(results);
1660 * ExecQueryUsingCursor: run a SELECT-like query using a cursor
1662 * This feature allows result sets larger than RAM to be dealt with.
1664 * Returns true if the query executed successfully, false otherwise.
1666 * If pset.timing is on, total query time (exclusive of result-printing) is
1667 * stored into *elapsed_msec.
1670 ExecQueryUsingCursor(const char *query, double *elapsed_msec)
1674 PQExpBufferData buf;
1675 printQueryOpt my_popt = pset.popt;
1678 bool is_pager = false;
1679 bool started_txn = false;
1680 int64 total_tuples = 0;
1690 /* initialize print options for partial table output */
1691 my_popt.topt.start_table = true;
1692 my_popt.topt.stop_table = false;
1693 my_popt.topt.prior_records = 0;
1696 INSTR_TIME_SET_CURRENT(before);
1698 /* if we're not in a transaction, start one */
1699 if (PQtransactionStatus(pset.db) == PQTRANS_IDLE)
1701 results = PQexec(pset.db, "BEGIN");
1702 OK = AcceptResult(results) &&
1703 (PQresultStatus(results) == PGRES_COMMAND_OK);
1704 ClearOrSaveResult(results);
1710 /* Send DECLARE CURSOR */
1711 initPQExpBuffer(&buf);
1712 appendPQExpBuffer(&buf, "DECLARE _psql_cursor NO SCROLL CURSOR FOR\n%s",
1715 results = PQexec(pset.db, buf.data);
1716 OK = AcceptResult(results) &&
1717 (PQresultStatus(results) == PGRES_COMMAND_OK);
1719 SetResultVariables(results, OK);
1720 ClearOrSaveResult(results);
1721 termPQExpBuffer(&buf);
1727 INSTR_TIME_SET_CURRENT(after);
1728 INSTR_TIME_SUBTRACT(after, before);
1729 *elapsed_msec += INSTR_TIME_GET_MILLISEC(after);
1733 * In \gset mode, we force the fetch count to be 2, so that we will throw
1734 * the appropriate error if the query returns more than one row.
1736 if (pset.gset_prefix)
1739 fetch_count = pset.fetch_count;
1741 snprintf(fetch_cmd, sizeof(fetch_cmd),
1742 "FETCH FORWARD %d FROM _psql_cursor",
1745 /* one-shot expanded output requested via \gx */
1746 if (pset.g_expanded)
1747 my_popt.topt.expanded = 1;
1749 /* prepare to write output to \g argument, if any */
1752 if (!openQueryOutputFile(pset.gfname, &fout, &is_pipe))
1758 disable_sigpipe_trap();
1762 fout = pset.queryFout;
1763 is_pipe = false; /* doesn't matter */
1766 /* clear any pre-existing error indication on the output stream */
1772 INSTR_TIME_SET_CURRENT(before);
1774 /* get fetch_count tuples at a time */
1775 results = PQexec(pset.db, fetch_cmd);
1779 INSTR_TIME_SET_CURRENT(after);
1780 INSTR_TIME_SUBTRACT(after, before);
1781 *elapsed_msec += INSTR_TIME_GET_MILLISEC(after);
1784 if (PQresultStatus(results) != PGRES_TUPLES_OK)
1786 /* shut down pager before printing error message */
1793 OK = AcceptResult(results);
1795 SetResultVariables(results, OK);
1796 ClearOrSaveResult(results);
1800 if (pset.gset_prefix)
1802 /* StoreQueryTuple will complain if not exactly one row */
1803 OK = StoreQueryTuple(results);
1804 ClearOrSaveResult(results);
1809 * Note we do not deal with \gdesc, \gexec or \crosstabview modes here
1812 ntuples = PQntuples(results);
1813 total_tuples += ntuples;
1815 if (ntuples < fetch_count)
1817 /* this is the last result set, so allow footer decoration */
1818 my_popt.topt.stop_table = true;
1820 else if (fout == stdout && !is_pager)
1823 * If query requires multiple result sets, hack to ensure that
1824 * only one pager instance is used for the whole mess
1826 fout = PageOutput(INT_MAX, &(my_popt.topt));
1830 printQuery(results, &my_popt, fout, is_pager, pset.logfile);
1832 ClearOrSaveResult(results);
1834 /* after the first result set, disallow header decoration */
1835 my_popt.topt.start_table = false;
1836 my_popt.topt.prior_records += ntuples;
1839 * Make sure to flush the output stream, so intermediate results are
1840 * visible to the client immediately. We check the results because if
1841 * the pager dies/exits/etc, there's no sense throwing more data at
1844 flush_error = fflush(fout);
1847 * Check if we are at the end, if a cancel was pressed, or if there
1848 * were any errors either trying to flush out the results, or more
1849 * generally on the output stream at all. If we hit any errors
1850 * writing things to the stream, we presume $PAGER has disappeared and
1851 * stop bothering to pull down more data.
1853 if (ntuples < fetch_count || cancel_pressed || flush_error ||
1860 /* close \g argument file/pipe */
1864 restore_sigpipe_trap();
1871 /* close transient pager */
1878 * We don't have a PGresult here, and even if we did it wouldn't have
1879 * the right row count, so fake SetResultVariables(). In error cases,
1880 * we already set the result variables above.
1884 SetVariable(pset.vars, "ERROR", "false");
1885 SetVariable(pset.vars, "SQLSTATE", "00000");
1886 snprintf(buf, sizeof(buf), INT64_FORMAT, total_tuples);
1887 SetVariable(pset.vars, "ROW_COUNT", buf);
1892 INSTR_TIME_SET_CURRENT(before);
1895 * We try to close the cursor on either success or failure, but on failure
1896 * ignore the result (it's probably just a bleat about being in an aborted
1899 results = PQexec(pset.db, "CLOSE _psql_cursor");
1902 OK = AcceptResult(results) &&
1903 (PQresultStatus(results) == PGRES_COMMAND_OK);
1904 ClearOrSaveResult(results);
1911 results = PQexec(pset.db, OK ? "COMMIT" : "ROLLBACK");
1912 OK &= AcceptResult(results) &&
1913 (PQresultStatus(results) == PGRES_COMMAND_OK);
1914 ClearOrSaveResult(results);
1919 INSTR_TIME_SET_CURRENT(after);
1920 INSTR_TIME_SUBTRACT(after, before);
1921 *elapsed_msec += INSTR_TIME_GET_MILLISEC(after);
1929 * Advance the given char pointer over white space and SQL comments.
1932 skip_white_space(const char *query)
1934 int cnestlevel = 0; /* slash-star comment nest level */
1938 int mblen = PQmblen(query, pset.encoding);
1941 * Note: we assume the encoding is a superset of ASCII, so that for
1942 * example "query[0] == '/'" is meaningful. However, we do NOT assume
1943 * that the second and subsequent bytes of a multibyte character
1944 * couldn't look like ASCII characters; so it is critical to advance
1945 * by mblen, not 1, whenever we haven't exactly identified the
1946 * character we are skipping over.
1948 if (isspace((unsigned char) *query))
1950 else if (query[0] == '/' && query[1] == '*')
1955 else if (cnestlevel > 0 && query[0] == '*' && query[1] == '/')
1960 else if (cnestlevel == 0 && query[0] == '-' && query[1] == '-')
1965 * We have to skip to end of line since any slash-star inside the
1966 * -- comment does NOT start a slash-star comment.
1975 query += PQmblen(query, pset.encoding);
1978 else if (cnestlevel > 0)
1981 break; /* found first token */
1989 * Check whether a command is one of those for which we should NOT start
1990 * a new transaction block (ie, send a preceding BEGIN).
1992 * These include the transaction control statements themselves, plus
1993 * certain statements that the backend disallows inside transaction blocks.
1996 command_no_begin(const char *query)
2001 * First we must advance over any whitespace and comments.
2003 query = skip_white_space(query);
2006 * Check word length (since "beginx" is not "begin").
2009 while (isalpha((unsigned char) query[wordlen]))
2010 wordlen += PQmblen(&query[wordlen], pset.encoding);
2013 * Transaction control commands. These should include every keyword that
2014 * gives rise to a TransactionStmt in the backend grammar, except for the
2015 * savepoint-related commands.
2017 * (We assume that START must be START TRANSACTION, since there is
2018 * presently no other "START foo" command.)
2020 if (wordlen == 5 && pg_strncasecmp(query, "abort", 5) == 0)
2022 if (wordlen == 5 && pg_strncasecmp(query, "begin", 5) == 0)
2024 if (wordlen == 5 && pg_strncasecmp(query, "start", 5) == 0)
2026 if (wordlen == 6 && pg_strncasecmp(query, "commit", 6) == 0)
2028 if (wordlen == 3 && pg_strncasecmp(query, "end", 3) == 0)
2030 if (wordlen == 8 && pg_strncasecmp(query, "rollback", 8) == 0)
2032 if (wordlen == 7 && pg_strncasecmp(query, "prepare", 7) == 0)
2034 /* PREPARE TRANSACTION is a TC command, PREPARE foo is not */
2037 query = skip_white_space(query);
2040 while (isalpha((unsigned char) query[wordlen]))
2041 wordlen += PQmblen(&query[wordlen], pset.encoding);
2043 if (wordlen == 11 && pg_strncasecmp(query, "transaction", 11) == 0)
2049 * Commands not allowed within transactions. The statements checked for
2050 * here should be exactly those that call PreventTransactionChain() in the
2053 if (wordlen == 6 && pg_strncasecmp(query, "vacuum", 6) == 0)
2055 if (wordlen == 7 && pg_strncasecmp(query, "cluster", 7) == 0)
2057 /* CLUSTER with any arguments is allowed in transactions */
2060 query = skip_white_space(query);
2062 if (isalpha((unsigned char) query[0]))
2063 return false; /* has additional words */
2064 return true; /* it's CLUSTER without arguments */
2067 if (wordlen == 6 && pg_strncasecmp(query, "create", 6) == 0)
2071 query = skip_white_space(query);
2074 while (isalpha((unsigned char) query[wordlen]))
2075 wordlen += PQmblen(&query[wordlen], pset.encoding);
2077 if (wordlen == 8 && pg_strncasecmp(query, "database", 8) == 0)
2079 if (wordlen == 10 && pg_strncasecmp(query, "tablespace", 10) == 0)
2082 /* CREATE [UNIQUE] INDEX CONCURRENTLY isn't allowed in xacts */
2083 if (wordlen == 6 && pg_strncasecmp(query, "unique", 6) == 0)
2087 query = skip_white_space(query);
2090 while (isalpha((unsigned char) query[wordlen]))
2091 wordlen += PQmblen(&query[wordlen], pset.encoding);
2094 if (wordlen == 5 && pg_strncasecmp(query, "index", 5) == 0)
2098 query = skip_white_space(query);
2101 while (isalpha((unsigned char) query[wordlen]))
2102 wordlen += PQmblen(&query[wordlen], pset.encoding);
2104 if (wordlen == 12 && pg_strncasecmp(query, "concurrently", 12) == 0)
2111 if (wordlen == 5 && pg_strncasecmp(query, "alter", 5) == 0)
2115 query = skip_white_space(query);
2118 while (isalpha((unsigned char) query[wordlen]))
2119 wordlen += PQmblen(&query[wordlen], pset.encoding);
2121 /* ALTER SYSTEM isn't allowed in xacts */
2122 if (wordlen == 6 && pg_strncasecmp(query, "system", 6) == 0)
2129 * Note: these tests will match DROP SYSTEM and REINDEX TABLESPACE, which
2130 * aren't really valid commands so we don't care much. The other four
2131 * possible matches are correct.
2133 if ((wordlen == 4 && pg_strncasecmp(query, "drop", 4) == 0) ||
2134 (wordlen == 7 && pg_strncasecmp(query, "reindex", 7) == 0))
2138 query = skip_white_space(query);
2141 while (isalpha((unsigned char) query[wordlen]))
2142 wordlen += PQmblen(&query[wordlen], pset.encoding);
2144 if (wordlen == 8 && pg_strncasecmp(query, "database", 8) == 0)
2146 if (wordlen == 6 && pg_strncasecmp(query, "system", 6) == 0)
2148 if (wordlen == 10 && pg_strncasecmp(query, "tablespace", 10) == 0)
2151 /* DROP INDEX CONCURRENTLY isn't allowed in xacts */
2152 if (wordlen == 5 && pg_strncasecmp(query, "index", 5) == 0)
2156 query = skip_white_space(query);
2159 while (isalpha((unsigned char) query[wordlen]))
2160 wordlen += PQmblen(&query[wordlen], pset.encoding);
2162 if (wordlen == 12 && pg_strncasecmp(query, "concurrently", 12) == 0)
2171 /* DISCARD ALL isn't allowed in xacts, but other variants are allowed. */
2172 if (wordlen == 7 && pg_strncasecmp(query, "discard", 7) == 0)
2176 query = skip_white_space(query);
2179 while (isalpha((unsigned char) query[wordlen]))
2180 wordlen += PQmblen(&query[wordlen], pset.encoding);
2182 if (wordlen == 3 && pg_strncasecmp(query, "all", 3) == 0)
2192 * Check whether the specified command is a SELECT (or VALUES).
2195 is_select_command(const char *query)
2200 * First advance over any whitespace, comments and left parentheses.
2204 query = skip_white_space(query);
2205 if (query[0] == '(')
2212 * Check word length (since "selectx" is not "select").
2215 while (isalpha((unsigned char) query[wordlen]))
2216 wordlen += PQmblen(&query[wordlen], pset.encoding);
2218 if (wordlen == 6 && pg_strncasecmp(query, "select", 6) == 0)
2221 if (wordlen == 6 && pg_strncasecmp(query, "values", 6) == 0)
2229 * Test if the current user is a database superuser.
2231 * Note: this will correctly detect superuserness only with a protocol-3.0
2232 * or newer backend; otherwise it will always say "false".
2242 val = PQparameterStatus(pset.db, "is_superuser");
2244 if (val && strcmp(val, "on") == 0)
2252 * Test if the current session uses standard string literals.
2254 * Note: With a pre-protocol-3.0 connection this will always say "false",
2255 * which should be the right answer.
2258 standard_strings(void)
2265 val = PQparameterStatus(pset.db, "standard_conforming_strings");
2267 if (val && strcmp(val, "on") == 0)
2275 * Return the session user of the current connection.
2277 * Note: this will correctly detect the session user only with a
2278 * protocol-3.0 or newer backend; otherwise it will return the
2282 session_username(void)
2289 val = PQparameterStatus(pset.db, "session_authorization");
2293 return PQuser(pset.db);
2299 * substitute '~' with HOME or '~username' with username's home dir
2303 expand_tilde(char **filename)
2305 if (!filename || !(*filename))
2309 * WIN32 doesn't use tilde expansion for file names. Also, it uses tilde
2310 * for short versions of long file names, though the tilde is usually
2311 * toward the end, not at the beginning.
2315 /* try tilde expansion */
2316 if (**filename == '~')
2322 char home[MAXPGPATH];
2328 while (*p != '/' && *p != '\0')
2334 if (*(fn + 1) == '\0')
2335 get_home_path(home); /* ~ or ~/ only */
2336 else if ((pw = getpwnam(fn + 1)) != NULL)
2337 strlcpy(home, pw->pw_dir, sizeof(home)); /* ~user */
2340 if (strlen(home) != 0)
2344 newfn = psprintf("%s%s", home, p);
2355 * Checks if connection string starts with either of the valid URI prefix
2358 * Returns the URI prefix length, 0 if the string doesn't contain a URI prefix.
2360 * XXX This is a duplicate of the eponymous libpq function.
2363 uri_prefix_length(const char *connstr)
2365 /* The connection URI must start with either of the following designators: */
2366 static const char uri_designator[] = "postgresql://";
2367 static const char short_uri_designator[] = "postgres://";
2369 if (strncmp(connstr, uri_designator,
2370 sizeof(uri_designator) - 1) == 0)
2371 return sizeof(uri_designator) - 1;
2373 if (strncmp(connstr, short_uri_designator,
2374 sizeof(short_uri_designator) - 1) == 0)
2375 return sizeof(short_uri_designator) - 1;
2381 * Recognized connection string either starts with a valid URI prefix or
2382 * contains a "=" in it.
2384 * Must be consistent with parse_connection_string: anything for which this
2385 * returns true should at least look like it's parseable by that routine.
2387 * XXX This is a duplicate of the eponymous libpq function.
2390 recognized_connection_string(const char *connstr)
2392 return uri_prefix_length(connstr) != 0 || strchr(connstr, '=') != NULL;