Debian Codegraph @

src/bin/psql/common.c

raw ◀ ▶
1 Debian patch touch this file
1 /*
2 * psql - the PostgreSQL interactive terminal
3 *
4 * Copyright (c) 2000-2025, PostgreSQL Global Development Group
5 *
6 * src/bin/psql/common.c
7 */
8 #include "postgres_fe.h"
9
10 #include <ctype.h>
11 #include <limits.h>
12 #include <math.h>
13 #include <pwd.h>
14 #include <signal.h>
15 #ifndef WIN32
16 #include <unistd.h> /* for write() */
17 #else
18 #include <io.h> /* for _write() */
19 #include <win32.h>
20 #endif
21
22 #include "command.h"
23 #include "common.h"
24 #include "common/logging.h"
25 #include "copy.h"
26 #include "crosstabview.h"
27 #include "fe_utils/cancel.h"
28 #include "fe_utils/mbprint.h"
29 #include "fe_utils/string_utils.h"
30 #include "mainloop.h"
31 #include "portability/instr_time.h"
32 #include "settings.h"
33
34 static bool DescribeQuery(const char *query, double *elapsed_msec);
35 static int ExecQueryAndProcessResults(const char *query,
36 double *elapsed_msec,
37 bool *svpt_gone_p,
38 int num_copy_from_stdin,
39 bool is_watch,
40 int min_rows,
41 const printQueryOpt *opt,
42 FILE *printQueryFout);
43 static bool command_no_begin(const char *query);
44
45
46 /*
47 * openQueryOutputFile --- attempt to open a query output file
48 *
49 * fname == NULL selects stdout, else an initial '|' selects a pipe,
50 * else plain file.
51 *
52 * Returns output file pointer into *fout, and is-a-pipe flag into *is_pipe.
53 * Caller is responsible for adjusting SIGPIPE state if it's a pipe.
54 *
55 * On error, reports suitable error message and returns false.
56 */
57 bool
58 openQueryOutputFile(const char *fname, FILE **fout, bool *is_pipe)
59 {
60 if (!fname || fname[0] == '\0')
61 {
62 *fout = stdout;
63 *is_pipe = false;
64 }
65 else if (*fname == '|')
66 {
67 fflush(NULL);
68 *fout = popen(fname + 1, "w");
69 *is_pipe = true;
70 }
71 else
72 {
73 *fout = fopen(fname, "w");
74 *is_pipe = false;
75 }
76
77 if (*fout == NULL)
78 {
79 pg_log_error("%s: %m", fname);
80 return false;
81 }
82
83 return true;
84 }
85
86 /*
87 * Check if an output stream for \g needs to be opened, and if yes,
88 * open it and update the caller's gfile_fout and is_pipe state variables.
89 * Return true if OK, false if an error occurred.
90 */
91 static bool
92 SetupGOutput(FILE **gfile_fout, bool *is_pipe)
93 {
94 /* If there is a \g file or program, and it's not already open, open it */
95 if (pset.gfname != NULL && *gfile_fout == NULL)
96 {
97 if (openQueryOutputFile(pset.gfname, gfile_fout, is_pipe))
98 {
99 if (*is_pipe)
100 disable_sigpipe_trap();
101 }
102 else
103 return false;
104 }
105 return true;
106 }
107
108 /*
109 * Close the output stream for \g, if we opened it.
110 */
111 static void
112 CloseGOutput(FILE *gfile_fout, bool is_pipe)
113 {
114 if (gfile_fout)
115 {
116 if (is_pipe)
117 {
118 SetShellResultVariables(pclose(gfile_fout));
119 restore_sigpipe_trap();
120 }
121 else
122 fclose(gfile_fout);
123 }
124 }
125
126 /*
127 * Reset pset pipeline state
128 */
129 static void
130 pipelineReset(void)
131 {
132 pset.piped_syncs = 0;
133 pset.piped_commands = 0;
134 pset.available_results = 0;
135 pset.requested_results = 0;
136 }
137
138 /*
139 * setQFout
140 * -- handler for -o command line option and \o command
141 *
142 * On success, updates pset with the new output file and returns true.
143 * On failure, returns false without changing pset state.
144 */
145 bool
146 setQFout(const char *fname)
147 {
148 FILE *fout;
149 bool is_pipe;
150
151 /* First make sure we can open the new output file/pipe */
152 if (!openQueryOutputFile(fname, &fout, &is_pipe))
153 return false;
154
155 /* Close old file/pipe */
156 if (pset.queryFout && pset.queryFout != stdout && pset.queryFout != stderr)
157 {
158 if (pset.queryFoutPipe)
159 SetShellResultVariables(pclose(pset.queryFout));
160 else
161 fclose(pset.queryFout);
162 }
163
164 pset.queryFout = fout;
165 pset.queryFoutPipe = is_pipe;
166
167 /* Adjust SIGPIPE handling appropriately: ignore signal if is_pipe */
168 set_sigpipe_trap_state(is_pipe);
169 restore_sigpipe_trap();
170
171 return true;
172 }
173
174
175 /*
176 * Variable-fetching callback for flex lexer
177 *
178 * If the specified variable exists, return its value as a string (malloc'd
179 * and expected to be freed by the caller); else return NULL.
180 *
181 * If "quote" isn't PQUOTE_PLAIN, then return the value suitably quoted and
182 * escaped for the specified quoting requirement. (Failure in escaping
183 * should lead to printing an error and returning NULL.)
184 *
185 * "passthrough" is the pointer previously given to psql_scan_set_passthrough.
186 * In psql, passthrough points to a ConditionalStack, which we check to
187 * determine whether variable expansion is allowed.
188 */
189 char *
190 psql_get_variable(const char *varname, PsqlScanQuoteType quote,
191 void *passthrough)
192 {
193 char *result = NULL;
194 const char *value;
195
196 /* In an inactive \if branch, suppress all variable substitutions */
197 if (passthrough && !conditional_active((ConditionalStack) passthrough))
198 return NULL;
199
200 value = GetVariable(pset.vars, varname);
201 if (!value)
202 return NULL;
203
204 switch (quote)
205 {
206 case PQUOTE_PLAIN:
207 result = pg_strdup(value);
208 break;
209 case PQUOTE_SQL_LITERAL:
210 case PQUOTE_SQL_IDENT:
211 {
212 /*
213 * For these cases, we use libpq's quoting functions, which
214 * assume the string is in the connection's client encoding.
215 */
216 char *escaped_value;
217
218 if (!pset.db)
219 {
220 pg_log_error("cannot escape without active connection");
221 return NULL;
222 }
223
224 if (quote == PQUOTE_SQL_LITERAL)
225 escaped_value =
226 PQescapeLiteral(pset.db, value, strlen(value));
227 else
228 escaped_value =
229 PQescapeIdentifier(pset.db, value, strlen(value));
230
231 if (escaped_value == NULL)
232 {
233 const char *error = PQerrorMessage(pset.db);
234
235 pg_log_info("%s", error);
236 return NULL;
237 }
238
239 /*
240 * Rather than complicate the lexer's API with a notion of
241 * which free() routine to use, just pay the price of an extra
242 * strdup().
243 */
244 result = pg_strdup(escaped_value);
245 PQfreemem(escaped_value);
246 break;
247 }
248 case PQUOTE_SHELL_ARG:
249 {
250 /*
251 * For this we use appendShellStringNoError, which is
252 * encoding-agnostic, which is fine since the shell probably
253 * is too. In any case, the only special character is "'",
254 * which is not known to appear in valid multibyte characters.
255 */
256 PQExpBufferData buf;
257
258 initPQExpBuffer(&buf);
259 if (!appendShellStringNoError(&buf, value))
260 {
261 pg_log_error("shell command argument contains a newline or carriage return: \"%s\"",
262 value);
263 free(buf.data);
264 return NULL;
265 }
266 result = buf.data;
267 break;
268 }
269
270 /* No default: we want a compiler warning for missing cases */
271 }
272
273 return result;
274 }
275
276
277 /*
278 * for backend Notice messages (INFO, WARNING, etc)
279 */
280 void
281 NoticeProcessor(void *arg, const char *message)
282 {
283 (void) arg; /* not used */
284 pg_log_info("%s", message);
285 }
286
287
288
289 /*
290 * Code to support query cancellation
291 *
292 * Before we start a query, we enable the SIGINT signal catcher to send a
293 * cancel request to the backend.
294 *
295 * SIGINT is supposed to abort all long-running psql operations, not only
296 * database queries. In most places, this is accomplished by checking
297 * cancel_pressed during long-running loops. However, that won't work when
298 * blocked on user input (in readline() or fgets()). In those places, we
299 * set sigint_interrupt_enabled true while blocked, instructing the signal
300 * catcher to longjmp through sigint_interrupt_jmp. We assume readline and
301 * fgets are coded to handle possible interruption.
302 *
303 * On Windows, currently this does not work, so control-C is less useful
304 * there.
305 */
306 volatile sig_atomic_t sigint_interrupt_enabled = false;
307
308 sigjmp_buf sigint_interrupt_jmp;
309
310 static void
311 psql_cancel_callback(void)
312 {
313 #ifndef WIN32
314 /* if we are waiting for input, longjmp out of it */
315 if (sigint_interrupt_enabled)
316 {
317 sigint_interrupt_enabled = false;
318 siglongjmp(sigint_interrupt_jmp, 1);
319 }
320 #endif
321
322 /* else, set cancel flag to stop any long-running loops */
323 cancel_pressed = true;
324 }
325
326 void
327 psql_setup_cancel_handler(void)
328 {
329 setup_cancel_handler(psql_cancel_callback);
330 }
331
332
333 /* ConnectionUp
334 *
335 * Returns whether our backend connection is still there.
336 */
337 static bool
338 ConnectionUp(void)
339 {
340 return PQstatus(pset.db) != CONNECTION_BAD;
341 }
342
343
344
345 /* CheckConnection
346 *
347 * Verify that we still have a good connection to the backend, and if not,
348 * see if it can be restored.
349 *
350 * Returns true if either the connection was still there, or it could be
351 * restored successfully; false otherwise. If, however, there was no
352 * connection and the session is non-interactive, this will exit the program
353 * with a code of EXIT_BADCONN.
354 */
355 static bool
356 CheckConnection(void)
357 {
358 bool OK;
359
360 OK = ConnectionUp();
361 if (!OK)
362 {
363 if (!pset.cur_cmd_interactive)
364 {
365 pg_log_error("connection to server was lost");
366 exit(EXIT_BADCONN);
367 }
368
369 fprintf(stderr, _("The connection to the server was lost. Attempting reset: "));
370 PQreset(pset.db);
371 pipelineReset();
372 OK = ConnectionUp();
373 if (!OK)
374 {
375 fprintf(stderr, _("Failed.\n"));
376
377 /*
378 * Transition to having no connection; but stash away the failed
379 * connection so that we can still refer to its parameters in a
380 * later \connect attempt. Keep the state cleanup here in sync
381 * with do_connect().
382 */
383 if (pset.dead_conn)
384 PQfinish(pset.dead_conn);
385 pset.dead_conn = pset.db;
386 pset.db = NULL;
387 ResetCancelConn();
388 UnsyncVariables();
389 }
390 else
391 {
392 fprintf(stderr, _("Succeeded.\n"));
393
394 /*
395 * Re-sync, just in case anything changed. Keep this in sync with
396 * do_connect().
397 */
398 SyncVariables();
399 connection_warnings(false); /* Must be after SyncVariables */
400 }
401 }
402
403 return OK;
404 }
405
406
407
408
409 /*
410 * AcceptResult
411 *
412 * Checks whether a result is valid, giving an error message if necessary;
413 * and ensures that the connection to the backend is still up.
414 *
415 * Returns true for valid result, false for error state.
416 */
417 static bool
418 AcceptResult(const PGresult *result, bool show_error)
419 {
420 bool OK;
421
422 if (!result)
423 OK = false;
424 else
425 switch (PQresultStatus(result))
426 {
427 case PGRES_COMMAND_OK:
428 case PGRES_TUPLES_OK:
429 case PGRES_TUPLES_CHUNK:
430 case PGRES_EMPTY_QUERY:
431 case PGRES_COPY_IN:
432 case PGRES_COPY_OUT:
433 case PGRES_PIPELINE_SYNC:
434 /* Fine, do nothing */
435 OK = true;
436 break;
437
438 case PGRES_PIPELINE_ABORTED:
439 case PGRES_BAD_RESPONSE:
440 case PGRES_NONFATAL_ERROR:
441 case PGRES_FATAL_ERROR:
442 OK = false;
443 break;
444
445 default:
446 OK = false;
447 pg_log_error("unexpected PQresultStatus: %d",
448 PQresultStatus(result));
449 break;
450 }
451
452 if (!OK && show_error)
453 {
454 const char *error = PQerrorMessage(pset.db);
455
456 if (strlen(error))
457 pg_log_info("%s", error);
458
459 CheckConnection();
460 }
461
462 return OK;
463 }
464
465
466 /*
467 * Set special variables from a query result
468 * - ERROR: true/false, whether an error occurred on this query
469 * - SQLSTATE: code of error, or "00000" if no error, or "" if unknown
470 * - ROW_COUNT: how many rows were returned or affected, or "0"
471 * - LAST_ERROR_SQLSTATE: same for last error
472 * - LAST_ERROR_MESSAGE: message of last error
473 *
474 * Note: current policy is to apply this only to the results of queries
475 * entered by the user, not queries generated by slash commands.
476 */
477 static void
478 SetResultVariables(PGresult *result, bool success)
479 {
480 if (success)
481 {
482 const char *ntuples = PQcmdTuples(result);
483
484 SetVariable(pset.vars, "ERROR", "false");
485 SetVariable(pset.vars, "SQLSTATE", "00000");
486 SetVariable(pset.vars, "ROW_COUNT", *ntuples ? ntuples : "0");
487 }
488 else
489 {
490 const char *code = PQresultErrorField(result, PG_DIAG_SQLSTATE);
491 const char *mesg = PQresultErrorField(result, PG_DIAG_MESSAGE_PRIMARY);
492
493 SetVariable(pset.vars, "ERROR", "true");
494
495 /*
496 * If there is no SQLSTATE code, use an empty string. This can happen
497 * for libpq-detected errors (e.g., lost connection, ENOMEM).
498 */
499 if (code == NULL)
500 code = "";
501 SetVariable(pset.vars, "SQLSTATE", code);
502 SetVariable(pset.vars, "ROW_COUNT", "0");
503 SetVariable(pset.vars, "LAST_ERROR_SQLSTATE", code);
504 SetVariable(pset.vars, "LAST_ERROR_MESSAGE", mesg ? mesg : "");
505 }
506 }
507
508
509 /*
510 * Set special variables from a shell command result
511 * - SHELL_ERROR: true/false, whether command returned exit code 0
512 * - SHELL_EXIT_CODE: exit code according to shell conventions
513 *
514 * The argument is a wait status as returned by wait(2) or waitpid(2),
515 * which also applies to pclose(3) and system(3).
516 */
517 void
518 SetShellResultVariables(int wait_result)
519 {
520 char buf[32];
521
522 SetVariable(pset.vars, "SHELL_ERROR",
523 (wait_result == 0) ? "false" : "true");
524 snprintf(buf, sizeof(buf), "%d", wait_result_to_exit_code(wait_result));
525 SetVariable(pset.vars, "SHELL_EXIT_CODE", buf);
526 }
527
528
529 /*
530 * Set special pipeline variables
531 * - PIPELINE_SYNC_COUNT: The number of piped syncs
532 * - PIPELINE_COMMAND_COUNT: The number of piped commands
533 * - PIPELINE_RESULT_COUNT: The number of results available to read
534 */
535 static void
536 SetPipelineVariables(void)
537 {
538 char buf[32];
539
540 snprintf(buf, sizeof(buf), "%d", pset.piped_syncs);
541 SetVariable(pset.vars, "PIPELINE_SYNC_COUNT", buf);
542 snprintf(buf, sizeof(buf), "%d", pset.piped_commands);
543 SetVariable(pset.vars, "PIPELINE_COMMAND_COUNT", buf);
544 snprintf(buf, sizeof(buf), "%d", pset.available_results);
545 SetVariable(pset.vars, "PIPELINE_RESULT_COUNT", buf);
546 }
547
548
549 /*
550 * ClearOrSaveResult
551 *
552 * If the result represents an error, remember it for possible display by
553 * \errverbose. Otherwise, just PQclear() it.
554 *
555 * Note: current policy is to apply this to the results of all queries,
556 * including "back door" queries, for debugging's sake. It's OK to use
557 * PQclear() directly on results known to not be error results, however.
558 */
559 static void
560 ClearOrSaveResult(PGresult *result)
561 {
562 if (result)
563 {
564 switch (PQresultStatus(result))
565 {
566 case PGRES_NONFATAL_ERROR:
567 case PGRES_FATAL_ERROR:
568 PQclear(pset.last_error_result);
569 pset.last_error_result = result;
570 break;
571
572 default:
573 PQclear(result);
574 break;
575 }
576 }
577 }
578
579
580 /*
581 * Consume all results
582 */
583 static void
584 ClearOrSaveAllResults(void)
585 {
586 PGresult *result;
587
588 while ((result = PQgetResult(pset.db)) != NULL)
589 ClearOrSaveResult(result);
590 }
591
592
593 /*
594 * Print microtiming output. Always print raw milliseconds; if the interval
595 * is >= 1 second, also break it down into days/hours/minutes/seconds.
596 */
597 static void
598 PrintTiming(double elapsed_msec)
599 {
600 double seconds;
601 double minutes;
602 double hours;
603 double days;
604
605 if (elapsed_msec < 1000.0)
606 {
607 /* This is the traditional (pre-v10) output format */
608 printf(_("Time: %.3f ms\n"), elapsed_msec);
609 return;
610 }
611
612 /*
613 * Note: we could print just seconds, in a format like %06.3f, when the
614 * total is less than 1min. But that's hard to interpret unless we tack
615 * on "s" or otherwise annotate it. Forcing the display to include
616 * minutes seems like a better solution.
617 */
618 seconds = elapsed_msec / 1000.0;
619 minutes = floor(seconds / 60.0);
620 seconds -= 60.0 * minutes;
621 if (minutes < 60.0)
622 {
623 printf(_("Time: %.3f ms (%02d:%06.3f)\n"),
624 elapsed_msec, (int) minutes, seconds);
625 return;
626 }
627
628 hours = floor(minutes / 60.0);
629 minutes -= 60.0 * hours;
630 if (hours < 24.0)
631 {
632 printf(_("Time: %.3f ms (%02d:%02d:%06.3f)\n"),
633 elapsed_msec, (int) hours, (int) minutes, seconds);
634 return;
635 }
636
637 days = floor(hours / 24.0);
638 hours -= 24.0 * days;
639 printf(_("Time: %.3f ms (%.0f d %02d:%02d:%06.3f)\n"),
640 elapsed_msec, days, (int) hours, (int) minutes, seconds);
641 }
642
643
644 /*
645 * PSQLexec
646 *
647 * This is the way to send "backdoor" queries (those not directly entered
648 * by the user). It is subject to -E but not -e.
649 *
650 * Caller is responsible for handling the ensuing processing if a COPY
651 * command is sent.
652 *
653 * Note: we don't bother to check PQclientEncoding; it is assumed that no
654 * caller uses this path to issue "SET CLIENT_ENCODING".
655 */
656 PGresult *
657 PSQLexec(const char *query)
658 {
659 PGresult *res;
660
661 if (!pset.db)
662 {
663 pg_log_error("You are currently not connected to a database.");
664 return NULL;
665 }
666
667 if (pset.echo_hidden != PSQL_ECHO_HIDDEN_OFF)
668 {
669 printf(_("/******** QUERY *********/\n"
670 "%s\n"
671 "/************************/\n\n"), query);
672 fflush(stdout);
673 if (pset.logfile)
674 {
675 fprintf(pset.logfile,
676 _("/******** QUERY *********/\n"
677 "%s\n"
678 "/************************/\n\n"), query);
679 fflush(pset.logfile);
680 }
681
682 if (pset.echo_hidden == PSQL_ECHO_HIDDEN_NOEXEC)
683 return NULL;
684 }
685
686 SetCancelConn(pset.db);
687
688 res = PQexec(pset.db, query);
689
690 ResetCancelConn();
691
692 if (!AcceptResult(res, true))
693 {
694 ClearOrSaveResult(res);
695 res = NULL;
696 }
697
698 return res;
699 }
700
701
702 /*
703 * PSQLexecWatch
704 *
705 * This function is used for \watch command to send the query to
706 * the server and print out the result.
707 *
708 * Returns 1 if the query executed successfully, 0 if it cannot be repeated,
709 * e.g., because of the interrupt, -1 on error.
710 */
711 int
712 PSQLexecWatch(const char *query, const printQueryOpt *opt, FILE *printQueryFout, int min_rows)
713 {
714 bool timing = pset.timing;
715 double elapsed_msec = 0;
716 int res;
717
718 if (!pset.db)
719 {
720 pg_log_error("You are currently not connected to a database.");
721 return 0;
722 }
723
724 SetCancelConn(pset.db);
725
726 res = ExecQueryAndProcessResults(query,
727 &elapsed_msec, NULL,
728 -1,
729 true, min_rows,
730 opt, printQueryFout);
731
732 ResetCancelConn();
733
734 /* Possible microtiming output */
735 if (timing)
736 PrintTiming(elapsed_msec);
737
738 return res;
739 }
740
741
742 /*
743 * PrintNotifications: check for asynchronous notifications, and print them out
744 */
745 static void
746 PrintNotifications(void)
747 {
748 PGnotify *notify;
749
750 PQconsumeInput(pset.db);
751 while ((notify = PQnotifies(pset.db)) != NULL)
752 {
753 /* for backward compatibility, only show payload if nonempty */
754 if (notify->extra[0])
755 fprintf(pset.queryFout, _("Asynchronous notification \"%s\" with payload \"%s\" received from server process with PID %d.\n"),
756 notify->relname, notify->extra, notify->be_pid);
757 else
758 fprintf(pset.queryFout, _("Asynchronous notification \"%s\" received from server process with PID %d.\n"),
759 notify->relname, notify->be_pid);
760 fflush(pset.queryFout);
761 PQfreemem(notify);
762 PQconsumeInput(pset.db);
763 }
764 }
765
766
767 /*
768 * PrintQueryTuples: assuming query result is OK, print its tuples
769 *
770 * We use the options given by opt unless that's NULL, in which case
771 * we use pset.popt.
772 *
773 * Output is to printQueryFout unless that's NULL, in which case
774 * we use pset.queryFout.
775 *
776 * Returns true if successful, false otherwise.
777 */
778 static bool
779 PrintQueryTuples(const PGresult *result, const printQueryOpt *opt,
780 FILE *printQueryFout)
781 {
782 bool ok = true;
783 FILE *fout = printQueryFout ? printQueryFout : pset.queryFout;
784
785 printQuery(result, opt ? opt : &pset.popt, fout, false, pset.logfile);
786 fflush(fout);
787 if (ferror(fout))
788 {
789 pg_log_error("could not print result table: %m");
790 ok = false;
791 }
792
793 return ok;
794 }
795
796
797 /*
798 * StoreQueryTuple: assuming query result is OK, save data into variables
799 *
800 * Returns true if successful, false otherwise.
801 */
802 static bool
803 StoreQueryTuple(const PGresult *result)
804 {
805 bool success = true;
806
807 if (PQntuples(result) < 1)
808 {
809 pg_log_error("no rows returned for \\gset");
810 success = false;
811 }
812 else if (PQntuples(result) > 1)
813 {
814 pg_log_error("more than one row returned for \\gset");
815 success = false;
816 }
817 else
818 {
819 int i;
820
821 for (i = 0; i < PQnfields(result); i++)
822 {
823 char *colname = PQfname(result, i);
824 char *varname;
825 char *value;
826
827 /* concatenate prefix and column name */
828 varname = psprintf("%s%s", pset.gset_prefix, colname);
829
830 if (VariableHasHook(pset.vars, varname))
831 {
832 pg_log_warning("attempt to \\gset into specially treated variable \"%s\" ignored",
833 varname);
834 continue;
835 }
836
837 if (!PQgetisnull(result, 0, i))
838 value = PQgetvalue(result, 0, i);
839 else
840 {
841 /* for NULL value, unset rather than set the variable */
842 value = NULL;
843 }
844
845 if (!SetVariable(pset.vars, varname, value))
846 {
847 free(varname);
848 success = false;
849 break;
850 }
851
852 free(varname);
853 }
854 }
855
856 return success;
857 }
858
859
860 /*
861 * ExecQueryTuples: assuming query result is OK, execute each query
862 * result field as a SQL statement
863 *
864 * Returns true if successful, false otherwise.
865 */
866 static bool
867 ExecQueryTuples(const PGresult *result)
868 {
869 bool success = true;
870 int nrows = PQntuples(result);
871 int ncolumns = PQnfields(result);
872 int r,
873 c;
874
875 /*
876 * We must turn off gexec_flag to avoid infinite recursion.
877 */
878 pset.gexec_flag = false;
879
880 for (r = 0; r < nrows; r++)
881 {
882 for (c = 0; c < ncolumns; c++)
883 {
884 if (!PQgetisnull(result, r, c))
885 {
886 const char *query = PQgetvalue(result, r, c);
887
888 /* Abandon execution if cancel_pressed */
889 if (cancel_pressed)
890 goto loop_exit;
891
892 /*
893 * ECHO_ALL mode should echo these queries, but SendQuery
894 * assumes that MainLoop did that, so we have to do it here.
895 */
896 if (pset.echo == PSQL_ECHO_ALL && !pset.singlestep)
897 {
898 puts(query);
899 fflush(stdout);
900 }
901
902 if (!SendQuery(query, -1))
903 {
904 /* Error - abandon execution if ON_ERROR_STOP */
905 success = false;
906 if (pset.on_error_stop)
907 goto loop_exit;
908 }
909 }
910 }
911 }
912
913 loop_exit:
914
915 /*
916 * Restore state. We know gexec_flag was on, else we'd not be here. (We
917 * also know it'll get turned off at end of command, but that's not ours
918 * to do here.)
919 */
920 pset.gexec_flag = true;
921
922 /* Return true if all queries were successful */
923 return success;
924 }
925
926
927 /*
928 * Marshal the COPY data. Either path will get the
929 * connection out of its COPY state, then call PQresultStatus()
930 * once and report any error. Return whether all was ok.
931 *
932 * For COPY OUT, direct the output to copystream, or discard if that's NULL.
933 * For COPY IN, read from copystream (which mustn't be NULL).
934 *
935 * Update *resultp if further processing is necessary; set to NULL otherwise.
936 * Return a result when queryFout can safely output a result status: on COPY
937 * IN, or on COPY OUT if written to something other than pset.queryFout.
938 * Returning NULL prevents the command status from being printed, which we
939 * want if the status line doesn't get taken as part of the COPY data.
940 */
941 static bool
942 HandleCopyResult(PGresult **resultp, FILE *copystream)
943 {
944 bool success;
945 PGresult *copy_result;
946 ExecStatusType result_status = PQresultStatus(*resultp);
947
948 Assert(result_status == PGRES_COPY_OUT ||
949 result_status == PGRES_COPY_IN);
950
951 SetCancelConn(pset.db);
952
953 if (result_status == PGRES_COPY_OUT)
954 {
955 success = handleCopyOut(pset.db,
956 copystream,
957 &copy_result)
958 && (copystream != NULL);
959
960 /*
961 * Suppress status printing if the report would go to the same place
962 * as the COPY data just went. Note this doesn't prevent error
963 * reporting, since handleCopyOut did that.
964 */
965 if (copystream == pset.queryFout)
966 {
967 PQclear(copy_result);
968 copy_result = NULL;
969 }
970 }
971 else
972 {
973 /* COPY IN */
974 Assert(copystream);
975 success = handleCopyIn(pset.db,
976 copystream,
977 PQbinaryTuples(*resultp),
978 &copy_result);
979 }
980 ResetCancelConn();
981
982 /*
983 * Replace the PGRES_COPY_OUT/IN result with COPY command's exit status,
984 * or with NULL if we want to suppress printing anything.
985 */
986 PQclear(*resultp);
987 *resultp = copy_result;
988
989 return success;
990 }
991
992 /*
993 * PrintQueryStatus: report command status as required
994 */
995 static void
996 PrintQueryStatus(PGresult *result, FILE *printQueryFout)
997 {
998 char buf[16];
999 const char *cmdstatus = PQcmdStatus(result);
1000 FILE *fout = printQueryFout ? printQueryFout : pset.queryFout;
1001
1002 /* Do nothing if it's a TUPLES_OK result that isn't from RETURNING */
1003 if (PQresultStatus(result) == PGRES_TUPLES_OK)
1004 {
1005 if (!(strncmp(cmdstatus, "INSERT", 6) == 0 ||
1006 strncmp(cmdstatus, "UPDATE", 6) == 0 ||
1007 strncmp(cmdstatus, "DELETE", 6) == 0 ||
1008 strncmp(cmdstatus, "MERGE", 5) == 0))
1009 return;
1010 }
1011
1012 if (!pset.quiet)
1013 {
1014 if (pset.popt.topt.format == PRINT_HTML)
1015 {
1016 fputs("<p>", fout);
1017 html_escaped_print(cmdstatus, fout);
1018 fputs("</p>\n", fout);
1019 }
1020 else
1021 fprintf(fout, "%s\n", cmdstatus);
1022 fflush(fout);
1023 }
1024
1025 if (pset.logfile)
1026 fprintf(pset.logfile, "%s\n", cmdstatus);
1027
1028 snprintf(buf, sizeof(buf), "%u", (unsigned int) PQoidValue(result));
1029 SetVariable(pset.vars, "LASTOID", buf);
1030 }
1031
1032
1033 /*
1034 * PrintQueryResult: print out (or store or execute) query result as required
1035 *
1036 * last is true if this is the last result of a command string.
1037 * opt and printQueryFout are defined as for PrintQueryTuples.
1038 * printStatusFout is where to send command status; NULL means pset.queryFout.
1039 *
1040 * Returns true if the query executed successfully, false otherwise.
1041 */
1042 static bool
1043 PrintQueryResult(PGresult *result, bool last,
1044 const printQueryOpt *opt, FILE *printQueryFout,
1045 FILE *printStatusFout)
1046 {
1047 bool success;
1048
1049 if (!result)
1050 return false;
1051
1052 switch (PQresultStatus(result))
1053 {
1054 case PGRES_TUPLES_OK:
1055 /* store or execute or print the data ... */
1056 if (last && pset.gset_prefix)
1057 success = StoreQueryTuple(result);
1058 else if (last && pset.gexec_flag)
1059 success = ExecQueryTuples(result);
1060 else if (last && pset.crosstab_flag)
1061 success = PrintResultInCrosstab(result);
1062 else if (last || pset.show_all_results)
1063 success = PrintQueryTuples(result, opt, printQueryFout);
1064 else
1065 success = true;
1066
1067 /*
1068 * If it's INSERT/UPDATE/DELETE/MERGE RETURNING, also print
1069 * status.
1070 */
1071 if (last || pset.show_all_results)
1072 PrintQueryStatus(result, printStatusFout);
1073
1074 break;
1075
1076 case PGRES_COMMAND_OK:
1077 if (last || pset.show_all_results)
1078 PrintQueryStatus(result, printStatusFout);
1079 success = true;
1080 break;
1081
1082 case PGRES_EMPTY_QUERY:
1083 success = true;
1084 break;
1085
1086 case PGRES_COPY_OUT:
1087 case PGRES_COPY_IN:
1088 /* nothing to do here: already processed */
1089 success = true;
1090 break;
1091
1092 case PGRES_PIPELINE_ABORTED:
1093 case PGRES_BAD_RESPONSE:
1094 case PGRES_NONFATAL_ERROR:
1095 case PGRES_FATAL_ERROR:
1096 success = false;
1097 break;
1098
1099 default:
1100 success = false;
1101 pg_log_error("unexpected PQresultStatus: %d",
1102 PQresultStatus(result));
1103 break;
1104 }
1105
1106 return success;
1107 }
1108
1109 /*
1110 * SendQuery: send the query string to the backend
1111 * (and print out result)
1112 *
1113 * Note: This is the "front door" way to send a query. That is, use it to
1114 * send queries actually entered by the user. These queries will be subject to
1115 * single step mode.
1116 * To send "back door" queries (generated by slash commands, etc.) in a
1117 * controlled way, use PSQLexec().
1118 *
1119 * In the most common case, the caller can determine whether the query
1120 * includes any COPY FROM STDIN command(s); if so, pass the count of them.
1121 * Otherwise pass num_copy_from_stdin == -1 and we'll compute it locally.
1122 *
1123 * Returns true if the query executed successfully, false otherwise.
1124 */
1125 bool
1126 SendQuery(const char *query, int num_copy_from_stdin)
1127 {
1128 bool timing = pset.timing;
1129 PGTransactionStatusType transaction_status;
1130 double elapsed_msec = 0;
1131 bool OK = false;
1132 int i;
1133 bool on_error_rollback_savepoint = false;
1134 bool svpt_gone = false;
1135
1136 if (!pset.db)
1137 {
1138 pg_log_error("You are currently not connected to a database.");
1139 goto sendquery_cleanup;
1140 }
1141
1142 if (pset.singlestep)
1143 {
1144 char buf[3];
1145
1146 fflush(stderr);
1147 printf(_("/**(Single step mode: verify command)******************************************/\n"
1148 "%s\n"
1149 "/**(press return to proceed or enter x and return to cancel)*******************/\n"),
1150 query);
1151 fflush(stdout);
1152 if (fgets(buf, sizeof(buf), stdin) != NULL)
1153 if (buf[0] == 'x')
1154 goto sendquery_cleanup;
1155 if (cancel_pressed)
1156 goto sendquery_cleanup;
1157 }
1158 else if (pset.echo == PSQL_ECHO_QUERIES)
1159 {
1160 puts(query);
1161 fflush(stdout);
1162 }
1163
1164 if (pset.logfile)
1165 {
1166 fprintf(pset.logfile,
1167 _("/******** QUERY *********/\n"
1168 "%s\n"
1169 "/************************/\n\n"), query);
1170 fflush(pset.logfile);
1171 }
1172
1173 SetCancelConn(pset.db);
1174
1175 transaction_status = PQtransactionStatus(pset.db);
1176
1177 if (transaction_status == PQTRANS_IDLE &&
1178 !pset.autocommit &&
1179 !command_no_begin(query))
1180 {
1181 PGresult *result;
1182
1183 result = PQexec(pset.db, "BEGIN");
1184 if (PQresultStatus(result) != PGRES_COMMAND_OK)
1185 {
1186 pg_log_info("%s", PQerrorMessage(pset.db));
1187 ClearOrSaveResult(result);
1188 goto sendquery_cleanup;
1189 }
1190 ClearOrSaveResult(result);
1191 transaction_status = PQtransactionStatus(pset.db);
1192 }
1193
1194 if (transaction_status == PQTRANS_INTRANS &&
1195 pset.on_error_rollback != PSQL_ERROR_ROLLBACK_OFF &&
1196 (pset.cur_cmd_interactive ||
1197 pset.on_error_rollback == PSQL_ERROR_ROLLBACK_ON))
1198 {
1199 PGresult *result;
1200
1201 result = PQexec(pset.db, "SAVEPOINT pg_psql_temporary_savepoint");
1202 if (PQresultStatus(result) != PGRES_COMMAND_OK)
1203 {
1204 pg_log_info("%s", PQerrorMessage(pset.db));
1205 ClearOrSaveResult(result);
1206 goto sendquery_cleanup;
1207 }
1208 ClearOrSaveResult(result);
1209 on_error_rollback_savepoint = true;
1210 }
1211
1212 if (pset.gdesc_flag)
1213 {
1214 /* Describe query's result columns, without executing it */
1215 OK = DescribeQuery(query, &elapsed_msec);
1216 }
1217 else
1218 {
1219 /* Default fetch-and-print mode */
1220 OK = (ExecQueryAndProcessResults(query,
1221 &elapsed_msec, &svpt_gone,
1222 num_copy_from_stdin,
1223 false, 0,
1224 NULL, NULL) > 0);
1225 }
1226
1227 if (!OK && pset.echo == PSQL_ECHO_ERRORS)
1228 pg_log_info("STATEMENT: %s", query);
1229
1230 /* If we made a temporary savepoint, possibly release/rollback */
1231 if (on_error_rollback_savepoint)
1232 {
1233 const char *svptcmd = NULL;
1234
1235 transaction_status = PQtransactionStatus(pset.db);
1236
1237 switch (transaction_status)
1238 {
1239 case PQTRANS_INERROR:
1240 /* We always rollback on an error */
1241 svptcmd = "ROLLBACK TO pg_psql_temporary_savepoint";
1242 break;
1243
1244 case PQTRANS_IDLE:
1245 /* If they are no longer in a transaction, then do nothing */
1246 break;
1247
1248 case PQTRANS_INTRANS:
1249
1250 /*
1251 * Release our savepoint, but do nothing if they are messing
1252 * with savepoints themselves
1253 */
1254 if (!svpt_gone)
1255 svptcmd = "RELEASE pg_psql_temporary_savepoint";
1256 break;
1257
1258 case PQTRANS_ACTIVE:
1259 case PQTRANS_UNKNOWN:
1260 default:
1261 OK = false;
1262 /* PQTRANS_UNKNOWN is expected given a broken connection. */
1263 if (transaction_status != PQTRANS_UNKNOWN || ConnectionUp())
1264 pg_log_error("unexpected transaction status (%d)",
1265 transaction_status);
1266 break;
1267 }
1268
1269 if (svptcmd)
1270 {
1271 PGresult *svptres;
1272
1273 svptres = PQexec(pset.db, svptcmd);
1274 if (PQresultStatus(svptres) != PGRES_COMMAND_OK)
1275 {
1276 pg_log_info("%s", PQerrorMessage(pset.db));
1277 ClearOrSaveResult(svptres);
1278 OK = false;
1279
1280 goto sendquery_cleanup;
1281 }
1282 PQclear(svptres);
1283 }
1284 }
1285
1286 /* Possible microtiming output */
1287 if (timing)
1288 PrintTiming(elapsed_msec);
1289
1290 /* check for events that may occur during query execution */
1291
1292 if (pset.encoding != PQclientEncoding(pset.db) &&
1293 PQclientEncoding(pset.db) >= 0)
1294 {
1295 /* track effects of SET CLIENT_ENCODING */
1296 pset.encoding = PQclientEncoding(pset.db);
1297 pset.popt.topt.encoding = pset.encoding;
1298 SetVariable(pset.vars, "ENCODING",
1299 pg_encoding_to_char(pset.encoding));
1300 }
1301
1302 PrintNotifications();
1303
1304 /* perform cleanup that should occur after any attempted query */
1305
1306 sendquery_cleanup:
1307
1308 /* global cancellation reset */
1309 ResetCancelConn();
1310
1311 /* reset \g's output-to-filename trigger */
1312 if (pset.gfname)
1313 {
1314 free(pset.gfname);
1315 pset.gfname = NULL;
1316 }
1317
1318 /* restore print settings if \g changed them */
1319 if (pset.gsavepopt)
1320 {
1321 restorePsetInfo(&pset.popt, pset.gsavepopt);
1322 pset.gsavepopt = NULL;
1323 }
1324
1325 /* clean up after extended protocol queries */
1326 clean_extended_state();
1327
1328 /* reset \gset trigger */
1329 if (pset.gset_prefix)
1330 {
1331 free(pset.gset_prefix);
1332 pset.gset_prefix = NULL;
1333 }
1334
1335 /* reset \gdesc trigger */
1336 pset.gdesc_flag = false;
1337
1338 /* reset \gexec trigger */
1339 pset.gexec_flag = false;
1340
1341 /* reset \crosstabview trigger */
1342 pset.crosstab_flag = false;
1343 for (i = 0; i < lengthof(pset.ctv_args); i++)
1344 {
1345 pg_free(pset.ctv_args[i]);
1346 pset.ctv_args[i] = NULL;
1347 }
1348
1349 return OK;
1350 }
1351
1352
1353 /*
1354 * DescribeQuery: describe the result columns of a query, without executing it
1355 *
1356 * Returns true if the operation executed successfully, false otherwise.
1357 *
1358 * If pset.timing is on, total query time (exclusive of result-printing) is
1359 * stored into *elapsed_msec.
1360 */
1361 static bool
1362 DescribeQuery(const char *query, double *elapsed_msec)
1363 {
1364 bool timing = pset.timing;
1365 PGresult *result;
1366 bool OK;
1367 instr_time before,
1368 after;
1369
1370 *elapsed_msec = 0;
1371
1372 if (timing)
1373 INSTR_TIME_SET_CURRENT(before);
1374 else
1375 INSTR_TIME_SET_ZERO(before);
1376
1377 /*
1378 * To parse the query but not execute it, we prepare it, using the unnamed
1379 * prepared statement. This is invisible to psql users, since there's no
1380 * way to access the unnamed prepared statement from psql user space. The
1381 * next Parse or Query protocol message would overwrite the statement
1382 * anyway. (So there's no great need to clear it when done, which is a
1383 * good thing because libpq provides no easy way to do that.)
1384 */
1385 result = PQprepare(pset.db, "", query, 0, NULL);
1386 if (PQresultStatus(result) != PGRES_COMMAND_OK)
1387 {
1388 pg_log_info("%s", PQerrorMessage(pset.db));
1389 SetResultVariables(result, false);
1390 ClearOrSaveResult(result);
1391 return false;
1392 }
1393 PQclear(result);
1394
1395 result = PQdescribePrepared(pset.db, "");
1396 OK = AcceptResult(result, true) &&
1397 (PQresultStatus(result) == PGRES_COMMAND_OK);
1398 if (OK && result)
1399 {
1400 if (PQnfields(result) > 0)
1401 {
1402 PQExpBufferData buf;
1403 int i;
1404
1405 initPQExpBuffer(&buf);
1406
1407 printfPQExpBuffer(&buf,
1408 "SELECT name AS \"%s\", pg_catalog.format_type(tp, tpm) AS \"%s\"\n"
1409 "FROM (VALUES ",
1410 gettext_noop("Column"),
1411 gettext_noop("Type"));
1412
1413 for (i = 0; i < PQnfields(result); i++)
1414 {
1415 const char *name;
1416 char *escname;
1417
1418 if (i > 0)
1419 appendPQExpBufferChar(&buf, ',');
1420
1421 name = PQfname(result, i);
1422 escname = PQescapeLiteral(pset.db, name, strlen(name));
1423
1424 if (escname == NULL)
1425 {
1426 pg_log_info("%s", PQerrorMessage(pset.db));
1427 PQclear(result);
1428 termPQExpBuffer(&buf);
1429 return false;
1430 }
1431
1432 appendPQExpBuffer(&buf, "(%s, '%u'::pg_catalog.oid, %d)",
1433 escname,
1434 PQftype(result, i),
1435 PQfmod(result, i));
1436
1437 PQfreemem(escname);
1438 }
1439
1440 appendPQExpBufferStr(&buf, ") s(name, tp, tpm)");
1441 PQclear(result);
1442
1443 result = PQexec(pset.db, buf.data);
1444 OK = AcceptResult(result, true);
1445
1446 if (timing)
1447 {
1448 INSTR_TIME_SET_CURRENT(after);
1449 INSTR_TIME_SUBTRACT(after, before);
1450 *elapsed_msec += INSTR_TIME_GET_MILLISEC(after);
1451 }
1452
1453 if (OK && result)
1454 OK = PrintQueryResult(result, true, NULL, NULL, NULL);
1455
1456 termPQExpBuffer(&buf);
1457 }
1458 else
1459 fprintf(pset.queryFout,
1460 _("The command has no result, or the result has no columns.\n"));
1461 }
1462
1463 SetResultVariables(result, OK);
1464 ClearOrSaveResult(result);
1465
1466 return OK;
1467 }
1468
1469 /*
1470 * Read and discard all results in an aborted pipeline.
1471 *
1472 * If a synchronisation point is found, we can stop discarding results as
1473 * the pipeline will switch back to a clean state. If no synchronisation
1474 * point is available, we need to stop when there are no more pending
1475 * results, otherwise, calling PQgetResult() would block.
1476 */
1477 static PGresult *
1478 discardAbortedPipelineResults(void)
1479 {
1480 for (;;)
1481 {
1482 PGresult *res = PQgetResult(pset.db);
1483 ExecStatusType result_status = PQresultStatus(res);
1484
1485 if (result_status == PGRES_PIPELINE_SYNC)
1486 {
1487 /*
1488 * Found a synchronisation point. The sync counter is decremented
1489 * by the caller.
1490 */
1491 return res;
1492 }
1493 else if (res != NULL && result_status == PGRES_FATAL_ERROR)
1494 {
1495 /*
1496 * Found a FATAL error sent by the backend, and we cannot recover
1497 * from this state. Instead, return the last result and let the
1498 * outer loop handle it.
1499 */
1500 PGresult *fatal_res PG_USED_FOR_ASSERTS_ONLY;
1501
1502 /*
1503 * Fetch result to consume the end of the current query being
1504 * processed.
1505 */
1506 fatal_res = PQgetResult(pset.db);
1507 Assert(fatal_res == NULL);
1508 return res;
1509 }
1510 else if (res == NULL)
1511 {
1512 /*
1513 * A query was processed, decrement the counters.
1514 *
1515 * It is possible to get here with available_results == 0 when an
1516 * error is generated by the Sync message processing itself. Such
1517 * errors are not counted in available_results because they are
1518 * not associated with a piped command. In that case, skip the
1519 * counter decrements and continue to find the Sync result.
1520 *
1521 * If the connection has been lost, there will never be any more
1522 * results to read, so bail out.
1523 */
1524 if (!ConnectionUp())
1525 return NULL;
1526 if (pset.available_results > 0)
1527 pset.available_results--;
1528 if (pset.requested_results > 0)
1529 pset.requested_results--;
1530 }
1531
1532 if (pset.requested_results == 0)
1533 {
1534 /* We have read all the requested results, leave */
1535 return res;
1536 }
1537
1538 if (pset.available_results == 0 && pset.piped_syncs == 0)
1539 {
1540 /*
1541 * There are no more results to get and there is no
1542 * synchronisation point to stop at. This will leave the pipeline
1543 * in an aborted state.
1544 */
1545 return res;
1546 }
1547
1548 /*
1549 * An aborted pipeline will have either NULL results or results in an
1550 * PGRES_PIPELINE_ABORTED status.
1551 */
1552 Assert(res == NULL || result_status == PGRES_PIPELINE_ABORTED);
1553 PQclear(res);
1554 }
1555 }
1556
1557 /*
1558 * ExecQueryAndProcessResults: utility function for use by SendQuery()
1559 * and PSQLexecWatch().
1560 *
1561 * Sends query and cycles through PGresult objects.
1562 *
1563 * If our command string contained a COPY FROM STDIN or COPY TO STDOUT, the
1564 * PGresult associated with these commands must be processed by providing an
1565 * input or output stream. In that event, we'll marshal data for the COPY.
1566 *
1567 * For other commands, the results are processed normally, depending on their
1568 * status and the status of a pipeline.
1569 *
1570 * When invoked from \watch, is_watch is true and min_rows is the value
1571 * of that option, or 0 if it wasn't set.
1572 *
1573 * Returns 1 on complete success, 0 on interrupt and -1 or errors. Possible
1574 * failure modes include purely client-side problems; check the transaction
1575 * status for the server-side opinion.
1576 *
1577 * Note that on a combined query, failure does not mean that nothing was
1578 * committed.
1579 */
1580 static int
1581 ExecQueryAndProcessResults(const char *query,
1582 double *elapsed_msec, bool *svpt_gone_p,
1583 int num_copy_from_stdin,
1584 bool is_watch, int min_rows,
1585 const printQueryOpt *opt, FILE *printQueryFout)
1586 {
1587 bool timing = pset.timing;
1588 bool success = false;
1589 bool return_early = false;
1590 bool end_pipeline = false;
1591 instr_time before,
1592 after;
1593 PGresult *result;
1594 FILE *gfile_fout = NULL;
1595 bool gfile_is_pipe = false;
1596
1597 if (timing)
1598 INSTR_TIME_SET_CURRENT(before);
1599 else
1600 INSTR_TIME_SET_ZERO(before);
1601
1602 switch (pset.send_mode)
1603 {
1604 case PSQL_SEND_EXTENDED_CLOSE:
1605 success = PQsendClosePrepared(pset.db, pset.stmtName);
1606 if (success && PQpipelineStatus(pset.db) != PQ_PIPELINE_OFF)
1607 pset.piped_commands++;
1608 break;
1609 case PSQL_SEND_EXTENDED_PARSE:
1610 success = PQsendPrepare(pset.db, pset.stmtName, query, 0, NULL);
1611 if (success && PQpipelineStatus(pset.db) != PQ_PIPELINE_OFF)
1612 pset.piped_commands++;
1613 break;
1614 case PSQL_SEND_EXTENDED_QUERY_PARAMS:
1615 Assert(pset.stmtName == NULL);
1616 success = PQsendQueryParams(pset.db, query,
1617 pset.bind_nparams, NULL,
1618 (const char *const *) pset.bind_params,
1619 NULL, NULL, 0);
1620 if (success && PQpipelineStatus(pset.db) != PQ_PIPELINE_OFF)
1621 pset.piped_commands++;
1622 break;
1623 case PSQL_SEND_EXTENDED_QUERY_PREPARED:
1624 Assert(pset.stmtName != NULL);
1625 success = PQsendQueryPrepared(pset.db, pset.stmtName,
1626 pset.bind_nparams,
1627 (const char *const *) pset.bind_params,
1628 NULL, NULL, 0);
1629 if (success && PQpipelineStatus(pset.db) != PQ_PIPELINE_OFF)
1630 pset.piped_commands++;
1631 break;
1632 case PSQL_SEND_START_PIPELINE_MODE:
1633 success = PQenterPipelineMode(pset.db);
1634 break;
1635 case PSQL_SEND_END_PIPELINE_MODE:
1636 success = PQpipelineSync(pset.db);
1637 if (success && PQpipelineStatus(pset.db) != PQ_PIPELINE_OFF)
1638 {
1639 /*
1640 * End of the pipeline, all queued commands need to be
1641 * processed.
1642 */
1643 end_pipeline = true;
1644 pset.piped_syncs++;
1645
1646 /*
1647 * The server will send a ReadyForQuery after a Sync is
1648 * processed, flushing all the results back to the client.
1649 */
1650 pset.available_results += pset.piped_commands;
1651 pset.piped_commands = 0;
1652
1653 /* We want to read all results */
1654 pset.requested_results = pset.available_results + pset.piped_syncs;
1655 }
1656 break;
1657 case PSQL_SEND_PIPELINE_SYNC:
1658 success = PQsendPipelineSync(pset.db);
1659 if (success && PQpipelineStatus(pset.db) != PQ_PIPELINE_OFF)
1660 {
1661 pset.piped_syncs++;
1662
1663 /*
1664 * The server will send a ReadyForQuery after a Sync is
1665 * processed, flushing all the results back to the client.
1666 */
1667 pset.available_results += pset.piped_commands;
1668 pset.piped_commands = 0;
1669 }
1670 break;
1671 case PSQL_SEND_FLUSH:
1672 success = PQflush(pset.db);
1673 break;
1674 case PSQL_SEND_FLUSH_REQUEST:
1675 success = PQsendFlushRequest(pset.db);
1676 if (success && PQpipelineStatus(pset.db) != PQ_PIPELINE_OFF)
1677 {
1678 /*
1679 * With the flush request, all commands in the pipeline are
1680 * pushed and the server will flush the results back to the
1681 * client, making them available.
1682 */
1683 pset.available_results += pset.piped_commands;
1684 pset.piped_commands = 0;
1685 }
1686 break;
1687 case PSQL_SEND_GET_RESULTS:
1688 if (pset.available_results == 0 && pset.piped_syncs == 0)
1689 {
1690 /*
1691 * If no sync or flush request were sent, PQgetResult() would
1692 * block as there are no results available. Forbid any
1693 * attempt to get pending results should we try to reach this
1694 * state.
1695 */
1696 pg_log_info("No pending results to get");
1697 success = false;
1698 pset.requested_results = 0;
1699 }
1700 else
1701 {
1702 success = true;
1703
1704 /*
1705 * Cap requested_results to the maximum number of known
1706 * results.
1707 */
1708 if (pset.requested_results == 0 ||
1709 pset.requested_results > (pset.available_results + pset.piped_syncs))
1710 pset.requested_results = pset.available_results + pset.piped_syncs;
1711 }
1712 break;
1713 case PSQL_SEND_QUERY:
1714 if (PQpipelineStatus(pset.db) != PQ_PIPELINE_OFF)
1715 {
1716 success = PQsendQueryParams(pset.db, query,
1717 0, NULL, NULL, NULL, NULL, 0);
1718 if (success)
1719 pset.piped_commands++;
1720 }
1721 else
1722 success = PQsendQuery(pset.db, query);
1723 break;
1724 }
1725
1726 if (!success)
1727 {
1728 const char *error = PQerrorMessage(pset.db);
1729
1730 if (strlen(error))
1731 pg_log_info("%s", error);
1732
1733 CheckConnection();
1734
1735 SetPipelineVariables();
1736
1737 return -1;
1738 }
1739
1740 if (pset.requested_results == 0 && !end_pipeline &&
1741 PQpipelineStatus(pset.db) != PQ_PIPELINE_OFF)
1742 {
1743 /*
1744 * We are in a pipeline and have not reached the pipeline end, or
1745 * there was no request to read pipeline results. Update the psql
1746 * variables tracking the pipeline activity and exit.
1747 */
1748 SetPipelineVariables();
1749 return 1;
1750 }
1751
1752 /*
1753 * Fetch the result in chunks if FETCH_COUNT is set, except when:
1754 *
1755 * * SHOW_ALL_RESULTS is false, since that requires us to complete the
1756 * query before we can tell if its results should be displayed.
1757 *
1758 * * We're doing \crosstab, which likewise needs to see all the rows at
1759 * once.
1760 *
1761 * * We're doing \gexec: we must complete the data fetch to make the
1762 * connection free for issuing the resulting commands.
1763 *
1764 * * We're doing \gset: only one result row is allowed anyway.
1765 *
1766 * * We're doing \watch: users probably don't want us to force use of the
1767 * pager for that, plus chunking could break the min_rows check.
1768 */
1769 if (pset.fetch_count > 0 && pset.show_all_results &&
1770 !pset.crosstab_flag && !pset.gexec_flag &&
1771 !pset.gset_prefix && !is_watch)
1772 {
1773 if (!PQsetChunkedRowsMode(pset.db, pset.fetch_count))
1774 pg_log_warning("fetching results in chunked mode failed");
1775 }
1776
1777 /*
1778 * If SIGINT is sent while the query is processing, the interrupt will be
1779 * consumed. The user's intention, though, is to cancel the entire watch
1780 * process, so detect a sent cancellation request and exit in this case.
1781 */
1782 if (is_watch && cancel_pressed)
1783 {
1784 ClearOrSaveAllResults();
1785 return 0;
1786 }
1787
1788 /*
1789 * If the caller didn't count the number of COPY FROM STDIN command(s) in
1790 * the query string, we must do so now.
1791 */
1792 if (num_copy_from_stdin < 0)
1793 {
1794 PsqlScanState scan_state;
1795 PQExpBuffer query_buf;
1796 promptStatus_t prompt_tmp;
1797 PsqlScanResult scan_result;
1798
•1799 scan_state = psql_scan_create(&psqlscan_callbacks);
1800 psql_scan_setup(scan_state, query, strlen(query),
1801 pset.encoding, standard_strings());
1802 query_buf = createPQExpBuffer();
1803
1804 /*
1805 * A semicolon ends only one sub-command; keep scanning so that COPY
•1806 * FROM STDIN commands past the first semicolon are counted too. The
1807 * count accumulates in scan_state across the psql_scan() calls.
1808 *
1809 * The scan stops early if it hits a backslash command, leaving the
1810 * rest of the string uncounted. That's fine: backslash commands are
1811 * not supported in query strings sent through this path, so the
1812 * server will fail to parse such a string before any COPY data
1813 * transfer can start.
1814 */
1815 do
1816 {
1817 scan_result = psql_scan(scan_state, query_buf, &prompt_tmp);
1818 } while (scan_result == PSCAN_SEMICOLON);
1819
1820 num_copy_from_stdin = psql_scan_count_copy_from_stdin(scan_state);
1821
1822 destroyPQExpBuffer(query_buf);
1823 psql_scan_destroy(scan_state);
1824 }
1825
1826 /* first result */
1827 result = PQgetResult(pset.db);
1828 if (min_rows > 0 && PQntuples(result) < min_rows)
1829 {
1830 return_early = true;
1831 }
1832
1833 while (result != NULL)
1834 {
1835 ExecStatusType result_status;
1836 bool is_chunked_result = false;
1837 PGresult *next_result = NULL;
1838 bool last;
1839
1840 if (!AcceptResult(result, false))
1841 {
1842 /*
1843 * Some error occurred, either a server-side failure or a failure
1844 * to submit the command string. Record that.
1845 */
1846 const char *error = PQresultErrorMessage(result);
1847
1848 if (strlen(error))
1849 pg_log_info("%s", error);
1850
1851 CheckConnection();
1852 if (!is_watch)
1853 SetResultVariables(result, false);
1854
1855 /* keep the result status before clearing it */
1856 result_status = PQresultStatus(result);
1857 ClearOrSaveResult(result);
1858 success = false;
1859
1860 if (result_status == PGRES_PIPELINE_ABORTED)
1861 pg_log_info("Pipeline aborted, command did not run");
1862
1863 /*
1864 * switch to next result
1865 */
1866 if (result_status == PGRES_COPY_BOTH ||
1867 result_status == PGRES_COPY_OUT ||
1868 result_status == PGRES_COPY_IN)
1869 {
1870 /*
1871 * For some obscure reason PQgetResult does *not* return a
1872 * NULL in copy cases despite the result having been cleared,
1873 * but keeps returning an "empty" result that we have to
1874 * ignore manually.
1875 */
1876 result = NULL;
1877 }
1878 else if ((end_pipeline || pset.requested_results > 0)
1879 && PQpipelineStatus(pset.db) != PQ_PIPELINE_OFF)
1880 {
1881 /*
1882 * Error within a pipeline. All commands are aborted until
1883 * the next synchronisation point. We need to consume all the
1884 * results until this synchronisation point, or stop when
1885 * there are no more result to discard.
1886 *
1887 * Checking the pipeline status is necessary for the case
1888 * where the connection was reset. The new connection is not
1889 * in any kind of pipeline state and thus has no result to
1890 * discard.
1891 */
1892 result = discardAbortedPipelineResults();
1893 }
1894 else
1895 result = PQgetResult(pset.db);
1896
1897 /*
1898 * Get current timing measure in case an error occurs
1899 */
1900 if (timing)
1901 {
1902 INSTR_TIME_SET_CURRENT(after);
1903 INSTR_TIME_SUBTRACT(after, before);
1904 *elapsed_msec = INSTR_TIME_GET_MILLISEC(after);
1905 }
1906
1907 continue;
1908 }
1909 else if (svpt_gone_p && !*svpt_gone_p)
1910 {
1911 /*
1912 * Check if the user ran any command that would destroy our
1913 * internal savepoint: If the user did COMMIT AND CHAIN, RELEASE
1914 * or ROLLBACK, our savepoint is gone. If they issued a SAVEPOINT,
1915 * releasing ours would remove theirs.
1916 */
1917 const char *cmd = PQcmdStatus(result);
1918
1919 *svpt_gone_p = (strcmp(cmd, "COMMIT") == 0 ||
1920 strcmp(cmd, "SAVEPOINT") == 0 ||
1921 strcmp(cmd, "RELEASE") == 0 ||
1922 strcmp(cmd, "ROLLBACK") == 0);
1923 }
1924
1925 result_status = PQresultStatus(result);
1926
1927 /* must handle COPY before changing the current result */
1928 Assert(result_status != PGRES_COPY_BOTH);
1929 if (result_status == PGRES_COPY_IN ||
1930 result_status == PGRES_COPY_OUT)
1931 {
1932 FILE *copy_stream = NULL;
1933
1934 if (PQpipelineStatus(pset.db) != PQ_PIPELINE_OFF)
1935 {
1936 /*
1937 * Running COPY within a pipeline can break the protocol
1938 * synchronisation in multiple ways, and psql shows its limits
1939 * when it comes to tracking this information.
1940 *
1941 * While in COPY mode, the backend process ignores additional
1942 * Sync messages and will not send the matching ReadyForQuery
1943 * expected by the frontend.
1944 *
1945 * Additionally, libpq automatically sends a Sync with the
1946 * Copy message, creating an unexpected synchronisation point.
1947 * A failure during COPY would leave the pipeline in an
1948 * aborted state while the backend would be in a clean state,
1949 * ready to process commands.
1950 *
1951 * Improving those issues would require modifications in how
1952 * libpq handles pipelines and COPY. Hence, for the time
1953 * being, we forbid the use of COPY within a pipeline,
1954 * aborting the connection to avoid an inconsistent state on
1955 * psql side if trying to use a COPY command.
1956 */
1957 pg_log_info("COPY in a pipeline is not supported, aborting connection");
1958 exit(EXIT_BADCONN);
1959 }
1960
1961 /* Select data source or sink. */
1962 if (result_status == PGRES_COPY_OUT)
1963 {
1964 /*
1965 * For COPY OUT, direct the output to the default place
1966 * (probably a pager pipe) for \watch, or to pset.copyStream
1967 * for \copy, otherwise to pset.gfname if that's set,
1968 * otherwise to pset.queryFout.
1969 */
1970 if (is_watch)
1971 {
1972 /* invoked by \watch */
1973 copy_stream = printQueryFout ? printQueryFout : pset.queryFout;
1974 }
1975 else if (pset.copyStream)
1976 {
1977 /* invoked by \copy */
1978 copy_stream = pset.copyStream;
1979 }
1980 else if (pset.gfname)
1981 {
1982 /* COPY followed by \g filename or \g |program */
1983 success &= SetupGOutput(&gfile_fout, &gfile_is_pipe);
1984 if (gfile_fout)
1985 copy_stream = gfile_fout;
1986 }
1987 else
1988 {
1989 /* fall back to the generic query output stream */
1990 copy_stream = pset.queryFout;
1991 }
1992 }
1993 else
1994 {
1995 if (num_copy_from_stdin <= 0)
1996 {
1997 /*
1998 * We didn't send a COPY FROM STDIN command. The server
1999 * is broken or possibly malicious. Report and quit. (We
2000 * could instead send an empty COPY response, but it's not
2001 * clear that that's a better behavior; it would make it
2002 * harder to diagnose any such problem.)
2003 */
2004 pg_log_info("unexpected COPY_IN result, aborting connection");
2005 exit(EXIT_BADCONN);
2006 }
2007 /* Keep track of the number of remaining copy operations */
2008 num_copy_from_stdin--;
2009
2010 /*
2011 * For COPY IN, read from pset.copyStream if \copy set that,
2012 * otherwise from the current command source.
2013 */
2014 if (pset.copyStream)
2015 copy_stream = pset.copyStream;
2016 else
2017 copy_stream = pset.cur_cmd_source;
2018 }
2019
2020 /*
2021 * Even if the output stream could not be opened, we call
2022 * HandleCopyResult() with a NULL output stream to collect and
2023 * discard the COPY data.
2024 */
2025 success &= HandleCopyResult(&result, copy_stream);
2026 }
2027
2028 /* If we have a chunked result, collect and print all chunks */
2029 if (result_status == PGRES_TUPLES_CHUNK)
2030 {
2031 FILE *tuples_fout = printQueryFout ? printQueryFout : pset.queryFout;
2032 printQueryOpt my_popt = opt ? *opt : pset.popt;
2033 int64 total_tuples = 0;
2034 bool is_pager = false;
2035 int flush_error = 0;
2036
2037 /* initialize print options for partial table output */
2038 my_popt.topt.start_table = true;
2039 my_popt.topt.stop_table = false;
2040 my_popt.topt.prior_records = 0;
2041
2042 /* open \g file if needed */
2043 success &= SetupGOutput(&gfile_fout, &gfile_is_pipe);
2044 if (gfile_fout)
2045 tuples_fout = gfile_fout;
2046
2047 /* force use of pager for any chunked resultset going to stdout */
2048 if (success && tuples_fout == stdout)
2049 {
2050 tuples_fout = PageOutput(INT_MAX, &(my_popt.topt));
2051 is_pager = true;
2052 }
2053
2054 do
2055 {
2056 /*
2057 * Display the current chunk of results, unless the output
2058 * stream stopped working or we got canceled. We skip use of
2059 * PrintQueryResult and go directly to printQuery, so that we
2060 * can pass the correct is_pager value and because we don't
2061 * want PrintQueryStatus to happen yet. Above, we rejected
2062 * use of chunking for all cases in which PrintQueryResult
2063 * would send the result to someplace other than printQuery.
2064 */
2065 if (success && !flush_error && !cancel_pressed)
2066 {
2067 printQuery(result, &my_popt, tuples_fout, is_pager, pset.logfile);
2068 flush_error = fflush(tuples_fout);
2069 }
2070
2071 /* after the first result set, disallow header decoration */
2072 my_popt.topt.start_table = false;
2073
2074 /* count tuples before dropping the result */
2075 my_popt.topt.prior_records += PQntuples(result);
2076 total_tuples += PQntuples(result);
2077
2078 ClearOrSaveResult(result);
2079
2080 /* get the next result, loop if it's PGRES_TUPLES_CHUNK */
2081 result = PQgetResult(pset.db);
2082 } while (PQresultStatus(result) == PGRES_TUPLES_CHUNK);
2083
2084 /* We expect an empty PGRES_TUPLES_OK, else there's a problem */
2085 if (PQresultStatus(result) == PGRES_TUPLES_OK)
2086 {
2087 char buf[32];
2088
2089 Assert(PQntuples(result) == 0);
2090
2091 /* Display the footer using the empty result */
2092 if (success && !flush_error && !cancel_pressed)
2093 {
2094 my_popt.topt.stop_table = true;
2095 printQuery(result, &my_popt, tuples_fout, is_pager, pset.logfile);
2096 fflush(tuples_fout);
2097 }
2098
2099 if (is_pager)
2100 ClosePager(tuples_fout);
2101
2102 /*
2103 * It's possible the data is from a RETURNING clause, in which
2104 * case we need to print query status.
2105 */
2106 PrintQueryStatus(result, printQueryFout);
2107
2108 /*
2109 * We must do a fake SetResultVariables(), since we don't have
2110 * a PGresult corresponding to the whole query.
2111 */
2112 SetVariable(pset.vars, "ERROR", "false");
2113 SetVariable(pset.vars, "SQLSTATE", "00000");
2114 snprintf(buf, sizeof(buf), INT64_FORMAT, total_tuples);
2115 SetVariable(pset.vars, "ROW_COUNT", buf);
2116 /* Prevent SetResultVariables call below */
2117 is_chunked_result = true;
2118
2119 /* Clear the empty result so it isn't printed below */
2120 ClearOrSaveResult(result);
2121 result = NULL;
2122 }
2123 else
2124 {
2125 /* Probably an error report, so close the pager and print it */
2126 if (is_pager)
2127 ClosePager(tuples_fout);
2128
2129 success &= AcceptResult(result, true);
2130 /* SetResultVariables and ClearOrSaveResult happen below */
2131 }
2132 }
2133
2134 if (result_status == PGRES_PIPELINE_SYNC)
2135 {
2136 /*
2137 * Sync response, decrease the sync and requested_results
2138 * counters. Guard against underflow: an error during Sync
2139 * processing on the server can cause the client-side counter to
2140 * drift.
2141 */
2142 if (pset.piped_syncs > 0)
2143 pset.piped_syncs--;
2144 if (pset.requested_results > 0)
2145 pset.requested_results--;
2146
2147 /*
2148 * After a synchronisation point, reset success state to print
2149 * possible successful results that will be processed after this.
2150 */
2151 success = true;
2152
2153 /*
2154 * If all syncs were processed and pipeline end was requested,
2155 * exit pipeline mode.
2156 */
2157 if (end_pipeline && pset.piped_syncs == 0)
2158 success &= PQexitPipelineMode(pset.db);
2159 }
2160 else if (PQpipelineStatus(pset.db) != PQ_PIPELINE_OFF &&
2161 result_status != PGRES_PIPELINE_SYNC)
2162 {
2163 /*
2164 * In a pipeline with a non-sync response? Decrease the result
2165 * counters.
2166 */
2167 if (pset.available_results > 0)
2168 pset.available_results--;
2169 if (pset.requested_results > 0)
2170 pset.requested_results--;
2171 }
2172
2173 /*
2174 * Check PQgetResult() again. In the typical case of a single-command
2175 * string, it will return NULL. Otherwise, we'll have other results
2176 * to process. We need to do that to check whether this is the last.
2177 */
2178 if (PQpipelineStatus(pset.db) == PQ_PIPELINE_OFF)
2179 next_result = PQgetResult(pset.db);
2180 else
2181 {
2182 /*
2183 * In pipeline mode, a NULL result indicates the end of the
2184 * current query being processed. Call PQgetResult() once to
2185 * consume this state.
2186 */
2187 if (result_status != PGRES_PIPELINE_SYNC)
2188 {
2189 next_result = PQgetResult(pset.db);
2190 Assert(next_result == NULL);
2191 }
2192
2193 /* Now, we can get the next result in the pipeline. */
2194 if (pset.requested_results > 0)
2195 next_result = PQgetResult(pset.db);
2196 }
2197
2198 last = (next_result == NULL);
2199
2200 /*
2201 * Update current timing measure.
2202 *
2203 * It will include the display of previous results, if any. This
2204 * cannot be helped because the server goes on processing further
2205 * queries anyway while the previous ones are being displayed. The
2206 * parallel execution of the client display hides the server time when
2207 * it is shorter.
2208 *
2209 * With combined queries, timing must be understood as an upper bound
2210 * of the time spent processing them.
2211 */
2212 if (timing)
2213 {
2214 INSTR_TIME_SET_CURRENT(after);
2215 INSTR_TIME_SUBTRACT(after, before);
2216 *elapsed_msec = INSTR_TIME_GET_MILLISEC(after);
2217 }
2218
2219 /*
2220 * This may or may not print something depending on settings.
2221 *
2222 * A pipeline sync will have a non-NULL result but does not have
2223 * anything to print, thus ignore results in this case.
2224 */
2225 if (result != NULL && result_status != PGRES_PIPELINE_SYNC)
2226 {
2227 /*
2228 * If results need to be printed into the file specified by \g,
2229 * open it, unless we already did. Note that when pset.gfname is
2230 * set, the passed-in value of printQueryFout is not used for
2231 * tuple output, but it's still used for status output.
2232 */
2233 FILE *tuples_fout = printQueryFout;
2234
2235 if (PQresultStatus(result) == PGRES_TUPLES_OK)
2236 success &= SetupGOutput(&gfile_fout, &gfile_is_pipe);
2237 if (gfile_fout)
2238 tuples_fout = gfile_fout;
2239 if (success)
2240 success &= PrintQueryResult(result, last, opt,
2241 tuples_fout, printQueryFout);
2242 }
2243
2244 /* set variables from last result, unless dealt with elsewhere */
2245 if (last && !is_watch && !is_chunked_result)
2246 SetResultVariables(result, success);
2247
2248 ClearOrSaveResult(result);
2249 result = next_result;
2250
2251 if (cancel_pressed && PQpipelineStatus(pset.db) == PQ_PIPELINE_OFF)
2252 {
2253 /*
2254 * Outside of a pipeline, drop the next result, as well as any
2255 * others not yet read.
2256 *
2257 * Within a pipeline, we can let the outer loop handle this as an
2258 * aborted pipeline, which will discard then all the results.
2259 */
2260 ClearOrSaveResult(result);
2261 ClearOrSaveAllResults();
2262 break;
2263 }
2264 }
2265
2266 /* close \g file if we opened it */
2267 CloseGOutput(gfile_fout, gfile_is_pipe);
2268
2269 if (end_pipeline)
2270 {
2271 /*
2272 * Reset available/requested results. Normally these are already 0,
2273 * but an error generated by a Sync processing itself can leave some
2274 * of them behind. Consume them before exiting pipeline mode.
2275 */
2276 while (pset.piped_syncs > 0)
2277 {
2278 PGresult *remaining;
2279
2280 remaining = PQgetResult(pset.db);
2281
2282 if (remaining == NULL)
2283 {
2284 if (!ConnectionUp())
2285 break;
2286 continue;
2287 }
2288 if (PQresultStatus(remaining) == PGRES_PIPELINE_SYNC)
2289 pset.piped_syncs--;
2290 PQclear(remaining);
2291 }
2292 pset.piped_syncs = 0;
2293 pset.piped_commands = 0;
2294 pset.available_results = 0;
2295 pset.requested_results = 0;
2296
2297 if (PQpipelineStatus(pset.db) != PQ_PIPELINE_OFF)
2298 PQexitPipelineMode(pset.db);
2299 }
2300 Assert(pset.requested_results == 0);
2301
2302 SetPipelineVariables();
2303
2304 /* may need this to recover from conn loss during COPY */
2305 if (!CheckConnection())
2306 return -1;
2307
2308 /*
2309 * If we were expecting COPY ... FROM STDIN, and we didn't get
2310 * PGRES_COPY_IN (presumably because the COPY failed server-side), and the
2311 * data is supposed to come from the current command source, we must eat
2312 * up the data in order to stay in sync with the command file's contents.
2313 * Repeat for the number of unfulfilled COPY commands.
2314 */
2315 while (num_copy_from_stdin > 0)
2316 {
2317 if (pset.copyStream == NULL ||
2318 pset.copyStream == pset.cur_cmd_source)
2319 (void) handleCopyIn(NULL, /* no connection */
2320 pset.cur_cmd_source,
2321 false, /* XXX assume not binary */
2322 NULL); /* no result */
2323 num_copy_from_stdin--;
2324 }
2325
2326 if (cancel_pressed || return_early)
2327 return 0;
2328
2329 return success ? 1 : -1;
2330 }
2331
2332
2333 /*
2334 * Advance the given char pointer over white space and SQL comments.
2335 */
2336 static const char *
2337 skip_white_space(const char *query)
2338 {
2339 int cnestlevel = 0; /* slash-star comment nest level */
2340
2341 while (*query)
2342 {
2343 int mblen = PQmblenBounded(query, pset.encoding);
2344
2345 /*
2346 * Note: we assume the encoding is a superset of ASCII, so that for
2347 * example "query[0] == '/'" is meaningful. However, we do NOT assume
2348 * that the second and subsequent bytes of a multibyte character
2349 * couldn't look like ASCII characters; so it is critical to advance
2350 * by mblen, not 1, whenever we haven't exactly identified the
2351 * character we are skipping over.
2352 */
2353 if (isspace((unsigned char) *query))
2354 query += mblen;
2355 else if (query[0] == '/' && query[1] == '*')
2356 {
2357 cnestlevel++;
2358 query += 2;
2359 }
2360 else if (cnestlevel > 0 && query[0] == '*' && query[1] == '/')
2361 {
2362 cnestlevel--;
2363 query += 2;
2364 }
2365 else if (cnestlevel == 0 && query[0] == '-' && query[1] == '-')
2366 {
2367 query += 2;
2368
2369 /*
2370 * We have to skip to end of line since any slash-star inside the
2371 * -- comment does NOT start a slash-star comment.
2372 */
2373 while (*query)
2374 {
2375 if (*query == '\n')
2376 {
2377 query++;
2378 break;
2379 }
2380 query += PQmblenBounded(query, pset.encoding);
2381 }
2382 }
2383 else if (cnestlevel > 0)
2384 query += mblen;
2385 else
2386 break; /* found first token */
2387 }
2388
2389 return query;
2390 }
2391
2392
2393 /*
2394 * Check whether a command is one of those for which we should NOT start
2395 * a new transaction block (ie, send a preceding BEGIN).
2396 *
2397 * These include the transaction control statements themselves, plus
2398 * certain statements that the backend disallows inside transaction blocks.
2399 */
2400 static bool
2401 command_no_begin(const char *query)
2402 {
2403 int wordlen;
2404
2405 /*
2406 * First we must advance over any whitespace and comments.
2407 */
2408 query = skip_white_space(query);
2409
2410 /*
2411 * Check word length (since "beginx" is not "begin").
2412 */
2413 wordlen = 0;
2414 while (isalpha((unsigned char) query[wordlen]))
2415 wordlen += PQmblenBounded(&query[wordlen], pset.encoding);
2416
2417 /*
2418 * Transaction control commands. These should include every keyword that
2419 * gives rise to a TransactionStmt in the backend grammar, except for the
2420 * savepoint-related commands.
2421 *
2422 * (We assume that START must be START TRANSACTION, since there is
2423 * presently no other "START foo" command.)
2424 */
2425 if (wordlen == 5 && pg_strncasecmp(query, "abort", 5) == 0)
2426 return true;
2427 if (wordlen == 5 && pg_strncasecmp(query, "begin", 5) == 0)
2428 return true;
2429 if (wordlen == 5 && pg_strncasecmp(query, "start", 5) == 0)
2430 return true;
2431 if (wordlen == 6 && pg_strncasecmp(query, "commit", 6) == 0)
2432 return true;
2433 if (wordlen == 3 && pg_strncasecmp(query, "end", 3) == 0)
2434 return true;
2435 if (wordlen == 8 && pg_strncasecmp(query, "rollback", 8) == 0)
2436 return true;
2437 if (wordlen == 7 && pg_strncasecmp(query, "prepare", 7) == 0)
2438 {
2439 /* PREPARE TRANSACTION is a TC command, PREPARE foo is not */
2440 query += wordlen;
2441
2442 query = skip_white_space(query);
2443
2444 wordlen = 0;
2445 while (isalpha((unsigned char) query[wordlen]))
2446 wordlen += PQmblenBounded(&query[wordlen], pset.encoding);
2447
2448 if (wordlen == 11 && pg_strncasecmp(query, "transaction", 11) == 0)
2449 return true;
2450 return false;
2451 }
2452
2453 /*
2454 * Commands not allowed within transactions. The statements checked for
2455 * here should be exactly those that call PreventInTransactionBlock() in
2456 * the backend.
2457 */
2458 if (wordlen == 6 && pg_strncasecmp(query, "vacuum", 6) == 0)
2459 return true;
2460 if (wordlen == 7 && pg_strncasecmp(query, "cluster", 7) == 0)
2461 {
2462 /* CLUSTER with any arguments is allowed in transactions */
2463 query += wordlen;
2464
2465 query = skip_white_space(query);
2466
2467 if (isalpha((unsigned char) query[0]))
2468 return false; /* has additional words */
2469 return true; /* it's CLUSTER without arguments */
2470 }
2471
2472 if (wordlen == 6 && pg_strncasecmp(query, "create", 6) == 0)
2473 {
2474 query += wordlen;
2475
2476 query = skip_white_space(query);
2477
2478 wordlen = 0;
2479 while (isalpha((unsigned char) query[wordlen]))
2480 wordlen += PQmblenBounded(&query[wordlen], pset.encoding);
2481
2482 if (wordlen == 8 && pg_strncasecmp(query, "database", 8) == 0)
2483 return true;
2484 if (wordlen == 10 && pg_strncasecmp(query, "tablespace", 10) == 0)
2485 return true;
2486
2487 /* CREATE [UNIQUE] INDEX CONCURRENTLY isn't allowed in xacts */
2488 if (wordlen == 6 && pg_strncasecmp(query, "unique", 6) == 0)
2489 {
2490 query += wordlen;
2491
2492 query = skip_white_space(query);
2493
2494 wordlen = 0;
2495 while (isalpha((unsigned char) query[wordlen]))
2496 wordlen += PQmblenBounded(&query[wordlen], pset.encoding);
2497 }
2498
2499 if (wordlen == 5 && pg_strncasecmp(query, "index", 5) == 0)
2500 {
2501 query += wordlen;
2502
2503 query = skip_white_space(query);
2504
2505 wordlen = 0;
2506 while (isalpha((unsigned char) query[wordlen]))
2507 wordlen += PQmblenBounded(&query[wordlen], pset.encoding);
2508
2509 if (wordlen == 12 && pg_strncasecmp(query, "concurrently", 12) == 0)
2510 return true;
2511 }
2512
2513 return false;
2514 }
2515
2516 if (wordlen == 5 && pg_strncasecmp(query, "alter", 5) == 0)
2517 {
2518 query += wordlen;
2519
2520 query = skip_white_space(query);
2521
2522 wordlen = 0;
2523 while (isalpha((unsigned char) query[wordlen]))
2524 wordlen += PQmblenBounded(&query[wordlen], pset.encoding);
2525
2526 /* ALTER SYSTEM isn't allowed in xacts */
2527 if (wordlen == 6 && pg_strncasecmp(query, "system", 6) == 0)
2528 return true;
2529
2530 return false;
2531 }
2532
2533 /*
2534 * Note: these tests will match DROP SYSTEM and REINDEX TABLESPACE, which
2535 * aren't really valid commands so we don't care much. The other four
2536 * possible matches are correct.
2537 */
2538 if ((wordlen == 4 && pg_strncasecmp(query, "drop", 4) == 0) ||
2539 (wordlen == 7 && pg_strncasecmp(query, "reindex", 7) == 0))
2540 {
2541 query += wordlen;
2542
2543 query = skip_white_space(query);
2544
2545 wordlen = 0;
2546 while (isalpha((unsigned char) query[wordlen]))
2547 wordlen += PQmblenBounded(&query[wordlen], pset.encoding);
2548
2549 if (wordlen == 8 && pg_strncasecmp(query, "database", 8) == 0)
2550 return true;
2551 if (wordlen == 6 && pg_strncasecmp(query, "system", 6) == 0)
2552 return true;
2553 if (wordlen == 10 && pg_strncasecmp(query, "tablespace", 10) == 0)
2554 return true;
2555 if (wordlen == 5 && (pg_strncasecmp(query, "index", 5) == 0 ||
2556 pg_strncasecmp(query, "table", 5) == 0))
2557 {
2558 query += wordlen;
2559 query = skip_white_space(query);
2560 wordlen = 0;
2561 while (isalpha((unsigned char) query[wordlen]))
2562 wordlen += PQmblenBounded(&query[wordlen], pset.encoding);
2563
2564 /*
2565 * REINDEX [ TABLE | INDEX ] CONCURRENTLY are not allowed in
2566 * xacts.
2567 */
2568 if (wordlen == 12 && pg_strncasecmp(query, "concurrently", 12) == 0)
2569 return true;
2570 }
2571
2572 /* DROP INDEX CONCURRENTLY isn't allowed in xacts */
2573 if (wordlen == 5 && pg_strncasecmp(query, "index", 5) == 0)
2574 {
2575 query += wordlen;
2576
2577 query = skip_white_space(query);
2578
2579 wordlen = 0;
2580 while (isalpha((unsigned char) query[wordlen]))
2581 wordlen += PQmblenBounded(&query[wordlen], pset.encoding);
2582
2583 if (wordlen == 12 && pg_strncasecmp(query, "concurrently", 12) == 0)
2584 return true;
2585
2586 return false;
2587 }
2588
2589 return false;
2590 }
2591
2592 /* DISCARD ALL isn't allowed in xacts, but other variants are allowed. */
2593 if (wordlen == 7 && pg_strncasecmp(query, "discard", 7) == 0)
2594 {
2595 query += wordlen;
2596
2597 query = skip_white_space(query);
2598
2599 wordlen = 0;
2600 while (isalpha((unsigned char) query[wordlen]))
2601 wordlen += PQmblenBounded(&query[wordlen], pset.encoding);
2602
2603 if (wordlen == 3 && pg_strncasecmp(query, "all", 3) == 0)
2604 return true;
2605 return false;
2606 }
2607
2608 return false;
2609 }
2610
2611
2612 /*
2613 * Test if the current user is a database superuser.
2614 */
2615 bool
2616 is_superuser(void)
2617 {
2618 const char *val;
2619
2620 if (!pset.db)
2621 return false;
2622
2623 val = PQparameterStatus(pset.db, "is_superuser");
2624
2625 if (val && strcmp(val, "on") == 0)
2626 return true;
2627
2628 return false;
2629 }
2630
2631
2632 /*
2633 * Test if the current session uses standard string literals.
2634 */
2635 bool
2636 standard_strings(void)
2637 {
2638 const char *val;
2639
2640 if (!pset.db)
2641 return false;
2642
2643 val = PQparameterStatus(pset.db, "standard_conforming_strings");
2644
2645 if (val && strcmp(val, "on") == 0)
2646 return true;
2647
2648 return false;
2649 }
2650
2651
2652 /*
2653 * Return the session user of the current connection.
2654 */
2655 const char *
2656 session_username(void)
2657 {
2658 const char *val;
2659
2660 if (!pset.db)
2661 return NULL;
2662
2663 val = PQparameterStatus(pset.db, "session_authorization");
2664 if (val)
2665 return val;
2666 else
2667 return PQuser(pset.db);
2668 }
2669
2670 /*
2671 * Return the value of option for keyword in the current connection.
2672 *
2673 * The caller is responsible for freeing the result value allocated.
2674 */
2675 char *
2676 get_conninfo_value(const char *keyword)
2677 {
2678 PQconninfoOption *opts;
2679 PQconninfoOption *serviceopt = NULL;
2680 char *res = NULL;
2681
2682 if (pset.db == NULL)
2683 return NULL;
2684
2685 opts = PQconninfo(pset.db);
2686 if (opts == NULL)
2687 return NULL;
2688
2689 for (PQconninfoOption *opt = opts; opt->keyword != NULL; ++opt)
2690 {
2691 if (strcmp(opt->keyword, keyword) == 0)
2692 {
2693 serviceopt = opt;
2694 break;
2695 }
2696 }
2697
2698 /* Take a copy of the value, as it is freed by PQconninfoFree(). */
2699 if (serviceopt && serviceopt->val != NULL)
2700 res = pg_strdup(serviceopt->val);
2701 PQconninfoFree(opts);
2702
2703 return res;
2704 }
2705
2706 /* expand_tilde
2707 *
2708 * substitute '~' with HOME or '~username' with username's home dir
2709 *
2710 */
2711 void
2712 expand_tilde(char **filename)
2713 {
2714 if (!filename || !(*filename))
2715 return;
2716
2717 /*
2718 * WIN32 doesn't use tilde expansion for file names. Also, it uses tilde
2719 * for short versions of long file names, though the tilde is usually
2720 * toward the end, not at the beginning.
2721 */
2722 #ifndef WIN32
2723
2724 /* try tilde expansion */
2725 if (**filename == '~')
2726 {
2727 char *fn;
2728 char oldp,
2729 *p;
2730 struct passwd *pw;
2731 char home[MAXPGPATH];
2732
2733 fn = *filename;
2734 *home = '\0';
2735
2736 p = fn + 1;
2737 while (*p != '/' && *p != '\0')
2738 p++;
2739
2740 oldp = *p;
2741 *p = '\0';
2742
2743 if (*(fn + 1) == '\0')
2744 get_home_path(home); /* ~ or ~/ only */
2745 else if ((pw = getpwnam(fn + 1)) != NULL)
2746 strlcpy(home, pw->pw_dir, sizeof(home)); /* ~user */
2747
2748 *p = oldp;
2749 if (strlen(home) != 0)
2750 {
2751 char *newfn;
2752
2753 newfn = psprintf("%s%s", home, p);
2754 free(fn);
2755 *filename = newfn;
2756 }
2757 }
2758 #endif
2759 }
2760
2761 /*
2762 * Checks if connection string starts with either of the valid URI prefix
2763 * designators.
2764 *
2765 * Returns the URI prefix length, 0 if the string doesn't contain a URI prefix.
2766 *
2767 * XXX This is a duplicate of the eponymous libpq function.
2768 */
2769 static int
2770 uri_prefix_length(const char *connstr)
2771 {
2772 /* The connection URI must start with either of the following designators: */
2773 static const char uri_designator[] = "postgresql://";
2774 static const char short_uri_designator[] = "postgres://";
2775
2776 if (strncmp(connstr, uri_designator,
2777 sizeof(uri_designator) - 1) == 0)
2778 return sizeof(uri_designator) - 1;
2779
2780 if (strncmp(connstr, short_uri_designator,
2781 sizeof(short_uri_designator) - 1) == 0)
2782 return sizeof(short_uri_designator) - 1;
2783
2784 return 0;
2785 }
2786
2787 /*
2788 * Reset state related to extended query protocol
2789 *
2790 * Clean up any state related to bind parameters, statement name and
2791 * PSQL_SEND_MODE. This needs to be called after processing a query or when
2792 * running a new meta-command that uses the extended query protocol, like
2793 * \parse, \bind, etc.
2794 */
2795 void
2796 clean_extended_state(void)
2797 {
2798 int i;
2799
2800 switch (pset.send_mode)
2801 {
2802 case PSQL_SEND_EXTENDED_CLOSE: /* \close_prepared */
2803 free(pset.stmtName);
2804 break;
2805 case PSQL_SEND_EXTENDED_PARSE: /* \parse */
2806 free(pset.stmtName);
2807 break;
2808 case PSQL_SEND_EXTENDED_QUERY_PARAMS: /* \bind */
2809 case PSQL_SEND_EXTENDED_QUERY_PREPARED: /* \bind_named */
2810 for (i = 0; i < pset.bind_nparams; i++)
2811 free(pset.bind_params[i]);
2812 free(pset.bind_params);
2813 free(pset.stmtName);
2814 pset.bind_params = NULL;
2815 break;
2816 case PSQL_SEND_QUERY:
2817 case PSQL_SEND_START_PIPELINE_MODE: /* \startpipeline */
2818 case PSQL_SEND_END_PIPELINE_MODE: /* \endpipeline */
2819 case PSQL_SEND_PIPELINE_SYNC: /* \syncpipeline */
2820 case PSQL_SEND_FLUSH: /* \flush */
2821 case PSQL_SEND_GET_RESULTS: /* \getresults */
2822 case PSQL_SEND_FLUSH_REQUEST: /* \flushrequest */
2823 break;
2824 }
2825
2826 pset.stmtName = NULL;
2827 pset.send_mode = PSQL_SEND_QUERY;
2828 }
2829
2830 /*
2831 * Recognized connection string either starts with a valid URI prefix or
2832 * contains a "=" in it.
2833 *
2834 * Must be consistent with parse_connection_string: anything for which this
2835 * returns true should at least look like it's parseable by that routine.
2836 *
2837 * XXX This is a duplicate of the eponymous libpq function.
2838 */
2839 bool
2840 recognized_connection_string(const char *connstr)
2841 {
2842 return uri_prefix_length(connstr) != 0 || strchr(connstr, '=') != NULL;
2843 }