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