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,
1035 
1036  /* Done with the snapshot used for parsing/planning */
1037  if (snapshot_set)
1039 
1040  /* If we got a cancel signal in analysis or planning, quit */
1042 
1043  /*
1044  * Create unnamed portal to run the query or queries in. If there
1045  * already is one, silently drop it.
1046  */
1047  portal = CreatePortal("", true, true);
1048  /* Don't display the portal in pg_cursors */
1049  portal->visible = false;
1050 
1051  /*
1052  * We don't have to copy anything into the portal, because everything
1053  * we are passing here is in MessageContext, which will outlive the
1054  * portal anyway.
1055  */
1056  PortalDefineQuery(portal,
1057  NULL,
1058  query_string,
1059  commandTag,
1060  plantree_list,
1061  NULL);
1062 
1063  /*
1064  * Start the portal. No parameters here.
1065  */
1066  PortalStart(portal, NULL, 0, InvalidSnapshot);
1067 
1068  /*
1069  * Select the appropriate output format: text unless we are doing a
1070  * FETCH from a binary cursor. (Pretty grotty to have to do this here
1071  * --- but it avoids grottiness in other places. Ah, the joys of
1072  * backward compatibility...)
1073  */
1074  format = 0; /* TEXT is default */
1075  if (IsA(parsetree, FetchStmt))
1076  {
1077  FetchStmt *stmt = (FetchStmt *) parsetree;
1078 
1079  if (!stmt->ismove)
1080  {
1081  Portal fportal = GetPortalByName(stmt->portalname);
1082 
1083  if (PortalIsValid(fportal) &&
1084  (fportal->cursorOptions & CURSOR_OPT_BINARY))
1085  format = 1; /* BINARY */
1086  }
1087  }
1088  PortalSetResultFormat(portal, 1, &format);
1089 
1090  /*
1091  * Now we can create the destination receiver object.
1092  */
1093  receiver = CreateDestReceiver(dest);
1094  if (dest == DestRemote)
1095  SetRemoteDestReceiverParams(receiver, portal);
1096 
1097  /*
1098  * Switch back to transaction context for execution.
1099  */
1100  MemoryContextSwitchTo(oldcontext);
1101 
1102  /*
1103  * Run the portal to completion, and then drop it (and the receiver).
1104  */
1105  (void) PortalRun(portal,
1106  FETCH_ALL,
1107  isTopLevel,
1108  receiver,
1109  receiver,
1110  completionTag);
1111 
1112  (*receiver->rDestroy) (receiver);
1113 
1114  PortalDrop(portal, false);
1115 
1116  if (IsA(parsetree, TransactionStmt))
1117  {
1118  /*
1119  * If this was a transaction control statement, commit it. We will
1120  * start a new xact command for the next command (if any).
1121  */
1123  }
1124  else if (lnext(parsetree_item) == NULL)
1125  {
1126  /*
1127  * If this is the last parsetree of the query string, close down
1128  * transaction statement before reporting command-complete. This
1129  * is so that any end-of-transaction errors are reported before
1130  * the command-complete message is issued, to avoid confusing
1131  * clients who will expect either a command-complete message or an
1132  * error, not one and then the other. But for compatibility with
1133  * historical Postgres behavior, we do not force a transaction
1134  * boundary between queries appearing in a single query string.
1135  */
1137  }
1138  else
1139  {
1140  /*
1141  * We need a CommandCounterIncrement after every query, except
1142  * those that start or end a transaction block.
1143  */
1145  }
1146 
1147  /*
1148  * Tell client that we're done with this query. Note we emit exactly
1149  * one EndCommand report for each raw parsetree, thus one for each SQL
1150  * command the client sent, regardless of rewriting. (But a command
1151  * aborted by error will not send an EndCommand report at all.)
1152  */
1153  EndCommand(completionTag, dest);
1154  } /* end loop over parsetrees */
1155 
1156  /*
1157  * Close down transaction statement, if one is open.
1158  */
1160 
1161  /*
1162  * If there were no parsetrees, return EmptyQueryResponse message.
1163  */
1164  if (!parsetree_list)
1165  NullCommand(dest);
1166 
1167  /*
1168  * Emit duration logging if appropriate.
1169  */
1170  switch (check_log_duration(msec_str, was_logged))
1171  {
1172  case 1:
1173  ereport(LOG,
1174  (errmsg("duration: %s ms", msec_str),
1175  errhidestmt(true)));
1176  break;
1177  case 2:
1178  ereport(LOG,
1179  (errmsg("duration: %s ms statement: %s",
1180  msec_str, query_string),
1181  errhidestmt(true),
1182  errdetail_execute(parsetree_list)));
1183  break;
1184  }
1185 
1186  if (save_log_statement_stats)
1187  ShowUsage("QUERY STATISTICS");
1188 
1189  TRACE_POSTGRESQL_QUERY_DONE(query_string);
1190 
1192 }
1193 
1194 /*
1195  * exec_parse_message
1196  *
1197  * Execute a "Parse" protocol message.
1198  */
1199 static void
1200 exec_parse_message(const char *query_string, /* string to execute */
1201  const char *stmt_name, /* name for prepared stmt */
1202  Oid *paramTypes, /* parameter types */
1203  int numParams) /* number of parameters */
1204 {
1205  MemoryContext unnamed_stmt_context = NULL;
1206  MemoryContext oldcontext;
1207  List *parsetree_list;
1208  Node *raw_parse_tree;
1209  const char *commandTag;
1210  List *querytree_list;
1211  CachedPlanSource *psrc;
1212  bool is_named;
1213  bool save_log_statement_stats = log_statement_stats;
1214  char msec_str[32];
1215 
1216  /*
1217  * Report query to various monitoring facilities.
1218  */
1219  debug_query_string = query_string;
1220 
1221  pgstat_report_activity(STATE_RUNNING, query_string);
1222 
1223  set_ps_display("PARSE", false);
1224 
1225  if (save_log_statement_stats)
1226  ResetUsage();
1227 
1228  ereport(DEBUG2,
1229  (errmsg("parse %s: %s",
1230  *stmt_name ? stmt_name : "<unnamed>",
1231  query_string)));
1232 
1233  /*
1234  * Start up a transaction command so we can run parse analysis etc. (Note
1235  * that this will normally change current memory context.) Nothing happens
1236  * if we are already in one.
1237  */
1239 
1240  /*
1241  * Switch to appropriate context for constructing parsetrees.
1242  *
1243  * We have two strategies depending on whether the prepared statement is
1244  * named or not. For a named prepared statement, we do parsing in
1245  * MessageContext and copy the finished trees into the prepared
1246  * statement's plancache entry; then the reset of MessageContext releases
1247  * temporary space used by parsing and rewriting. For an unnamed prepared
1248  * statement, we assume the statement isn't going to hang around long, so
1249  * getting rid of temp space quickly is probably not worth the costs of
1250  * copying parse trees. So in this case, we create the plancache entry's
1251  * query_context here, and do all the parsing work therein.
1252  */
1253  is_named = (stmt_name[0] != '\0');
1254  if (is_named)
1255  {
1256  /* Named prepared statement --- parse in MessageContext */
1257  oldcontext = MemoryContextSwitchTo(MessageContext);
1258  }
1259  else
1260  {
1261  /* Unnamed prepared statement --- release any prior unnamed stmt */
1263  /* Create context for parsing */
1264  unnamed_stmt_context =
1266  "unnamed prepared statement",
1270  oldcontext = MemoryContextSwitchTo(unnamed_stmt_context);
1271  }
1272 
1273  /*
1274  * Do basic parsing of the query or queries (this should be safe even if
1275  * we are in aborted transaction state!)
1276  */
1277  parsetree_list = pg_parse_query(query_string);
1278 
1279  /*
1280  * We only allow a single user statement in a prepared statement. This is
1281  * mainly to keep the protocol simple --- otherwise we'd need to worry
1282  * about multiple result tupdescs and things like that.
1283  */
1284  if (list_length(parsetree_list) > 1)
1285  ereport(ERROR,
1286  (errcode(ERRCODE_SYNTAX_ERROR),
1287  errmsg("cannot insert multiple commands into a prepared statement")));
1288 
1289  if (parsetree_list != NIL)
1290  {
1291  Query *query;
1292  bool snapshot_set = false;
1293  int i;
1294 
1295  raw_parse_tree = (Node *) linitial(parsetree_list);
1296 
1297  /*
1298  * Get the command name for possible use in status display.
1299  */
1300  commandTag = CreateCommandTag(raw_parse_tree);
1301 
1302  /*
1303  * If we are in an aborted transaction, reject all commands except
1304  * COMMIT/ROLLBACK. It is important that this test occur before we
1305  * try to do parse analysis, rewrite, or planning, since all those
1306  * phases try to do database accesses, which may fail in abort state.
1307  * (It might be safe to allow some additional utility commands in this
1308  * state, but not many...)
1309  */
1311  !IsTransactionExitStmt(raw_parse_tree))
1312  ereport(ERROR,
1313  (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1314  errmsg("current transaction is aborted, "
1315  "commands ignored until end of transaction block"),
1316  errdetail_abort()));
1317 
1318  /*
1319  * Create the CachedPlanSource before we do parse analysis, since it
1320  * needs to see the unmodified raw parse tree.
1321  */
1322  psrc = CreateCachedPlan(raw_parse_tree, query_string, commandTag);
1323 
1324  /*
1325  * Set up a snapshot if parse analysis will need one.
1326  */
1327  if (analyze_requires_snapshot(raw_parse_tree))
1328  {
1330  snapshot_set = true;
1331  }
1332 
1333  /*
1334  * Analyze and rewrite the query. Note that the originally specified
1335  * parameter set is not required to be complete, so we have to use
1336  * parse_analyze_varparams().
1337  */
1338  if (log_parser_stats)
1339  ResetUsage();
1340 
1341  query = parse_analyze_varparams(raw_parse_tree,
1342  query_string,
1343  &paramTypes,
1344  &numParams);
1345 
1346  /*
1347  * Check all parameter types got determined.
1348  */
1349  for (i = 0; i < numParams; i++)
1350  {
1351  Oid ptype = paramTypes[i];
1352 
1353  if (ptype == InvalidOid || ptype == UNKNOWNOID)
1354  ereport(ERROR,
1355  (errcode(ERRCODE_INDETERMINATE_DATATYPE),
1356  errmsg("could not determine data type of parameter $%d",
1357  i + 1)));
1358  }
1359 
1360  if (log_parser_stats)
1361  ShowUsage("PARSE ANALYSIS STATISTICS");
1362 
1363  querytree_list = pg_rewrite_query(query);
1364 
1365  /* Done with the snapshot used for parsing */
1366  if (snapshot_set)
1368  }
1369  else
1370  {
1371  /* Empty input string. This is legal. */
1372  raw_parse_tree = NULL;
1373  commandTag = NULL;
1374  psrc = CreateCachedPlan(raw_parse_tree, query_string, commandTag);
1375  querytree_list = NIL;
1376  }
1377 
1378  /*
1379  * CachedPlanSource must be a direct child of MessageContext before we
1380  * reparent unnamed_stmt_context under it, else we have a disconnected
1381  * circular subgraph. Klugy, but less so than flipping contexts even more
1382  * above.
1383  */
1384  if (unnamed_stmt_context)
1386 
1387  /* Finish filling in the CachedPlanSource */
1388  CompleteCachedPlan(psrc,
1389  querytree_list,
1390  unnamed_stmt_context,
1391  paramTypes,
1392  numParams,
1393  NULL,
1394  NULL,
1395  0, /* default cursor options */
1396  true); /* fixed result */
1397 
1398  /* If we got a cancel signal during analysis, quit */
1400 
1401  if (is_named)
1402  {
1403  /*
1404  * Store the query as a prepared statement.
1405  */
1406  StorePreparedStatement(stmt_name, psrc, false);
1407  }
1408  else
1409  {
1410  /*
1411  * We just save the CachedPlanSource into unnamed_stmt_psrc.
1412  */
1413  SaveCachedPlan(psrc);
1414  unnamed_stmt_psrc = psrc;
1415  }
1416 
1417  MemoryContextSwitchTo(oldcontext);
1418 
1419  /*
1420  * We do NOT close the open transaction command here; that only happens
1421  * when the client sends Sync. Instead, do CommandCounterIncrement just
1422  * in case something happened during parse/plan.
1423  */
1425 
1426  /*
1427  * Send ParseComplete.
1428  */
1430  pq_putemptymessage('1');
1431 
1432  /*
1433  * Emit duration logging if appropriate.
1434  */
1435  switch (check_log_duration(msec_str, false))
1436  {
1437  case 1:
1438  ereport(LOG,
1439  (errmsg("duration: %s ms", msec_str),
1440  errhidestmt(true)));
1441  break;
1442  case 2:
1443  ereport(LOG,
1444  (errmsg("duration: %s ms parse %s: %s",
1445  msec_str,
1446  *stmt_name ? stmt_name : "<unnamed>",
1447  query_string),
1448  errhidestmt(true)));
1449  break;
1450  }
1451 
1452  if (save_log_statement_stats)
1453  ShowUsage("PARSE MESSAGE STATISTICS");
1454 
1456 }
1457 
1458 /*
1459  * exec_bind_message
1460  *
1461  * Process a "Bind" message to create a portal from a prepared statement
1462  */
1463 static void
1465 {
1466  const char *portal_name;
1467  const char *stmt_name;
1468  int numPFormats;
1469  int16 *pformats = NULL;
1470  int numParams;
1471  int numRFormats;
1472  int16 *rformats = NULL;
1473  CachedPlanSource *psrc;
1474  CachedPlan *cplan;
1475  Portal portal;
1476  char *query_string;
1477  char *saved_stmt_name;
1478  ParamListInfo params;
1479  MemoryContext oldContext;
1480  bool save_log_statement_stats = log_statement_stats;
1481  bool snapshot_set = false;
1482  char msec_str[32];
1483 
1484  /* Get the fixed part of the message */
1485  portal_name = pq_getmsgstring(input_message);
1486  stmt_name = pq_getmsgstring(input_message);
1487 
1488  ereport(DEBUG2,
1489  (errmsg("bind %s to %s",
1490  *portal_name ? portal_name : "<unnamed>",
1491  *stmt_name ? stmt_name : "<unnamed>")));
1492 
1493  /* Find prepared statement */
1494  if (stmt_name[0] != '\0')
1495  {
1496  PreparedStatement *pstmt;
1497 
1498  pstmt = FetchPreparedStatement(stmt_name, true);
1499  psrc = pstmt->plansource;
1500  }
1501  else
1502  {
1503  /* special-case the unnamed statement */
1504  psrc = unnamed_stmt_psrc;
1505  if (!psrc)
1506  ereport(ERROR,
1507  (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
1508  errmsg("unnamed prepared statement does not exist")));
1509  }
1510 
1511  /*
1512  * Report query to various monitoring facilities.
1513  */
1515 
1517 
1518  set_ps_display("BIND", false);
1519 
1520  if (save_log_statement_stats)
1521  ResetUsage();
1522 
1523  /*
1524  * Start up a transaction command so we can call functions etc. (Note that
1525  * this will normally change current memory context.) Nothing happens if
1526  * we are already in one.
1527  */
1529 
1530  /* Switch back to message context */
1532 
1533  /* Get the parameter format codes */
1534  numPFormats = pq_getmsgint(input_message, 2);
1535  if (numPFormats > 0)
1536  {
1537  int i;
1538 
1539  pformats = (int16 *) palloc(numPFormats * sizeof(int16));
1540  for (i = 0; i < numPFormats; i++)
1541  pformats[i] = pq_getmsgint(input_message, 2);
1542  }
1543 
1544  /* Get the parameter value count */
1545  numParams = pq_getmsgint(input_message, 2);
1546 
1547  if (numPFormats > 1 && numPFormats != numParams)
1548  ereport(ERROR,
1549  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1550  errmsg("bind message has %d parameter formats but %d parameters",
1551  numPFormats, numParams)));
1552 
1553  if (numParams != psrc->num_params)
1554  ereport(ERROR,
1555  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1556  errmsg("bind message supplies %d parameters, but prepared statement \"%s\" requires %d",
1557  numParams, stmt_name, psrc->num_params)));
1558 
1559  /*
1560  * If we are in aborted transaction state, the only portals we can
1561  * actually run are those containing COMMIT or ROLLBACK commands. We
1562  * disallow binding anything else to avoid problems with infrastructure
1563  * that expects to run inside a valid transaction. We also disallow
1564  * binding any parameters, since we can't risk calling user-defined I/O
1565  * functions.
1566  */
1569  numParams != 0))
1570  ereport(ERROR,
1571  (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1572  errmsg("current transaction is aborted, "
1573  "commands ignored until end of transaction block"),
1574  errdetail_abort()));
1575 
1576  /*
1577  * Create the portal. Allow silent replacement of an existing portal only
1578  * if the unnamed portal is specified.
1579  */
1580  if (portal_name[0] == '\0')
1581  portal = CreatePortal(portal_name, true, true);
1582  else
1583  portal = CreatePortal(portal_name, false, false);
1584 
1585  /*
1586  * Prepare to copy stuff into the portal's memory context. We do all this
1587  * copying first, because it could possibly fail (out-of-memory) and we
1588  * don't want a failure to occur between GetCachedPlan and
1589  * PortalDefineQuery; that would result in leaking our plancache refcount.
1590  */
1591  oldContext = MemoryContextSwitchTo(PortalGetHeapMemory(portal));
1592 
1593  /* Copy the plan's query string into the portal */
1594  query_string = pstrdup(psrc->query_string);
1595 
1596  /* Likewise make a copy of the statement name, unless it's unnamed */
1597  if (stmt_name[0])
1598  saved_stmt_name = pstrdup(stmt_name);
1599  else
1600  saved_stmt_name = NULL;
1601 
1602  /*
1603  * Set a snapshot if we have parameters to fetch (since the input
1604  * functions might need it) or the query isn't a utility command (and
1605  * hence could require redoing parse analysis and planning). We keep the
1606  * snapshot active till we're done, so that plancache.c doesn't have to
1607  * take new ones.
1608  */
1609  if (numParams > 0 ||
1610  (psrc->raw_parse_tree &&
1612  {
1614  snapshot_set = true;
1615  }
1616 
1617  /*
1618  * Fetch parameters, if any, and store in the portal's memory context.
1619  */
1620  if (numParams > 0)
1621  {
1622  int paramno;
1623 
1624  params = (ParamListInfo) palloc(offsetof(ParamListInfoData, params) +
1625  numParams * sizeof(ParamExternData));
1626  /* we have static list of params, so no hooks needed */
1627  params->paramFetch = NULL;
1628  params->paramFetchArg = NULL;
1629  params->parserSetup = NULL;
1630  params->parserSetupArg = NULL;
1631  params->numParams = numParams;
1632 
1633  for (paramno = 0; paramno < numParams; paramno++)
1634  {
1635  Oid ptype = psrc->param_types[paramno];
1636  int32 plength;
1637  Datum pval;
1638  bool isNull;
1639  StringInfoData pbuf;
1640  char csave;
1641  int16 pformat;
1642 
1643  plength = pq_getmsgint(input_message, 4);
1644  isNull = (plength == -1);
1645 
1646  if (!isNull)
1647  {
1648  const char *pvalue = pq_getmsgbytes(input_message, plength);
1649 
1650  /*
1651  * Rather than copying data around, we just set up a phony
1652  * StringInfo pointing to the correct portion of the message
1653  * buffer. We assume we can scribble on the message buffer so
1654  * as to maintain the convention that StringInfos have a
1655  * trailing null. This is grotty but is a big win when
1656  * dealing with very large parameter strings.
1657  */
1658  pbuf.data = (char *) pvalue;
1659  pbuf.maxlen = plength + 1;
1660  pbuf.len = plength;
1661  pbuf.cursor = 0;
1662 
1663  csave = pbuf.data[plength];
1664  pbuf.data[plength] = '\0';
1665  }
1666  else
1667  {
1668  pbuf.data = NULL; /* keep compiler quiet */
1669  csave = 0;
1670  }
1671 
1672  if (numPFormats > 1)
1673  pformat = pformats[paramno];
1674  else if (numPFormats > 0)
1675  pformat = pformats[0];
1676  else
1677  pformat = 0; /* default = text */
1678 
1679  if (pformat == 0) /* text mode */
1680  {
1681  Oid typinput;
1682  Oid typioparam;
1683  char *pstring;
1684 
1685  getTypeInputInfo(ptype, &typinput, &typioparam);
1686 
1687  /*
1688  * We have to do encoding conversion before calling the
1689  * typinput routine.
1690  */
1691  if (isNull)
1692  pstring = NULL;
1693  else
1694  pstring = pg_client_to_server(pbuf.data, plength);
1695 
1696  pval = OidInputFunctionCall(typinput, pstring, typioparam, -1);
1697 
1698  /* Free result of encoding conversion, if any */
1699  if (pstring && pstring != pbuf.data)
1700  pfree(pstring);
1701  }
1702  else if (pformat == 1) /* binary mode */
1703  {
1704  Oid typreceive;
1705  Oid typioparam;
1706  StringInfo bufptr;
1707 
1708  /*
1709  * Call the parameter type's binary input converter
1710  */
1711  getTypeBinaryInputInfo(ptype, &typreceive, &typioparam);
1712 
1713  if (isNull)
1714  bufptr = NULL;
1715  else
1716  bufptr = &pbuf;
1717 
1718  pval = OidReceiveFunctionCall(typreceive, bufptr, typioparam, -1);
1719 
1720  /* Trouble if it didn't eat the whole buffer */
1721  if (!isNull && pbuf.cursor != pbuf.len)
1722  ereport(ERROR,
1723  (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
1724  errmsg("incorrect binary data format in bind parameter %d",
1725  paramno + 1)));
1726  }
1727  else
1728  {
1729  ereport(ERROR,
1730  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1731  errmsg("unsupported format code: %d",
1732  pformat)));
1733  pval = 0; /* keep compiler quiet */
1734  }
1735 
1736  /* Restore message buffer contents */
1737  if (!isNull)
1738  pbuf.data[plength] = csave;
1739 
1740  params->params[paramno].value = pval;
1741  params->params[paramno].isnull = isNull;
1742 
1743  /*
1744  * We mark the params as CONST. This ensures that any custom plan
1745  * makes full use of the parameter values.
1746  */
1747  params->params[paramno].pflags = PARAM_FLAG_CONST;
1748  params->params[paramno].ptype = ptype;
1749  }
1750  }
1751  else
1752  params = NULL;
1753 
1754  /* Done storing stuff in portal's context */
1755  MemoryContextSwitchTo(oldContext);
1756 
1757  /* Get the result format codes */
1758  numRFormats = pq_getmsgint(input_message, 2);
1759  if (numRFormats > 0)
1760  {
1761  int i;
1762 
1763  rformats = (int16 *) palloc(numRFormats * sizeof(int16));
1764  for (i = 0; i < numRFormats; i++)
1765  rformats[i] = pq_getmsgint(input_message, 2);
1766  }
1767 
1768  pq_getmsgend(input_message);
1769 
1770  /*
1771  * Obtain a plan from the CachedPlanSource. Any cruft from (re)planning
1772  * will be generated in MessageContext. The plan refcount will be
1773  * assigned to the Portal, so it will be released at portal destruction.
1774  */
1775  cplan = GetCachedPlan(psrc, params, false);
1776 
1777  /*
1778  * Now we can define the portal.
1779  *
1780  * DO NOT put any code that could possibly throw an error between the
1781  * above GetCachedPlan call and here.
1782  */
1783  PortalDefineQuery(portal,
1784  saved_stmt_name,
1785  query_string,
1786  psrc->commandTag,
1787  cplan->stmt_list,
1788  cplan);
1789 
1790  /* Done with the snapshot used for parameter I/O and parsing/planning */
1791  if (snapshot_set)
1793 
1794  /*
1795  * And we're ready to start portal execution.
1796  */
1797  PortalStart(portal, params, 0, InvalidSnapshot);
1798 
1799  /*
1800  * Apply the result format requests to the portal.
1801  */
1802  PortalSetResultFormat(portal, numRFormats, rformats);
1803 
1804  /*
1805  * Send BindComplete.
1806  */
1808  pq_putemptymessage('2');
1809 
1810  /*
1811  * Emit duration logging if appropriate.
1812  */
1813  switch (check_log_duration(msec_str, false))
1814  {
1815  case 1:
1816  ereport(LOG,
1817  (errmsg("duration: %s ms", msec_str),
1818  errhidestmt(true)));
1819  break;
1820  case 2:
1821  ereport(LOG,
1822  (errmsg("duration: %s ms bind %s%s%s: %s",
1823  msec_str,
1824  *stmt_name ? stmt_name : "<unnamed>",
1825  *portal_name ? "/" : "",
1826  *portal_name ? portal_name : "",
1827  psrc->query_string),
1828  errhidestmt(true),
1829  errdetail_params(params)));
1830  break;
1831  }
1832 
1833  if (save_log_statement_stats)
1834  ShowUsage("BIND MESSAGE STATISTICS");
1835 
1837 }
1838 
1839 /*
1840  * exec_execute_message
1841  *
1842  * Process an "Execute" message for a portal
1843  */
1844 static void
1845 exec_execute_message(const char *portal_name, long max_rows)
1846 {
1847  CommandDest dest;
1848  DestReceiver *receiver;
1849  Portal portal;
1850  bool completed;
1851  char completionTag[COMPLETION_TAG_BUFSIZE];
1852  const char *sourceText;
1853  const char *prepStmtName;
1854  ParamListInfo portalParams;
1855  bool save_log_statement_stats = log_statement_stats;
1856  bool is_xact_command;
1857  bool execute_is_fetch;
1858  bool was_logged = false;
1859  char msec_str[32];
1860 
1861  /* Adjust destination to tell printtup.c what to do */
1862  dest = whereToSendOutput;
1863  if (dest == DestRemote)
1864  dest = DestRemoteExecute;
1865 
1866  portal = GetPortalByName(portal_name);
1867  if (!PortalIsValid(portal))
1868  ereport(ERROR,
1869  (errcode(ERRCODE_UNDEFINED_CURSOR),
1870  errmsg("portal \"%s\" does not exist", portal_name)));
1871 
1872  /*
1873  * If the original query was a null string, just return
1874  * EmptyQueryResponse.
1875  */
1876  if (portal->commandTag == NULL)
1877  {
1878  Assert(portal->stmts == NIL);
1879  NullCommand(dest);
1880  return;
1881  }
1882 
1883  /* Does the portal contain a transaction command? */
1884  is_xact_command = IsTransactionStmtList(portal->stmts);
1885 
1886  /*
1887  * We must copy the sourceText and prepStmtName into MessageContext in
1888  * case the portal is destroyed during finish_xact_command. Can avoid the
1889  * copy if it's not an xact command, though.
1890  */
1891  if (is_xact_command)
1892  {
1893  sourceText = pstrdup(portal->sourceText);
1894  if (portal->prepStmtName)
1895  prepStmtName = pstrdup(portal->prepStmtName);
1896  else
1897  prepStmtName = "<unnamed>";
1898 
1899  /*
1900  * An xact command shouldn't have any parameters, which is a good
1901  * thing because they wouldn't be around after finish_xact_command.
1902  */
1903  portalParams = NULL;
1904  }
1905  else
1906  {
1907  sourceText = portal->sourceText;
1908  if (portal->prepStmtName)
1909  prepStmtName = portal->prepStmtName;
1910  else
1911  prepStmtName = "<unnamed>";
1912  portalParams = portal->portalParams;
1913  }
1914 
1915  /*
1916  * Report query to various monitoring facilities.
1917  */
1918  debug_query_string = sourceText;
1919 
1921 
1922  set_ps_display(portal->commandTag, false);
1923 
1924  if (save_log_statement_stats)
1925  ResetUsage();
1926 
1927  BeginCommand(portal->commandTag, dest);
1928 
1929  /*
1930  * Create dest receiver in MessageContext (we don't want it in transaction
1931  * context, because that may get deleted if portal contains VACUUM).
1932  */
1933  receiver = CreateDestReceiver(dest);
1934  if (dest == DestRemoteExecute)
1935  SetRemoteDestReceiverParams(receiver, portal);
1936 
1937  /*
1938  * Ensure we are in a transaction command (this should normally be the
1939  * case already due to prior BIND).
1940  */
1942 
1943  /*
1944  * If we re-issue an Execute protocol request against an existing portal,
1945  * then we are only fetching more rows rather than completely re-executing
1946  * the query from the start. atStart is never reset for a v3 portal, so we
1947  * are safe to use this check.
1948  */
1949  execute_is_fetch = !portal->atStart;
1950 
1951  /* Log immediately if dictated by log_statement */
1952  if (check_log_statement(portal->stmts))
1953  {
1954  ereport(LOG,
1955  (errmsg("%s %s%s%s: %s",
1956  execute_is_fetch ?
1957  _("execute fetch from") :
1958  _("execute"),
1959  prepStmtName,
1960  *portal_name ? "/" : "",
1961  *portal_name ? portal_name : "",
1962  sourceText),
1963  errhidestmt(true),
1964  errdetail_params(portalParams)));
1965  was_logged = true;
1966  }
1967 
1968  /*
1969  * If we are in aborted transaction state, the only portals we can
1970  * actually run are those containing COMMIT or ROLLBACK commands.
1971  */
1973  !IsTransactionExitStmtList(portal->stmts))
1974  ereport(ERROR,
1975  (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1976  errmsg("current transaction is aborted, "
1977  "commands ignored until end of transaction block"),
1978  errdetail_abort()));
1979 
1980  /* Check for cancel signal before we start execution */
1982 
1983  /*
1984  * Okay to run the portal.
1985  */
1986  if (max_rows <= 0)
1987  max_rows = FETCH_ALL;
1988 
1989  completed = PortalRun(portal,
1990  max_rows,
1991  true, /* always top level */
1992  receiver,
1993  receiver,
1994  completionTag);
1995 
1996  (*receiver->rDestroy) (receiver);
1997 
1998  if (completed)
1999  {
2000  if (is_xact_command)
2001  {
2002  /*
2003  * If this was a transaction control statement, commit it. We
2004  * will start a new xact command for the next command (if any).
2005  */
2007  }
2008  else
2009  {
2010  /*
2011  * We need a CommandCounterIncrement after every query, except
2012  * those that start or end a transaction block.
2013  */
2015  }
2016 
2017  /* Send appropriate CommandComplete to client */
2018  EndCommand(completionTag, dest);
2019  }
2020  else
2021  {
2022  /* Portal run not complete, so send PortalSuspended */
2024  pq_putemptymessage('s');
2025  }
2026 
2027  /*
2028  * Emit duration logging if appropriate.
2029  */
2030  switch (check_log_duration(msec_str, was_logged))
2031  {
2032  case 1:
2033  ereport(LOG,
2034  (errmsg("duration: %s ms", msec_str),
2035  errhidestmt(true)));
2036  break;
2037  case 2:
2038  ereport(LOG,
2039  (errmsg("duration: %s ms %s %s%s%s: %s",
2040  msec_str,
2041  execute_is_fetch ?
2042  _("execute fetch from") :
2043  _("execute"),
2044  prepStmtName,
2045  *portal_name ? "/" : "",
2046  *portal_name ? portal_name : "",
2047  sourceText),
2048  errhidestmt(true),
2049  errdetail_params(portalParams)));
2050  break;
2051  }
2052 
2053  if (save_log_statement_stats)
2054  ShowUsage("EXECUTE MESSAGE STATISTICS");
2055 
2057 }
2058 
2059 /*
2060  * check_log_statement
2061  * Determine whether command should be logged because of log_statement
2062  *
2063  * stmt_list can be either raw grammar output or a list of planned
2064  * statements
2065  */
2066 static bool
2068 {
2069  ListCell *stmt_item;
2070 
2071  if (log_statement == LOGSTMT_NONE)
2072  return false;
2073  if (log_statement == LOGSTMT_ALL)
2074  return true;
2075 
2076  /* Else we have to inspect the statement(s) to see whether to log */
2077  foreach(stmt_item, stmt_list)
2078  {
2079  Node *stmt = (Node *) lfirst(stmt_item);
2080 
2081  if (GetCommandLogLevel(stmt) <= log_statement)
2082  return true;
2083  }
2084 
2085  return false;
2086 }
2087 
2088 /*
2089  * check_log_duration
2090  * Determine whether current command's duration should be logged
2091  *
2092  * Returns:
2093  * 0 if no logging is needed
2094  * 1 if just the duration should be logged
2095  * 2 if duration and query details should be logged
2096  *
2097  * If logging is needed, the duration in msec is formatted into msec_str[],
2098  * which must be a 32-byte buffer.
2099  *
2100  * was_logged should be TRUE if caller already logged query details (this
2101  * essentially prevents 2 from being returned).
2102  */
2103 int
2104 check_log_duration(char *msec_str, bool was_logged)
2105 {
2107  {
2108  long secs;
2109  int usecs;
2110  int msecs;
2111  bool exceeded;
2112 
2115  &secs, &usecs);
2116  msecs = usecs / 1000;
2117 
2118  /*
2119  * This odd-looking test for log_min_duration_statement being exceeded
2120  * is designed to avoid integer overflow with very long durations:
2121  * don't compute secs * 1000 until we've verified it will fit in int.
2122  */
2123  exceeded = (log_min_duration_statement == 0 ||
2125  (secs > log_min_duration_statement / 1000 ||
2126  secs * 1000 + msecs >= log_min_duration_statement)));
2127 
2128  if (exceeded || log_duration)
2129  {
2130  snprintf(msec_str, 32, "%ld.%03d",
2131  secs * 1000 + msecs, usecs % 1000);
2132  if (exceeded && !was_logged)
2133  return 2;
2134  else
2135  return 1;
2136  }
2137  }
2138 
2139  return 0;
2140 }
2141 
2142 /*
2143  * errdetail_execute
2144  *
2145  * Add an errdetail() line showing the query referenced by an EXECUTE, if any.
2146  * The argument is the raw parsetree list.
2147  */
2148 static int
2149 errdetail_execute(List *raw_parsetree_list)
2150 {
2151  ListCell *parsetree_item;
2152 
2153  foreach(parsetree_item, raw_parsetree_list)
2154  {
2155  Node *parsetree = (Node *) lfirst(parsetree_item);
2156 
2157  if (IsA(parsetree, ExecuteStmt))
2158  {
2159  ExecuteStmt *stmt = (ExecuteStmt *) parsetree;
2160  PreparedStatement *pstmt;
2161 
2162  pstmt = FetchPreparedStatement(stmt->name, false);
2163  if (pstmt)
2164  {
2165  errdetail("prepare: %s", pstmt->plansource->query_string);
2166  return 0;
2167  }
2168  }
2169  }
2170 
2171  return 0;
2172 }
2173 
2174 /*
2175  * errdetail_params
2176  *
2177  * Add an errdetail() line showing bind-parameter data, if available.
2178  */
2179 static int
2181 {
2182  /* We mustn't call user-defined I/O functions when in an aborted xact */
2183  if (params && params->numParams > 0 && !IsAbortedTransactionBlockState())
2184  {
2185  StringInfoData param_str;
2186  MemoryContext oldcontext;
2187  int paramno;
2188 
2189  /* Make sure any trash is generated in MessageContext */
2190  oldcontext = MemoryContextSwitchTo(MessageContext);
2191 
2192  initStringInfo(&param_str);
2193 
2194  for (paramno = 0; paramno < params->numParams; paramno++)
2195  {
2196  ParamExternData *prm = &params->params[paramno];
2197  Oid typoutput;
2198  bool typisvarlena;
2199  char *pstring;
2200  char *p;
2201 
2202  appendStringInfo(&param_str, "%s$%d = ",
2203  paramno > 0 ? ", " : "",
2204  paramno + 1);
2205 
2206  if (prm->isnull || !OidIsValid(prm->ptype))
2207  {
2208  appendStringInfoString(&param_str, "NULL");
2209  continue;
2210  }
2211 
2212  getTypeOutputInfo(prm->ptype, &typoutput, &typisvarlena);
2213 
2214  pstring = OidOutputFunctionCall(typoutput, prm->value);
2215 
2216  appendStringInfoCharMacro(&param_str, '\'');
2217  for (p = pstring; *p; p++)
2218  {
2219  if (*p == '\'') /* double single quotes */
2220  appendStringInfoCharMacro(&param_str, *p);
2221  appendStringInfoCharMacro(&param_str, *p);
2222  }
2223  appendStringInfoCharMacro(&param_str, '\'');
2224 
2225  pfree(pstring);
2226  }
2227 
2228  errdetail("parameters: %s", param_str.data);
2229 
2230  pfree(param_str.data);
2231 
2232  MemoryContextSwitchTo(oldcontext);
2233  }
2234 
2235  return 0;
2236 }
2237 
2238 /*
2239  * errdetail_abort
2240  *
2241  * Add an errdetail() line showing abort reason, if any.
2242  */
2243 static int
2245 {
2247  errdetail("abort reason: recovery conflict");
2248 
2249  return 0;
2250 }
2251 
2252 /*
2253  * errdetail_recovery_conflict
2254  *
2255  * Add an errdetail() line showing conflict source.
2256  */
2257 static int
2259 {
2260  switch (RecoveryConflictReason)
2261  {
2263  errdetail("User was holding shared buffer pin for too long.");
2264  break;
2266  errdetail("User was holding a relation lock for too long.");
2267  break;
2269  errdetail("User was or might have been using tablespace that must be dropped.");
2270  break;
2272  errdetail("User query might have needed to see row versions that must be removed.");
2273  break;
2275  errdetail("User transaction caused buffer deadlock with recovery.");
2276  break;
2278  errdetail("User was connected to a database that must be dropped.");
2279  break;
2280  default:
2281  break;
2282  /* no errdetail */
2283  }
2284 
2285  return 0;
2286 }
2287 
2288 /*
2289  * exec_describe_statement_message
2290  *
2291  * Process a "Describe" message for a prepared statement
2292  */
2293 static void
2294 exec_describe_statement_message(const char *stmt_name)
2295 {
2296  CachedPlanSource *psrc;
2298  int i;
2299 
2300  /*
2301  * Start up a transaction command. (Note that this will normally change
2302  * current memory context.) Nothing happens if we are already in one.
2303  */
2305 
2306  /* Switch back to message context */
2308 
2309  /* Find prepared statement */
2310  if (stmt_name[0] != '\0')
2311  {
2312  PreparedStatement *pstmt;
2313 
2314  pstmt = FetchPreparedStatement(stmt_name, true);
2315  psrc = pstmt->plansource;
2316  }
2317  else
2318  {
2319  /* special-case the unnamed statement */
2320  psrc = unnamed_stmt_psrc;
2321  if (!psrc)
2322  ereport(ERROR,
2323  (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
2324  errmsg("unnamed prepared statement does not exist")));
2325  }
2326 
2327  /* Prepared statements shouldn't have changeable result descs */
2328  Assert(psrc->fixed_result);
2329 
2330  /*
2331  * If we are in aborted transaction state, we can't run
2332  * SendRowDescriptionMessage(), because that needs catalog accesses.
2333  * Hence, refuse to Describe statements that return data. (We shouldn't
2334  * just refuse all Describes, since that might break the ability of some
2335  * clients to issue COMMIT or ROLLBACK commands, if they use code that
2336  * blindly Describes whatever it does.) We can Describe parameters
2337  * without doing anything dangerous, so we don't restrict that.
2338  */
2340  psrc->resultDesc)
2341  ereport(ERROR,
2342  (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2343  errmsg("current transaction is aborted, "
2344  "commands ignored until end of transaction block"),
2345  errdetail_abort()));
2346 
2348  return; /* can't actually do anything... */
2349 
2350  /*
2351  * First describe the parameters...
2352  */
2353  pq_beginmessage(&buf, 't'); /* parameter description message type */
2354  pq_sendint(&buf, psrc->num_params, 2);
2355 
2356  for (i = 0; i < psrc->num_params; i++)
2357  {
2358  Oid ptype = psrc->param_types[i];
2359 
2360  pq_sendint(&buf, (int) ptype, 4);
2361  }
2362  pq_endmessage(&buf);
2363 
2364  /*
2365  * Next send RowDescription or NoData to describe the result...
2366  */
2367  if (psrc->resultDesc)
2368  {
2369  List *tlist;
2370 
2371  /* Get the plan's primary targetlist */
2372  tlist = CachedPlanGetTargetList(psrc);
2373 
2374  SendRowDescriptionMessage(psrc->resultDesc, tlist, NULL);
2375  }
2376  else
2377  pq_putemptymessage('n'); /* NoData */
2378 
2379 }
2380 
2381 /*
2382  * exec_describe_portal_message
2383  *
2384  * Process a "Describe" message for a portal
2385  */
2386 static void
2387 exec_describe_portal_message(const char *portal_name)
2388 {
2389  Portal portal;
2390 
2391  /*
2392  * Start up a transaction command. (Note that this will normally change
2393  * current memory context.) Nothing happens if we are already in one.
2394  */
2396 
2397  /* Switch back to message context */
2399 
2400  portal = GetPortalByName(portal_name);
2401  if (!PortalIsValid(portal))
2402  ereport(ERROR,
2403  (errcode(ERRCODE_UNDEFINED_CURSOR),
2404  errmsg("portal \"%s\" does not exist", portal_name)));
2405 
2406  /*
2407  * If we are in aborted transaction state, we can't run
2408  * SendRowDescriptionMessage(), because that needs catalog accesses.
2409  * Hence, refuse to Describe portals that return data. (We shouldn't just
2410  * refuse all Describes, since that might break the ability of some
2411  * clients to issue COMMIT or ROLLBACK commands, if they use code that
2412  * blindly Describes whatever it does.)
2413  */
2415  portal->tupDesc)
2416  ereport(ERROR,
2417  (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2418  errmsg("current transaction is aborted, "
2419  "commands ignored until end of transaction block"),
2420  errdetail_abort()));
2421 
2423  return; /* can't actually do anything... */
2424 
2425  if (portal->tupDesc)
2427  FetchPortalTargetList(portal),
2428  portal->formats);
2429  else
2430  pq_putemptymessage('n'); /* NoData */
2431 }
2432 
2433 
2434 /*
2435  * Convenience routines for starting/committing a single command.
2436  */
2437 static void
2439 {
2440  if (!xact_started)
2441  {
2442  ereport(DEBUG3,
2443  (errmsg_internal("StartTransactionCommand")));
2445 
2446  /* Set statement timeout running, if any */
2447  /* NB: this mustn't be enabled until we are within an xact */
2448  if (StatementTimeout > 0)
2450  else
2452 
2453  xact_started = true;
2454  }
2455 }
2456 
2457 static void
2459 {
2460  if (xact_started)
2461  {
2462  /* Cancel any active statement timeout before committing */
2464 
2465  /* Now commit the command */
2466  ereport(DEBUG3,
2467  (errmsg_internal("CommitTransactionCommand")));
2468 
2470 
2471 #ifdef MEMORY_CONTEXT_CHECKING
2472  /* Check all memory contexts that weren't freed during commit */
2473  /* (those that were, were checked before being deleted) */
2474  MemoryContextCheck(TopMemoryContext);
2475 #endif
2476 
2477 #ifdef SHOW_MEMORY_STATS
2478  /* Print mem stats after each commit for leak tracking */
2480 #endif
2481 
2482  xact_started = false;
2483  }
2484 }
2485 
2486 
2487 /*
2488  * Convenience routines for checking whether a statement is one of the
2489  * ones that we allow in transaction-aborted state.
2490  */
2491 
2492 /* Test a bare parsetree */
2493 static bool
2495 {
2496  if (parsetree && IsA(parsetree, TransactionStmt))
2497  {
2498  TransactionStmt *stmt = (TransactionStmt *) parsetree;
2499 
2500  if (stmt->kind == TRANS_STMT_COMMIT ||
2501  stmt->kind == TRANS_STMT_PREPARE ||
2502  stmt->kind == TRANS_STMT_ROLLBACK ||
2503  stmt->kind == TRANS_STMT_ROLLBACK_TO)
2504  return true;
2505  }
2506  return false;
2507 }
2508 
2509 /* Test a list that might contain Query nodes or bare parsetrees */
2510 static bool
2512 {
2513  if (list_length(parseTrees) == 1)
2514  {
2515  Node *stmt = (Node *) linitial(parseTrees);
2516 
2517  if (IsA(stmt, Query))
2518  {
2519  Query *query = (Query *) stmt;
2520 
2521  if (query->commandType == CMD_UTILITY &&
2523  return true;
2524  }
2525  else if (IsTransactionExitStmt(stmt))
2526  return true;
2527  }
2528  return false;
2529 }
2530 
2531 /* Test a list that might contain Query nodes or bare parsetrees */
2532 static bool
2534 {
2535  if (list_length(parseTrees) == 1)
2536  {
2537  Node *stmt = (Node *) linitial(parseTrees);
2538 
2539  if (IsA(stmt, Query))
2540  {
2541  Query *query = (Query *) stmt;
2542 
2543  if (query->commandType == CMD_UTILITY &&
2544  IsA(query->utilityStmt, TransactionStmt))
2545  return true;
2546  }
2547  else if (IsA(stmt, TransactionStmt))
2548  return true;
2549  }
2550  return false;
2551 }
2552 
2553 /* Release any existing unnamed prepared statement */
2554 static void
2556 {
2557  /* paranoia to avoid a dangling pointer in case of error */
2558  if (unnamed_stmt_psrc)
2559  {
2561 
2562  unnamed_stmt_psrc = NULL;
2563  DropCachedPlan(psrc);
2564  }
2565 }
2566 
2567 
2568 /* --------------------------------
2569  * signal handler routines used in PostgresMain()
2570  * --------------------------------
2571  */
2572 
2573 /*
2574  * quickdie() occurs when signalled SIGQUIT by the postmaster.
2575  *
2576  * Some backend has bought the farm,
2577  * so we need to stop what we're doing and exit.
2578  */
2579 void
2581 {
2582  sigaddset(&BlockSig, SIGQUIT); /* prevent nested calls */
2583  PG_SETMASK(&BlockSig);
2584 
2585  /*
2586  * Prevent interrupts while exiting; though we just blocked signals that
2587  * would queue new interrupts, one may have been pending. We don't want a
2588  * quickdie() downgraded to a mere query cancel.
2589  */
2590  HOLD_INTERRUPTS();
2591 
2592  /*
2593  * If we're aborting out of client auth, don't risk trying to send
2594  * anything to the client; we will likely violate the protocol, not to
2595  * mention that we may have interrupted the guts of OpenSSL or some
2596  * authentication library.
2597  */
2600 
2601  /*
2602  * Ideally this should be ereport(FATAL), but then we'd not get control
2603  * back...
2604  */
2605  ereport(WARNING,
2606  (errcode(ERRCODE_CRASH_SHUTDOWN),
2607  errmsg("terminating connection because of crash of another server process"),
2608  errdetail("The postmaster has commanded this server process to roll back"
2609  " the current transaction and exit, because another"
2610  " server process exited abnormally and possibly corrupted"
2611  " shared memory."),
2612  errhint("In a moment you should be able to reconnect to the"
2613  " database and repeat your command.")));
2614 
2615  /*
2616  * We DO NOT want to run proc_exit() callbacks -- we're here because
2617  * shared memory may be corrupted, so we don't want to try to clean up our
2618  * transaction. Just nail the windows shut and get out of town. Now that
2619  * there's an atexit callback to prevent third-party code from breaking
2620  * things by calling exit() directly, we have to reset the callbacks
2621  * explicitly to make this work as intended.
2622  */
2623  on_exit_reset();
2624 
2625  /*
2626  * Note we do exit(2) not exit(0). This is to force the postmaster into a
2627  * system reset cycle if some idiot DBA sends a manual SIGQUIT to a random
2628  * backend. This is necessary precisely because we don't clean up our
2629  * shared memory state. (The "dead man switch" mechanism in pmsignal.c
2630  * should ensure the postmaster sees this as a crash, too, but no harm in
2631  * being doubly sure.)
2632  */
2633  exit(2);
2634 }
2635 
2636 /*
2637  * Shutdown signal from postmaster: abort transaction and exit
2638  * at soonest convenient time
2639  */
2640 void
2642 {
2643  int save_errno = errno;
2644 
2645  /* Don't joggle the elbow of proc_exit */
2646  if (!proc_exit_inprogress)
2647  {
2648  InterruptPending = true;
2649  ProcDiePending = true;
2650  }
2651 
2652  /* If we're still here, waken anything waiting on the process latch */
2653  SetLatch(MyLatch);
2654 
2655  /*
2656  * If we're in single user mode, we want to quit immediately - we can't
2657  * rely on latches as they wouldn't work when stdin/stdout is a file.
2658  * Rather ugly, but it's unlikely to be worthwhile to invest much more
2659  * effort just for the benefit of single user mode.
2660  */
2663 
2664  errno = save_errno;
2665 }
2666 
2667 /*
2668  * Query-cancel signal from postmaster: abort current transaction
2669  * at soonest convenient time
2670  */
2671 void
2673 {
2674  int save_errno = errno;
2675 
2676  /*
2677  * Don't joggle the elbow of proc_exit
2678  */
2679  if (!proc_exit_inprogress)
2680  {
2681  InterruptPending = true;
2682  QueryCancelPending = true;
2683  }
2684 
2685  /* If we're still here, waken anything waiting on the process latch */
2686  SetLatch(MyLatch);
2687 
2688  errno = save_errno;
2689 }
2690 
2691 /* signal handler for floating point exception */
2692 void
2694 {
2695  /* We're not returning, so no need to save errno */
2696  ereport(ERROR,
2697  (errcode(ERRCODE_FLOATING_POINT_EXCEPTION),
2698  errmsg("floating-point exception"),
2699  errdetail("An invalid floating-point operation was signaled. "
2700  "This probably means an out-of-range result or an "
2701  "invalid operation, such as division by zero.")));
2702 }
2703 
2704 /* SIGHUP: set flag to re-read config file at next convenient time */
2705 static void
2707 {
2708  int save_errno = errno;
2709 
2710  got_SIGHUP = true;
2711  SetLatch(MyLatch);
2712 
2713  errno = save_errno;
2714 }
2715 
2716 /*
2717  * RecoveryConflictInterrupt: out-of-line portion of recovery conflict
2718  * handling following receipt of SIGUSR1. Designed to be similar to die()
2719  * and StatementCancelHandler(). Called only by a normal user backend
2720  * that begins a transaction during recovery.
2721  */
2722 void
2724 {
2725  int save_errno = errno;
2726 
2727  /*
2728  * Don't joggle the elbow of proc_exit
2729  */
2730  if (!proc_exit_inprogress)
2731  {
2732  RecoveryConflictReason = reason;
2733  switch (reason)
2734  {
2736 
2737  /*
2738  * If we aren't waiting for a lock we can never deadlock.
2739  */
2740  if (!IsWaitingForLock())
2741  return;
2742 
2743  /* Intentional drop through to check wait for pin */
2744 
2746 
2747  /*
2748  * If we aren't blocking the Startup process there is nothing
2749  * more to do.
2750  */
2752  return;
2753 
2755 
2756  /* Intentional drop through to error handling */
2757 
2761 
2762  /*
2763  * If we aren't in a transaction any longer then ignore.
2764  */
2766  return;
2767 
2768  /*
2769  * If we can abort just the current subtransaction then we are
2770  * OK to throw an ERROR to resolve the conflict. Otherwise
2771  * drop through to the FATAL case.
2772  *
2773  * XXX other times that we can throw just an ERROR *may* be
2774  * PROCSIG_RECOVERY_CONFLICT_LOCK if no locks are held in
2775  * parent transactions
2776  *
2777  * PROCSIG_RECOVERY_CONFLICT_SNAPSHOT if no snapshots are held
2778  * by parent transactions and the transaction is not
2779  * transaction-snapshot mode
2780  *
2781  * PROCSIG_RECOVERY_CONFLICT_TABLESPACE if no temp files or
2782  * cursors open in parent transactions
2783  */
2784  if (!IsSubTransaction())
2785  {
2786  /*
2787  * If we already aborted then we no longer need to cancel.
2788  * We do this here since we do not wish to ignore aborted
2789  * subtransactions, which must cause FATAL, currently.
2790  */
2792  return;
2793 
2794  RecoveryConflictPending = true;
2795  QueryCancelPending = true;
2796  InterruptPending = true;
2797  break;
2798  }
2799 
2800  /* Intentional drop through to session cancel */
2801 
2803  RecoveryConflictPending = true;
2804  ProcDiePending = true;
2805  InterruptPending = true;
2806  break;
2807 
2808  default:
2809  elog(FATAL, "unrecognized conflict mode: %d",
2810  (int) reason);
2811  }
2812 
2814 
2815  /*
2816  * All conflicts apart from database cause dynamic errors where the
2817  * command or transaction can be retried at a later point with some
2818  * potential for success. No need to reset this, since non-retryable
2819  * conflict errors are currently FATAL.
2820  */
2821  if (reason == PROCSIG_RECOVERY_CONFLICT_DATABASE)
2822  RecoveryConflictRetryable = false;
2823  }
2824 
2825  /*
2826  * Set the process latch. This function essentially emulates signal
2827  * handlers like die() and StatementCancelHandler() and it seems prudent
2828  * to behave similarly as they do. Alternatively all plain backend code
2829  * waiting on that latch, expecting to get interrupted by query cancels et
2830  * al., would also need to set set_latch_on_sigusr1.
2831  */
2832  SetLatch(MyLatch);
2833 
2834  errno = save_errno;
2835 }
2836 
2837 /*
2838  * ProcessInterrupts: out-of-line portion of CHECK_FOR_INTERRUPTS() macro
2839  *
2840  * If an interrupt condition is pending, and it's safe to service it,
2841  * then clear the flag and accept the interrupt. Called only when
2842  * InterruptPending is true.
2843  */
2844 void
2846 {
2847  /* OK to accept any interrupts now? */
2848  if (InterruptHoldoffCount != 0 || CritSectionCount != 0)
2849  return;
2850  InterruptPending = false;
2851 
2852  if (ProcDiePending)
2853  {
2854  ProcDiePending = false;
2855  QueryCancelPending = false; /* ProcDie trumps QueryCancel */
2856  LockErrorCleanup();
2857  /* As in quickdie, don't risk sending to client during auth */
2861  ereport(FATAL,
2862  (errcode(ERRCODE_QUERY_CANCELED),
2863  errmsg("canceling authentication due to timeout")));
2864  else if (IsAutoVacuumWorkerProcess())
2865  ereport(FATAL,
2866  (errcode(ERRCODE_ADMIN_SHUTDOWN),
2867  errmsg("terminating autovacuum process due to administrator command")));
2869  {
2871  ereport(FATAL,
2872  (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
2873  errmsg("terminating connection due to conflict with recovery"),
2875  }
2876  else if (RecoveryConflictPending)
2877  {
2878  /* Currently there is only one non-retryable recovery conflict */
2881  ereport(FATAL,
2882  (errcode(ERRCODE_DATABASE_DROPPED),
2883  errmsg("terminating connection due to conflict with recovery"),
2885  }
2886  else
2887  ereport(FATAL,
2888  (errcode(ERRCODE_ADMIN_SHUTDOWN),
2889  errmsg("terminating connection due to administrator command")));
2890  }
2892  {
2893  QueryCancelPending = false; /* lost connection trumps QueryCancel */
2894  LockErrorCleanup();
2895  /* don't send to client, we already know the connection to be dead. */
2897  ereport(FATAL,
2898  (errcode(ERRCODE_CONNECTION_FAILURE),
2899  errmsg("connection to client lost")));
2900  }
2901 
2902  /*
2903  * If a recovery conflict happens while we are waiting for input from the
2904  * client, the client is presumably just sitting idle in a transaction,
2905  * preventing recovery from making progress. Terminate the connection to
2906  * dislodge it.
2907  */
2909  {
2910  QueryCancelPending = false; /* this trumps QueryCancel */
2911  RecoveryConflictPending = false;
2912  LockErrorCleanup();
2914  ereport(FATAL,
2915  (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
2916  errmsg("terminating connection due to conflict with recovery"),
2918  errhint("In a moment you should be able to reconnect to the"
2919  " database and repeat your command.")));
2920  }
2921 
2922  if (QueryCancelPending)
2923  {
2924  /*
2925  * Don't allow query cancel interrupts while reading input from the
2926  * client, because we might lose sync in the FE/BE protocol. (Die
2927  * interrupts are OK, because we won't read any further messages from
2928  * the client in that case.)
2929  */
2930  if (QueryCancelHoldoffCount != 0)
2931  {
2932  /*
2933  * Re-arm InterruptPending so that we process the cancel request
2934  * as soon as we're done reading the message.
2935  */
2936  InterruptPending = true;
2937  return;
2938  }
2939 
2940  QueryCancelPending = false;
2941 
2942  /*
2943  * If LOCK_TIMEOUT and STATEMENT_TIMEOUT indicators are both set, we
2944  * prefer to report the former; but be sure to clear both.
2945  */
2947  {
2949  LockErrorCleanup();
2950  ereport(ERROR,
2951  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
2952  errmsg("canceling statement due to lock timeout")));
2953  }
2955  {
2956  LockErrorCleanup();
2957  ereport(ERROR,
2958  (errcode(ERRCODE_QUERY_CANCELED),
2959  errmsg("canceling statement due to statement timeout")));
2960  }
2962  {
2963  LockErrorCleanup();
2964  ereport(ERROR,
2965  (errcode(ERRCODE_QUERY_CANCELED),
2966  errmsg("canceling autovacuum task")));
2967  }
2969  {
2970  RecoveryConflictPending = false;
2971  LockErrorCleanup();
2973  ereport(ERROR,
2974  (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
2975  errmsg("canceling statement due to conflict with recovery"),
2977  }
2978 
2979  /*
2980  * If we are reading a command from the client, just ignore the cancel
2981  * request --- sending an extra error message won't accomplish
2982  * anything. Otherwise, go ahead and throw the error.
2983  */
2984  if (!DoingCommandRead)
2985  {
2986  LockErrorCleanup();
2987  ereport(ERROR,
2988  (errcode(ERRCODE_QUERY_CANCELED),
2989  errmsg("canceling statement due to user request")));
2990  }
2991  }
2992 
2995 }
2996 
2997 
2998 /*
2999  * IA64-specific code to fetch the AR.BSP register for stack depth checks.
3000  *
3001  * We currently support gcc, icc, and HP-UX's native compiler here.
3002  *
3003  * Note: while icc accepts gcc asm blocks on x86[_64], this is not true on
3004  * ia64 (at least not in icc versions before 12.x). So we have to carry a
3005  * separate implementation for it.
3006  */
3007 #if defined(__ia64__) || defined(__ia64)
3008 
3009 #if defined(__hpux) && !defined(__GNUC__) && !defined(__INTEL_COMPILER)
3010 /* Assume it's HP-UX native compiler */
3011 #include <ia64/sys/inline.h>
3012 #define ia64_get_bsp() ((char *) (_Asm_mov_from_ar(_AREG_BSP, _NO_FENCE)))
3013 #elif defined(__INTEL_COMPILER)
3014 /* icc */
3015 #include <asm/ia64regs.h>
3016 #define ia64_get_bsp() ((char *) __getReg(_IA64_REG_AR_BSP))
3017 #else
3018 /* gcc */
3019 static __inline__ char *
3020 ia64_get_bsp(void)
3021 {
3022  char *ret;
3023 
3024  /* the ;; is a "stop", seems to be required before fetching BSP */
3025  __asm__ __volatile__(
3026  ";;\n"
3027  " mov %0=ar.bsp \n"
3028  : "=r"(ret));
3029 
3030  return ret;
3031 }
3032 #endif
3033 #endif /* IA64 */
3034 
3035 
3036 /*
3037  * set_stack_base: set up reference point for stack depth checking
3038  *
3039  * Returns the old reference point, if any.
3040  */
3043 {
3044  char stack_base;
3045  pg_stack_base_t old;
3046 
3047 #if defined(__ia64__) || defined(__ia64)
3048  old.stack_base_ptr = stack_base_ptr;
3049  old.register_stack_base_ptr = register_stack_base_ptr;
3050 #else
3051  old = stack_base_ptr;
3052 #endif
3053 
3054  /* Set up reference point for stack depth checking */
3055  stack_base_ptr = &stack_base;
3056 #if defined(__ia64__) || defined(__ia64)
3057  register_stack_base_ptr = ia64_get_bsp();
3058 #endif
3059 
3060  return old;
3061 }
3062 
3063 /*
3064  * restore_stack_base: restore reference point for stack depth checking
3065  *
3066  * This can be used after set_stack_base() to restore the old value. This
3067  * is currently only used in PL/Java. When PL/Java calls a backend function
3068  * from different thread, the thread's stack is at a different location than
3069  * the main thread's stack, so it sets the base pointer before the call, and
3070  * restores it afterwards.
3071  */
3072 void
3074 {
3075 #if defined(__ia64__) || defined(__ia64)
3076  stack_base_ptr = base.stack_base_ptr;
3077  register_stack_base_ptr = base.register_stack_base_ptr;
3078 #else
3079  stack_base_ptr = base;
3080 #endif
3081 }
3082 
3083 /*
3084  * check_stack_depth: check for excessively deep recursion
3085  *
3086  * This should be called someplace in any recursive routine that might possibly
3087  * recurse deep enough to overflow the stack. Most Unixen treat stack
3088  * overflow as an unrecoverable SIGSEGV, so we want to error out ourselves
3089  * before hitting the hardware limit.
3090  */
3091 void
3093 {
3094  char stack_top_loc;
3095  long stack_depth;
3096 
3097  /*
3098  * Compute distance from reference point to my local variables
3099  */
3100  stack_depth = (long) (stack_base_ptr - &stack_top_loc);
3101 
3102  /*
3103  * Take abs value, since stacks grow up on some machines, down on others
3104  */
3105  if (stack_depth < 0)
3106  stack_depth = -stack_depth;
3107 
3108  /*
3109  * Trouble?
3110  *
3111  * The test on stack_base_ptr prevents us from erroring out if called
3112  * during process setup or in a non-backend process. Logically it should
3113  * be done first, but putting it here avoids wasting cycles during normal
3114  * cases.
3115  */
3116  if (stack_depth > max_stack_depth_bytes &&
3117  stack_base_ptr != NULL)
3118  {
3119  ereport(ERROR,
3120  (errcode(ERRCODE_STATEMENT_TOO_COMPLEX),
3121  errmsg("stack depth limit exceeded"),
3122  errhint("Increase the configuration parameter \"max_stack_depth\" (currently %dkB), "
3123  "after ensuring the platform's stack depth limit is adequate.",
3124  max_stack_depth)));
3125  }
3126 
3127  /*
3128  * On IA64 there is a separate "register" stack that requires its own
3129  * independent check. For this, we have to measure the change in the
3130  * "BSP" pointer from PostgresMain to here. Logic is just as above,
3131  * except that we know IA64's register stack grows up.
3132  *
3133  * Note we assume that the same max_stack_depth applies to both stacks.
3134  */
3135 #if defined(__ia64__) || defined(__ia64)
3136  stack_depth = (long) (ia64_get_bsp() - register_stack_base_ptr);
3137 
3138  if (stack_depth > max_stack_depth_bytes &&
3139  register_stack_base_ptr != NULL)
3140  {
3141  ereport(ERROR,
3142  (errcode(ERRCODE_STATEMENT_TOO_COMPLEX),
3143  errmsg("stack depth limit exceeded"),
3144  errhint("Increase the configuration parameter \"max_stack_depth\" (currently %dkB), "
3145  "after ensuring the platform's stack depth limit is adequate.",
3146  max_stack_depth)));
3147  }
3148 #endif /* IA64 */
3149 }
3150 
3151 /* GUC check hook for max_stack_depth */
3152 bool
3153 check_max_stack_depth(int *newval, void **extra, GucSource source)
3154 {
3155  long newval_bytes = *newval * 1024L;
3156  long stack_rlimit = get_stack_depth_rlimit();
3157 
3158  if (stack_rlimit > 0 && newval_bytes > stack_rlimit - STACK_DEPTH_SLOP)
3159  {
3160  GUC_check_errdetail("\"max_stack_depth\" must not exceed %ldkB.",
3161  (stack_rlimit - STACK_DEPTH_SLOP) / 1024L);
3162  GUC_check_errhint("Increase the platform's stack depth limit via \"ulimit -s\" or local equivalent.");
3163  return false;
3164  }
3165  return true;
3166 }
3167 
3168 /* GUC assign hook for max_stack_depth */
3169 void
3171 {
3172  long newval_bytes = newval * 1024L;
3173 
3174  max_stack_depth_bytes = newval_bytes;
3175 }
3176 
3177 
3178 /*
3179  * set_debug_options --- apply "-d N" command line option
3180  *
3181  * -d is not quite the same as setting log_min_messages because it enables
3182  * other output options.
3183  */
3184 void
3185 set_debug_options(int debug_flag, GucContext context, GucSource source)
3186 {
3187  if (debug_flag > 0)
3188  {
3189  char debugstr[64];
3190 
3191  sprintf(debugstr, "debug%d", debug_flag);
3192  SetConfigOption("log_min_messages", debugstr, context, source);
3193  }
3194  else
3195  SetConfigOption("log_min_messages", "notice", context, source);
3196 
3197  if (debug_flag >= 1 && context == PGC_POSTMASTER)
3198  {
3199  SetConfigOption("log_connections", "true", context, source);
3200  SetConfigOption("log_disconnections", "true", context, source);
3201  }
3202  if (debug_flag >= 2)
3203  SetConfigOption("log_statement", "all", context, source);
3204  if (debug_flag >= 3)
3205  SetConfigOption("debug_print_parse", "true", context, source);
3206  if (debug_flag >= 4)
3207  SetConfigOption("debug_print_plan", "true", context, source);
3208  if (debug_flag >= 5)
3209  SetConfigOption("debug_print_rewritten", "true", context, source);
3210 }
3211 
3212 
3213 bool
3215 {
3216  const char *tmp = NULL;
3217 
3218  switch (arg[0])
3219  {
3220  case 's': /* seqscan */
3221  tmp = "enable_seqscan";
3222  break;
3223  case 'i': /* indexscan */
3224  tmp = "enable_indexscan";
3225  break;
3226  case 'o': /* indexonlyscan */
3227  tmp = "enable_indexonlyscan";
3228  break;
3229  case 'b': /* bitmapscan */
3230  tmp = "enable_bitmapscan";
3231  break;
3232  case 't': /* tidscan */
3233  tmp = "enable_tidscan";
3234  break;
3235  case 'n': /* nestloop */
3236  tmp = "enable_nestloop";
3237  break;
3238  case 'm': /* mergejoin */
3239  tmp = "enable_mergejoin";
3240  break;
3241  case 'h': /* hashjoin */
3242  tmp = "enable_hashjoin";
3243  break;
3244  }
3245  if (tmp)
3246  {
3247  SetConfigOption(tmp, "false", context, source);
3248  return true;
3249  }
3250  else
3251  return false;
3252 }
3253 
3254 
3255 const char *
3257 {
3258  switch (arg[0])
3259  {
3260  case 'p':
3261  if (optarg[1] == 'a') /* "parser" */
3262  return "log_parser_stats";
3263  else if (optarg[1] == 'l') /* "planner" */
3264  return "log_planner_stats";
3265  break;
3266 
3267  case 'e': /* "executor" */
3268  return "log_executor_stats";
3269  break;
3270  }
3271 
3272  return NULL;
3273 }
3274 
3275 
3276 /* ----------------------------------------------------------------
3277  * process_postgres_switches
3278  * Parse command line arguments for PostgresMain
3279  *
3280  * This is called twice, once for the "secure" options coming from the
3281  * postmaster or command line, and once for the "insecure" options coming
3282  * from the client's startup packet. The latter have the same syntax but
3283  * may be restricted in what they can do.
3284  *
3285  * argv[0] is ignored in either case (it's assumed to be the program name).
3286  *
3287  * ctx is PGC_POSTMASTER for secure options, PGC_BACKEND for insecure options
3288  * coming from the client, or PGC_SU_BACKEND for insecure options coming from
3289  * a superuser client.
3290  *
3291  * If a database name is present in the command line arguments, it's
3292  * returned into *dbname (this is allowed only if *dbname is initially NULL).
3293  * ----------------------------------------------------------------
3294  */
3295 void
3296 process_postgres_switches(int argc, char *argv[], GucContext ctx,
3297  const char **dbname)
3298 {
3299  bool secure = (ctx == PGC_POSTMASTER);
3300  int errs = 0;
3301  GucSource gucsource;
3302  int flag;
3303 
3304  if (secure)
3305  {
3306  gucsource = PGC_S_ARGV; /* switches came from command line */
3307 
3308  /* Ignore the initial --single argument, if present */
3309  if (argc > 1 && strcmp(argv[1], "--single") == 0)
3310  {
3311  argv++;
3312  argc--;
3313  }
3314  }
3315  else
3316  {
3317  gucsource = PGC_S_CLIENT; /* switches came from client */
3318  }
3319 
3320 #ifdef HAVE_INT_OPTERR
3321 
3322  /*
3323  * Turn this off because it's either printed to stderr and not the log
3324  * where we'd want it, or argv[0] is now "--single", which would make for
3325  * a weird error message. We print our own error message below.
3326  */
3327  opterr = 0;
3328 #endif
3329 
3330  /*
3331  * Parse command-line options. CAUTION: keep this in sync with
3332  * postmaster/postmaster.c (the option sets should not conflict) and with
3333  * the common help() function in main/main.c.
3334  */
3335  while ((flag = getopt(argc, argv, "B:bc:C:D:d:EeFf:h:ijk:lN:nOo:Pp:r:S:sTt:v:W:-:")) != -1)
3336  {
3337  switch (flag)
3338  {
3339  case 'B':
3340  SetConfigOption("shared_buffers", optarg, ctx, gucsource);
3341  break;
3342 
3343  case 'b':
3344  /* Undocumented flag used for binary upgrades */
3345  if (secure)
3346  IsBinaryUpgrade = true;
3347  break;
3348 
3349  case 'C':
3350  /* ignored for consistency with the postmaster */
3351  break;
3352 
3353  case 'D':
3354  if (secure)
3355  userDoption = strdup(optarg);
3356  break;
3357 
3358  case 'd':
3359  set_debug_options(atoi(optarg), ctx, gucsource);
3360  break;
3361 
3362  case 'E':
3363  if (secure)
3364  EchoQuery = true;
3365  break;
3366 
3367  case 'e':
3368  SetConfigOption("datestyle", "euro", ctx, gucsource);
3369  break;
3370 
3371  case 'F':
3372  SetConfigOption("fsync", "false", ctx, gucsource);
3373  break;
3374 
3375  case 'f':
3376  if (!set_plan_disabling_options(optarg, ctx, gucsource))
3377  errs++;
3378  break;
3379 
3380  case 'h':
3381  SetConfigOption("listen_addresses", optarg, ctx, gucsource);
3382  break;
3383 
3384  case 'i':
3385  SetConfigOption("listen_addresses", "*", ctx, gucsource);
3386  break;
3387 
3388  case 'j':
3389  if (secure)
3390  UseNewLine = 0;
3391  break;
3392 
3393  case 'k':
3394  SetConfigOption("unix_socket_directories", optarg, ctx, gucsource);
3395  break;
3396 
3397  case 'l':
3398  SetConfigOption("ssl", "true", ctx, gucsource);
3399  break;
3400 
3401  case 'N':
3402  SetConfigOption("max_connections", optarg, ctx, gucsource);
3403  break;
3404 
3405  case 'n':
3406  /* ignored for consistency with postmaster */
3407  break;
3408 
3409  case 'O':
3410  SetConfigOption("allow_system_table_mods", "true", ctx, gucsource);
3411  break;
3412 
3413  case 'o':
3414  errs++;
3415  break;
3416 
3417  case 'P':
3418  SetConfigOption("ignore_system_indexes", "true", ctx, gucsource);
3419  break;
3420 
3421  case 'p':
3422  SetConfigOption("port", optarg, ctx, gucsource);
3423  break;
3424 
3425  case 'r':
3426  /* send output (stdout and stderr) to the given file */
3427  if (secure)
3429  break;
3430 
3431  case 'S':
3432  SetConfigOption("work_mem", optarg, ctx, gucsource);
3433  break;
3434 
3435  case 's':
3436  SetConfigOption("log_statement_stats", "true", ctx, gucsource);
3437  break;
3438 
3439  case 'T':
3440  /* ignored for consistency with the postmaster */
3441  break;
3442 
3443  case 't':
3444  {
3445  const char *tmp = get_stats_option_name(optarg);
3446 
3447  if (tmp)
3448  SetConfigOption(tmp, "true", ctx, gucsource);
3449  else
3450  errs++;
3451  break;
3452  }
3453 
3454  case 'v':
3455 
3456  /*
3457  * -v is no longer used in normal operation, since
3458  * FrontendProtocol is already set before we get here. We keep
3459  * the switch only for possible use in standalone operation,
3460  * in case we ever support using normal FE/BE protocol with a
3461  * standalone backend.
3462  */
3463  if (secure)
3465  break;
3466 
3467  case 'W':
3468  SetConfigOption("post_auth_delay", optarg, ctx, gucsource);
3469  break;
3470 
3471  case 'c':
3472  case '-':
3473  {
3474  char *name,
3475  *value;
3476 
3477  ParseLongOption(optarg, &name, &value);
3478  if (!value)
3479  {
3480  if (flag == '-')
3481  ereport(ERROR,
3482  (errcode(ERRCODE_SYNTAX_ERROR),
3483  errmsg("--%s requires a value",
3484  optarg)));
3485  else
3486  ereport(ERROR,
3487  (errcode(ERRCODE_SYNTAX_ERROR),
3488  errmsg("-c %s requires a value",
3489  optarg)));
3490  }
3491  SetConfigOption(name, value, ctx, gucsource);
3492  free(name);
3493  if (value)
3494  free(value);
3495  break;
3496  }
3497 
3498  default:
3499  errs++;
3500  break;
3501  }
3502 
3503  if (errs)
3504  break;
3505  }
3506 
3507  /*
3508  * Optional database name should be there only if *dbname is NULL.
3509  */
3510  if (!errs && dbname && *dbname == NULL && argc - optind >= 1)
3511  *dbname = strdup(argv[optind++]);
3512 
3513  if (errs || argc != optind)
3514  {
3515  if (errs)
3516  optind--; /* complain about the previous argument */
3517 
3518  /* spell the error message a bit differently depending on context */
3519  if (IsUnderPostmaster)
3520  ereport(FATAL,
3521  (errcode(ERRCODE_SYNTAX_ERROR),
3522  errmsg("invalid command-line argument for server process: %s", argv[optind]),
3523  errhint("Try \"%s --help\" for more information.", progname)));
3524  else
3525  ereport(FATAL,
3526  (errcode(ERRCODE_SYNTAX_ERROR),
3527  errmsg("%s: invalid command-line argument: %s",
3528  progname, argv[optind]),
3529  errhint("Try \"%s --help\" for more information.", progname)));
3530  }
3531 
3532  /*
3533  * Reset getopt(3) library so that it will work correctly in subprocesses
3534  * or when this function is called a second time with another array.
3535  */
3536  optind = 1;
3537 #ifdef HAVE_INT_OPTRESET
3538  optreset = 1; /* some systems need this too */
3539 #endif
3540 }
3541 
3542 
3543 /* ----------------------------------------------------------------
3544  * PostgresMain
3545  * postgres main loop -- all backends, interactive or otherwise start here
3546  *
3547  * argc/argv are the command line arguments to be used. (When being forked
3548  * by the postmaster, these are not the original argv array of the process.)
3549  * dbname is the name of the database to connect to, or NULL if the database
3550  * name should be extracted from the command line arguments or defaulted.
3551  * username is the PostgreSQL user name to be used for the session.
3552  * ----------------------------------------------------------------
3553  */
3554 void
3555 PostgresMain(int argc, char *argv[],
3556  const char *dbname,
3557  const char *username)
3558 {
3559  int firstchar;
3560  StringInfoData input_message;
3561  sigjmp_buf local_sigjmp_buf;
3562  volatile bool send_ready_for_query = true;
3563 
3564  /* Initialize startup process environment if necessary. */
3565  if (!IsUnderPostmaster)
3566  InitStandaloneProcess(argv[0]);
3567 
3569 
3570  /*
3571  * Set default values for command-line options.
3572  */
3573  if (!IsUnderPostmaster)
3575 
3576  /*
3577  * Parse command-line options.
3578  */
3579  process_postgres_switches(argc, argv, PGC_POSTMASTER, &dbname);
3580 
3581  /* Must have gotten a database name, or have a default (the username) */
3582  if (dbname == NULL)
3583  {
3584  dbname = username;
3585  if (dbname == NULL)
3586  ereport(FATAL,
3587  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3588  errmsg("%s: no database nor user name specified",
3589  progname)));
3590  }
3591 
3592  /* Acquire configuration parameters, unless inherited from postmaster */
3593  if (!IsUnderPostmaster)
3594  {
3596  proc_exit(1);
3597  }
3598 
3599  /*
3600  * Set up signal handlers and masks.
3601  *
3602  * Note that postmaster blocked all signals before forking child process,
3603  * so there is no race condition whereby we might receive a signal before
3604  * we have set up the handler.
3605  *
3606  * Also note: it's best not to use any signals that are SIG_IGNored in the
3607  * postmaster. If such a signal arrives before we are able to change the
3608  * handler to non-SIG_IGN, it'll get dropped. Instead, make a dummy
3609  * handler in the postmaster to reserve the signal. (Of course, this isn't
3610  * an issue for signals that are locally generated, such as SIGALRM and
3611  * SIGPIPE.)
3612  */
3613  if (am_walsender)
3614  WalSndSignals();
3615  else
3616  {
3617  pqsignal(SIGHUP, SigHupHandler); /* set flag to read config
3618  * file */
3619  pqsignal(SIGINT, StatementCancelHandler); /* cancel current query */
3620  pqsignal(SIGTERM, die); /* cancel current query and exit */
3621 
3622  /*
3623  * In a standalone backend, SIGQUIT can be generated from the keyboard
3624  * easily, while SIGTERM cannot, so we make both signals do die()
3625  * rather than quickdie().
3626  */
3627  if (IsUnderPostmaster)
3628  pqsignal(SIGQUIT, quickdie); /* hard crash time */
3629  else
3630  pqsignal(SIGQUIT, die); /* cancel current query and exit */
3631  InitializeTimeouts(); /* establishes SIGALRM handler */
3632 
3633  /*
3634  * Ignore failure to write to frontend. Note: if frontend closes
3635  * connection, we will notice it and exit cleanly when control next
3636  * returns to outer loop. This seems safer than forcing exit in the
3637  * midst of output during who-knows-what operation...
3638  */
3643 
3644  /*
3645  * Reset some signals that are accepted by postmaster but not by
3646  * backend
3647  */
3648  pqsignal(SIGCHLD, SIG_DFL); /* system() requires this on some
3649  * platforms */
3650  }
3651 
3652  pqinitmask();
3653 
3654  if (IsUnderPostmaster)
3655  {
3656  /* We allow SIGQUIT (quickdie) at all times */
3657  sigdelset(&BlockSig, SIGQUIT);
3658  }
3659 
3660  PG_SETMASK(&BlockSig); /* block everything except SIGQUIT */
3661 
3662  if (!IsUnderPostmaster)
3663  {
3664  /*
3665  * Validate we have been given a reasonable-looking DataDir (if under
3666  * postmaster, assume postmaster did this already).
3667  */
3668  Assert(DataDir);
3670 
3671  /* Change into DataDir (if under postmaster, was done already) */
3672  ChangeToDataDir();
3673 
3674  /*
3675  * Create lockfile for data directory.
3676  */
3677  CreateDataDirLockFile(false);
3678 
3679  /* Initialize MaxBackends (if under postmaster, was done already) */
3681  }
3682 
3683  /* Early initialization */
3684  BaseInit();
3685 
3686  /*
3687  * Create a per-backend PGPROC struct in shared memory, except in the
3688  * EXEC_BACKEND case where this was done in SubPostmasterMain. We must do
3689  * this before we can use LWLocks (and in the EXEC_BACKEND case we already
3690  * had to do some stuff with LWLocks).
3691  */
3692 #ifdef EXEC_BACKEND
3693  if (!IsUnderPostmaster)
3694  InitProcess();
3695 #else
3696  InitProcess();
3697 #endif
3698 
3699  /* We need to allow SIGINT, etc during the initial transaction */
3701 
3702  /*
3703  * General initialization.
3704  *
3705  * NOTE: if you are tempted to add code in this vicinity, consider putting
3706  * it inside InitPostgres() instead. In particular, anything that
3707  * involves database access should be there, not here.
3708  */
3709  InitPostgres(dbname, InvalidOid, username, InvalidOid, NULL);
3710 
3711  /*
3712  * If the PostmasterContext is still around, recycle the space; we don't
3713  * need it anymore after InitPostgres completes. Note this does not trash
3714  * *MyProcPort, because ConnCreate() allocated that space with malloc()
3715  * ... else we'd need to copy the Port data first. Also, subsidiary data
3716  * such as the username isn't lost either; see ProcessStartupPacket().
3717  */
3718  if (PostmasterContext)
3719  {
3722  }
3723 
3725 
3726  /*
3727  * Now all GUC states are fully set up. Report them to client if
3728  * appropriate.
3729  */
3731 
3732  /*
3733  * Also set up handler to log session end; we have to wait till now to be
3734  * sure Log_disconnections has its final value.
3735  */
3738 
3739  /* Perform initialization specific to a WAL sender process. */
3740  if (am_walsender)
3741  InitWalSender();
3742 
3743  /*
3744  * process any libraries that should be preloaded at backend start (this
3745  * likewise can't be done until GUC settings are complete)
3746  */
3748 
3749  /*
3750  * Send this backend's cancellation info to the frontend.
3751  */
3752  if (whereToSendOutput == DestRemote &&
3754  {
3756 
3757  pq_beginmessage(&buf, 'K');
3758  pq_sendint(&buf, (int32) MyProcPid, sizeof(int32));
3759  pq_sendint(&buf, (int32) MyCancelKey, sizeof(int32));
3760  pq_endmessage(&buf);
3761  /* Need not flush since ReadyForQuery will do it. */
3762  }
3763 
3764  /* Welcome banner for standalone case */
3766  printf("\nPostgreSQL stand-alone backend %s\n", PG_VERSION);
3767 
3768  /*
3769  * Create the memory context we will use in the main loop.
3770  *
3771  * MessageContext is reset once per iteration of the main loop, ie, upon
3772  * completion of processing of each command message from the client.
3773  */
3775  "MessageContext",
3779 
3780  /*
3781  * Remember stand-alone backend startup time
3782  */
3783  if (!IsUnderPostmaster)
3785 
3786  /*
3787  * POSTGRES main processing loop begins here
3788  *
3789  * If an exception is encountered, processing resumes here so we abort the
3790  * current transaction and start a new one.
3791  *
3792  * You might wonder why this isn't coded as an infinite loop around a
3793  * PG_TRY construct. The reason is that this is the bottom of the
3794  * exception stack, and so with PG_TRY there would be no exception handler
3795  * in force at all during the CATCH part. By leaving the outermost setjmp
3796  * always active, we have at least some chance of recovering from an error
3797  * during error recovery. (If we get into an infinite loop thereby, it
3798  * will soon be stopped by overflow of elog.c's internal state stack.)
3799  *
3800  * Note that we use sigsetjmp(..., 1), so that this function's signal mask
3801  * (to wit, UnBlockSig) will be restored when longjmp'ing to here. This
3802  * is essential in case we longjmp'd out of a signal handler on a platform
3803  * where that leaves the signal blocked. It's not redundant with the
3804  * unblock in AbortTransaction() because the latter is only called if we
3805  * were inside a transaction.
3806  */
3807 
3808  if (sigsetjmp(local_sigjmp_buf, 1) != 0)
3809  {
3810  /*
3811  * NOTE: if you are tempted to add more code in this if-block,
3812  * consider the high probability that it should be in
3813  * AbortTransaction() instead. The only stuff done directly here
3814  * should be stuff that is guaranteed to apply *only* for outer-level
3815  * error recovery, such as adjusting the FE/BE protocol status.
3816  */
3817 
3818  /* Since not using PG_TRY, must reset error stack by hand */
3820 
3821  /* Prevent interrupts while cleaning up */
3822  HOLD_INTERRUPTS();
3823 
3824  /*
3825  * Forget any pending QueryCancel request, since we're returning to
3826  * the idle loop anyway, and cancel any active timeout requests. (In
3827  * future we might want to allow some timeout requests to survive, but
3828  * at minimum it'd be necessary to do reschedule_timeouts(), in case
3829  * we got here because of a query cancel interrupting the SIGALRM
3830  * interrupt handler.) Note in particular that we must clear the
3831  * statement and lock timeout indicators, to prevent any future plain
3832  * query cancels from being misreported as timeouts in case we're
3833  * forgetting a timeout cancel.
3834  */
3835  disable_all_timeouts(false);
3836  QueryCancelPending = false; /* second to avoid race condition */
3837 
3838  /* Not reading from the client anymore. */
3839  DoingCommandRead = false;
3840 
3841  /* Make sure libpq is in a good state */
3842  pq_comm_reset();
3843 
3844  /* Report the error to the client and/or server log */
3845  EmitErrorReport();
3846 
3847  /*
3848  * Make sure debug_query_string gets reset before we possibly clobber
3849  * the storage it points at.
3850  */
3852 
3853  /*
3854  * Abort the current transaction in order to recover.
3855  */
3857 
3858  if (am_walsender)
3860 
3861  /*
3862  * We can't release replication slots inside AbortTransaction() as we
3863  * need to be able to start and abort transactions while having a slot
3864  * acquired. But we never need to hold them across top level errors,
3865  * so releasing here is fine. There's another cleanup in ProcKill()
3866  * ensuring we'll correctly cleanup on FATAL errors as well.
3867  */
3868  if (MyReplicationSlot != NULL)
3870 
3871  /*
3872  * Now return to normal top-level context and clear ErrorContext for
3873  * next time.
3874  */
3876  FlushErrorState();
3877 
3878  /*
3879  * If we were handling an extended-query-protocol message, initiate
3880  * skip till next Sync. This also causes us not to issue
3881  * ReadyForQuery (until we get Sync).
3882  */
3884  ignore_till_sync = true;
3885 
3886  /* We don't have a transaction command open anymore */
3887  xact_started = false;
3888 
3889  /*
3890  * If an error occurred while we were reading a message from the
3891  * client, we have potentially lost track of where the previous
3892  * message ends and the next one begins. Even though we have
3893  * otherwise recovered from the error, we cannot safely read any more
3894  * messages from the client, so there isn't much we can do with the
3895  * connection anymore.
3896  */
3897  if (pq_is_reading_msg())
3898  ereport(FATAL,
3899  (errcode(ERRCODE_PROTOCOL_VIOLATION),
3900  errmsg("terminating connection because protocol sync was lost")));
3901 
3902  /* Now we can allow interrupts again */
3904  }
3905 
3906  /* We can now handle ereport(ERROR) */
3907  PG_exception_stack = &local_sigjmp_buf;
3908 
3909  if (!ignore_till_sync)
3910  send_ready_for_query = true; /* initially, or after error */
3911 
3912  /*
3913  * Non-error queries loop here.
3914  */
3915 
3916  for (;;)
3917  {
3918  /*
3919  * At top of loop, reset extended-query-message flag, so that any
3920  * errors encountered in "idle" state don't provoke skip.
3921  */
3923 
3924  /*
3925  * Release storage left over from prior query cycle, and create a new
3926  * query input buffer in the cleared MessageContext.
3927  */
3930 
3931  initStringInfo(&input_message);
3932 
3933  /*
3934  * (1) If we've reached idle state, tell the frontend we're ready for
3935  * a new query.
3936  *
3937  * Note: this includes fflush()'ing the last of the prior output.
3938  *
3939  * This is also a good time to send collected statistics to the
3940  * collector, and to update the PS stats display. We avoid doing
3941  * those every time through the message loop because it'd slow down
3942  * processing of batched messages, and because we don't want to report
3943  * uncommitted updates (that confuses autovacuum). The notification
3944  * processor wants a call too, if we are not in a transaction block.
3945  */
3946  if (send_ready_for_query)
3947  {
3949  {
3950  set_ps_display("idle in transaction (aborted)", false);
3952  }
3954  {
3955  set_ps_display("idle in transaction", false);
3957  }
3958  else
3959  {
3961  pgstat_report_stat(false);
3962 
3963  set_ps_display("idle", false);
3965  }
3966 
3968  send_ready_for_query = false;
3969  }
3970 
3971  /*
3972  * (2) Allow asynchronous signals to be executed immediately if they
3973  * come in while we are waiting for client input. (This must be
3974  * conditional since we don't want, say, reads on behalf of COPY FROM
3975  * STDIN doing the same thing.)
3976  */
3977  DoingCommandRead = true;
3978 
3979  /*
3980  * (3) read a command (loop blocks here)
3981  */
3982  firstchar = ReadCommand(&input_message);
3983 
3984  /*
3985  * (4) disable async signal conditions again.
3986  *
3987  * Query cancel is supposed to be a no-op when there is no query in
3988  * progress, so if a query cancel arrived while we were idle, just
3989  * reset QueryCancelPending. ProcessInterrupts() has that effect when
3990  * it's called when DoingCommandRead is set, so check for interrupts
3991  * before resetting DoingCommandRead.
3992  */
3994  DoingCommandRead = false;
3995 
3996  /*
3997  * (5) check for any other interesting events that happened while we
3998  * slept.
3999  */
4000  if (got_SIGHUP)
4001  {
4002  got_SIGHUP = false;
4004  }
4005 
4006  /*
4007  * (6) process the command. But ignore it if we're skipping till
4008  * Sync.
4009  */
4010  if (ignore_till_sync && firstchar != EOF)
4011  continue;
4012 
4013  switch (firstchar)
4014  {
4015  case 'Q': /* simple query */
4016  {
4017  const char *query_string;
4018 
4019  /* Set statement_timestamp() */
4021 
4022  query_string = pq_getmsgstring(&input_message);
4023  pq_getmsgend(&input_message);
4024 
4025  if (am_walsender)
4026  exec_replication_command(query_string);
4027  else
4028  exec_simple_query(query_string);
4029 
4030  send_ready_for_query = true;
4031  }
4032  break;
4033 
4034  case 'P': /* parse */
4035  {
4036  const char *stmt_name;
4037  const char *query_string;
4038  int numParams;
4039  Oid *paramTypes = NULL;
4040 
4041  forbidden_in_wal_sender(firstchar);
4042 
4043  /* Set statement_timestamp() */
4045 
4046  stmt_name = pq_getmsgstring(&input_message);
4047  query_string = pq_getmsgstring(&input_message);
4048  numParams = pq_getmsgint(&input_message, 2);
4049  if (numParams > 0)
4050  {
4051  int i;
4052 
4053  paramTypes = (Oid *) palloc(numParams * sizeof(Oid));
4054  for (i = 0; i < numParams; i++)
4055  paramTypes[i] = pq_getmsgint(&input_message, 4);
4056  }
4057  pq_getmsgend(&input_message);
4058 
4059  exec_parse_message(query_string, stmt_name,
4060  paramTypes, numParams);
4061  }
4062  break;
4063 
4064  case 'B': /* bind */
4065  forbidden_in_wal_sender(firstchar);
4066 
4067  /* Set statement_timestamp() */
4069 
4070  /*
4071  * this message is complex enough that it seems best to put
4072  * the field extraction out-of-line
4073  */
4074  exec_bind_message(&input_message);
4075  break;
4076 
4077  case 'E': /* execute */
4078  {
4079  const char *portal_name;
4080  int max_rows;
4081 
4082  forbidden_in_wal_sender(firstchar);
4083 
4084  /* Set statement_timestamp() */
4086 
4087  portal_name = pq_getmsgstring(&input_message);
4088  max_rows = pq_getmsgint(&input_message, 4);
4089  pq_getmsgend(&input_message);
4090 
4091  exec_execute_message(portal_name, max_rows);
4092  }
4093  break;
4094 
4095  case 'F': /* fastpath function call */
4096  forbidden_in_wal_sender(firstchar);
4097 
4098  /* Set statement_timestamp() */
4100 
4101  /* Report query to various monitoring facilities. */
4103  set_ps_display("<FASTPATH>", false);
4104 
4105  /* start an xact for this function invocation */
4107 
4108  /*
4109  * Note: we may at this point be inside an aborted
4110  * transaction. We can't throw error for that until we've
4111  * finished reading the function-call message, so
4112  * HandleFunctionRequest() must check for it after doing so.
4113  * Be careful not to do anything that assumes we're inside a
4114  * valid transaction here.
4115  */
4116 
4117  /* switch back to message context */
4119 
4120  if (HandleFunctionRequest(&input_message) == EOF)
4121  {
4122  /* lost frontend connection during F message input */
4123 
4124  /*
4125  * Reset whereToSendOutput to prevent ereport from
4126  * attempting to send any more messages to client.
4127  */
4130 
4131  proc_exit(0);
4132  }
4133 
4134  /* commit the function-invocation transaction */
4136 
4137  send_ready_for_query = true;
4138  break;
4139 
4140  case 'C': /* close */
4141  {
4142  int close_type;
4143  const char *close_target;
4144 
4145  forbidden_in_wal_sender(firstchar);
4146 
4147  close_type = pq_getmsgbyte(&input_message);
4148  close_target = pq_getmsgstring(&input_message);
4149  pq_getmsgend(&input_message);
4150 
4151  switch (close_type)
4152  {
4153  case 'S':
4154  if (close_target[0] != '\0')
4155  DropPreparedStatement(close_target, false);
4156  else
4157  {
4158  /* special-case the unnamed statement */
4160  }
4161  break;
4162  case 'P':
4163  {
4164  Portal portal;
4165 
4166  portal = GetPortalByName(close_target);
4167  if (PortalIsValid(portal))
4168  PortalDrop(portal, false);
4169  }
4170  break;
4171  default:
4172  ereport(ERROR,
4173  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4174  errmsg("invalid CLOSE message subtype %d",
4175  close_type)));
4176  break;
4177  }
4178 
4180  pq_putemptymessage('3'); /* CloseComplete */
4181  }
4182  break;
4183 
4184  case 'D': /* describe */
4185  {
4186  int describe_type;
4187  const char *describe_target;
4188 
4189  forbidden_in_wal_sender(firstchar);
4190 
4191  /* Set statement_timestamp() (needed for xact) */
4193 
4194  describe_type = pq_getmsgbyte(&input_message);
4195  describe_target = pq_getmsgstring(&input_message);
4196  pq_getmsgend(&input_message);
4197 
4198  switch (describe_type)
4199  {
4200  case 'S':
4201  exec_describe_statement_message(describe_target);
4202  break;
4203  case 'P':
4204  exec_describe_portal_message(describe_target);
4205  break;
4206  default:
4207  ereport(ERROR,
4208  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4209  errmsg("invalid DESCRIBE message subtype %d",
4210  describe_type)));
4211  break;
4212  }
4213  }
4214  break;
4215 
4216  case 'H': /* flush */
4217  pq_getmsgend(&input_message);
4219  pq_flush();
4220  break;
4221 
4222  case 'S': /* sync */
4223  pq_getmsgend(&input_message);
4225  send_ready_for_query = true;
4226  break;
4227 
4228  /*
4229  * 'X' means that the frontend is closing down the socket. EOF
4230  * means unexpected loss of frontend connection. Either way,
4231  * perform normal shutdown.
4232  */
4233  case 'X':
4234  case EOF:
4235 
4236  /*
4237  * Reset whereToSendOutput to prevent ereport from attempting
4238  * to send any more messages to client.
4239  */
4242 
4243  /*
4244  * NOTE: if you are tempted to add more code here, DON'T!
4245  * Whatever you had in mind to do should be set up as an
4246  * on_proc_exit or on_shmem_exit callback, instead. Otherwise
4247  * it will fail to be called during other backend-shutdown
4248  * scenarios.
4249  */
4250  proc_exit(0);
4251 
4252  case 'd': /* copy data */
4253  case 'c': /* copy done */
4254  case 'f': /* copy fail */
4255 
4256  /*
4257  * Accept but ignore these messages, per protocol spec; we
4258  * probably got here because a COPY failed, and the frontend
4259  * is still sending data.
4260  */
4261  break;
4262 
4263  default:
4264  ereport(FATAL,
4265  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4266  errmsg("invalid frontend message type %d",
4267  firstchar)));
4268  }
4269  } /* end of input-reading loop */
4270 }
4271 
4272 /*
4273  * Throw an error if we're a WAL sender process.
4274  *
4275  * This is used to forbid anything else than simple query protocol messages
4276  * in a WAL sender process. 'firstchar' specifies what kind of a forbidden
4277  * message was received, and is used to construct the error message.
4278  */
4279 static void
4281 {
4282  if (am_walsender)
4283  {
4284  if (firstchar == 'F')
4285  ereport(ERROR,
4286  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4287  errmsg("fastpath function calls not supported in a replication connection")));
4288  else
4289  ereport(ERROR,
4290  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4291  errmsg("extended query protocol not supported in a replication connection")));
4292  }
4293 }
4294 
4295 
4296 /*
4297  * Obtain platform stack depth limit (in bytes)
4298  *
4299  * Return -1 if unknown
4300  */
4301 long
4303 {
4304 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_STACK)
4305  static long val = 0;
4306 
4307  /* This won't change after process launch, so check just once */
4308  if (val == 0)
4309  {
4310  struct rlimit rlim;
4311 
4312  if (getrlimit(RLIMIT_STACK, &rlim) < 0)
4313  val = -1;
4314  else if (rlim.rlim_cur == RLIM_INFINITY)
4315  val = LONG_MAX;
4316  /* rlim_cur is probably of an unsigned type, so check for overflow */
4317  else if (rlim.rlim_cur >= LONG_MAX)
4318  val = LONG_MAX;
4319  else
4320  val = rlim.rlim_cur;
4321  }
4322  return val;
4323 #else /* no getrlimit */
4324 #if defined(WIN32) || defined(__CYGWIN__)
4325  /* On Windows we set the backend stack size in src/backend/Makefile */
4326  return WIN32_STACK_RLIMIT;
4327 #else /* not windows ... give up */
4328  return -1;
4329 #endif
4330 #endif
4331 }
4332 
4333 
4334 static struct rusage Save_r;
4335 static struct timeval Save_t;
4336 
4337 void
4339 {
4342 }
4343 
4344 void
4345 ShowUsage(const char *title)
4346 {
4347  StringInfoData str;
4348  struct timeval user,
4349  sys;
4350  struct timeval elapse_t;
4351  struct rusage r;
4352 
4353  getrusage(RUSAGE_SELF, &r);
4354  gettimeofday(&elapse_t, NULL);
4355  memcpy((char *) &user, (char *) &r.ru_utime, sizeof(user));
4356  memcpy((char *) &sys, (char *) &r.ru_stime, sizeof(sys));
4357  if (elapse_t.tv_usec < Save_t.tv_usec)
4358  {
4359  elapse_t.tv_sec--;
4360  elapse_t.tv_usec += 1000000;
4361  }
4362  if (r.ru_utime.tv_usec < Save_r.ru_utime.tv_usec)
4363  {
4364  r.ru_utime.tv_sec--;
4365  r.ru_utime.tv_usec += 1000000;
4366  }
4367  if (r.ru_stime.tv_usec < Save_r.ru_stime.tv_usec)
4368  {
4369  r.ru_stime.tv_sec--;
4370  r.ru_stime.tv_usec += 1000000;
4371  }
4372 
4373  /*
4374  * the only stats we don't show here are for memory usage -- i can't
4375  * figure out how to interpret the relevant fields in the rusage struct,
4376  * and they change names across o/s platforms, anyway. if you can figure
4377  * out what the entries mean, you can somehow extract resident set size,
4378  * shared text size, and unshared data and stack sizes.
4379  */
4380  initStringInfo(&str);
4381 
4382  appendStringInfoString(&str, "! system usage stats:\n");
4383  appendStringInfo(&str,
4384  "!\t%ld.%06ld elapsed %ld.%06ld user %ld.%06ld system sec\n",
4385  (long) (elapse_t.tv_sec - Save_t.tv_sec),
4386  (long) (elapse_t.tv_usec - Save_t.tv_usec),
4387  (long) (r.ru_utime.tv_sec - Save_r.ru_utime.tv_sec),
4388  (long) (r.ru_utime.tv_usec - Save_r.ru_utime.tv_usec),
4389  (long) (r.ru_stime.tv_sec - Save_r.ru_stime.tv_sec),
4390  (long) (r.ru_stime.tv_usec - Save_r.ru_stime.tv_usec));
4391  appendStringInfo(&str,
4392  "!\t[%ld.%06ld user %ld.%06ld sys total]\n",
4393  (long) user.tv_sec,
4394  (long) user.tv_usec,
4395  (long) sys.tv_sec,
4396  (long) sys.tv_usec);
4397 #if defined(HAVE_GETRUSAGE)
4398  appendStringInfo(&str,
4399  "!\t%ld/%ld [%ld/%ld] filesystem blocks in/out\n",
4400  r.ru_inblock - Save_r.ru_inblock,
4401  /* they only drink coffee at dec */
4402  r.ru_oublock - Save_r.ru_oublock,
4403  r.ru_inblock, r.ru_oublock);
4404  appendStringInfo(&str,
4405  "!\t%ld/%ld [%ld/%ld] page faults/reclaims, %ld [%ld] swaps\n",
4406  r.ru_majflt - Save_r.ru_majflt,
4407  r.ru_minflt - Save_r.ru_minflt,
4408  r.ru_majflt, r.ru_minflt,
4409  r.ru_nswap - Save_r.ru_nswap,
4410  r.ru_nswap);
4411  appendStringInfo(&str,
4412  "!\t%ld [%ld] signals rcvd, %ld/%ld [%ld/%ld] messages rcvd/sent\n",
4413  r.ru_nsignals - Save_r.ru_nsignals,
4414  r.ru_nsignals,
4415  r.ru_msgrcv - Save_r.ru_msgrcv,
4416  r.ru_msgsnd - Save_r.ru_msgsnd,
4417  r.ru_msgrcv, r.ru_msgsnd);
4418  appendStringInfo(&str,
4419  "!\t%ld/%ld [%ld/%ld] voluntary/involuntary context switches\n",
4420  r.ru_nvcsw - Save_r.ru_nvcsw,
4421  r.ru_nivcsw - Save_r.ru_nivcsw,
4422  r.ru_nvcsw, r.ru_nivcsw);
4423 #endif /* HAVE_GETRUSAGE */
4424 
4425  /* remove trailing newline */
4426  if (str.data[str.len - 1] == '\n')
4427  str.data[--str.len] = '\0';
4428 
4429  ereport(LOG,
4430  (errmsg_internal("%s", title),
4431  errdetail_internal("%s", str.data)));
4432 
4433  pfree(str.data);
4434 }
4435 
4436 /*
4437  * on_proc_exit handler to log end of session
4438  */
4439 static void
4441 {
4442  Port *port = MyProcPort;
4443  long secs;
4444  int usecs;
4445  int msecs;
4446  int hours,
4447  minutes,
4448  seconds;
4449 
4452  &secs, &usecs);
4453  msecs = usecs / 1000;
4454 
4455  hours = secs / SECS_PER_HOUR;
4456  secs %= SECS_PER_HOUR;
4457  minutes = secs / SECS_PER_MINUTE;
4458  seconds = secs % SECS_PER_MINUTE;
4459 
4460  ereport(LOG,
4461  (errmsg("disconnection: session time: %d:%02d:%02d.%03d "
4462  "user=%s database=%s host=%s%s%s",
4463  hours, minutes, seconds, msecs,
4464  port->user_name, port->database_name, port->remote_host,
4465  port->remote_port[0] ? " port=" : "", port->remote_port)));
4466 }
pg_stack_base_t set_stack_base(void)
Definition: postgres.c:3042
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:417
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:2387
#define SIGUSR1
Definition: win32.h:197
void(* rDestroy)(DestReceiver *self)
Definition: dest.h:123
#define IsA(nodeptr, _type_)
Definition: nodes.h:515
int gettimeofday(struct timeval *tp, struct timezone *tzp)
Definition: gettimeofday.c:105
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:203
bool IsWaitingForLock(void)
Definition: proc.c:652
void RecoveryConflictInterrupt(ProcSignalReason reason)
Definition: postgres.c:2723
#define HOLD_CANCEL_INTERRUPTS()
Definition: miscadmin.h:121
List * QueryRewrite(Query *parsetree)
void BeginReportingGUCOptions(void)
Definition: guc.c:5063
#define DEBUG1
Definition: elog.h:25
int MyProcPid
Definition: globals.c:37
int errhint(const char *fmt,...)
Definition: elog.c:982
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition: lsyscache.c:2554
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:2458
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:181
CommandDest
Definition: dest.h:86
#define end(cp)
Definition: zic.c:59
bool log_parser_stats
Definition: guc.c:399
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:2679
void PortalDefineQuery(Portal portal, const char *prepStmtName, const char *sourceText, const char *commandTag, List *stmts, CachedPlan *cplan)
Definition: portalmem.c:301
#define DEBUG3
Definition: elog.h:23
static volatile sig_atomic_t got_SIGHUP
Definition: postgres.c:129
bool log_statement_stats
Definition: guc.c:402
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:4345
void MemoryContextSetParent(MemoryContext context, MemoryContext new_parent)
Definition: mcxt.c:320
Portal GetPortalByName(const char *name)
Definition: portalmem.c:130
#define CURSOR_OPT_BINARY
Definition: parsenodes.h:2345
char * pstrdup(const char *in)
Definition: mcxt.c:1160
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:9031
void ValidatePgVersion(const char *path)
Definition: miscinit.c:1217
bool IsAbortedTransactionBlockState(void)
Definition: xact.c:367
bool set_plan_disabling_options(const char *arg, GucContext context, GucSource source)
Definition: postgres.c:3214
static struct rusage Save_r
Definition: postgres.c:4334
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:2533
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:4280
Definition: nodes.h:464
void proc_exit(int code)
Definition: ipc.c:99
int errcode(int sqlerrcode)
Definition: elog.c:573
Definition: libpq-be.h:118
int errhidestmt(bool hide_stmt)
Definition: elog.c:1063
bool IsTransactionOrTransactionBlock(void)
Definition: xact.c:4282
const char * get_stats_option_name(const char *arg)
Definition: postgres.c:3256
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:365
void BaseInit(void)
Definition: postinit.c:517
static int errdetail_abort(void)
Definition: postgres.c:2244
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:3185
struct timeval ru_stime
Definition: rusagestub.h:29
void BeginCommand(const char *commandTag, CommandDest dest)
Definition: dest.c:92
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:136
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:3073
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:187
#define OidIsValid(objectId)
Definition: c.h:519
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:152
int getopt(int nargc, char *const *nargv, const char *ostr)
Definition: getopt.c:72
void FlushErrorState(void)
Definition: elog.c:1575
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
void pq_beginmessage(StringInfo buf, char msgtype)
Definition: pqformat.c:87
void StatementCancelHandler(SIGNAL_ARGS)
Definition: postgres.c:2672
#define ALLOCSET_DEFAULT_MINSIZE
Definition: memutils.h:142
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:1845
int errdetail_internal(const char *fmt,...)
Definition: elog.c:895
GucSource
Definition: guc.h:105
static bool IsTransactionExitStmt(Node *parsetree)
Definition: postgres.c:2494
static void log_disconnections(int code, Datum arg)
Definition: postgres.c:4440
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
TupleDesc resultDesc
Definition: plancache.h:88
void * copyObject(const void *from)
Definition: copyfuncs.c:4192
#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:2104
#define list_make1(x1)
Definition: pg_list.h:133
volatile bool ClientConnectionLost
Definition: globals.c:32
void pqinitmask(void)
Definition: pqsignal.c:41
static int errdetail_execute(List *raw_parsetree_list)
Definition: postgres.c:2149
bool ClientAuthInProgress
Definition: postmaster.c:342
void ResetUsage(void)
Definition: postgres.c:4338
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:3153
bool Debug_print_plan
Definition: guc.c:394
#define appendStringInfoCharMacro(str, ch)
Definition: stringinfo.h:127
ParamFetchHook paramFetch
Definition: params.h:69
void pfree(void *pointer)
Definition: mcxt.c:993
ParamListInfo portalParams
Definition: portal.h:139
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:147
Node * raw_parse_tree
Definition: plancache.h:79
#define ERROR
Definition: elog.h:41
void CreateDataDirLockFile(bool amPostmaster)
Definition: miscinit.c:1027
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:1121
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:2601
void ProcessInterrupts(void)
Definition: postgres.c:2845
#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:487
#define MAXPGPATH
bool Debug_print_parse
Definition: guc.c:395
static void SigHupHandler(SIGNAL_ARGS)
Definition: postgres.c:2706
TimestampTz SessionStartTime
Definition: libpq-be.h:154
const char * commandTag
Definition: portal.h:135
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:3555
#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
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:6374
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:4335
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:542
bool recoveryConflictPending
Definition: proc.h:110
void check_stack_depth(void)
Definition: postgres.c:3092
bool IsUnderPostmaster
Definition: globals.c:97
static CachedPlanSource * unnamed_stmt_psrc
Definition: postgres.c:156
DestReceiver * CreateDestReceiver(CommandDest dest)
Definition: dest.c:102
static void exec_bind_message(StringInfo input_message)
Definition: postgres.c:1464
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:868
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
sigset_t UnBlockSig
Definition: pqsignal.c:22
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:2180
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:2587
char * portalname
Definition: parsenodes.h:2396
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:2521
#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:1270
void LockErrorCleanup(void)
Definition: proc.c:669
#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:4302
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:2067
static void exec_parse_message(const char *query_string, const char *stmt_name, Oid *paramTypes, int numParams)
Definition: postgres.c:1200
#define PortalIsValid(p)
Definition: portal.h:188
static bool RecoveryConflictRetryable
Definition: postgres.c:175
static void start_xact_command(void)
Definition: postgres.c:2438
static bool IsTransactionExitStmtList(List *parseTrees)
Definition: postgres.c:2511
static bool doing_extended_query_message
Definition: postgres.c:148
sigset_t BlockSig
Definition: pqsignal.c:22
void process_session_preload_libraries(void)
Definition: miscinit.c:1362
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:436
bool ismove
Definition: parsenodes.h:2397
int16 * formats
Definition: portal.h:155
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:4403
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:2258
void EmitErrorReport(void)
Definition: elog.c:1439
const char * sourceText
Definition: portal.h:134
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:153
#define InvalidOid
Definition: postgres_ext.h:36
#define SIG_DFL
Definition: win32.h:177
void SaveCachedPlan(CachedPlanSource *plansource)
Definition: plancache.c:435
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:393
int errmsg_internal(const char *fmt,...)
Definition: elog.c:824
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:1048
#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:656
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:321
bool HoldingBufferPinThatDelaysRecovery(void)
Definition: bufmgr.c:3367
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:194
List * CachedPlanGetTargetList(CachedPlanSource *plansource)
Definition: plancache.c:1410
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:174
#define CURSOR_OPT_PARALLEL_OK
Definition: parsenodes.h:2354
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:892
int errmsg(const char *fmt,...)
Definition: elog.c:795
void PortalDrop(Portal portal, bool isTopCommit)
Definition: portalmem.c:486
void pq_sendint(StringInfo buf, int i, int b)
Definition: pqformat.c:235
void ReadyForQuery(CommandDest dest)
Definition: dest.c:229
void pq_endmessage(StringInfo buf)
Definition: pqformat.c:343
char * optarg
Definition: getopt.c:53
void die(SIGNAL_ARGS)
Definition: postgres.c:2641
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:113
#define ALLOCSET_DEFAULT_INITSIZE
Definition: memutils.h:143
int i
void FloatExceptionHandler(SIGNAL_ARGS)
Definition: postgres.c:2693
static void drop_unnamed_stmt(void)
Definition: postgres.c:2555
bool Debug_pretty_print
Definition: guc.c:397
char * name
Definition: parsenodes.h:2990
ProcSignalReason
Definition: procsignal.h:30
int pq_getstring(StringInfo s)
Definition: pqcomm.c:1118
void * arg
char * DataDir
Definition: globals.c:58
void DropCachedPlan(CachedPlanSource *plansource)
Definition: plancache.c:480
struct Latch * MyLatch
Definition: globals.c:50
volatile sig_atomic_t notifyInterruptPending
Definition: async.c:346
#define ALLOCSET_DEFAULT_MAXSIZE
Definition: memutils.h:144
unsigned int pq_getmsgint(StringInfo msg, int b)
Definition: pqformat.c:447
bool Debug_print_rewritten
Definition: guc.c:396
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:129
void process_postgres_switches(int argc, char *argv[], GucContext ctx, const char **dbname)
Definition: postgres.c:3296
#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:143
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:3170
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:2580
#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:400
#define SIGUSR2
Definition: win32.h:198
#define offsetof(type, field)
Definition: c.h:536
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:187
TimestampTz GetCurrentStatementStartTimestamp(void)
Definition: xact.c:714
char * pg_stack_base_t
Definition: miscadmin.h:265
void InitializeGUCOptions(void)
Definition: guc.c:4181
TransactionStmtKind kind
Definition: parsenodes.h:2626
#define RESUME_CANCEL_INTERRUPTS()
Definition: miscadmin.h:123
void ProcessClientWriteInterrupt(bool blocked)
Definition: postgres.c:571
#define FETCH_ALL
Definition: parsenodes.h:2389
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:2294
PlannedStmt * pg_plan_query(Query *querytree, int cursorOptions, ParamListInfo boundParams)
Definition: postgres.c:792