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