PostgreSQL Source Code  git master
common.c
Go to the documentation of this file.
1 /*
2  * psql - the PostgreSQL interactive terminal
3  *
4  * Copyright (c) 2000-2020, 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 <signal.h>
14 #ifndef WIN32
15 #include <unistd.h> /* for write() */
16 #else
17 #include <io.h> /* for _write() */
18 #include <win32.h>
19 #endif
20 
21 #include "command.h"
22 #include "common.h"
23 #include "common/logging.h"
24 #include "copy.h"
25 #include "crosstabview.h"
26 #include "fe_utils/cancel.h"
27 #include "fe_utils/mbprint.h"
28 #include "fe_utils/string_utils.h"
29 #include "portability/instr_time.h"
30 #include "settings.h"
31 
32 static bool DescribeQuery(const char *query, double *elapsed_msec);
33 static bool ExecQueryUsingCursor(const char *query, double *elapsed_msec);
34 static bool command_no_begin(const char *query);
35 static bool is_select_command(const char *query);
36 
37 
38 /*
39  * openQueryOutputFile --- attempt to open a query output file
40  *
41  * fname == NULL selects stdout, else an initial '|' selects a pipe,
42  * else plain file.
43  *
44  * Returns output file pointer into *fout, and is-a-pipe flag into *is_pipe.
45  * Caller is responsible for adjusting SIGPIPE state if it's a pipe.
46  *
47  * On error, reports suitable error message and returns false.
48  */
49 bool
50 openQueryOutputFile(const char *fname, FILE **fout, bool *is_pipe)
51 {
52  if (!fname || fname[0] == '\0')
53  {
54  *fout = stdout;
55  *is_pipe = false;
56  }
57  else if (*fname == '|')
58  {
59  *fout = popen(fname + 1, "w");
60  *is_pipe = true;
61  }
62  else
63  {
64  *fout = fopen(fname, "w");
65  *is_pipe = false;
66  }
67 
68  if (*fout == NULL)
69  {
70  pg_log_error("%s: %m", fname);
71  return false;
72  }
73 
74  return true;
75 }
76 
77 /*
78  * setQFout
79  * -- handler for -o command line option and \o command
80  *
81  * On success, updates pset with the new output file and returns true.
82  * On failure, returns false without changing pset state.
83  */
84 bool
85 setQFout(const char *fname)
86 {
87  FILE *fout;
88  bool is_pipe;
89 
90  /* First make sure we can open the new output file/pipe */
91  if (!openQueryOutputFile(fname, &fout, &is_pipe))
92  return false;
93 
94  /* Close old file/pipe */
95  if (pset.queryFout && pset.queryFout != stdout && pset.queryFout != stderr)
96  {
97  if (pset.queryFoutPipe)
98  pclose(pset.queryFout);
99  else
100  fclose(pset.queryFout);
101  }
102 
103  pset.queryFout = fout;
104  pset.queryFoutPipe = is_pipe;
105 
106  /* Adjust SIGPIPE handling appropriately: ignore signal if is_pipe */
107  set_sigpipe_trap_state(is_pipe);
109 
110  return true;
111 }
112 
113 
114 /*
115  * Variable-fetching callback for flex lexer
116  *
117  * If the specified variable exists, return its value as a string (malloc'd
118  * and expected to be freed by the caller); else return NULL.
119  *
120  * If "quote" isn't PQUOTE_PLAIN, then return the value suitably quoted and
121  * escaped for the specified quoting requirement. (Failure in escaping
122  * should lead to printing an error and returning NULL.)
123  *
124  * "passthrough" is the pointer previously given to psql_scan_set_passthrough.
125  * In psql, passthrough points to a ConditionalStack, which we check to
126  * determine whether variable expansion is allowed.
127  */
128 char *
129 psql_get_variable(const char *varname, PsqlScanQuoteType quote,
130  void *passthrough)
131 {
132  char *result = NULL;
133  const char *value;
134 
135  /* In an inactive \if branch, suppress all variable substitutions */
136  if (passthrough && !conditional_active((ConditionalStack) passthrough))
137  return NULL;
138 
139  value = GetVariable(pset.vars, varname);
140  if (!value)
141  return NULL;
142 
143  switch (quote)
144  {
145  case PQUOTE_PLAIN:
146  result = pg_strdup(value);
147  break;
148  case PQUOTE_SQL_LITERAL:
149  case PQUOTE_SQL_IDENT:
150  {
151  /*
152  * For these cases, we use libpq's quoting functions, which
153  * assume the string is in the connection's client encoding.
154  */
155  char *escaped_value;
156 
157  if (!pset.db)
158  {
159  pg_log_error("cannot escape without active connection");
160  return NULL;
161  }
162 
163  if (quote == PQUOTE_SQL_LITERAL)
164  escaped_value =
165  PQescapeLiteral(pset.db, value, strlen(value));
166  else
167  escaped_value =
168  PQescapeIdentifier(pset.db, value, strlen(value));
169 
170  if (escaped_value == NULL)
171  {
172  const char *error = PQerrorMessage(pset.db);
173 
174  pg_log_info("%s", error);
175  return NULL;
176  }
177 
178  /*
179  * Rather than complicate the lexer's API with a notion of
180  * which free() routine to use, just pay the price of an extra
181  * strdup().
182  */
183  result = pg_strdup(escaped_value);
184  PQfreemem(escaped_value);
185  break;
186  }
187  case PQUOTE_SHELL_ARG:
188  {
189  /*
190  * For this we use appendShellStringNoError, which is
191  * encoding-agnostic, which is fine since the shell probably
192  * is too. In any case, the only special character is "'",
193  * which is not known to appear in valid multibyte characters.
194  */
196 
197  initPQExpBuffer(&buf);
198  if (!appendShellStringNoError(&buf, value))
199  {
200  pg_log_error("shell command argument contains a newline or carriage return: \"%s\"",
201  value);
202  free(buf.data);
203  return NULL;
204  }
205  result = buf.data;
206  break;
207  }
208 
209  /* No default: we want a compiler warning for missing cases */
210  }
211 
212  return result;
213 }
214 
215 
216 /*
217  * for backend Notice messages (INFO, WARNING, etc)
218  */
219 void
220 NoticeProcessor(void *arg, const char *message)
221 {
222  (void) arg; /* not used */
223  pg_log_info("%s", message);
224 }
225 
226 
227 
228 /*
229  * Code to support query cancellation
230  *
231  * Before we start a query, we enable the SIGINT signal catcher to send a
232  * cancel request to the backend.
233  *
234  * SIGINT is supposed to abort all long-running psql operations, not only
235  * database queries. In most places, this is accomplished by checking
236  * cancel_pressed during long-running loops. However, that won't work when
237  * blocked on user input (in readline() or fgets()). In those places, we
238  * set sigint_interrupt_enabled true while blocked, instructing the signal
239  * catcher to longjmp through sigint_interrupt_jmp. We assume readline and
240  * fgets are coded to handle possible interruption.
241  *
242  * On Windows, currently this does not work, so control-C is less useful
243  * there, and the callback is just a no-op.
244  */
245 volatile bool sigint_interrupt_enabled = false;
246 
248 
249 static void
251 {
252 #ifndef WIN32
253  /* if we are waiting for input, longjmp out of it */
255  {
256  sigint_interrupt_enabled = false;
257  siglongjmp(sigint_interrupt_jmp, 1);
258  }
259 #endif
260 
261  /* else, set cancel flag to stop any long-running loops */
262  cancel_pressed = true;
263 }
264 
265 void
267 {
269 }
270 
271 
272 /* ConnectionUp
273  *
274  * Returns whether our backend connection is still there.
275  */
276 static bool
278 {
279  return PQstatus(pset.db) != CONNECTION_BAD;
280 }
281 
282 
283 
284 /* CheckConnection
285  *
286  * Verify that we still have a good connection to the backend, and if not,
287  * see if it can be restored.
288  *
289  * Returns true if either the connection was still there, or it could be
290  * restored successfully; false otherwise. If, however, there was no
291  * connection and the session is non-interactive, this will exit the program
292  * with a code of EXIT_BADCONN.
293  */
294 static bool
296 {
297  bool OK;
298 
299  OK = ConnectionUp();
300  if (!OK)
301  {
303  {
304  pg_log_fatal("connection to server was lost");
305  exit(EXIT_BADCONN);
306  }
307 
308  fprintf(stderr, _("The connection to the server was lost. Attempting reset: "));
309  PQreset(pset.db);
310  OK = ConnectionUp();
311  if (!OK)
312  {
313  fprintf(stderr, _("Failed.\n"));
314 
315  /*
316  * Transition to having no connection. Keep this bit in sync with
317  * do_connect().
318  */
319  PQfinish(pset.db);
320  pset.db = NULL;
321  ResetCancelConn();
322  UnsyncVariables();
323  }
324  else
325  {
326  fprintf(stderr, _("Succeeded.\n"));
327 
328  /*
329  * Re-sync, just in case anything changed. Keep this in sync with
330  * do_connect().
331  */
332  SyncVariables();
333  connection_warnings(false); /* Must be after SyncVariables */
334  }
335  }
336 
337  return OK;
338 }
339 
340 
341 
342 
343 /*
344  * AcceptResult
345  *
346  * Checks whether a result is valid, giving an error message if necessary;
347  * and ensures that the connection to the backend is still up.
348  *
349  * Returns true for valid result, false for error state.
350  */
351 static bool
352 AcceptResult(const PGresult *result)
353 {
354  bool OK;
355 
356  if (!result)
357  OK = false;
358  else
359  switch (PQresultStatus(result))
360  {
361  case PGRES_COMMAND_OK:
362  case PGRES_TUPLES_OK:
363  case PGRES_EMPTY_QUERY:
364  case PGRES_COPY_IN:
365  case PGRES_COPY_OUT:
366  /* Fine, do nothing */
367  OK = true;
368  break;
369 
370  case PGRES_BAD_RESPONSE:
372  case PGRES_FATAL_ERROR:
373  OK = false;
374  break;
375 
376  default:
377  OK = false;
378  pg_log_error("unexpected PQresultStatus: %d",
379  PQresultStatus(result));
380  break;
381  }
382 
383  if (!OK)
384  {
385  const char *error = PQerrorMessage(pset.db);
386 
387  if (strlen(error))
388  pg_log_info("%s", error);
389 
390  CheckConnection();
391  }
392 
393  return OK;
394 }
395 
396 
397 /*
398  * Set special variables from a query result
399  * - ERROR: true/false, whether an error occurred on this query
400  * - SQLSTATE: code of error, or "00000" if no error, or "" if unknown
401  * - ROW_COUNT: how many rows were returned or affected, or "0"
402  * - LAST_ERROR_SQLSTATE: same for last error
403  * - LAST_ERROR_MESSAGE: message of last error
404  *
405  * Note: current policy is to apply this only to the results of queries
406  * entered by the user, not queries generated by slash commands.
407  */
408 static void
410 {
411  if (success)
412  {
413  const char *ntuples = PQcmdTuples(results);
414 
415  SetVariable(pset.vars, "ERROR", "false");
416  SetVariable(pset.vars, "SQLSTATE", "00000");
417  SetVariable(pset.vars, "ROW_COUNT", *ntuples ? ntuples : "0");
418  }
419  else
420  {
421  const char *code = PQresultErrorField(results, PG_DIAG_SQLSTATE);
422  const char *mesg = PQresultErrorField(results, PG_DIAG_MESSAGE_PRIMARY);
423 
424  SetVariable(pset.vars, "ERROR", "true");
425 
426  /*
427  * If there is no SQLSTATE code, use an empty string. This can happen
428  * for libpq-detected errors (e.g., lost connection, ENOMEM).
429  */
430  if (code == NULL)
431  code = "";
432  SetVariable(pset.vars, "SQLSTATE", code);
433  SetVariable(pset.vars, "ROW_COUNT", "0");
434  SetVariable(pset.vars, "LAST_ERROR_SQLSTATE", code);
435  SetVariable(pset.vars, "LAST_ERROR_MESSAGE", mesg ? mesg : "");
436  }
437 }
438 
439 
440 /*
441  * ClearOrSaveResult
442  *
443  * If the result represents an error, remember it for possible display by
444  * \errverbose. Otherwise, just PQclear() it.
445  *
446  * Note: current policy is to apply this to the results of all queries,
447  * including "back door" queries, for debugging's sake. It's OK to use
448  * PQclear() directly on results known to not be error results, however.
449  */
450 static void
452 {
453  if (result)
454  {
455  switch (PQresultStatus(result))
456  {
458  case PGRES_FATAL_ERROR:
461  pset.last_error_result = result;
462  break;
463 
464  default:
465  PQclear(result);
466  break;
467  }
468  }
469 }
470 
471 
472 /*
473  * Print microtiming output. Always print raw milliseconds; if the interval
474  * is >= 1 second, also break it down into days/hours/minutes/seconds.
475  */
476 static void
477 PrintTiming(double elapsed_msec)
478 {
479  double seconds;
480  double minutes;
481  double hours;
482  double days;
483 
484  if (elapsed_msec < 1000.0)
485  {
486  /* This is the traditional (pre-v10) output format */
487  printf(_("Time: %.3f ms\n"), elapsed_msec);
488  return;
489  }
490 
491  /*
492  * Note: we could print just seconds, in a format like %06.3f, when the
493  * total is less than 1min. But that's hard to interpret unless we tack
494  * on "s" or otherwise annotate it. Forcing the display to include
495  * minutes seems like a better solution.
496  */
497  seconds = elapsed_msec / 1000.0;
498  minutes = floor(seconds / 60.0);
499  seconds -= 60.0 * minutes;
500  if (minutes < 60.0)
501  {
502  printf(_("Time: %.3f ms (%02d:%06.3f)\n"),
503  elapsed_msec, (int) minutes, seconds);
504  return;
505  }
506 
507  hours = floor(minutes / 60.0);
508  minutes -= 60.0 * hours;
509  if (hours < 24.0)
510  {
511  printf(_("Time: %.3f ms (%02d:%02d:%06.3f)\n"),
512  elapsed_msec, (int) hours, (int) minutes, seconds);
513  return;
514  }
515 
516  days = floor(hours / 24.0);
517  hours -= 24.0 * days;
518  printf(_("Time: %.3f ms (%.0f d %02d:%02d:%06.3f)\n"),
519  elapsed_msec, days, (int) hours, (int) minutes, seconds);
520 }
521 
522 
523 /*
524  * PSQLexec
525  *
526  * This is the way to send "backdoor" queries (those not directly entered
527  * by the user). It is subject to -E but not -e.
528  *
529  * Caller is responsible for handling the ensuing processing if a COPY
530  * command is sent.
531  *
532  * Note: we don't bother to check PQclientEncoding; it is assumed that no
533  * caller uses this path to issue "SET CLIENT_ENCODING".
534  */
535 PGresult *
536 PSQLexec(const char *query)
537 {
538  PGresult *res;
539 
540  if (!pset.db)
541  {
542  pg_log_error("You are currently not connected to a database.");
543  return NULL;
544  }
545 
547  {
548  printf(_("********* QUERY **********\n"
549  "%s\n"
550  "**************************\n\n"), query);
551  fflush(stdout);
552  if (pset.logfile)
553  {
555  _("********* QUERY **********\n"
556  "%s\n"
557  "**************************\n\n"), query);
558  fflush(pset.logfile);
559  }
560 
562  return NULL;
563  }
564 
566 
567  res = PQexec(pset.db, query);
568 
569  ResetCancelConn();
570 
571  if (!AcceptResult(res))
572  {
573  ClearOrSaveResult(res);
574  res = NULL;
575  }
576 
577  return res;
578 }
579 
580 
581 /*
582  * PSQLexecWatch
583  *
584  * This function is used for \watch command to send the query to
585  * the server and print out the results.
586  *
587  * Returns 1 if the query executed successfully, 0 if it cannot be repeated,
588  * e.g., because of the interrupt, -1 on error.
589  */
590 int
591 PSQLexecWatch(const char *query, const printQueryOpt *opt)
592 {
593  PGresult *res;
594  double elapsed_msec = 0;
596  instr_time after;
597 
598  if (!pset.db)
599  {
600  pg_log_error("You are currently not connected to a database.");
601  return 0;
602  }
603 
605 
606  if (pset.timing)
607  INSTR_TIME_SET_CURRENT(before);
608 
609  res = PQexec(pset.db, query);
610 
611  ResetCancelConn();
612 
613  if (!AcceptResult(res))
614  {
615  ClearOrSaveResult(res);
616  return 0;
617  }
618 
619  if (pset.timing)
620  {
621  INSTR_TIME_SET_CURRENT(after);
622  INSTR_TIME_SUBTRACT(after, before);
623  elapsed_msec = INSTR_TIME_GET_MILLISEC(after);
624  }
625 
626  /*
627  * If SIGINT is sent while the query is processing, the interrupt will be
628  * consumed. The user's intention, though, is to cancel the entire watch
629  * process, so detect a sent cancellation request and exit in this case.
630  */
631  if (cancel_pressed)
632  {
633  PQclear(res);
634  return 0;
635  }
636 
637  switch (PQresultStatus(res))
638  {
639  case PGRES_TUPLES_OK:
640  printQuery(res, opt, pset.queryFout, false, pset.logfile);
641  break;
642 
643  case PGRES_COMMAND_OK:
644  fprintf(pset.queryFout, "%s\n%s\n\n", opt->title, PQcmdStatus(res));
645  break;
646 
647  case PGRES_EMPTY_QUERY:
648  pg_log_error("\\watch cannot be used with an empty query");
649  PQclear(res);
650  return -1;
651 
652  case PGRES_COPY_OUT:
653  case PGRES_COPY_IN:
654  case PGRES_COPY_BOTH:
655  pg_log_error("\\watch cannot be used with COPY");
656  PQclear(res);
657  return -1;
658 
659  default:
660  pg_log_error("unexpected result status for \\watch");
661  PQclear(res);
662  return -1;
663  }
664 
665  PQclear(res);
666 
667  fflush(pset.queryFout);
668 
669  /* Possible microtiming output */
670  if (pset.timing)
671  PrintTiming(elapsed_msec);
672 
673  return 1;
674 }
675 
676 
677 /*
678  * PrintNotifications: check for asynchronous notifications, and print them out
679  */
680 static void
682 {
683  PGnotify *notify;
684 
686  while ((notify = PQnotifies(pset.db)) != NULL)
687  {
688  /* for backward compatibility, only show payload if nonempty */
689  if (notify->extra[0])
690  fprintf(pset.queryFout, _("Asynchronous notification \"%s\" with payload \"%s\" received from server process with PID %d.\n"),
691  notify->relname, notify->extra, notify->be_pid);
692  else
693  fprintf(pset.queryFout, _("Asynchronous notification \"%s\" received from server process with PID %d.\n"),
694  notify->relname, notify->be_pid);
695  fflush(pset.queryFout);
696  PQfreemem(notify);
698  }
699 }
700 
701 
702 /*
703  * PrintQueryTuples: assuming query result is OK, print its tuples
704  *
705  * Returns true if successful, false otherwise.
706  */
707 static bool
708 PrintQueryTuples(const PGresult *results)
709 {
710  printQueryOpt my_popt = pset.popt;
711  bool result = true;
712 
713  /* one-shot expanded output requested via \gx */
714  if (pset.g_expanded)
715  my_popt.topt.expanded = 1;
716 
717  /* write output to \g argument, if any */
718  if (pset.gfname)
719  {
720  FILE *fout;
721  bool is_pipe;
722 
723  if (!openQueryOutputFile(pset.gfname, &fout, &is_pipe))
724  return false;
725  if (is_pipe)
727 
728  printQuery(results, &my_popt, fout, false, pset.logfile);
729  if (ferror(fout))
730  {
731  pg_log_error("could not print result table: %m");
732  result = false;
733  }
734 
735  if (is_pipe)
736  {
737  pclose(fout);
739  }
740  else
741  fclose(fout);
742  }
743  else
744  {
745  printQuery(results, &my_popt, pset.queryFout, false, pset.logfile);
746  if (ferror(pset.queryFout))
747  {
748  pg_log_error("could not print result table: %m");
749  result = false;
750  }
751  }
752 
753  return result;
754 }
755 
756 
757 /*
758  * StoreQueryTuple: assuming query result is OK, save data into variables
759  *
760  * Returns true if successful, false otherwise.
761  */
762 static bool
763 StoreQueryTuple(const PGresult *result)
764 {
765  bool success = true;
766 
767  if (PQntuples(result) < 1)
768  {
769  pg_log_error("no rows returned for \\gset");
770  success = false;
771  }
772  else if (PQntuples(result) > 1)
773  {
774  pg_log_error("more than one row returned for \\gset");
775  success = false;
776  }
777  else
778  {
779  int i;
780 
781  for (i = 0; i < PQnfields(result); i++)
782  {
783  char *colname = PQfname(result, i);
784  char *varname;
785  char *value;
786 
787  /* concatenate prefix and column name */
788  varname = psprintf("%s%s", pset.gset_prefix, colname);
789 
790  if (!PQgetisnull(result, 0, i))
791  value = PQgetvalue(result, 0, i);
792  else
793  {
794  /* for NULL value, unset rather than set the variable */
795  value = NULL;
796  }
797 
798  if (!SetVariable(pset.vars, varname, value))
799  {
800  free(varname);
801  success = false;
802  break;
803  }
804 
805  free(varname);
806  }
807  }
808 
809  return success;
810 }
811 
812 
813 /*
814  * ExecQueryTuples: assuming query result is OK, execute each query
815  * result field as a SQL statement
816  *
817  * Returns true if successful, false otherwise.
818  */
819 static bool
820 ExecQueryTuples(const PGresult *result)
821 {
822  bool success = true;
823  int nrows = PQntuples(result);
824  int ncolumns = PQnfields(result);
825  int r,
826  c;
827 
828  /*
829  * We must turn off gexec_flag to avoid infinite recursion. Note that
830  * this allows ExecQueryUsingCursor to be applied to the individual query
831  * results. SendQuery prevents it from being applied when fetching the
832  * queries-to-execute, because it can't handle recursion either.
833  */
834  pset.gexec_flag = false;
835 
836  for (r = 0; r < nrows; r++)
837  {
838  for (c = 0; c < ncolumns; c++)
839  {
840  if (!PQgetisnull(result, r, c))
841  {
842  const char *query = PQgetvalue(result, r, c);
843 
844  /* Abandon execution if cancel_pressed */
845  if (cancel_pressed)
846  goto loop_exit;
847 
848  /*
849  * ECHO_ALL mode should echo these queries, but SendQuery
850  * assumes that MainLoop did that, so we have to do it here.
851  */
853  {
854  puts(query);
855  fflush(stdout);
856  }
857 
858  if (!SendQuery(query))
859  {
860  /* Error - abandon execution if ON_ERROR_STOP */
861  success = false;
862  if (pset.on_error_stop)
863  goto loop_exit;
864  }
865  }
866  }
867  }
868 
869 loop_exit:
870 
871  /*
872  * Restore state. We know gexec_flag was on, else we'd not be here. (We
873  * also know it'll get turned off at end of command, but that's not ours
874  * to do here.)
875  */
876  pset.gexec_flag = true;
877 
878  /* Return true if all queries were successful */
879  return success;
880 }
881 
882 
883 /*
884  * ProcessResult: utility function for use by SendQuery() only
885  *
886  * When our command string contained a COPY FROM STDIN or COPY TO STDOUT,
887  * PQexec() has stopped at the PGresult associated with the first such
888  * command. In that event, we'll marshal data for the COPY and then cycle
889  * through any subsequent PGresult objects.
890  *
891  * When the command string contained no such COPY command, this function
892  * degenerates to an AcceptResult() call.
893  *
894  * Changes its argument to point to the last PGresult of the command string,
895  * or NULL if that result was for a COPY TO STDOUT. (Returning NULL prevents
896  * the command status from being printed, which we want in that case so that
897  * the status line doesn't get taken as part of the COPY data.)
898  *
899  * Returns true on complete success, false otherwise. Possible failure modes
900  * include purely client-side problems; check the transaction status for the
901  * server-side opinion.
902  */
903 static bool
905 {
906  bool success = true;
907  bool first_cycle = true;
908 
909  for (;;)
910  {
911  ExecStatusType result_status;
912  bool is_copy;
913  PGresult *next_result;
914 
915  if (!AcceptResult(*results))
916  {
917  /*
918  * Failure at this point is always a server-side failure or a
919  * failure to submit the command string. Either way, we're
920  * finished with this command string.
921  */
922  success = false;
923  break;
924  }
925 
926  result_status = PQresultStatus(*results);
927  switch (result_status)
928  {
929  case PGRES_EMPTY_QUERY:
930  case PGRES_COMMAND_OK:
931  case PGRES_TUPLES_OK:
932  is_copy = false;
933  break;
934 
935  case PGRES_COPY_OUT:
936  case PGRES_COPY_IN:
937  is_copy = true;
938  break;
939 
940  default:
941  /* AcceptResult() should have caught anything else. */
942  is_copy = false;
943  pg_log_error("unexpected PQresultStatus: %d", result_status);
944  break;
945  }
946 
947  if (is_copy)
948  {
949  /*
950  * Marshal the COPY data. Either subroutine will get the
951  * connection out of its COPY state, then call PQresultStatus()
952  * once and report any error.
953  *
954  * For COPY OUT, direct the output to pset.copyStream if it's set,
955  * otherwise to pset.gfname if it's set, otherwise to queryFout.
956  * For COPY IN, use pset.copyStream as data source if it's set,
957  * otherwise cur_cmd_source.
958  */
959  FILE *copystream;
960  PGresult *copy_result;
961 
963  if (result_status == PGRES_COPY_OUT)
964  {
965  bool need_close = false;
966  bool is_pipe = false;
967 
968  if (pset.copyStream)
969  {
970  /* invoked by \copy */
971  copystream = pset.copyStream;
972  }
973  else if (pset.gfname)
974  {
975  /* invoked by \g */
977  &copystream, &is_pipe))
978  {
979  need_close = true;
980  if (is_pipe)
982  }
983  else
984  copystream = NULL; /* discard COPY data entirely */
985  }
986  else
987  {
988  /* fall back to the generic query output stream */
989  copystream = pset.queryFout;
990  }
991 
992  success = handleCopyOut(pset.db,
993  copystream,
994  &copy_result)
995  && success
996  && (copystream != NULL);
997 
998  /*
999  * Suppress status printing if the report would go to the same
1000  * place as the COPY data just went. Note this doesn't
1001  * prevent error reporting, since handleCopyOut did that.
1002  */
1003  if (copystream == pset.queryFout)
1004  {
1005  PQclear(copy_result);
1006  copy_result = NULL;
1007  }
1008 
1009  if (need_close)
1010  {
1011  /* close \g argument file/pipe */
1012  if (is_pipe)
1013  {
1014  pclose(copystream);
1016  }
1017  else
1018  {
1019  fclose(copystream);
1020  }
1021  }
1022  }
1023  else
1024  {
1025  /* COPY IN */
1026  copystream = pset.copyStream ? pset.copyStream : pset.cur_cmd_source;
1027  success = handleCopyIn(pset.db,
1028  copystream,
1029  PQbinaryTuples(*results),
1030  &copy_result) && success;
1031  }
1032  ResetCancelConn();
1033 
1034  /*
1035  * Replace the PGRES_COPY_OUT/IN result with COPY command's exit
1036  * status, or with NULL if we want to suppress printing anything.
1037  */
1038  PQclear(*results);
1039  *results = copy_result;
1040  }
1041  else if (first_cycle)
1042  {
1043  /* fast path: no COPY commands; PQexec visited all results */
1044  break;
1045  }
1046 
1047  /*
1048  * Check PQgetResult() again. In the typical case of a single-command
1049  * string, it will return NULL. Otherwise, we'll have other results
1050  * to process that may include other COPYs. We keep the last result.
1051  */
1052  next_result = PQgetResult(pset.db);
1053  if (!next_result)
1054  break;
1055 
1056  PQclear(*results);
1057  *results = next_result;
1058  first_cycle = false;
1059  }
1060 
1061  SetResultVariables(*results, success);
1062 
1063  /* may need this to recover from conn loss during COPY */
1064  if (!first_cycle && !CheckConnection())
1065  return false;
1066 
1067  return success;
1068 }
1069 
1070 
1071 /*
1072  * PrintQueryStatus: report command status as required
1073  *
1074  * Note: Utility function for use by PrintQueryResults() only.
1075  */
1076 static void
1078 {
1079  char buf[16];
1080 
1081  if (!pset.quiet)
1082  {
1083  if (pset.popt.topt.format == PRINT_HTML)
1084  {
1085  fputs("<p>", pset.queryFout);
1087  fputs("</p>\n", pset.queryFout);
1088  }
1089  else
1090  fprintf(pset.queryFout, "%s\n", PQcmdStatus(results));
1091  }
1092 
1093  if (pset.logfile)
1094  fprintf(pset.logfile, "%s\n", PQcmdStatus(results));
1095 
1096  snprintf(buf, sizeof(buf), "%u", (unsigned int) PQoidValue(results));
1097  SetVariable(pset.vars, "LASTOID", buf);
1098 }
1099 
1100 
1101 /*
1102  * PrintQueryResults: print out (or store or execute) query results as required
1103  *
1104  * Note: Utility function for use by SendQuery() only.
1105  *
1106  * Returns true if the query executed successfully, false otherwise.
1107  */
1108 static bool
1110 {
1111  bool success;
1112  const char *cmdstatus;
1113 
1114  if (!results)
1115  return false;
1116 
1117  switch (PQresultStatus(results))
1118  {
1119  case PGRES_TUPLES_OK:
1120  /* store or execute or print the data ... */
1121  if (pset.gset_prefix)
1122  success = StoreQueryTuple(results);
1123  else if (pset.gexec_flag)
1124  success = ExecQueryTuples(results);
1125  else if (pset.crosstab_flag)
1126  success = PrintResultsInCrosstab(results);
1127  else
1128  success = PrintQueryTuples(results);
1129  /* if it's INSERT/UPDATE/DELETE RETURNING, also print status */
1130  cmdstatus = PQcmdStatus(results);
1131  if (strncmp(cmdstatus, "INSERT", 6) == 0 ||
1132  strncmp(cmdstatus, "UPDATE", 6) == 0 ||
1133  strncmp(cmdstatus, "DELETE", 6) == 0)
1134  PrintQueryStatus(results);
1135  break;
1136 
1137  case PGRES_COMMAND_OK:
1138  PrintQueryStatus(results);
1139  success = true;
1140  break;
1141 
1142  case PGRES_EMPTY_QUERY:
1143  success = true;
1144  break;
1145 
1146  case PGRES_COPY_OUT:
1147  case PGRES_COPY_IN:
1148  /* nothing to do here */
1149  success = true;
1150  break;
1151 
1152  case PGRES_BAD_RESPONSE:
1153  case PGRES_NONFATAL_ERROR:
1154  case PGRES_FATAL_ERROR:
1155  success = false;
1156  break;
1157 
1158  default:
1159  success = false;
1160  pg_log_error("unexpected PQresultStatus: %d",
1161  PQresultStatus(results));
1162  break;
1163  }
1164 
1165  fflush(pset.queryFout);
1166 
1167  return success;
1168 }
1169 
1170 
1171 /*
1172  * SendQuery: send the query string to the backend
1173  * (and print out results)
1174  *
1175  * Note: This is the "front door" way to send a query. That is, use it to
1176  * send queries actually entered by the user. These queries will be subject to
1177  * single step mode.
1178  * To send "back door" queries (generated by slash commands, etc.) in a
1179  * controlled way, use PSQLexec().
1180  *
1181  * Returns true if the query executed successfully, false otherwise.
1182  */
1183 bool
1184 SendQuery(const char *query)
1185 {
1186  PGresult *results;
1187  PGTransactionStatusType transaction_status;
1188  double elapsed_msec = 0;
1189  bool OK = false;
1190  int i;
1191  bool on_error_rollback_savepoint = false;
1192  static bool on_error_rollback_warning = false;
1193 
1194  if (!pset.db)
1195  {
1196  pg_log_error("You are currently not connected to a database.");
1197  goto sendquery_cleanup;
1198  }
1199 
1200  if (pset.singlestep)
1201  {
1202  char buf[3];
1203 
1204  fflush(stderr);
1205  printf(_("***(Single step mode: verify command)*******************************************\n"
1206  "%s\n"
1207  "***(press return to proceed or enter x and return to cancel)********************\n"),
1208  query);
1209  fflush(stdout);
1210  if (fgets(buf, sizeof(buf), stdin) != NULL)
1211  if (buf[0] == 'x')
1212  goto sendquery_cleanup;
1213  if (cancel_pressed)
1214  goto sendquery_cleanup;
1215  }
1216  else if (pset.echo == PSQL_ECHO_QUERIES)
1217  {
1218  puts(query);
1219  fflush(stdout);
1220  }
1221 
1222  if (pset.logfile)
1223  {
1225  _("********* QUERY **********\n"
1226  "%s\n"
1227  "**************************\n\n"), query);
1228  fflush(pset.logfile);
1229  }
1230 
1232 
1233  transaction_status = PQtransactionStatus(pset.db);
1234 
1235  if (transaction_status == PQTRANS_IDLE &&
1236  !pset.autocommit &&
1237  !command_no_begin(query))
1238  {
1239  results = PQexec(pset.db, "BEGIN");
1240  if (PQresultStatus(results) != PGRES_COMMAND_OK)
1241  {
1243  ClearOrSaveResult(results);
1244  ResetCancelConn();
1245  goto sendquery_cleanup;
1246  }
1247  ClearOrSaveResult(results);
1248  transaction_status = PQtransactionStatus(pset.db);
1249  }
1250 
1251  if (transaction_status == PQTRANS_INTRANS &&
1255  {
1256  if (on_error_rollback_warning == false && pset.sversion < 80000)
1257  {
1258  char sverbuf[32];
1259 
1260  pg_log_warning("The server (version %s) does not support savepoints for ON_ERROR_ROLLBACK.",
1262  sverbuf, sizeof(sverbuf)));
1263  on_error_rollback_warning = true;
1264  }
1265  else
1266  {
1267  results = PQexec(pset.db, "SAVEPOINT pg_psql_temporary_savepoint");
1268  if (PQresultStatus(results) != PGRES_COMMAND_OK)
1269  {
1271  ClearOrSaveResult(results);
1272  ResetCancelConn();
1273  goto sendquery_cleanup;
1274  }
1275  ClearOrSaveResult(results);
1276  on_error_rollback_savepoint = true;
1277  }
1278  }
1279 
1280  if (pset.gdesc_flag)
1281  {
1282  /* Describe query's result columns, without executing it */
1283  OK = DescribeQuery(query, &elapsed_msec);
1284  ResetCancelConn();
1285  results = NULL; /* PQclear(NULL) does nothing */
1286  }
1287  else if (pset.fetch_count <= 0 || pset.gexec_flag ||
1289  {
1290  /* Default fetch-it-all-and-print mode */
1292  after;
1293 
1294  if (pset.timing)
1295  INSTR_TIME_SET_CURRENT(before);
1296 
1297  results = PQexec(pset.db, query);
1298 
1299  /* these operations are included in the timing result: */
1300  ResetCancelConn();
1301  OK = ProcessResult(&results);
1302 
1303  if (pset.timing)
1304  {
1305  INSTR_TIME_SET_CURRENT(after);
1306  INSTR_TIME_SUBTRACT(after, before);
1307  elapsed_msec = INSTR_TIME_GET_MILLISEC(after);
1308  }
1309 
1310  /* but printing results isn't: */
1311  if (OK && results)
1312  OK = PrintQueryResults(results);
1313  }
1314  else
1315  {
1316  /* Fetch-in-segments mode */
1317  OK = ExecQueryUsingCursor(query, &elapsed_msec);
1318  ResetCancelConn();
1319  results = NULL; /* PQclear(NULL) does nothing */
1320  }
1321 
1322  if (!OK && pset.echo == PSQL_ECHO_ERRORS)
1323  pg_log_info("STATEMENT: %s", query);
1324 
1325  /* If we made a temporary savepoint, possibly release/rollback */
1326  if (on_error_rollback_savepoint)
1327  {
1328  const char *svptcmd = NULL;
1329 
1330  transaction_status = PQtransactionStatus(pset.db);
1331 
1332  switch (transaction_status)
1333  {
1334  case PQTRANS_INERROR:
1335  /* We always rollback on an error */
1336  svptcmd = "ROLLBACK TO pg_psql_temporary_savepoint";
1337  break;
1338 
1339  case PQTRANS_IDLE:
1340  /* If they are no longer in a transaction, then do nothing */
1341  break;
1342 
1343  case PQTRANS_INTRANS:
1344 
1345  /*
1346  * Do nothing if they are messing with savepoints themselves:
1347  * If the user did RELEASE or ROLLBACK, our savepoint is gone.
1348  * If they issued a SAVEPOINT, releasing ours would remove
1349  * theirs.
1350  */
1351  if (results &&
1352  (strcmp(PQcmdStatus(results), "SAVEPOINT") == 0 ||
1353  strcmp(PQcmdStatus(results), "RELEASE") == 0 ||
1354  strcmp(PQcmdStatus(results), "ROLLBACK") == 0))
1355  svptcmd = NULL;
1356  else
1357  svptcmd = "RELEASE pg_psql_temporary_savepoint";
1358  break;
1359 
1360  case PQTRANS_ACTIVE:
1361  case PQTRANS_UNKNOWN:
1362  default:
1363  OK = false;
1364  /* PQTRANS_UNKNOWN is expected given a broken connection. */
1365  if (transaction_status != PQTRANS_UNKNOWN || ConnectionUp())
1366  pg_log_error("unexpected transaction status (%d)",
1367  transaction_status);
1368  break;
1369  }
1370 
1371  if (svptcmd)
1372  {
1373  PGresult *svptres;
1374 
1375  svptres = PQexec(pset.db, svptcmd);
1376  if (PQresultStatus(svptres) != PGRES_COMMAND_OK)
1377  {
1379  ClearOrSaveResult(svptres);
1380  OK = false;
1381 
1382  PQclear(results);
1383  ResetCancelConn();
1384  goto sendquery_cleanup;
1385  }
1386  PQclear(svptres);
1387  }
1388  }
1389 
1390  ClearOrSaveResult(results);
1391 
1392  /* Possible microtiming output */
1393  if (pset.timing)
1394  PrintTiming(elapsed_msec);
1395 
1396  /* check for events that may occur during query execution */
1397 
1398  if (pset.encoding != PQclientEncoding(pset.db) &&
1399  PQclientEncoding(pset.db) >= 0)
1400  {
1401  /* track effects of SET CLIENT_ENCODING */
1404  SetVariable(pset.vars, "ENCODING",
1406  }
1407 
1409 
1410  /* perform cleanup that should occur after any attempted query */
1411 
1412 sendquery_cleanup:
1413 
1414  /* reset \g's output-to-filename trigger */
1415  if (pset.gfname)
1416  {
1417  free(pset.gfname);
1418  pset.gfname = NULL;
1419  }
1420 
1421  /* reset \gx's expanded-mode flag */
1422  pset.g_expanded = false;
1423 
1424  /* reset \gset trigger */
1425  if (pset.gset_prefix)
1426  {
1428  pset.gset_prefix = NULL;
1429  }
1430 
1431  /* reset \gdesc trigger */
1432  pset.gdesc_flag = false;
1433 
1434  /* reset \gexec trigger */
1435  pset.gexec_flag = false;
1436 
1437  /* reset \crosstabview trigger */
1438  pset.crosstab_flag = false;
1439  for (i = 0; i < lengthof(pset.ctv_args); i++)
1440  {
1441  pg_free(pset.ctv_args[i]);
1442  pset.ctv_args[i] = NULL;
1443  }
1444 
1445  return OK;
1446 }
1447 
1448 
1449 /*
1450  * DescribeQuery: describe the result columns of a query, without executing it
1451  *
1452  * Returns true if the operation executed successfully, false otherwise.
1453  *
1454  * If pset.timing is on, total query time (exclusive of result-printing) is
1455  * stored into *elapsed_msec.
1456  */
1457 static bool
1458 DescribeQuery(const char *query, double *elapsed_msec)
1459 {
1460  PGresult *results;
1461  bool OK;
1463  after;
1464 
1465  *elapsed_msec = 0;
1466 
1467  if (pset.timing)
1468  INSTR_TIME_SET_CURRENT(before);
1469 
1470  /*
1471  * To parse the query but not execute it, we prepare it, using the unnamed
1472  * prepared statement. This is invisible to psql users, since there's no
1473  * way to access the unnamed prepared statement from psql user space. The
1474  * next Parse or Query protocol message would overwrite the statement
1475  * anyway. (So there's no great need to clear it when done, which is a
1476  * good thing because libpq provides no easy way to do that.)
1477  */
1478  results = PQprepare(pset.db, "", query, 0, NULL);
1479  if (PQresultStatus(results) != PGRES_COMMAND_OK)
1480  {
1482  SetResultVariables(results, false);
1483  ClearOrSaveResult(results);
1484  return false;
1485  }
1486  PQclear(results);
1487 
1488  results = PQdescribePrepared(pset.db, "");
1489  OK = AcceptResult(results) &&
1490  (PQresultStatus(results) == PGRES_COMMAND_OK);
1491  if (OK && results)
1492  {
1493  if (PQnfields(results) > 0)
1494  {
1496  int i;
1497 
1498  initPQExpBuffer(&buf);
1499 
1500  printfPQExpBuffer(&buf,
1501  "SELECT name AS \"%s\", pg_catalog.format_type(tp, tpm) AS \"%s\"\n"
1502  "FROM (VALUES ",
1503  gettext_noop("Column"),
1504  gettext_noop("Type"));
1505 
1506  for (i = 0; i < PQnfields(results); i++)
1507  {
1508  const char *name;
1509  char *escname;
1510 
1511  if (i > 0)
1512  appendPQExpBufferStr(&buf, ",");
1513 
1514  name = PQfname(results, i);
1515  escname = PQescapeLiteral(pset.db, name, strlen(name));
1516 
1517  if (escname == NULL)
1518  {
1520  PQclear(results);
1521  termPQExpBuffer(&buf);
1522  return false;
1523  }
1524 
1525  appendPQExpBuffer(&buf, "(%s, '%u'::pg_catalog.oid, %d)",
1526  escname,
1527  PQftype(results, i),
1528  PQfmod(results, i));
1529 
1530  PQfreemem(escname);
1531  }
1532 
1533  appendPQExpBufferStr(&buf, ") s(name, tp, tpm)");
1534  PQclear(results);
1535 
1536  results = PQexec(pset.db, buf.data);
1537  OK = AcceptResult(results);
1538 
1539  if (pset.timing)
1540  {
1541  INSTR_TIME_SET_CURRENT(after);
1542  INSTR_TIME_SUBTRACT(after, before);
1543  *elapsed_msec += INSTR_TIME_GET_MILLISEC(after);
1544  }
1545 
1546  if (OK && results)
1547  OK = PrintQueryResults(results);
1548 
1549  termPQExpBuffer(&buf);
1550  }
1551  else
1553  _("The command has no result, or the result has no columns.\n"));
1554  }
1555 
1556  SetResultVariables(results, OK);
1557  ClearOrSaveResult(results);
1558 
1559  return OK;
1560 }
1561 
1562 
1563 /*
1564  * ExecQueryUsingCursor: run a SELECT-like query using a cursor
1565  *
1566  * This feature allows result sets larger than RAM to be dealt with.
1567  *
1568  * Returns true if the query executed successfully, false otherwise.
1569  *
1570  * If pset.timing is on, total query time (exclusive of result-printing) is
1571  * stored into *elapsed_msec.
1572  */
1573 static bool
1574 ExecQueryUsingCursor(const char *query, double *elapsed_msec)
1575 {
1576  bool OK = true;
1577  PGresult *results;
1579  printQueryOpt my_popt = pset.popt;
1580  FILE *fout;
1581  bool is_pipe;
1582  bool is_pager = false;
1583  bool started_txn = false;
1584  int64 total_tuples = 0;
1585  int ntuples;
1586  int fetch_count;
1587  char fetch_cmd[64];
1589  after;
1590  int flush_error;
1591 
1592  *elapsed_msec = 0;
1593 
1594  /* initialize print options for partial table output */
1595  my_popt.topt.start_table = true;
1596  my_popt.topt.stop_table = false;
1597  my_popt.topt.prior_records = 0;
1598 
1599  if (pset.timing)
1600  INSTR_TIME_SET_CURRENT(before);
1601 
1602  /* if we're not in a transaction, start one */
1604  {
1605  results = PQexec(pset.db, "BEGIN");
1606  OK = AcceptResult(results) &&
1607  (PQresultStatus(results) == PGRES_COMMAND_OK);
1608  ClearOrSaveResult(results);
1609  if (!OK)
1610  return false;
1611  started_txn = true;
1612  }
1613 
1614  /* Send DECLARE CURSOR */
1615  initPQExpBuffer(&buf);
1616  appendPQExpBuffer(&buf, "DECLARE _psql_cursor NO SCROLL CURSOR FOR\n%s",
1617  query);
1618 
1619  results = PQexec(pset.db, buf.data);
1620  OK = AcceptResult(results) &&
1621  (PQresultStatus(results) == PGRES_COMMAND_OK);
1622  if (!OK)
1623  SetResultVariables(results, OK);
1624  ClearOrSaveResult(results);
1625  termPQExpBuffer(&buf);
1626  if (!OK)
1627  goto cleanup;
1628 
1629  if (pset.timing)
1630  {
1631  INSTR_TIME_SET_CURRENT(after);
1632  INSTR_TIME_SUBTRACT(after, before);
1633  *elapsed_msec += INSTR_TIME_GET_MILLISEC(after);
1634  }
1635 
1636  /*
1637  * In \gset mode, we force the fetch count to be 2, so that we will throw
1638  * the appropriate error if the query returns more than one row.
1639  */
1640  if (pset.gset_prefix)
1641  fetch_count = 2;
1642  else
1643  fetch_count = pset.fetch_count;
1644 
1645  snprintf(fetch_cmd, sizeof(fetch_cmd),
1646  "FETCH FORWARD %d FROM _psql_cursor",
1647  fetch_count);
1648 
1649  /* one-shot expanded output requested via \gx */
1650  if (pset.g_expanded)
1651  my_popt.topt.expanded = 1;
1652 
1653  /* prepare to write output to \g argument, if any */
1654  if (pset.gfname)
1655  {
1656  if (!openQueryOutputFile(pset.gfname, &fout, &is_pipe))
1657  {
1658  OK = false;
1659  goto cleanup;
1660  }
1661  if (is_pipe)
1663  }
1664  else
1665  {
1666  fout = pset.queryFout;
1667  is_pipe = false; /* doesn't matter */
1668  }
1669 
1670  /* clear any pre-existing error indication on the output stream */
1671  clearerr(fout);
1672 
1673  for (;;)
1674  {
1675  if (pset.timing)
1676  INSTR_TIME_SET_CURRENT(before);
1677 
1678  /* get fetch_count tuples at a time */
1679  results = PQexec(pset.db, fetch_cmd);
1680 
1681  if (pset.timing)
1682  {
1683  INSTR_TIME_SET_CURRENT(after);
1684  INSTR_TIME_SUBTRACT(after, before);
1685  *elapsed_msec += INSTR_TIME_GET_MILLISEC(after);
1686  }
1687 
1688  if (PQresultStatus(results) != PGRES_TUPLES_OK)
1689  {
1690  /* shut down pager before printing error message */
1691  if (is_pager)
1692  {
1693  ClosePager(fout);
1694  is_pager = false;
1695  }
1696 
1697  OK = AcceptResult(results);
1698  Assert(!OK);
1699  SetResultVariables(results, OK);
1700  ClearOrSaveResult(results);
1701  break;
1702  }
1703 
1704  if (pset.gset_prefix)
1705  {
1706  /* StoreQueryTuple will complain if not exactly one row */
1707  OK = StoreQueryTuple(results);
1708  ClearOrSaveResult(results);
1709  break;
1710  }
1711 
1712  /*
1713  * Note we do not deal with \gdesc, \gexec or \crosstabview modes here
1714  */
1715 
1716  ntuples = PQntuples(results);
1717  total_tuples += ntuples;
1718 
1719  if (ntuples < fetch_count)
1720  {
1721  /* this is the last result set, so allow footer decoration */
1722  my_popt.topt.stop_table = true;
1723  }
1724  else if (fout == stdout && !is_pager)
1725  {
1726  /*
1727  * If query requires multiple result sets, hack to ensure that
1728  * only one pager instance is used for the whole mess
1729  */
1730  fout = PageOutput(INT_MAX, &(my_popt.topt));
1731  is_pager = true;
1732  }
1733 
1734  printQuery(results, &my_popt, fout, is_pager, pset.logfile);
1735 
1736  ClearOrSaveResult(results);
1737 
1738  /* after the first result set, disallow header decoration */
1739  my_popt.topt.start_table = false;
1740  my_popt.topt.prior_records += ntuples;
1741 
1742  /*
1743  * Make sure to flush the output stream, so intermediate results are
1744  * visible to the client immediately. We check the results because if
1745  * the pager dies/exits/etc, there's no sense throwing more data at
1746  * it.
1747  */
1748  flush_error = fflush(fout);
1749 
1750  /*
1751  * Check if we are at the end, if a cancel was pressed, or if there
1752  * were any errors either trying to flush out the results, or more
1753  * generally on the output stream at all. If we hit any errors
1754  * writing things to the stream, we presume $PAGER has disappeared and
1755  * stop bothering to pull down more data.
1756  */
1757  if (ntuples < fetch_count || cancel_pressed || flush_error ||
1758  ferror(fout))
1759  break;
1760  }
1761 
1762  if (pset.gfname)
1763  {
1764  /* close \g argument file/pipe */
1765  if (is_pipe)
1766  {
1767  pclose(fout);
1769  }
1770  else
1771  fclose(fout);
1772  }
1773  else if (is_pager)
1774  {
1775  /* close transient pager */
1776  ClosePager(fout);
1777  }
1778 
1779  if (OK)
1780  {
1781  /*
1782  * We don't have a PGresult here, and even if we did it wouldn't have
1783  * the right row count, so fake SetResultVariables(). In error cases,
1784  * we already set the result variables above.
1785  */
1786  char buf[32];
1787 
1788  SetVariable(pset.vars, "ERROR", "false");
1789  SetVariable(pset.vars, "SQLSTATE", "00000");
1790  snprintf(buf, sizeof(buf), INT64_FORMAT, total_tuples);
1791  SetVariable(pset.vars, "ROW_COUNT", buf);
1792  }
1793 
1794 cleanup:
1795  if (pset.timing)
1796  INSTR_TIME_SET_CURRENT(before);
1797 
1798  /*
1799  * We try to close the cursor on either success or failure, but on failure
1800  * ignore the result (it's probably just a bleat about being in an aborted
1801  * transaction)
1802  */
1803  results = PQexec(pset.db, "CLOSE _psql_cursor");
1804  if (OK)
1805  {
1806  OK = AcceptResult(results) &&
1807  (PQresultStatus(results) == PGRES_COMMAND_OK);
1808  ClearOrSaveResult(results);
1809  }
1810  else
1811  PQclear(results);
1812 
1813  if (started_txn)
1814  {
1815  results = PQexec(pset.db, OK ? "COMMIT" : "ROLLBACK");
1816  OK &= AcceptResult(results) &&
1817  (PQresultStatus(results) == PGRES_COMMAND_OK);
1818  ClearOrSaveResult(results);
1819  }
1820 
1821  if (pset.timing)
1822  {
1823  INSTR_TIME_SET_CURRENT(after);
1824  INSTR_TIME_SUBTRACT(after, before);
1825  *elapsed_msec += INSTR_TIME_GET_MILLISEC(after);
1826  }
1827 
1828  return OK;
1829 }
1830 
1831 
1832 /*
1833  * Advance the given char pointer over white space and SQL comments.
1834  */
1835 static const char *
1836 skip_white_space(const char *query)
1837 {
1838  int cnestlevel = 0; /* slash-star comment nest level */
1839 
1840  while (*query)
1841  {
1842  int mblen = PQmblen(query, pset.encoding);
1843 
1844  /*
1845  * Note: we assume the encoding is a superset of ASCII, so that for
1846  * example "query[0] == '/'" is meaningful. However, we do NOT assume
1847  * that the second and subsequent bytes of a multibyte character
1848  * couldn't look like ASCII characters; so it is critical to advance
1849  * by mblen, not 1, whenever we haven't exactly identified the
1850  * character we are skipping over.
1851  */
1852  if (isspace((unsigned char) *query))
1853  query += mblen;
1854  else if (query[0] == '/' && query[1] == '*')
1855  {
1856  cnestlevel++;
1857  query += 2;
1858  }
1859  else if (cnestlevel > 0 && query[0] == '*' && query[1] == '/')
1860  {
1861  cnestlevel--;
1862  query += 2;
1863  }
1864  else if (cnestlevel == 0 && query[0] == '-' && query[1] == '-')
1865  {
1866  query += 2;
1867 
1868  /*
1869  * We have to skip to end of line since any slash-star inside the
1870  * -- comment does NOT start a slash-star comment.
1871  */
1872  while (*query)
1873  {
1874  if (*query == '\n')
1875  {
1876  query++;
1877  break;
1878  }
1879  query += PQmblen(query, pset.encoding);
1880  }
1881  }
1882  else if (cnestlevel > 0)
1883  query += mblen;
1884  else
1885  break; /* found first token */
1886  }
1887 
1888  return query;
1889 }
1890 
1891 
1892 /*
1893  * Check whether a command is one of those for which we should NOT start
1894  * a new transaction block (ie, send a preceding BEGIN).
1895  *
1896  * These include the transaction control statements themselves, plus
1897  * certain statements that the backend disallows inside transaction blocks.
1898  */
1899 static bool
1900 command_no_begin(const char *query)
1901 {
1902  int wordlen;
1903 
1904  /*
1905  * First we must advance over any whitespace and comments.
1906  */
1907  query = skip_white_space(query);
1908 
1909  /*
1910  * Check word length (since "beginx" is not "begin").
1911  */
1912  wordlen = 0;
1913  while (isalpha((unsigned char) query[wordlen]))
1914  wordlen += PQmblen(&query[wordlen], pset.encoding);
1915 
1916  /*
1917  * Transaction control commands. These should include every keyword that
1918  * gives rise to a TransactionStmt in the backend grammar, except for the
1919  * savepoint-related commands.
1920  *
1921  * (We assume that START must be START TRANSACTION, since there is
1922  * presently no other "START foo" command.)
1923  */
1924  if (wordlen == 5 && pg_strncasecmp(query, "abort", 5) == 0)
1925  return true;
1926  if (wordlen == 5 && pg_strncasecmp(query, "begin", 5) == 0)
1927  return true;
1928  if (wordlen == 5 && pg_strncasecmp(query, "start", 5) == 0)
1929  return true;
1930  if (wordlen == 6 && pg_strncasecmp(query, "commit", 6) == 0)
1931  return true;
1932  if (wordlen == 3 && pg_strncasecmp(query, "end", 3) == 0)
1933  return true;
1934  if (wordlen == 8 && pg_strncasecmp(query, "rollback", 8) == 0)
1935  return true;
1936  if (wordlen == 7 && pg_strncasecmp(query, "prepare", 7) == 0)
1937  {
1938  /* PREPARE TRANSACTION is a TC command, PREPARE foo is not */
1939  query += wordlen;
1940 
1941  query = skip_white_space(query);
1942 
1943  wordlen = 0;
1944  while (isalpha((unsigned char) query[wordlen]))
1945  wordlen += PQmblen(&query[wordlen], pset.encoding);
1946 
1947  if (wordlen == 11 && pg_strncasecmp(query, "transaction", 11) == 0)
1948  return true;
1949  return false;
1950  }
1951 
1952  /*
1953  * Commands not allowed within transactions. The statements checked for
1954  * here should be exactly those that call PreventInTransactionBlock() in
1955  * the backend.
1956  */
1957  if (wordlen == 6 && pg_strncasecmp(query, "vacuum", 6) == 0)
1958  return true;
1959  if (wordlen == 7 && pg_strncasecmp(query, "cluster", 7) == 0)
1960  {
1961  /* CLUSTER with any arguments is allowed in transactions */
1962  query += wordlen;
1963 
1964  query = skip_white_space(query);
1965 
1966  if (isalpha((unsigned char) query[0]))
1967  return false; /* has additional words */
1968  return true; /* it's CLUSTER without arguments */
1969  }
1970 
1971  if (wordlen == 6 && pg_strncasecmp(query, "create", 6) == 0)
1972  {
1973  query += wordlen;
1974 
1975  query = skip_white_space(query);
1976 
1977  wordlen = 0;
1978  while (isalpha((unsigned char) query[wordlen]))
1979  wordlen += PQmblen(&query[wordlen], pset.encoding);
1980 
1981  if (wordlen == 8 && pg_strncasecmp(query, "database", 8) == 0)
1982  return true;
1983  if (wordlen == 10 && pg_strncasecmp(query, "tablespace", 10) == 0)
1984  return true;
1985 
1986  /* CREATE [UNIQUE] INDEX CONCURRENTLY isn't allowed in xacts */
1987  if (wordlen == 6 && pg_strncasecmp(query, "unique", 6) == 0)
1988  {
1989  query += wordlen;
1990 
1991  query = skip_white_space(query);
1992 
1993  wordlen = 0;
1994  while (isalpha((unsigned char) query[wordlen]))
1995  wordlen += PQmblen(&query[wordlen], pset.encoding);
1996  }
1997 
1998  if (wordlen == 5 && pg_strncasecmp(query, "index", 5) == 0)
1999  {
2000  query += wordlen;
2001 
2002  query = skip_white_space(query);
2003 
2004  wordlen = 0;
2005  while (isalpha((unsigned char) query[wordlen]))
2006  wordlen += PQmblen(&query[wordlen], pset.encoding);
2007 
2008  if (wordlen == 12 && pg_strncasecmp(query, "concurrently", 12) == 0)
2009  return true;
2010  }
2011 
2012  return false;
2013  }
2014 
2015  if (wordlen == 5 && pg_strncasecmp(query, "alter", 5) == 0)
2016  {
2017  query += wordlen;
2018 
2019  query = skip_white_space(query);
2020 
2021  wordlen = 0;
2022  while (isalpha((unsigned char) query[wordlen]))
2023  wordlen += PQmblen(&query[wordlen], pset.encoding);
2024 
2025  /* ALTER SYSTEM isn't allowed in xacts */
2026  if (wordlen == 6 && pg_strncasecmp(query, "system", 6) == 0)
2027  return true;
2028 
2029  return false;
2030  }
2031 
2032  /*
2033  * Note: these tests will match DROP SYSTEM and REINDEX TABLESPACE, which
2034  * aren't really valid commands so we don't care much. The other four
2035  * possible matches are correct.
2036  */
2037  if ((wordlen == 4 && pg_strncasecmp(query, "drop", 4) == 0) ||
2038  (wordlen == 7 && pg_strncasecmp(query, "reindex", 7) == 0))
2039  {
2040  query += wordlen;
2041 
2042  query = skip_white_space(query);
2043 
2044  wordlen = 0;
2045  while (isalpha((unsigned char) query[wordlen]))
2046  wordlen += PQmblen(&query[wordlen], pset.encoding);
2047 
2048  if (wordlen == 8 && pg_strncasecmp(query, "database", 8) == 0)
2049  return true;
2050  if (wordlen == 6 && pg_strncasecmp(query, "system", 6) == 0)
2051  return true;
2052  if (wordlen == 10 && pg_strncasecmp(query, "tablespace", 10) == 0)
2053  return true;
2054  if (wordlen == 5 && (pg_strncasecmp(query, "index", 5) == 0 ||
2055  pg_strncasecmp(query, "table", 5) == 0))
2056  {
2057  query += wordlen;
2058  query = skip_white_space(query);
2059  wordlen = 0;
2060  while (isalpha((unsigned char) query[wordlen]))
2061  wordlen += PQmblen(&query[wordlen], pset.encoding);
2062 
2063  /*
2064  * REINDEX [ TABLE | INDEX ] CONCURRENTLY are not allowed in
2065  * xacts.
2066  */
2067  if (wordlen == 12 && pg_strncasecmp(query, "concurrently", 12) == 0)
2068  return true;
2069  }
2070 
2071  /* DROP INDEX CONCURRENTLY isn't allowed in xacts */
2072  if (wordlen == 5 && pg_strncasecmp(query, "index", 5) == 0)
2073  {
2074  query += wordlen;
2075 
2076  query = skip_white_space(query);
2077 
2078  wordlen = 0;
2079  while (isalpha((unsigned char) query[wordlen]))
2080  wordlen += PQmblen(&query[wordlen], pset.encoding);
2081 
2082  if (wordlen == 12 && pg_strncasecmp(query, "concurrently", 12) == 0)
2083  return true;
2084 
2085  return false;
2086  }
2087 
2088  return false;
2089  }
2090 
2091  /* DISCARD ALL isn't allowed in xacts, but other variants are allowed. */
2092  if (wordlen == 7 && pg_strncasecmp(query, "discard", 7) == 0)
2093  {
2094  query += wordlen;
2095 
2096  query = skip_white_space(query);
2097 
2098  wordlen = 0;
2099  while (isalpha((unsigned char) query[wordlen]))
2100  wordlen += PQmblen(&query[wordlen], pset.encoding);
2101 
2102  if (wordlen == 3 && pg_strncasecmp(query, "all", 3) == 0)
2103  return true;
2104  return false;
2105  }
2106 
2107  return false;
2108 }
2109 
2110 
2111 /*
2112  * Check whether the specified command is a SELECT (or VALUES).
2113  */
2114 static bool
2115 is_select_command(const char *query)
2116 {
2117  int wordlen;
2118 
2119  /*
2120  * First advance over any whitespace, comments and left parentheses.
2121  */
2122  for (;;)
2123  {
2124  query = skip_white_space(query);
2125  if (query[0] == '(')
2126  query++;
2127  else
2128  break;
2129  }
2130 
2131  /*
2132  * Check word length (since "selectx" is not "select").
2133  */
2134  wordlen = 0;
2135  while (isalpha((unsigned char) query[wordlen]))
2136  wordlen += PQmblen(&query[wordlen], pset.encoding);
2137 
2138  if (wordlen == 6 && pg_strncasecmp(query, "select", 6) == 0)
2139  return true;
2140 
2141  if (wordlen == 6 && pg_strncasecmp(query, "values", 6) == 0)
2142  return true;
2143 
2144  return false;
2145 }
2146 
2147 
2148 /*
2149  * Test if the current user is a database superuser.
2150  *
2151  * Note: this will correctly detect superuserness only with a protocol-3.0
2152  * or newer backend; otherwise it will always say "false".
2153  */
2154 bool
2156 {
2157  const char *val;
2158 
2159  if (!pset.db)
2160  return false;
2161 
2162  val = PQparameterStatus(pset.db, "is_superuser");
2163 
2164  if (val && strcmp(val, "on") == 0)
2165  return true;
2166 
2167  return false;
2168 }
2169 
2170 
2171 /*
2172  * Test if the current session uses standard string literals.
2173  *
2174  * Note: With a pre-protocol-3.0 connection this will always say "false",
2175  * which should be the right answer.
2176  */
2177 bool
2179 {
2180  const char *val;
2181 
2182  if (!pset.db)
2183  return false;
2184 
2185  val = PQparameterStatus(pset.db, "standard_conforming_strings");
2186 
2187  if (val && strcmp(val, "on") == 0)
2188  return true;
2189 
2190  return false;
2191 }
2192 
2193 
2194 /*
2195  * Return the session user of the current connection.
2196  *
2197  * Note: this will correctly detect the session user only with a
2198  * protocol-3.0 or newer backend; otherwise it will return the
2199  * connection user.
2200  */
2201 const char *
2203 {
2204  const char *val;
2205 
2206  if (!pset.db)
2207  return NULL;
2208 
2209  val = PQparameterStatus(pset.db, "session_authorization");
2210  if (val)
2211  return val;
2212  else
2213  return PQuser(pset.db);
2214 }
2215 
2216 
2217 /* expand_tilde
2218  *
2219  * substitute '~' with HOME or '~username' with username's home dir
2220  *
2221  */
2222 void
2224 {
2225  if (!filename || !(*filename))
2226  return;
2227 
2228  /*
2229  * WIN32 doesn't use tilde expansion for file names. Also, it uses tilde
2230  * for short versions of long file names, though the tilde is usually
2231  * toward the end, not at the beginning.
2232  */
2233 #ifndef WIN32
2234 
2235  /* try tilde expansion */
2236  if (**filename == '~')
2237  {
2238  char *fn;
2239  char oldp,
2240  *p;
2241  struct passwd *pw;
2242  char home[MAXPGPATH];
2243 
2244  fn = *filename;
2245  *home = '\0';
2246 
2247  p = fn + 1;
2248  while (*p != '/' && *p != '\0')
2249  p++;
2250 
2251  oldp = *p;
2252  *p = '\0';
2253 
2254  if (*(fn + 1) == '\0')
2255  get_home_path(home); /* ~ or ~/ only */
2256  else if ((pw = getpwnam(fn + 1)) != NULL)
2257  strlcpy(home, pw->pw_dir, sizeof(home)); /* ~user */
2258 
2259  *p = oldp;
2260  if (strlen(home) != 0)
2261  {
2262  char *newfn;
2263 
2264  newfn = psprintf("%s%s", home, p);
2265  free(fn);
2266  *filename = newfn;
2267  }
2268  }
2269 #endif
2270 }
2271 
2272 /*
2273  * Checks if connection string starts with either of the valid URI prefix
2274  * designators.
2275  *
2276  * Returns the URI prefix length, 0 if the string doesn't contain a URI prefix.
2277  *
2278  * XXX This is a duplicate of the eponymous libpq function.
2279  */
2280 static int
2282 {
2283  /* The connection URI must start with either of the following designators: */
2284  static const char uri_designator[] = "postgresql://";
2285  static const char short_uri_designator[] = "postgres://";
2286 
2287  if (strncmp(connstr, uri_designator,
2288  sizeof(uri_designator) - 1) == 0)
2289  return sizeof(uri_designator) - 1;
2290 
2291  if (strncmp(connstr, short_uri_designator,
2292  sizeof(short_uri_designator) - 1) == 0)
2293  return sizeof(short_uri_designator) - 1;
2294 
2295  return 0;
2296 }
2297 
2298 /*
2299  * Recognized connection string either starts with a valid URI prefix or
2300  * contains a "=" in it.
2301  *
2302  * Must be consistent with parse_connection_string: anything for which this
2303  * returns true should at least look like it's parseable by that routine.
2304  *
2305  * XXX This is a duplicate of the eponymous libpq function.
2306  */
2307 bool
2309 {
2310  return uri_prefix_length(connstr) != 0 || strchr(connstr, '=') != NULL;
2311 }
static void PrintQueryStatus(PGresult *results)
Definition: common.c:1077
PSQL_ECHO echo
Definition: settings.h:133
bool singlestep
Definition: settings.h:128
char * gset_prefix
Definition: settings.h:95
char * extra
Definition: libpq-fe.h:168
static bool PrintQueryResults(PGresult *results)
Definition: common.c:1109
int PQnfields(const PGresult *res)
Definition: fe-exec.c:2777
PGresult * PQprepare(PGconn *conn, const char *stmtName, const char *query, int nParams, const Oid *paramTypes)
Definition: fe-exec.c:1983
PGconn * db
Definition: settings.h:82
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6684
PGresult * PQdescribePrepared(PGconn *conn, const char *stmt)
Definition: fe-exec.c:2156
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:237
bool conditional_active(ConditionalStack cstack)
Definition: conditional.c:128
volatile bool sigint_interrupt_enabled
Definition: common.c:245
#define PG_DIAG_MESSAGE_PRIMARY
Definition: postgres_ext.h:58
int encoding
Definition: print.h:122
PsqlSettings pset
Definition: startup.c:31
static void ClearOrSaveResult(PGresult *result)
Definition: common.c:451
void SyncVariables(void)
Definition: command.c:3350
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3163
static void error(void)
Definition: sql-dyntest.c:147
const char * PQparameterStatus(const PGconn *conn, const char *paramName)
Definition: fe-connect.c:6649
PGnotify * PQnotifies(PGconn *conn)
Definition: fe-exec.c:2289
char * PQfname(const PGresult *res, int field_num)
Definition: fe-exec.c:2855
int PSQLexecWatch(const char *query, const printQueryOpt *opt)
Definition: common.c:591
void disable_sigpipe_trap(void)
Definition: print.c:2941
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:131
#define pg_log_error(...)
Definition: logging.h:79
void ResetCancelConn(void)
Definition: cancel.c:100
char * PQcmdTuples(PGresult *res)
Definition: fe-exec.c:3110
bool appendShellStringNoError(PQExpBuffer buf, const char *str)
Definition: string_utils.c:441
static bool ExecQueryTuples(const PGresult *result)
Definition: common.c:820
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
void ClosePager(FILE *pagerpipe)
Definition: print.c:3042
static bool PrintQueryTuples(const PGresult *results)
Definition: common.c:708
static void SetResultVariables(PGresult *results, bool success)
Definition: common.c:409
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
bool recognized_connection_string(const char *connstr)
Definition: common.c:2308
#define INSTR_TIME_GET_MILLISEC(t)
Definition: instr_time.h:202
Oid PQoidValue(const PGresult *res)
Definition: fe-exec.c:3081
struct timeval instr_time
Definition: instr_time.h:150
bool gexec_flag
Definition: settings.h:97
bool start_table
Definition: print.h:111
enum printFormat format
Definition: print.h:101
printTableOpt topt
Definition: print.h:169
static void PrintTiming(double elapsed_msec)
Definition: common.c:477
bool queryFoutPipe
Definition: settings.h:85
#define gettext_noop(x)
Definition: c.h:1160
FILE * queryFout
Definition: settings.h:84
void set_sigpipe_trap_state(bool ignore)
Definition: print.c:2977
void PQfinish(PGconn *conn)
Definition: fe-connect.c:4182
static bool CheckConnection(void)
Definition: common.c:295
#define printf(...)
Definition: port.h:198
static bool ConnectionUp(void)
Definition: common.c:277
ExecStatusType
Definition: libpq-fe.h:84
static void setup_cancel_handler(void)
Definition: parallel.c:627
bool on_error_stop
Definition: settings.h:125
bool autocommit
Definition: settings.h:124
#define lengthof(array)
Definition: c.h:668
int PQbinaryTuples(const PGresult *res)
Definition: fe-exec.c:2785
int PQntuples(const PGresult *res)
Definition: fe-exec.c:2769
#define PG_DIAG_SQLSTATE
Definition: postgres_ext.h:57
#define fprintf
Definition: port.h:196
unsigned long prior_records
Definition: print.h:114
FILE * copyStream
Definition: settings.h:87
PSQL_ERROR_ROLLBACK on_error_rollback
Definition: settings.h:135
int PQclientEncoding(const PGconn *conn)
Definition: fe-connect.c:6744
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2692
FILE * cur_cmd_source
Definition: settings.h:104
void UnsyncVariables(void)
Definition: command.c:3391
static bool AcceptResult(const PGresult *result)
Definition: common.c:352
char * PQuser(const PGconn *conn)
Definition: fe-connect.c:6542
sigjmp_buf sigint_interrupt_jmp
Definition: common.c:247
#define EXIT_BADCONN
Definition: settings.h:156
static void PrintNotifications(void)
Definition: common.c:681
static int uri_prefix_length(const char *connstr)
Definition: common.c:2281
int pg_strncasecmp(const char *s1, const char *s2, size_t n)
Definition: pgstrcasecmp.c:69
char * ctv_args[4]
Definition: settings.h:99
char * PQescapeIdentifier(PGconn *conn, const char *str, size_t len)
Definition: fe-exec.c:3570
static int before(chr x, chr y)
Definition: regc_locale.c:496
unsigned short int expanded
Definition: print.h:102
bool cur_cmd_interactive
Definition: settings.h:106
PSQL_ECHO_HIDDEN echo_hidden
Definition: settings.h:134
FILE * PageOutput(int lines, const printTableOpt *topt)
Definition: print.c:2991
static bool is_select_command(const char *query)
Definition: common.c:2115
#define INSTR_TIME_SUBTRACT(x, y)
Definition: instr_time.h:170
int be_pid
Definition: libpq-fe.h:167
void expand_tilde(char **filename)
Definition: common.c:2223
#define MAXPGPATH
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:267
Oid PQftype(const PGresult *res, int field_num)
Definition: fe-exec.c:3007
bool gdesc_flag
Definition: settings.h:96
char * c
static char * buf
Definition: pg_test_fsync.c:67
const char * session_username(void)
Definition: common.c:2202
int fetch_count
Definition: settings.h:130
static bool ProcessResult(PGresult **results)
Definition: common.c:904
char * pg_strdup(const char *in)
Definition: fe_memutils.c:85
bool handleCopyOut(PGconn *conn, FILE *copystream, PGresult **res)
Definition: copy.c:436
void SetCancelConn(PGconn *conn)
Definition: cancel.c:70
bool g_expanded
Definition: settings.h:94
bool PrintResultsInCrosstab(const PGresult *res)
Definition: crosstabview.c:103
const char *const days[]
Definition: datetime.c:68
char * relname
Definition: libpq-fe.h:166
void restore_sigpipe_trap(void)
Definition: print.c:2964
static bool ExecQueryUsingCursor(const char *query, double *elapsed_msec)
Definition: common.c:1574
PsqlScanQuoteType
Definition: psqlscan.h:52
PGTransactionStatusType PQtransactionStatus(const PGconn *conn)
Definition: fe-connect.c:6639
const char * GetVariable(VariableSpace space, const char *name)
Definition: variables.c:71
static bool DescribeQuery(const char *query, double *elapsed_msec)
Definition: common.c:1458
char * PQcmdStatus(PGresult *res)
Definition: fe-exec.c:3040
bool openQueryOutputFile(const char *fname, FILE **fout, bool *is_pipe)
Definition: common.c:50
char * gfname
Definition: settings.h:93
bool setQFout(const char *fname)
Definition: common.c:85
static void cleanup(void)
Definition: bootstrap.c:893
int PQconsumeInput(PGconn *conn)
Definition: fe-exec.c:1704
PGresult * last_error_result
Definition: settings.h:89
FILE * logfile
Definition: settings.h:115
char * PQescapeLiteral(PGconn *conn, const char *str, size_t len)
Definition: fe-exec.c:3564
volatile sig_atomic_t cancel_pressed
Definition: print.c:43
static struct @143 value
bool stop_table
Definition: print.h:112
void PQclear(PGresult *res)
Definition: fe-exec.c:694
static void * fn(void *arg)
bool is_superuser(void)
Definition: common.c:2155
bool standard_strings(void)
Definition: common.c:2178
#define free(a)
Definition: header.h:65
static void psql_cancel_callback(void)
Definition: common.c:250
void NoticeProcessor(void *arg, const char *message)
Definition: common.c:220
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
const char * pg_encoding_to_char(int encoding)
Definition: encnames.c:588
bool handleCopyIn(PGconn *conn, FILE *copystream, bool isbinary, PGresult **res)
Definition: copy.c:513
PGTransactionStatusType
Definition: libpq-fe.h:103
char * title
Definition: print.h:171
char * PQresultErrorField(const PGresult *res, int fieldcode)
Definition: fe-exec.c:2754
#define Assert(condition)
Definition: c.h:738
bool SetVariable(VariableSpace space, const char *name, const char *value)
Definition: variables.c:211
printQueryOpt popt
Definition: settings.h:91
int PQfmod(const PGresult *res, int field_num)
Definition: fe-exec.c:3029
void printQuery(const PGresult *result, const printQueryOpt *opt, FILE *fout, bool is_pager, FILE *flog)
Definition: print.c:3433
void pg_free(void *ptr)
Definition: fe_memutils.c:105
#define INSTR_TIME_SET_CURRENT(t)
Definition: instr_time.h:156
#define INT64_FORMAT
Definition: c.h:409
const char * name
Definition: encode.c:521
static const char short_uri_designator[]
Definition: fe-connect.c:382
char * psql_get_variable(const char *varname, PsqlScanQuoteType quote, void *passthrough)
Definition: common.c:129
static char * filename
Definition: pg_dumpall.c:90
void psql_setup_cancel_handler(void)
Definition: common.c:266
static const char uri_designator[]
Definition: fe-connect.c:381
int i
static bool StoreQueryTuple(const PGresult *result)
Definition: common.c:763
void html_escaped_print(const char *in, FILE *fout)
Definition: print.c:1854
bool crosstab_flag
Definition: settings.h:98
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:1939
void * arg
bool SendQuery(const char *query)
Definition: common.c:1184
void connection_warnings(bool in_startup)
Definition: command.c:3227
#define pg_log_warning(...)
Definition: pgfnames.c:24
int encoding
Definition: settings.h:83
int PQgetisnull(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3188
ConnStatusType PQstatus(const PGconn *conn)
Definition: fe-connect.c:6631
static bool command_no_begin(const char *query)
Definition: common.c:1900
static bool success
Definition: initdb.c:161
int PQmblen(const char *s, int encoding)
Definition: fe-misc.c:1215
#define snprintf
Definition: port.h:192
#define _(x)
Definition: elog.c:88
void PQfreemem(void *ptr)
Definition: fe-exec.c:3296
long val
Definition: informix.c:664
PGresult * PQgetResult(PGconn *conn)
Definition: fe-exec.c:1778
static const char * skip_white_space(const char *query)
Definition: common.c:1836
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:92
#define pg_log_info(...)
Definition: logging.h:87
void PQreset(PGconn *conn)
Definition: fe-connect.c:4196
bool get_home_path(char *ret_path)
Definition: path.c:807
char * formatPGVersionNumber(int version_number, bool include_minor, char *buf, size_t buflen)
Definition: string_utils.c:177
PGresult * PSQLexec(const char *query)
Definition: common.c:536
VariableSpace vars
Definition: settings.h:117
static char * connstr
Definition: pg_dumpall.c:61
#define pg_log_fatal(...)
Definition: logging.h:75