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