Branch data Line data Source code
1 : : /*
2 : : * psql - the PostgreSQL interactive terminal
3 : : *
4 : : * Copyright (c) 2000-2026, 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 "mb/pg_wchar.h"
32 : : #include "portability/instr_time.h"
33 : : #include "settings.h"
34 : :
35 : : static bool DescribeQuery(const char *query, double *elapsed_msec);
36 : : static int ExecQueryAndProcessResults(const char *query,
37 : : double *elapsed_msec,
38 : : bool *svpt_gone_p,
39 : : int num_copy_from_stdin,
40 : : bool is_watch,
41 : : int min_rows,
42 : : const printQueryOpt *opt,
43 : : FILE *printQueryFout);
44 : : static bool command_no_begin(const char *query);
45 : :
46 : :
47 : : /*
48 : : * openQueryOutputFile --- attempt to open a query output file
49 : : *
50 : : * fname == NULL selects stdout, else an initial '|' selects a pipe,
51 : : * else plain file.
52 : : *
53 : : * Returns output file pointer into *fout, and is-a-pipe flag into *is_pipe.
54 : : * Caller is responsible for adjusting SIGPIPE state if it's a pipe.
55 : : *
56 : : * On error, reports suitable error message and returns false.
57 : : */
58 : : bool
59 : 11317 : openQueryOutputFile(const char *fname, FILE **fout, bool *is_pipe)
60 : : {
61 [ + + - + ]: 11317 : if (!fname || fname[0] == '\0')
62 : : {
63 : 11285 : *fout = stdout;
64 : 11285 : *is_pipe = false;
65 : : }
66 [ + + ]: 32 : else if (*fname == '|')
67 : : {
68 : 4 : fflush(NULL);
69 : 4 : *fout = popen(fname + 1, "w");
70 : 4 : *is_pipe = true;
71 : : }
72 : : else
73 : : {
74 : 28 : *fout = fopen(fname, "w");
75 : 28 : *is_pipe = false;
76 : : }
77 : :
78 [ - + ]: 11317 : if (*fout == NULL)
79 : : {
80 : 0 : pg_log_error("%s: %m", fname);
81 : 0 : return false;
82 : : }
83 : :
84 : 11317 : return true;
85 : : }
86 : :
87 : : /*
88 : : * Check if an output stream for \g needs to be opened, and if yes,
89 : : * open it and update the caller's gfile_fout and is_pipe state variables.
90 : : * Return true if OK, false if an error occurred.
91 : : */
92 : : static bool
93 : 98275 : SetupGOutput(FILE **gfile_fout, bool *is_pipe)
94 : : {
95 : : /* If there is a \g file or program, and it's not already open, open it */
96 [ + + + + ]: 98275 : if (pset.gfname != NULL && *gfile_fout == NULL)
97 : : {
98 [ + - ]: 20 : if (openQueryOutputFile(pset.gfname, gfile_fout, is_pipe))
99 : : {
100 [ + + ]: 20 : if (*is_pipe)
101 : 4 : disable_sigpipe_trap();
102 : : }
103 : : else
104 : 0 : return false;
105 : : }
106 : 98275 : return true;
107 : : }
108 : :
109 : : /*
110 : : * Close the output stream for \g, if we opened it.
111 : : */
112 : : static void
113 : 261231 : CloseGOutput(FILE *gfile_fout, bool is_pipe)
114 : : {
115 [ + + ]: 261231 : if (gfile_fout)
116 : : {
117 [ + + ]: 20 : if (is_pipe)
118 : : {
119 : 4 : SetShellResultVariables(pclose(gfile_fout));
120 : 4 : restore_sigpipe_trap();
121 : : }
122 : : else
123 : 16 : fclose(gfile_fout);
124 : : }
125 : 261231 : }
126 : :
127 : : /*
128 : : * Reset pset pipeline state
129 : : */
130 : : static void
131 : 0 : pipelineReset(void)
132 : : {
133 : 0 : pset.piped_syncs = 0;
134 : 0 : pset.piped_commands = 0;
135 : 0 : pset.available_results = 0;
136 : 0 : pset.requested_results = 0;
137 : 0 : }
138 : :
139 : : /*
140 : : * setQFout
141 : : * -- handler for -o command line option and \o command
142 : : *
143 : : * On success, updates pset with the new output file and returns true.
144 : : * On failure, returns false without changing pset state.
145 : : */
146 : : bool
147 : 11297 : setQFout(const char *fname)
148 : : {
149 : : FILE *fout;
150 : : bool is_pipe;
151 : :
152 : : /* First make sure we can open the new output file/pipe */
153 [ - + ]: 11297 : if (!openQueryOutputFile(fname, &fout, &is_pipe))
154 : 0 : return false;
155 : :
156 : : /* Close old file/pipe */
157 [ + - + + : 11297 : if (pset.queryFout && pset.queryFout != stdout && pset.queryFout != stderr)
+ - ]
158 : : {
159 [ - + ]: 12 : if (pset.queryFoutPipe)
160 : 0 : SetShellResultVariables(pclose(pset.queryFout));
161 : : else
162 : 12 : fclose(pset.queryFout);
163 : : }
164 : :
165 : 11297 : pset.queryFout = fout;
166 : 11297 : pset.queryFoutPipe = is_pipe;
167 : :
168 : : /* Adjust SIGPIPE handling appropriately: ignore signal if is_pipe */
169 : 11297 : set_sigpipe_trap_state(is_pipe);
170 : 11297 : restore_sigpipe_trap();
171 : :
172 : 11297 : return true;
173 : : }
174 : :
175 : :
176 : : /*
177 : : * Variable-fetching callback for flex lexer
178 : : *
179 : : * If the specified variable exists, return its value as a string (malloc'd
180 : : * and expected to be freed by the caller); else return NULL.
181 : : *
182 : : * If "quote" isn't PQUOTE_PLAIN, then return the value suitably quoted and
183 : : * escaped for the specified quoting requirement. (Failure in escaping
184 : : * should lead to printing an error and returning NULL.)
185 : : *
186 : : * "passthrough" is the pointer previously given to psql_scan_set_passthrough.
187 : : * In psql, passthrough points to a ConditionalStack, which we check to
188 : : * determine whether variable expansion is allowed.
189 : : */
190 : : char *
191 : 2969 : psql_get_variable(const char *varname, PsqlScanQuoteType quote,
192 : : void *passthrough)
193 : : {
194 : 2969 : char *result = NULL;
195 : : const char *value;
196 : :
197 : : /* In an inactive \if branch, suppress all variable substitutions */
198 [ + - + + ]: 2969 : if (passthrough && !conditional_active((ConditionalStack) passthrough))
199 : 48 : return NULL;
200 : :
201 : 2921 : value = GetVariable(pset.vars, varname);
202 [ + + ]: 2921 : if (!value)
203 : 333 : return NULL;
204 : :
205 [ + + - - ]: 2588 : switch (quote)
206 : : {
207 : 1858 : case PQUOTE_PLAIN:
208 : 1858 : result = pg_strdup(value);
209 : 1858 : break;
210 : 730 : case PQUOTE_SQL_LITERAL:
211 : : case PQUOTE_SQL_IDENT:
212 : : {
213 : : /*
214 : : * For these cases, we use libpq's quoting functions, which
215 : : * assume the string is in the connection's client encoding.
216 : : */
217 : : char *escaped_value;
218 : :
219 [ - + ]: 730 : if (!pset.db)
220 : : {
221 : 0 : pg_log_error("cannot escape without active connection");
222 : 0 : return NULL;
223 : : }
224 : :
225 [ + + ]: 730 : if (quote == PQUOTE_SQL_LITERAL)
226 : : escaped_value =
227 : 709 : PQescapeLiteral(pset.db, value, strlen(value));
228 : : else
229 : : escaped_value =
230 : 21 : PQescapeIdentifier(pset.db, value, strlen(value));
231 : :
232 [ - + ]: 730 : if (escaped_value == NULL)
233 : : {
234 : 0 : const char *error = PQerrorMessage(pset.db);
235 : :
236 : 0 : pg_log_info("%s", error);
237 : 0 : return NULL;
238 : : }
239 : :
240 : : /*
241 : : * Rather than complicate the lexer's API with a notion of
242 : : * which free() routine to use, just pay the price of an extra
243 : : * strdup().
244 : : */
245 : 730 : result = pg_strdup(escaped_value);
246 : 730 : PQfreemem(escaped_value);
247 : 730 : break;
248 : : }
249 : 0 : case PQUOTE_SHELL_ARG:
250 : : {
251 : : /*
252 : : * For this we use appendShellStringNoError, which is
253 : : * encoding-agnostic, which is fine since the shell probably
254 : : * is too. In any case, the only special character is "'",
255 : : * which is not known to appear in valid multibyte characters.
256 : : */
257 : : PQExpBufferData buf;
258 : :
259 : 0 : initPQExpBuffer(&buf);
260 [ # # ]: 0 : if (!appendShellStringNoError(&buf, value))
261 : : {
262 : 0 : pg_log_error("shell command argument contains a newline or carriage return: \"%s\"",
263 : : value);
264 : 0 : free(buf.data);
265 : 0 : return NULL;
266 : : }
267 : 0 : result = buf.data;
268 : 0 : break;
269 : : }
270 : :
271 : : /* No default: we want a compiler warning for missing cases */
272 : : }
273 : :
274 : 2588 : return result;
275 : : }
276 : :
277 : :
278 : : /*
279 : : * for backend Notice messages (INFO, WARNING, etc)
280 : : */
281 : : void
282 : 186375 : NoticeProcessor(void *arg, const char *message)
283 : : {
284 : : (void) arg; /* not used */
285 : 186375 : pg_log_info("%s", message);
286 : 186375 : }
287 : :
288 : :
289 : :
290 : : /*
291 : : * Code to support query cancellation
292 : : *
293 : : * Before we start a query, we enable the SIGINT signal catcher to send a
294 : : * cancel request to the backend.
295 : : *
296 : : * SIGINT is supposed to abort all long-running psql operations, not only
297 : : * database queries. In most places, this is accomplished by checking
298 : : * CancelRequested during long-running loops. However, that won't work when
299 : : * blocked on user input (in readline() or fgets()). In those places, we
300 : : * set sigint_interrupt_enabled true while blocked, instructing the signal
301 : : * catcher to longjmp through sigint_interrupt_jmp. We assume readline and
302 : : * fgets are coded to handle possible interruption.
303 : : *
304 : : * On Windows, currently this does not work, so control-C is less useful
305 : : * there.
306 : : */
307 : : volatile sig_atomic_t sigint_interrupt_enabled = false;
308 : :
309 : : sigjmp_buf sigint_interrupt_jmp;
310 : :
311 : : static void
312 : 1 : psql_cancel_callback(void)
313 : : {
314 : : #ifndef WIN32
315 : : /* if we are waiting for input, longjmp out of it */
316 [ - + ]: 1 : if (sigint_interrupt_enabled)
317 : : {
318 : 0 : sigint_interrupt_enabled = false;
319 : 0 : siglongjmp(sigint_interrupt_jmp, 1);
320 : : }
321 : : #endif
322 : 1 : }
323 : :
324 : : void
325 : 11289 : psql_setup_cancel_handler(void)
326 : : {
327 : 11289 : setup_cancel_handler(psql_cancel_callback);
328 : 11289 : }
329 : :
330 : :
331 : : /*
332 : : * ConnectionUp
333 : : *
334 : : * Returns whether our backend connection is still there.
335 : : */
336 : : static bool
337 : 292566 : ConnectionUp(void)
338 : : {
339 : 292566 : return PQstatus(pset.db) != CONNECTION_BAD;
340 : : }
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 : 292386 : CheckConnection(void)
357 : : {
358 : : bool OK;
359 : :
360 : 292386 : OK = ConnectionUp();
361 [ + + ]: 292386 : if (!OK)
362 : : {
363 [ + - ]: 12 : if (!pset.cur_cmd_interactive)
364 : : {
365 : 12 : pg_log_error("connection to server was lost");
366 : 12 : exit(EXIT_BADCONN);
367 : : }
368 : :
369 : 0 : fprintf(stderr, _("The connection to the server was lost. Attempting reset: "));
370 : 0 : PQreset(pset.db);
371 : 0 : pipelineReset();
372 : 0 : OK = ConnectionUp();
373 [ # # ]: 0 : if (!OK)
374 : : {
375 : 0 : 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 [ # # ]: 0 : if (pset.dead_conn)
384 : 0 : PQfinish(pset.dead_conn);
385 : 0 : pset.dead_conn = pset.db;
386 : 0 : pset.db = NULL;
387 : 0 : ResetCancelConn();
388 : 0 : UnsyncVariables();
389 : : }
390 : : else
391 : : {
392 : 0 : fprintf(stderr, _("Succeeded.\n"));
393 : :
394 : : /*
395 : : * Re-sync, just in case anything changed. Keep this in sync with
396 : : * do_connect().
397 : : */
398 : 0 : SyncVariables();
399 : 0 : connection_warnings(false); /* Must be after SyncVariables */
400 : : }
401 : : }
402 : :
403 : 292374 : 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 : 293600 : AcceptResult(const PGresult *result, bool show_error)
419 : : {
420 : : bool OK;
421 : :
422 [ - + ]: 293600 : if (!result)
423 : 0 : OK = false;
424 : : else
425 [ + + + ]: 293600 : switch (PQresultStatus(result))
426 : : {
427 : 262477 : 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 : 262477 : OK = true;
436 : 262477 : break;
437 : :
438 : 31122 : case PGRES_PIPELINE_ABORTED:
439 : : case PGRES_BAD_RESPONSE:
440 : : case PGRES_NONFATAL_ERROR:
441 : : case PGRES_FATAL_ERROR:
442 : 31122 : OK = false;
443 : 31122 : break;
444 : :
445 : 1 : default:
446 : 1 : OK = false;
447 : 1 : pg_log_error("unexpected PQresultStatus: %d",
448 : : PQresultStatus(result));
449 : 1 : break;
450 : : }
451 : :
452 [ + + + + ]: 293600 : if (!OK && show_error)
453 : : {
454 : 4 : const char *error = PQerrorMessage(pset.db);
455 : :
456 [ + - ]: 4 : if (strlen(error))
457 : 4 : pg_log_info("%s", error);
458 : :
459 : 4 : CheckConnection();
460 : : }
461 : :
462 : 293600 : 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 : 261207 : SetResultVariables(PGresult *result, bool success)
479 : : {
480 [ + + ]: 261207 : if (success)
481 : : {
482 : 229834 : const char *ntuples = PQcmdTuples(result);
483 : :
484 : 229834 : SetVariable(pset.vars, "ERROR", "false");
485 : 229834 : SetVariable(pset.vars, "SQLSTATE", "00000");
486 [ + + ]: 229834 : SetVariable(pset.vars, "ROW_COUNT", *ntuples ? ntuples : "0");
487 : : }
488 : : else
489 : : {
490 : 31373 : const char *code = PQresultErrorField(result, PG_DIAG_SQLSTATE);
491 : 31373 : const char *mesg = PQresultErrorField(result, PG_DIAG_MESSAGE_PRIMARY);
492 : :
493 : 31373 : 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 [ + + ]: 31373 : if (code == NULL)
500 : 106 : code = "";
501 : 31373 : SetVariable(pset.vars, "SQLSTATE", code);
502 : 31373 : SetVariable(pset.vars, "ROW_COUNT", "0");
503 : 31373 : SetVariable(pset.vars, "LAST_ERROR_SQLSTATE", code);
504 [ + + ]: 31373 : SetVariable(pset.vars, "LAST_ERROR_MESSAGE", mesg ? mesg : "");
505 : : }
506 : 261207 : }
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 : 4 : SetShellResultVariables(int wait_result)
519 : : {
520 : : char buf[32];
521 : :
522 [ + - ]: 4 : SetVariable(pset.vars, "SHELL_ERROR",
523 : : (wait_result == 0) ? "false" : "true");
524 : 4 : snprintf(buf, sizeof(buf), "%d", wait_result_to_exit_code(wait_result));
525 : 4 : SetVariable(pset.vars, "SHELL_EXIT_CODE", buf);
526 : 4 : }
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 : 262224 : SetPipelineVariables(void)
537 : : {
538 : : char buf[32];
539 : :
540 : 262224 : snprintf(buf, sizeof(buf), "%d", pset.piped_syncs);
541 : 262224 : SetVariable(pset.vars, "PIPELINE_SYNC_COUNT", buf);
542 : 262224 : snprintf(buf, sizeof(buf), "%d", pset.piped_commands);
543 : 262224 : SetVariable(pset.vars, "PIPELINE_COMMAND_COUNT", buf);
544 : 262224 : snprintf(buf, sizeof(buf), "%d", pset.available_results);
545 : 262224 : SetVariable(pset.vars, "PIPELINE_RESULT_COUNT", buf);
546 : 262224 : }
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 : 263070 : ClearOrSaveResult(PGresult *result)
561 : : {
562 [ + + ]: 263070 : if (result)
563 : : {
564 [ + + ]: 262534 : switch (PQresultStatus(result))
565 : : {
566 : 31272 : case PGRES_NONFATAL_ERROR:
567 : : case PGRES_FATAL_ERROR:
568 : 31272 : PQclear(pset.last_error_result);
569 : 31272 : pset.last_error_result = result;
570 : 31272 : break;
571 : :
572 : 231262 : default:
573 : 231262 : PQclear(result);
574 : 231262 : break;
575 : : }
576 : : }
577 : 263070 : }
578 : :
579 : :
580 : : /*
581 : : * Consume all results
582 : : */
583 : : static void
584 : 0 : ClearOrSaveAllResults(void)
585 : : {
586 : : PGresult *result;
587 : :
588 [ # # ]: 0 : while ((result = PQgetResult(pset.db)) != NULL)
589 : 0 : ClearOrSaveResult(result);
590 : 0 : }
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 : 2 : PrintTiming(double elapsed_msec)
599 : : {
600 : : double seconds;
601 : : double minutes;
602 : : double hours;
603 : : double days;
604 : :
605 [ + - ]: 2 : if (elapsed_msec < 1000.0)
606 : : {
607 : : /* This is the traditional (pre-v10) output format */
608 : 2 : printf(_("Time: %.3f ms\n"), elapsed_msec);
609 : 2 : 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 : 0 : seconds = elapsed_msec / 1000.0;
619 : 0 : minutes = floor(seconds / 60.0);
620 : 0 : seconds -= 60.0 * minutes;
621 [ # # ]: 0 : if (minutes < 60.0)
622 : : {
623 : 0 : printf(_("Time: %.3f ms (%02d:%06.3f)\n"),
624 : : elapsed_msec, (int) minutes, seconds);
625 : 0 : return;
626 : : }
627 : :
628 : 0 : hours = floor(minutes / 60.0);
629 : 0 : minutes -= 60.0 * hours;
630 [ # # ]: 0 : if (hours < 24.0)
631 : : {
632 : 0 : printf(_("Time: %.3f ms (%02d:%02d:%06.3f)\n"),
633 : : elapsed_msec, (int) hours, (int) minutes, seconds);
634 : 0 : return;
635 : : }
636 : :
637 : 0 : days = floor(hours / 24.0);
638 : 0 : hours -= 24.0 * days;
639 : 0 : 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 : 30759 : PSQLexec(const char *query)
658 : : {
659 : : PGresult *res;
660 : :
661 [ - + ]: 30759 : if (!pset.db)
662 : : {
663 : 0 : pg_log_error("You are currently not connected to a database.");
664 : 0 : return NULL;
665 : : }
666 : :
667 [ - + ]: 30759 : if (pset.echo_hidden != PSQL_ECHO_HIDDEN_OFF)
668 : : {
669 : 0 : printf(_("/**** INTERNAL QUERY ****/\n"
670 : : "%s\n"
671 : : "/************************/\n\n"), query);
672 : 0 : fflush(stdout);
673 [ # # ]: 0 : if (pset.logfile)
674 : : {
675 : 0 : fprintf(pset.logfile,
676 : 0 : _("/**** INTERNAL QUERY ****/\n"
677 : : "%s\n"
678 : : "/************************/\n\n"), query);
679 : 0 : fflush(pset.logfile);
680 : : }
681 : :
682 [ # # ]: 0 : if (pset.echo_hidden == PSQL_ECHO_HIDDEN_NOEXEC)
683 : 0 : return NULL;
684 : : }
685 : :
686 : 30759 : SetCancelConn(pset.db);
687 : :
688 : 30759 : res = PQexec(pset.db, query);
689 : :
690 : 30759 : ResetCancelConn();
691 : :
692 [ - + ]: 30759 : if (!AcceptResult(res, true))
693 : : {
694 : 0 : ClearOrSaveResult(res);
695 : 0 : res = NULL;
696 : : }
697 : :
698 : 30759 : 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 : 101 : PSQLexecWatch(const char *query, const printQueryOpt *opt, FILE *printQueryFout, int min_rows)
713 : : {
714 : 101 : bool timing = pset.timing;
715 : 101 : double elapsed_msec = 0;
716 : : int res;
717 : :
718 [ - + ]: 101 : if (!pset.db)
719 : : {
720 : 0 : pg_log_error("You are currently not connected to a database.");
721 : 0 : return 0;
722 : : }
723 : :
724 : 101 : SetCancelConn(pset.db);
725 : :
726 : 101 : res = ExecQueryAndProcessResults(query,
727 : : &elapsed_msec, NULL,
728 : : -1,
729 : : true, min_rows,
730 : : opt, printQueryFout);
731 : :
732 : 99 : ResetCancelConn();
733 : :
734 : : /* Possible microtiming output */
735 [ - + ]: 99 : if (timing)
736 : 0 : PrintTiming(elapsed_msec);
737 : :
738 : 99 : return res;
739 : : }
740 : :
741 : :
742 : : /*
743 : : * PrintNotifications: check for asynchronous notifications, and print them out
744 : : */
745 : : static void
746 : 262182 : PrintNotifications(void)
747 : : {
748 : : PGnotify *notify;
749 : :
750 : 262182 : PQconsumeInput(pset.db);
751 [ + + ]: 262194 : while ((notify = PQnotifies(pset.db)) != NULL)
752 : : {
753 : : /* for backward compatibility, only show payload if nonempty */
754 [ + + ]: 12 : if (notify->extra[0])
755 : 11 : 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 : 1 : fprintf(pset.queryFout, _("Asynchronous notification \"%s\" received from server process with PID %d.\n"),
759 : : notify->relname, notify->be_pid);
760 : 12 : fflush(pset.queryFout);
761 : 12 : PQfreemem(notify);
762 : 12 : PQconsumeInput(pset.db);
763 : : }
764 : 262182 : }
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 : 97504 : PrintQueryTuples(const PGresult *result, const printQueryOpt *opt,
780 : : FILE *printQueryFout)
781 : : {
782 : 97504 : bool ok = true;
783 [ + + ]: 97504 : FILE *fout = printQueryFout ? printQueryFout : pset.queryFout;
784 : :
785 [ + + ]: 97504 : printQuery(result, opt ? opt : &pset.popt, fout, false, pset.logfile);
786 : 97504 : fflush(fout);
787 [ - + ]: 97504 : if (ferror(fout))
788 : : {
789 : 0 : pg_log_error("could not print result table: %m");
790 : 0 : ok = false;
791 : : }
792 : :
793 : 97504 : 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 : 600 : StoreQueryTuple(const PGresult *result)
804 : : {
805 : 600 : bool success = true;
806 : :
807 [ + + ]: 600 : if (PQntuples(result) < 1)
808 : : {
809 : 12 : pg_log_error("no rows returned for \\gset");
810 : 12 : success = false;
811 : : }
812 [ + + ]: 588 : else if (PQntuples(result) > 1)
813 : : {
814 : 8 : pg_log_error("more than one row returned for \\gset");
815 : 8 : success = false;
816 : : }
817 : : else
818 : : {
819 : : int i;
820 : :
821 [ + + ]: 1278 : for (i = 0; i < PQnfields(result); i++)
822 : : {
823 : 702 : char *colname = PQfname(result, i);
824 : : char *varname;
825 : : char *value;
826 : :
827 : : /* concatenate prefix and column name */
828 : 702 : varname = psprintf("%s%s", pset.gset_prefix, colname);
829 : :
830 [ + + ]: 702 : if (VariableHasHook(pset.vars, varname))
831 : : {
832 : 4 : pg_log_warning("attempt to \\gset into specially treated variable \"%s\" ignored",
833 : : varname);
834 : 4 : continue;
835 : : }
836 : :
837 [ + + ]: 698 : if (!PQgetisnull(result, 0, i))
838 : 690 : value = PQgetvalue(result, 0, i);
839 : : else
840 : : {
841 : : /* for NULL value, unset rather than set the variable */
842 : 8 : value = NULL;
843 : : }
844 : :
845 [ + + ]: 698 : if (!SetVariable(pset.vars, varname, value))
846 : : {
847 : 4 : pfree(varname);
848 : 4 : success = false;
849 : 4 : break;
850 : : }
851 : :
852 : 694 : pfree(varname);
853 : : }
854 : : }
855 : :
856 : 600 : 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 : 29 : ExecQueryTuples(const PGresult *result)
868 : : {
869 : 29 : bool success = true;
870 : 29 : int nrows = PQntuples(result);
871 : 29 : int ncolumns = PQnfields(result);
872 : : int r,
873 : : c;
874 : :
875 : : /*
876 : : * We must turn off gexec_flag to avoid infinite recursion.
877 : : */
878 : 29 : pset.gexec_flag = false;
879 : :
880 [ + + ]: 290 : for (r = 0; r < nrows; r++)
881 : : {
882 [ + + ]: 534 : for (c = 0; c < ncolumns; c++)
883 : : {
884 [ + + ]: 273 : if (!PQgetisnull(result, r, c))
885 : : {
886 : 269 : const char *query = PQgetvalue(result, r, c);
887 : :
888 : : /* Abandon execution if CancelRequested */
889 [ - + ]: 269 : if (CancelRequested)
890 : 0 : 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 [ + + + - ]: 269 : if (pset.echo == PSQL_ECHO_ALL && !pset.singlestep)
897 : : {
898 : 264 : puts(query);
899 : 264 : fflush(stdout);
900 : : }
901 : :
902 [ + + ]: 269 : if (!SendQuery(query, -1))
903 : : {
904 : : /* Error - abandon execution if ON_ERROR_STOP */
905 : 4 : success = false;
906 [ - + ]: 4 : if (pset.on_error_stop)
907 : 0 : goto loop_exit;
908 : : }
909 : : }
910 : : }
911 : : }
912 : :
913 : 29 : 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 : 29 : pset.gexec_flag = true;
921 : :
922 : : /* Return true if all queries were successful */
923 : 29 : 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 : 1183 : HandleCopyResult(PGresult **resultp, FILE *copystream)
943 : : {
944 : : bool success;
945 : : PGresult *copy_result;
946 : 1183 : ExecStatusType result_status = PQresultStatus(*resultp);
947 : :
948 : : Assert(result_status == PGRES_COPY_OUT ||
949 : : result_status == PGRES_COPY_IN);
950 : :
951 : 1183 : SetCancelConn(pset.db);
952 : :
953 [ + + ]: 1183 : if (result_status == PGRES_COPY_OUT)
954 : : {
955 : 501 : success = handleCopyOut(pset.db,
956 : : copystream,
957 : : ©_result)
958 [ + + + - ]: 501 : && (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 [ + + ]: 501 : if (copystream == pset.queryFout)
966 : : {
967 : 484 : PQclear(copy_result);
968 : 484 : copy_result = NULL;
969 : : }
970 : : }
971 : : else
972 : : {
973 : : /* COPY IN */
974 : : Assert(copystream);
975 : 682 : success = handleCopyIn(pset.db,
976 : : copystream,
977 : 682 : PQbinaryTuples(*resultp),
978 : : ©_result);
979 : : }
980 : 1183 : 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 : 1183 : PQclear(*resultp);
987 : 1183 : *resultp = copy_result;
988 : :
989 : 1183 : return success;
990 : : }
991 : :
992 : : /*
993 : : * PrintQueryStatus: report command status as required
994 : : */
995 : : static void
996 : 230046 : PrintQueryStatus(PGresult *result, FILE *printQueryFout)
997 : : {
998 : : char buf[16];
999 : 230046 : const char *cmdstatus = PQcmdStatus(result);
1000 [ + - ]: 230046 : FILE *fout = printQueryFout ? printQueryFout : pset.queryFout;
1001 : :
1002 : : /* Do nothing if it's a TUPLES_OK result that isn't from RETURNING */
1003 [ + + ]: 230046 : if (PQresultStatus(result) == PGRES_TUPLES_OK)
1004 : : {
1005 [ + + ]: 98269 : if (!(strncmp(cmdstatus, "INSERT", 6) == 0 ||
1006 [ + + ]: 97687 : strncmp(cmdstatus, "UPDATE", 6) == 0 ||
1007 [ + + ]: 97332 : strncmp(cmdstatus, "DELETE", 6) == 0 ||
1008 [ + + ]: 97180 : strncmp(cmdstatus, "MERGE", 5) == 0))
1009 : 97056 : return;
1010 : : }
1011 : :
1012 [ + + ]: 132990 : if (!pset.quiet)
1013 : : {
1014 [ - + ]: 745 : if (pset.popt.topt.format == PRINT_HTML)
1015 : : {
1016 : 0 : fputs("<p>", fout);
1017 : 0 : html_escaped_print(cmdstatus, fout);
1018 : 0 : fputs("</p>\n", fout);
1019 : : }
1020 : : else
1021 : 745 : fprintf(fout, "%s\n", cmdstatus);
1022 : 745 : fflush(fout);
1023 : : }
1024 : :
1025 [ - + ]: 132990 : if (pset.logfile)
1026 : 0 : fprintf(pset.logfile, "%s\n", cmdstatus);
1027 : :
1028 : 132990 : snprintf(buf, sizeof(buf), "%u", PQoidValue(result));
1029 : 132990 : 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 : 230688 : PrintQueryResult(PGresult *result, bool last,
1044 : : const printQueryOpt *opt, FILE *printQueryFout,
1045 : : FILE *printStatusFout)
1046 : : {
1047 : : bool success;
1048 : :
1049 [ - + ]: 230688 : if (!result)
1050 : 0 : return false;
1051 : :
1052 [ + + + - : 230688 : switch (PQresultStatus(result))
- - ]
1053 : : {
1054 : 98238 : case PGRES_TUPLES_OK:
1055 : : /* store or execute or print the data ... */
1056 [ + + + + ]: 98238 : if (last && pset.gset_prefix)
1057 : 600 : success = StoreQueryTuple(result);
1058 [ + + + + ]: 97638 : else if (last && pset.gexec_flag)
1059 : 29 : success = ExecQueryTuples(result);
1060 [ + + + + ]: 97609 : else if (last && pset.crosstab_flag)
1061 : 96 : success = PrintResultInCrosstab(result);
1062 [ + + + + ]: 97513 : else if (last || pset.show_all_results)
1063 : 97504 : success = PrintQueryTuples(result, opt, printQueryFout);
1064 : : else
1065 : 9 : success = true;
1066 : :
1067 : : /*
1068 : : * If it's INSERT/UPDATE/DELETE/MERGE RETURNING, also print
1069 : : * status.
1070 : : */
1071 [ + + + + ]: 98238 : if (last || pset.show_all_results)
1072 : 98229 : PrintQueryStatus(result, printStatusFout);
1073 : :
1074 : 98238 : break;
1075 : :
1076 : 131777 : case PGRES_COMMAND_OK:
1077 [ + + + - ]: 131777 : if (last || pset.show_all_results)
1078 : 131777 : PrintQueryStatus(result, printStatusFout);
1079 : 131777 : success = true;
1080 : 131777 : break;
1081 : :
1082 : 673 : case PGRES_EMPTY_QUERY:
1083 : 673 : success = true;
1084 : 673 : break;
1085 : :
1086 : 0 : case PGRES_COPY_OUT:
1087 : : case PGRES_COPY_IN:
1088 : : /* nothing to do here: already processed */
1089 : 0 : success = true;
1090 : 0 : break;
1091 : :
1092 : 0 : case PGRES_PIPELINE_ABORTED:
1093 : : case PGRES_BAD_RESPONSE:
1094 : : case PGRES_NONFATAL_ERROR:
1095 : : case PGRES_FATAL_ERROR:
1096 : 0 : success = false;
1097 : 0 : break;
1098 : :
1099 : 0 : default:
1100 : 0 : success = false;
1101 : 0 : pg_log_error("unexpected PQresultStatus: %d",
1102 : : PQresultStatus(result));
1103 : 0 : break;
1104 : : }
1105 : :
1106 : 230688 : 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 : 262196 : SendQuery(const char *query, int num_copy_from_stdin)
1127 : : {
1128 : 262196 : bool timing = pset.timing;
1129 : : PGTransactionStatusType transaction_status;
1130 : 262196 : double elapsed_msec = 0;
1131 : 262196 : bool OK = false;
1132 : : int i;
1133 : 262196 : bool on_error_rollback_savepoint = false;
1134 : 262196 : bool svpt_gone = false;
1135 : :
1136 [ - + ]: 262196 : if (!pset.db)
1137 : : {
1138 : 0 : pg_log_error("You are currently not connected to a database.");
1139 : 0 : goto sendquery_cleanup;
1140 : : }
1141 : :
1142 [ - + ]: 262196 : if (pset.singlestep)
1143 : : {
1144 : : char buf[3];
1145 : :
1146 : 0 : fflush(stderr);
1147 : 0 : 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 : 0 : fflush(stdout);
1152 [ # # ]: 0 : if (fgets(buf, sizeof(buf), stdin) != NULL)
1153 [ # # ]: 0 : if (buf[0] == 'x')
1154 : 0 : goto sendquery_cleanup;
1155 [ # # ]: 0 : if (CancelRequested)
1156 : 0 : goto sendquery_cleanup;
1157 : : }
1158 [ + + ]: 262196 : else if (pset.echo == PSQL_ECHO_QUERIES)
1159 : : {
1160 : 87 : puts(query);
1161 : 87 : fflush(stdout);
1162 : : }
1163 : :
1164 [ - + ]: 262196 : if (pset.logfile)
1165 : : {
1166 : 0 : fprintf(pset.logfile,
1167 : 0 : _("/******** QUERY *********/\n"
1168 : : "%s\n"
1169 : : "/************************/\n\n"), query);
1170 : 0 : fflush(pset.logfile);
1171 : : }
1172 : :
1173 : 262196 : SetCancelConn(pset.db);
1174 : :
1175 : 262196 : transaction_status = PQtransactionStatus(pset.db);
1176 : :
1177 [ + + ]: 262196 : if (transaction_status == PQTRANS_IDLE &&
1178 [ + + ]: 232377 : !pset.autocommit &&
1179 [ + + ]: 56 : !command_no_begin(query))
1180 : : {
1181 : : PGresult *result;
1182 : :
1183 : 48 : result = PQexec(pset.db, "BEGIN");
1184 [ - + ]: 48 : if (PQresultStatus(result) != PGRES_COMMAND_OK)
1185 : : {
1186 : 0 : pg_log_info("%s", PQerrorMessage(pset.db));
1187 : 0 : ClearOrSaveResult(result);
1188 : 0 : goto sendquery_cleanup;
1189 : : }
1190 : 48 : ClearOrSaveResult(result);
1191 : 48 : transaction_status = PQtransactionStatus(pset.db);
1192 : : }
1193 : :
1194 [ + + ]: 262196 : if (transaction_status == PQTRANS_INTRANS &&
1195 [ + + ]: 28110 : pset.on_error_rollback != PSQL_ERROR_ROLLBACK_OFF &&
1196 [ + - ]: 104 : (pset.cur_cmd_interactive ||
1197 [ + - ]: 104 : pset.on_error_rollback == PSQL_ERROR_ROLLBACK_ON))
1198 : : {
1199 : : PGresult *result;
1200 : :
1201 : 104 : result = PQexec(pset.db, "SAVEPOINT pg_psql_temporary_savepoint");
1202 [ - + ]: 104 : if (PQresultStatus(result) != PGRES_COMMAND_OK)
1203 : : {
1204 : 0 : pg_log_info("%s", PQerrorMessage(pset.db));
1205 : 0 : ClearOrSaveResult(result);
1206 : 0 : goto sendquery_cleanup;
1207 : : }
1208 : 104 : ClearOrSaveResult(result);
1209 : 104 : on_error_rollback_savepoint = true;
1210 : : }
1211 : :
1212 [ + + ]: 262196 : if (pset.gdesc_flag)
1213 : : {
1214 : : /* Describe query's result columns, without executing it */
1215 : 57 : OK = DescribeQuery(query, &elapsed_msec);
1216 : : }
1217 : : else
1218 : : {
1219 : : /* Default fetch-and-print mode */
1220 : 262139 : OK = (ExecQueryAndProcessResults(query,
1221 : : &elapsed_msec, &svpt_gone,
1222 : : num_copy_from_stdin,
1223 : : false, 0,
1224 : : NULL, NULL) > 0);
1225 : : }
1226 : :
1227 [ + + + + ]: 262182 : if (!OK && pset.echo == PSQL_ECHO_ERRORS)
1228 : 4 : pg_log_info("STATEMENT: %s", query);
1229 : :
1230 : : /* If we made a temporary savepoint, possibly release/rollback */
1231 [ + + ]: 262182 : if (on_error_rollback_savepoint)
1232 : : {
1233 : 104 : const char *svptcmd = NULL;
1234 : :
1235 : 104 : transaction_status = PQtransactionStatus(pset.db);
1236 : :
1237 [ + + + - ]: 104 : switch (transaction_status)
1238 : : {
1239 : 28 : case PQTRANS_INERROR:
1240 : : /* We always rollback on an error */
1241 : 28 : svptcmd = "ROLLBACK TO pg_psql_temporary_savepoint";
1242 : 28 : break;
1243 : :
1244 : 28 : case PQTRANS_IDLE:
1245 : : /* If they are no longer in a transaction, then do nothing */
1246 : 28 : break;
1247 : :
1248 : 48 : case PQTRANS_INTRANS:
1249 : :
1250 : : /*
1251 : : * Release our savepoint, but do nothing if they are messing
1252 : : * with savepoints themselves
1253 : : */
1254 [ + + ]: 48 : if (!svpt_gone)
1255 : 44 : svptcmd = "RELEASE pg_psql_temporary_savepoint";
1256 : 48 : break;
1257 : :
1258 : 0 : case PQTRANS_ACTIVE:
1259 : : case PQTRANS_UNKNOWN:
1260 : : default:
1261 : 0 : OK = false;
1262 : : /* PQTRANS_UNKNOWN is expected given a broken connection. */
1263 [ # # # # ]: 0 : if (transaction_status != PQTRANS_UNKNOWN || ConnectionUp())
1264 : 0 : pg_log_error("unexpected transaction status (%d)",
1265 : : transaction_status);
1266 : 0 : break;
1267 : : }
1268 : :
1269 [ + + ]: 104 : if (svptcmd)
1270 : : {
1271 : : PGresult *svptres;
1272 : :
1273 : 72 : svptres = PQexec(pset.db, svptcmd);
1274 [ - + ]: 72 : if (PQresultStatus(svptres) != PGRES_COMMAND_OK)
1275 : : {
1276 : 0 : pg_log_info("%s", PQerrorMessage(pset.db));
1277 : 0 : ClearOrSaveResult(svptres);
1278 : 0 : OK = false;
1279 : :
1280 : 0 : goto sendquery_cleanup;
1281 : : }
1282 : 72 : PQclear(svptres);
1283 : : }
1284 : : }
1285 : :
1286 : : /* Possible microtiming output */
1287 [ + + ]: 262182 : if (timing)
1288 : 2 : PrintTiming(elapsed_msec);
1289 : :
1290 : : /* check for events that may occur during query execution */
1291 : :
1292 [ + + + - ]: 262211 : if (pset.encoding != PQclientEncoding(pset.db) &&
1293 : 29 : PQclientEncoding(pset.db) >= 0)
1294 : : {
1295 : : /* track effects of SET CLIENT_ENCODING */
1296 : 29 : pset.encoding = PQclientEncoding(pset.db);
1297 : 29 : pset.popt.topt.encoding = pset.encoding;
1298 : 29 : SetVariable(pset.vars, "ENCODING",
1299 : : pg_encoding_to_char(pset.encoding));
1300 : : }
1301 : :
1302 : 262182 : PrintNotifications();
1303 : :
1304 : : /* perform cleanup that should occur after any attempted query */
1305 : :
1306 : 262182 : sendquery_cleanup:
1307 : :
1308 : : /* global cancellation reset */
1309 : 262182 : ResetCancelConn();
1310 : :
1311 : : /* reset \g's output-to-filename trigger */
1312 [ + + ]: 262182 : if (pset.gfname)
1313 : : {
1314 : 20 : free(pset.gfname);
1315 : 20 : pset.gfname = NULL;
1316 : : }
1317 : :
1318 : : /* restore print settings if \g changed them */
1319 [ + + ]: 262182 : if (pset.gsavepopt)
1320 : : {
1321 : 110 : restorePsetInfo(&pset.popt, pset.gsavepopt);
1322 : 110 : pset.gsavepopt = NULL;
1323 : : }
1324 : :
1325 : : /* clean up after extended protocol queries */
1326 : 262182 : clean_extended_state();
1327 : :
1328 : : /* reset \gset trigger */
1329 [ + + ]: 262182 : if (pset.gset_prefix)
1330 : : {
1331 : 600 : free(pset.gset_prefix);
1332 : 600 : pset.gset_prefix = NULL;
1333 : : }
1334 : :
1335 : : /* reset \gdesc trigger */
1336 : 262182 : pset.gdesc_flag = false;
1337 : :
1338 : : /* reset \gexec trigger */
1339 : 262182 : pset.gexec_flag = false;
1340 : :
1341 : : /* reset \crosstabview trigger */
1342 : 262182 : pset.crosstab_flag = false;
1343 [ + + ]: 1310910 : for (i = 0; i < lengthof(pset.ctv_args); i++)
1344 : : {
1345 : 1048728 : pg_free(pset.ctv_args[i]);
1346 : 1048728 : pset.ctv_args[i] = NULL;
1347 : : }
1348 : :
1349 : 262182 : 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 : 57 : DescribeQuery(const char *query, double *elapsed_msec)
1363 : : {
1364 : 57 : bool timing = pset.timing;
1365 : : PGresult *result;
1366 : : bool OK;
1367 : : instr_time before,
1368 : : after;
1369 : :
1370 : 57 : *elapsed_msec = 0;
1371 : :
1372 [ - + ]: 57 : if (timing)
1373 : 0 : INSTR_TIME_SET_CURRENT(before);
1374 : : else
1375 : 57 : 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 : 57 : result = PQprepare(pset.db, "", query, 0, NULL);
1386 [ + + ]: 57 : if (PQresultStatus(result) != PGRES_COMMAND_OK)
1387 : : {
1388 : 21 : pg_log_info("%s", PQerrorMessage(pset.db));
1389 : 21 : SetResultVariables(result, false);
1390 : 21 : ClearOrSaveResult(result);
1391 : 21 : return false;
1392 : : }
1393 : 36 : PQclear(result);
1394 : :
1395 : 36 : result = PQdescribePrepared(pset.db, "");
1396 [ + - + - ]: 72 : OK = AcceptResult(result, true) &&
1397 : 36 : (PQresultStatus(result) == PGRES_COMMAND_OK);
1398 [ + - + - ]: 36 : if (OK && result)
1399 : : {
1400 [ + + ]: 36 : if (PQnfields(result) > 0)
1401 : : {
1402 : : PQExpBufferData buf;
1403 : : int i;
1404 : :
1405 : 24 : initPQExpBuffer(&buf);
1406 : :
1407 : 24 : 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 [ + + ]: 108 : for (i = 0; i < PQnfields(result); i++)
1414 : : {
1415 : : const char *name;
1416 : : char *escname;
1417 : :
1418 [ + + ]: 84 : if (i > 0)
1419 : 60 : appendPQExpBufferChar(&buf, ',');
1420 : :
1421 : 84 : name = PQfname(result, i);
1422 : 84 : escname = PQescapeLiteral(pset.db, name, strlen(name));
1423 : :
1424 [ - + ]: 84 : if (escname == NULL)
1425 : : {
1426 : 0 : pg_log_info("%s", PQerrorMessage(pset.db));
1427 : 0 : PQclear(result);
1428 : 0 : termPQExpBuffer(&buf);
1429 : 0 : return false;
1430 : : }
1431 : :
1432 : 84 : appendPQExpBuffer(&buf, "(%s, '%u'::pg_catalog.oid, %d)",
1433 : : escname,
1434 : : PQftype(result, i),
1435 : : PQfmod(result, i));
1436 : :
1437 : 84 : PQfreemem(escname);
1438 : : }
1439 : :
1440 : 24 : appendPQExpBufferStr(&buf, ") s(name, tp, tpm)");
1441 : 24 : PQclear(result);
1442 : :
1443 : 24 : result = PQexec(pset.db, buf.data);
1444 : 24 : OK = AcceptResult(result, true);
1445 : :
1446 [ - + ]: 24 : if (timing)
1447 : : {
1448 : 0 : INSTR_TIME_SET_CURRENT(after);
1449 : 0 : INSTR_TIME_SUBTRACT(after, before);
1450 : 0 : *elapsed_msec += INSTR_TIME_GET_MILLISEC(after);
1451 : : }
1452 : :
1453 [ + - + - ]: 24 : if (OK && result)
1454 : 24 : OK = PrintQueryResult(result, true, NULL, NULL, NULL);
1455 : :
1456 : 24 : termPQExpBuffer(&buf);
1457 : : }
1458 : : else
1459 : 12 : fprintf(pset.queryFout,
1460 : 12 : _("The command has no result, or the result has no columns.\n"));
1461 : : }
1462 : :
1463 : 36 : SetResultVariables(result, OK);
1464 : 36 : ClearOrSaveResult(result);
1465 : :
1466 : 36 : 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 : 108 : discardAbortedPipelineResults(void)
1479 : : {
1480 : : for (;;)
1481 : 196 : {
1482 : 304 : PGresult *res = PQgetResult(pset.db);
1483 : 304 : ExecStatusType result_status = PQresultStatus(res);
1484 : :
1485 [ + + ]: 304 : if (result_status == PGRES_PIPELINE_SYNC)
1486 : : {
1487 : : /*
1488 : : * Found a synchronisation point. The sync counter is decremented
1489 : : * by the caller.
1490 : : */
1491 : 52 : return res;
1492 : : }
1493 [ + + - + ]: 252 : 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 : 0 : fatal_res = PQgetResult(pset.db);
1507 : : Assert(fatal_res == NULL);
1508 : 0 : return res;
1509 : : }
1510 [ + + ]: 252 : 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 [ - + ]: 180 : if (!ConnectionUp())
1525 : 0 : return NULL;
1526 [ + + ]: 180 : if (pset.available_results > 0)
1527 : 152 : pset.available_results--;
1528 [ + - ]: 180 : if (pset.requested_results > 0)
1529 : 180 : pset.requested_results--;
1530 : : }
1531 : :
1532 [ + + ]: 252 : if (pset.requested_results == 0)
1533 : : {
1534 : : /* We have read all the requested results, leave */
1535 : 56 : return res;
1536 : : }
1537 : :
1538 [ + + - + ]: 196 : 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 : 0 : 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 : 196 : 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 : 262240 : 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 : 262240 : bool timing = pset.timing;
1588 : 262240 : bool success = false;
1589 : 262240 : bool return_early = false;
1590 : 262240 : bool end_pipeline = false;
1591 : : instr_time before,
1592 : : after;
1593 : : PGresult *result;
1594 : 262240 : FILE *gfile_fout = NULL;
1595 : 262240 : bool gfile_is_pipe = false;
1596 : :
1597 [ + + ]: 262240 : if (timing)
1598 : 2 : INSTR_TIME_SET_CURRENT(before);
1599 : : else
1600 : 262238 : INSTR_TIME_SET_ZERO(before);
1601 : :
1602 [ + + + + : 262240 : switch (pset.send_mode)
+ + + + +
+ + - ]
1603 : : {
1604 : 25 : case PSQL_SEND_EXTENDED_CLOSE:
1605 : 25 : success = PQsendClosePrepared(pset.db, pset.stmtName);
1606 [ + - + + ]: 25 : if (success && PQpipelineStatus(pset.db) != PQ_PIPELINE_OFF)
1607 : 12 : pset.piped_commands++;
1608 : 25 : break;
1609 : 67 : case PSQL_SEND_EXTENDED_PARSE:
1610 : 67 : success = PQsendPrepare(pset.db, pset.stmtName, query, 0, NULL);
1611 [ + - + + ]: 67 : if (success && PQpipelineStatus(pset.db) != PQ_PIPELINE_OFF)
1612 : 44 : pset.piped_commands++;
1613 : 67 : break;
1614 : 508 : case PSQL_SEND_EXTENDED_QUERY_PARAMS:
1615 : : Assert(pset.stmtName == NULL);
1616 : 1016 : success = PQsendQueryParams(pset.db, query,
1617 : : pset.bind_nparams, NULL,
1618 : 508 : (const char *const *) pset.bind_params,
1619 : : NULL, NULL, 0);
1620 [ + - + + ]: 508 : if (success && PQpipelineStatus(pset.db) != PQ_PIPELINE_OFF)
1621 : 433 : pset.piped_commands++;
1622 : 508 : break;
1623 : 80 : case PSQL_SEND_EXTENDED_QUERY_PREPARED:
1624 : : Assert(pset.stmtName != NULL);
1625 : 160 : success = PQsendQueryPrepared(pset.db, pset.stmtName,
1626 : : pset.bind_nparams,
1627 : 80 : (const char *const *) pset.bind_params,
1628 : : NULL, NULL, 0);
1629 [ + - + + ]: 80 : if (success && PQpipelineStatus(pset.db) != PQ_PIPELINE_OFF)
1630 : 32 : pset.piped_commands++;
1631 : 80 : break;
1632 : 225 : case PSQL_SEND_START_PIPELINE_MODE:
1633 : 225 : success = PQenterPipelineMode(pset.db);
1634 : 225 : break;
1635 : 225 : case PSQL_SEND_END_PIPELINE_MODE:
1636 : 225 : success = PQpipelineSync(pset.db);
1637 [ + + + - ]: 225 : 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 : 221 : end_pipeline = true;
1644 : 221 : 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 : 221 : pset.available_results += pset.piped_commands;
1651 : 221 : pset.piped_commands = 0;
1652 : :
1653 : : /* We want to read all results */
1654 : 221 : pset.requested_results = pset.available_results + pset.piped_syncs;
1655 : : }
1656 : 225 : break;
1657 : 95 : case PSQL_SEND_PIPELINE_SYNC:
1658 : 95 : success = PQsendPipelineSync(pset.db);
1659 [ + - + - ]: 95 : if (success && PQpipelineStatus(pset.db) != PQ_PIPELINE_OFF)
1660 : : {
1661 : 95 : 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 : 95 : pset.available_results += pset.piped_commands;
1668 : 95 : pset.piped_commands = 0;
1669 : : }
1670 : 95 : break;
1671 : 12 : case PSQL_SEND_FLUSH:
1672 : 12 : success = PQflush(pset.db);
1673 : 12 : break;
1674 : 44 : case PSQL_SEND_FLUSH_REQUEST:
1675 : 44 : success = PQsendFlushRequest(pset.db);
1676 [ + - + - ]: 44 : 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 : 44 : pset.available_results += pset.piped_commands;
1684 : 44 : pset.piped_commands = 0;
1685 : : }
1686 : 44 : break;
1687 : 124 : case PSQL_SEND_GET_RESULTS:
1688 [ + + + + ]: 124 : 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 : 16 : pg_log_info("No pending results to get");
1697 : 16 : success = false;
1698 : 16 : pset.requested_results = 0;
1699 : : }
1700 : : else
1701 : : {
1702 : 108 : success = true;
1703 : :
1704 : : /*
1705 : : * Cap requested_results to the maximum number of known
1706 : : * results.
1707 : : */
1708 [ + + ]: 108 : if (pset.requested_results == 0 ||
1709 [ - + ]: 44 : pset.requested_results > (pset.available_results + pset.piped_syncs))
1710 : 64 : pset.requested_results = pset.available_results + pset.piped_syncs;
1711 : : }
1712 : 124 : break;
1713 : 260835 : case PSQL_SEND_QUERY:
1714 [ + + ]: 260835 : if (PQpipelineStatus(pset.db) != PQ_PIPELINE_OFF)
1715 : : {
1716 : 76 : success = PQsendQueryParams(pset.db, query,
1717 : : 0, NULL, NULL, NULL, NULL, 0);
1718 [ + - ]: 76 : if (success)
1719 : 76 : pset.piped_commands++;
1720 : : }
1721 : : else
1722 : 260759 : success = PQsendQuery(pset.db, query);
1723 : 260835 : break;
1724 : : }
1725 : :
1726 [ + + ]: 262240 : if (!success)
1727 : : {
1728 : 32 : const char *error = PQerrorMessage(pset.db);
1729 : :
1730 [ + + ]: 32 : if (strlen(error))
1731 : 4 : pg_log_info("%s", error);
1732 : :
1733 : 32 : CheckConnection();
1734 : :
1735 : 32 : SetPipelineVariables();
1736 : :
1737 : 32 : return -1;
1738 : : }
1739 : :
1740 [ + + + - : 524087 : if (pset.requested_results == 0 && !end_pipeline &&
+ + ]
1741 : 261879 : 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 : 961 : SetPipelineVariables();
1749 : 961 : 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 [ + + + - ]: 261247 : if (pset.fetch_count > 0 && pset.show_all_results &&
1770 [ + - + + ]: 89 : !pset.crosstab_flag && !pset.gexec_flag &&
1771 [ + + + - ]: 85 : !pset.gset_prefix && !is_watch)
1772 : : {
1773 [ + + ]: 69 : if (!PQsetChunkedRowsMode(pset.db, pset.fetch_count))
1774 : 4 : 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 [ + + - + ]: 261247 : if (is_watch && CancelRequested)
1783 : : {
1784 : 0 : ClearOrSaveAllResults();
1785 : 0 : 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 [ + + ]: 261247 : 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 : 2206 : scan_state = psql_scan_create(&psqlscan_callbacks);
1800 : 2206 : psql_scan_setup(scan_state, query, strlen(query),
1801 : 2206 : pset.encoding, standard_strings());
1802 : 2206 : 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 : : do
1810 : : {
1811 : 3038 : scan_result = psql_scan(scan_state, query_buf, &prompt_tmp);
1812 [ + + ]: 3038 : } while (scan_result == PSCAN_SEMICOLON);
1813 : :
1814 : : /*
1815 : : * We expect the result now to be PSCAN_EOL. If it is PSCAN_BACKSLASH
1816 : : * or PSCAN_INCOMPLETE, the server will get a parse error and refuse
1817 : : * to execute any part of the command string, so don't expect any
1818 : : * PGRES_COPY_IN results. (This will mean that we don't attempt to
1819 : : * discard any following data, but this seems consistent with the
1820 : : * general contract of psql_scan_count_copy_from_stdin, which is that
1821 : : * it only promises to count syntactically-valid COPY commands.)
1822 : : */
1823 [ + + ]: 2206 : if (scan_result == PSCAN_EOL)
1824 : 2189 : num_copy_from_stdin = psql_scan_count_copy_from_stdin(scan_state);
1825 : : else
1826 : 17 : num_copy_from_stdin = 0;
1827 : :
1828 : 2206 : destroyPQExpBuffer(query_buf);
1829 : 2206 : psql_scan_destroy(scan_state);
1830 : : }
1831 : :
1832 : : /* first result */
1833 : 261247 : result = PQgetResult(pset.db);
1834 [ + + + - ]: 261247 : if (min_rows > 0 && PQntuples(result) < min_rows)
1835 : : {
1836 : 1 : return_early = true;
1837 : : }
1838 : :
1839 [ + + ]: 524008 : while (result != NULL)
1840 : : {
1841 : : ExecStatusType result_status;
1842 : 262777 : bool is_chunked_result = false;
1843 : 262777 : PGresult *next_result = NULL;
1844 : : bool last;
1845 : :
1846 [ + + ]: 262777 : if (!AcceptResult(result, false))
1847 : 31107 : {
1848 : : /*
1849 : : * Some error occurred, either a server-side failure or a failure
1850 : : * to submit the command string. Record that.
1851 : : */
1852 : 31119 : const char *error = PQresultErrorMessage(result);
1853 : :
1854 [ + + ]: 31119 : if (strlen(error))
1855 : 31098 : pg_log_info("%s", error);
1856 : :
1857 : 31119 : CheckConnection();
1858 [ + + ]: 31107 : if (!is_watch)
1859 : 31105 : SetResultVariables(result, false);
1860 : :
1861 : : /* keep the result status before clearing it */
1862 : 31107 : result_status = PQresultStatus(result);
1863 : 31107 : ClearOrSaveResult(result);
1864 : 31107 : success = false;
1865 : :
1866 [ + + ]: 31107 : if (result_status == PGRES_PIPELINE_ABORTED)
1867 : 20 : pg_log_info("Pipeline aborted, command did not run");
1868 : :
1869 : : /*
1870 : : * switch to next result
1871 : : */
1872 [ + + + - ]: 31107 : if (result_status == PGRES_COPY_BOTH ||
1873 [ - + ]: 31106 : result_status == PGRES_COPY_OUT ||
1874 : : result_status == PGRES_COPY_IN)
1875 : : {
1876 : : /*
1877 : : * For some obscure reason PQgetResult does *not* return a
1878 : : * NULL in copy cases despite the result having been cleared,
1879 : : * but keeps returning an "empty" result that we have to
1880 : : * ignore manually.
1881 : : */
1882 : 1 : result = NULL;
1883 : : }
1884 [ + + + + ]: 31106 : else if ((end_pipeline || pset.requested_results > 0)
1885 [ + - ]: 108 : && PQpipelineStatus(pset.db) != PQ_PIPELINE_OFF)
1886 : : {
1887 : : /*
1888 : : * Error within a pipeline. All commands are aborted until
1889 : : * the next synchronisation point. We need to consume all the
1890 : : * results until this synchronisation point, or stop when
1891 : : * there are no more result to discard.
1892 : : *
1893 : : * Checking the pipeline status is necessary for the case
1894 : : * where the connection was reset. The new connection is not
1895 : : * in any kind of pipeline state and thus has no result to
1896 : : * discard.
1897 : : */
1898 : 108 : result = discardAbortedPipelineResults();
1899 : : }
1900 : : else
1901 : 30998 : result = PQgetResult(pset.db);
1902 : :
1903 : : /*
1904 : : * Get current timing measure in case an error occurs
1905 : : */
1906 [ + + ]: 31107 : if (timing)
1907 : : {
1908 : 1 : INSTR_TIME_SET_CURRENT(after);
1909 : 1 : INSTR_TIME_SUBTRACT(after, before);
1910 : 1 : *elapsed_msec = INSTR_TIME_GET_MILLISEC(after);
1911 : : }
1912 : :
1913 : 31107 : continue;
1914 : : }
1915 [ + + + + ]: 231658 : else if (svpt_gone_p && !*svpt_gone_p)
1916 : : {
1917 : : /*
1918 : : * Check if the user ran any command that would destroy our
1919 : : * internal savepoint: If the user did COMMIT AND CHAIN, RELEASE
1920 : : * or ROLLBACK, our savepoint is gone. If they issued a SAVEPOINT,
1921 : : * releasing ours would remove theirs.
1922 : : */
1923 : 231500 : const char *cmd = PQcmdStatus(result);
1924 : :
1925 : 690511 : *svpt_gone_p = (strcmp(cmd, "COMMIT") == 0 ||
1926 [ + + ]: 227511 : strcmp(cmd, "SAVEPOINT") == 0 ||
1927 [ + + + + ]: 685629 : strcmp(cmd, "RELEASE") == 0 ||
1928 [ + + ]: 458118 : strcmp(cmd, "ROLLBACK") == 0);
1929 : : }
1930 : :
1931 : 231658 : result_status = PQresultStatus(result);
1932 : :
1933 : : /* must handle COPY before changing the current result */
1934 : : Assert(result_status != PGRES_COPY_BOTH);
1935 [ + + + + ]: 231658 : if (result_status == PGRES_COPY_IN ||
1936 : : result_status == PGRES_COPY_OUT)
1937 : : {
1938 : 1187 : FILE *copy_stream = NULL;
1939 : :
1940 [ + + ]: 1187 : if (PQpipelineStatus(pset.db) != PQ_PIPELINE_OFF)
1941 : : {
1942 : : /*
1943 : : * Running COPY within a pipeline can break the protocol
1944 : : * synchronisation in multiple ways, and psql shows its limits
1945 : : * when it comes to tracking this information.
1946 : : *
1947 : : * While in COPY mode, the backend process ignores additional
1948 : : * Sync messages and will not send the matching ReadyForQuery
1949 : : * expected by the frontend.
1950 : : *
1951 : : * Additionally, libpq automatically sends a Sync with the
1952 : : * Copy message, creating an unexpected synchronisation point.
1953 : : * A failure during COPY would leave the pipeline in an
1954 : : * aborted state while the backend would be in a clean state,
1955 : : * ready to process commands.
1956 : : *
1957 : : * Improving those issues would require modifications in how
1958 : : * libpq handles pipelines and COPY. Hence, for the time
1959 : : * being, we forbid the use of COPY within a pipeline,
1960 : : * aborting the connection to avoid an inconsistent state on
1961 : : * psql side if trying to use a COPY command.
1962 : : */
1963 : 4 : pg_log_info("COPY in a pipeline is not supported, aborting connection");
1964 : 4 : exit(EXIT_BADCONN);
1965 : : }
1966 : :
1967 : : /* Select data source or sink. */
1968 [ + + ]: 1183 : if (result_status == PGRES_COPY_OUT)
1969 : : {
1970 : : /*
1971 : : * For COPY OUT, direct the output to the default place
1972 : : * (probably a pager pipe) for \watch, or to pset.copyStream
1973 : : * for \copy, otherwise to pset.gfname if that's set,
1974 : : * otherwise to pset.queryFout.
1975 : : */
1976 [ - + ]: 501 : if (is_watch)
1977 : : {
1978 : : /* invoked by \watch */
1979 [ # # ]: 0 : copy_stream = printQueryFout ? printQueryFout : pset.queryFout;
1980 : : }
1981 [ + + ]: 501 : else if (pset.copyStream)
1982 : : {
1983 : : /* invoked by \copy */
1984 : 36 : copy_stream = pset.copyStream;
1985 : : }
1986 [ + + ]: 465 : else if (pset.gfname)
1987 : : {
1988 : : /* COPY followed by \g filename or \g |program */
1989 : 17 : success &= SetupGOutput(&gfile_fout, &gfile_is_pipe);
1990 [ + - ]: 17 : if (gfile_fout)
1991 : 17 : copy_stream = gfile_fout;
1992 : : }
1993 : : else
1994 : : {
1995 : : /* fall back to the generic query output stream */
1996 : 448 : copy_stream = pset.queryFout;
1997 : : }
1998 : : }
1999 : : else
2000 : : {
2001 [ - + ]: 682 : if (num_copy_from_stdin <= 0)
2002 : : {
2003 : : /*
2004 : : * We didn't send a COPY FROM STDIN command. The server
2005 : : * is broken or possibly malicious. Report and quit. (We
2006 : : * could instead send an empty COPY response, but it's not
2007 : : * clear that that's a better behavior; it would make it
2008 : : * harder to diagnose any such problem.)
2009 : : */
2010 : 0 : pg_log_info("unexpected COPY_IN result, aborting connection");
2011 : 0 : exit(EXIT_BADCONN);
2012 : : }
2013 : : /* Keep track of the number of remaining copy operations */
2014 : 682 : num_copy_from_stdin--;
2015 : :
2016 : : /*
2017 : : * For COPY IN, read from pset.copyStream if \copy set that,
2018 : : * otherwise from the current command source.
2019 : : */
2020 [ + + ]: 682 : if (pset.copyStream)
2021 : 47 : copy_stream = pset.copyStream;
2022 : : else
2023 : 635 : copy_stream = pset.cur_cmd_source;
2024 : : }
2025 : :
2026 : : /*
2027 : : * Even if the output stream could not be opened, we call
2028 : : * HandleCopyResult() with a NULL output stream to collect and
2029 : : * discard the COPY data.
2030 : : */
2031 : 1183 : success &= HandleCopyResult(&result, copy_stream);
2032 : : }
2033 : :
2034 : : /* If we have a chunked result, collect and print all chunks */
2035 [ + + ]: 231654 : if (result_status == PGRES_TUPLES_CHUNK)
2036 : : {
2037 [ + - ]: 44 : FILE *tuples_fout = printQueryFout ? printQueryFout : pset.queryFout;
2038 [ - + ]: 44 : printQueryOpt my_popt = opt ? *opt : pset.popt;
2039 : 44 : int64 total_tuples = 0;
2040 : 44 : bool is_pager = false;
2041 : 44 : int flush_error = 0;
2042 : :
2043 : : /* initialize print options for partial table output */
2044 : 44 : my_popt.topt.start_table = true;
2045 : 44 : my_popt.topt.stop_table = false;
2046 : 44 : my_popt.topt.prior_records = 0;
2047 : :
2048 : : /* open \g file if needed */
2049 : 44 : success &= SetupGOutput(&gfile_fout, &gfile_is_pipe);
2050 [ - + ]: 44 : if (gfile_fout)
2051 : 0 : tuples_fout = gfile_fout;
2052 : :
2053 : : /* force use of pager for any chunked resultset going to stdout */
2054 [ + - + - ]: 44 : if (success && tuples_fout == stdout)
2055 : : {
2056 : 44 : tuples_fout = PageOutput(INT_MAX, &(my_popt.topt));
2057 : 44 : is_pager = true;
2058 : : }
2059 : :
2060 : : do
2061 : : {
2062 : : /*
2063 : : * Display the current chunk of results, unless the output
2064 : : * stream stopped working or we got canceled. We skip use of
2065 : : * PrintQueryResult and go directly to printQuery, so that we
2066 : : * can pass the correct is_pager value and because we don't
2067 : : * want PrintQueryStatus to happen yet. Above, we rejected
2068 : : * use of chunking for all cases in which PrintQueryResult
2069 : : * would send the result to someplace other than printQuery.
2070 : : */
2071 [ + - + - : 60 : if (success && !flush_error && !CancelRequested)
+ - ]
2072 : : {
2073 : 60 : printQuery(result, &my_popt, tuples_fout, is_pager, pset.logfile);
2074 : 60 : flush_error = fflush(tuples_fout);
2075 : : }
2076 : :
2077 : : /* after the first result set, disallow header decoration */
2078 : 60 : my_popt.topt.start_table = false;
2079 : :
2080 : : /* count tuples before dropping the result */
2081 : 60 : my_popt.topt.prior_records += PQntuples(result);
2082 : 60 : total_tuples += PQntuples(result);
2083 : :
2084 : 60 : ClearOrSaveResult(result);
2085 : :
2086 : : /* get the next result, loop if it's PGRES_TUPLES_CHUNK */
2087 : 60 : result = PQgetResult(pset.db);
2088 [ + + ]: 60 : } while (PQresultStatus(result) == PGRES_TUPLES_CHUNK);
2089 : :
2090 : : /* We expect an empty PGRES_TUPLES_OK, else there's a problem */
2091 [ + + ]: 44 : if (PQresultStatus(result) == PGRES_TUPLES_OK)
2092 : : {
2093 : : char buf[32];
2094 : :
2095 : : Assert(PQntuples(result) == 0);
2096 : :
2097 : : /* Display the footer using the empty result */
2098 [ + - + - : 40 : if (success && !flush_error && !CancelRequested)
+ - ]
2099 : : {
2100 : 40 : my_popt.topt.stop_table = true;
2101 : 40 : printQuery(result, &my_popt, tuples_fout, is_pager, pset.logfile);
2102 : 40 : fflush(tuples_fout);
2103 : : }
2104 : :
2105 [ + - ]: 40 : if (is_pager)
2106 : 40 : ClosePager(tuples_fout);
2107 : :
2108 : : /*
2109 : : * It's possible the data is from a RETURNING clause, in which
2110 : : * case we need to print query status.
2111 : : */
2112 : 40 : PrintQueryStatus(result, printQueryFout);
2113 : :
2114 : : /*
2115 : : * We must do a fake SetResultVariables(), since we don't have
2116 : : * a PGresult corresponding to the whole query.
2117 : : */
2118 : 40 : SetVariable(pset.vars, "ERROR", "false");
2119 : 40 : SetVariable(pset.vars, "SQLSTATE", "00000");
2120 : 40 : snprintf(buf, sizeof(buf), INT64_FORMAT, total_tuples);
2121 : 40 : SetVariable(pset.vars, "ROW_COUNT", buf);
2122 : : /* Prevent SetResultVariables call below */
2123 : 40 : is_chunked_result = true;
2124 : :
2125 : : /* Clear the empty result so it isn't printed below */
2126 : 40 : ClearOrSaveResult(result);
2127 : 40 : result = NULL;
2128 : : }
2129 : : else
2130 : : {
2131 : : /* Probably an error report, so close the pager and print it */
2132 [ + - ]: 4 : if (is_pager)
2133 : 4 : ClosePager(tuples_fout);
2134 : :
2135 : 4 : success &= AcceptResult(result, true);
2136 : : /* SetResultVariables and ClearOrSaveResult happen below */
2137 : : }
2138 : : }
2139 : :
2140 [ + + ]: 231654 : if (result_status == PGRES_PIPELINE_SYNC)
2141 : : {
2142 : : /*
2143 : : * Sync response, decrease the sync and requested_results
2144 : : * counters. Guard against underflow: an error during Sync
2145 : : * processing on the server can cause the client-side counter to
2146 : : * drift.
2147 : : */
2148 [ + - ]: 289 : if (pset.piped_syncs > 0)
2149 : 289 : pset.piped_syncs--;
2150 [ + - ]: 289 : if (pset.requested_results > 0)
2151 : 289 : pset.requested_results--;
2152 : :
2153 : : /*
2154 : : * After a synchronisation point, reset success state to print
2155 : : * possible successful results that will be processed after this.
2156 : : */
2157 : 289 : success = true;
2158 : :
2159 : : /*
2160 : : * If all syncs were processed and pipeline end was requested,
2161 : : * exit pipeline mode.
2162 : : */
2163 [ + + + + ]: 289 : if (end_pipeline && pset.piped_syncs == 0)
2164 : 197 : success &= PQexitPipelineMode(pset.db);
2165 : : }
2166 [ + + + - ]: 231365 : else if (PQpipelineStatus(pset.db) != PQ_PIPELINE_OFF &&
2167 : : result_status != PGRES_PIPELINE_SYNC)
2168 : : {
2169 : : /*
2170 : : * In a pipeline with a non-sync response? Decrease the result
2171 : : * counters.
2172 : : */
2173 [ + + ]: 442 : if (pset.available_results > 0)
2174 : 438 : pset.available_results--;
2175 [ + - ]: 442 : if (pset.requested_results > 0)
2176 : 442 : pset.requested_results--;
2177 : : }
2178 : :
2179 : : /*
2180 : : * Check PQgetResult() again. In the typical case of a single-command
2181 : : * string, it will return NULL. Otherwise, we'll have other results
2182 : : * to process. We need to do that to check whether this is the last.
2183 : : */
2184 [ + + ]: 231654 : if (PQpipelineStatus(pset.db) == PQ_PIPELINE_OFF)
2185 : 231120 : next_result = PQgetResult(pset.db);
2186 : : else
2187 : : {
2188 : : /*
2189 : : * In pipeline mode, a NULL result indicates the end of the
2190 : : * current query being processed. Call PQgetResult() once to
2191 : : * consume this state.
2192 : : */
2193 [ + + ]: 534 : if (result_status != PGRES_PIPELINE_SYNC)
2194 : : {
2195 : 442 : next_result = PQgetResult(pset.db);
2196 : : Assert(next_result == NULL);
2197 : : }
2198 : :
2199 : : /* Now, we can get the next result in the pipeline. */
2200 [ + + ]: 534 : if (pset.requested_results > 0)
2201 : 462 : next_result = PQgetResult(pset.db);
2202 : : }
2203 : :
2204 : 231654 : last = (next_result == NULL);
2205 : :
2206 : : /*
2207 : : * Update current timing measure.
2208 : : *
2209 : : * It will include the display of previous results, if any. This
2210 : : * cannot be helped because the server goes on processing further
2211 : : * queries anyway while the previous ones are being displayed. The
2212 : : * parallel execution of the client display hides the server time when
2213 : : * it is shorter.
2214 : : *
2215 : : * With combined queries, timing must be understood as an upper bound
2216 : : * of the time spent processing them.
2217 : : */
2218 [ + + ]: 231654 : if (timing)
2219 : : {
2220 : 1 : INSTR_TIME_SET_CURRENT(after);
2221 : 1 : INSTR_TIME_SUBTRACT(after, before);
2222 : 1 : *elapsed_msec = INSTR_TIME_GET_MILLISEC(after);
2223 : : }
2224 : :
2225 : : /*
2226 : : * This may or may not print something depending on settings.
2227 : : *
2228 : : * A pipeline sync will have a non-NULL result but does not have
2229 : : * anything to print, thus ignore results in this case.
2230 : : */
2231 [ + + + + ]: 231654 : if (result != NULL && result_status != PGRES_PIPELINE_SYNC)
2232 : : {
2233 : : /*
2234 : : * If results need to be printed into the file specified by \g,
2235 : : * open it, unless we already did. Note that when pset.gfname is
2236 : : * set, the passed-in value of printQueryFout is not used for
2237 : : * tuple output, but it's still used for status output.
2238 : : */
2239 : 230841 : FILE *tuples_fout = printQueryFout;
2240 : :
2241 [ + + ]: 230841 : if (PQresultStatus(result) == PGRES_TUPLES_OK)
2242 : 98214 : success &= SetupGOutput(&gfile_fout, &gfile_is_pipe);
2243 [ + + ]: 230841 : if (gfile_fout)
2244 : 38 : tuples_fout = gfile_fout;
2245 [ + + ]: 230841 : if (success)
2246 : 230664 : success &= PrintQueryResult(result, last, opt,
2247 : : tuples_fout, printQueryFout);
2248 : : }
2249 : :
2250 : : /* set variables from last result, unless dealt with elsewhere */
2251 [ + + + + : 231654 : if (last && !is_watch && !is_chunked_result)
+ + ]
2252 : 230045 : SetResultVariables(result, success);
2253 : :
2254 : 231654 : ClearOrSaveResult(result);
2255 : 231654 : result = next_result;
2256 : :
2257 [ - + - - ]: 231654 : if (CancelRequested && PQpipelineStatus(pset.db) == PQ_PIPELINE_OFF)
2258 : : {
2259 : : /*
2260 : : * Outside of a pipeline, drop the next result, as well as any
2261 : : * others not yet read.
2262 : : *
2263 : : * Within a pipeline, we can let the outer loop handle this as an
2264 : : * aborted pipeline, which will discard then all the results.
2265 : : */
2266 : 0 : ClearOrSaveResult(result);
2267 : 0 : ClearOrSaveAllResults();
2268 : 0 : break;
2269 : : }
2270 : : }
2271 : :
2272 : : /* close \g file if we opened it */
2273 : 261231 : CloseGOutput(gfile_fout, gfile_is_pipe);
2274 : :
2275 [ + + ]: 261231 : if (end_pipeline)
2276 : : {
2277 : : /*
2278 : : * Reset available/requested results. Normally these are already 0,
2279 : : * but an error generated by a Sync processing itself can leave some
2280 : : * of them behind. Consume them before exiting pipeline mode.
2281 : : */
2282 [ + + ]: 237 : while (pset.piped_syncs > 0)
2283 : : {
2284 : : PGresult *remaining;
2285 : :
2286 : 20 : remaining = PQgetResult(pset.db);
2287 : :
2288 [ - + ]: 20 : if (remaining == NULL)
2289 : : {
2290 [ # # ]: 0 : if (!ConnectionUp())
2291 : 0 : break;
2292 : 0 : continue;
2293 : : }
2294 [ + - ]: 20 : if (PQresultStatus(remaining) == PGRES_PIPELINE_SYNC)
2295 : 20 : pset.piped_syncs--;
2296 : 20 : PQclear(remaining);
2297 : : }
2298 : 217 : pset.piped_syncs = 0;
2299 : 217 : pset.piped_commands = 0;
2300 : 217 : pset.available_results = 0;
2301 : 217 : pset.requested_results = 0;
2302 : :
2303 [ + + ]: 217 : if (PQpipelineStatus(pset.db) != PQ_PIPELINE_OFF)
2304 : 20 : PQexitPipelineMode(pset.db);
2305 : : }
2306 : : Assert(pset.requested_results == 0);
2307 : :
2308 : 261231 : SetPipelineVariables();
2309 : :
2310 : : /* may need this to recover from conn loss during COPY */
2311 [ - + ]: 261231 : if (!CheckConnection())
2312 : 0 : return -1;
2313 : :
2314 : : /*
2315 : : * If we were expecting COPY ... FROM STDIN, and we didn't get
2316 : : * PGRES_COPY_IN (presumably because the COPY failed server-side), and the
2317 : : * data is supposed to come from the current command source, we must eat
2318 : : * up the data in order to stay in sync with the command file's contents.
2319 : : * Repeat for the number of unfulfilled COPY commands.
2320 : : */
2321 [ + + ]: 261536 : while (num_copy_from_stdin > 0)
2322 : : {
2323 [ + + ]: 305 : if (pset.copyStream == NULL ||
2324 [ + + ]: 5 : pset.copyStream == pset.cur_cmd_source)
2325 : 304 : (void) handleCopyIn(NULL, /* no connection */
2326 : : pset.cur_cmd_source,
2327 : : false, /* XXX assume not binary */
2328 : : NULL); /* no result */
2329 : 305 : num_copy_from_stdin--;
2330 : : }
2331 : :
2332 [ + + + + ]: 261231 : if (CancelRequested || return_early)
2333 : 2 : return 0;
2334 : :
2335 [ + + ]: 261229 : return success ? 1 : -1;
2336 : : }
2337 : :
2338 : :
2339 : : /*
2340 : : * Advance the given char pointer over white space and SQL comments.
2341 : : */
2342 : : static const char *
2343 : 72 : skip_white_space(const char *query)
2344 : : {
2345 : 72 : int cnestlevel = 0; /* slash-star comment nest level */
2346 : :
2347 [ + - ]: 88 : while (*query)
2348 : : {
2349 : 88 : int mblen = PQmblenBounded(query, pset.encoding);
2350 : :
2351 : : /*
2352 : : * Note: we assume the encoding is a superset of ASCII, so that for
2353 : : * example "query[0] == '/'" is meaningful. However, we do NOT assume
2354 : : * that the second and subsequent bytes of a multibyte character
2355 : : * couldn't look like ASCII characters; so it is critical to advance
2356 : : * by mblen, not 1, whenever we haven't exactly identified the
2357 : : * character we are skipping over.
2358 : : */
2359 [ + + ]: 88 : if (isspace((unsigned char) *query))
2360 : 16 : query += mblen;
2361 [ - + - - ]: 72 : else if (query[0] == '/' && query[1] == '*')
2362 : : {
2363 : 0 : cnestlevel++;
2364 : 0 : query += 2;
2365 : : }
2366 [ - + - - : 72 : else if (cnestlevel > 0 && query[0] == '*' && query[1] == '/')
- - ]
2367 : : {
2368 : 0 : cnestlevel--;
2369 : 0 : query += 2;
2370 : : }
2371 [ + - - + : 72 : else if (cnestlevel == 0 && query[0] == '-' && query[1] == '-')
- - ]
2372 : : {
2373 : 0 : query += 2;
2374 : :
2375 : : /*
2376 : : * We have to skip to end of line since any slash-star inside the
2377 : : * -- comment does NOT start a slash-star comment.
2378 : : */
2379 [ # # ]: 0 : while (*query)
2380 : : {
2381 [ # # ]: 0 : if (*query == '\n')
2382 : : {
2383 : 0 : query++;
2384 : 0 : break;
2385 : : }
2386 : 0 : query += PQmblenBounded(query, pset.encoding);
2387 : : }
2388 : : }
2389 [ - + ]: 72 : else if (cnestlevel > 0)
2390 : 0 : query += mblen;
2391 : : else
2392 : 72 : break; /* found first token */
2393 : : }
2394 : :
2395 : 72 : return query;
2396 : : }
2397 : :
2398 : :
2399 : : /*
2400 : : * Check whether a command is one of those for which we should NOT start
2401 : : * a new transaction block (ie, send a preceding BEGIN).
2402 : : *
2403 : : * These include the transaction control statements themselves, plus
2404 : : * certain statements that the backend disallows inside transaction blocks.
2405 : : */
2406 : : static bool
2407 : 56 : command_no_begin(const char *query)
2408 : : {
2409 : : int wordlen;
2410 : :
2411 : : /*
2412 : : * First we must advance over any whitespace and comments.
2413 : : */
2414 : 56 : query = skip_white_space(query);
2415 : :
2416 : : /*
2417 : : * Check word length (since "beginx" is not "begin").
2418 : : */
2419 : 56 : wordlen = 0;
2420 [ + + ]: 376 : while (isalpha((unsigned char) query[wordlen]))
2421 : 320 : wordlen += PQmblenBounded(&query[wordlen], pset.encoding);
2422 : :
2423 : : /*
2424 : : * Transaction control commands. These should include every keyword that
2425 : : * gives rise to a TransactionStmt in the backend grammar, except for the
2426 : : * savepoint-related commands.
2427 : : *
2428 : : * (We assume that START must be START TRANSACTION, since there is
2429 : : * presently no other "START foo" command.)
2430 : : */
2431 [ + + - + ]: 56 : if (wordlen == 5 && pg_strncasecmp(query, "abort", 5) == 0)
2432 : 0 : return true;
2433 [ + + + - ]: 56 : if (wordlen == 5 && pg_strncasecmp(query, "begin", 5) == 0)
2434 : 8 : return true;
2435 [ - + - - ]: 48 : if (wordlen == 5 && pg_strncasecmp(query, "start", 5) == 0)
2436 : 0 : return true;
2437 [ + + - + ]: 48 : if (wordlen == 6 && pg_strncasecmp(query, "commit", 6) == 0)
2438 : 0 : return true;
2439 [ - + - - ]: 48 : if (wordlen == 3 && pg_strncasecmp(query, "end", 3) == 0)
2440 : 0 : return true;
2441 [ - + - - ]: 48 : if (wordlen == 8 && pg_strncasecmp(query, "rollback", 8) == 0)
2442 : 0 : return true;
2443 [ - + - - ]: 48 : if (wordlen == 7 && pg_strncasecmp(query, "prepare", 7) == 0)
2444 : : {
2445 : : /* PREPARE TRANSACTION is a TC command, PREPARE foo is not */
2446 : 0 : query += wordlen;
2447 : :
2448 : 0 : query = skip_white_space(query);
2449 : :
2450 : 0 : wordlen = 0;
2451 [ # # ]: 0 : while (isalpha((unsigned char) query[wordlen]))
2452 : 0 : wordlen += PQmblenBounded(&query[wordlen], pset.encoding);
2453 : :
2454 [ # # # # ]: 0 : if (wordlen == 11 && pg_strncasecmp(query, "transaction", 11) == 0)
2455 : 0 : return true;
2456 : 0 : return false;
2457 : : }
2458 : :
2459 : : /*
2460 : : * Commands not allowed within transactions. The statements checked for
2461 : : * here should be exactly those that call PreventInTransactionBlock() in
2462 : : * the backend.
2463 : : */
2464 [ + + - + ]: 48 : if (wordlen == 6 && pg_strncasecmp(query, "vacuum", 6) == 0)
2465 : 0 : return true;
2466 [ - + - - ]: 48 : if (wordlen == 7 && pg_strncasecmp(query, "cluster", 7) == 0)
2467 : : {
2468 : : /* CLUSTER with any arguments is allowed in transactions */
2469 : 0 : query += wordlen;
2470 : :
2471 : 0 : query = skip_white_space(query);
2472 : :
2473 [ # # ]: 0 : if (isalpha((unsigned char) query[0]))
2474 : 0 : return false; /* has additional words */
2475 : 0 : return true; /* it's CLUSTER without arguments */
2476 : : }
2477 : :
2478 [ + + + + ]: 48 : if (wordlen == 6 && pg_strncasecmp(query, "create", 6) == 0)
2479 : : {
2480 : 8 : query += wordlen;
2481 : :
2482 : 8 : query = skip_white_space(query);
2483 : :
2484 : 8 : wordlen = 0;
2485 [ + + ]: 48 : while (isalpha((unsigned char) query[wordlen]))
2486 : 40 : wordlen += PQmblenBounded(&query[wordlen], pset.encoding);
2487 : :
2488 [ - + - - ]: 8 : if (wordlen == 8 && pg_strncasecmp(query, "database", 8) == 0)
2489 : 0 : return true;
2490 [ - + - - ]: 8 : if (wordlen == 10 && pg_strncasecmp(query, "tablespace", 10) == 0)
2491 : 0 : return true;
2492 : :
2493 : : /* CREATE [UNIQUE] INDEX CONCURRENTLY isn't allowed in xacts */
2494 [ - + - - ]: 8 : if (wordlen == 6 && pg_strncasecmp(query, "unique", 6) == 0)
2495 : : {
2496 : 0 : query += wordlen;
2497 : :
2498 : 0 : query = skip_white_space(query);
2499 : :
2500 : 0 : wordlen = 0;
2501 [ # # ]: 0 : while (isalpha((unsigned char) query[wordlen]))
2502 : 0 : wordlen += PQmblenBounded(&query[wordlen], pset.encoding);
2503 : : }
2504 : :
2505 [ + - - + ]: 8 : if (wordlen == 5 && pg_strncasecmp(query, "index", 5) == 0)
2506 : : {
2507 : 0 : query += wordlen;
2508 : :
2509 : 0 : query = skip_white_space(query);
2510 : :
2511 : 0 : wordlen = 0;
2512 [ # # ]: 0 : while (isalpha((unsigned char) query[wordlen]))
2513 : 0 : wordlen += PQmblenBounded(&query[wordlen], pset.encoding);
2514 : :
2515 [ # # # # ]: 0 : if (wordlen == 12 && pg_strncasecmp(query, "concurrently", 12) == 0)
2516 : 0 : return true;
2517 : : }
2518 : :
2519 : 8 : return false;
2520 : : }
2521 : :
2522 [ - + - - ]: 40 : if (wordlen == 5 && pg_strncasecmp(query, "alter", 5) == 0)
2523 : : {
2524 : 0 : query += wordlen;
2525 : :
2526 : 0 : query = skip_white_space(query);
2527 : :
2528 : 0 : wordlen = 0;
2529 [ # # ]: 0 : while (isalpha((unsigned char) query[wordlen]))
2530 : 0 : wordlen += PQmblenBounded(&query[wordlen], pset.encoding);
2531 : :
2532 : : /* ALTER SYSTEM isn't allowed in xacts */
2533 [ # # # # ]: 0 : if (wordlen == 6 && pg_strncasecmp(query, "system", 6) == 0)
2534 : 0 : return true;
2535 : :
2536 : 0 : return false;
2537 : : }
2538 : :
2539 : : /*
2540 : : * Note: these tests will match DROP SYSTEM and REINDEX TABLESPACE, which
2541 : : * aren't really valid commands so we don't care much. The other four
2542 : : * possible matches are correct.
2543 : : */
2544 [ + + - + : 40 : if ((wordlen == 4 && pg_strncasecmp(query, "drop", 4) == 0) ||
- + ]
2545 [ # # ]: 0 : (wordlen == 7 && pg_strncasecmp(query, "reindex", 7) == 0))
2546 : : {
2547 : 4 : query += wordlen;
2548 : :
2549 : 4 : query = skip_white_space(query);
2550 : :
2551 : 4 : wordlen = 0;
2552 [ + + ]: 24 : while (isalpha((unsigned char) query[wordlen]))
2553 : 20 : wordlen += PQmblenBounded(&query[wordlen], pset.encoding);
2554 : :
2555 [ - + - - ]: 4 : if (wordlen == 8 && pg_strncasecmp(query, "database", 8) == 0)
2556 : 0 : return true;
2557 [ - + - - ]: 4 : if (wordlen == 6 && pg_strncasecmp(query, "system", 6) == 0)
2558 : 0 : return true;
2559 [ - + - - ]: 4 : if (wordlen == 10 && pg_strncasecmp(query, "tablespace", 10) == 0)
2560 : 0 : return true;
2561 [ + - + - : 8 : if (wordlen == 5 && (pg_strncasecmp(query, "index", 5) == 0 ||
+ - ]
2562 : 4 : pg_strncasecmp(query, "table", 5) == 0))
2563 : : {
2564 : 4 : query += wordlen;
2565 : 4 : query = skip_white_space(query);
2566 : 4 : wordlen = 0;
2567 [ + + ]: 16 : while (isalpha((unsigned char) query[wordlen]))
2568 : 12 : wordlen += PQmblenBounded(&query[wordlen], pset.encoding);
2569 : :
2570 : : /*
2571 : : * REINDEX [ TABLE | INDEX ] CONCURRENTLY are not allowed in
2572 : : * xacts.
2573 : : */
2574 [ - + - - ]: 4 : if (wordlen == 12 && pg_strncasecmp(query, "concurrently", 12) == 0)
2575 : 0 : return true;
2576 : : }
2577 : :
2578 : : /* DROP INDEX CONCURRENTLY isn't allowed in xacts */
2579 [ - + - - ]: 4 : if (wordlen == 5 && pg_strncasecmp(query, "index", 5) == 0)
2580 : : {
2581 : 0 : query += wordlen;
2582 : :
2583 : 0 : query = skip_white_space(query);
2584 : :
2585 : 0 : wordlen = 0;
2586 [ # # ]: 0 : while (isalpha((unsigned char) query[wordlen]))
2587 : 0 : wordlen += PQmblenBounded(&query[wordlen], pset.encoding);
2588 : :
2589 [ # # # # ]: 0 : if (wordlen == 12 && pg_strncasecmp(query, "concurrently", 12) == 0)
2590 : 0 : return true;
2591 : :
2592 : 0 : return false;
2593 : : }
2594 : :
2595 : 4 : return false;
2596 : : }
2597 : :
2598 : : /* DISCARD ALL isn't allowed in xacts, but other variants are allowed. */
2599 [ - + - - ]: 36 : if (wordlen == 7 && pg_strncasecmp(query, "discard", 7) == 0)
2600 : : {
2601 : 0 : query += wordlen;
2602 : :
2603 : 0 : query = skip_white_space(query);
2604 : :
2605 : 0 : wordlen = 0;
2606 [ # # ]: 0 : while (isalpha((unsigned char) query[wordlen]))
2607 : 0 : wordlen += PQmblenBounded(&query[wordlen], pset.encoding);
2608 : :
2609 [ # # # # ]: 0 : if (wordlen == 3 && pg_strncasecmp(query, "all", 3) == 0)
2610 : 0 : return true;
2611 : 0 : return false;
2612 : : }
2613 : :
2614 : 36 : return false;
2615 : : }
2616 : :
2617 : :
2618 : : /*
2619 : : * addQueryComment
2620 : : *
2621 : : * Reset buf and insert a comment holding label. The comment will show up
2622 : : * in -E output and in the server log.
2623 : : *
2624 : : * If it's safe, we attempt to translate the label string.
2625 : : * (addQueryComment is marked as a gettext trigger, so this requires no
2626 : : * special effort at call sites.)
2627 : : */
2628 : : void
2629 : 31595 : addQueryComment(PQExpBuffer buf, const char *label)
2630 : : {
2631 : : #if defined(ENABLE_NLS)
2632 : 31595 : const char *server_enc = PQparameterStatus(pset.db, "server_encoding");
2633 : 31595 : int client_enc = PQclientEncoding(pset.db);
2634 : :
2635 : : /*
2636 : : * We must skip translation if it would cause the server to reject the
2637 : : * query due to an encoding conversion/verification failure. For now it
2638 : : * seems sufficient to handle only the case of equal client and server
2639 : : * encodings: then the server just verifies the string in that encoding,
2640 : : * and we can run the same check here. It's necessary to check for this
2641 : : * because we can't be 100% sure which encoding gettext() thinks it should
2642 : : * produce. If it is indeed different from our client encoding, the
2643 : : * result may look like junk to a human, but it won't cause an error.
2644 : : */
2645 [ + - + - ]: 63190 : if (server_enc != NULL &&
2646 : 31595 : pg_char_to_encoding(server_enc) == client_enc)
2647 : : {
2648 : 31595 : const char *translated = _(label);
2649 : 31595 : int len = strlen(translated);
2650 : :
2651 [ + - ]: 31595 : if (pg_encoding_verifymbstr(client_enc, translated, len) == len)
2652 : 31595 : label = translated;
2653 : : }
2654 : : #endif
2655 : :
2656 : 31595 : printfPQExpBuffer(buf, "/* %s */\n", label);
2657 : 31595 : }
2658 : :
2659 : :
2660 : : /*
2661 : : * Test if the current user is a database superuser.
2662 : : */
2663 : : bool
2664 : 70 : is_superuser(void)
2665 : : {
2666 : : const char *val;
2667 : :
2668 [ - + ]: 70 : if (!pset.db)
2669 : 0 : return false;
2670 : :
2671 : 70 : val = PQparameterStatus(pset.db, "is_superuser");
2672 : :
2673 [ + - + - ]: 70 : if (val && strcmp(val, "on") == 0)
2674 : 70 : return true;
2675 : :
2676 : 0 : return false;
2677 : : }
2678 : :
2679 : :
2680 : : /*
2681 : : * Test if the current session uses standard string literals.
2682 : : */
2683 : : bool
2684 : 545442 : standard_strings(void)
2685 : : {
2686 : : const char *val;
2687 : :
2688 [ - + ]: 545442 : if (!pset.db)
2689 : 0 : return false;
2690 : :
2691 : 545442 : val = PQparameterStatus(pset.db, "standard_conforming_strings");
2692 : :
2693 [ + - + - ]: 545442 : if (val && strcmp(val, "on") == 0)
2694 : 545442 : return true;
2695 : :
2696 : 0 : return false;
2697 : : }
2698 : :
2699 : :
2700 : : /*
2701 : : * Return the session user of the current connection.
2702 : : */
2703 : : const char *
2704 : 0 : session_username(void)
2705 : : {
2706 : : const char *val;
2707 : :
2708 [ # # ]: 0 : if (!pset.db)
2709 : 0 : return NULL;
2710 : :
2711 : 0 : val = PQparameterStatus(pset.db, "session_authorization");
2712 [ # # ]: 0 : if (val)
2713 : 0 : return val;
2714 : : else
2715 : 0 : return PQuser(pset.db);
2716 : : }
2717 : :
2718 : : /*
2719 : : * Return the value of option for keyword in the current connection.
2720 : : *
2721 : : * The caller is responsible for freeing the result value allocated.
2722 : : */
2723 : : char *
2724 : 11529 : get_conninfo_value(const char *keyword)
2725 : : {
2726 : : PQconninfoOption *opts;
2727 : 11529 : PQconninfoOption *serviceopt = NULL;
2728 : 11529 : char *res = NULL;
2729 : :
2730 [ - + ]: 11529 : if (pset.db == NULL)
2731 : 0 : return NULL;
2732 : :
2733 : 11529 : opts = PQconninfo(pset.db);
2734 [ - + ]: 11529 : if (opts == NULL)
2735 : 0 : return NULL;
2736 : :
2737 [ + - ]: 11529 : for (PQconninfoOption *opt = opts; opt->keyword != NULL; ++opt)
2738 : : {
2739 [ + - ]: 11529 : if (strcmp(opt->keyword, keyword) == 0)
2740 : : {
2741 : 11529 : serviceopt = opt;
2742 : 11529 : break;
2743 : : }
2744 : : }
2745 : :
2746 : : /* Take a copy of the value, as it is freed by PQconninfoFree(). */
2747 [ + - + + ]: 11529 : if (serviceopt && serviceopt->val != NULL)
2748 : 12 : res = pg_strdup(serviceopt->val);
2749 : 11529 : PQconninfoFree(opts);
2750 : :
2751 : 11529 : return res;
2752 : : }
2753 : :
2754 : : /*
2755 : : * expand_tilde
2756 : : *
2757 : : * substitute '~' with HOME or '~username' with username's home dir
2758 : : *
2759 : : */
2760 : : void
2761 : 107 : expand_tilde(char **filename)
2762 : : {
2763 [ + - + + ]: 107 : if (!filename || !(*filename))
2764 : 12 : return;
2765 : :
2766 : : /*
2767 : : * WIN32 doesn't use tilde expansion for file names. Also, it uses tilde
2768 : : * for short versions of long file names, though the tilde is usually
2769 : : * toward the end, not at the beginning.
2770 : : */
2771 : : #ifndef WIN32
2772 : :
2773 : : /* try tilde expansion */
2774 [ - + ]: 95 : if (**filename == '~')
2775 : : {
2776 : : char *fn;
2777 : : char oldp,
2778 : : *p;
2779 : : struct passwd *pw;
2780 : : char home[MAXPGPATH];
2781 : :
2782 : 0 : fn = *filename;
2783 : 0 : *home = '\0';
2784 : :
2785 : 0 : p = fn + 1;
2786 [ # # # # ]: 0 : while (*p != '/' && *p != '\0')
2787 : 0 : p++;
2788 : :
2789 : 0 : oldp = *p;
2790 : 0 : *p = '\0';
2791 : :
2792 [ # # ]: 0 : if (*(fn + 1) == '\0')
2793 : 0 : get_home_path(home); /* ~ or ~/ only */
2794 [ # # ]: 0 : else if ((pw = getpwnam(fn + 1)) != NULL)
2795 : 0 : strlcpy(home, pw->pw_dir, sizeof(home)); /* ~user */
2796 : :
2797 : 0 : *p = oldp;
2798 [ # # ]: 0 : if (strlen(home) != 0)
2799 : : {
2800 : : char *newfn;
2801 : :
2802 : 0 : newfn = psprintf("%s%s", home, p);
2803 : 0 : free(fn);
2804 : 0 : *filename = newfn;
2805 : : }
2806 : : }
2807 : : #endif
2808 : : }
2809 : :
2810 : : /*
2811 : : * Checks if connection string starts with either of the valid URI prefix
2812 : : * designators.
2813 : : *
2814 : : * Returns the URI prefix length, 0 if the string doesn't contain a URI prefix.
2815 : : *
2816 : : * XXX This is a duplicate of the eponymous libpq function.
2817 : : */
2818 : : static int
2819 : 27 : uri_prefix_length(const char *connstr)
2820 : : {
2821 : : /* The connection URI must start with either of the following designators: */
2822 : : static const char uri_designator[] = "postgresql://";
2823 : : static const char short_uri_designator[] = "postgres://";
2824 : :
2825 [ - + ]: 27 : if (strncmp(connstr, uri_designator,
2826 : : sizeof(uri_designator) - 1) == 0)
2827 : 0 : return sizeof(uri_designator) - 1;
2828 : :
2829 [ - + ]: 27 : if (strncmp(connstr, short_uri_designator,
2830 : : sizeof(short_uri_designator) - 1) == 0)
2831 : 0 : return sizeof(short_uri_designator) - 1;
2832 : :
2833 : 27 : return 0;
2834 : : }
2835 : :
2836 : : /*
2837 : : * Reset state related to extended query protocol
2838 : : *
2839 : : * Clean up any state related to bind parameters, statement name and
2840 : : * PSQL_SEND_MODE. This needs to be called after processing a query or when
2841 : : * running a new meta-command that uses the extended query protocol, like
2842 : : * \parse, \bind, etc.
2843 : : */
2844 : : void
2845 : 262994 : clean_extended_state(void)
2846 : : {
2847 : : int i;
2848 : :
2849 [ + + + + : 262994 : switch (pset.send_mode)
- ]
2850 : : {
2851 : 25 : case PSQL_SEND_EXTENDED_CLOSE: /* \close_prepared */
2852 : 25 : free(pset.stmtName);
2853 : 25 : break;
2854 : 67 : case PSQL_SEND_EXTENDED_PARSE: /* \parse */
2855 : 67 : free(pset.stmtName);
2856 : 67 : break;
2857 : 644 : case PSQL_SEND_EXTENDED_QUERY_PARAMS: /* \bind */
2858 : : case PSQL_SEND_EXTENDED_QUERY_PREPARED: /* \bind_named */
2859 [ + + ]: 1199 : for (i = 0; i < pset.bind_nparams; i++)
2860 : 555 : free(pset.bind_params[i]);
2861 : 644 : free(pset.bind_params);
2862 : 644 : free(pset.stmtName);
2863 : 644 : pset.bind_params = NULL;
2864 : 644 : break;
2865 : 262258 : case PSQL_SEND_QUERY:
2866 : : case PSQL_SEND_START_PIPELINE_MODE: /* \startpipeline */
2867 : : case PSQL_SEND_END_PIPELINE_MODE: /* \endpipeline */
2868 : : case PSQL_SEND_PIPELINE_SYNC: /* \syncpipeline */
2869 : : case PSQL_SEND_FLUSH: /* \flush */
2870 : : case PSQL_SEND_GET_RESULTS: /* \getresults */
2871 : : case PSQL_SEND_FLUSH_REQUEST: /* \flushrequest */
2872 : 262258 : break;
2873 : : }
2874 : :
2875 : 262994 : pset.stmtName = NULL;
2876 : 262994 : pset.send_mode = PSQL_SEND_QUERY;
2877 : 262994 : }
2878 : :
2879 : : /*
2880 : : * Recognized connection string either starts with a valid URI prefix or
2881 : : * contains a "=" in it.
2882 : : *
2883 : : * Must be consistent with parse_connection_string: anything for which this
2884 : : * returns true should at least look like it's parseable by that routine.
2885 : : *
2886 : : * XXX This is a duplicate of the eponymous libpq function.
2887 : : */
2888 : : bool
2889 : 27 : recognized_connection_string(const char *connstr)
2890 : : {
2891 [ + - + + ]: 27 : return uri_prefix_length(connstr) != 0 || strchr(connstr, '=') != NULL;
2892 : : }
|