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