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