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