2
* psql - the PostgreSQL interactive terminal
4
* Copyright (c) 2000-2013, PostgreSQL Global Development Group
6
* src/bin/psql/common.c
8
#include "postgres_fe.h"
14
#include <unistd.h> /* for write() */
16
#include <io.h> /* for _write() */
20
#include "portability/instr_time.h"
29
static bool ExecQueryUsingCursor(const char *query, double *elapsed_msec);
30
static bool command_no_begin(const char *query);
31
static bool is_select_command(const char *query);
35
* -- handler for -o command line option and \o command
37
* Tries to open file fname (or pipe if fname starts with '|')
38
* and stores the file handle in pset)
39
* Upon failure, sets stdout and returns false.
42
setQFout(const char *fname)
46
/* Close old file/pipe */
47
if (pset.queryFout && pset.queryFout != stdout && pset.queryFout != stderr)
49
if (pset.queryFoutPipe)
50
pclose(pset.queryFout);
52
fclose(pset.queryFout);
55
/* If no filename, set stdout */
56
if (!fname || fname[0] == '\0')
58
pset.queryFout = stdout;
59
pset.queryFoutPipe = false;
61
else if (*fname == '|')
63
pset.queryFout = popen(fname + 1, "w");
64
pset.queryFoutPipe = true;
68
pset.queryFout = fopen(fname, "w");
69
pset.queryFoutPipe = false;
72
if (!(pset.queryFout))
74
psql_error("%s: %s\n", fname, strerror(errno));
75
pset.queryFout = stdout;
76
pset.queryFoutPipe = false;
82
pqsignal(SIGPIPE, pset.queryFoutPipe ? SIG_IGN : SIG_DFL);
91
* Error reporting for scripts. Errors should look like
92
* psql:filename:lineno: message
96
psql_error(const char *fmt,...)
101
if (pset.queryFout && pset.queryFout != stdout)
102
fflush(pset.queryFout);
105
fprintf(stderr, "%s:%s:" UINT64_FORMAT ": ", pset.progname, pset.inputfile, pset.lineno);
107
vfprintf(stderr, _(fmt), ap);
114
* for backend Notice messages (INFO, WARNING, etc)
117
NoticeProcessor(void *arg, const char *message)
119
(void) arg; /* not used */
120
psql_error("%s", message);
126
* Code to support query cancellation
128
* Before we start a query, we enable the SIGINT signal catcher to send a
129
* cancel request to the backend. Note that sending the cancel directly from
130
* the signal handler is safe because PQcancel() is written to make it
131
* so. We use write() to report to stderr because it's better to use simple
132
* facilities in a signal handler.
134
* On win32, the signal canceling happens on a separate thread, because
135
* that's how SetConsoleCtrlHandler works. The PQcancel function is safe
136
* for this (unlike PQrequestCancel). However, a CRITICAL_SECTION is required
137
* to protect the PGcancel structure against being changed while the signal
138
* thread is using it.
140
* SIGINT is supposed to abort all long-running psql operations, not only
141
* database queries. In most places, this is accomplished by checking
142
* cancel_pressed during long-running loops. However, that won't work when
143
* blocked on user input (in readline() or fgets()). In those places, we
144
* set sigint_interrupt_enabled TRUE while blocked, instructing the signal
145
* catcher to longjmp through sigint_interrupt_jmp. We assume readline and
146
* fgets are coded to handle possible interruption. (XXX currently this does
147
* not work on win32, so control-C is less useful there)
149
volatile bool sigint_interrupt_enabled = false;
151
sigjmp_buf sigint_interrupt_jmp;
153
static PGcancel *volatile cancelConn = NULL;
156
static CRITICAL_SECTION cancelConnLock;
159
/* Used from signal handlers, no buffering */
160
#define write_stderr(str) write(fileno(stderr), str, strlen(str))
166
handle_sigint(SIGNAL_ARGS)
168
int save_errno = errno;
172
/* if we are waiting for input, longjmp out of it */
173
if (sigint_interrupt_enabled)
175
sigint_interrupt_enabled = false;
176
siglongjmp(sigint_interrupt_jmp, 1);
179
/* else, set cancel flag to stop any long-running loops */
180
cancel_pressed = true;
182
/* and send QueryCancel if we are processing a database query */
183
if (cancelConn != NULL)
185
if (PQcancel(cancelConn, errbuf, sizeof(errbuf)))
187
rc = write_stderr("Cancel request sent\n");
188
(void) rc; /* ignore errors, nothing we can do here */
192
rc = write_stderr("Could not send cancel request: ");
193
(void) rc; /* ignore errors, nothing we can do here */
194
rc = write_stderr(errbuf);
195
(void) rc; /* ignore errors, nothing we can do here */
199
errno = save_errno; /* just in case the write changed it */
203
setup_cancel_handler(void)
205
pqsignal(SIGINT, handle_sigint);
210
consoleHandler(DWORD dwCtrlType)
214
if (dwCtrlType == CTRL_C_EVENT ||
215
dwCtrlType == CTRL_BREAK_EVENT)
218
* Can't longjmp here, because we are in wrong thread :-(
221
/* set cancel flag to stop any long-running loops */
222
cancel_pressed = true;
224
/* and send QueryCancel if we are processing a database query */
225
EnterCriticalSection(&cancelConnLock);
226
if (cancelConn != NULL)
228
if (PQcancel(cancelConn, errbuf, sizeof(errbuf)))
229
write_stderr("Cancel request sent\n");
232
write_stderr("Could not send cancel request: ");
233
write_stderr(errbuf);
236
LeaveCriticalSection(&cancelConnLock);
241
/* Return FALSE for any signals not being handled */
246
setup_cancel_handler(void)
248
InitializeCriticalSection(&cancelConnLock);
250
SetConsoleCtrlHandler(consoleHandler, TRUE);
257
* Returns whether our backend connection is still there.
262
return PQstatus(pset.db) != CONNECTION_BAD;
269
* Verify that we still have a good connection to the backend, and if not,
270
* see if it can be restored.
272
* Returns true if either the connection was still there, or it could be
273
* restored successfully; false otherwise. If, however, there was no
274
* connection and the session is non-interactive, this will exit the program
275
* with a code of EXIT_BADCONN.
278
CheckConnection(void)
285
if (!pset.cur_cmd_interactive)
287
psql_error("connection to server was lost\n");
291
psql_error("The connection to the server was lost. Attempting reset: ");
296
psql_error("Failed.\n");
303
psql_error("Succeeded.\n");
314
* Set cancelConn to point to the current database connection.
319
PGcancel *oldCancelConn;
322
EnterCriticalSection(&cancelConnLock);
325
/* Free the old one if we have one */
326
oldCancelConn = cancelConn;
327
/* be sure handle_sigint doesn't use pointer while freeing */
330
if (oldCancelConn != NULL)
331
PQfreeCancel(oldCancelConn);
333
cancelConn = PQgetCancel(pset.db);
336
LeaveCriticalSection(&cancelConnLock);
344
* Free the current cancel connection, if any, and set to NULL.
347
ResetCancelConn(void)
349
PGcancel *oldCancelConn;
352
EnterCriticalSection(&cancelConnLock);
355
oldCancelConn = cancelConn;
356
/* be sure handle_sigint doesn't use pointer while freeing */
359
if (oldCancelConn != NULL)
360
PQfreeCancel(oldCancelConn);
363
LeaveCriticalSection(&cancelConnLock);
371
* Checks whether a result is valid, giving an error message if necessary;
372
* and ensures that the connection to the backend is still up.
374
* Returns true for valid result, false for error state.
377
AcceptResult(const PGresult *result)
384
switch (PQresultStatus(result))
386
case PGRES_COMMAND_OK:
387
case PGRES_TUPLES_OK:
388
case PGRES_EMPTY_QUERY:
391
/* Fine, do nothing */
395
case PGRES_BAD_RESPONSE:
396
case PGRES_NONFATAL_ERROR:
397
case PGRES_FATAL_ERROR:
403
psql_error("unexpected PQresultStatus: %d\n",
404
PQresultStatus(result));
410
const char *error = PQerrorMessage(pset.db);
413
psql_error("%s", error);
426
* This is the way to send "backdoor" queries (those not directly entered
427
* by the user). It is subject to -E but not -e.
429
* In autocommit-off mode, a new transaction block is started if start_xact
430
* is true; nothing special is done when start_xact is false. Typically,
431
* start_xact = false is used for SELECTs and explicit BEGIN/COMMIT commands.
433
* Caller is responsible for handling the ensuing processing if a COPY
436
* Note: we don't bother to check PQclientEncoding; it is assumed that no
437
* caller uses this path to issue "SET CLIENT_ENCODING".
440
PSQLexec(const char *query, bool start_xact)
446
psql_error("You are currently not connected to a database.\n");
450
if (pset.echo_hidden != PSQL_ECHO_HIDDEN_OFF)
452
printf(_("********* QUERY **********\n"
454
"**************************\n\n"), query);
458
fprintf(pset.logfile,
459
_("********* QUERY **********\n"
461
"**************************\n\n"), query);
462
fflush(pset.logfile);
465
if (pset.echo_hidden == PSQL_ECHO_HIDDEN_NOEXEC)
473
PQtransactionStatus(pset.db) == PQTRANS_IDLE)
475
res = PQexec(pset.db, "BEGIN");
476
if (PQresultStatus(res) != PGRES_COMMAND_OK)
478
psql_error("%s", PQerrorMessage(pset.db));
486
res = PQexec(pset.db, query);
490
if (!AcceptResult(res))
502
* PrintNotifications: check for asynchronous notifications, and print them out
505
PrintNotifications(void)
509
while ((notify = PQnotifies(pset.db)))
511
/* for backward compatibility, only show payload if nonempty */
512
if (notify->extra[0])
513
fprintf(pset.queryFout, _("Asynchronous notification \"%s\" with payload \"%s\" received from server process with PID %d.\n"),
514
notify->relname, notify->extra, notify->be_pid);
516
fprintf(pset.queryFout, _("Asynchronous notification \"%s\" received from server process with PID %d.\n"),
517
notify->relname, notify->be_pid);
518
fflush(pset.queryFout);
525
* PrintQueryTuples: assuming query result is OK, print its tuples
527
* Returns true if successful, false otherwise.
530
PrintQueryTuples(const PGresult *results)
532
printQueryOpt my_popt = pset.popt;
534
/* write output to \g argument, if any */
537
/* keep this code in sync with ExecQueryUsingCursor */
538
FILE *queryFout_copy = pset.queryFout;
539
bool queryFoutPipe_copy = pset.queryFoutPipe;
541
pset.queryFout = stdout; /* so it doesn't get closed */
544
if (!setQFout(pset.gfname))
546
pset.queryFout = queryFout_copy;
547
pset.queryFoutPipe = queryFoutPipe_copy;
551
printQuery(results, &my_popt, pset.queryFout, pset.logfile);
553
/* close file/pipe, restore old setting */
556
pset.queryFout = queryFout_copy;
557
pset.queryFoutPipe = queryFoutPipe_copy;
560
printQuery(results, &my_popt, pset.queryFout, pset.logfile);
567
* StoreQueryTuple: assuming query result is OK, save data into variables
569
* Returns true if successful, false otherwise.
572
StoreQueryTuple(const PGresult *result)
576
if (PQntuples(result) < 1)
578
psql_error("no rows returned for \\gset\n");
581
else if (PQntuples(result) > 1)
583
psql_error("more than one row returned for \\gset\n");
590
for (i = 0; i < PQnfields(result); i++)
592
char *colname = PQfname(result, i);
596
/* concate prefix and column name */
597
varname = pg_malloc(strlen(pset.gset_prefix) + strlen(colname) + 1);
598
strcpy(varname, pset.gset_prefix);
599
strcat(varname, colname);
601
if (!PQgetisnull(result, 0, i))
602
value = PQgetvalue(result, 0, i);
605
/* for NULL value, unset rather than set the variable */
609
if (!SetVariable(pset.vars, varname, value))
611
psql_error("could not set variable \"%s\"\n", varname);
626
* ProcessResult: utility function for use by SendQuery() only
628
* When our command string contained a COPY FROM STDIN or COPY TO STDOUT,
629
* PQexec() has stopped at the PGresult associated with the first such
630
* command. In that event, we'll marshal data for the COPY and then cycle
631
* through any subsequent PGresult objects.
633
* When the command string contained no affected COPY command, this function
634
* degenerates to an AcceptResult() call.
636
* Changes its argument to point to the last PGresult of the command string,
637
* or NULL if that result was for a COPY FROM STDIN or COPY TO STDOUT.
639
* Returns true on complete success, false otherwise. Possible failure modes
640
* include purely client-side problems; check the transaction status for the
641
* server-side opinion.
644
ProcessResult(PGresult **results)
646
PGresult *next_result;
648
bool first_cycle = true;
652
ExecStatusType result_status;
655
if (!AcceptResult(*results))
658
* Failure at this point is always a server-side failure or a
659
* failure to submit the command string. Either way, we're
660
* finished with this command string.
666
result_status = PQresultStatus(*results);
667
switch (result_status)
669
case PGRES_EMPTY_QUERY:
670
case PGRES_COMMAND_OK:
671
case PGRES_TUPLES_OK:
681
/* AcceptResult() should have caught anything else. */
683
psql_error("unexpected PQresultStatus: %d\n", result_status);
690
* Marshal the COPY data. Either subroutine will get the
691
* connection out of its COPY state, then call PQresultStatus()
692
* once and report any error.
695
if (result_status == PGRES_COPY_OUT)
696
success = handleCopyOut(pset.db, pset.queryFout) && success;
698
success = handleCopyIn(pset.db, pset.cur_cmd_source,
699
PQbinaryTuples(*results)) && success;
703
* Call PQgetResult() once more. In the typical case of a
704
* single-command string, it will return NULL. Otherwise, we'll
705
* have other results to process that may include other COPYs.
708
*results = next_result = PQgetResult(pset.db);
710
else if (first_cycle)
711
/* fast path: no COPY commands; PQexec visited all results */
713
else if ((next_result = PQgetResult(pset.db)))
715
/* non-COPY command(s) after a COPY: keep the last one */
717
*results = next_result;
721
} while (next_result);
723
/* may need this to recover from conn loss during COPY */
724
if (!first_cycle && !CheckConnection())
732
* PrintQueryStatus: report command status as required
734
* Note: Utility function for use by PrintQueryResults() only.
737
PrintQueryStatus(PGresult *results)
743
if (pset.popt.topt.format == PRINT_HTML)
745
fputs("<p>", pset.queryFout);
746
html_escaped_print(PQcmdStatus(results), pset.queryFout);
747
fputs("</p>\n", pset.queryFout);
750
fprintf(pset.queryFout, "%s\n", PQcmdStatus(results));
754
fprintf(pset.logfile, "%s\n", PQcmdStatus(results));
756
snprintf(buf, sizeof(buf), "%u", (unsigned int) PQoidValue(results));
757
SetVariable(pset.vars, "LASTOID", buf);
762
* PrintQueryResults: print out (or store) query results as required
764
* Note: Utility function for use by SendQuery() only.
766
* Returns true if the query executed successfully, false otherwise.
769
PrintQueryResults(PGresult *results)
772
const char *cmdstatus;
777
switch (PQresultStatus(results))
779
case PGRES_TUPLES_OK:
780
/* store or print the data ... */
781
if (pset.gset_prefix)
782
success = StoreQueryTuple(results);
784
success = PrintQueryTuples(results);
785
/* if it's INSERT/UPDATE/DELETE RETURNING, also print status */
786
cmdstatus = PQcmdStatus(results);
787
if (strncmp(cmdstatus, "INSERT", 6) == 0 ||
788
strncmp(cmdstatus, "UPDATE", 6) == 0 ||
789
strncmp(cmdstatus, "DELETE", 6) == 0)
790
PrintQueryStatus(results);
793
case PGRES_COMMAND_OK:
794
PrintQueryStatus(results);
798
case PGRES_EMPTY_QUERY:
804
/* nothing to do here */
808
case PGRES_BAD_RESPONSE:
809
case PGRES_NONFATAL_ERROR:
810
case PGRES_FATAL_ERROR:
816
psql_error("unexpected PQresultStatus: %d\n",
817
PQresultStatus(results));
821
fflush(pset.queryFout);
828
* SendQuery: send the query string to the backend
829
* (and print out results)
831
* Note: This is the "front door" way to send a query. That is, use it to
832
* send queries actually entered by the user. These queries will be subject to
834
* To send "back door" queries (generated by slash commands, etc.) in a
835
* controlled way, use PSQLexec().
837
* Returns true if the query executed successfully, false otherwise.
840
SendQuery(const char *query)
843
PGTransactionStatusType transaction_status;
844
double elapsed_msec = 0;
846
bool on_error_rollback_savepoint = false;
847
static bool on_error_rollback_warning = false;
851
psql_error("You are currently not connected to a database.\n");
852
goto sendquery_cleanup;
859
printf(_("***(Single step mode: verify command)*******************************************\n"
861
"***(press return to proceed or enter x and return to cancel)********************\n"),
864
if (fgets(buf, sizeof(buf), stdin) != NULL)
866
goto sendquery_cleanup;
868
else if (pset.echo == PSQL_ECHO_QUERIES)
876
fprintf(pset.logfile,
877
_("********* QUERY **********\n"
879
"**************************\n\n"), query);
880
fflush(pset.logfile);
885
transaction_status = PQtransactionStatus(pset.db);
887
if (transaction_status == PQTRANS_IDLE &&
889
!command_no_begin(query))
891
results = PQexec(pset.db, "BEGIN");
892
if (PQresultStatus(results) != PGRES_COMMAND_OK)
894
psql_error("%s", PQerrorMessage(pset.db));
897
goto sendquery_cleanup;
900
transaction_status = PQtransactionStatus(pset.db);
903
if (transaction_status == PQTRANS_INTRANS &&
904
pset.on_error_rollback != PSQL_ERROR_ROLLBACK_OFF &&
905
(pset.cur_cmd_interactive ||
906
pset.on_error_rollback == PSQL_ERROR_ROLLBACK_ON))
908
if (on_error_rollback_warning == false && pset.sversion < 80000)
910
psql_error("The server (version %d.%d) does not support savepoints for ON_ERROR_ROLLBACK.\n",
911
pset.sversion / 10000, (pset.sversion / 100) % 100);
912
on_error_rollback_warning = true;
916
results = PQexec(pset.db, "SAVEPOINT pg_psql_temporary_savepoint");
917
if (PQresultStatus(results) != PGRES_COMMAND_OK)
919
psql_error("%s", PQerrorMessage(pset.db));
922
goto sendquery_cleanup;
925
on_error_rollback_savepoint = true;
929
if (pset.fetch_count <= 0 || !is_select_command(query))
931
/* Default fetch-it-all-and-print mode */
936
INSTR_TIME_SET_CURRENT(before);
938
results = PQexec(pset.db, query);
940
/* these operations are included in the timing result: */
942
OK = ProcessResult(&results);
946
INSTR_TIME_SET_CURRENT(after);
947
INSTR_TIME_SUBTRACT(after, before);
948
elapsed_msec = INSTR_TIME_GET_MILLISEC(after);
951
/* but printing results isn't: */
953
OK = PrintQueryResults(results);
957
/* Fetch-in-segments mode */
958
OK = ExecQueryUsingCursor(query, &elapsed_msec);
960
results = NULL; /* PQclear(NULL) does nothing */
963
/* If we made a temporary savepoint, possibly release/rollback */
964
if (on_error_rollback_savepoint)
966
const char *svptcmd = NULL;
968
transaction_status = PQtransactionStatus(pset.db);
970
switch (transaction_status)
972
case PQTRANS_INERROR:
973
/* We always rollback on an error */
974
svptcmd = "ROLLBACK TO pg_psql_temporary_savepoint";
978
/* If they are no longer in a transaction, then do nothing */
981
case PQTRANS_INTRANS:
984
* Do nothing if they are messing with savepoints themselves:
985
* If the user did RELEASE or ROLLBACK, our savepoint is gone.
986
* If they issued a SAVEPOINT, releasing ours would remove
990
(strcmp(PQcmdStatus(results), "SAVEPOINT") == 0 ||
991
strcmp(PQcmdStatus(results), "RELEASE") == 0 ||
992
strcmp(PQcmdStatus(results), "ROLLBACK") == 0))
995
svptcmd = "RELEASE pg_psql_temporary_savepoint";
999
case PQTRANS_UNKNOWN:
1002
/* PQTRANS_UNKNOWN is expected given a broken connection. */
1003
if (transaction_status != PQTRANS_UNKNOWN || ConnectionUp())
1004
psql_error("unexpected transaction status (%d)\n",
1005
transaction_status);
1013
svptres = PQexec(pset.db, svptcmd);
1014
if (PQresultStatus(svptres) != PGRES_COMMAND_OK)
1016
psql_error("%s", PQerrorMessage(pset.db));
1022
goto sendquery_cleanup;
1030
/* Possible microtiming output */
1032
printf(_("Time: %.3f ms\n"), elapsed_msec);
1034
/* check for events that may occur during query execution */
1036
if (pset.encoding != PQclientEncoding(pset.db) &&
1037
PQclientEncoding(pset.db) >= 0)
1039
/* track effects of SET CLIENT_ENCODING */
1040
pset.encoding = PQclientEncoding(pset.db);
1041
pset.popt.topt.encoding = pset.encoding;
1042
SetVariable(pset.vars, "ENCODING",
1043
pg_encoding_to_char(pset.encoding));
1046
PrintNotifications();
1048
/* perform cleanup that should occur after any attempted query */
1052
/* reset \g's output-to-filename trigger */
1059
/* reset \gset trigger */
1060
if (pset.gset_prefix)
1062
free(pset.gset_prefix);
1063
pset.gset_prefix = NULL;
1071
* ExecQueryUsingCursor: run a SELECT-like query using a cursor
1073
* This feature allows result sets larger than RAM to be dealt with.
1075
* Returns true if the query executed successfully, false otherwise.
1077
* If pset.timing is on, total query time (exclusive of result-printing) is
1078
* stored into *elapsed_msec.
1081
ExecQueryUsingCursor(const char *query, double *elapsed_msec)
1085
PQExpBufferData buf;
1086
printQueryOpt my_popt = pset.popt;
1087
FILE *queryFout_copy = pset.queryFout;
1088
bool queryFoutPipe_copy = pset.queryFoutPipe;
1089
bool started_txn = false;
1090
bool did_pager = false;
1100
/* initialize print options for partial table output */
1101
my_popt.topt.start_table = true;
1102
my_popt.topt.stop_table = false;
1103
my_popt.topt.prior_records = 0;
1106
INSTR_TIME_SET_CURRENT(before);
1108
/* if we're not in a transaction, start one */
1109
if (PQtransactionStatus(pset.db) == PQTRANS_IDLE)
1111
results = PQexec(pset.db, "BEGIN");
1112
OK = AcceptResult(results) &&
1113
(PQresultStatus(results) == PGRES_COMMAND_OK);
1120
/* Send DECLARE CURSOR */
1121
initPQExpBuffer(&buf);
1122
appendPQExpBuffer(&buf, "DECLARE _psql_cursor NO SCROLL CURSOR FOR\n%s",
1125
results = PQexec(pset.db, buf.data);
1126
OK = AcceptResult(results) &&
1127
(PQresultStatus(results) == PGRES_COMMAND_OK);
1129
termPQExpBuffer(&buf);
1135
INSTR_TIME_SET_CURRENT(after);
1136
INSTR_TIME_SUBTRACT(after, before);
1137
*elapsed_msec += INSTR_TIME_GET_MILLISEC(after);
1141
* In \gset mode, we force the fetch count to be 2, so that we will throw
1142
* the appropriate error if the query returns more than one row.
1144
if (pset.gset_prefix)
1147
fetch_count = pset.fetch_count;
1149
snprintf(fetch_cmd, sizeof(fetch_cmd),
1150
"FETCH FORWARD %d FROM _psql_cursor",
1153
/* prepare to write output to \g argument, if any */
1156
/* keep this code in sync with PrintQueryTuples */
1157
pset.queryFout = stdout; /* so it doesn't get closed */
1159
/* open file/pipe */
1160
if (!setQFout(pset.gfname))
1162
pset.queryFout = queryFout_copy;
1163
pset.queryFoutPipe = queryFoutPipe_copy;
1169
/* clear any pre-existing error indication on the output stream */
1170
clearerr(pset.queryFout);
1175
INSTR_TIME_SET_CURRENT(before);
1177
/* get fetch_count tuples at a time */
1178
results = PQexec(pset.db, fetch_cmd);
1182
INSTR_TIME_SET_CURRENT(after);
1183
INSTR_TIME_SUBTRACT(after, before);
1184
*elapsed_msec += INSTR_TIME_GET_MILLISEC(after);
1187
if (PQresultStatus(results) != PGRES_TUPLES_OK)
1189
/* shut down pager before printing error message */
1192
ClosePager(pset.queryFout);
1193
pset.queryFout = queryFout_copy;
1194
pset.queryFoutPipe = queryFoutPipe_copy;
1198
OK = AcceptResult(results);
1204
if (pset.gset_prefix)
1206
/* StoreQueryTuple will complain if not exactly one row */
1207
OK = StoreQueryTuple(results);
1212
ntuples = PQntuples(results);
1214
if (ntuples < fetch_count)
1216
/* this is the last result set, so allow footer decoration */
1217
my_popt.topt.stop_table = true;
1219
else if (pset.queryFout == stdout && !did_pager)
1222
* If query requires multiple result sets, hack to ensure that
1223
* only one pager instance is used for the whole mess
1225
pset.queryFout = PageOutput(100000, my_popt.topt.pager);
1229
printQuery(results, &my_popt, pset.queryFout, pset.logfile);
1233
/* after the first result set, disallow header decoration */
1234
my_popt.topt.start_table = false;
1235
my_popt.topt.prior_records += ntuples;
1238
* Make sure to flush the output stream, so intermediate results are
1239
* visible to the client immediately. We check the results because if
1240
* the pager dies/exits/etc, there's no sense throwing more data at
1243
flush_error = fflush(pset.queryFout);
1246
* Check if we are at the end, if a cancel was pressed, or if there
1247
* were any errors either trying to flush out the results, or more
1248
* generally on the output stream at all. If we hit any errors
1249
* writing things to the stream, we presume $PAGER has disappeared and
1250
* stop bothering to pull down more data.
1252
if (ntuples < fetch_count || cancel_pressed || flush_error ||
1253
ferror(pset.queryFout))
1257
/* close \g argument file/pipe, restore old setting */
1260
/* keep this code in sync with PrintQueryTuples */
1263
pset.queryFout = queryFout_copy;
1264
pset.queryFoutPipe = queryFoutPipe_copy;
1268
ClosePager(pset.queryFout);
1269
pset.queryFout = queryFout_copy;
1270
pset.queryFoutPipe = queryFoutPipe_copy;
1275
INSTR_TIME_SET_CURRENT(before);
1278
* We try to close the cursor on either success or failure, but on failure
1279
* ignore the result (it's probably just a bleat about being in an aborted
1282
results = PQexec(pset.db, "CLOSE _psql_cursor");
1285
OK = AcceptResult(results) &&
1286
(PQresultStatus(results) == PGRES_COMMAND_OK);
1292
results = PQexec(pset.db, OK ? "COMMIT" : "ROLLBACK");
1293
OK &= AcceptResult(results) &&
1294
(PQresultStatus(results) == PGRES_COMMAND_OK);
1300
INSTR_TIME_SET_CURRENT(after);
1301
INSTR_TIME_SUBTRACT(after, before);
1302
*elapsed_msec += INSTR_TIME_GET_MILLISEC(after);
1310
* Advance the given char pointer over white space and SQL comments.
1313
skip_white_space(const char *query)
1315
int cnestlevel = 0; /* slash-star comment nest level */
1319
int mblen = PQmblen(query, pset.encoding);
1322
* Note: we assume the encoding is a superset of ASCII, so that for
1323
* example "query[0] == '/'" is meaningful. However, we do NOT assume
1324
* that the second and subsequent bytes of a multibyte character
1325
* couldn't look like ASCII characters; so it is critical to advance
1326
* by mblen, not 1, whenever we haven't exactly identified the
1327
* character we are skipping over.
1329
if (isspace((unsigned char) *query))
1331
else if (query[0] == '/' && query[1] == '*')
1336
else if (cnestlevel > 0 && query[0] == '*' && query[1] == '/')
1341
else if (cnestlevel == 0 && query[0] == '-' && query[1] == '-')
1346
* We have to skip to end of line since any slash-star inside the
1347
* -- comment does NOT start a slash-star comment.
1356
query += PQmblen(query, pset.encoding);
1359
else if (cnestlevel > 0)
1362
break; /* found first token */
1370
* Check whether a command is one of those for which we should NOT start
1371
* a new transaction block (ie, send a preceding BEGIN).
1373
* These include the transaction control statements themselves, plus
1374
* certain statements that the backend disallows inside transaction blocks.
1377
command_no_begin(const char *query)
1382
* First we must advance over any whitespace and comments.
1384
query = skip_white_space(query);
1387
* Check word length (since "beginx" is not "begin").
1390
while (isalpha((unsigned char) query[wordlen]))
1391
wordlen += PQmblen(&query[wordlen], pset.encoding);
1394
* Transaction control commands. These should include every keyword that
1395
* gives rise to a TransactionStmt in the backend grammar, except for the
1396
* savepoint-related commands.
1398
* (We assume that START must be START TRANSACTION, since there is
1399
* presently no other "START foo" command.)
1401
if (wordlen == 5 && pg_strncasecmp(query, "abort", 5) == 0)
1403
if (wordlen == 5 && pg_strncasecmp(query, "begin", 5) == 0)
1405
if (wordlen == 5 && pg_strncasecmp(query, "start", 5) == 0)
1407
if (wordlen == 6 && pg_strncasecmp(query, "commit", 6) == 0)
1409
if (wordlen == 3 && pg_strncasecmp(query, "end", 3) == 0)
1411
if (wordlen == 8 && pg_strncasecmp(query, "rollback", 8) == 0)
1413
if (wordlen == 7 && pg_strncasecmp(query, "prepare", 7) == 0)
1415
/* PREPARE TRANSACTION is a TC command, PREPARE foo is not */
1418
query = skip_white_space(query);
1421
while (isalpha((unsigned char) query[wordlen]))
1422
wordlen += PQmblen(&query[wordlen], pset.encoding);
1424
if (wordlen == 11 && pg_strncasecmp(query, "transaction", 11) == 0)
1430
* Commands not allowed within transactions. The statements checked for
1431
* here should be exactly those that call PreventTransactionChain() in the
1434
if (wordlen == 6 && pg_strncasecmp(query, "vacuum", 6) == 0)
1436
if (wordlen == 7 && pg_strncasecmp(query, "cluster", 7) == 0)
1438
/* CLUSTER with any arguments is allowed in transactions */
1441
query = skip_white_space(query);
1443
if (isalpha((unsigned char) query[0]))
1444
return false; /* has additional words */
1445
return true; /* it's CLUSTER without arguments */
1448
if (wordlen == 6 && pg_strncasecmp(query, "create", 6) == 0)
1452
query = skip_white_space(query);
1455
while (isalpha((unsigned char) query[wordlen]))
1456
wordlen += PQmblen(&query[wordlen], pset.encoding);
1458
if (wordlen == 8 && pg_strncasecmp(query, "database", 8) == 0)
1460
if (wordlen == 10 && pg_strncasecmp(query, "tablespace", 10) == 0)
1463
/* CREATE [UNIQUE] INDEX CONCURRENTLY isn't allowed in xacts */
1464
if (wordlen == 6 && pg_strncasecmp(query, "unique", 6) == 0)
1468
query = skip_white_space(query);
1471
while (isalpha((unsigned char) query[wordlen]))
1472
wordlen += PQmblen(&query[wordlen], pset.encoding);
1475
if (wordlen == 5 && pg_strncasecmp(query, "index", 5) == 0)
1479
query = skip_white_space(query);
1482
while (isalpha((unsigned char) query[wordlen]))
1483
wordlen += PQmblen(&query[wordlen], pset.encoding);
1485
if (wordlen == 12 && pg_strncasecmp(query, "concurrently", 12) == 0)
1493
* Note: these tests will match DROP SYSTEM and REINDEX TABLESPACE, which
1494
* aren't really valid commands so we don't care much. The other four
1495
* possible matches are correct.
1497
if ((wordlen == 4 && pg_strncasecmp(query, "drop", 4) == 0) ||
1498
(wordlen == 7 && pg_strncasecmp(query, "reindex", 7) == 0))
1502
query = skip_white_space(query);
1505
while (isalpha((unsigned char) query[wordlen]))
1506
wordlen += PQmblen(&query[wordlen], pset.encoding);
1508
if (wordlen == 8 && pg_strncasecmp(query, "database", 8) == 0)
1510
if (wordlen == 6 && pg_strncasecmp(query, "system", 6) == 0)
1512
if (wordlen == 10 && pg_strncasecmp(query, "tablespace", 10) == 0)
1517
/* DISCARD ALL isn't allowed in xacts, but other variants are allowed. */
1518
if (wordlen == 7 && pg_strncasecmp(query, "discard", 7) == 0)
1522
query = skip_white_space(query);
1525
while (isalpha((unsigned char) query[wordlen]))
1526
wordlen += PQmblen(&query[wordlen], pset.encoding);
1528
if (wordlen == 3 && pg_strncasecmp(query, "all", 3) == 0)
1538
* Check whether the specified command is a SELECT (or VALUES).
1541
is_select_command(const char *query)
1546
* First advance over any whitespace, comments and left parentheses.
1550
query = skip_white_space(query);
1551
if (query[0] == '(')
1558
* Check word length (since "selectx" is not "select").
1561
while (isalpha((unsigned char) query[wordlen]))
1562
wordlen += PQmblen(&query[wordlen], pset.encoding);
1564
if (wordlen == 6 && pg_strncasecmp(query, "select", 6) == 0)
1567
if (wordlen == 6 && pg_strncasecmp(query, "values", 6) == 0)
1575
* Test if the current user is a database superuser.
1577
* Note: this will correctly detect superuserness only with a protocol-3.0
1578
* or newer backend; otherwise it will always say "false".
1588
val = PQparameterStatus(pset.db, "is_superuser");
1590
if (val && strcmp(val, "on") == 0)
1598
* Test if the current session uses standard string literals.
1600
* Note: With a pre-protocol-3.0 connection this will always say "false",
1601
* which should be the right answer.
1604
standard_strings(void)
1611
val = PQparameterStatus(pset.db, "standard_conforming_strings");
1613
if (val && strcmp(val, "on") == 0)
1621
* Return the session user of the current connection.
1623
* Note: this will correctly detect the session user only with a
1624
* protocol-3.0 or newer backend; otherwise it will return the
1628
session_username(void)
1635
val = PQparameterStatus(pset.db, "session_authorization");
1639
return PQuser(pset.db);
1645
* substitute '~' with HOME or '~username' with username's home dir
1649
expand_tilde(char **filename)
1651
if (!filename || !(*filename))
1655
* WIN32 doesn't use tilde expansion for file names. Also, it uses tilde
1656
* for short versions of long file names, though the tilde is usually
1657
* toward the end, not at the beginning.
1661
/* try tilde expansion */
1662
if (**filename == '~')
1668
char home[MAXPGPATH];
1674
while (*p != '/' && *p != '\0')
1680
if (*(fn + 1) == '\0')
1681
get_home_path(home); /* ~ or ~/ only */
1682
else if ((pw = getpwnam(fn + 1)) != NULL)
1683
strlcpy(home, pw->pw_dir, sizeof(home)); /* ~user */
1686
if (strlen(home) != 0)
1690
newfn = pg_malloc(strlen(home) + strlen(p) + 1);
1691
strcpy(newfn, home);