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