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