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