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