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