PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
postgres.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * postgres.c
4  * POSTGRES C Backend Interface
5  *
6  * Portions Copyright (c) 1996-2015, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  * src/backend/tcop/postgres.c
12  *
13  * NOTES
14  * this is the "main" module of the postgres backend and
15  * hence the main module of the "traffic cop".
16  *
17  *-------------------------------------------------------------------------
18  */
19 
20 #include "postgres.h"
21 
22 #include <fcntl.h>
23 #include <limits.h>
24 #include <signal.h>
25 #include <unistd.h>
26 #include <sys/socket.h>
27 #ifdef HAVE_SYS_SELECT_H
28 #include <sys/select.h>
29 #endif
30 #ifdef HAVE_SYS_RESOURCE_H
31 #include <sys/time.h>
32 #include <sys/resource.h>
33 #endif
34 
35 #ifndef HAVE_GETRUSAGE
36 #include "rusagestub.h"
37 #endif
38 
39 #include "access/parallel.h"
40 #include "access/printtup.h"
41 #include "access/xact.h"
42 #include "catalog/pg_type.h"
43 #include "commands/async.h"
44 #include "commands/prepare.h"
45 #include "libpq/libpq.h"
46 #include "libpq/pqformat.h"
47 #include "libpq/pqsignal.h"
48 #include "miscadmin.h"
49 #include "nodes/print.h"
50 #include "optimizer/planner.h"
51 #include "pgstat.h"
52 #include "pg_trace.h"
53 #include "parser/analyze.h"
54 #include "parser/parser.h"
55 #include "pg_getopt.h"
56 #include "postmaster/autovacuum.h"
57 #include "postmaster/postmaster.h"
58 #include "replication/slot.h"
59 #include "replication/walsender.h"
60 #include "rewrite/rewriteHandler.h"
61 #include "storage/bufmgr.h"
62 #include "storage/ipc.h"
63 #include "storage/proc.h"
64 #include "storage/procsignal.h"
65 #include "storage/sinval.h"
66 #include "tcop/fastpath.h"
67 #include "tcop/pquery.h"
68 #include "tcop/tcopprot.h"
69 #include "tcop/utility.h"
70 #include "utils/lsyscache.h"
71 #include "utils/memutils.h"
72 #include "utils/ps_status.h"
73 #include "utils/snapmgr.h"
74 #include "utils/timeout.h"
75 #include "utils/timestamp.h"
76 #include "mb/pg_wchar.h"
77 
78 
79 /* ----------------
80  * global variables
81  * ----------------
82  */
83 const char *debug_query_string; /* client-supplied query string */
84 
85 /* Note: whereToSendOutput is initialized for the bootstrap/standalone case */
87 
88 /* flag for logging end of session */
89 bool Log_disconnections = false;
90 
92 
93 /* GUC variable for maximum stack depth (measured in kilobytes) */
94 int max_stack_depth = 100;
95 
96 /* wait N seconds to allow attach from a debugger */
97 int PostAuthDelay = 0;
98 
99 
100 
101 /* ----------------
102  * private variables
103  * ----------------
104  */
105 
106 /* max_stack_depth converted to bytes for speed of checking */
107 static long max_stack_depth_bytes = 100 * 1024L;
108 
109 /*
110  * Stack base pointer -- initialized by PostmasterMain and inherited by
111  * subprocesses. This is not static because old versions of PL/Java modify
112  * it directly. Newer versions use set_stack_base(), but we want to stay
113  * binary-compatible for the time being.
114  */
116 
117 /*
118  * On IA64 we also have to remember the register stack base.
119  */
120 #if defined(__ia64__) || defined(__ia64)
121 char *register_stack_base_ptr = NULL;
122 #endif
123 
124 /*
125  * Flag to mark SIGHUP. Whenever the main loop comes around it
126  * will reread the configuration file. (Better than doing the
127  * reading in the signal handler, ey?)
128  */
129 static volatile sig_atomic_t got_SIGHUP = false;
130 
131 /*
132  * Flag to keep track of whether we have started a transaction.
133  * For extended query protocol this has to be remembered across messages.
134  */
135 static bool xact_started = false;
136 
137 /*
138  * Flag to indicate that we are doing the outer loop's read-from-client,
139  * as opposed to any random read from client that might happen within
140  * commands like COPY FROM STDIN.
141  */
142 static bool DoingCommandRead = false;
143 
144 /*
145  * Flags to implement skip-till-Sync-after-error behavior for messages of
146  * the extended query protocol.
147  */
148 static bool doing_extended_query_message = false;
149 static bool ignore_till_sync = false;
150 
151 /*
152  * If an unnamed prepared statement exists, it's stored here.
153  * We keep it separate from the hashtable kept by commands/prepare.c
154  * in order to reduce overhead for short-lived queries.
155  */
157 
158 /* assorted command-line switches */
159 static const char *userDoption = NULL; /* -D switch */
160 
161 static bool EchoQuery = false; /* -E switch */
162 
163 /*
164  * people who want to use EOF should #define DONTUSENEWLINE in
165  * tcop/tcopdebug.h
166  */
167 #ifndef TCOP_DONTUSENEWLINE
168 static int UseNewLine = 1; /* Use newlines query delimiters (the default) */
169 #else
170 static int UseNewLine = 0; /* Use EOF as query delimiters */
171 #endif /* TCOP_DONTUSENEWLINE */
172 
173 /* whether or not, and why, we were canceled by conflict with recovery */
174 static bool RecoveryConflictPending = false;
175 static bool RecoveryConflictRetryable = true;
177 
178 /* ----------------------------------------------------------------
179  * decls for routines only used in this file
180  * ----------------------------------------------------------------
181  */
182 static int InteractiveBackend(StringInfo inBuf);
183 static int interactive_getc(void);
184 static int SocketBackend(StringInfo inBuf);
185 static int ReadCommand(StringInfo inBuf);
186 static void forbidden_in_wal_sender(char firstchar);
187 static List *pg_rewrite_query(Query *query);
188 static bool check_log_statement(List *stmt_list);
189 static int errdetail_execute(List *raw_parsetree_list);
190 static int errdetail_params(ParamListInfo params);
191 static int errdetail_abort(void);
192 static int errdetail_recovery_conflict(void);
193 static void start_xact_command(void);
194 static void finish_xact_command(void);
195 static bool IsTransactionExitStmt(Node *parsetree);
196 static bool IsTransactionExitStmtList(List *parseTrees);
197 static bool IsTransactionStmtList(List *parseTrees);
198 static void drop_unnamed_stmt(void);
199 static void SigHupHandler(SIGNAL_ARGS);
200 static void log_disconnections(int code, Datum arg);
201 
202 
203 /* ----------------------------------------------------------------
204  * routines to obtain user input
205  * ----------------------------------------------------------------
206  */
207 
208 /* ----------------
209  * InteractiveBackend() is called for user interactive connections
210  *
211  * the string entered by the user is placed in its parameter inBuf,
212  * and we act like a Q message was received.
213  *
214  * EOF is returned if end-of-file input is seen; time to shut down.
215  * ----------------
216  */
217 
218 static int
220 {
221  int c; /* character read from getc() */
222  bool end = false; /* end-of-input flag */
223  bool backslashSeen = false; /* have we seen a \ ? */
224 
225  /*
226  * display a prompt and obtain input from the user
227  */
228  printf("backend> ");
229  fflush(stdout);
230 
231  resetStringInfo(inBuf);
232 
233  if (UseNewLine)
234  {
235  /*
236  * if we are using \n as a delimiter, then read characters until the
237  * \n.
238  */
239  while ((c = interactive_getc()) != EOF)
240  {
241  if (c == '\n')
242  {
243  if (backslashSeen)
244  {
245  /* discard backslash from inBuf */
246  inBuf->data[--inBuf->len] = '\0';
247  backslashSeen = false;
248  continue;
249  }
250  else
251  {
252  /* keep the newline character */
253  appendStringInfoChar(inBuf, '\n');
254  break;
255  }
256  }
257  else if (c == '\\')
258  backslashSeen = true;
259  else
260  backslashSeen = false;
261 
262  appendStringInfoChar(inBuf, (char) c);
263  }
264 
265  if (c == EOF)
266  end = true;
267  }
268  else
269  {
270  /*
271  * otherwise read characters until EOF.
272  */
273  while ((c = interactive_getc()) != EOF)
274  appendStringInfoChar(inBuf, (char) c);
275 
276  /* No input before EOF signal means time to quit. */
277  if (inBuf->len == 0)
278  end = true;
279  }
280 
281  if (end)
282  return EOF;
283 
284  /*
285  * otherwise we have a user query so process it.
286  */
287 
288  /* Add '\0' to make it look the same as message case. */
289  appendStringInfoChar(inBuf, (char) '\0');
290 
291  /*
292  * if the query echo flag was given, print the query..
293  */
294  if (EchoQuery)
295  printf("statement: %s\n", inBuf->data);
296  fflush(stdout);
297 
298  return 'Q';
299 }
300 
301 /*
302  * interactive_getc -- collect one character from stdin
303  *
304  * Even though we are not reading from a "client" process, we still want to
305  * respond to signals, particularly SIGTERM/SIGQUIT.
306  */
307 static int
309 {
310  int c;
311 
312  /*
313  * This will not process catchup interrupts or notifications while
314  * reading. But those can't really be relevant for a standalone backend
315  * anyway. To properly handle SIGTERM there's a hack in die() that
316  * directly processes interrupts at this stage...
317  */
319 
320  c = getc(stdin);
321 
323 
324  return c;
325 }
326 
327 /* ----------------
328  * SocketBackend() Is called for frontend-backend connections
329  *
330  * Returns the message type code, and loads message body data into inBuf.
331  *
332  * EOF is returned if the connection is lost.
333  * ----------------
334  */
335 static int
337 {
338  int qtype;
339 
340  /*
341  * Get message type code from the frontend.
342  */
344  pq_startmsgread();
345  qtype = pq_getbyte();
346 
347  if (qtype == EOF) /* frontend disconnected */
348  {
349  if (IsTransactionState())
351  (errcode(ERRCODE_CONNECTION_FAILURE),
352  errmsg("unexpected EOF on client connection with an open transaction")));
353  else
354  {
355  /*
356  * Can't send DEBUG log messages to client at this point. Since
357  * we're disconnecting right away, we don't need to restore
358  * whereToSendOutput.
359  */
361  ereport(DEBUG1,
362  (errcode(ERRCODE_CONNECTION_DOES_NOT_EXIST),
363  errmsg("unexpected EOF on client connection")));
364  }
365  return qtype;
366  }
367 
368  /*
369  * Validate message type code before trying to read body; if we have lost
370  * sync, better to say "command unknown" than to run out of memory because
371  * we used garbage as a length word.
372  *
373  * This also gives us a place to set the doing_extended_query_message flag
374  * as soon as possible.
375  */
376  switch (qtype)
377  {
378  case 'Q': /* simple query */
381  {
382  /* old style without length word; convert */
383  if (pq_getstring(inBuf))
384  {
385  if (IsTransactionState())
387  (errcode(ERRCODE_CONNECTION_FAILURE),
388  errmsg("unexpected EOF on client connection with an open transaction")));
389  else
390  {
391  /*
392  * Can't send DEBUG log messages to client at this
393  * point. Since we're disconnecting right away, we
394  * don't need to restore whereToSendOutput.
395  */
397  ereport(DEBUG1,
398  (errcode(ERRCODE_CONNECTION_DOES_NOT_EXIST),
399  errmsg("unexpected EOF on client connection")));
400  }
401  return EOF;
402  }
403  }
404  break;
405 
406  case 'F': /* fastpath function call */
409  {
410  if (GetOldFunctionMessage(inBuf))
411  {
412  if (IsTransactionState())
414  (errcode(ERRCODE_CONNECTION_FAILURE),
415  errmsg("unexpected EOF on client connection with an open transaction")));
416  else
417  {
418  /*
419  * Can't send DEBUG log messages to client at this
420  * point. Since we're disconnecting right away, we
421  * don't need to restore whereToSendOutput.
422  */
424  ereport(DEBUG1,
425  (errcode(ERRCODE_CONNECTION_DOES_NOT_EXIST),
426  errmsg("unexpected EOF on client connection")));
427  }
428  return EOF;
429  }
430  }
431  break;
432 
433  case 'X': /* terminate */
435  ignore_till_sync = false;
436  break;
437 
438  case 'B': /* bind */
439  case 'C': /* close */
440  case 'D': /* describe */
441  case 'E': /* execute */
442  case 'H': /* flush */
443  case 'P': /* parse */
445  /* these are only legal in protocol 3 */
447  ereport(FATAL,
448  (errcode(ERRCODE_PROTOCOL_VIOLATION),
449  errmsg("invalid frontend message type %d", qtype)));
450  break;
451 
452  case 'S': /* sync */
453  /* stop any active skip-till-Sync */
454  ignore_till_sync = false;
455  /* mark not-extended, so that a new error doesn't begin skip */
457  /* only legal in protocol 3 */
459  ereport(FATAL,
460  (errcode(ERRCODE_PROTOCOL_VIOLATION),
461  errmsg("invalid frontend message type %d", qtype)));
462  break;
463 
464  case 'd': /* copy data */
465  case 'c': /* copy done */
466  case 'f': /* copy fail */
468  /* these are only legal in protocol 3 */
470  ereport(FATAL,
471  (errcode(ERRCODE_PROTOCOL_VIOLATION),
472  errmsg("invalid frontend message type %d", qtype)));
473  break;
474 
475  default:
476 
477  /*
478  * Otherwise we got garbage from the frontend. We treat this as
479  * fatal because we have probably lost message boundary sync, and
480  * there's no good way to recover.
481  */
482  ereport(FATAL,
483  (errcode(ERRCODE_PROTOCOL_VIOLATION),
484  errmsg("invalid frontend message type %d", qtype)));
485  break;
486  }
487 
488  /*
489  * In protocol version 3, all frontend messages have a length word next
490  * after the type code; we can read the message contents independently of
491  * the type.
492  */
494  {
495  if (pq_getmessage(inBuf, 0))
496  return EOF; /* suitable message already logged */
497  }
498  else
499  pq_endmsgread();
501 
502  return qtype;
503 }
504 
505 /* ----------------
506  * ReadCommand reads a command from either the frontend or
507  * standard input, places it in inBuf, and returns the
508  * message type code (first byte of the message).
509  * EOF is returned if end of file.
510  * ----------------
511  */
512 static int
514 {
515  int result;
516 
518  result = SocketBackend(inBuf);
519  else
520  result = InteractiveBackend(inBuf);
521  return result;
522 }
523 
524 /*
525  * ProcessClientReadInterrupt() - Process interrupts specific to client reads
526  *
527  * This is called just after low-level reads. That might be after the read
528  * finished successfully, or it was interrupted via interrupt.
529  *
530  * Must preserve errno!
531  */
532 void
534 {
535  int save_errno = errno;
536 
537  if (DoingCommandRead)
538  {
539  /* Check for general interrupts that arrived while reading */
541 
542  /* Process sinval catchup interrupts that happened while reading */
545 
546  /* Process sinval catchup interrupts that happened while reading */
549  }
550  else if (ProcDiePending && blocked)
551  {
552  /*
553  * We're dying. It's safe (and sane) to handle that now.
554  */
556  }
557 
558  errno = save_errno;
559 }
560 
561 /*
562  * ProcessClientWriteInterrupt() - Process interrupts specific to client writes
563  *
564  * This is called just after low-level writes. That might be after the read
565  * finished successfully, or it was interrupted via interrupt. 'blocked' tells
566  * us whether the
567  *
568  * Must preserve errno!
569  */
570 void
572 {
573  int save_errno = errno;
574 
575  /*
576  * We only want to process the interrupt here if socket writes are
577  * blocking to increase the chance to get an error message to the client.
578  * If we're not blocked there'll soon be a CHECK_FOR_INTERRUPTS(). But if
579  * we're blocked we'll never get out of that situation if the client has
580  * died.
581  */
582  if (ProcDiePending && blocked)
583  {
584  /*
585  * We're dying. It's safe (and sane) to handle that now. But we don't
586  * want to send the client the error message as that a) would possibly
587  * block again b) would possibly lead to sending an error message to
588  * the client, while we already started to send something else.
589  */
592 
594  }
595 
596  errno = save_errno;
597 }
598 
599 /*
600  * Do raw parsing (only).
601  *
602  * A list of parsetrees is returned, since there might be multiple
603  * commands in the given string.
604  *
605  * NOTE: for interactive queries, it is important to keep this routine
606  * separate from the analysis & rewrite stages. Analysis and rewriting
607  * cannot be done in an aborted transaction, since they require access to
608  * database tables. So, we rely on the raw parser to determine whether
609  * we've seen a COMMIT or ABORT command; when we are in abort state, other
610  * commands are not processed any further than the raw parse stage.
611  */
612 List *
613 pg_parse_query(const char *query_string)
614 {
615  List *raw_parsetree_list;
616 
617  TRACE_POSTGRESQL_QUERY_PARSE_START(query_string);
618 
619  if (log_parser_stats)
620  ResetUsage();
621 
622  raw_parsetree_list = raw_parser(query_string);
623 
624  if (log_parser_stats)
625  ShowUsage("PARSER STATISTICS");
626 
627 #ifdef COPY_PARSE_PLAN_TREES
628  /* Optional debugging check: pass raw parsetrees through copyObject() */
629  {
630  List *new_list = (List *) copyObject(raw_parsetree_list);
631 
632  /* This checks both copyObject() and the equal() routines... */
633  if (!equal(new_list, raw_parsetree_list))
634  elog(WARNING, "copyObject() failed to produce an equal raw parse tree");
635  else
636  raw_parsetree_list = new_list;
637  }
638 #endif
639 
640  TRACE_POSTGRESQL_QUERY_PARSE_DONE(query_string);
641 
642  return raw_parsetree_list;
643 }
644 
645 /*
646  * Given a raw parsetree (gram.y output), and optionally information about
647  * types of parameter symbols ($n), perform parse analysis and rule rewriting.
648  *
649  * A list of Query nodes is returned, since either the analyzer or the
650  * rewriter might expand one query to several.
651  *
652  * NOTE: for reasons mentioned above, this must be separate from raw parsing.
653  */
654 List *
655 pg_analyze_and_rewrite(Node *parsetree, const char *query_string,
656  Oid *paramTypes, int numParams)
657 {
658  Query *query;
659  List *querytree_list;
660 
661  TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
662 
663  /*
664  * (1) Perform parse analysis.
665  */
666  if (log_parser_stats)
667  ResetUsage();
668 
669  query = parse_analyze(parsetree, query_string, paramTypes, numParams);
670 
671  if (log_parser_stats)
672  ShowUsage("PARSE ANALYSIS STATISTICS");
673 
674  /*
675  * (2) Rewrite the queries, as necessary
676  */
677  querytree_list = pg_rewrite_query(query);
678 
679  TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
680 
681  return querytree_list;
682 }
683 
684 /*
685  * Do parse analysis and rewriting. This is the same as pg_analyze_and_rewrite
686  * except that external-parameter resolution is determined by parser callback
687  * hooks instead of a fixed list of parameter datatypes.
688  */
689 List *
691  const char *query_string,
692  ParserSetupHook parserSetup,
693  void *parserSetupArg)
694 {
695  ParseState *pstate;
696  Query *query;
697  List *querytree_list;
698 
699  Assert(query_string != NULL); /* required as of 8.4 */
700 
701  TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
702 
703  /*
704  * (1) Perform parse analysis.
705  */
706  if (log_parser_stats)
707  ResetUsage();
708 
709  pstate = make_parsestate(NULL);
710  pstate->p_sourcetext = query_string;
711  (*parserSetup) (pstate, parserSetupArg);
712 
713  query = transformTopLevelStmt(pstate, parsetree);
714 
716  (*post_parse_analyze_hook) (pstate, query);
717 
718  free_parsestate(pstate);
719 
720  if (log_parser_stats)
721  ShowUsage("PARSE ANALYSIS STATISTICS");
722 
723  /*
724  * (2) Rewrite the queries, as necessary
725  */
726  querytree_list = pg_rewrite_query(query);
727 
728  TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
729 
730  return querytree_list;
731 }
732 
733 /*
734  * Perform rewriting of a query produced by parse analysis.
735  *
736  * Note: query must just have come from the parser, because we do not do
737  * AcquireRewriteLocks() on it.
738  */
739 static List *
741 {
742  List *querytree_list;
743 
744  if (Debug_print_parse)
745  elog_node_display(LOG, "parse tree", query,
747 
748  if (log_parser_stats)
749  ResetUsage();
750 
751  if (query->commandType == CMD_UTILITY)
752  {
753  /* don't rewrite utilities, just dump 'em into result list */
754  querytree_list = list_make1(query);
755  }
756  else
757  {
758  /* rewrite regular queries */
759  querytree_list = QueryRewrite(query);
760  }
761 
762  if (log_parser_stats)
763  ShowUsage("REWRITER STATISTICS");
764 
765 #ifdef COPY_PARSE_PLAN_TREES
766  /* Optional debugging check: pass querytree output through copyObject() */
767  {
768  List *new_list;
769 
770  new_list = (List *) copyObject(querytree_list);
771  /* This checks both copyObject() and the equal() routines... */
772  if (!equal(new_list, querytree_list))
773  elog(WARNING, "copyObject() failed to produce equal parse tree");
774  else
775  querytree_list = new_list;
776  }
777 #endif
778 
780  elog_node_display(LOG, "rewritten parse tree", querytree_list,
782 
783  return querytree_list;
784 }
785 
786 
787 /*
788  * Generate a plan for a single already-rewritten query.
789  * This is a thin wrapper around planner() and takes the same parameters.
790  */
791 PlannedStmt *
792 pg_plan_query(Query *querytree, int cursorOptions, ParamListInfo boundParams)
793 {
794  PlannedStmt *plan;
795 
796  /* Utility commands have no plans. */
797  if (querytree->commandType == CMD_UTILITY)
798  return NULL;
799 
800  /* Planner must have a snapshot in case it calls user-defined functions. */
802 
803  TRACE_POSTGRESQL_QUERY_PLAN_START();
804 
805  if (log_planner_stats)
806  ResetUsage();
807 
808  /* call the optimizer */
809  plan = planner(querytree, cursorOptions, boundParams);
810 
811  if (log_planner_stats)
812  ShowUsage("PLANNER STATISTICS");
813 
814 #ifdef COPY_PARSE_PLAN_TREES
815  /* Optional debugging check: pass plan output through copyObject() */
816  {
817  PlannedStmt *new_plan = (PlannedStmt *) copyObject(plan);
818 
819  /*
820  * equal() currently does not have routines to compare Plan nodes, so
821  * don't try to test equality here. Perhaps fix someday?
822  */
823 #ifdef NOT_USED
824  /* This checks both copyObject() and the equal() routines... */
825  if (!equal(new_plan, plan))
826  elog(WARNING, "copyObject() failed to produce an equal plan tree");
827  else
828 #endif
829  plan = new_plan;
830  }
831 #endif
832 
833  /*
834  * Print plan if debugging.
835  */
836  if (Debug_print_plan)
837  elog_node_display(LOG, "plan", plan, Debug_pretty_print);
838 
839  TRACE_POSTGRESQL_QUERY_PLAN_DONE();
840 
841  return plan;
842 }
843 
844 /*
845  * Generate plans for a list of already-rewritten queries.
846  *
847  * Normal optimizable statements generate PlannedStmt entries in the result
848  * list. Utility statements are simply represented by their statement nodes.
849  */
850 List *
851 pg_plan_queries(List *querytrees, int cursorOptions, ParamListInfo boundParams)
852 {
853  List *stmt_list = NIL;
854  ListCell *query_list;
855 
856  foreach(query_list, querytrees)
857  {
858  Query *query = (Query *) lfirst(query_list);
859  Node *stmt;
860 
861  if (query->commandType == CMD_UTILITY)
862  {
863  /* Utility commands have no plans. */
864  stmt = query->utilityStmt;
865  }
866  else
867  {
868  stmt = (Node *) pg_plan_query(query, cursorOptions, boundParams);
869  }
870 
871  stmt_list = lappend(stmt_list, stmt);
872  }
873 
874  return stmt_list;
875 }
876 
877 
878 /*
879  * exec_simple_query
880  *
881  * Execute a "simple Query" protocol message.
882  */
883 static void
884 exec_simple_query(const char *query_string)
885 {
887  MemoryContext oldcontext;
888  List *parsetree_list;
889  ListCell *parsetree_item;
890  bool save_log_statement_stats = log_statement_stats;
891  bool was_logged = false;
892  bool isTopLevel;
893  char msec_str[32];
894 
895 
896  /*
897  * Report query to various monitoring facilities.
898  */
899  debug_query_string = query_string;
900 
901  pgstat_report_activity(STATE_RUNNING, query_string);
902 
903  TRACE_POSTGRESQL_QUERY_START(query_string);
904 
905  /*
906  * We use save_log_statement_stats so ShowUsage doesn't report incorrect
907  * results because ResetUsage wasn't called.
908  */
909  if (save_log_statement_stats)
910  ResetUsage();
911 
912  /*
913  * Start up a transaction command. All queries generated by the
914  * query_string will be in this same command block, *unless* we find a
915  * BEGIN/COMMIT/ABORT statement; we have to force a new xact command after
916  * one of those, else bad things will happen in xact.c. (Note that this
917  * will normally change current memory context.)
918  */
920 
921  /*
922  * Zap any pre-existing unnamed statement. (While not strictly necessary,
923  * it seems best to define simple-Query mode as if it used the unnamed
924  * statement and portal; this ensures we recover any storage used by prior
925  * unnamed operations.)
926  */
928 
929  /*
930  * Switch to appropriate context for constructing parsetrees.
931  */
933 
934  /*
935  * Do basic parsing of the query or queries (this should be safe even if
936  * we are in aborted transaction state!)
937  */
938  parsetree_list = pg_parse_query(query_string);
939 
940  /* Log immediately if dictated by log_statement */
941  if (check_log_statement(parsetree_list))
942  {
943  ereport(LOG,
944  (errmsg("statement: %s", query_string),
945  errhidestmt(true),
946  errdetail_execute(parsetree_list)));
947  was_logged = true;
948  }
949 
950  /*
951  * Switch back to transaction context to enter the loop.
952  */
953  MemoryContextSwitchTo(oldcontext);
954 
955  /*
956  * We'll tell PortalRun it's a top-level command iff there's exactly one
957  * raw parsetree. If more than one, it's effectively a transaction block
958  * and we want PreventTransactionChain to reject unsafe commands. (Note:
959  * we're assuming that query rewrite cannot add commands that are
960  * significant to PreventTransactionChain.)
961  */
962  isTopLevel = (list_length(parsetree_list) == 1);
963 
964  /*
965  * Run through the raw parsetree(s) and process each one.
966  */
967  foreach(parsetree_item, parsetree_list)
968  {
969  Node *parsetree = (Node *) lfirst(parsetree_item);
970  bool snapshot_set = false;
971  const char *commandTag;
972  char completionTag[COMPLETION_TAG_BUFSIZE];
973  List *querytree_list,
974  *plantree_list;
975  Portal portal;
976  DestReceiver *receiver;
977  int16 format;
978 
979  /*
980  * Get the command name for use in status display (it also becomes the
981  * default completion tag, down inside PortalRun). Set ps_status and
982  * do any special start-of-SQL-command processing needed by the
983  * destination.
984  */
985  commandTag = CreateCommandTag(parsetree);
986 
987  set_ps_display(commandTag, false);
988 
989  BeginCommand(commandTag, dest);
990 
991  /*
992  * If we are in an aborted transaction, reject all commands except
993  * COMMIT/ABORT. It is important that this test occur before we try
994  * to do parse analysis, rewrite, or planning, since all those phases
995  * try to do database accesses, which may fail in abort state. (It
996  * might be safe to allow some additional utility commands in this
997  * state, but not many...)
998  */
1000  !IsTransactionExitStmt(parsetree))
1001  ereport(ERROR,
1002  (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1003  errmsg("current transaction is aborted, "
1004  "commands ignored until end of transaction block"),
1005  errdetail_abort()));
1006 
1007  /* Make sure we are in a transaction command */
1009 
1010  /* If we got a cancel signal in parsing or prior command, quit */
1012 
1013  /*
1014  * Set up a snapshot if parse analysis/planning will need one.
1015  */
1016  if (analyze_requires_snapshot(parsetree))
1017  {
1019  snapshot_set = true;
1020  }
1021 
1022  /*
1023  * OK to analyze, rewrite, and plan this query.
1024  *
1025  * Switch to appropriate context for constructing querytrees (again,
1026  * these must outlive the execution context).
1027  */
1028  oldcontext = MemoryContextSwitchTo(MessageContext);
1029 
1030  querytree_list = pg_analyze_and_rewrite(parsetree, query_string,
1031  NULL, 0);
1032 
1033  plantree_list = pg_plan_queries(querytree_list, 0, NULL);
1034 
1035  /* Done with the snapshot used for parsing/planning */
1036  if (snapshot_set)
1038 
1039  /* If we got a cancel signal in analysis or planning, quit */
1041 
1042  /*
1043  * Create unnamed portal to run the query or queries in. If there
1044  * already is one, silently drop it.
1045  */
1046  portal = CreatePortal("", true, true);
1047  /* Don't display the portal in pg_cursors */
1048  portal->visible = false;
1049 
1050  /*
1051  * We don't have to copy anything into the portal, because everything
1052  * we are passing here is in MessageContext, which will outlive the
1053  * portal anyway.
1054  */
1055  PortalDefineQuery(portal,
1056  NULL,
1057  query_string,
1058  commandTag,
1059  plantree_list,
1060  NULL);
1061 
1062  /*
1063  * Start the portal. No parameters here.
1064  */
1065  PortalStart(portal, NULL, 0, InvalidSnapshot);
1066 
1067  /*
1068  * Select the appropriate output format: text unless we are doing a
1069  * FETCH from a binary cursor. (Pretty grotty to have to do this here
1070  * --- but it avoids grottiness in other places. Ah, the joys of
1071  * backward compatibility...)
1072  */
1073  format = 0; /* TEXT is default */
1074  if (IsA(parsetree, FetchStmt))
1075  {
1076  FetchStmt *stmt = (FetchStmt *) parsetree;
1077 
1078  if (!stmt->ismove)
1079  {
1080  Portal fportal = GetPortalByName(stmt->portalname);
1081 
1082  if (PortalIsValid(fportal) &&
1083  (fportal->cursorOptions & CURSOR_OPT_BINARY))
1084  format = 1; /* BINARY */
1085  }
1086  }
1087  PortalSetResultFormat(portal, 1, &format);
1088 
1089  /*
1090  * Now we can create the destination receiver object.
1091  */
1092  receiver = CreateDestReceiver(dest);
1093  if (dest == DestRemote)
1094  SetRemoteDestReceiverParams(receiver, portal);
1095 
1096  /*
1097  * Switch back to transaction context for execution.
1098  */
1099  MemoryContextSwitchTo(oldcontext);
1100 
1101  /*
1102  * Run the portal to completion, and then drop it (and the receiver).
1103  */
1104  (void) PortalRun(portal,
1105  FETCH_ALL,
1106  isTopLevel,
1107  receiver,
1108  receiver,
1109  completionTag);
1110 
1111  (*receiver->rDestroy) (receiver);
1112 
1113  PortalDrop(portal, false);
1114 
1115  if (IsA(parsetree, TransactionStmt))
1116  {
1117  /*
1118  * If this was a transaction control statement, commit it. We will
1119  * start a new xact command for the next command (if any).
1120  */
1122  }
1123  else if (lnext(parsetree_item) == NULL)
1124  {
1125  /*
1126  * If this is the last parsetree of the query string, close down
1127  * transaction statement before reporting command-complete. This
1128  * is so that any end-of-transaction errors are reported before
1129  * the command-complete message is issued, to avoid confusing
1130  * clients who will expect either a command-complete message or an
1131  * error, not one and then the other. But for compatibility with
1132  * historical Postgres behavior, we do not force a transaction
1133  * boundary between queries appearing in a single query string.
1134  */
1136  }
1137  else
1138  {
1139  /*
1140  * We need a CommandCounterIncrement after every query, except
1141  * those that start or end a transaction block.
1142  */
1144  }
1145 
1146  /*
1147  * Tell client that we're done with this query. Note we emit exactly
1148  * one EndCommand report for each raw parsetree, thus one for each SQL
1149  * command the client sent, regardless of rewriting. (But a command
1150  * aborted by error will not send an EndCommand report at all.)
1151  */
1152  EndCommand(completionTag, dest);
1153  } /* end loop over parsetrees */
1154 
1155  /*
1156  * Close down transaction statement, if one is open.
1157  */
1159 
1160  /*
1161  * If there were no parsetrees, return EmptyQueryResponse message.
1162  */
1163  if (!parsetree_list)
1164  NullCommand(dest);
1165 
1166  /*
1167  * Emit duration logging if appropriate.
1168  */
1169  switch (check_log_duration(msec_str, was_logged))
1170  {
1171  case 1:
1172  ereport(LOG,
1173  (errmsg("duration: %s ms", msec_str),
1174  errhidestmt(true)));
1175  break;
1176  case 2:
1177  ereport(LOG,
1178  (errmsg("duration: %s ms statement: %s",
1179  msec_str, query_string),
1180  errhidestmt(true),
1181  errdetail_execute(parsetree_list)));
1182  break;
1183  }
1184 
1185  if (save_log_statement_stats)
1186  ShowUsage("QUERY STATISTICS");
1187 
1188  TRACE_POSTGRESQL_QUERY_DONE(query_string);
1189 
1191 }
1192 
1193 /*
1194  * exec_parse_message
1195  *
1196  * Execute a "Parse" protocol message.
1197  */
1198 static void
1199 exec_parse_message(const char *query_string, /* string to execute */
1200  const char *stmt_name, /* name for prepared stmt */
1201  Oid *paramTypes, /* parameter types */
1202  int numParams) /* number of parameters */
1203 {
1204  MemoryContext unnamed_stmt_context = NULL;
1205  MemoryContext oldcontext;
1206  List *parsetree_list;
1207  Node *raw_parse_tree;
1208  const char *commandTag;
1209  List *querytree_list;
1210  CachedPlanSource *psrc;
1211  bool is_named;
1212  bool save_log_statement_stats = log_statement_stats;
1213  char msec_str[32];
1214 
1215  /*
1216  * Report query to various monitoring facilities.
1217  */
1218  debug_query_string = query_string;
1219 
1220  pgstat_report_activity(STATE_RUNNING, query_string);
1221 
1222  set_ps_display("PARSE", false);
1223 
1224  if (save_log_statement_stats)
1225  ResetUsage();
1226 
1227  ereport(DEBUG2,
1228  (errmsg("parse %s: %s",
1229  *stmt_name ? stmt_name : "<unnamed>",
1230  query_string)));
1231 
1232  /*
1233  * Start up a transaction command so we can run parse analysis etc. (Note
1234  * that this will normally change current memory context.) Nothing happens
1235  * if we are already in one.
1236  */
1238 
1239  /*
1240  * Switch to appropriate context for constructing parsetrees.
1241  *
1242  * We have two strategies depending on whether the prepared statement is
1243  * named or not. For a named prepared statement, we do parsing in
1244  * MessageContext and copy the finished trees into the prepared
1245  * statement's plancache entry; then the reset of MessageContext releases
1246  * temporary space used by parsing and rewriting. For an unnamed prepared
1247  * statement, we assume the statement isn't going to hang around long, so
1248  * getting rid of temp space quickly is probably not worth the costs of
1249  * copying parse trees. So in this case, we create the plancache entry's
1250  * query_context here, and do all the parsing work therein.
1251  */
1252  is_named = (stmt_name[0] != '\0');
1253  if (is_named)
1254  {
1255  /* Named prepared statement --- parse in MessageContext */
1256  oldcontext = MemoryContextSwitchTo(MessageContext);
1257  }
1258  else
1259  {
1260  /* Unnamed prepared statement --- release any prior unnamed stmt */
1262  /* Create context for parsing */
1263  unnamed_stmt_context =
1265  "unnamed prepared statement",
1269  oldcontext = MemoryContextSwitchTo(unnamed_stmt_context);
1270  }
1271 
1272  /*
1273  * Do basic parsing of the query or queries (this should be safe even if
1274  * we are in aborted transaction state!)
1275  */
1276  parsetree_list = pg_parse_query(query_string);
1277 
1278  /*
1279  * We only allow a single user statement in a prepared statement. This is
1280  * mainly to keep the protocol simple --- otherwise we'd need to worry
1281  * about multiple result tupdescs and things like that.
1282  */
1283  if (list_length(parsetree_list) > 1)
1284  ereport(ERROR,
1285  (errcode(ERRCODE_SYNTAX_ERROR),
1286  errmsg("cannot insert multiple commands into a prepared statement")));
1287 
1288  if (parsetree_list != NIL)
1289  {
1290  Query *query;
1291  bool snapshot_set = false;
1292  int i;
1293 
1294  raw_parse_tree = (Node *) linitial(parsetree_list);
1295 
1296  /*
1297  * Get the command name for possible use in status display.
1298  */
1299  commandTag = CreateCommandTag(raw_parse_tree);
1300 
1301  /*
1302  * If we are in an aborted transaction, reject all commands except
1303  * COMMIT/ROLLBACK. It is important that this test occur before we
1304  * try to do parse analysis, rewrite, or planning, since all those
1305  * phases try to do database accesses, which may fail in abort state.
1306  * (It might be safe to allow some additional utility commands in this
1307  * state, but not many...)
1308  */
1310  !IsTransactionExitStmt(raw_parse_tree))
1311  ereport(ERROR,
1312  (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1313  errmsg("current transaction is aborted, "
1314  "commands ignored until end of transaction block"),
1315  errdetail_abort()));
1316 
1317  /*
1318  * Create the CachedPlanSource before we do parse analysis, since it
1319  * needs to see the unmodified raw parse tree.
1320  */
1321  psrc = CreateCachedPlan(raw_parse_tree, query_string, commandTag);
1322 
1323  /*
1324  * Set up a snapshot if parse analysis will need one.
1325  */
1326  if (analyze_requires_snapshot(raw_parse_tree))
1327  {
1329  snapshot_set = true;
1330  }
1331 
1332  /*
1333  * Analyze and rewrite the query. Note that the originally specified
1334  * parameter set is not required to be complete, so we have to use
1335  * parse_analyze_varparams().
1336  */
1337  if (log_parser_stats)
1338  ResetUsage();
1339 
1340  query = parse_analyze_varparams(raw_parse_tree,
1341  query_string,
1342  &paramTypes,
1343  &numParams);
1344 
1345  /*
1346  * Check all parameter types got determined.
1347  */
1348  for (i = 0; i < numParams; i++)
1349  {
1350  Oid ptype = paramTypes[i];
1351 
1352  if (ptype == InvalidOid || ptype == UNKNOWNOID)
1353  ereport(ERROR,
1354  (errcode(ERRCODE_INDETERMINATE_DATATYPE),
1355  errmsg("could not determine data type of parameter $%d",
1356  i + 1)));
1357  }
1358 
1359  if (log_parser_stats)
1360  ShowUsage("PARSE ANALYSIS STATISTICS");
1361 
1362  querytree_list = pg_rewrite_query(query);
1363 
1364  /* Done with the snapshot used for parsing */
1365  if (snapshot_set)
1367  }
1368  else
1369  {
1370  /* Empty input string. This is legal. */
1371  raw_parse_tree = NULL;
1372  commandTag = NULL;
1373  psrc = CreateCachedPlan(raw_parse_tree, query_string, commandTag);
1374  querytree_list = NIL;
1375  }
1376 
1377  /*
1378  * CachedPlanSource must be a direct child of MessageContext before we
1379  * reparent unnamed_stmt_context under it, else we have a disconnected
1380  * circular subgraph. Klugy, but less so than flipping contexts even more
1381  * above.
1382  */
1383  if (unnamed_stmt_context)
1385 
1386  /* Finish filling in the CachedPlanSource */
1387  CompleteCachedPlan(psrc,
1388  querytree_list,
1389  unnamed_stmt_context,
1390  paramTypes,
1391  numParams,
1392  NULL,
1393  NULL,
1394  0, /* default cursor options */
1395  true); /* fixed result */
1396 
1397  /* If we got a cancel signal during analysis, quit */
1399 
1400  if (is_named)
1401  {
1402  /*
1403  * Store the query as a prepared statement.
1404  */
1405  StorePreparedStatement(stmt_name, psrc, false);
1406  }
1407  else
1408  {
1409  /*
1410  * We just save the CachedPlanSource into unnamed_stmt_psrc.
1411  */
1412  SaveCachedPlan(psrc);
1413  unnamed_stmt_psrc = psrc;
1414  }
1415 
1416  MemoryContextSwitchTo(oldcontext);
1417 
1418  /*
1419  * We do NOT close the open transaction command here; that only happens
1420  * when the client sends Sync. Instead, do CommandCounterIncrement just
1421  * in case something happened during parse/plan.
1422  */
1424 
1425  /*
1426  * Send ParseComplete.
1427  */
1429  pq_putemptymessage('1');
1430 
1431  /*
1432  * Emit duration logging if appropriate.
1433  */
1434  switch (check_log_duration(msec_str, false))
1435  {
1436  case 1:
1437  ereport(LOG,
1438  (errmsg("duration: %s ms", msec_str),
1439  errhidestmt(true)));
1440  break;
1441  case 2:
1442  ereport(LOG,
1443  (errmsg("duration: %s ms parse %s: %s",
1444  msec_str,
1445  *stmt_name ? stmt_name : "<unnamed>",
1446  query_string),
1447  errhidestmt(true)));
1448  break;
1449  }
1450 
1451  if (save_log_statement_stats)
1452  ShowUsage("PARSE MESSAGE STATISTICS");
1453 
1455 }
1456 
1457 /*
1458  * exec_bind_message
1459  *
1460  * Process a "Bind" message to create a portal from a prepared statement
1461  */
1462 static void
1464 {
1465  const char *portal_name;
1466  const char *stmt_name;
1467  int numPFormats;
1468  int16 *pformats = NULL;
1469  int numParams;
1470  int numRFormats;
1471  int16 *rformats = NULL;
1472  CachedPlanSource *psrc;
1473  CachedPlan *cplan;
1474  Portal portal;
1475  char *query_string;
1476  char *saved_stmt_name;
1477  ParamListInfo params;
1478  MemoryContext oldContext;
1479  bool save_log_statement_stats = log_statement_stats;
1480  bool snapshot_set = false;
1481  char msec_str[32];
1482 
1483  /* Get the fixed part of the message */
1484  portal_name = pq_getmsgstring(input_message);
1485  stmt_name = pq_getmsgstring(input_message);
1486 
1487  ereport(DEBUG2,
1488  (errmsg("bind %s to %s",
1489  *portal_name ? portal_name : "<unnamed>",
1490  *stmt_name ? stmt_name : "<unnamed>")));
1491 
1492  /* Find prepared statement */
1493  if (stmt_name[0] != '\0')
1494  {
1495  PreparedStatement *pstmt;
1496 
1497  pstmt = FetchPreparedStatement(stmt_name, true);
1498  psrc = pstmt->plansource;
1499  }
1500  else
1501  {
1502  /* special-case the unnamed statement */
1503  psrc = unnamed_stmt_psrc;
1504  if (!psrc)
1505  ereport(ERROR,
1506  (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
1507  errmsg("unnamed prepared statement does not exist")));
1508  }
1509 
1510  /*
1511  * Report query to various monitoring facilities.
1512  */
1514 
1516 
1517  set_ps_display("BIND", false);
1518 
1519  if (save_log_statement_stats)
1520  ResetUsage();
1521 
1522  /*
1523  * Start up a transaction command so we can call functions etc. (Note that
1524  * this will normally change current memory context.) Nothing happens if
1525  * we are already in one.
1526  */
1528 
1529  /* Switch back to message context */
1531 
1532  /* Get the parameter format codes */
1533  numPFormats = pq_getmsgint(input_message, 2);
1534  if (numPFormats > 0)
1535  {
1536  int i;
1537 
1538  pformats = (int16 *) palloc(numPFormats * sizeof(int16));
1539  for (i = 0; i < numPFormats; i++)
1540  pformats[i] = pq_getmsgint(input_message, 2);
1541  }
1542 
1543  /* Get the parameter value count */
1544  numParams = pq_getmsgint(input_message, 2);
1545 
1546  if (numPFormats > 1 && numPFormats != numParams)
1547  ereport(ERROR,
1548  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1549  errmsg("bind message has %d parameter formats but %d parameters",
1550  numPFormats, numParams)));
1551 
1552  if (numParams != psrc->num_params)
1553  ereport(ERROR,
1554  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1555  errmsg("bind message supplies %d parameters, but prepared statement \"%s\" requires %d",
1556  numParams, stmt_name, psrc->num_params)));
1557 
1558  /*
1559  * If we are in aborted transaction state, the only portals we can
1560  * actually run are those containing COMMIT or ROLLBACK commands. We
1561  * disallow binding anything else to avoid problems with infrastructure
1562  * that expects to run inside a valid transaction. We also disallow
1563  * binding any parameters, since we can't risk calling user-defined I/O
1564  * functions.
1565  */
1568  numParams != 0))
1569  ereport(ERROR,
1570  (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1571  errmsg("current transaction is aborted, "
1572  "commands ignored until end of transaction block"),
1573  errdetail_abort()));
1574 
1575  /*
1576  * Create the portal. Allow silent replacement of an existing portal only
1577  * if the unnamed portal is specified.
1578  */
1579  if (portal_name[0] == '\0')
1580  portal = CreatePortal(portal_name, true, true);
1581  else
1582  portal = CreatePortal(portal_name, false, false);
1583 
1584  /*
1585  * Prepare to copy stuff into the portal's memory context. We do all this
1586  * copying first, because it could possibly fail (out-of-memory) and we
1587  * don't want a failure to occur between GetCachedPlan and
1588  * PortalDefineQuery; that would result in leaking our plancache refcount.
1589  */
1590  oldContext = MemoryContextSwitchTo(PortalGetHeapMemory(portal));
1591 
1592  /* Copy the plan's query string into the portal */
1593  query_string = pstrdup(psrc->query_string);
1594 
1595  /* Likewise make a copy of the statement name, unless it's unnamed */
1596  if (stmt_name[0])
1597  saved_stmt_name = pstrdup(stmt_name);
1598  else
1599  saved_stmt_name = NULL;
1600 
1601  /*
1602  * Set a snapshot if we have parameters to fetch (since the input
1603  * functions might need it) or the query isn't a utility command (and
1604  * hence could require redoing parse analysis and planning). We keep the
1605  * snapshot active till we're done, so that plancache.c doesn't have to
1606  * take new ones.
1607  */
1608  if (numParams > 0 ||
1609  (psrc->raw_parse_tree &&
1611  {
1613  snapshot_set = true;
1614  }
1615 
1616  /*
1617  * Fetch parameters, if any, and store in the portal's memory context.
1618  */
1619  if (numParams > 0)
1620  {
1621  int paramno;
1622 
1623  params = (ParamListInfo) palloc(offsetof(ParamListInfoData, params) +
1624  numParams * sizeof(ParamExternData));
1625  /* we have static list of params, so no hooks needed */
1626  params->paramFetch = NULL;
1627  params->paramFetchArg = NULL;
1628  params->parserSetup = NULL;
1629  params->parserSetupArg = NULL;
1630  params->numParams = numParams;
1631 
1632  for (paramno = 0; paramno < numParams; paramno++)
1633  {
1634  Oid ptype = psrc->param_types[paramno];
1635  int32 plength;
1636  Datum pval;
1637  bool isNull;
1638  StringInfoData pbuf;
1639  char csave;
1640  int16 pformat;
1641 
1642  plength = pq_getmsgint(input_message, 4);
1643  isNull = (plength == -1);
1644 
1645  if (!isNull)
1646  {
1647  const char *pvalue = pq_getmsgbytes(input_message, plength);
1648 
1649  /*
1650  * Rather than copying data around, we just set up a phony
1651  * StringInfo pointing to the correct portion of the message
1652  * buffer. We assume we can scribble on the message buffer so
1653  * as to maintain the convention that StringInfos have a
1654  * trailing null. This is grotty but is a big win when
1655  * dealing with very large parameter strings.
1656  */
1657  pbuf.data = (char *) pvalue;
1658  pbuf.maxlen = plength + 1;
1659  pbuf.len = plength;
1660  pbuf.cursor = 0;
1661 
1662  csave = pbuf.data[plength];
1663  pbuf.data[plength] = '\0';
1664  }
1665  else
1666  {
1667  pbuf.data = NULL; /* keep compiler quiet */
1668  csave = 0;
1669  }
1670 
1671  if (numPFormats > 1)
1672  pformat = pformats[paramno];
1673  else if (numPFormats > 0)
1674  pformat = pformats[0];
1675  else
1676  pformat = 0; /* default = text */
1677 
1678  if (pformat == 0) /* text mode */
1679  {
1680  Oid typinput;
1681  Oid typioparam;
1682  char *pstring;
1683 
1684  getTypeInputInfo(ptype, &typinput, &typioparam);
1685 
1686  /*
1687  * We have to do encoding conversion before calling the
1688  * typinput routine.
1689  */
1690  if (isNull)
1691  pstring = NULL;
1692  else
1693  pstring = pg_client_to_server(pbuf.data, plength);
1694 
1695  pval = OidInputFunctionCall(typinput, pstring, typioparam, -1);
1696 
1697  /* Free result of encoding conversion, if any */
1698  if (pstring && pstring != pbuf.data)
1699  pfree(pstring);
1700  }
1701  else if (pformat == 1) /* binary mode */
1702  {
1703  Oid typreceive;
1704  Oid typioparam;
1705  StringInfo bufptr;
1706 
1707  /*
1708  * Call the parameter type's binary input converter
1709  */
1710  getTypeBinaryInputInfo(ptype, &typreceive, &typioparam);
1711 
1712  if (isNull)
1713  bufptr = NULL;
1714  else
1715  bufptr = &pbuf;
1716 
1717  pval = OidReceiveFunctionCall(typreceive, bufptr, typioparam, -1);
1718 
1719  /* Trouble if it didn't eat the whole buffer */
1720  if (!isNull && pbuf.cursor != pbuf.len)
1721  ereport(ERROR,
1722  (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
1723  errmsg("incorrect binary data format in bind parameter %d",
1724  paramno + 1)));
1725  }
1726  else
1727  {
1728  ereport(ERROR,
1729  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1730  errmsg("unsupported format code: %d",
1731  pformat)));
1732  pval = 0; /* keep compiler quiet */
1733  }
1734 
1735  /* Restore message buffer contents */
1736  if (!isNull)
1737  pbuf.data[plength] = csave;
1738 
1739  params->params[paramno].value = pval;
1740  params->params[paramno].isnull = isNull;
1741 
1742  /*
1743  * We mark the params as CONST. This ensures that any custom plan
1744  * makes full use of the parameter values.
1745  */
1746  params->params[paramno].pflags = PARAM_FLAG_CONST;
1747  params->params[paramno].ptype = ptype;
1748  }
1749  }
1750  else
1751  params = NULL;
1752 
1753  /* Done storing stuff in portal's context */
1754  MemoryContextSwitchTo(oldContext);
1755 
1756  /* Get the result format codes */
1757  numRFormats = pq_getmsgint(input_message, 2);
1758  if (numRFormats > 0)
1759  {
1760  int i;
1761 
1762  rformats = (int16 *) palloc(numRFormats * sizeof(int16));
1763  for (i = 0; i < numRFormats; i++)
1764  rformats[i] = pq_getmsgint(input_message, 2);
1765  }
1766 
1767  pq_getmsgend(input_message);
1768 
1769  /*
1770  * Obtain a plan from the CachedPlanSource. Any cruft from (re)planning
1771  * will be generated in MessageContext. The plan refcount will be
1772  * assigned to the Portal, so it will be released at portal destruction.
1773  */
1774  cplan = GetCachedPlan(psrc, params, false);
1775 
1776  /*
1777  * Now we can define the portal.
1778  *
1779  * DO NOT put any code that could possibly throw an error between the
1780  * above GetCachedPlan call and here.
1781  */
1782  PortalDefineQuery(portal,
1783  saved_stmt_name,
1784  query_string,
1785  psrc->commandTag,
1786  cplan->stmt_list,
1787  cplan);
1788 
1789  /* Done with the snapshot used for parameter I/O and parsing/planning */
1790  if (snapshot_set)
1792 
1793  /*
1794  * And we're ready to start portal execution.
1795  */
1796  PortalStart(portal, params, 0, InvalidSnapshot);
1797 
1798  /*
1799  * Apply the result format requests to the portal.
1800  */
1801  PortalSetResultFormat(portal, numRFormats, rformats);
1802 
1803  /*
1804  * Send BindComplete.
1805  */
1807  pq_putemptymessage('2');
1808 
1809  /*
1810  * Emit duration logging if appropriate.
1811  */
1812  switch (check_log_duration(msec_str, false))
1813  {
1814  case 1:
1815  ereport(LOG,
1816  (errmsg("duration: %s ms", msec_str),
1817  errhidestmt(true)));
1818  break;
1819  case 2:
1820  ereport(LOG,
1821  (errmsg("duration: %s ms bind %s%s%s: %s",
1822  msec_str,
1823  *stmt_name ? stmt_name : "<unnamed>",
1824  *portal_name ? "/" : "",
1825  *portal_name ? portal_name : "",
1826  psrc->query_string),
1827  errhidestmt(true),
1828  errdetail_params(params)));
1829  break;
1830  }
1831 
1832  if (save_log_statement_stats)
1833  ShowUsage("BIND MESSAGE STATISTICS");
1834 
1836 }
1837 
1838 /*
1839  * exec_execute_message
1840  *
1841  * Process an "Execute" message for a portal
1842  */
1843 static void
1844 exec_execute_message(const char *portal_name, long max_rows)
1845 {
1846  CommandDest dest;
1847  DestReceiver *receiver;
1848  Portal portal;
1849  bool completed;
1850  char completionTag[COMPLETION_TAG_BUFSIZE];
1851  const char *sourceText;
1852  const char *prepStmtName;
1853  ParamListInfo portalParams;
1854  bool save_log_statement_stats = log_statement_stats;
1855  bool is_xact_command;
1856  bool execute_is_fetch;
1857  bool was_logged = false;
1858  char msec_str[32];
1859 
1860  /* Adjust destination to tell printtup.c what to do */
1861  dest = whereToSendOutput;
1862  if (dest == DestRemote)
1863  dest = DestRemoteExecute;
1864 
1865  portal = GetPortalByName(portal_name);
1866  if (!PortalIsValid(portal))
1867  ereport(ERROR,
1868  (errcode(ERRCODE_UNDEFINED_CURSOR),
1869  errmsg("portal \"%s\" does not exist", portal_name)));
1870 
1871  /*
1872  * If the original query was a null string, just return
1873  * EmptyQueryResponse.
1874  */
1875  if (portal->commandTag == NULL)
1876  {
1877  Assert(portal->stmts == NIL);
1878  NullCommand(dest);
1879  return;
1880  }
1881 
1882  /* Does the portal contain a transaction command? */
1883  is_xact_command = IsTransactionStmtList(portal->stmts);
1884 
1885  /*
1886  * We must copy the sourceText and prepStmtName into MessageContext in
1887  * case the portal is destroyed during finish_xact_command. Can avoid the
1888  * copy if it's not an xact command, though.
1889  */
1890  if (is_xact_command)
1891  {
1892  sourceText = pstrdup(portal->sourceText);
1893  if (portal->prepStmtName)
1894  prepStmtName = pstrdup(portal->prepStmtName);
1895  else
1896  prepStmtName = "<unnamed>";
1897 
1898  /*
1899  * An xact command shouldn't have any parameters, which is a good
1900  * thing because they wouldn't be around after finish_xact_command.
1901  */
1902  portalParams = NULL;
1903  }
1904  else
1905  {
1906  sourceText = portal->sourceText;
1907  if (portal->prepStmtName)
1908  prepStmtName = portal->prepStmtName;
1909  else
1910  prepStmtName = "<unnamed>";
1911  portalParams = portal->portalParams;
1912  }
1913 
1914  /*
1915  * Report query to various monitoring facilities.
1916  */
1917  debug_query_string = sourceText;
1918 
1920 
1921  set_ps_display(portal->commandTag, false);
1922 
1923  if (save_log_statement_stats)
1924  ResetUsage();
1925 
1926  BeginCommand(portal->commandTag, dest);
1927 
1928  /*
1929  * Create dest receiver in MessageContext (we don't want it in transaction
1930  * context, because that may get deleted if portal contains VACUUM).
1931  */
1932  receiver = CreateDestReceiver(dest);
1933  if (dest == DestRemoteExecute)
1934  SetRemoteDestReceiverParams(receiver, portal);
1935 
1936  /*
1937  * Ensure we are in a transaction command (this should normally be the
1938  * case already due to prior BIND).
1939  */
1941 
1942  /*
1943  * If we re-issue an Execute protocol request against an existing portal,
1944  * then we are only fetching more rows rather than completely re-executing
1945  * the query from the start. atStart is never reset for a v3 portal, so we
1946  * are safe to use this check.
1947  */
1948  execute_is_fetch = !portal->atStart;
1949 
1950  /* Log immediately if dictated by log_statement */
1951  if (check_log_statement(portal->stmts))
1952  {
1953  ereport(LOG,
1954  (errmsg("%s %s%s%s: %s",
1955  execute_is_fetch ?
1956  _("execute fetch from") :
1957  _("execute"),
1958  prepStmtName,
1959  *portal_name ? "/" : "",
1960  *portal_name ? portal_name : "",
1961  sourceText),
1962  errhidestmt(true),
1963  errdetail_params(portalParams)));
1964  was_logged = true;
1965  }
1966 
1967  /*
1968  * If we are in aborted transaction state, the only portals we can
1969  * actually run are those containing COMMIT or ROLLBACK commands.
1970  */
1972  !IsTransactionExitStmtList(portal->stmts))
1973  ereport(ERROR,
1974  (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1975  errmsg("current transaction is aborted, "
1976  "commands ignored until end of transaction block"),
1977  errdetail_abort()));
1978 
1979  /* Check for cancel signal before we start execution */
1981 
1982  /*
1983  * Okay to run the portal.
1984  */
1985  if (max_rows <= 0)
1986  max_rows = FETCH_ALL;
1987 
1988  completed = PortalRun(portal,
1989  max_rows,
1990  true, /* always top level */
1991  receiver,
1992  receiver,
1993  completionTag);
1994 
1995  (*receiver->rDestroy) (receiver);
1996 
1997  if (completed)
1998  {
1999  if (is_xact_command)
2000  {
2001  /*
2002  * If this was a transaction control statement, commit it. We
2003  * will start a new xact command for the next command (if any).
2004  */
2006  }
2007  else
2008  {
2009  /*
2010  * We need a CommandCounterIncrement after every query, except
2011  * those that start or end a transaction block.
2012  */
2014  }
2015 
2016  /* Send appropriate CommandComplete to client */
2017  EndCommand(completionTag, dest);
2018  }
2019  else
2020  {
2021  /* Portal run not complete, so send PortalSuspended */
2023  pq_putemptymessage('s');
2024  }
2025 
2026  /*
2027  * Emit duration logging if appropriate.
2028  */
2029  switch (check_log_duration(msec_str, was_logged))
2030  {
2031  case 1:
2032  ereport(LOG,
2033  (errmsg("duration: %s ms", msec_str),
2034  errhidestmt(true)));
2035  break;
2036  case 2:
2037  ereport(LOG,
2038  (errmsg("duration: %s ms %s %s%s%s: %s",
2039  msec_str,
2040  execute_is_fetch ?
2041  _("execute fetch from") :
2042  _("execute"),
2043  prepStmtName,
2044  *portal_name ? "/" : "",
2045  *portal_name ? portal_name : "",
2046  sourceText),
2047  errhidestmt(true),
2048  errdetail_params(portalParams)));
2049  break;
2050  }
2051 
2052  if (save_log_statement_stats)
2053  ShowUsage("EXECUTE MESSAGE STATISTICS");
2054 
2056 }
2057 
2058 /*
2059  * check_log_statement
2060  * Determine whether command should be logged because of log_statement
2061  *
2062  * stmt_list can be either raw grammar output or a list of planned
2063  * statements
2064  */
2065 static bool
2067 {
2068  ListCell *stmt_item;
2069 
2070  if (log_statement == LOGSTMT_NONE)
2071  return false;
2072  if (log_statement == LOGSTMT_ALL)
2073  return true;
2074 
2075  /* Else we have to inspect the statement(s) to see whether to log */
2076  foreach(stmt_item, stmt_list)
2077  {
2078  Node *stmt = (Node *) lfirst(stmt_item);
2079 
2080  if (GetCommandLogLevel(stmt) <= log_statement)
2081  return true;
2082  }
2083 
2084  return false;
2085 }
2086 
2087 /*
2088  * check_log_duration
2089  * Determine whether current command's duration should be logged
2090  *
2091  * Returns:
2092  * 0 if no logging is needed
2093  * 1 if just the duration should be logged
2094  * 2 if duration and query details should be logged
2095  *
2096  * If logging is needed, the duration in msec is formatted into msec_str[],
2097  * which must be a 32-byte buffer.
2098  *
2099  * was_logged should be TRUE if caller already logged query details (this
2100  * essentially prevents 2 from being returned).
2101  */
2102 int
2103 check_log_duration(char *msec_str, bool was_logged)
2104 {
2106  {
2107  long secs;
2108  int usecs;
2109  int msecs;
2110  bool exceeded;
2111 
2114  &secs, &usecs);
2115  msecs = usecs / 1000;
2116 
2117  /*
2118  * This odd-looking test for log_min_duration_statement being exceeded
2119  * is designed to avoid integer overflow with very long durations:
2120  * don't compute secs * 1000 until we've verified it will fit in int.
2121  */
2122  exceeded = (log_min_duration_statement == 0 ||
2124  (secs > log_min_duration_statement / 1000 ||
2125  secs * 1000 + msecs >= log_min_duration_statement)));
2126 
2127  if (exceeded || log_duration)
2128  {
2129  snprintf(msec_str, 32, "%ld.%03d",
2130  secs * 1000 + msecs, usecs % 1000);
2131  if (exceeded && !was_logged)
2132  return 2;
2133  else
2134  return 1;
2135  }
2136  }
2137 
2138  return 0;
2139 }
2140 
2141 /*
2142  * errdetail_execute
2143  *
2144  * Add an errdetail() line showing the query referenced by an EXECUTE, if any.
2145  * The argument is the raw parsetree list.
2146  */
2147 static int
2148 errdetail_execute(List *raw_parsetree_list)
2149 {
2150  ListCell *parsetree_item;
2151 
2152  foreach(parsetree_item, raw_parsetree_list)
2153  {
2154  Node *parsetree = (Node *) lfirst(parsetree_item);
2155 
2156  if (IsA(parsetree, ExecuteStmt))
2157  {
2158  ExecuteStmt *stmt = (ExecuteStmt *) parsetree;
2159  PreparedStatement *pstmt;
2160 
2161  pstmt = FetchPreparedStatement(stmt->name, false);
2162  if (pstmt)
2163  {
2164  errdetail("prepare: %s", pstmt->plansource->query_string);
2165  return 0;
2166  }
2167  }
2168  }
2169 
2170  return 0;
2171 }
2172 
2173 /*
2174  * errdetail_params
2175  *
2176  * Add an errdetail() line showing bind-parameter data, if available.
2177  */
2178 static int
2180 {
2181  /* We mustn't call user-defined I/O functions when in an aborted xact */
2182  if (params && params->numParams > 0 && !IsAbortedTransactionBlockState())
2183  {
2184  StringInfoData param_str;
2185  MemoryContext oldcontext;
2186  int paramno;
2187 
2188  /* Make sure any trash is generated in MessageContext */
2189  oldcontext = MemoryContextSwitchTo(MessageContext);
2190 
2191  initStringInfo(&param_str);
2192 
2193  for (paramno = 0; paramno < params->numParams; paramno++)
2194  {
2195  ParamExternData *prm = &params->params[paramno];
2196  Oid typoutput;
2197  bool typisvarlena;
2198  char *pstring;
2199  char *p;
2200 
2201  appendStringInfo(&param_str, "%s$%d = ",
2202  paramno > 0 ? ", " : "",
2203  paramno + 1);
2204 
2205  if (prm->isnull || !OidIsValid(prm->ptype))
2206  {
2207  appendStringInfoString(&param_str, "NULL");
2208  continue;
2209  }
2210 
2211  getTypeOutputInfo(prm->ptype, &typoutput, &typisvarlena);
2212 
2213  pstring = OidOutputFunctionCall(typoutput, prm->value);
2214 
2215  appendStringInfoCharMacro(&param_str, '\'');
2216  for (p = pstring; *p; p++)
2217  {
2218  if (*p == '\'') /* double single quotes */
2219  appendStringInfoCharMacro(&param_str, *p);
2220  appendStringInfoCharMacro(&param_str, *p);
2221  }
2222  appendStringInfoCharMacro(&param_str, '\'');
2223 
2224  pfree(pstring);
2225  }
2226 
2227  errdetail("parameters: %s", param_str.data);
2228 
2229  pfree(param_str.data);
2230 
2231  MemoryContextSwitchTo(oldcontext);
2232  }
2233 
2234  return 0;
2235 }
2236 
2237 /*
2238  * errdetail_abort
2239  *
2240  * Add an errdetail() line showing abort reason, if any.
2241  */
2242 static int
2244 {
2246  errdetail("abort reason: recovery conflict");
2247 
2248  return 0;
2249 }
2250 
2251 /*
2252  * errdetail_recovery_conflict
2253  *
2254  * Add an errdetail() line showing conflict source.
2255  */
2256 static int
2258 {
2259  switch (RecoveryConflictReason)
2260  {
2262  errdetail("User was holding shared buffer pin for too long.");
2263  break;
2265  errdetail("User was holding a relation lock for too long.");
2266  break;
2268  errdetail("User was or might have been using tablespace that must be dropped.");
2269  break;
2271  errdetail("User query might have needed to see row versions that must be removed.");
2272  break;
2274  errdetail("User transaction caused buffer deadlock with recovery.");
2275  break;
2277  errdetail("User was connected to a database that must be dropped.");
2278  break;
2279  default:
2280  break;
2281  /* no errdetail */
2282  }
2283 
2284  return 0;
2285 }
2286 
2287 /*
2288  * exec_describe_statement_message
2289  *
2290  * Process a "Describe" message for a prepared statement
2291  */
2292 static void
2293 exec_describe_statement_message(const char *stmt_name)
2294 {
2295  CachedPlanSource *psrc;
2297  int i;
2298 
2299  /*
2300  * Start up a transaction command. (Note that this will normally change
2301  * current memory context.) Nothing happens if we are already in one.
2302  */
2304 
2305  /* Switch back to message context */
2307 
2308  /* Find prepared statement */
2309  if (stmt_name[0] != '\0')
2310  {
2311  PreparedStatement *pstmt;
2312 
2313  pstmt = FetchPreparedStatement(stmt_name, true);
2314  psrc = pstmt->plansource;
2315  }
2316  else
2317  {
2318  /* special-case the unnamed statement */
2319  psrc = unnamed_stmt_psrc;
2320  if (!psrc)
2321  ereport(ERROR,
2322  (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
2323  errmsg("unnamed prepared statement does not exist")));
2324  }
2325 
2326  /* Prepared statements shouldn't have changeable result descs */
2327  Assert(psrc->fixed_result);
2328 
2329  /*
2330  * If we are in aborted transaction state, we can't run
2331  * SendRowDescriptionMessage(), because that needs catalog accesses.
2332  * Hence, refuse to Describe statements that return data. (We shouldn't
2333  * just refuse all Describes, since that might break the ability of some
2334  * clients to issue COMMIT or ROLLBACK commands, if they use code that
2335  * blindly Describes whatever it does.) We can Describe parameters
2336  * without doing anything dangerous, so we don't restrict that.
2337  */
2339  psrc->resultDesc)
2340  ereport(ERROR,
2341  (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2342  errmsg("current transaction is aborted, "
2343  "commands ignored until end of transaction block"),
2344  errdetail_abort()));
2345 
2347  return; /* can't actually do anything... */
2348 
2349  /*
2350  * First describe the parameters...
2351  */
2352  pq_beginmessage(&buf, 't'); /* parameter description message type */
2353  pq_sendint(&buf, psrc->num_params, 2);
2354 
2355  for (i = 0; i < psrc->num_params; i++)
2356  {
2357  Oid ptype = psrc->param_types[i];
2358 
2359  pq_sendint(&buf, (int) ptype, 4);
2360  }
2361  pq_endmessage(&buf);
2362 
2363  /*
2364  * Next send RowDescription or NoData to describe the result...
2365  */
2366  if (psrc->resultDesc)
2367  {
2368  List *tlist;
2369 
2370  /* Get the plan's primary targetlist */
2371  tlist = CachedPlanGetTargetList(psrc);
2372 
2373  SendRowDescriptionMessage(psrc->resultDesc, tlist, NULL);
2374  }
2375  else
2376  pq_putemptymessage('n'); /* NoData */
2377 
2378 }
2379 
2380 /*
2381  * exec_describe_portal_message
2382  *
2383  * Process a "Describe" message for a portal
2384  */
2385 static void
2386 exec_describe_portal_message(const char *portal_name)
2387 {
2388  Portal portal;
2389 
2390  /*
2391  * Start up a transaction command. (Note that this will normally change
2392  * current memory context.) Nothing happens if we are already in one.
2393  */
2395 
2396  /* Switch back to message context */
2398 
2399  portal = GetPortalByName(portal_name);
2400  if (!PortalIsValid(portal))
2401  ereport(ERROR,
2402  (errcode(ERRCODE_UNDEFINED_CURSOR),
2403  errmsg("portal \"%s\" does not exist", portal_name)));
2404 
2405  /*
2406  * If we are in aborted transaction state, we can't run
2407  * SendRowDescriptionMessage(), because that needs catalog accesses.
2408  * Hence, refuse to Describe portals that return data. (We shouldn't just
2409  * refuse all Describes, since that might break the ability of some
2410  * clients to issue COMMIT or ROLLBACK commands, if they use code that
2411  * blindly Describes whatever it does.)
2412  */
2414  portal->tupDesc)
2415  ereport(ERROR,
2416  (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2417  errmsg("current transaction is aborted, "
2418  "commands ignored until end of transaction block"),
2419  errdetail_abort()));
2420 
2422  return; /* can't actually do anything... */
2423 
2424  if (portal->tupDesc)
2426  FetchPortalTargetList(portal),
2427  portal->formats);
2428  else
2429  pq_putemptymessage('n'); /* NoData */
2430 }
2431 
2432 
2433 /*
2434  * Convenience routines for starting/committing a single command.
2435  */
2436 static void
2438 {
2439  if (!xact_started)
2440  {
2441  ereport(DEBUG3,
2442  (errmsg_internal("StartTransactionCommand")));
2444 
2445  /* Set statement timeout running, if any */
2446  /* NB: this mustn't be enabled until we are within an xact */
2447  if (StatementTimeout > 0)
2449  else
2451 
2452  xact_started = true;
2453  }
2454 }
2455 
2456 static void
2458 {
2459  if (xact_started)
2460  {
2461  /* Cancel any active statement timeout before committing */
2463 
2464  /* Now commit the command */
2465  ereport(DEBUG3,
2466  (errmsg_internal("CommitTransactionCommand")));
2467 
2469 
2470 #ifdef MEMORY_CONTEXT_CHECKING
2471  /* Check all memory contexts that weren't freed during commit */
2472  /* (those that were, were checked before being deleted) */
2473  MemoryContextCheck(TopMemoryContext);
2474 #endif
2475 
2476 #ifdef SHOW_MEMORY_STATS
2477  /* Print mem stats after each commit for leak tracking */
2479 #endif
2480 
2481  xact_started = false;
2482  }
2483 }
2484 
2485 
2486 /*
2487  * Convenience routines for checking whether a statement is one of the
2488  * ones that we allow in transaction-aborted state.
2489  */
2490 
2491 /* Test a bare parsetree */
2492 static bool
2494 {
2495  if (parsetree && IsA(parsetree, TransactionStmt))
2496  {
2497  TransactionStmt *stmt = (TransactionStmt *) parsetree;
2498 
2499  if (stmt->kind == TRANS_STMT_COMMIT ||
2500  stmt->kind == TRANS_STMT_PREPARE ||
2501  stmt->kind == TRANS_STMT_ROLLBACK ||
2502  stmt->kind == TRANS_STMT_ROLLBACK_TO)
2503  return true;
2504  }
2505  return false;
2506 }
2507 
2508 /* Test a list that might contain Query nodes or bare parsetrees */
2509 static bool
2511 {
2512  if (list_length(parseTrees) == 1)
2513  {
2514  Node *stmt = (Node *) linitial(parseTrees);
2515 
2516  if (IsA(stmt, Query))
2517  {
2518  Query *query = (Query *) stmt;
2519 
2520  if (query->commandType == CMD_UTILITY &&
2522  return true;
2523  }
2524  else if (IsTransactionExitStmt(stmt))
2525  return true;
2526  }
2527  return false;
2528 }
2529 
2530 /* Test a list that might contain Query nodes or bare parsetrees */
2531 static bool
2533 {
2534  if (list_length(parseTrees) == 1)
2535  {
2536  Node *stmt = (Node *) linitial(parseTrees);
2537 
2538  if (IsA(stmt, Query))
2539  {
2540  Query *query = (Query *) stmt;
2541 
2542  if (query->commandType == CMD_UTILITY &&
2543  IsA(query->utilityStmt, TransactionStmt))
2544  return true;
2545  }
2546  else if (IsA(stmt, TransactionStmt))
2547  return true;
2548  }
2549  return false;
2550 }
2551 
2552 /* Release any existing unnamed prepared statement */
2553 static void
2555 {
2556  /* paranoia to avoid a dangling pointer in case of error */
2557  if (unnamed_stmt_psrc)
2558  {
2560 
2561  unnamed_stmt_psrc = NULL;
2562  DropCachedPlan(psrc);
2563  }
2564 }
2565 
2566 
2567 /* --------------------------------
2568  * signal handler routines used in PostgresMain()
2569  * --------------------------------
2570  */
2571 
2572 /*
2573  * quickdie() occurs when signalled SIGQUIT by the postmaster.
2574  *
2575  * Some backend has bought the farm,
2576  * so we need to stop what we're doing and exit.
2577  */
2578 void
2580 {
2581  sigaddset(&BlockSig, SIGQUIT); /* prevent nested calls */
2582  PG_SETMASK(&BlockSig);
2583 
2584  /*
2585  * Prevent interrupts while exiting; though we just blocked signals that
2586  * would queue new interrupts, one may have been pending. We don't want a
2587  * quickdie() downgraded to a mere query cancel.
2588  */
2589  HOLD_INTERRUPTS();
2590 
2591  /*
2592  * If we're aborting out of client auth, don't risk trying to send
2593  * anything to the client; we will likely violate the protocol, not to
2594  * mention that we may have interrupted the guts of OpenSSL or some
2595  * authentication library.
2596  */
2599 
2600  /*
2601  * Ideally this should be ereport(FATAL), but then we'd not get control
2602  * back...
2603  */
2604  ereport(WARNING,
2605  (errcode(ERRCODE_CRASH_SHUTDOWN),
2606  errmsg("terminating connection because of crash of another server process"),
2607  errdetail("The postmaster has commanded this server process to roll back"
2608  " the current transaction and exit, because another"
2609  " server process exited abnormally and possibly corrupted"
2610  " shared memory."),
2611  errhint("In a moment you should be able to reconnect to the"
2612  " database and repeat your command.")));
2613 
2614  /*
2615  * We DO NOT want to run proc_exit() callbacks -- we're here because
2616  * shared memory may be corrupted, so we don't want to try to clean up our
2617  * transaction. Just nail the windows shut and get out of town. Now that
2618  * there's an atexit callback to prevent third-party code from breaking
2619  * things by calling exit() directly, we have to reset the callbacks
2620  * explicitly to make this work as intended.
2621  */
2622  on_exit_reset();
2623 
2624  /*
2625  * Note we do exit(2) not exit(0). This is to force the postmaster into a
2626  * system reset cycle if some idiot DBA sends a manual SIGQUIT to a random
2627  * backend. This is necessary precisely because we don't clean up our
2628  * shared memory state. (The "dead man switch" mechanism in pmsignal.c
2629  * should ensure the postmaster sees this as a crash, too, but no harm in
2630  * being doubly sure.)
2631  */
2632  exit(2);
2633 }
2634 
2635 /*
2636  * Shutdown signal from postmaster: abort transaction and exit
2637  * at soonest convenient time
2638  */
2639 void
2641 {
2642  int save_errno = errno;
2643 
2644  /* Don't joggle the elbow of proc_exit */
2645  if (!proc_exit_inprogress)
2646  {
2647  InterruptPending = true;
2648  ProcDiePending = true;
2649  }
2650 
2651  /* If we're still here, waken anything waiting on the process latch */
2652  SetLatch(MyLatch);
2653 
2654  /*
2655  * If we're in single user mode, we want to quit immediately - we can't
2656  * rely on latches as they wouldn't work when stdin/stdout is a file.
2657  * Rather ugly, but it's unlikely to be worthwhile to invest much more
2658  * effort just for the benefit of single user mode.
2659  */
2662 
2663  errno = save_errno;
2664 }
2665 
2666 /*
2667  * Query-cancel signal from postmaster: abort current transaction
2668  * at soonest convenient time
2669  */
2670 void
2672 {
2673  int save_errno = errno;
2674 
2675  /*
2676  * Don't joggle the elbow of proc_exit
2677  */
2678  if (!proc_exit_inprogress)
2679  {
2680  InterruptPending = true;
2681  QueryCancelPending = true;
2682  }
2683 
2684  /* If we're still here, waken anything waiting on the process latch */
2685  SetLatch(MyLatch);
2686 
2687  errno = save_errno;
2688 }
2689 
2690 /* signal handler for floating point exception */
2691 void
2693 {
2694  /* We're not returning, so no need to save errno */
2695  ereport(ERROR,
2696  (errcode(ERRCODE_FLOATING_POINT_EXCEPTION),
2697  errmsg("floating-point exception"),
2698  errdetail("An invalid floating-point operation was signaled. "
2699  "This probably means an out-of-range result or an "
2700  "invalid operation, such as division by zero.")));
2701 }
2702 
2703 /* SIGHUP: set flag to re-read config file at next convenient time */
2704 static void
2706 {
2707  int save_errno = errno;
2708 
2709  got_SIGHUP = true;
2710  SetLatch(MyLatch);
2711 
2712  errno = save_errno;
2713 }
2714 
2715 /*
2716  * RecoveryConflictInterrupt: out-of-line portion of recovery conflict
2717  * handling following receipt of SIGUSR1. Designed to be similar to die()
2718  * and StatementCancelHandler(). Called only by a normal user backend
2719  * that begins a transaction during recovery.
2720  */
2721 void
2723 {
2724  int save_errno = errno;
2725 
2726  /*
2727  * Don't joggle the elbow of proc_exit
2728  */
2729  if (!proc_exit_inprogress)
2730  {
2731  RecoveryConflictReason = reason;
2732  switch (reason)
2733  {
2735 
2736  /*
2737  * If we aren't waiting for a lock we can never deadlock.
2738  */
2739  if (!IsWaitingForLock())
2740  return;
2741 
2742  /* Intentional drop through to check wait for pin */
2743 
2745 
2746  /*
2747  * If we aren't blocking the Startup process there is nothing
2748  * more to do.
2749  */
2751  return;
2752 
2754 
2755  /* Intentional drop through to error handling */
2756 
2760 
2761  /*
2762  * If we aren't in a transaction any longer then ignore.
2763  */
2765  return;
2766 
2767  /*
2768  * If we can abort just the current subtransaction then we are
2769  * OK to throw an ERROR to resolve the conflict. Otherwise
2770  * drop through to the FATAL case.
2771  *
2772  * XXX other times that we can throw just an ERROR *may* be
2773  * PROCSIG_RECOVERY_CONFLICT_LOCK if no locks are held in
2774  * parent transactions
2775  *
2776  * PROCSIG_RECOVERY_CONFLICT_SNAPSHOT if no snapshots are held
2777  * by parent transactions and the transaction is not
2778  * transaction-snapshot mode
2779  *
2780  * PROCSIG_RECOVERY_CONFLICT_TABLESPACE if no temp files or
2781  * cursors open in parent transactions
2782  */
2783  if (!IsSubTransaction())
2784  {
2785  /*
2786  * If we already aborted then we no longer need to cancel.
2787  * We do this here since we do not wish to ignore aborted
2788  * subtransactions, which must cause FATAL, currently.
2789  */
2791  return;
2792 
2793  RecoveryConflictPending = true;
2794  QueryCancelPending = true;
2795  InterruptPending = true;
2796  break;
2797  }
2798 
2799  /* Intentional drop through to session cancel */
2800 
2802  RecoveryConflictPending = true;
2803  ProcDiePending = true;
2804  InterruptPending = true;
2805  break;
2806 
2807  default:
2808  elog(FATAL, "unrecognized conflict mode: %d",
2809  (int) reason);
2810  }
2811 
2813 
2814  /*
2815  * All conflicts apart from database cause dynamic errors where the
2816  * command or transaction can be retried at a later point with some
2817  * potential for success. No need to reset this, since non-retryable
2818  * conflict errors are currently FATAL.
2819  */
2820  if (reason == PROCSIG_RECOVERY_CONFLICT_DATABASE)
2821  RecoveryConflictRetryable = false;
2822  }
2823 
2824  /*
2825  * Set the process latch. This function essentially emulates signal
2826  * handlers like die() and StatementCancelHandler() and it seems prudent
2827  * to behave similarly as they do. Alternatively all plain backend code
2828  * waiting on that latch, expecting to get interrupted by query cancels et
2829  * al., would also need to set set_latch_on_sigusr1.
2830  */
2831  SetLatch(MyLatch);
2832 
2833  errno = save_errno;
2834 }
2835 
2836 /*
2837  * ProcessInterrupts: out-of-line portion of CHECK_FOR_INTERRUPTS() macro
2838  *
2839  * If an interrupt condition is pending, and it's safe to service it,
2840  * then clear the flag and accept the interrupt. Called only when
2841  * InterruptPending is true.
2842  */
2843 void
2845 {
2846  /* OK to accept any interrupts now? */
2847  if (InterruptHoldoffCount != 0 || CritSectionCount != 0)
2848  return;
2849  InterruptPending = false;
2850 
2851  if (ProcDiePending)
2852  {
2853  ProcDiePending = false;
2854  QueryCancelPending = false; /* ProcDie trumps QueryCancel */
2855  LockErrorCleanup();
2856  /* As in quickdie, don't risk sending to client during auth */
2860  ereport(FATAL,
2861  (errcode(ERRCODE_QUERY_CANCELED),
2862  errmsg("canceling authentication due to timeout")));
2863  else if (IsAutoVacuumWorkerProcess())
2864  ereport(FATAL,
2865  (errcode(ERRCODE_ADMIN_SHUTDOWN),
2866  errmsg("terminating autovacuum process due to administrator command")));
2868  {
2870  ereport(FATAL,
2871  (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
2872  errmsg("terminating connection due to conflict with recovery"),
2874  }
2875  else if (RecoveryConflictPending)
2876  {
2877  /* Currently there is only one non-retryable recovery conflict */
2880  ereport(FATAL,
2881  (errcode(ERRCODE_DATABASE_DROPPED),
2882  errmsg("terminating connection due to conflict with recovery"),
2884  }
2885  else
2886  ereport(FATAL,
2887  (errcode(ERRCODE_ADMIN_SHUTDOWN),
2888  errmsg("terminating connection due to administrator command")));
2889  }
2891  {
2892  QueryCancelPending = false; /* lost connection trumps QueryCancel */
2893  LockErrorCleanup();
2894  /* don't send to client, we already know the connection to be dead. */
2896  ereport(FATAL,
2897  (errcode(ERRCODE_CONNECTION_FAILURE),
2898  errmsg("connection to client lost")));
2899  }
2900 
2901  /*
2902  * If a recovery conflict happens while we are waiting for input from the
2903  * client, the client is presumably just sitting idle in a transaction,
2904  * preventing recovery from making progress. Terminate the connection to
2905  * dislodge it.
2906  */
2908  {
2909  QueryCancelPending = false; /* this trumps QueryCancel */
2910  RecoveryConflictPending = false;
2911  LockErrorCleanup();
2913  ereport(FATAL,
2914  (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
2915  errmsg("terminating connection due to conflict with recovery"),
2917  errhint("In a moment you should be able to reconnect to the"
2918  " database and repeat your command.")));
2919  }
2920 
2921  if (QueryCancelPending)
2922  {
2923  /*
2924  * Don't allow query cancel interrupts while reading input from the
2925  * client, because we might lose sync in the FE/BE protocol. (Die
2926  * interrupts are OK, because we won't read any further messages from
2927  * the client in that case.)
2928  */
2929  if (QueryCancelHoldoffCount != 0)
2930  {
2931  /*
2932  * Re-arm InterruptPending so that we process the cancel request
2933  * as soon as we're done reading the message.
2934  */
2935  InterruptPending = true;
2936  return;
2937  }
2938 
2939  QueryCancelPending = false;
2940 
2941  /*
2942  * If LOCK_TIMEOUT and STATEMENT_TIMEOUT indicators are both set, we
2943  * prefer to report the former; but be sure to clear both.
2944  */
2946  {
2948  LockErrorCleanup();
2949  ereport(ERROR,
2950  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
2951  errmsg("canceling statement due to lock timeout")));
2952  }
2954  {
2955  LockErrorCleanup();
2956  ereport(ERROR,
2957  (errcode(ERRCODE_QUERY_CANCELED),
2958  errmsg("canceling statement due to statement timeout")));
2959  }
2961  {
2962  LockErrorCleanup();
2963  ereport(ERROR,
2964  (errcode(ERRCODE_QUERY_CANCELED),
2965  errmsg("canceling autovacuum task")));
2966  }
2968  {
2969  RecoveryConflictPending = false;
2970  LockErrorCleanup();
2972  ereport(ERROR,
2973  (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
2974  errmsg("canceling statement due to conflict with recovery"),
2976  }
2977 
2978  /*
2979  * If we are reading a command from the client, just ignore the cancel
2980  * request --- sending an extra error message won't accomplish
2981  * anything. Otherwise, go ahead and throw the error.
2982  */
2983  if (!DoingCommandRead)
2984  {
2985  LockErrorCleanup();
2986  ereport(ERROR,
2987  (errcode(ERRCODE_QUERY_CANCELED),
2988  errmsg("canceling statement due to user request")));
2989  }
2990  }
2991 
2994 }
2995 
2996 
2997 /*
2998  * IA64-specific code to fetch the AR.BSP register for stack depth checks.
2999  *
3000  * We currently support gcc, icc, and HP-UX inline assembly here.
3001  */
3002 #if defined(__ia64__) || defined(__ia64)
3003 
3004 #if defined(__hpux) && !defined(__GNUC__) && !defined __INTEL_COMPILER
3005 #include <ia64/sys/inline.h>
3006 #define ia64_get_bsp() ((char *) (_Asm_mov_from_ar(_AREG_BSP, _NO_FENCE)))
3007 #else
3008 
3009 #ifdef __INTEL_COMPILER
3010 #include <asm/ia64regs.h>
3011 #endif
3012 
3013 static __inline__ char *
3014 ia64_get_bsp(void)
3015 {
3016  char *ret;
3017 
3018 #ifndef __INTEL_COMPILER
3019  /* the ;; is a "stop", seems to be required before fetching BSP */
3020  __asm__ __volatile__(
3021  ";;\n"
3022  " mov %0=ar.bsp \n"
3023  : "=r"(ret));
3024 #else
3025  ret = (char *) __getReg(_IA64_REG_AR_BSP);
3026 #endif
3027  return ret;
3028 }
3029 #endif
3030 #endif /* IA64 */
3031 
3032 
3033 /*
3034  * set_stack_base: set up reference point for stack depth checking
3035  *
3036  * Returns the old reference point, if any.
3037  */
3040 {
3041  char stack_base;
3042  pg_stack_base_t old;
3043 
3044 #if defined(__ia64__) || defined(__ia64)
3045  old.stack_base_ptr = stack_base_ptr;
3046  old.register_stack_base_ptr = register_stack_base_ptr;
3047 #else
3048  old = stack_base_ptr;
3049 #endif
3050 
3051  /* Set up reference point for stack depth checking */
3052  stack_base_ptr = &stack_base;
3053 #if defined(__ia64__) || defined(__ia64)
3054  register_stack_base_ptr = ia64_get_bsp();
3055 #endif
3056 
3057  return old;
3058 }
3059 
3060 /*
3061  * restore_stack_base: restore reference point for stack depth checking
3062  *
3063  * This can be used after set_stack_base() to restore the old value. This
3064  * is currently only used in PL/Java. When PL/Java calls a backend function
3065  * from different thread, the thread's stack is at a different location than
3066  * the main thread's stack, so it sets the base pointer before the call, and
3067  * restores it afterwards.
3068  */
3069 void
3071 {
3072 #if defined(__ia64__) || defined(__ia64)
3073  stack_base_ptr = base.stack_base_ptr;
3074  register_stack_base_ptr = base.register_stack_base_ptr;
3075 #else
3076  stack_base_ptr = base;
3077 #endif
3078 }
3079 
3080 /*
3081  * check_stack_depth: check for excessively deep recursion
3082  *
3083  * This should be called someplace in any recursive routine that might possibly
3084  * recurse deep enough to overflow the stack. Most Unixen treat stack
3085  * overflow as an unrecoverable SIGSEGV, so we want to error out ourselves
3086  * before hitting the hardware limit.
3087  */
3088 void
3090 {
3091  char stack_top_loc;
3092  long stack_depth;
3093 
3094  /*
3095  * Compute distance from reference point to my local variables
3096  */
3097  stack_depth = (long) (stack_base_ptr - &stack_top_loc);
3098 
3099  /*
3100  * Take abs value, since stacks grow up on some machines, down on others
3101  */
3102  if (stack_depth < 0)
3103  stack_depth = -stack_depth;
3104 
3105  /*
3106  * Trouble?
3107  *
3108  * The test on stack_base_ptr prevents us from erroring out if called
3109  * during process setup or in a non-backend process. Logically it should
3110  * be done first, but putting it here avoids wasting cycles during normal
3111  * cases.
3112  */
3113  if (stack_depth > max_stack_depth_bytes &&
3114  stack_base_ptr != NULL)
3115  {
3116  ereport(ERROR,
3117  (errcode(ERRCODE_STATEMENT_TOO_COMPLEX),
3118  errmsg("stack depth limit exceeded"),
3119  errhint("Increase the configuration parameter \"max_stack_depth\" (currently %dkB), "
3120  "after ensuring the platform's stack depth limit is adequate.",
3121  max_stack_depth)));
3122  }
3123 
3124  /*
3125  * On IA64 there is a separate "register" stack that requires its own
3126  * independent check. For this, we have to measure the change in the
3127  * "BSP" pointer from PostgresMain to here. Logic is just as above,
3128  * except that we know IA64's register stack grows up.
3129  *
3130  * Note we assume that the same max_stack_depth applies to both stacks.
3131  */
3132 #if defined(__ia64__) || defined(__ia64)
3133  stack_depth = (long) (ia64_get_bsp() - register_stack_base_ptr);
3134 
3135  if (stack_depth > max_stack_depth_bytes &&
3136  register_stack_base_ptr != NULL)
3137  {
3138  ereport(ERROR,
3139  (errcode(ERRCODE_STATEMENT_TOO_COMPLEX),
3140  errmsg("stack depth limit exceeded"),
3141  errhint("Increase the configuration parameter \"max_stack_depth\" (currently %dkB), "
3142  "after ensuring the platform's stack depth limit is adequate.",
3143  max_stack_depth)));
3144  }
3145 #endif /* IA64 */
3146 }
3147 
3148 /* GUC check hook for max_stack_depth */
3149 bool
3150 check_max_stack_depth(int *newval, void **extra, GucSource source)
3151 {
3152  long newval_bytes = *newval * 1024L;
3153  long stack_rlimit = get_stack_depth_rlimit();
3154 
3155  if (stack_rlimit > 0 && newval_bytes > stack_rlimit - STACK_DEPTH_SLOP)
3156  {
3157  GUC_check_errdetail("\"max_stack_depth\" must not exceed %ldkB.",
3158  (stack_rlimit - STACK_DEPTH_SLOP) / 1024L);
3159  GUC_check_errhint("Increase the platform's stack depth limit via \"ulimit -s\" or local equivalent.");
3160  return false;
3161  }
3162  return true;
3163 }
3164 
3165 /* GUC assign hook for max_stack_depth */
3166 void
3168 {
3169  long newval_bytes = newval * 1024L;
3170 
3171  max_stack_depth_bytes = newval_bytes;
3172 }
3173 
3174 
3175 /*
3176  * set_debug_options --- apply "-d N" command line option
3177  *
3178  * -d is not quite the same as setting log_min_messages because it enables
3179  * other output options.
3180  */
3181 void
3182 set_debug_options(int debug_flag, GucContext context, GucSource source)
3183 {
3184  if (debug_flag > 0)
3185  {
3186  char debugstr[64];
3187 
3188  sprintf(debugstr, "debug%d", debug_flag);
3189  SetConfigOption("log_min_messages", debugstr, context, source);
3190  }
3191  else
3192  SetConfigOption("log_min_messages", "notice", context, source);
3193 
3194  if (debug_flag >= 1 && context == PGC_POSTMASTER)
3195  {
3196  SetConfigOption("log_connections", "true", context, source);
3197  SetConfigOption("log_disconnections", "true", context, source);
3198  }
3199  if (debug_flag >= 2)
3200  SetConfigOption("log_statement", "all", context, source);
3201  if (debug_flag >= 3)
3202  SetConfigOption("debug_print_parse", "true", context, source);
3203  if (debug_flag >= 4)
3204  SetConfigOption("debug_print_plan", "true", context, source);
3205  if (debug_flag >= 5)
3206  SetConfigOption("debug_print_rewritten", "true", context, source);
3207 }
3208 
3209 
3210 bool
3212 {
3213  const char *tmp = NULL;
3214 
3215  switch (arg[0])
3216  {
3217  case 's': /* seqscan */
3218  tmp = "enable_seqscan";
3219  break;
3220  case 'i': /* indexscan */
3221  tmp = "enable_indexscan";
3222  break;
3223  case 'o': /* indexonlyscan */
3224  tmp = "enable_indexonlyscan";
3225  break;
3226  case 'b': /* bitmapscan */
3227  tmp = "enable_bitmapscan";
3228  break;
3229  case 't': /* tidscan */
3230  tmp = "enable_tidscan";
3231  break;
3232  case 'n': /* nestloop */
3233  tmp = "enable_nestloop";
3234  break;
3235  case 'm': /* mergejoin */
3236  tmp = "enable_mergejoin";
3237  break;
3238  case 'h': /* hashjoin */
3239  tmp = "enable_hashjoin";
3240  break;
3241  }
3242  if (tmp)
3243  {
3244  SetConfigOption(tmp, "false", context, source);
3245  return true;
3246  }
3247  else
3248  return false;
3249 }
3250 
3251 
3252 const char *
3254 {
3255  switch (arg[0])
3256  {
3257  case 'p':
3258  if (optarg[1] == 'a') /* "parser" */
3259  return "log_parser_stats";
3260  else if (optarg[1] == 'l') /* "planner" */
3261  return "log_planner_stats";
3262  break;
3263 
3264  case 'e': /* "executor" */
3265  return "log_executor_stats";
3266  break;
3267  }
3268 
3269  return NULL;
3270 }
3271 
3272 
3273 /* ----------------------------------------------------------------
3274  * process_postgres_switches
3275  * Parse command line arguments for PostgresMain
3276  *
3277  * This is called twice, once for the "secure" options coming from the
3278  * postmaster or command line, and once for the "insecure" options coming
3279  * from the client's startup packet. The latter have the same syntax but
3280  * may be restricted in what they can do.
3281  *
3282  * argv[0] is ignored in either case (it's assumed to be the program name).
3283  *
3284  * ctx is PGC_POSTMASTER for secure options, PGC_BACKEND for insecure options
3285  * coming from the client, or PGC_SU_BACKEND for insecure options coming from
3286  * a superuser client.
3287  *
3288  * If a database name is present in the command line arguments, it's
3289  * returned into *dbname (this is allowed only if *dbname is initially NULL).
3290  * ----------------------------------------------------------------
3291  */
3292 void
3293 process_postgres_switches(int argc, char *argv[], GucContext ctx,
3294  const char **dbname)
3295 {
3296  bool secure = (ctx == PGC_POSTMASTER);
3297  int errs = 0;
3298  GucSource gucsource;
3299  int flag;
3300 
3301  if (secure)
3302  {
3303  gucsource = PGC_S_ARGV; /* switches came from command line */
3304 
3305  /* Ignore the initial --single argument, if present */
3306  if (argc > 1 && strcmp(argv[1], "--single") == 0)
3307  {
3308  argv++;
3309  argc--;
3310  }
3311  }
3312  else
3313  {
3314  gucsource = PGC_S_CLIENT; /* switches came from client */
3315  }
3316 
3317 #ifdef HAVE_INT_OPTERR
3318 
3319  /*
3320  * Turn this off because it's either printed to stderr and not the log
3321  * where we'd want it, or argv[0] is now "--single", which would make for
3322  * a weird error message. We print our own error message below.
3323  */
3324  opterr = 0;
3325 #endif
3326 
3327  /*
3328  * Parse command-line options. CAUTION: keep this in sync with
3329  * postmaster/postmaster.c (the option sets should not conflict) and with
3330  * the common help() function in main/main.c.
3331  */
3332  while ((flag = getopt(argc, argv, "B:bc:C:D:d:EeFf:h:ijk:lN:nOo:Pp:r:S:sTt:v:W:-:")) != -1)
3333  {
3334  switch (flag)
3335  {
3336  case 'B':
3337  SetConfigOption("shared_buffers", optarg, ctx, gucsource);
3338  break;
3339 
3340  case 'b':
3341  /* Undocumented flag used for binary upgrades */
3342  if (secure)
3343  IsBinaryUpgrade = true;
3344  break;
3345 
3346  case 'C':
3347  /* ignored for consistency with the postmaster */
3348  break;
3349 
3350  case 'D':
3351  if (secure)
3352  userDoption = strdup(optarg);
3353  break;
3354 
3355  case 'd':
3356  set_debug_options(atoi(optarg), ctx, gucsource);
3357  break;
3358 
3359  case 'E':
3360  if (secure)
3361  EchoQuery = true;
3362  break;
3363 
3364  case 'e':
3365  SetConfigOption("datestyle", "euro", ctx, gucsource);
3366  break;
3367 
3368  case 'F':
3369  SetConfigOption("fsync", "false", ctx, gucsource);
3370  break;
3371 
3372  case 'f':
3373  if (!set_plan_disabling_options(optarg, ctx, gucsource))
3374  errs++;
3375  break;
3376 
3377  case 'h':
3378  SetConfigOption("listen_addresses", optarg, ctx, gucsource);
3379  break;
3380 
3381  case 'i':
3382  SetConfigOption("listen_addresses", "*", ctx, gucsource);
3383  break;
3384 
3385  case 'j':
3386  if (secure)
3387  UseNewLine = 0;
3388  break;
3389 
3390  case 'k':
3391  SetConfigOption("unix_socket_directories", optarg, ctx, gucsource);
3392  break;
3393 
3394  case 'l':
3395  SetConfigOption("ssl", "true", ctx, gucsource);
3396  break;
3397 
3398  case 'N':
3399  SetConfigOption("max_connections", optarg, ctx, gucsource);
3400  break;
3401 
3402  case 'n':
3403  /* ignored for consistency with postmaster */
3404  break;
3405 
3406  case 'O':
3407  SetConfigOption("allow_system_table_mods", "true", ctx, gucsource);
3408  break;
3409 
3410  case 'o':
3411  errs++;
3412  break;
3413 
3414  case 'P':
3415  SetConfigOption("ignore_system_indexes", "true", ctx, gucsource);
3416  break;
3417 
3418  case 'p':
3419  SetConfigOption("port", optarg, ctx, gucsource);
3420  break;
3421 
3422  case 'r':
3423  /* send output (stdout and stderr) to the given file */
3424  if (secure)
3426  break;
3427 
3428  case 'S':
3429  SetConfigOption("work_mem", optarg, ctx, gucsource);
3430  break;
3431 
3432  case 's':
3433  SetConfigOption("log_statement_stats", "true", ctx, gucsource);
3434  break;
3435 
3436  case 'T':
3437  /* ignored for consistency with the postmaster */
3438  break;
3439 
3440  case 't':
3441  {
3442  const char *tmp = get_stats_option_name(optarg);
3443 
3444  if (tmp)
3445  SetConfigOption(tmp, "true", ctx, gucsource);
3446  else
3447  errs++;
3448  break;
3449  }
3450 
3451  case 'v':
3452 
3453  /*
3454  * -v is no longer used in normal operation, since
3455  * FrontendProtocol is already set before we get here. We keep
3456  * the switch only for possible use in standalone operation,
3457  * in case we ever support using normal FE/BE protocol with a
3458  * standalone backend.
3459  */
3460  if (secure)
3462  break;
3463 
3464  case 'W':
3465  SetConfigOption("post_auth_delay", optarg, ctx, gucsource);
3466  break;
3467 
3468  case 'c':
3469  case '-':
3470  {
3471  char *name,
3472  *value;
3473 
3474  ParseLongOption(optarg, &name, &value);
3475  if (!value)
3476  {
3477  if (flag == '-')
3478  ereport(ERROR,
3479  (errcode(ERRCODE_SYNTAX_ERROR),
3480  errmsg("--%s requires a value",
3481  optarg)));
3482  else
3483  ereport(ERROR,
3484  (errcode(ERRCODE_SYNTAX_ERROR),
3485  errmsg("-c %s requires a value",
3486  optarg)));
3487  }
3488  SetConfigOption(name, value, ctx, gucsource);
3489  free(name);
3490  if (value)
3491  free(value);
3492  break;
3493  }
3494 
3495  default:
3496  errs++;
3497  break;
3498  }
3499 
3500  if (errs)
3501  break;
3502  }
3503 
3504  /*
3505  * Optional database name should be there only if *dbname is NULL.
3506  */
3507  if (!errs && dbname && *dbname == NULL && argc - optind >= 1)
3508  *dbname = strdup(argv[optind++]);
3509 
3510  if (errs || argc != optind)
3511  {
3512  if (errs)
3513  optind--; /* complain about the previous argument */
3514 
3515  /* spell the error message a bit differently depending on context */
3516  if (IsUnderPostmaster)
3517  ereport(FATAL,
3518  (errcode(ERRCODE_SYNTAX_ERROR),
3519  errmsg("invalid command-line argument for server process: %s", argv[optind]),
3520  errhint("Try \"%s --help\" for more information.", progname)));
3521  else
3522  ereport(FATAL,
3523  (errcode(ERRCODE_SYNTAX_ERROR),
3524  errmsg("%s: invalid command-line argument: %s",
3525  progname, argv[optind]),
3526  errhint("Try \"%s --help\" for more information.", progname)));
3527  }
3528 
3529  /*
3530  * Reset getopt(3) library so that it will work correctly in subprocesses
3531  * or when this function is called a second time with another array.
3532  */
3533  optind = 1;
3534 #ifdef HAVE_INT_OPTRESET
3535  optreset = 1; /* some systems need this too */
3536 #endif
3537 }
3538 
3539 
3540 /* ----------------------------------------------------------------
3541  * PostgresMain
3542  * postgres main loop -- all backends, interactive or otherwise start here
3543  *
3544  * argc/argv are the command line arguments to be used. (When being forked
3545  * by the postmaster, these are not the original argv array of the process.)
3546  * dbname is the name of the database to connect to, or NULL if the database
3547  * name should be extracted from the command line arguments or defaulted.
3548  * username is the PostgreSQL user name to be used for the session.
3549  * ----------------------------------------------------------------
3550  */
3551 void
3552 PostgresMain(int argc, char *argv[],
3553  const char *dbname,
3554  const char *username)
3555 {
3556  int firstchar;
3557  StringInfoData input_message;
3558  sigjmp_buf local_sigjmp_buf;
3559  volatile bool send_ready_for_query = true;
3560 
3561  /* Initialize startup process environment if necessary. */
3562  if (!IsUnderPostmaster)
3563  InitStandaloneProcess(argv[0]);
3564 
3566 
3567  /*
3568  * Set default values for command-line options.
3569  */
3570  if (!IsUnderPostmaster)
3572 
3573  /*
3574  * Parse command-line options.
3575  */
3576  process_postgres_switches(argc, argv, PGC_POSTMASTER, &dbname);
3577 
3578  /* Must have gotten a database name, or have a default (the username) */
3579  if (dbname == NULL)
3580  {
3581  dbname = username;
3582  if (dbname == NULL)
3583  ereport(FATAL,
3584  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3585  errmsg("%s: no database nor user name specified",
3586  progname)));
3587  }
3588 
3589  /* Acquire configuration parameters, unless inherited from postmaster */
3590  if (!IsUnderPostmaster)
3591  {
3593  proc_exit(1);
3594  }
3595 
3596  /*
3597  * Set up signal handlers and masks.
3598  *
3599  * Note that postmaster blocked all signals before forking child process,
3600  * so there is no race condition whereby we might receive a signal before
3601  * we have set up the handler.
3602  *
3603  * Also note: it's best not to use any signals that are SIG_IGNored in the
3604  * postmaster. If such a signal arrives before we are able to change the
3605  * handler to non-SIG_IGN, it'll get dropped. Instead, make a dummy
3606  * handler in the postmaster to reserve the signal. (Of course, this isn't
3607  * an issue for signals that are locally generated, such as SIGALRM and
3608  * SIGPIPE.)
3609  */
3610  if (am_walsender)
3611  WalSndSignals();
3612  else
3613  {
3614  pqsignal(SIGHUP, SigHupHandler); /* set flag to read config
3615  * file */
3616  pqsignal(SIGINT, StatementCancelHandler); /* cancel current query */
3617  pqsignal(SIGTERM, die); /* cancel current query and exit */
3618 
3619  /*
3620  * In a standalone backend, SIGQUIT can be generated from the keyboard
3621  * easily, while SIGTERM cannot, so we make both signals do die()
3622  * rather than quickdie().
3623  */
3624  if (IsUnderPostmaster)
3625  pqsignal(SIGQUIT, quickdie); /* hard crash time */
3626  else
3627  pqsignal(SIGQUIT, die); /* cancel current query and exit */
3628  InitializeTimeouts(); /* establishes SIGALRM handler */
3629 
3630  /*
3631  * Ignore failure to write to frontend. Note: if frontend closes
3632  * connection, we will notice it and exit cleanly when control next
3633  * returns to outer loop. This seems safer than forcing exit in the
3634  * midst of output during who-knows-what operation...
3635  */
3640 
3641  /*
3642  * Reset some signals that are accepted by postmaster but not by
3643  * backend
3644  */
3645  pqsignal(SIGCHLD, SIG_DFL); /* system() requires this on some
3646  * platforms */
3647  }
3648 
3649  pqinitmask();
3650 
3651  if (IsUnderPostmaster)
3652  {
3653  /* We allow SIGQUIT (quickdie) at all times */
3655  }
3656 
3657  PG_SETMASK(&BlockSig); /* block everything except SIGQUIT */
3658 
3659  if (!IsUnderPostmaster)
3660  {
3661  /*
3662  * Validate we have been given a reasonable-looking DataDir (if under
3663  * postmaster, assume postmaster did this already).
3664  */
3665  Assert(DataDir);
3667 
3668  /* Change into DataDir (if under postmaster, was done already) */
3669  ChangeToDataDir();
3670 
3671  /*
3672  * Create lockfile for data directory.
3673  */
3674  CreateDataDirLockFile(false);
3675 
3676  /* Initialize MaxBackends (if under postmaster, was done already) */
3678  }
3679 
3680  /* Early initialization */
3681  BaseInit();
3682 
3683  /*
3684  * Create a per-backend PGPROC struct in shared memory, except in the
3685  * EXEC_BACKEND case where this was done in SubPostmasterMain. We must do
3686  * this before we can use LWLocks (and in the EXEC_BACKEND case we already
3687  * had to do some stuff with LWLocks).
3688  */
3689 #ifdef EXEC_BACKEND
3690  if (!IsUnderPostmaster)
3691  InitProcess();
3692 #else
3693  InitProcess();
3694 #endif
3695 
3696  /* We need to allow SIGINT, etc during the initial transaction */
3698 
3699  /*
3700  * General initialization.
3701  *
3702  * NOTE: if you are tempted to add code in this vicinity, consider putting
3703  * it inside InitPostgres() instead. In particular, anything that
3704  * involves database access should be there, not here.
3705  */
3706  InitPostgres(dbname, InvalidOid, username, InvalidOid, NULL);
3707 
3708  /*
3709  * If the PostmasterContext is still around, recycle the space; we don't
3710  * need it anymore after InitPostgres completes. Note this does not trash
3711  * *MyProcPort, because ConnCreate() allocated that space with malloc()
3712  * ... else we'd need to copy the Port data first. Also, subsidiary data
3713  * such as the username isn't lost either; see ProcessStartupPacket().
3714  */
3715  if (PostmasterContext)
3716  {
3719  }
3720 
3722 
3723  /*
3724  * Now all GUC states are fully set up. Report them to client if
3725  * appropriate.
3726  */
3728 
3729  /*
3730  * Also set up handler to log session end; we have to wait till now to be
3731  * sure Log_disconnections has its final value.
3732  */
3735 
3736  /* Perform initialization specific to a WAL sender process. */
3737  if (am_walsender)
3738  InitWalSender();
3739 
3740  /*
3741  * process any libraries that should be preloaded at backend start (this
3742  * likewise can't be done until GUC settings are complete)
3743  */
3745 
3746  /*
3747  * Send this backend's cancellation info to the frontend.
3748  */
3749  if (whereToSendOutput == DestRemote &&
3751  {
3753 
3754  pq_beginmessage(&buf, 'K');
3755  pq_sendint(&buf, (int32) MyProcPid, sizeof(int32));
3756  pq_sendint(&buf, (int32) MyCancelKey, sizeof(int32));
3757  pq_endmessage(&buf);
3758  /* Need not flush since ReadyForQuery will do it. */
3759  }
3760 
3761  /* Welcome banner for standalone case */
3763  printf("\nPostgreSQL stand-alone backend %s\n", PG_VERSION);
3764 
3765  /*
3766  * Create the memory context we will use in the main loop.
3767  *
3768  * MessageContext is reset once per iteration of the main loop, ie, upon
3769  * completion of processing of each command message from the client.
3770  */
3772  "MessageContext",
3776 
3777  /*
3778  * Remember stand-alone backend startup time
3779  */
3780  if (!IsUnderPostmaster)
3782 
3783  /*
3784  * POSTGRES main processing loop begins here
3785  *
3786  * If an exception is encountered, processing resumes here so we abort the
3787  * current transaction and start a new one.
3788  *
3789  * You might wonder why this isn't coded as an infinite loop around a
3790  * PG_TRY construct. The reason is that this is the bottom of the
3791  * exception stack, and so with PG_TRY there would be no exception handler
3792  * in force at all during the CATCH part. By leaving the outermost setjmp
3793  * always active, we have at least some chance of recovering from an error
3794  * during error recovery. (If we get into an infinite loop thereby, it
3795  * will soon be stopped by overflow of elog.c's internal state stack.)
3796  *
3797  * Note that we use sigsetjmp(..., 1), so that this function's signal mask
3798  * (to wit, UnBlockSig) will be restored when longjmp'ing to here. This
3799  * is essential in case we longjmp'd out of a signal handler on a platform
3800  * where that leaves the signal blocked. It's not redundant with the
3801  * unblock in AbortTransaction() because the latter is only called if we
3802  * were inside a transaction.
3803  */
3804 
3805  if (sigsetjmp(local_sigjmp_buf, 1) != 0)
3806  {
3807  /*
3808  * NOTE: if you are tempted to add more code in this if-block,
3809  * consider the high probability that it should be in
3810  * AbortTransaction() instead. The only stuff done directly here
3811  * should be stuff that is guaranteed to apply *only* for outer-level
3812  * error recovery, such as adjusting the FE/BE protocol status.
3813  */
3814 
3815  /* Since not using PG_TRY, must reset error stack by hand */
3817 
3818  /* Prevent interrupts while cleaning up */
3819  HOLD_INTERRUPTS();
3820 
3821  /*
3822  * Forget any pending QueryCancel request, since we're returning to
3823  * the idle loop anyway, and cancel any active timeout requests. (In
3824  * future we might want to allow some timeout requests to survive, but
3825  * at minimum it'd be necessary to do reschedule_timeouts(), in case
3826  * we got here because of a query cancel interrupting the SIGALRM
3827  * interrupt handler.) Note in particular that we must clear the
3828  * statement and lock timeout indicators, to prevent any future plain
3829  * query cancels from being misreported as timeouts in case we're
3830  * forgetting a timeout cancel.
3831  */
3832  disable_all_timeouts(false);
3833  QueryCancelPending = false; /* second to avoid race condition */
3834 
3835  /* Not reading from the client anymore. */
3836  DoingCommandRead = false;
3837 
3838  /* Make sure libpq is in a good state */
3839  pq_comm_reset();
3840 
3841  /* Report the error to the client and/or server log */
3842  EmitErrorReport();
3843 
3844  /*
3845  * Make sure debug_query_string gets reset before we possibly clobber
3846  * the storage it points at.
3847  */
3849 
3850  /*
3851  * Abort the current transaction in order to recover.
3852  */
3854 
3855  if (am_walsender)
3857 
3858  /*
3859  * We can't release replication slots inside AbortTransaction() as we
3860  * need to be able to start and abort transactions while having a slot
3861  * acquired. But we never need to hold them across top level errors,
3862  * so releasing here is fine. There's another cleanup in ProcKill()
3863  * ensuring we'll correctly cleanup on FATAL errors as well.
3864  */
3865  if (MyReplicationSlot != NULL)
3867 
3868  /*
3869  * Now return to normal top-level context and clear ErrorContext for
3870  * next time.
3871  */
3873  FlushErrorState();
3874 
3875  /*
3876  * If we were handling an extended-query-protocol message, initiate
3877  * skip till next Sync. This also causes us not to issue
3878  * ReadyForQuery (until we get Sync).
3879  */
3881  ignore_till_sync = true;
3882 
3883  /* We don't have a transaction command open anymore */
3884  xact_started = false;
3885 
3886  /*
3887  * If an error occurred while we were reading a message from the
3888  * client, we have potentially lost track of where the previous
3889  * message ends and the next one begins. Even though we have
3890  * otherwise recovered from the error, we cannot safely read any more
3891  * messages from the client, so there isn't much we can do with the
3892  * connection anymore.
3893  */
3894  if (pq_is_reading_msg())
3895  ereport(FATAL,
3896  (errcode(ERRCODE_PROTOCOL_VIOLATION),
3897  errmsg("terminating connection because protocol sync was lost")));
3898 
3899  /* Now we can allow interrupts again */
3901  }
3902 
3903  /* We can now handle ereport(ERROR) */
3904  PG_exception_stack = &local_sigjmp_buf;
3905 
3906  if (!ignore_till_sync)
3907  send_ready_for_query = true; /* initially, or after error */
3908 
3909  /*
3910  * Non-error queries loop here.
3911  */
3912 
3913  for (;;)
3914  {
3915  /*
3916  * At top of loop, reset extended-query-message flag, so that any
3917  * errors encountered in "idle" state don't provoke skip.
3918  */
3920 
3921  /*
3922  * Release storage left over from prior query cycle, and create a new
3923  * query input buffer in the cleared MessageContext.
3924  */
3927 
3928  initStringInfo(&input_message);
3929 
3930  /*
3931  * (1) If we've reached idle state, tell the frontend we're ready for
3932  * a new query.
3933  *
3934  * Note: this includes fflush()'ing the last of the prior output.
3935  *
3936  * This is also a good time to send collected statistics to the
3937  * collector, and to update the PS stats display. We avoid doing
3938  * those every time through the message loop because it'd slow down
3939  * processing of batched messages, and because we don't want to report
3940  * uncommitted updates (that confuses autovacuum). The notification
3941  * processor wants a call too, if we are not in a transaction block.
3942  */
3943  if (send_ready_for_query)
3944  {
3946  {
3947  set_ps_display("idle in transaction (aborted)", false);
3949  }
3951  {
3952  set_ps_display("idle in transaction", false);
3954  }
3955  else
3956  {
3958  pgstat_report_stat(false);
3959 
3960  set_ps_display("idle", false);
3962  }
3963 
3965  send_ready_for_query = false;
3966  }
3967 
3968  /*
3969  * (2) Allow asynchronous signals to be executed immediately if they
3970  * come in while we are waiting for client input. (This must be
3971  * conditional since we don't want, say, reads on behalf of COPY FROM
3972  * STDIN doing the same thing.)
3973  */
3974  DoingCommandRead = true;
3975 
3976  /*
3977  * (3) read a command (loop blocks here)
3978  */
3979  firstchar = ReadCommand(&input_message);
3980 
3981  /*
3982  * (4) disable async signal conditions again.
3983  *
3984  * Query cancel is supposed to be a no-op when there is no query in
3985  * progress, so if a query cancel arrived while we were idle, just
3986  * reset QueryCancelPending. ProcessInterrupts() has that effect when
3987  * it's called when DoingCommandRead is set, so check for interrupts
3988  * before resetting DoingCommandRead.
3989  */
3991  DoingCommandRead = false;
3992 
3993  /*
3994  * (5) check for any other interesting events that happened while we
3995  * slept.
3996  */
3997  if (got_SIGHUP)
3998  {
3999  got_SIGHUP = false;
4001  }
4002 
4003  /*
4004  * (6) process the command. But ignore it if we're skipping till
4005  * Sync.
4006  */
4007  if (ignore_till_sync && firstchar != EOF)
4008  continue;
4009 
4010  switch (firstchar)
4011  {
4012  case 'Q': /* simple query */
4013  {
4014  const char *query_string;
4015 
4016  /* Set statement_timestamp() */
4018 
4019  query_string = pq_getmsgstring(&input_message);
4020  pq_getmsgend(&input_message);
4021 
4022  if (am_walsender)
4023  exec_replication_command(query_string);
4024  else
4025  exec_simple_query(query_string);
4026 
4027  send_ready_for_query = true;
4028  }
4029  break;
4030 
4031  case 'P': /* parse */
4032  {
4033  const char *stmt_name;
4034  const char *query_string;
4035  int numParams;
4036  Oid *paramTypes = NULL;
4037 
4038  forbidden_in_wal_sender(firstchar);
4039 
4040  /* Set statement_timestamp() */
4042 
4043  stmt_name = pq_getmsgstring(&input_message);
4044  query_string = pq_getmsgstring(&input_message);
4045  numParams = pq_getmsgint(&input_message, 2);
4046  if (numParams > 0)
4047  {
4048  int i;
4049 
4050  paramTypes = (Oid *) palloc(numParams * sizeof(Oid));
4051  for (i = 0; i < numParams; i++)
4052  paramTypes[i] = pq_getmsgint(&input_message, 4);
4053  }
4054  pq_getmsgend(&input_message);
4055 
4056  exec_parse_message(query_string, stmt_name,
4057  paramTypes, numParams);
4058  }
4059  break;
4060 
4061  case 'B': /* bind */
4062  forbidden_in_wal_sender(firstchar);
4063 
4064  /* Set statement_timestamp() */
4066 
4067  /*
4068  * this message is complex enough that it seems best to put
4069  * the field extraction out-of-line
4070  */
4071  exec_bind_message(&input_message);
4072  break;
4073 
4074  case 'E': /* execute */
4075  {
4076  const char *portal_name;
4077  int max_rows;
4078 
4079  forbidden_in_wal_sender(firstchar);
4080 
4081  /* Set statement_timestamp() */
4083 
4084  portal_name = pq_getmsgstring(&input_message);
4085  max_rows = pq_getmsgint(&input_message, 4);
4086  pq_getmsgend(&input_message);
4087 
4088  exec_execute_message(portal_name, max_rows);
4089  }
4090  break;
4091 
4092  case 'F': /* fastpath function call */
4093  forbidden_in_wal_sender(firstchar);
4094 
4095  /* Set statement_timestamp() */
4097 
4098  /* Report query to various monitoring facilities. */
4100  set_ps_display("<FASTPATH>", false);
4101 
4102  /* start an xact for this function invocation */
4104 
4105  /*
4106  * Note: we may at this point be inside an aborted
4107  * transaction. We can't throw error for that until we've
4108  * finished reading the function-call message, so
4109  * HandleFunctionRequest() must check for it after doing so.
4110  * Be careful not to do anything that assumes we're inside a
4111  * valid transaction here.
4112  */
4113 
4114  /* switch back to message context */
4116 
4117  if (HandleFunctionRequest(&input_message) == EOF)
4118  {
4119  /* lost frontend connection during F message input */
4120 
4121  /*
4122  * Reset whereToSendOutput to prevent ereport from
4123  * attempting to send any more messages to client.
4124  */
4127 
4128  proc_exit(0);
4129  }
4130 
4131  /* commit the function-invocation transaction */
4133 
4134  send_ready_for_query = true;
4135  break;
4136 
4137  case 'C': /* close */
4138  {
4139  int close_type;
4140  const char *close_target;
4141 
4142  forbidden_in_wal_sender(firstchar);
4143 
4144  close_type = pq_getmsgbyte(&input_message);
4145  close_target = pq_getmsgstring(&input_message);
4146  pq_getmsgend(&input_message);
4147 
4148  switch (close_type)
4149  {
4150  case 'S':
4151  if (close_target[0] != '\0')
4152  DropPreparedStatement(close_target, false);
4153  else
4154  {
4155  /* special-case the unnamed statement */
4157  }
4158  break;
4159  case 'P':
4160  {
4161  Portal portal;
4162 
4163  portal = GetPortalByName(close_target);
4164  if (PortalIsValid(portal))
4165  PortalDrop(portal, false);
4166  }
4167  break;
4168  default:
4169  ereport(ERROR,
4170  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4171  errmsg("invalid CLOSE message subtype %d",
4172  close_type)));
4173  break;
4174  }
4175 
4177  pq_putemptymessage('3'); /* CloseComplete */
4178  }
4179  break;
4180 
4181  case 'D': /* describe */
4182  {
4183  int describe_type;
4184  const char *describe_target;
4185 
4186  forbidden_in_wal_sender(firstchar);
4187 
4188  /* Set statement_timestamp() (needed for xact) */
4190 
4191  describe_type = pq_getmsgbyte(&input_message);
4192  describe_target = pq_getmsgstring(&input_message);
4193  pq_getmsgend(&input_message);
4194 
4195  switch (describe_type)
4196  {
4197  case 'S':
4198  exec_describe_statement_message(describe_target);
4199  break;
4200  case 'P':
4201  exec_describe_portal_message(describe_target);
4202  break;
4203  default:
4204  ereport(ERROR,
4205  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4206  errmsg("invalid DESCRIBE message subtype %d",
4207  describe_type)));
4208  break;
4209  }
4210  }
4211  break;
4212 
4213  case 'H': /* flush */
4214  pq_getmsgend(&input_message);
4216  pq_flush();
4217  break;
4218 
4219  case 'S': /* sync */
4220  pq_getmsgend(&input_message);
4222  send_ready_for_query = true;
4223  break;
4224 
4225  /*
4226  * 'X' means that the frontend is closing down the socket. EOF
4227  * means unexpected loss of frontend connection. Either way,
4228  * perform normal shutdown.
4229  */
4230  case 'X':
4231  case EOF:
4232 
4233  /*
4234  * Reset whereToSendOutput to prevent ereport from attempting
4235  * to send any more messages to client.
4236  */
4239 
4240  /*
4241  * NOTE: if you are tempted to add more code here, DON'T!
4242  * Whatever you had in mind to do should be set up as an
4243  * on_proc_exit or on_shmem_exit callback, instead. Otherwise
4244  * it will fail to be called during other backend-shutdown
4245  * scenarios.
4246  */
4247  proc_exit(0);
4248 
4249  case 'd': /* copy data */
4250  case 'c': /* copy done */
4251  case 'f': /* copy fail */
4252 
4253  /*
4254  * Accept but ignore these messages, per protocol spec; we
4255  * probably got here because a COPY failed, and the frontend
4256  * is still sending data.
4257  */
4258  break;
4259 
4260  default:
4261  ereport(FATAL,
4262  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4263  errmsg("invalid frontend message type %d",
4264  firstchar)));
4265  }
4266  } /* end of input-reading loop */
4267 }
4268 
4269 /*
4270  * Throw an error if we're a WAL sender process.
4271  *
4272  * This is used to forbid anything else than simple query protocol messages
4273  * in a WAL sender process. 'firstchar' specifies what kind of a forbidden
4274  * message was received, and is used to construct the error message.
4275  */
4276 static void
4278 {
4279  if (am_walsender)
4280  {
4281  if (firstchar == 'F')
4282  ereport(ERROR,
4283  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4284  errmsg("fastpath function calls not supported in a replication connection")));
4285  else
4286  ereport(ERROR,
4287  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4288  errmsg("extended query protocol not supported in a replication connection")));
4289  }
4290 }
4291 
4292 
4293 /*
4294  * Obtain platform stack depth limit (in bytes)
4295  *
4296  * Return -1 if unknown
4297  */
4298 long
4300 {
4301 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_STACK)
4302  static long val = 0;
4303 
4304  /* This won't change after process launch, so check just once */
4305  if (val == 0)
4306  {
4307  struct rlimit rlim;
4308 
4309  if (getrlimit(RLIMIT_STACK, &rlim) < 0)
4310  val = -1;
4311  else if (rlim.rlim_cur == RLIM_INFINITY)
4312  val = LONG_MAX;
4313  /* rlim_cur is probably of an unsigned type, so check for overflow */
4314  else if (rlim.rlim_cur >= LONG_MAX)
4315  val = LONG_MAX;
4316  else
4317  val = rlim.rlim_cur;
4318  }
4319  return val;
4320 #else /* no getrlimit */
4321 #if defined(WIN32) || defined(__CYGWIN__)
4322  /* On Windows we set the backend stack size in src/backend/Makefile */
4323  return WIN32_STACK_RLIMIT;
4324 #else /* not windows ... give up */
4325  return -1;
4326 #endif
4327 #endif
4328 }
4329 
4330 
4331 static struct rusage Save_r;
4332 static struct timeval Save_t;
4333 
4334 void
4336 {
4339 }
4340 
4341 void
4342 ShowUsage(const char *title)
4343 {
4344  StringInfoData str;
4345  struct timeval user,
4346  sys;
4347  struct timeval elapse_t;
4348  struct rusage r;
4349 
4350  getrusage(RUSAGE_SELF, &r);
4351  gettimeofday(&elapse_t, NULL);
4352  memcpy((char *) &user, (char *) &r.ru_utime, sizeof(user));
4353  memcpy((char *) &sys, (char *) &r.ru_stime, sizeof(sys));
4354  if (elapse_t.tv_usec < Save_t.tv_usec)
4355  {
4356  elapse_t.tv_sec--;
4357  elapse_t.tv_usec += 1000000;
4358  }
4359  if (r.ru_utime.tv_usec < Save_r.ru_utime.tv_usec)
4360  {
4361  r.ru_utime.tv_sec--;
4362  r.ru_utime.tv_usec += 1000000;
4363  }
4364  if (r.ru_stime.tv_usec < Save_r.ru_stime.tv_usec)
4365  {
4366  r.ru_stime.tv_sec--;
4367  r.ru_stime.tv_usec += 1000000;
4368  }
4369 
4370  /*
4371  * the only stats we don't show here are for memory usage -- i can't
4372  * figure out how to interpret the relevant fields in the rusage struct,
4373  * and they change names across o/s platforms, anyway. if you can figure
4374  * out what the entries mean, you can somehow extract resident set size,
4375  * shared text size, and unshared data and stack sizes.
4376  */
4377  initStringInfo(&str);
4378 
4379  appendStringInfoString(&str, "! system usage stats:\n");
4380  appendStringInfo(&str,
4381  "!\t%ld.%06ld elapsed %ld.%06ld user %ld.%06ld system sec\n",
4382  (long) (elapse_t.tv_sec - Save_t.tv_sec),
4383  (long) (elapse_t.tv_usec - Save_t.tv_usec),
4384  (long) (r.ru_utime.tv_sec - Save_r.ru_utime.tv_sec),
4385  (long) (r.ru_utime.tv_usec - Save_r.ru_utime.tv_usec),
4386  (long) (r.ru_stime.tv_sec - Save_r.ru_stime.tv_sec),
4387  (long) (r.ru_stime.tv_usec - Save_r.ru_stime.tv_usec));
4388  appendStringInfo(&str,
4389  "!\t[%ld.%06ld user %ld.%06ld sys total]\n",
4390  (long) user.tv_sec,
4391  (long) user.tv_usec,
4392  (long) sys.tv_sec,
4393  (long) sys.tv_usec);
4394 #if defined(HAVE_GETRUSAGE)
4395  appendStringInfo(&str,
4396  "!\t%ld/%ld [%ld/%ld] filesystem blocks in/out\n",
4397  r.ru_inblock - Save_r.ru_inblock,
4398  /* they only drink coffee at dec */
4399  r.ru_oublock - Save_r.ru_oublock,
4400  r.ru_inblock, r.ru_oublock);
4401  appendStringInfo(&str,
4402  "!\t%ld/%ld [%ld/%ld] page faults/reclaims, %ld [%ld] swaps\n",
4403  r.ru_majflt - Save_r.ru_majflt,
4404  r.ru_minflt - Save_r.ru_minflt,
4405  r.ru_majflt, r.ru_minflt,
4406  r.ru_nswap - Save_r.ru_nswap,
4407  r.ru_nswap);
4408  appendStringInfo(&str,
4409  "!\t%ld [%ld] signals rcvd, %ld/%ld [%ld/%ld] messages rcvd/sent\n",
4410  r.ru_nsignals - Save_r.ru_nsignals,
4411  r.ru_nsignals,
4412  r.ru_msgrcv - Save_r.ru_msgrcv,
4413  r.ru_msgsnd - Save_r.ru_msgsnd,
4414  r.ru_msgrcv, r.ru_msgsnd);
4415  appendStringInfo(&str,
4416  "!\t%ld/%ld [%ld/%ld] voluntary/involuntary context switches\n",
4417  r.ru_nvcsw - Save_r.ru_nvcsw,
4418  r.ru_nivcsw - Save_r.ru_nivcsw,
4419  r.ru_nvcsw, r.ru_nivcsw);
4420 #endif /* HAVE_GETRUSAGE */
4421 
4422  /* remove trailing newline */
4423  if (str.data[str.len - 1] == '\n')
4424  str.data[--str.len] = '\0';
4425 
4426  ereport(LOG,
4427  (errmsg_internal("%s", title),
4428  errdetail_internal("%s", str.data)));
4429 
4430  pfree(str.data);
4431 }
4432 
4433 /*
4434  * on_proc_exit handler to log end of session
4435  */
4436 static void
4438 {
4439  Port *port = MyProcPort;
4440  long secs;
4441  int usecs;
4442  int msecs;
4443  int hours,
4444  minutes,
4445  seconds;
4446 
4449  &secs, &usecs);
4450  msecs = usecs / 1000;
4451 
4452  hours = secs / SECS_PER_HOUR;
4453  secs %= SECS_PER_HOUR;
4454  minutes = secs / SECS_PER_MINUTE;
4455  seconds = secs % SECS_PER_MINUTE;
4456 
4457  ereport(LOG,
4458  (errmsg("disconnection: session time: %d:%02d:%02d.%03d "
4459  "user=%s database=%s host=%s%s%s",
4460  hours, minutes, seconds, msecs,
4461  port->user_name, port->database_name, port->remote_host,
4462  port->remote_port[0] ? " port=" : "", port->remote_port)));
4463 }
pg_stack_base_t set_stack_base(void)
Definition: postgres.c:3039
signed short int16
Definition: c.h:241
void ProcessCatchupInterrupt(void)
Definition: sinval.c:177
void InitializeTimeouts(void)
Definition: timeout.c:340
MemoryContext context
Definition: plancache.h:89
ParamExternData params[FLEXIBLE_ARRAY_MEMBER]
Definition: params.h:74
#define NIL
Definition: pg_list.h:69
Datum value
Definition: params.h:55
int log_min_duration_statement
Definition: guc.c:433
void AbortCurrentTransaction(void)
Definition: xact.c:2946
volatile uint32 InterruptHoldoffCount
Definition: globals.c:33
GucContext
Definition: guc.h:68
void SetRemoteDestReceiverParams(DestReceiver *self, Portal portal)
Definition: printtup.c:101
Portal CreatePortal(const char *name, bool allowDup, bool dupSilent)
Definition: portalmem.c:196
static void exec_describe_portal_message(const char *portal_name)
Definition: postgres.c:2386
#define SIGUSR1
Definition: win32.h:197
void(* rDestroy)(DestReceiver *self)
Definition: dest.h:122
#define IsA(nodeptr, _type_)
Definition: nodes.h:516
int gettimeofday(struct timeval *tp, struct timezone *tzp)
Definition: gettimeofday.c:105
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:201
bool IsWaitingForLock(void)
Definition: proc.c:651
void RecoveryConflictInterrupt(ProcSignalReason reason)
Definition: postgres.c:2722
#define HOLD_CANCEL_INTERRUPTS()
Definition: miscadmin.h:121
List * QueryRewrite(Query *parsetree)
void BeginReportingGUCOptions(void)
Definition: guc.c:5083
#define DEBUG1
Definition: elog.h:25
int MyProcPid
Definition: globals.c:37
int errhint(const char *fmt,...)
Definition: elog.c:978
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition: lsyscache.c:2535
void PortalSetResultFormat(Portal portal, int nFormats, int16 *formats)
Definition: pquery.c:644
void * parserSetupArg
Definition: params.h:72
int GetOldFunctionMessage(StringInfo buf)
Definition: fastpath.c:79
List * raw_parser(const char *str)
Definition: parser.c:35
#define pq_flush()
Definition: libpq.h:39
static int ReadCommand(StringInfo inBuf)
Definition: postgres.c:513
struct Port * MyProcPort
Definition: globals.c:39
void PortalStart(Portal portal, ParamListInfo params, int eflags, Snapshot snapshot)
Definition: pquery.c:459
void pgstat_report_recovery_conflict(int reason)
Definition: pgstat.c:1407
static void finish_xact_command(void)
Definition: postgres.c:2457
void elog_node_display(int lev, const char *title, const void *obj, bool pretty)
Definition: print.c:71
void ProcessConfigFile(GucContext context)
bool visible
Definition: portal.h:177
CommandDest
Definition: dest.h:86
#define end(cp)
Definition: zic.c:59
bool log_parser_stats
Definition: guc.c:416
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:2678
void PortalDefineQuery(Portal portal, const char *prepStmtName, const char *sourceText, const char *commandTag, List *stmts, CachedPlan *cplan)
Definition: portalmem.c:300
#define DEBUG3
Definition: elog.h:23
static volatile sig_atomic_t got_SIGHUP
Definition: postgres.c:129
bool log_statement_stats
Definition: guc.c:419
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1551
#define GUC_check_errdetail
Definition: guc.h:408
const char * commandTag
Definition: plancache.h:81
void on_proc_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:292
void pgstat_report_activity(BackendState state, const char *cmd_str)
Definition: pgstat.c:2790
CachedPlanSource * plansource
Definition: prepare.h:31
PGPROC * MyProc
Definition: proc.c:63
const char * pq_getmsgstring(StringInfo msg)
Definition: pqformat.c:620
void ShowUsage(const char *title)
Definition: postgres.c:4342
void MemoryContextSetParent(MemoryContext context, MemoryContext new_parent)
Definition: mcxt.c:318
Portal GetPortalByName(const char *name)
Definition: portalmem.c:130
#define CURSOR_OPT_BINARY
Definition: parsenodes.h:2344
char * pstrdup(const char *in)
Definition: mcxt.c:1077
void CommitTransactionCommand(void)
Definition: xact.c:2707
void InitStandaloneProcess(const char *argv0)
Definition: miscinit.c:217
void ParseLongOption(const char *string, char **name, char **value)
Definition: guc.c:9051
void ValidatePgVersion(const char *path)
Definition: miscinit.c:1229
bool IsAbortedTransactionBlockState(void)
Definition: xact.c:367
bool set_plan_disabling_options(const char *arg, GucContext context, GucSource source)
Definition: postgres.c:3211
static struct rusage Save_r
Definition: postgres.c:4331
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
volatile uint32 QueryCancelHoldoffCount
Definition: globals.c:34
void set_ps_display(const char *activity, bool force)
Definition: ps_status.c:299
static bool IsTransactionStmtList(List *parseTrees)
Definition: postgres.c:2532
List * pg_analyze_and_rewrite_params(Node *parsetree, const char *query_string, ParserSetupHook parserSetup, void *parserSetupArg)
Definition: postgres.c:690
static void forbidden_in_wal_sender(char firstchar)
Definition: postgres.c:4277
Definition: nodes.h:465
void proc_exit(int code)
Definition: ipc.c:99
int errcode(int sqlerrcode)
Definition: elog.c:569
Definition: libpq-be.h:118
int errhidestmt(bool hide_stmt)
Definition: elog.c:1059
bool IsTransactionOrTransactionBlock(void)
Definition: xact.c:4282
const char * get_stats_option_name(const char *arg)
Definition: postgres.c:3253
static List * new_list(NodeTag type)
Definition: list.c:63
void pq_putemptymessage(char msgtype)
Definition: pqformat.c:420
#define SetProcessingMode(mode)
Definition: miscadmin.h:367
void BaseInit(void)
Definition: postinit.c:517
static int errdetail_abort(void)
Definition: postgres.c:2243
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
char * remote_port
Definition: libpq-be.h:130
void PopActiveSnapshot(void)
Definition: snapmgr.c:619
void set_debug_options(int debug_flag, GucContext context, GucSource source)
Definition: postgres.c:3182
int sig_atomic_t
Definition: c.h:339
struct timeval ru_stime
Definition: rusagestub.h:29
void BeginCommand(const char *commandTag, CommandDest dest)
Definition: dest.c:91
ParserSetupHook parserSetup
Definition: params.h:71
struct ParamListInfoData * ParamListInfo
Definition: params.h:61
int getrusage(int who, struct rusage *rusage)
Definition: getrusage.c:32
#define LOG
Definition: elog.h:26
unsigned int Oid
Definition: postgres_ext.h:31
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:104
Node * utilityStmt
Definition: parsenodes.h:111
List * stmts
Definition: portal.h:132
volatile bool QueryCancelPending
Definition: globals.c:30
const char * progname
Definition: pg_standby.c:37
void restore_stack_base(pg_stack_base_t base)
Definition: postgres.c:3070
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:187
#define OidIsValid(objectId)
Definition: c.h:524
void SendRowDescriptionMessage(TupleDesc typeinfo, List *targetlist, int16 *formats)
Definition: printtup.c:190
List * pg_analyze_and_rewrite(Node *parsetree, const char *query_string, Oid *paramTypes, int numParams)
Definition: postgres.c:655
bool IsBinaryUpgrade
Definition: globals.c:98
#define SIGQUIT
Definition: win32.h:183
PlannedStmt * planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
Definition: planner.c:150
int getopt(int nargc, char *const *nargv, const char *ostr)
Definition: getopt.c:72
void FlushErrorState(void)
Definition: elog.c:1571
#define PG_SETMASK(mask)
Definition: pqsignal.h:30
int BlockSig
Definition: pqsignal.c:26
void pq_beginmessage(StringInfo buf, char msgtype)
Definition: pqformat.c:87
void StatementCancelHandler(SIGNAL_ARGS)
Definition: postgres.c:2671
#define ALLOCSET_DEFAULT_MINSIZE
Definition: memutils.h:141
const char * pq_getmsgbytes(StringInfo msg, int datalen)
Definition: pqformat.c:549
signed int int32
Definition: c.h:242
static void exec_execute_message(const char *portal_name, long max_rows)
Definition: postgres.c:1844
int errdetail_internal(const char *fmt,...)
Definition: elog.c:891
GucSource
Definition: guc.h:105
static bool IsTransactionExitStmt(Node *parsetree)
Definition: postgres.c:2493
static void log_disconnections(int code, Datum arg)
Definition: postgres.c:4437
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
TupleDesc resultDesc
Definition: plancache.h:88
void * copyObject(const void *from)
Definition: copyfuncs.c:4190
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:115
ErrorContextCallback * error_context_stack
Definition: elog.c:89
int check_log_duration(char *msec_str, bool was_logged)
Definition: postgres.c:2103
#define list_make1(x1)
Definition: pg_list.h:133
volatile bool ClientConnectionLost
Definition: globals.c:32
void pqinitmask(void)
Definition: pqsignal.c:46
static int errdetail_execute(List *raw_parsetree_list)
Definition: postgres.c:2148
bool ClientAuthInProgress
Definition: postmaster.c:343
void ResetUsage(void)
Definition: postgres.c:4335
void * paramFetchArg
Definition: params.h:70
bool am_walsender
Definition: walsender.c:101
bool check_max_stack_depth(int *newval, void **extra, GucSource source)
Definition: postgres.c:3150
bool Debug_print_plan
Definition: guc.c:411
#define appendStringInfoCharMacro(str, ch)
Definition: stringinfo.h:127
#define sigsetjmp(x, y)
Definition: c.h:1063
ParamFetchHook paramFetch
Definition: params.h:69
void pfree(void *pointer)
Definition: mcxt.c:910
ParamListInfo portalParams
Definition: portal.h:135
char * pg_client_to_server(const char *s, int len)
Definition: mbutils.c:556
#define SIG_IGN
Definition: win32.h:179
void disable_all_timeouts(bool keep_indicators)
Definition: timeout.c:596
int optind
Definition: getopt.c:51
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
#define linitial(l)
Definition: pg_list.h:110
void EndCommand(const char *commandTag, CommandDest dest)
Definition: dest.c:143
Node * raw_parse_tree
Definition: plancache.h:79
#define ERROR
Definition: elog.h:41
void CreateDataDirLockFile(bool amPostmaster)
Definition: miscinit.c:1039
void pq_startmsgread(void)
Definition: pqcomm.c:1162
void ProcessNotifyInterrupt(void)
Definition: async.c:1685
static int InteractiveBackend(StringInfo inBuf)
Definition: postgres.c:219
bool pq_is_reading_msg(void)
Definition: pqcomm.c:1202
CachedPlan * GetCachedPlan(CachedPlanSource *plansource, ParamListInfo boundParams, bool useResOwner)
Definition: plancache.c:1129
void on_exit_reset(void)
Definition: ipc.c:396
static struct @72 value
static int interactive_getc(void)
Definition: postgres.c:308
void WalSndSignals(void)
Definition: walsender.c:2593
void ProcessInterrupts(void)
Definition: postgres.c:2844
#define FATAL
Definition: elog.h:50
List * pg_parse_query(const char *query_string)
Definition: postgres.c:613
void MemoryContextStats(MemoryContext context)
Definition: mcxt.c:484
#define MAXPGPATH
bool Debug_print_parse
Definition: guc.c:412
static void SigHupHandler(SIGNAL_ARGS)
Definition: postgres.c:2705
TimestampTz SessionStartTime
Definition: libpq-be.h:154
const char * commandTag
Definition: portal.h:131
Datum OidReceiveFunctionCall(Oid functionId, StringInfo buf, Oid typioparam, int32 typmod)
Definition: fmgr.c:2057
void PostgresMain(int argc, char *argv[], const char *dbname, const char *username)
Definition: postgres.c:3552
#define DEBUG2
Definition: elog.h:24
void InitProcess(void)
Definition: proc.c:284
void HandleParallelMessages(void)
Definition: parallel.c:620
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:157
Definition: dest.h:88
int UnBlockSig
Definition: pqsignal.c:26
Oid * param_types
Definition: plancache.h:82
char * c
char OutputFileName[MAXPGPATH]
Definition: globals.c:60
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:6394
static char * buf
Definition: pg_test_fsync.c:65
bool analyze_requires_snapshot(Node *parseTree)
Definition: analyze.c:298
static struct timeval Save_t
Definition: postgres.c:4332
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:542
bool recoveryConflictPending
Definition: proc.h:110
void check_stack_depth(void)
Definition: postgres.c:3089
bool IsUnderPostmaster
Definition: globals.c:97
static CachedPlanSource * unnamed_stmt_psrc
Definition: postgres.c:156
DestReceiver * CreateDestReceiver(CommandDest dest)
Definition: dest.c:101
static void exec_bind_message(StringInfo input_message)
Definition: postgres.c:1463
char * flag(int b)
Definition: test-ctype.c:33
#define SECS_PER_MINUTE
Definition: timestamp.h:100
int errdetail(const char *fmt,...)
Definition: elog.c:864
Definition: dest.h:89
#define COMMERROR
Definition: elog.h:28
char * user_name
Definition: libpq-be.h:139
void ChangeToDataDir(void)
Definition: miscinit.c:113
int opterr
Definition: getopt.c:50
void resetStringInfo(StringInfo str)
Definition: stringinfo.c:62
long MyCancelKey
Definition: globals.c:40
void ReplicationSlotRelease(void)
Definition: slot.c:365
void(* ParserSetupHook)(struct ParseState *pstate, void *arg)
Definition: params.h:65
bool ActiveSnapshotSet(void)
Definition: snapmgr.c:656
static int SocketBackend(StringInfo inBuf)
Definition: postgres.c:336
static bool xact_started
Definition: postgres.c:135
const char * p_sourcetext
Definition: parse_node.h:134
void InitWalSender(void)
volatile uint32 CritSectionCount
Definition: globals.c:35
static int errdetail_params(ParamListInfo params)
Definition: postgres.c:2179
Query * parse_analyze(Node *parseTree, const char *sourceText, Oid *paramTypes, int numParams)
Definition: analyze.c:91
void getTypeBinaryInputInfo(Oid type, Oid *typReceive, Oid *typIOParam)
Definition: lsyscache.c:2568
char * portalname
Definition: parsenodes.h:2394
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:2893
#define lnext(lc)
Definition: pg_list.h:105
void getTypeInputInfo(Oid type, Oid *typInput, Oid *typIOParam)
Definition: lsyscache.c:2502
#define ereport(elevel, rest)
Definition: elog.h:132
int max_stack_depth
Definition: postgres.c:94
void exec_replication_command(const char *cmd_string)
Definition: walsender.c:1262
void LockErrorCleanup(void)
Definition: proc.c:668
#define SECS_PER_HOUR
Definition: timestamp.h:99
MemoryContext TopMemoryContext
Definition: mcxt.c:43
const char * CreateCommandTag(Node *parsetree)
Definition: utility.c:1901
void SetLatch(volatile Latch *latch)
Definition: unix_latch.c:520
static int port
Definition: pg_regress.c:87
static ProcSignalReason RecoveryConflictReason
Definition: postgres.c:176
Definition: guc.h:72
long get_stack_depth_rlimit(void)
Definition: postgres.c:4299
struct ParamExternData ParamExternData
List * lappend(List *list, void *datum)
Definition: list.c:128
static bool RecoveryConflictPending
Definition: postgres.c:174
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:169
void initStringInfo(StringInfo str)
Definition: stringinfo.c:46
#define WARNING
Definition: elog.h:38
const char * debug_query_string
Definition: postgres.c:83
uint32 ProtocolVersion
Definition: pqcomm.h:113
int pq_getmessage(StringInfo s, int maxlen)
Definition: pqcomm.c:1224
static List * pg_rewrite_query(Query *query)
Definition: postgres.c:740
#define InvalidSnapshot
Definition: snapshot.h:23
#define MemoryContextResetAndDeleteChildren(ctx)
Definition: memutils.h:88
static bool check_log_statement(List *stmt_list)
Definition: postgres.c:2066
static void exec_parse_message(const char *query_string, const char *stmt_name, Oid *paramTypes, int numParams)
Definition: postgres.c:1199
#define PortalIsValid(p)
Definition: portal.h:184
static bool RecoveryConflictRetryable
Definition: postgres.c:175
static void start_xact_command(void)
Definition: postgres.c:2437
static bool IsTransactionExitStmtList(List *parseTrees)
Definition: postgres.c:2510
static bool doing_extended_query_message
Definition: postgres.c:148
void process_session_preload_libraries(void)
Definition: miscinit.c:1374
void WalSndErrorCleanup(void)
Definition: walsender.c:252
struct timeval ru_utime
Definition: rusagestub.h:28
MemoryContext AllocSetContextCreate(MemoryContext parent, const char *name, Size minContextSize, Size initBlockSize, Size maxBlockSize)
Definition: aset.c:435
bool ismove
Definition: parsenodes.h:2395
int16 * formats
Definition: portal.h:151
uintptr_t Datum
Definition: postgres.h:374
void CommandCounterIncrement(void)
Definition: xact.c:919
bool SelectConfigFiles(const char *userDoption, const char *progname)
Definition: guc.c:4423
void ProcessClientReadInterrupt(bool blocked)
Definition: postgres.c:533
#define RUSAGE_SELF
Definition: rusagestub.h:23
int PostAuthDelay
Definition: postgres.c:97
bool get_timeout_indicator(TimeoutId id, bool reset_indicator)
Definition: timeout.c:633
static int errdetail_recovery_conflict(void)
Definition: postgres.c:2257
void EmitErrorReport(void)
Definition: elog.c:1435
const char * sourceText
Definition: portal.h:130
TimestampTz PgStartTime
Definition: timestamp.c:48
Query * transformTopLevelStmt(ParseState *pstate, Node *parseTree)
Definition: analyze.c:180
void StorePreparedStatement(const char *stmt_name, CachedPlanSource *plansource, bool from_sql)
Definition: prepare.c:442
#define SIGPIPE
Definition: win32.h:187
int pq_getbyte(void)
Definition: pqcomm.c:952
#define SIGHUP
Definition: win32.h:182
void pq_endmsgread(void)
Definition: pqcomm.c:1186
static char * username
Definition: initdb.c:124
TupleDesc tupDesc
Definition: portal.h:149
#define InvalidOid
Definition: postgres_ext.h:36
#define SIG_DFL
Definition: win32.h:177
void SaveCachedPlan(CachedPlanSource *plansource)
Definition: plancache.c:436
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:167
#define free(a)
Definition: header.h:60
CmdType commandType
Definition: parsenodes.h:103
volatile bool InterruptPending
Definition: globals.c:29
int pq_getmsgbyte(StringInfo msg)
Definition: pqformat.c:431
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
bool log_duration
Definition: guc.c:410
int errmsg_internal(const char *fmt,...)
Definition: elog.c:820
void enable_timeout_after(TimeoutId id, int delay_ms)
Definition: timeout.c:428
ReplicationSlot * MyReplicationSlot
Definition: slot.c:94
static long max_stack_depth_bytes
Definition: postgres.c:107
#define COMPLETION_TAG_BUFSIZE
Definition: dest.h:74
#define pq_comm_reset()
Definition: libpq.h:38
Query * parse_analyze_varparams(Node *parseTree, const char *sourceText, Oid **paramTypes, int *numParams)
Definition: analyze.c:122
#define SIGNAL_ARGS
Definition: c.h:1053
#define NULL
Definition: c.h:215
bool PortalRun(Portal portal, long count, bool isTopLevel, DestReceiver *dest, DestReceiver *altdest, char *completionTag)
Definition: pquery.c:706
#define Assert(condition)
Definition: c.h:661
void ProcessCompletedNotifies(void)
Definition: async.c:1056
#define lfirst(lc)
Definition: pg_list.h:106
bool proc_exit_inprogress
Definition: ipc.c:40
void CompleteCachedPlan(CachedPlanSource *plansource, List *querytree_list, MemoryContext querytree_context, Oid *param_types, int num_params, ParserSetupHook parserSetup, void *parserSetupArg, int cursor_options, bool fixed_result)
Definition: plancache.c:322
bool HoldingBufferPinThatDelaysRecovery(void)
Definition: bufmgr.c:3306
void StartTransactionCommand(void)
Definition: xact.c:2637
static bool DoingCommandRead
Definition: postgres.c:142
uint16 pflags
Definition: params.h:57
const char * query_string
Definition: plancache.h:80
void InitializeMaxBackends(void)
Definition: postinit.c:495
char * dbname
Definition: streamutil.c:42
bool ParallelMessagePending
Definition: parallel.c:96
static int list_length(const List *l)
Definition: pg_list.h:89
#define newval
#define PortalGetHeapMemory(portal)
Definition: portal.h:190
List * CachedPlanGetTargetList(CachedPlanSource *plansource)
Definition: plancache.c:1418
bool IsTransactionState(void)
Definition: xact.c:347
MemoryContext MessageContext
Definition: mcxt.c:47
Datum querytree(PG_FUNCTION_ARGS)
Definition: _int_bool.c:662
#define UNKNOWNOID
Definition: pg_type.h:423
sigjmp_buf * PG_exception_stack
Definition: elog.c:91
const char * name
Definition: encode.c:521
int log_statement
Definition: postgres.c:91
int StatementTimeout
Definition: proc.c:58
static bool EchoQuery
Definition: postgres.c:161
char * stack_base_ptr
Definition: postgres.c:115
static const char * userDoption
Definition: postgres.c:159
bool IsSubTransaction(void)
Definition: xact.c:4336
volatile bool ProcDiePending
Definition: globals.c:31
bool atStart
Definition: portal.h:170
void SetCurrentStatementStartTimestamp(void)
Definition: xact.c:737
char * remote_host
Definition: libpq-be.h:125
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, char *out_dbname)
Definition: postinit.c:558
char * OidOutputFunctionCall(Oid functionId, Datum val)
Definition: fmgr.c:2048
#define GUC_check_errhint
Definition: guc.h:412
void * palloc(Size size)
Definition: mcxt.c:809
int errmsg(const char *fmt,...)
Definition: elog.c:791
void PortalDrop(Portal portal, bool isTopCommit)
Definition: portalmem.c:466
void pq_sendint(StringInfo buf, int i, int b)
Definition: pqformat.c:235
void ReadyForQuery(CommandDest dest)
Definition: dest.c:223
void pq_endmessage(StringInfo buf)
Definition: pqformat.c:343
#define sigjmp_buf
Definition: c.h:1062
char * optarg
Definition: getopt.c:53
void die(SIGNAL_ARGS)
Definition: postgres.c:2640
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:113
#define ALLOCSET_DEFAULT_INITSIZE
Definition: memutils.h:142
int i
void FloatExceptionHandler(SIGNAL_ARGS)
Definition: postgres.c:2692
static void drop_unnamed_stmt(void)
Definition: postgres.c:2554
bool Debug_pretty_print
Definition: guc.c:414
char * name
Definition: parsenodes.h:2988
ProcSignalReason
Definition: procsignal.h:30
int pq_getstring(StringInfo s)
Definition: pqcomm.c:1118
void * arg
char * DataDir
Definition: globals.c:58
#define sigaddset(set, signum)
Definition: pqsignal.h:36
void DropCachedPlan(CachedPlanSource *plansource)
Definition: plancache.c:481
#define sigdelset(set, signum)
Definition: pqsignal.h:37
struct Latch * MyLatch
Definition: globals.c:50
volatile sig_atomic_t notifyInterruptPending
Definition: async.c:346
#define ALLOCSET_DEFAULT_MAXSIZE
Definition: memutils.h:143
unsigned int pq_getmsgint(StringInfo msg, int b)
Definition: pqformat.c:447
bool Debug_print_rewritten
Definition: guc.c:413
volatile sig_atomic_t catchupInterruptPending
Definition: sinval.c:41
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:96
bool Log_disconnections
Definition: postgres.c:89
static char format
Definition: pg_basebackup.c:58
List * stmt_list
Definition: plancache.h:130
void process_postgres_switches(int argc, char *argv[], GucContext ctx, const char **dbname)
Definition: postgres.c:3293
#define elog
Definition: elog.h:228
void pq_getmsgend(StringInfo msg)
Definition: pqformat.c:647
void disable_timeout(TimeoutId id, bool keep_indicator)
Definition: timeout.c:525
int cursorOptions
Definition: portal.h:139
void procsignal_sigusr1_handler(SIGNAL_ARGS)
Definition: procsignal.c:268
CommandDest whereToSendOutput
Definition: postgres.c:86
List * FetchPortalTargetList(Portal portal)
Definition: pquery.c:357
#define SIGCHLD
Definition: win32.h:192
void TimestampDifference(TimestampTz start_time, TimestampTz stop_time, long *secs, int *microsecs)
Definition: timestamp.c:1626
void free_parsestate(ParseState *pstate)
Definition: parse_node.c:74
static bool ignore_till_sync
Definition: postgres.c:149
char * database_name
Definition: libpq-be.h:138
void assign_max_stack_depth(int newval, void *extra)
Definition: postgres.c:3167
PreparedStatement * FetchPreparedStatement(const char *stmt_name, bool throwError)
Definition: prepare.c:484
CachedPlanSource * CreateCachedPlan(Node *raw_parse_tree, const char *query_string, const char *commandTag)
Definition: plancache.c:149
Definition: pg_list.h:45
bool isnull
Definition: params.h:56
#define STACK_DEPTH_SLOP
Definition: tcopprot.h:30
Datum OidInputFunctionCall(Oid functionId, char *str, Oid typioparam, int32 typmod)
Definition: fmgr.c:2039
List * pg_plan_queries(List *querytrees, int cursorOptions, ParamListInfo boundParams)
Definition: postgres.c:851
void quickdie(SIGNAL_ARGS)
Definition: postgres.c:2579
#define _(x)
Definition: elog.c:83
ProtocolVersion FrontendProtocol
Definition: globals.c:27
MemoryContext PostmasterContext
Definition: mcxt.c:45
long val
Definition: informix.c:689
post_parse_analyze_hook_type post_parse_analyze_hook
Definition: analyze.c:49
bool log_planner_stats
Definition: guc.c:417
#define SIGUSR2
Definition: win32.h:198
#define offsetof(type, field)
Definition: c.h:541
static void exec_simple_query(const char *query_string)
Definition: postgres.c:884
#define PARAM_FLAG_CONST
Definition: params.h:51
const char * prepStmtName
Definition: portal.h:118
static int UseNewLine
Definition: postgres.c:168
LogStmtLevel GetCommandLogLevel(Node *parsetree)
Definition: utility.c:2688
int HandleFunctionRequest(StringInfo msgBuf)
Definition: fastpath.c:270
void NullCommand(CommandDest dest)
Definition: dest.c:182
TimestampTz GetCurrentStatementStartTimestamp(void)
Definition: xact.c:714
char * pg_stack_base_t
Definition: miscadmin.h:265
void InitializeGUCOptions(void)
Definition: guc.c:4201
TransactionStmtKind kind
Definition: parsenodes.h:2624
#define RESUME_CANCEL_INTERRUPTS()
Definition: miscadmin.h:123
void ProcessClientWriteInterrupt(bool blocked)
Definition: postgres.c:571
#define FETCH_ALL
Definition: parsenodes.h:2387
void pgstat_report_stat(bool force)
Definition: pgstat.c:743
void DropPreparedStatement(const char *stmt_name, bool showError)
Definition: prepare.c:569
static void exec_describe_statement_message(const char *stmt_name)
Definition: postgres.c:2293
PlannedStmt * pg_plan_query(Query *querytree, int cursorOptions, ParamListInfo boundParams)
Definition: postgres.c:792