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/lsyscache.h"
76 #include "utils/memutils.h"
77 #include "utils/ps_status.h"
78 #include "utils/snapmgr.h"
79 #include "utils/timeout.h"
80 #include "utils/timestamp.h"
81 
82 /* ----------------
83  * global variables
84  * ----------------
85  */
86 const char *debug_query_string; /* client-supplied query string */
87 
88 /* Note: whereToSendOutput is initialized for the bootstrap/standalone case */
90 
91 /* flag for logging end of session */
92 bool Log_disconnections = false;
93 
95 
96 /* GUC variable for maximum stack depth (measured in kilobytes) */
97 int max_stack_depth = 100;
98 
99 /* wait N seconds to allow attach from a debugger */
101 
102 /* Time between checks that the client is still connected. */
104 
105 /* ----------------
106  * private typedefs etc
107  * ----------------
108  */
109 
110 /* type of argument for bind_param_error_callback */
111 typedef struct BindParamCbData
112 {
113  const char *portalName;
114  int paramno; /* zero-based param number, or -1 initially */
115  const char *paramval; /* textual input string, if available */
117 
118 /* ----------------
119  * private variables
120  * ----------------
121  */
122 
123 /* max_stack_depth converted to bytes for speed of checking */
124 static long max_stack_depth_bytes = 100 * 1024L;
125 
126 /*
127  * Stack base pointer -- initialized by PostmasterMain and inherited by
128  * subprocesses (but see also InitPostmasterChild).
129  */
130 static char *stack_base_ptr = NULL;
131 
132 /*
133  * Flag to keep track of whether we have started a transaction.
134  * For extended query protocol this has to be remembered across messages.
135  */
136 static bool xact_started = false;
137 
138 /*
139  * Flag to indicate that we are doing the outer loop's read-from-client,
140  * as opposed to any random read from client that might happen within
141  * commands like COPY FROM STDIN.
142  */
143 static bool DoingCommandRead = false;
144 
145 /*
146  * Flags to implement skip-till-Sync-after-error behavior for messages of
147  * the extended query protocol.
148  */
149 static bool doing_extended_query_message = false;
150 static bool ignore_till_sync = false;
151 
152 /*
153  * If an unnamed prepared statement exists, it's stored here.
154  * We keep it separate from the hashtable kept by commands/prepare.c
155  * in order to reduce overhead for short-lived queries.
156  */
158 
159 /* assorted command-line switches */
160 static const char *userDoption = NULL; /* -D switch */
161 static bool EchoQuery = false; /* -E switch */
162 static bool UseSemiNewlineNewline = false; /* -j switch */
163 
164 /* whether or not, and why, we were canceled by conflict with recovery */
165 static volatile sig_atomic_t RecoveryConflictPending = false;
166 static volatile sig_atomic_t RecoveryConflictPendingReasons[NUM_PROCSIGNALS];
167 
168 /* reused buffer to pass to SendRowDescriptionMessage() */
171 
172 /* ----------------------------------------------------------------
173  * decls for routines only used in this file
174  * ----------------------------------------------------------------
175  */
176 static int InteractiveBackend(StringInfo inBuf);
177 static int interactive_getc(void);
178 static int SocketBackend(StringInfo inBuf);
179 static int ReadCommand(StringInfo inBuf);
180 static void forbidden_in_wal_sender(char firstchar);
181 static bool check_log_statement(List *stmt_list);
182 static int errdetail_execute(List *raw_parsetree_list);
183 static int errdetail_params(ParamListInfo params);
184 static int errdetail_abort(void);
185 static void bind_param_error_callback(void *arg);
186 static void start_xact_command(void);
187 static void finish_xact_command(void);
188 static bool IsTransactionExitStmt(Node *parsetree);
189 static bool IsTransactionExitStmtList(List *pstmts);
190 static bool IsTransactionStmtList(List *pstmts);
191 static void drop_unnamed_stmt(void);
192 static void log_disconnections(int code, Datum arg);
193 static void enable_statement_timeout(void);
194 static void disable_statement_timeout(void);
195 
196 
197 /* ----------------------------------------------------------------
198  * infrastructure for valgrind debugging
199  * ----------------------------------------------------------------
200  */
201 #ifdef USE_VALGRIND
202 /* This variable should be set at the top of the main loop. */
203 static unsigned int old_valgrind_error_count;
204 
205 /*
206  * If Valgrind detected any errors since old_valgrind_error_count was updated,
207  * report the current query as the cause. This should be called at the end
208  * of message processing.
209  */
210 static void
211 valgrind_report_error_query(const char *query)
212 {
213  unsigned int valgrind_error_count = VALGRIND_COUNT_ERRORS;
214 
215  if (unlikely(valgrind_error_count != old_valgrind_error_count) &&
216  query != NULL)
217  VALGRIND_PRINTF("Valgrind detected %u error(s) during execution of \"%s\"\n",
218  valgrind_error_count - old_valgrind_error_count,
219  query);
220 }
221 
222 #else /* !USE_VALGRIND */
223 #define valgrind_report_error_query(query) ((void) 0)
224 #endif /* USE_VALGRIND */
225 
226 
227 /* ----------------------------------------------------------------
228  * routines to obtain user input
229  * ----------------------------------------------------------------
230  */
231 
232 /* ----------------
233  * InteractiveBackend() is called for user interactive connections
234  *
235  * the string entered by the user is placed in its parameter inBuf,
236  * and we act like a Q message was received.
237  *
238  * EOF is returned if end-of-file input is seen; time to shut down.
239  * ----------------
240  */
241 
242 static int
244 {
245  int c; /* character read from getc() */
246 
247  /*
248  * display a prompt and obtain input from the user
249  */
250  printf("backend> ");
251  fflush(stdout);
252 
253  resetStringInfo(inBuf);
254 
255  /*
256  * Read characters until EOF or the appropriate delimiter is seen.
257  */
258  while ((c = interactive_getc()) != EOF)
259  {
260  if (c == '\n')
261  {
263  {
264  /*
265  * In -j mode, semicolon followed by two newlines ends the
266  * command; otherwise treat newline as regular character.
267  */
268  if (inBuf->len > 1 &&
269  inBuf->data[inBuf->len - 1] == '\n' &&
270  inBuf->data[inBuf->len - 2] == ';')
271  {
272  /* might as well drop the second newline */
273  break;
274  }
275  }
276  else
277  {
278  /*
279  * In plain mode, newline ends the command unless preceded by
280  * backslash.
281  */
282  if (inBuf->len > 0 &&
283  inBuf->data[inBuf->len - 1] == '\\')
284  {
285  /* discard backslash from inBuf */
286  inBuf->data[--inBuf->len] = '\0';
287  /* discard newline too */
288  continue;
289  }
290  else
291  {
292  /* keep the newline character, but end the command */
293  appendStringInfoChar(inBuf, '\n');
294  break;
295  }
296  }
297  }
298 
299  /* Not newline, or newline treated as regular character */
300  appendStringInfoChar(inBuf, (char) c);
301  }
302 
303  /* No input before EOF signal means time to quit. */
304  if (c == EOF && inBuf->len == 0)
305  return EOF;
306 
307  /*
308  * otherwise we have a user query so process it.
309  */
310 
311  /* Add '\0' to make it look the same as message case. */
312  appendStringInfoChar(inBuf, (char) '\0');
313 
314  /*
315  * if the query echo flag was given, print the query..
316  */
317  if (EchoQuery)
318  printf("statement: %s\n", inBuf->data);
319  fflush(stdout);
320 
321  return 'Q';
322 }
323 
324 /*
325  * interactive_getc -- collect one character from stdin
326  *
327  * Even though we are not reading from a "client" process, we still want to
328  * respond to signals, particularly SIGTERM/SIGQUIT.
329  */
330 static int
332 {
333  int c;
334 
335  /*
336  * This will not process catchup interrupts or notifications while
337  * reading. But those can't really be relevant for a standalone backend
338  * anyway. To properly handle SIGTERM there's a hack in die() that
339  * directly processes interrupts at this stage...
340  */
342 
343  c = getc(stdin);
344 
346 
347  return c;
348 }
349 
350 /* ----------------
351  * SocketBackend() Is called for frontend-backend connections
352  *
353  * Returns the message type code, and loads message body data into inBuf.
354  *
355  * EOF is returned if the connection is lost.
356  * ----------------
357  */
358 static int
360 {
361  int qtype;
362  int maxmsglen;
363 
364  /*
365  * Get message type code from the frontend.
366  */
368  pq_startmsgread();
369  qtype = pq_getbyte();
370 
371  if (qtype == EOF) /* frontend disconnected */
372  {
373  if (IsTransactionState())
375  (errcode(ERRCODE_CONNECTION_FAILURE),
376  errmsg("unexpected EOF on client connection with an open transaction")));
377  else
378  {
379  /*
380  * Can't send DEBUG log messages to client at this point. Since
381  * we're disconnecting right away, we don't need to restore
382  * whereToSendOutput.
383  */
385  ereport(DEBUG1,
386  (errcode(ERRCODE_CONNECTION_DOES_NOT_EXIST),
387  errmsg_internal("unexpected EOF on client connection")));
388  }
389  return qtype;
390  }
391 
392  /*
393  * Validate message type code before trying to read body; if we have lost
394  * sync, better to say "command unknown" than to run out of memory because
395  * we used garbage as a length word. We can also select a type-dependent
396  * limit on what a sane length word could be. (The limit could be chosen
397  * more granularly, but it's not clear it's worth fussing over.)
398  *
399  * This also gives us a place to set the doing_extended_query_message flag
400  * as soon as possible.
401  */
402  switch (qtype)
403  {
404  case PqMsg_Query:
405  maxmsglen = PQ_LARGE_MESSAGE_LIMIT;
407  break;
408 
409  case PqMsg_FunctionCall:
410  maxmsglen = PQ_LARGE_MESSAGE_LIMIT;
412  break;
413 
414  case PqMsg_Terminate:
415  maxmsglen = PQ_SMALL_MESSAGE_LIMIT;
417  ignore_till_sync = false;
418  break;
419 
420  case PqMsg_Bind:
421  case PqMsg_Parse:
422  maxmsglen = PQ_LARGE_MESSAGE_LIMIT;
424  break;
425 
426  case PqMsg_Close:
427  case PqMsg_Describe:
428  case PqMsg_Execute:
429  case PqMsg_Flush:
430  maxmsglen = PQ_SMALL_MESSAGE_LIMIT;
432  break;
433 
434  case PqMsg_Sync:
435  maxmsglen = PQ_SMALL_MESSAGE_LIMIT;
436  /* stop any active skip-till-Sync */
437  ignore_till_sync = false;
438  /* mark not-extended, so that a new error doesn't begin skip */
440  break;
441 
442  case PqMsg_CopyData:
443  maxmsglen = PQ_LARGE_MESSAGE_LIMIT;
445  break;
446 
447  case PqMsg_CopyDone:
448  case PqMsg_CopyFail:
449  maxmsglen = PQ_SMALL_MESSAGE_LIMIT;
451  break;
452 
453  default:
454 
455  /*
456  * Otherwise we got garbage from the frontend. We treat this as
457  * fatal because we have probably lost message boundary sync, and
458  * there's no good way to recover.
459  */
460  ereport(FATAL,
461  (errcode(ERRCODE_PROTOCOL_VIOLATION),
462  errmsg("invalid frontend message type %d", qtype)));
463  maxmsglen = 0; /* keep compiler quiet */
464  break;
465  }
466 
467  /*
468  * In protocol version 3, all frontend messages have a length word next
469  * after the type code; we can read the message contents independently of
470  * the type.
471  */
472  if (pq_getmessage(inBuf, maxmsglen))
473  return EOF; /* suitable message already logged */
475 
476  return qtype;
477 }
478 
479 /* ----------------
480  * ReadCommand reads a command from either the frontend or
481  * standard input, places it in inBuf, and returns the
482  * message type code (first byte of the message).
483  * EOF is returned if end of file.
484  * ----------------
485  */
486 static int
488 {
489  int result;
490 
492  result = SocketBackend(inBuf);
493  else
494  result = InteractiveBackend(inBuf);
495  return result;
496 }
497 
498 /*
499  * ProcessClientReadInterrupt() - Process interrupts specific to client reads
500  *
501  * This is called just before and after low-level reads.
502  * 'blocked' is true if no data was available to read and we plan to retry,
503  * false if about to read or done reading.
504  *
505  * Must preserve errno!
506  */
507 void
509 {
510  int save_errno = errno;
511 
512  if (DoingCommandRead)
513  {
514  /* Check for general interrupts that arrived before/while reading */
516 
517  /* Process sinval catchup interrupts, if any */
520 
521  /* Process notify interrupts, if any */
524  }
525  else if (ProcDiePending)
526  {
527  /*
528  * We're dying. If there is no data available to read, then it's safe
529  * (and sane) to handle that now. If we haven't tried to read yet,
530  * make sure the process latch is set, so that if there is no data
531  * then we'll come back here and die. If we're done reading, also
532  * make sure the process latch is set, as we might've undesirably
533  * cleared it while reading.
534  */
535  if (blocked)
537  else
538  SetLatch(MyLatch);
539  }
540 
541  errno = save_errno;
542 }
543 
544 /*
545  * ProcessClientWriteInterrupt() - Process interrupts specific to client writes
546  *
547  * This is called just before and after low-level writes.
548  * 'blocked' is true if no data could be written and we plan to retry,
549  * false if about to write or done writing.
550  *
551  * Must preserve errno!
552  */
553 void
555 {
556  int save_errno = errno;
557 
558  if (ProcDiePending)
559  {
560  /*
561  * We're dying. If it's not possible to write, then we should handle
562  * that immediately, else a stuck client could indefinitely delay our
563  * response to the signal. If we haven't tried to write yet, make
564  * sure the process latch is set, so that if the write would block
565  * then we'll come back here and die. If we're done writing, also
566  * make sure the process latch is set, as we might've undesirably
567  * cleared it while writing.
568  */
569  if (blocked)
570  {
571  /*
572  * Don't mess with whereToSendOutput if ProcessInterrupts wouldn't
573  * service ProcDiePending.
574  */
575  if (InterruptHoldoffCount == 0 && CritSectionCount == 0)
576  {
577  /*
578  * We don't want to send the client the error message, as a)
579  * that would possibly block again, and b) it would likely
580  * lead to loss of protocol sync because we may have already
581  * sent a partial protocol message.
582  */
585 
587  }
588  }
589  else
590  SetLatch(MyLatch);
591  }
592 
593  errno = save_errno;
594 }
595 
596 /*
597  * Do raw parsing (only).
598  *
599  * A list of parsetrees (RawStmt nodes) is returned, since there might be
600  * multiple commands in the given string.
601  *
602  * NOTE: for interactive queries, it is important to keep this routine
603  * separate from the analysis & rewrite stages. Analysis and rewriting
604  * cannot be done in an aborted transaction, since they require access to
605  * database tables. So, we rely on the raw parser to determine whether
606  * we've seen a COMMIT or ABORT command; when we are in abort state, other
607  * commands are not processed any further than the raw parse stage.
608  */
609 List *
610 pg_parse_query(const char *query_string)
611 {
612  List *raw_parsetree_list;
613 
614  TRACE_POSTGRESQL_QUERY_PARSE_START(query_string);
615 
616  if (log_parser_stats)
617  ResetUsage();
618 
619  raw_parsetree_list = raw_parser(query_string, RAW_PARSE_DEFAULT);
620 
621  if (log_parser_stats)
622  ShowUsage("PARSER STATISTICS");
623 
624 #ifdef COPY_PARSE_PLAN_TREES
625  /* Optional debugging check: pass raw parsetrees through copyObject() */
626  {
627  List *new_list = copyObject(raw_parsetree_list);
628 
629  /* This checks both copyObject() and the equal() routines... */
630  if (!equal(new_list, raw_parsetree_list))
631  elog(WARNING, "copyObject() failed to produce an equal raw parse tree");
632  else
633  raw_parsetree_list = new_list;
634  }
635 #endif
636 
637  /*
638  * Optional debugging check: pass raw parsetrees through
639  * outfuncs/readfuncs
640  */
641 #ifdef WRITE_READ_PARSE_PLAN_TREES
642  {
643  char *str = nodeToString(raw_parsetree_list);
644  List *new_list = stringToNodeWithLocations(str);
645 
646  pfree(str);
647  /* This checks both outfuncs/readfuncs and the equal() routines... */
648  if (!equal(new_list, raw_parsetree_list))
649  elog(WARNING, "outfuncs/readfuncs failed to produce an equal raw parse tree");
650  else
651  raw_parsetree_list = new_list;
652  }
653 #endif
654 
655  TRACE_POSTGRESQL_QUERY_PARSE_DONE(query_string);
656 
657  return raw_parsetree_list;
658 }
659 
660 /*
661  * Given a raw parsetree (gram.y output), and optionally information about
662  * types of parameter symbols ($n), perform parse analysis and rule rewriting.
663  *
664  * A list of Query nodes is returned, since either the analyzer or the
665  * rewriter might expand one query to several.
666  *
667  * NOTE: for reasons mentioned above, this must be separate from raw parsing.
668  */
669 List *
671  const char *query_string,
672  const Oid *paramTypes,
673  int numParams,
674  QueryEnvironment *queryEnv)
675 {
676  Query *query;
677  List *querytree_list;
678 
679  TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
680 
681  /*
682  * (1) Perform parse analysis.
683  */
684  if (log_parser_stats)
685  ResetUsage();
686 
687  query = parse_analyze_fixedparams(parsetree, query_string, paramTypes, numParams,
688  queryEnv);
689 
690  if (log_parser_stats)
691  ShowUsage("PARSE ANALYSIS STATISTICS");
692 
693  /*
694  * (2) Rewrite the queries, as necessary
695  */
696  querytree_list = pg_rewrite_query(query);
697 
698  TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
699 
700  return querytree_list;
701 }
702 
703 /*
704  * Do parse analysis and rewriting. This is the same as
705  * pg_analyze_and_rewrite_fixedparams except that it's okay to deduce
706  * information about $n symbol datatypes from context.
707  */
708 List *
710  const char *query_string,
711  Oid **paramTypes,
712  int *numParams,
713  QueryEnvironment *queryEnv)
714 {
715  Query *query;
716  List *querytree_list;
717 
718  TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
719 
720  /*
721  * (1) Perform parse analysis.
722  */
723  if (log_parser_stats)
724  ResetUsage();
725 
726  query = parse_analyze_varparams(parsetree, query_string, paramTypes, numParams,
727  queryEnv);
728 
729  /*
730  * Check all parameter types got determined.
731  */
732  for (int i = 0; i < *numParams; i++)
733  {
734  Oid ptype = (*paramTypes)[i];
735 
736  if (ptype == InvalidOid || ptype == UNKNOWNOID)
737  ereport(ERROR,
738  (errcode(ERRCODE_INDETERMINATE_DATATYPE),
739  errmsg("could not determine data type of parameter $%d",
740  i + 1)));
741  }
742 
743  if (log_parser_stats)
744  ShowUsage("PARSE ANALYSIS STATISTICS");
745 
746  /*
747  * (2) Rewrite the queries, as necessary
748  */
749  querytree_list = pg_rewrite_query(query);
750 
751  TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
752 
753  return querytree_list;
754 }
755 
756 /*
757  * Do parse analysis and rewriting. This is the same as
758  * pg_analyze_and_rewrite_fixedparams except that, instead of a fixed list of
759  * parameter datatypes, a parser callback is supplied that can do
760  * external-parameter resolution and possibly other things.
761  */
762 List *
764  const char *query_string,
765  ParserSetupHook parserSetup,
766  void *parserSetupArg,
767  QueryEnvironment *queryEnv)
768 {
769  Query *query;
770  List *querytree_list;
771 
772  TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
773 
774  /*
775  * (1) Perform parse analysis.
776  */
777  if (log_parser_stats)
778  ResetUsage();
779 
780  query = parse_analyze_withcb(parsetree, query_string, parserSetup, parserSetupArg,
781  queryEnv);
782 
783  if (log_parser_stats)
784  ShowUsage("PARSE ANALYSIS STATISTICS");
785 
786  /*
787  * (2) Rewrite the queries, as necessary
788  */
789  querytree_list = pg_rewrite_query(query);
790 
791  TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
792 
793  return querytree_list;
794 }
795 
796 /*
797  * Perform rewriting of a query produced by parse analysis.
798  *
799  * Note: query must just have come from the parser, because we do not do
800  * AcquireRewriteLocks() on it.
801  */
802 List *
804 {
805  List *querytree_list;
806 
807  if (Debug_print_parse)
808  elog_node_display(LOG, "parse tree", query,
810 
811  if (log_parser_stats)
812  ResetUsage();
813 
814  if (query->commandType == CMD_UTILITY)
815  {
816  /* don't rewrite utilities, just dump 'em into result list */
817  querytree_list = list_make1(query);
818  }
819  else
820  {
821  /* rewrite regular queries */
822  querytree_list = QueryRewrite(query);
823  }
824 
825  if (log_parser_stats)
826  ShowUsage("REWRITER STATISTICS");
827 
828 #ifdef COPY_PARSE_PLAN_TREES
829  /* Optional debugging check: pass querytree through copyObject() */
830  {
831  List *new_list;
832 
833  new_list = copyObject(querytree_list);
834  /* This checks both copyObject() and the equal() routines... */
835  if (!equal(new_list, querytree_list))
836  elog(WARNING, "copyObject() failed to produce an equal rewritten parse tree");
837  else
838  querytree_list = new_list;
839  }
840 #endif
841 
842 #ifdef WRITE_READ_PARSE_PLAN_TREES
843  /* Optional debugging check: pass querytree through outfuncs/readfuncs */
844  {
845  List *new_list = NIL;
846  ListCell *lc;
847 
848  foreach(lc, querytree_list)
849  {
850  Query *curr_query = lfirst_node(Query, lc);
851  char *str = nodeToString(curr_query);
852  Query *new_query = stringToNodeWithLocations(str);
853 
854  /*
855  * queryId is not saved in stored rules, but we must preserve it
856  * here to avoid breaking pg_stat_statements.
857  */
858  new_query->queryId = curr_query->queryId;
859 
860  new_list = lappend(new_list, new_query);
861  pfree(str);
862  }
863 
864  /* This checks both outfuncs/readfuncs and the equal() routines... */
865  if (!equal(new_list, querytree_list))
866  elog(WARNING, "outfuncs/readfuncs failed to produce an equal rewritten parse tree");
867  else
868  querytree_list = new_list;
869  }
870 #endif
871 
873  elog_node_display(LOG, "rewritten parse tree", querytree_list,
875 
876  return querytree_list;
877 }
878 
879 
880 /*
881  * Generate a plan for a single already-rewritten query.
882  * This is a thin wrapper around planner() and takes the same parameters.
883  */
884 PlannedStmt *
885 pg_plan_query(Query *querytree, const char *query_string, int cursorOptions,
886  ParamListInfo boundParams)
887 {
888  PlannedStmt *plan;
889 
890  /* Utility commands have no plans. */
891  if (querytree->commandType == CMD_UTILITY)
892  return NULL;
893 
894  /* Planner must have a snapshot in case it calls user-defined functions. */
896 
897  TRACE_POSTGRESQL_QUERY_PLAN_START();
898 
899  if (log_planner_stats)
900  ResetUsage();
901 
902  /* call the optimizer */
903  plan = planner(querytree, query_string, cursorOptions, boundParams);
904 
905  if (log_planner_stats)
906  ShowUsage("PLANNER STATISTICS");
907 
908 #ifdef COPY_PARSE_PLAN_TREES
909  /* Optional debugging check: pass plan tree through copyObject() */
910  {
911  PlannedStmt *new_plan = copyObject(plan);
912 
913  /*
914  * equal() currently does not have routines to compare Plan nodes, so
915  * don't try to test equality here. Perhaps fix someday?
916  */
917 #ifdef NOT_USED
918  /* This checks both copyObject() and the equal() routines... */
919  if (!equal(new_plan, plan))
920  elog(WARNING, "copyObject() failed to produce an equal plan tree");
921  else
922 #endif
923  plan = new_plan;
924  }
925 #endif
926 
927 #ifdef WRITE_READ_PARSE_PLAN_TREES
928  /* Optional debugging check: pass plan tree through outfuncs/readfuncs */
929  {
930  char *str;
931  PlannedStmt *new_plan;
932 
933  str = nodeToString(plan);
934  new_plan = stringToNodeWithLocations(str);
935  pfree(str);
936 
937  /*
938  * equal() currently does not have routines to compare Plan nodes, so
939  * don't try to test equality here. Perhaps fix someday?
940  */
941 #ifdef NOT_USED
942  /* This checks both outfuncs/readfuncs and the equal() routines... */
943  if (!equal(new_plan, plan))
944  elog(WARNING, "outfuncs/readfuncs failed to produce an equal plan tree");
945  else
946 #endif
947  plan = new_plan;
948  }
949 #endif
950 
951  /*
952  * Print plan if debugging.
953  */
954  if (Debug_print_plan)
956 
957  TRACE_POSTGRESQL_QUERY_PLAN_DONE();
958 
959  return plan;
960 }
961 
962 /*
963  * Generate plans for a list of already-rewritten queries.
964  *
965  * For normal optimizable statements, invoke the planner. For utility
966  * statements, just make a wrapper PlannedStmt node.
967  *
968  * The result is a list of PlannedStmt nodes.
969  */
970 List *
971 pg_plan_queries(List *querytrees, const char *query_string, int cursorOptions,
972  ParamListInfo boundParams)
973 {
974  List *stmt_list = NIL;
975  ListCell *query_list;
976 
977  foreach(query_list, querytrees)
978  {
979  Query *query = lfirst_node(Query, query_list);
980  PlannedStmt *stmt;
981 
982  if (query->commandType == CMD_UTILITY)
983  {
984  /* Utility commands require no planning. */
986  stmt->commandType = CMD_UTILITY;
987  stmt->canSetTag = query->canSetTag;
988  stmt->utilityStmt = query->utilityStmt;
989  stmt->stmt_location = query->stmt_location;
990  stmt->stmt_len = query->stmt_len;
991  stmt->queryId = query->queryId;
992  }
993  else
994  {
995  stmt = pg_plan_query(query, query_string, cursorOptions,
996  boundParams);
997  }
998 
999  stmt_list = lappend(stmt_list, stmt);
1000  }
1001 
1002  return stmt_list;
1003 }
1004 
1005 
1006 /*
1007  * exec_simple_query
1008  *
1009  * Execute a "simple Query" protocol message.
1010  */
1011 static void
1012 exec_simple_query(const char *query_string)
1013 {
1015  MemoryContext oldcontext;
1016  List *parsetree_list;
1017  ListCell *parsetree_item;
1018  bool save_log_statement_stats = log_statement_stats;
1019  bool was_logged = false;
1020  bool use_implicit_block;
1021  char msec_str[32];
1022 
1023  /*
1024  * Report query to various monitoring facilities.
1025  */
1026  debug_query_string = query_string;
1027 
1028  pgstat_report_activity(STATE_RUNNING, query_string);
1029 
1030  TRACE_POSTGRESQL_QUERY_START(query_string);
1031 
1032  /*
1033  * We use save_log_statement_stats so ShowUsage doesn't report incorrect
1034  * results because ResetUsage wasn't called.
1035  */
1036  if (save_log_statement_stats)
1037  ResetUsage();
1038 
1039  /*
1040  * Start up a transaction command. All queries generated by the
1041  * query_string will be in this same command block, *unless* we find a
1042  * BEGIN/COMMIT/ABORT statement; we have to force a new xact command after
1043  * one of those, else bad things will happen in xact.c. (Note that this
1044  * will normally change current memory context.)
1045  */
1047 
1048  /*
1049  * Zap any pre-existing unnamed statement. (While not strictly necessary,
1050  * it seems best to define simple-Query mode as if it used the unnamed
1051  * statement and portal; this ensures we recover any storage used by prior
1052  * unnamed operations.)
1053  */
1055 
1056  /*
1057  * Switch to appropriate context for constructing parsetrees.
1058  */
1059  oldcontext = MemoryContextSwitchTo(MessageContext);
1060 
1061  /*
1062  * Do basic parsing of the query or queries (this should be safe even if
1063  * we are in aborted transaction state!)
1064  */
1065  parsetree_list = pg_parse_query(query_string);
1066 
1067  /* Log immediately if dictated by log_statement */
1068  if (check_log_statement(parsetree_list))
1069  {
1070  ereport(LOG,
1071  (errmsg("statement: %s", query_string),
1072  errhidestmt(true),
1073  errdetail_execute(parsetree_list)));
1074  was_logged = true;
1075  }
1076 
1077  /*
1078  * Switch back to transaction context to enter the loop.
1079  */
1080  MemoryContextSwitchTo(oldcontext);
1081 
1082  /*
1083  * For historical reasons, if multiple SQL statements are given in a
1084  * single "simple Query" message, we execute them as a single transaction,
1085  * unless explicit transaction control commands are included to make
1086  * portions of the list be separate transactions. To represent this
1087  * behavior properly in the transaction machinery, we use an "implicit"
1088  * transaction block.
1089  */
1090  use_implicit_block = (list_length(parsetree_list) > 1);
1091 
1092  /*
1093  * Run through the raw parsetree(s) and process each one.
1094  */
1095  foreach(parsetree_item, parsetree_list)
1096  {
1097  RawStmt *parsetree = lfirst_node(RawStmt, parsetree_item);
1098  bool snapshot_set = false;
1099  CommandTag commandTag;
1100  QueryCompletion qc;
1101  MemoryContext per_parsetree_context = NULL;
1102  List *querytree_list,
1103  *plantree_list;
1104  Portal portal;
1105  DestReceiver *receiver;
1106  int16 format;
1107  const char *cmdtagname;
1108  size_t cmdtaglen;
1109 
1110  pgstat_report_query_id(0, true);
1111 
1112  /*
1113  * Get the command name for use in status display (it also becomes the
1114  * default completion tag, down inside PortalRun). Set ps_status and
1115  * do any special start-of-SQL-command processing needed by the
1116  * destination.
1117  */
1118  commandTag = CreateCommandTag(parsetree->stmt);
1119  cmdtagname = GetCommandTagNameAndLen(commandTag, &cmdtaglen);
1120 
1121  set_ps_display_with_len(cmdtagname, cmdtaglen);
1122 
1123  BeginCommand(commandTag, dest);
1124 
1125  /*
1126  * If we are in an aborted transaction, reject all commands except
1127  * COMMIT/ABORT. It is important that this test occur before we try
1128  * to do parse analysis, rewrite, or planning, since all those phases
1129  * try to do database accesses, which may fail in abort state. (It
1130  * might be safe to allow some additional utility commands in this
1131  * state, but not many...)
1132  */
1134  !IsTransactionExitStmt(parsetree->stmt))
1135  ereport(ERROR,
1136  (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1137  errmsg("current transaction is aborted, "
1138  "commands ignored until end of transaction block"),
1139  errdetail_abort()));
1140 
1141  /* Make sure we are in a transaction command */
1143 
1144  /*
1145  * If using an implicit transaction block, and we're not already in a
1146  * transaction block, start an implicit block to force this statement
1147  * to be grouped together with any following ones. (We must do this
1148  * each time through the loop; otherwise, a COMMIT/ROLLBACK in the
1149  * list would cause later statements to not be grouped.)
1150  */
1151  if (use_implicit_block)
1153 
1154  /* If we got a cancel signal in parsing or prior command, quit */
1156 
1157  /*
1158  * Set up a snapshot if parse analysis/planning will need one.
1159  */
1160  if (analyze_requires_snapshot(parsetree))
1161  {
1163  snapshot_set = true;
1164  }
1165 
1166  /*
1167  * OK to analyze, rewrite, and plan this query.
1168  *
1169  * Switch to appropriate context for constructing query and plan trees
1170  * (these can't be in the transaction context, as that will get reset
1171  * when the command is COMMIT/ROLLBACK). If we have multiple
1172  * parsetrees, we use a separate context for each one, so that we can
1173  * free that memory before moving on to the next one. But for the
1174  * last (or only) parsetree, just use MessageContext, which will be
1175  * reset shortly after completion anyway. In event of an error, the
1176  * per_parsetree_context will be deleted when MessageContext is reset.
1177  */
1178  if (lnext(parsetree_list, parsetree_item) != NULL)
1179  {
1180  per_parsetree_context =
1182  "per-parsetree message context",
1184  oldcontext = MemoryContextSwitchTo(per_parsetree_context);
1185  }
1186  else
1187  oldcontext = MemoryContextSwitchTo(MessageContext);
1188 
1189  querytree_list = pg_analyze_and_rewrite_fixedparams(parsetree, query_string,
1190  NULL, 0, NULL);
1191 
1192  plantree_list = pg_plan_queries(querytree_list, query_string,
1193  CURSOR_OPT_PARALLEL_OK, NULL);
1194 
1195  /*
1196  * Done with the snapshot used for parsing/planning.
1197  *
1198  * While it looks promising to reuse the same snapshot for query
1199  * execution (at least for simple protocol), unfortunately it causes
1200  * execution to use a snapshot that has been acquired before locking
1201  * any of the tables mentioned in the query. This creates user-
1202  * visible anomalies, so refrain. Refer to
1203  * https://postgr.es/m/flat/5075D8DF.6050500@fuzzy.cz for details.
1204  */
1205  if (snapshot_set)
1207 
1208  /* If we got a cancel signal in analysis or planning, quit */
1210 
1211  /*
1212  * Create unnamed portal to run the query or queries in. If there
1213  * already is one, silently drop it.
1214  */
1215  portal = CreatePortal("", true, true);
1216  /* Don't display the portal in pg_cursors */
1217  portal->visible = false;
1218 
1219  /*
1220  * We don't have to copy anything into the portal, because everything
1221  * we are passing here is in MessageContext or the
1222  * per_parsetree_context, and so will outlive the portal anyway.
1223  */
1224  PortalDefineQuery(portal,
1225  NULL,
1226  query_string,
1227  commandTag,
1228  plantree_list,
1229  NULL);
1230 
1231  /*
1232  * Start the portal. No parameters here.
1233  */
1234  PortalStart(portal, NULL, 0, InvalidSnapshot);
1235 
1236  /*
1237  * Select the appropriate output format: text unless we are doing a
1238  * FETCH from a binary cursor. (Pretty grotty to have to do this here
1239  * --- but it avoids grottiness in other places. Ah, the joys of
1240  * backward compatibility...)
1241  */
1242  format = 0; /* TEXT is default */
1243  if (IsA(parsetree->stmt, FetchStmt))
1244  {
1245  FetchStmt *stmt = (FetchStmt *) parsetree->stmt;
1246 
1247  if (!stmt->ismove)
1248  {
1249  Portal fportal = GetPortalByName(stmt->portalname);
1250 
1251  if (PortalIsValid(fportal) &&
1252  (fportal->cursorOptions & CURSOR_OPT_BINARY))
1253  format = 1; /* BINARY */
1254  }
1255  }
1256  PortalSetResultFormat(portal, 1, &format);
1257 
1258  /*
1259  * Now we can create the destination receiver object.
1260  */
1261  receiver = CreateDestReceiver(dest);
1262  if (dest == DestRemote)
1263  SetRemoteDestReceiverParams(receiver, portal);
1264 
1265  /*
1266  * Switch back to transaction context for execution.
1267  */
1268  MemoryContextSwitchTo(oldcontext);
1269 
1270  /*
1271  * Run the portal to completion, and then drop it (and the receiver).
1272  */
1273  (void) PortalRun(portal,
1274  FETCH_ALL,
1275  true, /* always top level */
1276  true,
1277  receiver,
1278  receiver,
1279  &qc);
1280 
1281  receiver->rDestroy(receiver);
1282 
1283  PortalDrop(portal, false);
1284 
1285  if (lnext(parsetree_list, parsetree_item) == NULL)
1286  {
1287  /*
1288  * If this is the last parsetree of the query string, close down
1289  * transaction statement before reporting command-complete. This
1290  * is so that any end-of-transaction errors are reported before
1291  * the command-complete message is issued, to avoid confusing
1292  * clients who will expect either a command-complete message or an
1293  * error, not one and then the other. Also, if we're using an
1294  * implicit transaction block, we must close that out first.
1295  */
1296  if (use_implicit_block)
1299  }
1300  else if (IsA(parsetree->stmt, TransactionStmt))
1301  {
1302  /*
1303  * If this was a transaction control statement, commit it. We will
1304  * start a new xact command for the next command.
1305  */
1307  }
1308  else
1309  {
1310  /*
1311  * We had better not see XACT_FLAGS_NEEDIMMEDIATECOMMIT set if
1312  * we're not calling finish_xact_command(). (The implicit
1313  * transaction block should have prevented it from getting set.)
1314  */
1316 
1317  /*
1318  * We need a CommandCounterIncrement after every query, except
1319  * those that start or end a transaction block.
1320  */
1322 
1323  /*
1324  * Disable statement timeout between queries of a multi-query
1325  * string, so that the timeout applies separately to each query.
1326  * (Our next loop iteration will start a fresh timeout.)
1327  */
1329  }
1330 
1331  /*
1332  * Tell client that we're done with this query. Note we emit exactly
1333  * one EndCommand report for each raw parsetree, thus one for each SQL
1334  * command the client sent, regardless of rewriting. (But a command
1335  * aborted by error will not send an EndCommand report at all.)
1336  */
1337  EndCommand(&qc, dest, false);
1338 
1339  /* Now we may drop the per-parsetree context, if one was created. */
1340  if (per_parsetree_context)
1341  MemoryContextDelete(per_parsetree_context);
1342  } /* end loop over parsetrees */
1343 
1344  /*
1345  * Close down transaction statement, if one is open. (This will only do
1346  * something if the parsetree list was empty; otherwise the last loop
1347  * iteration already did it.)
1348  */
1350 
1351  /*
1352  * If there were no parsetrees, return EmptyQueryResponse message.
1353  */
1354  if (!parsetree_list)
1355  NullCommand(dest);
1356 
1357  /*
1358  * Emit duration logging if appropriate.
1359  */
1360  switch (check_log_duration(msec_str, was_logged))
1361  {
1362  case 1:
1363  ereport(LOG,
1364  (errmsg("duration: %s ms", msec_str),
1365  errhidestmt(true)));
1366  break;
1367  case 2:
1368  ereport(LOG,
1369  (errmsg("duration: %s ms statement: %s",
1370  msec_str, query_string),
1371  errhidestmt(true),
1372  errdetail_execute(parsetree_list)));
1373  break;
1374  }
1375 
1376  if (save_log_statement_stats)
1377  ShowUsage("QUERY STATISTICS");
1378 
1379  TRACE_POSTGRESQL_QUERY_DONE(query_string);
1380 
1381  debug_query_string = NULL;
1382 }
1383 
1384 /*
1385  * exec_parse_message
1386  *
1387  * Execute a "Parse" protocol message.
1388  */
1389 static void
1390 exec_parse_message(const char *query_string, /* string to execute */
1391  const char *stmt_name, /* name for prepared stmt */
1392  Oid *paramTypes, /* parameter types */
1393  int numParams) /* number of parameters */
1394 {
1395  MemoryContext unnamed_stmt_context = NULL;
1396  MemoryContext oldcontext;
1397  List *parsetree_list;
1398  RawStmt *raw_parse_tree;
1399  List *querytree_list;
1400  CachedPlanSource *psrc;
1401  bool is_named;
1402  bool save_log_statement_stats = log_statement_stats;
1403  char msec_str[32];
1404 
1405  /*
1406  * Report query to various monitoring facilities.
1407  */
1408  debug_query_string = query_string;
1409 
1410  pgstat_report_activity(STATE_RUNNING, query_string);
1411 
1412  set_ps_display("PARSE");
1413 
1414  if (save_log_statement_stats)
1415  ResetUsage();
1416 
1417  ereport(DEBUG2,
1418  (errmsg_internal("parse %s: %s",
1419  *stmt_name ? stmt_name : "<unnamed>",
1420  query_string)));
1421 
1422  /*
1423  * Start up a transaction command so we can run parse analysis etc. (Note
1424  * that this will normally change current memory context.) Nothing happens
1425  * if we are already in one. This also arms the statement timeout if
1426  * necessary.
1427  */
1429 
1430  /*
1431  * Switch to appropriate context for constructing parsetrees.
1432  *
1433  * We have two strategies depending on whether the prepared statement is
1434  * named or not. For a named prepared statement, we do parsing in
1435  * MessageContext and copy the finished trees into the prepared
1436  * statement's plancache entry; then the reset of MessageContext releases
1437  * temporary space used by parsing and rewriting. For an unnamed prepared
1438  * statement, we assume the statement isn't going to hang around long, so
1439  * getting rid of temp space quickly is probably not worth the costs of
1440  * copying parse trees. So in this case, we create the plancache entry's
1441  * query_context here, and do all the parsing work therein.
1442  */
1443  is_named = (stmt_name[0] != '\0');
1444  if (is_named)
1445  {
1446  /* Named prepared statement --- parse in MessageContext */
1447  oldcontext = MemoryContextSwitchTo(MessageContext);
1448  }
1449  else
1450  {
1451  /* Unnamed prepared statement --- release any prior unnamed stmt */
1453  /* Create context for parsing */
1454  unnamed_stmt_context =
1456  "unnamed prepared statement",
1458  oldcontext = MemoryContextSwitchTo(unnamed_stmt_context);
1459  }
1460 
1461  /*
1462  * Do basic parsing of the query or queries (this should be safe even if
1463  * we are in aborted transaction state!)
1464  */
1465  parsetree_list = pg_parse_query(query_string);
1466 
1467  /*
1468  * We only allow a single user statement in a prepared statement. This is
1469  * mainly to keep the protocol simple --- otherwise we'd need to worry
1470  * about multiple result tupdescs and things like that.
1471  */
1472  if (list_length(parsetree_list) > 1)
1473  ereport(ERROR,
1474  (errcode(ERRCODE_SYNTAX_ERROR),
1475  errmsg("cannot insert multiple commands into a prepared statement")));
1476 
1477  if (parsetree_list != NIL)
1478  {
1479  bool snapshot_set = false;
1480 
1481  raw_parse_tree = linitial_node(RawStmt, parsetree_list);
1482 
1483  /*
1484  * If we are in an aborted transaction, reject all commands except
1485  * COMMIT/ROLLBACK. It is important that this test occur before we
1486  * try to do parse analysis, rewrite, or planning, since all those
1487  * phases try to do database accesses, which may fail in abort state.
1488  * (It might be safe to allow some additional utility commands in this
1489  * state, but not many...)
1490  */
1492  !IsTransactionExitStmt(raw_parse_tree->stmt))
1493  ereport(ERROR,
1494  (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1495  errmsg("current transaction is aborted, "
1496  "commands ignored until end of transaction block"),
1497  errdetail_abort()));
1498 
1499  /*
1500  * Create the CachedPlanSource before we do parse analysis, since it
1501  * needs to see the unmodified raw parse tree.
1502  */
1503  psrc = CreateCachedPlan(raw_parse_tree, query_string,
1504  CreateCommandTag(raw_parse_tree->stmt));
1505 
1506  /*
1507  * Set up a snapshot if parse analysis will need one.
1508  */
1509  if (analyze_requires_snapshot(raw_parse_tree))
1510  {
1512  snapshot_set = true;
1513  }
1514 
1515  /*
1516  * Analyze and rewrite the query. Note that the originally specified
1517  * parameter set is not required to be complete, so we have to use
1518  * pg_analyze_and_rewrite_varparams().
1519  */
1520  querytree_list = pg_analyze_and_rewrite_varparams(raw_parse_tree,
1521  query_string,
1522  &paramTypes,
1523  &numParams,
1524  NULL);
1525 
1526  /* Done with the snapshot used for parsing */
1527  if (snapshot_set)
1529  }
1530  else
1531  {
1532  /* Empty input string. This is legal. */
1533  raw_parse_tree = NULL;
1534  psrc = CreateCachedPlan(raw_parse_tree, query_string,
1535  CMDTAG_UNKNOWN);
1536  querytree_list = NIL;
1537  }
1538 
1539  /*
1540  * CachedPlanSource must be a direct child of MessageContext before we
1541  * reparent unnamed_stmt_context under it, else we have a disconnected
1542  * circular subgraph. Klugy, but less so than flipping contexts even more
1543  * above.
1544  */
1545  if (unnamed_stmt_context)
1547 
1548  /* Finish filling in the CachedPlanSource */
1549  CompleteCachedPlan(psrc,
1550  querytree_list,
1551  unnamed_stmt_context,
1552  paramTypes,
1553  numParams,
1554  NULL,
1555  NULL,
1556  CURSOR_OPT_PARALLEL_OK, /* allow parallel mode */
1557  true); /* fixed result */
1558 
1559  /* If we got a cancel signal during analysis, quit */
1561 
1562  if (is_named)
1563  {
1564  /*
1565  * Store the query as a prepared statement.
1566  */
1567  StorePreparedStatement(stmt_name, psrc, false);
1568  }
1569  else
1570  {
1571  /*
1572  * We just save the CachedPlanSource into unnamed_stmt_psrc.
1573  */
1574  SaveCachedPlan(psrc);
1575  unnamed_stmt_psrc = psrc;
1576  }
1577 
1578  MemoryContextSwitchTo(oldcontext);
1579 
1580  /*
1581  * We do NOT close the open transaction command here; that only happens
1582  * when the client sends Sync. Instead, do CommandCounterIncrement just
1583  * in case something happened during parse/plan.
1584  */
1586 
1587  /*
1588  * Send ParseComplete.
1589  */
1592 
1593  /*
1594  * Emit duration logging if appropriate.
1595  */
1596  switch (check_log_duration(msec_str, false))
1597  {
1598  case 1:
1599  ereport(LOG,
1600  (errmsg("duration: %s ms", msec_str),
1601  errhidestmt(true)));
1602  break;
1603  case 2:
1604  ereport(LOG,
1605  (errmsg("duration: %s ms parse %s: %s",
1606  msec_str,
1607  *stmt_name ? stmt_name : "<unnamed>",
1608  query_string),
1609  errhidestmt(true)));
1610  break;
1611  }
1612 
1613  if (save_log_statement_stats)
1614  ShowUsage("PARSE MESSAGE STATISTICS");
1615 
1616  debug_query_string = NULL;
1617 }
1618 
1619 /*
1620  * exec_bind_message
1621  *
1622  * Process a "Bind" message to create a portal from a prepared statement
1623  */
1624 static void
1626 {
1627  const char *portal_name;
1628  const char *stmt_name;
1629  int numPFormats;
1630  int16 *pformats = NULL;
1631  int numParams;
1632  int numRFormats;
1633  int16 *rformats = NULL;
1634  CachedPlanSource *psrc;
1635  CachedPlan *cplan;
1636  Portal portal;
1637  char *query_string;
1638  char *saved_stmt_name;
1639  ParamListInfo params;
1640  MemoryContext oldContext;
1641  bool save_log_statement_stats = log_statement_stats;
1642  bool snapshot_set = false;
1643  char msec_str[32];
1644  ParamsErrorCbData params_data;
1645  ErrorContextCallback params_errcxt;
1646 
1647  /* Get the fixed part of the message */
1648  portal_name = pq_getmsgstring(input_message);
1649  stmt_name = pq_getmsgstring(input_message);
1650 
1651  ereport(DEBUG2,
1652  (errmsg_internal("bind %s to %s",
1653  *portal_name ? portal_name : "<unnamed>",
1654  *stmt_name ? stmt_name : "<unnamed>")));
1655 
1656  /* Find prepared statement */
1657  if (stmt_name[0] != '\0')
1658  {
1659  PreparedStatement *pstmt;
1660 
1661  pstmt = FetchPreparedStatement(stmt_name, true);
1662  psrc = pstmt->plansource;
1663  }
1664  else
1665  {
1666  /* special-case the unnamed statement */
1667  psrc = unnamed_stmt_psrc;
1668  if (!psrc)
1669  ereport(ERROR,
1670  (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
1671  errmsg("unnamed prepared statement does not exist")));
1672  }
1673 
1674  /*
1675  * Report query to various monitoring facilities.
1676  */
1678 
1680 
1681  set_ps_display("BIND");
1682 
1683  if (save_log_statement_stats)
1684  ResetUsage();
1685 
1686  /*
1687  * Start up a transaction command so we can call functions etc. (Note that
1688  * this will normally change current memory context.) Nothing happens if
1689  * we are already in one. This also arms the statement timeout if
1690  * necessary.
1691  */
1693 
1694  /* Switch back to message context */
1696 
1697  /* Get the parameter format codes */
1698  numPFormats = pq_getmsgint(input_message, 2);
1699  if (numPFormats > 0)
1700  {
1701  pformats = palloc_array(int16, numPFormats);
1702  for (int i = 0; i < numPFormats; i++)
1703  pformats[i] = pq_getmsgint(input_message, 2);
1704  }
1705 
1706  /* Get the parameter value count */
1707  numParams = pq_getmsgint(input_message, 2);
1708 
1709  if (numPFormats > 1 && numPFormats != numParams)
1710  ereport(ERROR,
1711  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1712  errmsg("bind message has %d parameter formats but %d parameters",
1713  numPFormats, numParams)));
1714 
1715  if (numParams != psrc->num_params)
1716  ereport(ERROR,
1717  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1718  errmsg("bind message supplies %d parameters, but prepared statement \"%s\" requires %d",
1719  numParams, stmt_name, psrc->num_params)));
1720 
1721  /*
1722  * If we are in aborted transaction state, the only portals we can
1723  * actually run are those containing COMMIT or ROLLBACK commands. We
1724  * disallow binding anything else to avoid problems with infrastructure
1725  * that expects to run inside a valid transaction. We also disallow
1726  * binding any parameters, since we can't risk calling user-defined I/O
1727  * functions.
1728  */
1730  (!(psrc->raw_parse_tree &&
1732  numParams != 0))
1733  ereport(ERROR,
1734  (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1735  errmsg("current transaction is aborted, "
1736  "commands ignored until end of transaction block"),
1737  errdetail_abort()));
1738 
1739  /*
1740  * Create the portal. Allow silent replacement of an existing portal only
1741  * if the unnamed portal is specified.
1742  */
1743  if (portal_name[0] == '\0')
1744  portal = CreatePortal(portal_name, true, true);
1745  else
1746  portal = CreatePortal(portal_name, false, false);
1747 
1748  /*
1749  * Prepare to copy stuff into the portal's memory context. We do all this
1750  * copying first, because it could possibly fail (out-of-memory) and we
1751  * don't want a failure to occur between GetCachedPlan and
1752  * PortalDefineQuery; that would result in leaking our plancache refcount.
1753  */
1754  oldContext = MemoryContextSwitchTo(portal->portalContext);
1755 
1756  /* Copy the plan's query string into the portal */
1757  query_string = pstrdup(psrc->query_string);
1758 
1759  /* Likewise make a copy of the statement name, unless it's unnamed */
1760  if (stmt_name[0])
1761  saved_stmt_name = pstrdup(stmt_name);
1762  else
1763  saved_stmt_name = NULL;
1764 
1765  /*
1766  * Set a snapshot if we have parameters to fetch (since the input
1767  * functions might need it) or the query isn't a utility command (and
1768  * hence could require redoing parse analysis and planning). We keep the
1769  * snapshot active till we're done, so that plancache.c doesn't have to
1770  * take new ones.
1771  */
1772  if (numParams > 0 ||
1773  (psrc->raw_parse_tree &&
1775  {
1777  snapshot_set = true;
1778  }
1779 
1780  /*
1781  * Fetch parameters, if any, and store in the portal's memory context.
1782  */
1783  if (numParams > 0)
1784  {
1785  char **knownTextValues = NULL; /* allocate on first use */
1786  BindParamCbData one_param_data;
1787 
1788  /*
1789  * Set up an error callback so that if there's an error in this phase,
1790  * we can report the specific parameter causing the problem.
1791  */
1792  one_param_data.portalName = portal->name;
1793  one_param_data.paramno = -1;
1794  one_param_data.paramval = NULL;
1795  params_errcxt.previous = error_context_stack;
1796  params_errcxt.callback = bind_param_error_callback;
1797  params_errcxt.arg = (void *) &one_param_data;
1798  error_context_stack = &params_errcxt;
1799 
1800  params = makeParamList(numParams);
1801 
1802  for (int paramno = 0; paramno < numParams; paramno++)
1803  {
1804  Oid ptype = psrc->param_types[paramno];
1805  int32 plength;
1806  Datum pval;
1807  bool isNull;
1808  StringInfoData pbuf;
1809  char csave;
1810  int16 pformat;
1811 
1812  one_param_data.paramno = paramno;
1813  one_param_data.paramval = NULL;
1814 
1815  plength = pq_getmsgint(input_message, 4);
1816  isNull = (plength == -1);
1817 
1818  if (!isNull)
1819  {
1820  char *pvalue;
1821 
1822  /*
1823  * Rather than copying data around, we just initialize a
1824  * StringInfo pointing to the correct portion of the message
1825  * buffer. We assume we can scribble on the message buffer to
1826  * add a trailing NUL which is required for the input function
1827  * call.
1828  */
1829  pvalue = unconstify(char *, pq_getmsgbytes(input_message, plength));
1830  csave = pvalue[plength];
1831  pvalue[plength] = '\0';
1832  initReadOnlyStringInfo(&pbuf, pvalue, plength);
1833  }
1834  else
1835  {
1836  pbuf.data = NULL; /* keep compiler quiet */
1837  csave = 0;
1838  }
1839 
1840  if (numPFormats > 1)
1841  pformat = pformats[paramno];
1842  else if (numPFormats > 0)
1843  pformat = pformats[0];
1844  else
1845  pformat = 0; /* default = text */
1846 
1847  if (pformat == 0) /* text mode */
1848  {
1849  Oid typinput;
1850  Oid typioparam;
1851  char *pstring;
1852 
1853  getTypeInputInfo(ptype, &typinput, &typioparam);
1854 
1855  /*
1856  * We have to do encoding conversion before calling the
1857  * typinput routine.
1858  */
1859  if (isNull)
1860  pstring = NULL;
1861  else
1862  pstring = pg_client_to_server(pbuf.data, plength);
1863 
1864  /* Now we can log the input string in case of error */
1865  one_param_data.paramval = pstring;
1866 
1867  pval = OidInputFunctionCall(typinput, pstring, typioparam, -1);
1868 
1869  one_param_data.paramval = NULL;
1870 
1871  /*
1872  * If we might need to log parameters later, save a copy of
1873  * the converted string in MessageContext; then free the
1874  * result of encoding conversion, if any was done.
1875  */
1876  if (pstring)
1877  {
1879  {
1880  MemoryContext oldcxt;
1881 
1883 
1884  if (knownTextValues == NULL)
1885  knownTextValues = palloc0_array(char *, numParams);
1886 
1888  knownTextValues[paramno] = pstrdup(pstring);
1889  else
1890  {
1891  /*
1892  * We can trim the saved string, knowing that we
1893  * won't print all of it. But we must copy at
1894  * least two more full characters than
1895  * BuildParamLogString wants to use; otherwise it
1896  * might fail to include the trailing ellipsis.
1897  */
1898  knownTextValues[paramno] =
1899  pnstrdup(pstring,
1901  + 2 * MAX_MULTIBYTE_CHAR_LEN);
1902  }
1903 
1904  MemoryContextSwitchTo(oldcxt);
1905  }
1906  if (pstring != pbuf.data)
1907  pfree(pstring);
1908  }
1909  }
1910  else if (pformat == 1) /* binary mode */
1911  {
1912  Oid typreceive;
1913  Oid typioparam;
1914  StringInfo bufptr;
1915 
1916  /*
1917  * Call the parameter type's binary input converter
1918  */
1919  getTypeBinaryInputInfo(ptype, &typreceive, &typioparam);
1920 
1921  if (isNull)
1922  bufptr = NULL;
1923  else
1924  bufptr = &pbuf;
1925 
1926  pval = OidReceiveFunctionCall(typreceive, bufptr, typioparam, -1);
1927 
1928  /* Trouble if it didn't eat the whole buffer */
1929  if (!isNull && pbuf.cursor != pbuf.len)
1930  ereport(ERROR,
1931  (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
1932  errmsg("incorrect binary data format in bind parameter %d",
1933  paramno + 1)));
1934  }
1935  else
1936  {
1937  ereport(ERROR,
1938  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1939  errmsg("unsupported format code: %d",
1940  pformat)));
1941  pval = 0; /* keep compiler quiet */
1942  }
1943 
1944  /* Restore message buffer contents */
1945  if (!isNull)
1946  pbuf.data[plength] = csave;
1947 
1948  params->params[paramno].value = pval;
1949  params->params[paramno].isnull = isNull;
1950 
1951  /*
1952  * We mark the params as CONST. This ensures that any custom plan
1953  * makes full use of the parameter values.
1954  */
1955  params->params[paramno].pflags = PARAM_FLAG_CONST;
1956  params->params[paramno].ptype = ptype;
1957  }
1958 
1959  /* Pop the per-parameter error callback */
1961 
1962  /*
1963  * Once all parameters have been received, prepare for printing them
1964  * in future errors, if configured to do so. (This is saved in the
1965  * portal, so that they'll appear when the query is executed later.)
1966  */
1968  params->paramValuesStr =
1969  BuildParamLogString(params,
1970  knownTextValues,
1972  }
1973  else
1974  params = NULL;
1975 
1976  /* Done storing stuff in portal's context */
1977  MemoryContextSwitchTo(oldContext);
1978 
1979  /*
1980  * Set up another error callback so that all the parameters are logged if
1981  * we get an error during the rest of the BIND processing.
1982  */
1983  params_data.portalName = portal->name;
1984  params_data.params = params;
1985  params_errcxt.previous = error_context_stack;
1986  params_errcxt.callback = ParamsErrorCallback;
1987  params_errcxt.arg = (void *) &params_data;
1988  error_context_stack = &params_errcxt;
1989 
1990  /* Get the result format codes */
1991  numRFormats = pq_getmsgint(input_message, 2);
1992  if (numRFormats > 0)
1993  {
1994  rformats = palloc_array(int16, numRFormats);
1995  for (int i = 0; i < numRFormats; i++)
1996  rformats[i] = pq_getmsgint(input_message, 2);
1997  }
1998 
1999  pq_getmsgend(input_message);
2000 
2001  /*
2002  * Obtain a plan from the CachedPlanSource. Any cruft from (re)planning
2003  * will be generated in MessageContext. The plan refcount will be
2004  * assigned to the Portal, so it will be released at portal destruction.
2005  */
2006  cplan = GetCachedPlan(psrc, params, NULL, NULL);
2007 
2008  /*
2009  * Now we can define the portal.
2010  *
2011  * DO NOT put any code that could possibly throw an error between the
2012  * above GetCachedPlan call and here.
2013  */
2014  PortalDefineQuery(portal,
2015  saved_stmt_name,
2016  query_string,
2017  psrc->commandTag,
2018  cplan->stmt_list,
2019  cplan);
2020 
2021  /* Done with the snapshot used for parameter I/O and parsing/planning */
2022  if (snapshot_set)
2024 
2025  /*
2026  * And we're ready to start portal execution.
2027  */
2028  PortalStart(portal, params, 0, InvalidSnapshot);
2029 
2030  /*
2031  * Apply the result format requests to the portal.
2032  */
2033  PortalSetResultFormat(portal, numRFormats, rformats);
2034 
2035  /*
2036  * Done binding; remove the parameters error callback. Entries emitted
2037  * later determine independently whether to log the parameters or not.
2038  */
2040 
2041  /*
2042  * Send BindComplete.
2043  */
2046 
2047  /*
2048  * Emit duration logging if appropriate.
2049  */
2050  switch (check_log_duration(msec_str, false))
2051  {
2052  case 1:
2053  ereport(LOG,
2054  (errmsg("duration: %s ms", msec_str),
2055  errhidestmt(true)));
2056  break;
2057  case 2:
2058  ereport(LOG,
2059  (errmsg("duration: %s ms bind %s%s%s: %s",
2060  msec_str,
2061  *stmt_name ? stmt_name : "<unnamed>",
2062  *portal_name ? "/" : "",
2063  *portal_name ? portal_name : "",
2064  psrc->query_string),
2065  errhidestmt(true),
2066  errdetail_params(params)));
2067  break;
2068  }
2069 
2070  if (save_log_statement_stats)
2071  ShowUsage("BIND MESSAGE STATISTICS");
2072 
2074 
2075  debug_query_string = NULL;
2076 }
2077 
2078 /*
2079  * exec_execute_message
2080  *
2081  * Process an "Execute" message for a portal
2082  */
2083 static void
2084 exec_execute_message(const char *portal_name, long max_rows)
2085 {
2086  CommandDest dest;
2087  DestReceiver *receiver;
2088  Portal portal;
2089  bool completed;
2090  QueryCompletion qc;
2091  const char *sourceText;
2092  const char *prepStmtName;
2093  ParamListInfo portalParams;
2094  bool save_log_statement_stats = log_statement_stats;
2095  bool is_xact_command;
2096  bool execute_is_fetch;
2097  bool was_logged = false;
2098  char msec_str[32];
2099  ParamsErrorCbData params_data;
2100  ErrorContextCallback params_errcxt;
2101  const char *cmdtagname;
2102  size_t cmdtaglen;
2103 
2104  /* Adjust destination to tell printtup.c what to do */
2106  if (dest == DestRemote)
2108 
2109  portal = GetPortalByName(portal_name);
2110  if (!PortalIsValid(portal))
2111  ereport(ERROR,
2112  (errcode(ERRCODE_UNDEFINED_CURSOR),
2113  errmsg("portal \"%s\" does not exist", portal_name)));
2114 
2115  /*
2116  * If the original query was a null string, just return
2117  * EmptyQueryResponse.
2118  */
2119  if (portal->commandTag == CMDTAG_UNKNOWN)
2120  {
2121  Assert(portal->stmts == NIL);
2122  NullCommand(dest);
2123  return;
2124  }
2125 
2126  /* Does the portal contain a transaction command? */
2127  is_xact_command = IsTransactionStmtList(portal->stmts);
2128 
2129  /*
2130  * We must copy the sourceText and prepStmtName into MessageContext in
2131  * case the portal is destroyed during finish_xact_command. We do not
2132  * make a copy of the portalParams though, preferring to just not print
2133  * them in that case.
2134  */
2135  sourceText = pstrdup(portal->sourceText);
2136  if (portal->prepStmtName)
2137  prepStmtName = pstrdup(portal->prepStmtName);
2138  else
2139  prepStmtName = "<unnamed>";
2140  portalParams = portal->portalParams;
2141 
2142  /*
2143  * Report query to various monitoring facilities.
2144  */
2145  debug_query_string = sourceText;
2146 
2148 
2149  cmdtagname = GetCommandTagNameAndLen(portal->commandTag, &cmdtaglen);
2150 
2151  set_ps_display_with_len(cmdtagname, cmdtaglen);
2152 
2153  if (save_log_statement_stats)
2154  ResetUsage();
2155 
2156  BeginCommand(portal->commandTag, dest);
2157 
2158  /*
2159  * Create dest receiver in MessageContext (we don't want it in transaction
2160  * context, because that may get deleted if portal contains VACUUM).
2161  */
2162  receiver = CreateDestReceiver(dest);
2163  if (dest == DestRemoteExecute)
2164  SetRemoteDestReceiverParams(receiver, portal);
2165 
2166  /*
2167  * Ensure we are in a transaction command (this should normally be the
2168  * case already due to prior BIND).
2169  */
2171 
2172  /*
2173  * If we re-issue an Execute protocol request against an existing portal,
2174  * then we are only fetching more rows rather than completely re-executing
2175  * the query from the start. atStart is never reset for a v3 portal, so we
2176  * are safe to use this check.
2177  */
2178  execute_is_fetch = !portal->atStart;
2179 
2180  /* Log immediately if dictated by log_statement */
2181  if (check_log_statement(portal->stmts))
2182  {
2183  ereport(LOG,
2184  (errmsg("%s %s%s%s: %s",
2185  execute_is_fetch ?
2186  _("execute fetch from") :
2187  _("execute"),
2188  prepStmtName,
2189  *portal_name ? "/" : "",
2190  *portal_name ? portal_name : "",
2191  sourceText),
2192  errhidestmt(true),
2193  errdetail_params(portalParams)));
2194  was_logged = true;
2195  }
2196 
2197  /*
2198  * If we are in aborted transaction state, the only portals we can
2199  * actually run are those containing COMMIT or ROLLBACK commands.
2200  */
2202  !IsTransactionExitStmtList(portal->stmts))
2203  ereport(ERROR,
2204  (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2205  errmsg("current transaction is aborted, "
2206  "commands ignored until end of transaction block"),
2207  errdetail_abort()));
2208 
2209  /* Check for cancel signal before we start execution */
2211 
2212  /*
2213  * Okay to run the portal. Set the error callback so that parameters are
2214  * logged. The parameters must have been saved during the bind phase.
2215  */
2216  params_data.portalName = portal->name;
2217  params_data.params = portalParams;
2218  params_errcxt.previous = error_context_stack;
2219  params_errcxt.callback = ParamsErrorCallback;
2220  params_errcxt.arg = (void *) &params_data;
2221  error_context_stack = &params_errcxt;
2222 
2223  if (max_rows <= 0)
2224  max_rows = FETCH_ALL;
2225 
2226  completed = PortalRun(portal,
2227  max_rows,
2228  true, /* always top level */
2229  !execute_is_fetch && max_rows == FETCH_ALL,
2230  receiver,
2231  receiver,
2232  &qc);
2233 
2234  receiver->rDestroy(receiver);
2235 
2236  /* Done executing; remove the params error callback */
2238 
2239  if (completed)
2240  {
2241  if (is_xact_command || (MyXactFlags & XACT_FLAGS_NEEDIMMEDIATECOMMIT))
2242  {
2243  /*
2244  * If this was a transaction control statement, commit it. We
2245  * will start a new xact command for the next command (if any).
2246  * Likewise if the statement required immediate commit. Without
2247  * this provision, we wouldn't force commit until Sync is
2248  * received, which creates a hazard if the client tries to
2249  * pipeline immediate-commit statements.
2250  */
2252 
2253  /*
2254  * These commands typically don't have any parameters, and even if
2255  * one did we couldn't print them now because the storage went
2256  * away during finish_xact_command. So pretend there were none.
2257  */
2258  portalParams = NULL;
2259  }
2260  else
2261  {
2262  /*
2263  * We need a CommandCounterIncrement after every query, except
2264  * those that start or end a transaction block.
2265  */
2267 
2268  /*
2269  * Set XACT_FLAGS_PIPELINING whenever we complete an Execute
2270  * message without immediately committing the transaction.
2271  */
2273 
2274  /*
2275  * Disable statement timeout whenever we complete an Execute
2276  * message. The next protocol message will start a fresh timeout.
2277  */
2279  }
2280 
2281  /* Send appropriate CommandComplete to client */
2282  EndCommand(&qc, dest, false);
2283  }
2284  else
2285  {
2286  /* Portal run not complete, so send PortalSuspended */
2289 
2290  /*
2291  * Set XACT_FLAGS_PIPELINING whenever we suspend an Execute message,
2292  * too.
2293  */
2295  }
2296 
2297  /*
2298  * Emit duration logging if appropriate.
2299  */
2300  switch (check_log_duration(msec_str, was_logged))
2301  {
2302  case 1:
2303  ereport(LOG,
2304  (errmsg("duration: %s ms", msec_str),
2305  errhidestmt(true)));
2306  break;
2307  case 2:
2308  ereport(LOG,
2309  (errmsg("duration: %s ms %s %s%s%s: %s",
2310  msec_str,
2311  execute_is_fetch ?
2312  _("execute fetch from") :
2313  _("execute"),
2314  prepStmtName,
2315  *portal_name ? "/" : "",
2316  *portal_name ? portal_name : "",
2317  sourceText),
2318  errhidestmt(true),
2319  errdetail_params(portalParams)));
2320  break;
2321  }
2322 
2323  if (save_log_statement_stats)
2324  ShowUsage("EXECUTE MESSAGE STATISTICS");
2325 
2327 
2328  debug_query_string = NULL;
2329 }
2330 
2331 /*
2332  * check_log_statement
2333  * Determine whether command should be logged because of log_statement
2334  *
2335  * stmt_list can be either raw grammar output or a list of planned
2336  * statements
2337  */
2338 static bool
2340 {
2341  ListCell *stmt_item;
2342 
2343  if (log_statement == LOGSTMT_NONE)
2344  return false;
2345  if (log_statement == LOGSTMT_ALL)
2346  return true;
2347 
2348  /* Else we have to inspect the statement(s) to see whether to log */
2349  foreach(stmt_item, stmt_list)
2350  {
2351  Node *stmt = (Node *) lfirst(stmt_item);
2352 
2354  return true;
2355  }
2356 
2357  return false;
2358 }
2359 
2360 /*
2361  * check_log_duration
2362  * Determine whether current command's duration should be logged
2363  * We also check if this statement in this transaction must be logged
2364  * (regardless of its duration).
2365  *
2366  * Returns:
2367  * 0 if no logging is needed
2368  * 1 if just the duration should be logged
2369  * 2 if duration and query details should be logged
2370  *
2371  * If logging is needed, the duration in msec is formatted into msec_str[],
2372  * which must be a 32-byte buffer.
2373  *
2374  * was_logged should be true if caller already logged query details (this
2375  * essentially prevents 2 from being returned).
2376  */
2377 int
2378 check_log_duration(char *msec_str, bool was_logged)
2379 {
2380  if (log_duration || log_min_duration_sample >= 0 ||
2382  {
2383  long secs;
2384  int usecs;
2385  int msecs;
2386  bool exceeded_duration;
2387  bool exceeded_sample_duration;
2388  bool in_sample = false;
2389 
2392  &secs, &usecs);
2393  msecs = usecs / 1000;
2394 
2395  /*
2396  * This odd-looking test for log_min_duration_* being exceeded is
2397  * designed to avoid integer overflow with very long durations: don't
2398  * compute secs * 1000 until we've verified it will fit in int.
2399  */
2400  exceeded_duration = (log_min_duration_statement == 0 ||
2402  (secs > log_min_duration_statement / 1000 ||
2403  secs * 1000 + msecs >= log_min_duration_statement)));
2404 
2405  exceeded_sample_duration = (log_min_duration_sample == 0 ||
2406  (log_min_duration_sample > 0 &&
2407  (secs > log_min_duration_sample / 1000 ||
2408  secs * 1000 + msecs >= log_min_duration_sample)));
2409 
2410  /*
2411  * Do not log if log_statement_sample_rate = 0. Log a sample if
2412  * log_statement_sample_rate <= 1 and avoid unnecessary PRNG call if
2413  * log_statement_sample_rate = 1.
2414  */
2415  if (exceeded_sample_duration)
2416  in_sample = log_statement_sample_rate != 0 &&
2417  (log_statement_sample_rate == 1 ||
2419 
2420  if (exceeded_duration || in_sample || log_duration || xact_is_sampled)
2421  {
2422  snprintf(msec_str, 32, "%ld.%03d",
2423  secs * 1000 + msecs, usecs % 1000);
2424  if ((exceeded_duration || in_sample || xact_is_sampled) && !was_logged)
2425  return 2;
2426  else
2427  return 1;
2428  }
2429  }
2430 
2431  return 0;
2432 }
2433 
2434 /*
2435  * errdetail_execute
2436  *
2437  * Add an errdetail() line showing the query referenced by an EXECUTE, if any.
2438  * The argument is the raw parsetree list.
2439  */
2440 static int
2441 errdetail_execute(List *raw_parsetree_list)
2442 {
2443  ListCell *parsetree_item;
2444 
2445  foreach(parsetree_item, raw_parsetree_list)
2446  {
2447  RawStmt *parsetree = lfirst_node(RawStmt, parsetree_item);
2448 
2449  if (IsA(parsetree->stmt, ExecuteStmt))
2450  {
2451  ExecuteStmt *stmt = (ExecuteStmt *) parsetree->stmt;
2452  PreparedStatement *pstmt;
2453 
2454  pstmt = FetchPreparedStatement(stmt->name, false);
2455  if (pstmt)
2456  {
2457  errdetail("prepare: %s", pstmt->plansource->query_string);
2458  return 0;
2459  }
2460  }
2461  }
2462 
2463  return 0;
2464 }
2465 
2466 /*
2467  * errdetail_params
2468  *
2469  * Add an errdetail() line showing bind-parameter data, if available.
2470  * Note that this is only used for statement logging, so it is controlled
2471  * by log_parameter_max_length not log_parameter_max_length_on_error.
2472  */
2473 static int
2475 {
2476  if (params && params->numParams > 0 && log_parameter_max_length != 0)
2477  {
2478  char *str;
2479 
2481  if (str && str[0] != '\0')
2482  errdetail("Parameters: %s", str);
2483  }
2484 
2485  return 0;
2486 }
2487 
2488 /*
2489  * errdetail_abort
2490  *
2491  * Add an errdetail() line showing abort reason, if any.
2492  */
2493 static int
2495 {
2497  errdetail("Abort reason: recovery conflict");
2498 
2499  return 0;
2500 }
2501 
2502 /*
2503  * errdetail_recovery_conflict
2504  *
2505  * Add an errdetail() line showing conflict source.
2506  */
2507 static int
2509 {
2510  switch (reason)
2511  {
2513  errdetail("User was holding shared buffer pin for too long.");
2514  break;
2516  errdetail("User was holding a relation lock for too long.");
2517  break;
2519  errdetail("User was or might have been using tablespace that must be dropped.");
2520  break;
2522  errdetail("User query might have needed to see row versions that must be removed.");
2523  break;
2525  errdetail("User was using a logical replication slot that must be invalidated.");
2526  break;
2528  errdetail("User transaction caused buffer deadlock with recovery.");
2529  break;
2531  errdetail("User was connected to a database that must be dropped.");
2532  break;
2533  default:
2534  break;
2535  /* no errdetail */
2536  }
2537 
2538  return 0;
2539 }
2540 
2541 /*
2542  * bind_param_error_callback
2543  *
2544  * Error context callback used while parsing parameters in a Bind message
2545  */
2546 static void
2548 {
2551  char *quotedval;
2552 
2553  if (data->paramno < 0)
2554  return;
2555 
2556  /* If we have a textual value, quote it, and trim if necessary */
2557  if (data->paramval)
2558  {
2559  initStringInfo(&buf);
2562  quotedval = buf.data;
2563  }
2564  else
2565  quotedval = NULL;
2566 
2567  if (data->portalName && data->portalName[0] != '\0')
2568  {
2569  if (quotedval)
2570  errcontext("portal \"%s\" parameter $%d = %s",
2571  data->portalName, data->paramno + 1, quotedval);
2572  else
2573  errcontext("portal \"%s\" parameter $%d",
2574  data->portalName, data->paramno + 1);
2575  }
2576  else
2577  {
2578  if (quotedval)
2579  errcontext("unnamed portal parameter $%d = %s",
2580  data->paramno + 1, quotedval);
2581  else
2582  errcontext("unnamed portal parameter $%d",
2583  data->paramno + 1);
2584  }
2585 
2586  if (quotedval)
2587  pfree(quotedval);
2588 }
2589 
2590 /*
2591  * exec_describe_statement_message
2592  *
2593  * Process a "Describe" message for a prepared statement
2594  */
2595 static void
2596 exec_describe_statement_message(const char *stmt_name)
2597 {
2598  CachedPlanSource *psrc;
2599 
2600  /*
2601  * Start up a transaction command. (Note that this will normally change
2602  * current memory context.) Nothing happens if we are already in one.
2603  */
2605 
2606  /* Switch back to message context */
2608 
2609  /* Find prepared statement */
2610  if (stmt_name[0] != '\0')
2611  {
2612  PreparedStatement *pstmt;
2613 
2614  pstmt = FetchPreparedStatement(stmt_name, true);
2615  psrc = pstmt->plansource;
2616  }
2617  else
2618  {
2619  /* special-case the unnamed statement */
2620  psrc = unnamed_stmt_psrc;
2621  if (!psrc)
2622  ereport(ERROR,
2623  (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
2624  errmsg("unnamed prepared statement does not exist")));
2625  }
2626 
2627  /* Prepared statements shouldn't have changeable result descs */
2628  Assert(psrc->fixed_result);
2629 
2630  /*
2631  * If we are in aborted transaction state, we can't run
2632  * SendRowDescriptionMessage(), because that needs catalog accesses.
2633  * Hence, refuse to Describe statements that return data. (We shouldn't
2634  * just refuse all Describes, since that might break the ability of some
2635  * clients to issue COMMIT or ROLLBACK commands, if they use code that
2636  * blindly Describes whatever it does.) We can Describe parameters
2637  * without doing anything dangerous, so we don't restrict that.
2638  */
2640  psrc->resultDesc)
2641  ereport(ERROR,
2642  (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2643  errmsg("current transaction is aborted, "
2644  "commands ignored until end of transaction block"),
2645  errdetail_abort()));
2646 
2648  return; /* can't actually do anything... */
2649 
2650  /*
2651  * First describe the parameters...
2652  */
2653  pq_beginmessage_reuse(&row_description_buf, 't'); /* parameter description
2654  * message type */
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.
3412  */
3414  ereport(FATAL,
3415  (errcode(ERRCODE_IDLE_IN_TRANSACTION_SESSION_TIMEOUT),
3416  errmsg("terminating connection due to idle-in-transaction timeout")));
3417  else
3419  }
3420 
3422  {
3423  /* As above, ignore the signal if the GUC has been reset to zero. */
3424  if (TransactionTimeout > 0)
3425  ereport(FATAL,
3426  (errcode(ERRCODE_TRANSACTION_TIMEOUT),
3427  errmsg("terminating connection due to transaction timeout")));
3428  else
3429  TransactionTimeoutPending = false;
3430  }
3431 
3433  {
3434  /* As above, ignore the signal if the GUC has been reset to zero. */
3435  if (IdleSessionTimeout > 0)
3436  ereport(FATAL,
3437  (errcode(ERRCODE_IDLE_SESSION_TIMEOUT),
3438  errmsg("terminating connection due to idle-session timeout")));
3439  else
3440  IdleSessionTimeoutPending = false;
3441  }
3442 
3443  /*
3444  * If there are pending stats updates and we currently are truly idle
3445  * (matching the conditions in PostgresMain(), report stats now.
3446  */
3449  {
3451  pgstat_report_stat(true);
3452  }
3453 
3456 
3459 
3462 
3465 }
3466 
3467 /*
3468  * set_stack_base: set up reference point for stack depth checking
3469  *
3470  * Returns the old reference point, if any.
3471  */
3474 {
3475 #ifndef HAVE__BUILTIN_FRAME_ADDRESS
3476  char stack_base;
3477 #endif
3478  pg_stack_base_t old;
3479 
3480  old = stack_base_ptr;
3481 
3482  /*
3483  * Set up reference point for stack depth checking. On recent gcc we use
3484  * __builtin_frame_address() to avoid a warning about storing a local
3485  * variable's address in a long-lived variable.
3486  */
3487 #ifdef HAVE__BUILTIN_FRAME_ADDRESS
3488  stack_base_ptr = __builtin_frame_address(0);
3489 #else
3490  stack_base_ptr = &stack_base;
3491 #endif
3492 
3493  return old;
3494 }
3495 
3496 /*
3497  * restore_stack_base: restore reference point for stack depth checking
3498  *
3499  * This can be used after set_stack_base() to restore the old value. This
3500  * is currently only used in PL/Java. When PL/Java calls a backend function
3501  * from different thread, the thread's stack is at a different location than
3502  * the main thread's stack, so it sets the base pointer before the call, and
3503  * restores it afterwards.
3504  */
3505 void
3507 {
3508  stack_base_ptr = base;
3509 }
3510 
3511 /*
3512  * check_stack_depth/stack_is_too_deep: check for excessively deep recursion
3513  *
3514  * This should be called someplace in any recursive routine that might possibly
3515  * recurse deep enough to overflow the stack. Most Unixen treat stack
3516  * overflow as an unrecoverable SIGSEGV, so we want to error out ourselves
3517  * before hitting the hardware limit.
3518  *
3519  * check_stack_depth() just throws an error summarily. stack_is_too_deep()
3520  * can be used by code that wants to handle the error condition itself.
3521  */
3522 void
3524 {
3525  if (stack_is_too_deep())
3526  {
3527  ereport(ERROR,
3528  (errcode(ERRCODE_STATEMENT_TOO_COMPLEX),
3529  errmsg("stack depth limit exceeded"),
3530  errhint("Increase the configuration parameter max_stack_depth (currently %dkB), "
3531  "after ensuring the platform's stack depth limit is adequate.",
3532  max_stack_depth)));
3533  }
3534 }
3535 
3536 bool
3538 {
3539  char stack_top_loc;
3540  long stack_depth;
3541 
3542  /*
3543  * Compute distance from reference point to my local variables
3544  */
3545  stack_depth = (long) (stack_base_ptr - &stack_top_loc);
3546 
3547  /*
3548  * Take abs value, since stacks grow up on some machines, down on others
3549  */
3550  if (stack_depth < 0)
3551  stack_depth = -stack_depth;
3552 
3553  /*
3554  * Trouble?
3555  *
3556  * The test on stack_base_ptr prevents us from erroring out if called
3557  * during process setup or in a non-backend process. Logically it should
3558  * be done first, but putting it here avoids wasting cycles during normal
3559  * cases.
3560  */
3561  if (stack_depth > max_stack_depth_bytes &&
3562  stack_base_ptr != NULL)
3563  return true;
3564 
3565  return false;
3566 }
3567 
3568 /* GUC check hook for max_stack_depth */
3569 bool
3571 {
3572  long newval_bytes = *newval * 1024L;
3573  long stack_rlimit = get_stack_depth_rlimit();
3574 
3575  if (stack_rlimit > 0 && newval_bytes > stack_rlimit - STACK_DEPTH_SLOP)
3576  {
3577  GUC_check_errdetail("max_stack_depth must not exceed %ldkB.",
3578  (stack_rlimit - STACK_DEPTH_SLOP) / 1024L);
3579  GUC_check_errhint("Increase the platform's stack depth limit via \"ulimit -s\" or local equivalent.");
3580  return false;
3581  }
3582  return true;
3583 }
3584 
3585 /* GUC assign hook for max_stack_depth */
3586 void
3588 {
3589  long newval_bytes = newval * 1024L;
3590 
3591  max_stack_depth_bytes = newval_bytes;
3592 }
3593 
3594 /*
3595  * GUC check_hook for client_connection_check_interval
3596  */
3597 bool
3599 {
3600  if (!WaitEventSetCanReportClosed() && *newval != 0)
3601  {
3602  GUC_check_errdetail("client_connection_check_interval must be set to 0 on this platform.");
3603  return false;
3604  }
3605  return true;
3606 }
3607 
3608 /*
3609  * GUC check_hook for log_parser_stats, log_planner_stats, log_executor_stats
3610  *
3611  * This function and check_log_stats interact to prevent their variables from
3612  * being set in a disallowed combination. This is a hack that doesn't really
3613  * work right; for example it might fail while applying pg_db_role_setting
3614  * values even though the final state would have been acceptable. However,
3615  * since these variables are legacy settings with little production usage,
3616  * we tolerate that.
3617  */
3618 bool
3620 {
3621  if (*newval && log_statement_stats)
3622  {
3623  GUC_check_errdetail("Cannot enable parameter when \"log_statement_stats\" is true.");
3624  return false;
3625  }
3626  return true;
3627 }
3628 
3629 /*
3630  * GUC check_hook for log_statement_stats
3631  */
3632 bool
3634 {
3635  if (*newval &&
3637  {
3638  GUC_check_errdetail("Cannot enable log_statement_stats when "
3639  "log_parser_stats, log_planner_stats, "
3640  "or log_executor_stats is true.");
3641  return false;
3642  }
3643  return true;
3644 }
3645 
3646 /* GUC assign hook for transaction_timeout */
3647 void
3649 {
3650  if (IsTransactionState())
3651  {
3652  /*
3653  * If transaction_timeout GUC has changed within the transaction block
3654  * enable or disable the timer correspondingly.
3655  */
3658  else if (newval <= 0 && get_timeout_active(TRANSACTION_TIMEOUT))
3660  }
3661 }
3662 
3663 
3664 /*
3665  * set_debug_options --- apply "-d N" command line option
3666  *
3667  * -d is not quite the same as setting log_min_messages because it enables
3668  * other output options.
3669  */
3670 void
3672 {
3673  if (debug_flag > 0)
3674  {
3675  char debugstr[64];
3676 
3677  sprintf(debugstr, "debug%d", debug_flag);
3678  SetConfigOption("log_min_messages", debugstr, context, source);
3679  }
3680  else
3681  SetConfigOption("log_min_messages", "notice", context, source);
3682 
3683  if (debug_flag >= 1 && context == PGC_POSTMASTER)
3684  {
3685  SetConfigOption("log_connections", "true", context, source);
3686  SetConfigOption("log_disconnections", "true", context, source);
3687  }
3688  if (debug_flag >= 2)
3689  SetConfigOption("log_statement", "all", context, source);
3690  if (debug_flag >= 3)
3691  SetConfigOption("debug_print_parse", "true", context, source);
3692  if (debug_flag >= 4)
3693  SetConfigOption("debug_print_plan", "true", context, source);
3694  if (debug_flag >= 5)
3695  SetConfigOption("debug_print_rewritten", "true", context, source);
3696 }
3697 
3698 
3699 bool
3701 {
3702  const char *tmp = NULL;
3703 
3704  switch (arg[0])
3705  {
3706  case 's': /* seqscan */
3707  tmp = "enable_seqscan";
3708  break;
3709  case 'i': /* indexscan */
3710  tmp = "enable_indexscan";
3711  break;
3712  case 'o': /* indexonlyscan */
3713  tmp = "enable_indexonlyscan";
3714  break;
3715  case 'b': /* bitmapscan */
3716  tmp = "enable_bitmapscan";
3717  break;
3718  case 't': /* tidscan */
3719  tmp = "enable_tidscan";
3720  break;
3721  case 'n': /* nestloop */
3722  tmp = "enable_nestloop";
3723  break;
3724  case 'm': /* mergejoin */
3725  tmp = "enable_mergejoin";
3726  break;
3727  case 'h': /* hashjoin */
3728  tmp = "enable_hashjoin";
3729  break;
3730  }
3731  if (tmp)
3732  {
3733  SetConfigOption(tmp, "false", context, source);
3734  return true;
3735  }
3736  else
3737  return false;
3738 }
3739 
3740 
3741 const char *
3743 {
3744  switch (arg[0])
3745  {
3746  case 'p':
3747  if (optarg[1] == 'a') /* "parser" */
3748  return "log_parser_stats";
3749  else if (optarg[1] == 'l') /* "planner" */
3750  return "log_planner_stats";
3751  break;
3752 
3753  case 'e': /* "executor" */
3754  return "log_executor_stats";
3755  break;
3756  }
3757 
3758  return NULL;
3759 }
3760 
3761 
3762 /* ----------------------------------------------------------------
3763  * process_postgres_switches
3764  * Parse command line arguments for backends
3765  *
3766  * This is called twice, once for the "secure" options coming from the
3767  * postmaster or command line, and once for the "insecure" options coming
3768  * from the client's startup packet. The latter have the same syntax but
3769  * may be restricted in what they can do.
3770  *
3771  * argv[0] is ignored in either case (it's assumed to be the program name).
3772  *
3773  * ctx is PGC_POSTMASTER for secure options, PGC_BACKEND for insecure options
3774  * coming from the client, or PGC_SU_BACKEND for insecure options coming from
3775  * a superuser client.
3776  *
3777  * If a database name is present in the command line arguments, it's
3778  * returned into *dbname (this is allowed only if *dbname is initially NULL).
3779  * ----------------------------------------------------------------
3780  */
3781 void
3782 process_postgres_switches(int argc, char *argv[], GucContext ctx,
3783  const char **dbname)
3784 {
3785  bool secure = (ctx == PGC_POSTMASTER);
3786  int errs = 0;
3787  GucSource gucsource;
3788  int flag;
3789 
3790  if (secure)
3791  {
3792  gucsource = PGC_S_ARGV; /* switches came from command line */
3793 
3794  /* Ignore the initial --single argument, if present */
3795  if (argc > 1 && strcmp(argv[1], "--single") == 0)
3796  {
3797  argv++;
3798  argc--;
3799  }
3800  }
3801  else
3802  {
3803  gucsource = PGC_S_CLIENT; /* switches came from client */
3804  }
3805 
3806 #ifdef HAVE_INT_OPTERR
3807 
3808  /*
3809  * Turn this off because it's either printed to stderr and not the log
3810  * where we'd want it, or argv[0] is now "--single", which would make for
3811  * a weird error message. We print our own error message below.
3812  */
3813  opterr = 0;
3814 #endif
3815 
3816  /*
3817  * Parse command-line options. CAUTION: keep this in sync with
3818  * postmaster/postmaster.c (the option sets should not conflict) and with
3819  * the common help() function in main/main.c.
3820  */
3821  while ((flag = getopt(argc, argv, "B:bC:c:D:d:EeFf:h:ijk:lN:nOPp:r:S:sTt:v:W:-:")) != -1)
3822  {
3823  switch (flag)
3824  {
3825  case 'B':
3826  SetConfigOption("shared_buffers", optarg, ctx, gucsource);
3827  break;
3828 
3829  case 'b':
3830  /* Undocumented flag used for binary upgrades */
3831  if (secure)
3832  IsBinaryUpgrade = true;
3833  break;
3834 
3835  case 'C':
3836  /* ignored for consistency with the postmaster */
3837  break;
3838 
3839  case 'c':
3840  case '-':
3841  {
3842  char *name,
3843  *value;
3844 
3846  if (!value)
3847  {
3848  if (flag == '-')
3849  ereport(ERROR,
3850  (errcode(ERRCODE_SYNTAX_ERROR),
3851  errmsg("--%s requires a value",
3852  optarg)));
3853  else
3854  ereport(ERROR,
3855  (errcode(ERRCODE_SYNTAX_ERROR),
3856  errmsg("-c %s requires a value",
3857  optarg)));
3858  }
3859  SetConfigOption(name, value, ctx, gucsource);
3860  pfree(name);
3861  pfree(value);
3862  break;
3863  }
3864 
3865  case 'D':
3866  if (secure)
3867  userDoption = strdup(optarg);
3868  break;
3869 
3870  case 'd':
3871  set_debug_options(atoi(optarg), ctx, gucsource);
3872  break;
3873 
3874  case 'E':
3875  if (secure)
3876  EchoQuery = true;
3877  break;
3878 
3879  case 'e':
3880  SetConfigOption("datestyle", "euro", ctx, gucsource);
3881  break;
3882 
3883  case 'F':
3884  SetConfigOption("fsync", "false", ctx, gucsource);
3885  break;
3886 
3887  case 'f':
3888  if (!set_plan_disabling_options(optarg, ctx, gucsource))
3889  errs++;
3890  break;
3891 
3892  case 'h':
3893  SetConfigOption("listen_addresses", optarg, ctx, gucsource);
3894  break;
3895 
3896  case 'i':
3897  SetConfigOption("listen_addresses", "*", ctx, gucsource);
3898  break;
3899 
3900  case 'j':
3901  if (secure)
3902  UseSemiNewlineNewline = true;
3903  break;
3904 
3905  case 'k':
3906  SetConfigOption("unix_socket_directories", optarg, ctx, gucsource);
3907  break;
3908 
3909  case 'l':
3910  SetConfigOption("ssl", "true", ctx, gucsource);
3911  break;
3912 
3913  case 'N':
3914  SetConfigOption("max_connections", optarg, ctx, gucsource);
3915  break;
3916 
3917  case 'n':
3918  /* ignored for consistency with postmaster */
3919  break;
3920 
3921  case 'O':
3922  SetConfigOption("allow_system_table_mods", "true", ctx, gucsource);
3923  break;
3924 
3925  case 'P':
3926  SetConfigOption("ignore_system_indexes", "true", ctx, gucsource);
3927  break;
3928 
3929  case 'p':
3930  SetConfigOption("port", optarg, ctx, gucsource);
3931  break;
3932 
3933  case 'r':
3934  /* send output (stdout and stderr) to the given file */
3935  if (secure)
3937  break;
3938 
3939  case 'S':
3940  SetConfigOption("work_mem", optarg, ctx, gucsource);
3941  break;
3942 
3943  case 's':
3944  SetConfigOption("log_statement_stats", "true", ctx, gucsource);
3945  break;
3946 
3947  case 'T':
3948  /* ignored for consistency with the postmaster */
3949  break;
3950 
3951  case 't':
3952  {
3953  const char *tmp = get_stats_option_name(optarg);
3954 
3955  if (tmp)
3956  SetConfigOption(tmp, "true", ctx, gucsource);
3957  else
3958  errs++;
3959  break;
3960  }
3961 
3962  case 'v':
3963 
3964  /*
3965  * -v is no longer used in normal operation, since
3966  * FrontendProtocol is already set before we get here. We keep
3967  * the switch only for possible use in standalone operation,
3968  * in case we ever support using normal FE/BE protocol with a
3969  * standalone backend.
3970  */
3971  if (secure)
3973  break;
3974 
3975  case 'W':
3976  SetConfigOption("post_auth_delay", optarg, ctx, gucsource);
3977  break;
3978 
3979  default:
3980  errs++;
3981  break;
3982  }
3983 
3984  if (errs)
3985  break;
3986  }
3987 
3988  /*
3989  * Optional database name should be there only if *dbname is NULL.
3990  */
3991  if (!errs && dbname && *dbname == NULL && argc - optind >= 1)
3992  *dbname = strdup(argv[optind++]);
3993 
3994  if (errs || argc != optind)
3995  {
3996  if (errs)
3997  optind--; /* complain about the previous argument */
3998 
3999  /* spell the error message a bit differently depending on context */
4000  if (IsUnderPostmaster)
4001  ereport(FATAL,
4002  errcode(ERRCODE_SYNTAX_ERROR),
4003  errmsg("invalid command-line argument for server process: %s", argv[optind]),
4004  errhint("Try \"%s --help\" for more information.", progname));
4005  else
4006  ereport(FATAL,
4007  errcode(ERRCODE_SYNTAX_ERROR),
4008  errmsg("%s: invalid command-line argument: %s",
4009  progname, argv[optind]),
4010  errhint("Try \"%s --help\" for more information.", progname));
4011  }
4012 
4013  /*
4014  * Reset getopt(3) library so that it will work correctly in subprocesses
4015  * or when this function is called a second time with another array.
4016  */
4017  optind = 1;
4018 #ifdef HAVE_INT_OPTRESET
4019  optreset = 1; /* some systems need this too */
4020 #endif
4021 }
4022 
4023 
4024 /*
4025  * PostgresSingleUserMain
4026  * Entry point for single user mode. argc/argv are the command line
4027  * arguments to be used.
4028  *
4029  * Performs single user specific setup then calls PostgresMain() to actually
4030  * process queries. Single user mode specific setup should go here, rather
4031  * than PostgresMain() or InitPostgres() when reasonably possible.
4032  */
4033 void
4034 PostgresSingleUserMain(int argc, char *argv[],
4035  const char *username)
4036 {
4037  const char *dbname = NULL;
4038 
4040 
4041  /* Initialize startup process environment. */
4042  InitStandaloneProcess(argv[0]);
4043 
4044  /*
4045  * Set default values for command-line options.
4046  */
4048 
4049  /*
4050  * Parse command-line options.
4051  */
4053 
4054  /* Must have gotten a database name, or have a default (the username) */
4055  if (dbname == NULL)
4056  {
4057  dbname = username;
4058  if (dbname == NULL)
4059  ereport(FATAL,
4060  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4061  errmsg("%s: no database nor user name specified",
4062  progname)));
4063  }
4064 
4065  /* Acquire configuration parameters */
4067  proc_exit(1);
4068 
4069  /*
4070  * Validate we have been given a reasonable-looking DataDir and change
4071  * into it.
4072  */
4073  checkDataDir();
4074  ChangeToDataDir();
4075 
4076  /*
4077  * Create lockfile for data directory.
4078  */
4079  CreateDataDirLockFile(false);
4080 
4081  /* read control file (error checking and contains config ) */
4082  LocalProcessControlFile(false);
4083 
4084  /*
4085  * process any libraries that should be preloaded at postmaster start
4086  */
4088 
4089  /* Initialize MaxBackends */
4091 
4092  /*
4093  * Give preloaded libraries a chance to request additional shared memory.
4094  */
4096 
4097  /*
4098  * Now that loadable modules have had their chance to request additional
4099  * shared memory, determine the value of any runtime-computed GUCs that
4100  * depend on the amount of shared memory required.
4101  */
4103 
4104  /*
4105  * Now that modules have been loaded, we can process any custom resource
4106  * managers specified in the wal_consistency_checking GUC.
4107  */
4109 
4111 
4112  /*
4113  * Remember stand-alone backend startup time,roughly at the same point
4114  * during startup that postmaster does so.
4115  */
4117 
4118  /*
4119  * Create a per-backend PGPROC struct in shared memory. We must do this
4120  * before we can use LWLocks.
4121  */
4122  InitProcess();
4123 
4124  /*
4125  * Now that sufficient infrastructure has been initialized, PostgresMain()
4126  * can do the rest.
4127  */
4129 }
4130 
4131 
4132 /* ----------------------------------------------------------------
4133  * PostgresMain
4134  * postgres main loop -- all backends, interactive or otherwise loop here
4135  *
4136  * dbname is the name of the database to connect to, username is the
4137  * PostgreSQL user name to be used for the session.
4138  *
4139  * NB: Single user mode specific setup should go to PostgresSingleUserMain()
4140  * if reasonably possible.
4141  * ----------------------------------------------------------------
4142  */
4143 void
4144 PostgresMain(const char *dbname, const char *username)
4145 {
4146  sigjmp_buf local_sigjmp_buf;
4147 
4148  /* these must be volatile to ensure state is preserved across longjmp: */
4149  volatile bool send_ready_for_query = true;
4150  volatile bool idle_in_transaction_timeout_enabled = false;
4151  volatile bool idle_session_timeout_enabled = false;
4152 
4153  Assert(dbname != NULL);
4154  Assert(username != NULL);
4155 
4157 
4158  /*
4159  * Set up signal handlers. (InitPostmasterChild or InitStandaloneProcess
4160  * has already set up BlockSig and made that the active signal mask.)
4161  *
4162  * Note that postmaster blocked all signals before forking child process,
4163  * so there is no race condition whereby we might receive a signal before
4164  * we have set up the handler.
4165  *
4166  * Also note: it's best not to use any signals that are SIG_IGNored in the
4167  * postmaster. If such a signal arrives before we are able to change the
4168  * handler to non-SIG_IGN, it'll get dropped. Instead, make a dummy
4169  * handler in the postmaster to reserve the signal. (Of course, this isn't
4170  * an issue for signals that are locally generated, such as SIGALRM and
4171  * SIGPIPE.)
4172  */
4173  if (am_walsender)
4174  WalSndSignals();
4175  else
4176  {
4178  pqsignal(SIGINT, StatementCancelHandler); /* cancel current query */
4179  pqsignal(SIGTERM, die); /* cancel current query and exit */
4180 
4181  /*
4182  * In a postmaster child backend, replace SignalHandlerForCrashExit
4183  * with quickdie, so we can tell the client we're dying.
4184  *
4185  * In a standalone backend, SIGQUIT can be generated from the keyboard
4186  * easily, while SIGTERM cannot, so we make both signals do die()
4187  * rather than quickdie().
4188  */
4189  if (IsUnderPostmaster)
4190  pqsignal(SIGQUIT, quickdie); /* hard crash time */
4191  else
4192  pqsignal(SIGQUIT, die); /* cancel current query and exit */
4193  InitializeTimeouts(); /* establishes SIGALRM handler */
4194 
4195  /*
4196  * Ignore failure to write to frontend. Note: if frontend closes
4197  * connection, we will notice it and exit cleanly when control next
4198  * returns to outer loop. This seems safer than forcing exit in the
4199  * midst of output during who-knows-what operation...
4200  */
4205 
4206  /*
4207  * Reset some signals that are accepted by postmaster but not by
4208  * backend
4209  */
4210  pqsignal(SIGCHLD, SIG_DFL); /* system() requires this on some
4211  * platforms */
4212  }
4213 
4214  /* Early initialization */
4215  BaseInit();
4216 
4217  /* We need to allow SIGINT, etc during the initial transaction */
4218  sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
4219 
4220  /*
4221  * General initialization.
4222  *
4223  * NOTE: if you are tempted to add code in this vicinity, consider putting
4224  * it inside InitPostgres() instead. In particular, anything that
4225  * involves database access should be there, not here.
4226  *
4227  * Honor session_preload_libraries if not dealing with a WAL sender.
4228  */
4229  InitPostgres(dbname, InvalidOid, /* database to connect to */
4230  username, InvalidOid, /* role to connect as */
4232  NULL); /* no out_dbname */
4233 
4234  /*
4235  * If the PostmasterContext is still around, recycle the space; we don't
4236  * need it anymore after InitPostgres completes. Note this does not trash
4237  * *MyProcPort, because ConnCreate() allocated that space with malloc()
4238  * ... else we'd need to copy the Port data first. Also, subsidiary data
4239  * such as the username isn't lost either; see ProcessStartupPacket().
4240  */
4241  if (PostmasterContext)
4242  {
4244  PostmasterContext = NULL;
4245  }
4246 
4248 
4249  /*
4250  * Now all GUC states are fully set up. Report them to client if
4251  * appropriate.
4252  */
4254 
4255  /*
4256  * Also set up handler to log session end; we have to wait till now to be
4257  * sure Log_disconnections has its final value.
4258  */
4261 
4263 
4264  /* Perform initialization specific to a WAL sender process. */
4265  if (am_walsender)
4266  InitWalSender();
4267 
4268  /*
4269  * Send this backend's cancellation info to the frontend.
4270  */
4272  {
4274 
4278  pq_endmessage(&buf);
4279  /* Need not flush since ReadyForQuery will do it. */
4280  }
4281 
4282  /* Welcome banner for standalone case */
4284  printf("\nPostgreSQL stand-alone backend %s\n", PG_VERSION);
4285 
4286  /*
4287  * Create the memory context we will use in the main loop.
4288  *
4289  * MessageContext is reset once per iteration of the main loop, ie, upon
4290  * completion of processing of each command message from the client.
4291  */
4293  "MessageContext",
4295 
4296  /*
4297  * Create memory context and buffer used for RowDescription messages. As
4298  * SendRowDescriptionMessage(), via exec_describe_statement_message(), is
4299  * frequently executed for ever single statement, we don't want to
4300  * allocate a separate buffer every time.
4301  */
4303  "RowDescriptionContext",
4308 
4309  /* Fire any defined login event triggers, if appropriate */
4311 
4312  /*
4313  * POSTGRES main processing loop begins here
4314  *
4315  * If an exception is encountered, processing resumes here so we abort the
4316  * current transaction and start a new one.
4317  *
4318  * You might wonder why this isn't coded as an infinite loop around a
4319  * PG_TRY construct. The reason is that this is the bottom of the
4320  * exception stack, and so with PG_TRY there would be no exception handler
4321  * in force at all during the CATCH part. By leaving the outermost setjmp
4322  * always active, we have at least some chance of recovering from an error
4323  * during error recovery. (If we get into an infinite loop thereby, it
4324  * will soon be stopped by overflow of elog.c's internal state stack.)
4325  *
4326  * Note that we use sigsetjmp(..., 1), so that this function's signal mask
4327  * (to wit, UnBlockSig) will be restored when longjmp'ing to here. This
4328  * is essential in case we longjmp'd out of a signal handler on a platform
4329  * where that leaves the signal blocked. It's not redundant with the
4330  * unblock in AbortTransaction() because the latter is only called if we
4331  * were inside a transaction.
4332  */
4333 
4334  if (sigsetjmp(local_sigjmp_buf, 1) != 0)
4335  {
4336  /*
4337  * NOTE: if you are tempted to add more code in this if-block,
4338  * consider the high probability that it should be in
4339  * AbortTransaction() instead. The only stuff done directly here
4340  * should be stuff that is guaranteed to apply *only* for outer-level
4341  * error recovery, such as adjusting the FE/BE protocol status.
4342  */
4343 
4344  /* Since not using PG_TRY, must reset error stack by hand */
4345  error_context_stack = NULL;
4346 
4347  /* Prevent interrupts while cleaning up */
4348  HOLD_INTERRUPTS();
4349 
4350  /*
4351  * Forget any pending QueryCancel request, since we're returning to
4352  * the idle loop anyway, and cancel any active timeout requests. (In
4353  * future we might want to allow some timeout requests to survive, but
4354  * at minimum it'd be necessary to do reschedule_timeouts(), in case
4355  * we got here because of a query cancel interrupting the SIGALRM
4356  * interrupt handler.) Note in particular that we must clear the
4357  * statement and lock timeout indicators, to prevent any future plain
4358  * query cancels from being misreported as timeouts in case we're
4359  * forgetting a timeout cancel.
4360  */
4361  disable_all_timeouts(false); /* do first to avoid race condition */
4362  QueryCancelPending = false;
4363  idle_in_transaction_timeout_enabled = false;
4364  idle_session_timeout_enabled = false;
4365 
4366  /* Not reading from the client anymore. */
4367  DoingCommandRead = false;
4368 
4369  /* Make sure libpq is in a good state */
4370  pq_comm_reset();
4371 
4372  /* Report the error to the client and/or server log */
4373  EmitErrorReport();
4374 
4375  /*
4376  * If Valgrind noticed something during the erroneous query, print the
4377  * query string, assuming we have one.
4378  */
4380 
4381  /*
4382  * Make sure debug_query_string gets reset before we possibly clobber
4383  * the storage it points at.
4384  */
4385  debug_query_string = NULL;
4386 
4387  /*
4388  * Abort the current transaction in order to recover.
4389  */
4391 
4392  if (am_walsender)
4394 
4396 
4397  /*
4398  * We can't release replication slots inside AbortTransaction() as we
4399  * need to be able to start and abort transactions while having a slot
4400  * acquired. But we never need to hold them across top level errors,
4401  * so releasing here is fine. There also is a before_shmem_exit()
4402  * callback ensuring correct cleanup on FATAL errors.
4403  */
4404  if (MyReplicationSlot != NULL)
4406 
4407  /* We also want to cleanup temporary slots on error. */
4409 
4411 
4412  /*
4413  * Now return to normal top-level context and clear ErrorContext for
4414  * next time.
4415  */
4417  FlushErrorState();
4418 
4419  /*
4420  * If we were handling an extended-query-protocol message, initiate
4421  * skip till next Sync. This also causes us not to issue
4422  * ReadyForQuery (until we get Sync).
4423  */
4425  ignore_till_sync = true;
4426 
4427  /* We don't have a transaction command open anymore */
4428  xact_started = false;
4429 
4430  /*
4431  * If an error occurred while we were reading a message from the
4432  * client, we have potentially lost track of where the previous
4433  * message ends and the next one begins. Even though we have
4434  * otherwise recovered from the error, we cannot safely read any more
4435  * messages from the client, so there isn't much we can do with the
4436  * connection anymore.
4437  */
4438  if (pq_is_reading_msg())
4439  ereport(FATAL,
4440  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4441  errmsg("terminating connection because protocol synchronization was lost")));
4442 
4443  /* Now we can allow interrupts again */
4445  }
4446 
4447  /* We can now handle ereport(ERROR) */
4448  PG_exception_stack = &local_sigjmp_buf;
4449 
4450  if (!ignore_till_sync)
4451  send_ready_for_query = true; /* initially, or after error */
4452 
4453  /*
4454  * Non-error queries loop here.
4455  */
4456 
4457  for (;;)
4458  {
4459  int firstchar;
4460  StringInfoData input_message;
4461 
4462  /*
4463  * At top of loop, reset extended-query-message flag, so that any
4464  * errors encountered in "idle" state don't provoke skip.
4465  */
4467 
4468  /*
4469  * For valgrind reporting purposes, the "current query" begins here.
4470  */
4471 #ifdef USE_VALGRIND
4472  old_valgrind_error_count = VALGRIND_COUNT_ERRORS;
4473 #endif
4474 
4475  /*
4476  * Release storage left over from prior query cycle, and create a new
4477  * query input buffer in the cleared MessageContext.
4478  */
4481 
4482  initStringInfo(&input_message);
4483 
4484  /*
4485  * Also consider releasing our catalog snapshot if any, so that it's
4486  * not preventing advance of global xmin while we wait for the client.
4487  */
4489 
4490  /*
4491  * (1) If we've reached idle state, tell the frontend we're ready for
4492  * a new query.
4493  *
4494  * Note: this includes fflush()'ing the last of the prior output.
4495  *
4496  * This is also a good time to flush out collected statistics to the
4497  * cumulative stats system, and to update the PS stats display. We
4498  * avoid doing those every time through the message loop because it'd
4499  * slow down processing of batched messages, and because we don't want
4500  * to report uncommitted updates (that confuses autovacuum). The
4501  * notification processor wants a call too, if we are not in a
4502  * transaction block.
4503  *
4504  * Also, if an idle timeout is enabled, start the timer for that.
4505  */
4506  if (send_ready_for_query)
4507  {
4509  {
4510  set_ps_display("idle in transaction (aborted)");
4512 
4513  /* Start the idle-in-transaction timer */
4516  {
4517  idle_in_transaction_timeout_enabled = true;
4520  }
4521  }
4523  {
4524  set_ps_display("idle in transaction");
4526 
4527  /* Start the idle-in-transaction timer */
4530  {
4531  idle_in_transaction_timeout_enabled = true;
4534  }
4535  }
4536  else
4537  {
4538  long stats_timeout;
4539 
4540  /*
4541  * Process incoming notifies (including self-notifies), if
4542  * any, and send relevant messages to the client. Doing it
4543  * here helps ensure stable behavior in tests: if any notifies
4544  * were received during the just-finished transaction, they'll
4545  * be seen by the client before ReadyForQuery is.
4546  */
4548  ProcessNotifyInterrupt(false);
4549 
4550  /*
4551  * Check if we need to report stats. If pgstat_report_stat()
4552  * decides it's too soon to flush out pending stats / lock
4553  * contention prevented reporting, it'll tell us when we
4554  * should try to report stats again (so that stats updates
4555  * aren't unduly delayed if the connection goes idle for a
4556  * long time). We only enable the timeout if we don't already
4557  * have a timeout in progress, because we don't disable the
4558  * timeout below. enable_timeout_after() needs to determine
4559  * the current timestamp, which can have a negative
4560  * performance impact. That's OK because pgstat_report_stat()
4561  * won't have us wake up sooner than a prior call.
4562  */
4563  stats_timeout = pgstat_report_stat(false);
4564  if (stats_timeout > 0)
4565  {
4568  stats_timeout);
4569  }
4570  else
4571  {
4572  /* all stats flushed, no need for the timeout */
4575  }
4576 
4577  set_ps_display("idle");
4579 
4580  /* Start the idle-session timer */
4581  if (IdleSessionTimeout > 0)
4582  {
4583  idle_session_timeout_enabled = true;
4586  }
4587  }
4588 
4589  /* Report any recently-changed GUC options */
4591 
4593  send_ready_for_query = false;
4594  }
4595 
4596  /*
4597  * (2) Allow asynchronous signals to be executed immediately if they
4598  * come in while we are waiting for client input. (This must be
4599  * conditional since we don't want, say, reads on behalf of COPY FROM
4600  * STDIN doing the same thing.)
4601  */
4602  DoingCommandRead = true;
4603 
4604  /*
4605  * (3) read a command (loop blocks here)
4606  */
4607  firstchar = ReadCommand(&input_message);
4608 
4609  /*
4610  * (4) turn off the idle-in-transaction and idle-session timeouts if
4611  * active. We do this before step (5) so that any last-moment timeout
4612  * is certain to be detected in step (5).
4613  *
4614  * At most one of these timeouts will be active, so there's no need to
4615  * worry about combining the timeout.c calls into one.
4616  */
4617  if (idle_in_transaction_timeout_enabled)
4618  {
4620  idle_in_transaction_timeout_enabled = false;
4621  }
4622  if (idle_session_timeout_enabled)
4623  {
4625  idle_session_timeout_enabled = false;
4626  }
4627 
4628  /*
4629  * (5) disable async signal conditions again.
4630  *
4631  * Query cancel is supposed to be a no-op when there is no query in
4632  * progress, so if a query cancel arrived while we were idle, just
4633  * reset QueryCancelPending. ProcessInterrupts() has that effect when
4634  * it's called when DoingCommandRead is set, so check for interrupts
4635  * before resetting DoingCommandRead.
4636  */
4638  DoingCommandRead = false;
4639 
4640  /*
4641  * (6) check for any other interesting events that happened while we
4642  * slept.
4643  */
4644  if (ConfigReloadPending)
4645  {
4646  ConfigReloadPending = false;
4648  }
4649 
4650  /*
4651  * (7) process the command. But ignore it if we're skipping till
4652  * Sync.
4653  */
4654  if (ignore_till_sync && firstchar != EOF)
4655  continue;
4656 
4657  switch (firstchar)
4658  {
4659  case PqMsg_Query:
4660  {
4661  const char *query_string;
4662 
4663  /* Set statement_timestamp() */
4665 
4666  query_string = pq_getmsgstring(&input_message);
4667  pq_getmsgend(&input_message);
4668 
4669  if (am_walsender)
4670  {
4671  if (!exec_replication_command(query_string))
4672  exec_simple_query(query_string);
4673  }
4674  else
4675  exec_simple_query(query_string);
4676 
4677  valgrind_report_error_query(query_string);
4678 
4679  send_ready_for_query = true;
4680  }
4681  break;
4682 
4683  case PqMsg_Parse:
4684  {
4685  const char *stmt_name;
4686  const char *query_string;
4687  int numParams;
4688  Oid *paramTypes = NULL;
4689 
4690  forbidden_in_wal_sender(firstchar);
4691 
4692  /* Set statement_timestamp() */
4694 
4695  stmt_name = pq_getmsgstring(&input_message);
4696  query_string = pq_getmsgstring(&input_message);
4697  numParams = pq_getmsgint(&input_message, 2);
4698  if (numParams > 0)
4699  {
4700  paramTypes = palloc_array(Oid, numParams);
4701  for (int i = 0; i < numParams; i++)
4702  paramTypes[i] = pq_getmsgint(&input_message, 4);
4703  }
4704  pq_getmsgend(&input_message);
4705 
4706  exec_parse_message(query_string, stmt_name,
4707  paramTypes, numParams);
4708 
4709  valgrind_report_error_query(query_string);
4710  }
4711  break;
4712 
4713  case PqMsg_Bind:
4714  forbidden_in_wal_sender(firstchar);
4715 
4716  /* Set statement_timestamp() */
4718 
4719  /*
4720  * this message is complex enough that it seems best to put
4721  * the field extraction out-of-line
4722  */
4723  exec_bind_message(&input_message);
4724 
4725  /* exec_bind_message does valgrind_report_error_query */
4726  break;
4727 
4728  case PqMsg_Execute:
4729  {
4730  const char *portal_name;
4731  int max_rows;
4732 
4733  forbidden_in_wal_sender(firstchar);
4734 
4735  /* Set statement_timestamp() */
4737 
4738  portal_name = pq_getmsgstring(&input_message);
4739  max_rows = pq_getmsgint(&input_message, 4);
4740  pq_getmsgend(&input_message);
4741 
4742  exec_execute_message(portal_name, max_rows);
4743 
4744  /* exec_execute_message does valgrind_report_error_query */
4745  }
4746  break;
4747 
4748  case PqMsg_FunctionCall:
4749  forbidden_in_wal_sender(firstchar);
4750 
4751  /* Set statement_timestamp() */
4753 
4754  /* Report query to various monitoring facilities. */
4756  set_ps_display("<FASTPATH>");
4757 
4758  /* start an xact for this function invocation */
4760 
4761  /*
4762  * Note: we may at this point be inside an aborted
4763  * transaction. We can't throw error for that until we've
4764  * finished reading the function-call message, so
4765  * HandleFunctionRequest() must check for it after doing so.
4766  * Be careful not to do anything that assumes we're inside a
4767  * valid transaction here.
4768  */
4769 
4770  /* switch back to message context */
4772 
4773  HandleFunctionRequest(&input_message);
4774 
4775  /* commit the function-invocation transaction */
4777 
4778  valgrind_report_error_query("fastpath function call");
4779 
4780  send_ready_for_query = true;
4781  break;
4782 
4783  case PqMsg_Close:
4784  {
4785  int close_type;
4786  const char *close_target;
4787 
4788  forbidden_in_wal_sender(firstchar);
4789 
4790  close_type = pq_getmsgbyte(&input_message);
4791  close_target = pq_getmsgstring(&input_message);
4792  pq_getmsgend(&input_message);
4793 
4794  switch (close_type)
4795  {
4796  case 'S':
4797  if (close_target[0] != '\0')
4798  DropPreparedStatement(close_target, false);
4799  else
4800  {
4801  /* special-case the unnamed statement */
4803  }
4804  break;
4805  case 'P':
4806  {
4807  Portal portal;
4808 
4809  portal = GetPortalByName(close_target);
4810  if (PortalIsValid(portal))
4811  PortalDrop(portal, false);
4812  }
4813  break;
4814  default:
4815  ereport(ERROR,
4816  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4817  errmsg("invalid CLOSE message subtype %d",
4818  close_type)));
4819  break;
4820  }
4821 
4824 
4825  valgrind_report_error_query("CLOSE message");
4826  }
4827  break;
4828 
4829  case PqMsg_Describe:
4830  {
4831  int describe_type;
4832  const char *describe_target;
4833 
4834  forbidden_in_wal_sender(firstchar);
4835 
4836  /* Set statement_timestamp() (needed for xact) */
4838 
4839  describe_type = pq_getmsgbyte(&input_message);
4840  describe_target = pq_getmsgstring(&input_message);
4841  pq_getmsgend(&input_message);
4842 
4843  switch (describe_type)
4844  {
4845  case 'S':
4846  exec_describe_statement_message(describe_target);
4847  break;
4848  case 'P':
4849  exec_describe_portal_message(describe_target);
4850  break;
4851  default:
4852  ereport(ERROR,
4853  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4854  errmsg("invalid DESCRIBE message subtype %d",
4855  describe_type)));
4856  break;
4857  }
4858 
4859  valgrind_report_error_query("DESCRIBE message");
4860  }
4861  break;
4862 
4863  case PqMsg_Flush:
4864  pq_getmsgend(&input_message);
4866  pq_flush();
4867  break;
4868 
4869  case PqMsg_Sync:
4870  pq_getmsgend(&input_message);
4872  valgrind_report_error_query("SYNC message");
4873  send_ready_for_query = true;
4874  break;
4875 
4876  /*
4877  * 'X' means that the frontend is closing down the socket. EOF
4878  * means unexpected loss of frontend connection. Either way,
4879  * perform normal shutdown.
4880  */
4881  case EOF:
4882 
4883  /* for the cumulative statistics system */
4885 
4886  /* FALLTHROUGH */
4887 
4888  case PqMsg_Terminate:
4889 
4890  /*
4891  * Reset whereToSendOutput to prevent ereport from attempting
4892  * to send any more messages to client.
4893  */
4896 
4897  /*
4898  * NOTE: if you are tempted to add more code here, DON'T!
4899  * Whatever you had in mind to do should be set up as an
4900  * on_proc_exit or on_shmem_exit callback, instead. Otherwise
4901  * it will fail to be called during other backend-shutdown
4902  * scenarios.
4903  */
4904  proc_exit(0);
4905 
4906  case PqMsg_CopyData:
4907  case PqMsg_CopyDone:
4908  case PqMsg_CopyFail:
4909 
4910  /*
4911  * Accept but ignore these messages, per protocol spec; we
4912  * probably got here because a COPY failed, and the frontend
4913  * is still sending data.
4914  */
4915  break;
4916 
4917  default:
4918  ereport(FATAL,
4919  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4920  errmsg("invalid frontend message type %d",
4921  firstchar)));
4922  }
4923  } /* end of input-reading loop */
4924 }
4925 
4926 /*
4927  * Throw an error if we're a WAL sender process.
4928  *
4929  * This is used to forbid anything else than simple query protocol messages
4930  * in a WAL sender process. 'firstchar' specifies what kind of a forbidden
4931  * message was received, and is used to construct the error message.
4932  */
4933 static void
4935 {
4936  if (am_walsender)
4937  {
4938  if (firstchar == PqMsg_FunctionCall)
4939  ereport(ERROR,
4940  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4941  errmsg("fastpath function calls not supported in a replication connection")));
4942  else
4943  ereport(ERROR,
4944  (errcode(ERRCODE_PROTOCOL_VIOLATION),
4945  errmsg("extended query protocol not supported in a replication connection")));
4946  }
4947 }
4948 
4949 
4950 /*
4951  * Obtain platform stack depth limit (in bytes)
4952  *
4953  * Return -1 if unknown
4954  */
4955 long
4957 {
4958 #if defined(HAVE_GETRLIMIT)
4959  static long val = 0;
4960 
4961  /* This won't change after process launch, so check just once */
4962  if (val == 0)
4963  {
4964  struct rlimit rlim;
4965 
4966  if (getrlimit(RLIMIT_STACK, &rlim) < 0)
4967  val = -1;
4968  else if (rlim.rlim_cur == RLIM_INFINITY)
4969  val = LONG_MAX;
4970  /* rlim_cur is probably of an unsigned type, so check for overflow */
4971  else if (rlim.rlim_cur >= LONG_MAX)
4972  val = LONG_MAX;
4973  else
4974  val = rlim.rlim_cur;
4975  }
4976  return val;
4977 #else
4978  /* On Windows we set the backend stack size in src/backend/Makefile */
4979  return WIN32_STACK_RLIMIT;
4980 #endif
4981 }
4982 
4983 
4984 static struct rusage Save_r;
4985 static struct timeval Save_t;
4986 
4987 void
4989 {
4991  gettimeofday(&Save_t, NULL);
4992 }
4993 
4994 void
4995 ShowUsage(const char *title)
4996 {
4998  struct timeval user,
4999  sys;
5000  struct timeval elapse_t;
5001  struct rusage r;
5002 
5003  getrusage(RUSAGE_SELF, &r);
5004  gettimeofday(&elapse_t, NULL);
5005  memcpy((char *) &user, (char *) &r.ru_utime, sizeof(user));
5006  memcpy((char *) &sys, (char *) &r.ru_stime, sizeof(sys));
5007  if (elapse_t.tv_usec < Save_t.tv_usec)
5008  {
5009  elapse_t.tv_sec--;
5010  elapse_t.tv_usec += 1000000;
5011  }
5012  if (r.ru_utime.tv_usec < Save_r.ru_utime.tv_usec)
5013  {
5014  r.ru_utime.tv_sec--;
5015  r.ru_utime.tv_usec += 1000000;
5016  }
5017  if (r.ru_stime.tv_usec < Save_r.ru_stime.tv_usec)
5018  {
5019  r.ru_stime.tv_sec--;
5020  r.ru_stime.tv_usec += 1000000;
5021  }
5022 
5023  /*
5024  * The only stats we don't show here are ixrss, idrss, isrss. It takes
5025  * some work to interpret them, and most platforms don't fill them in.
5026  */
5027  initStringInfo(&str);
5028 
5029  appendStringInfoString(&str, "! system usage stats:\n");
5031  "!\t%ld.%06ld s user, %ld.%06ld s system, %ld.%06ld s elapsed\n",
5032  (long) (r.ru_utime.tv_sec - Save_r.ru_utime.tv_sec),
5033  (long) (r.ru_utime.tv_usec - Save_r.ru_utime.tv_usec),
5034  (long) (r.ru_stime.tv_sec - Save_r.ru_stime.tv_sec),
5035  (long) (r.ru_stime.tv_usec - Save_r.ru_stime.tv_usec),
5036  (long) (elapse_t.tv_sec - Save_t.tv_sec),
5037  (long) (elapse_t.tv_usec - Save_t.tv_usec));
5039  "!\t[%ld.%06ld s user, %ld.%06ld s system total]\n",
5040  (long) user.tv_sec,
5041  (long) user.tv_usec,
5042  (long) sys.tv_sec,
5043  (long) sys.tv_usec);
5044 #ifndef WIN32
5045 
5046  /*
5047  * The following rusage fields are not defined by POSIX, but they're
5048  * present on all current Unix-like systems so we use them without any
5049  * special checks. Some of these could be provided in our Windows
5050  * emulation in src/port/win32getrusage.c with more work.
5051  */
5053  "!\t%ld kB max resident size\n",
5054 #if defined(__darwin__)
5055  /* in bytes on macOS */
5056  r.ru_maxrss / 1024
5057 #else
5058  /* in kilobytes on most other platforms */
5059  r.ru_maxrss
5060 #endif
5061  );
5063  "!\t%ld/%ld [%ld/%ld] filesystem blocks in/out\n",
5064  r.ru_inblock - Save_r.ru_inblock,
5065  /* they only drink coffee at dec */
5066  r.ru_oublock - Save_r.ru_oublock,
5067  r.ru_inblock, r.ru_oublock);
5069  "!\t%ld/%ld [%ld/%ld] page faults/reclaims, %ld [%ld] swaps\n",
5070  r.ru_majflt - Save_r.ru_majflt,
5071  r.ru_minflt - Save_r.ru_minflt,
5072  r.ru_majflt, r.ru_minflt,
5073  r.ru_nswap - Save_r.ru_nswap,
5074  r.ru_nswap);
5076  "!\t%ld [%ld] signals rcvd, %ld/%ld [%ld/%ld] messages rcvd/sent\n",
5077  r.ru_nsignals - Save_r.ru_nsignals,
5078  r.ru_nsignals,
5079  r.ru_msgrcv - Save_r.ru_msgrcv,
5080  r.ru_msgsnd - Save_r.ru_msgsnd,
5081  r.ru_msgrcv, r.ru_msgsnd);
5083  "!\t%ld/%ld [%ld/%ld] voluntary/involuntary context switches\n",
5084  r.ru_nvcsw - Save_r.ru_nvcsw,
5085  r.ru_nivcsw - Save_r.ru_nivcsw,
5086  r.ru_nvcsw, r.ru_nivcsw);
5087 #endif /* !WIN32 */
5088 
5089  /* remove trailing newline */
5090  if (str.data[str.len - 1] == '\n')
5091  str.data[--str.len] = '\0';
5092 
5093  ereport(LOG,
5094  (errmsg_internal("%s", title),
5095  errdetail_internal("%s", str.data)));
5096 
5097  pfree(str.data);
5098 }
5099 
5100 /*
5101  * on_proc_exit handler to log end of session
5102  */
5103 static void
5105 {
5106  Port *port = MyProcPort;
5107  long secs;
5108  int usecs;
5109  int msecs;
5110  int hours,
5111  minutes,
5112  seconds;
5113 
5116  &secs, &usecs);
5117  msecs = usecs / 1000;
5118 
5119  hours = secs / SECS_PER_HOUR;
5120  secs %= SECS_PER_HOUR;
5121  minutes = secs / SECS_PER_MINUTE;
5122  seconds = secs % SECS_PER_MINUTE;
5123 
5124  ereport(LOG,
5125  (errmsg("disconnection: session time: %d:%02d:%02d.%03d "
5126  "user=%s database=%s host=%s%s%s",
5127  hours, minutes, seconds, msecs,
5128  port->user_name, port->database_name, port->remote_host,
5129  port->remote_port[0] ? " port=" : "", port->remote_port)));
5130 }
5131 
5132 /*
5133  * Start statement timeout timer, if enabled.
5134  *
5135  * If there's already a timeout running, don't restart the timer. That
5136  * enables compromises between accuracy of timeouts and cost of starting a
5137  * timeout.
5138  */
5139 static void
5141 {
5142  /* must be within an xact */
5144 
5145  if (StatementTimeout > 0
5147  {
5150  }
5151  else
5152  {
5155  }
5156 }
5157 
5158 /*
5159  * Disable statement timeout, if active.
5160  */
5161 static void
5163 {
5166 }
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:4744
void TimestampDifference(TimestampTz start_time, TimestampTz stop_time, long *secs, int *microsecs)
Definition: timestamp.c:1730
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1654
TimestampTz PgStartTime
Definition: timestamp.c:52
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:5010
#define unconstify(underlying_type, expr)
Definition: c.h:1232
signed short int16
Definition: c.h:480
signed int int32
Definition: c.h:481
#define SIGNAL_ARGS
Definition: c.h:1332
#define unlikely(x)
Definition: c.h:298
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:165
void BeginCommand(CommandTag commandTag, CommandDest dest)
Definition: dest.c:102
void ReadyForQuery(CommandDest dest)
Definition: dest.c:250
DestReceiver * CreateDestReceiver(CommandDest dest)
Definition: dest.c:112
void NullCommand(CommandDest dest)
Definition: dest.c:213
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:1159
int errhidestmt(bool hide_stmt)
Definition: elog.c:1413
void EmitErrorReport(void)
Definition: elog.c:1672
int errdetail_internal(const char *fmt,...)
Definition: elog.c:1232
int errdetail(const char *fmt,...)
Definition: elog.c:1205
ErrorContextCallback * error_context_stack
Definition: elog.c:94
void FlushErrorState(void)
Definition: elog.c:1828
int errhint(const char *fmt,...)
Definition: elog.c:1319
int errcode(int sqlerrcode)
Definition: elog.c:859
int errmsg(const char *fmt,...)
Definition: elog.c:1072
#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:40
volatile sig_atomic_t LogMemoryContextPending
Definition: globals.c:39
volatile sig_atomic_t ProcSignalBarrierPending
Definition: globals.c:38
volatile sig_atomic_t InterruptPending
Definition: globals.c:30
volatile sig_atomic_t IdleSessionTimeoutPending
Definition: globals.c:37
bool IsBinaryUpgrade
Definition: globals.c:117
volatile uint32 QueryCancelHoldoffCount
Definition: globals.c:42
int32 MyCancelKey
Definition: globals.c:49
ProtocolVersion FrontendProtocol
Definition: globals.c:28
volatile sig_atomic_t IdleInTransactionSessionTimeoutPending
Definition: globals.c:35
volatile uint32 InterruptHoldoffCount
Definition: globals.c:41
volatile sig_atomic_t TransactionTimeoutPending
Definition: globals.c:36
int MyProcPid
Definition: globals.c:45
bool IsUnderPostmaster
Definition: globals.c:116
volatile sig_atomic_t ClientConnectionLost
Definition: globals.c:34
volatile uint32 CritSectionCount
Definition: globals.c:43
volatile sig_atomic_t QueryCancelPending
Definition: globals.c:31
TimestampTz MyStartTimestamp
Definition: globals.c:47
struct Port * MyProcPort
Definition: globals.c:48
struct Latch * MyLatch
Definition: globals.c:59
char OutputFileName[MAXPGPATH]
Definition: globals.c:75
volatile sig_atomic_t ProcDiePending
Definition: globals.c:32
volatile sig_atomic_t CheckClientConnectionPending
Definition: globals.c:33
Oid MyDatabaseId
Definition: globals.c:90
void BeginReportingGUCOptions(void)
Definition: guc.c:2530
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:4257
#define newval
bool SelectConfigFiles(const char *userDoption, const char *progname)
Definition: guc.c:1780
void ParseLongOption(const char *string, char **name, char **value)
Definition: guc.c:6288
void InitializeGUCOptions(void)
Definition: guc.c:1526
void ReportChangedGUCOptions(void)
Definition: guc.c:2580
#define GUC_check_errdetail
Definition: guc.h:446
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:450
void ProcessConfigFile(GucContext context)
bool log_statement_stats
Definition: guc_tables.c:506
bool Debug_print_plan
Definition: guc_tables.c:498
bool log_parser_stats
Definition: guc_tables.c:503
bool Debug_pretty_print
Definition: guc_tables.c:501
int log_parameter_max_length_on_error
Definition: guc_tables.c:527
int log_min_duration_statement
Definition: guc_tables.c:525
int log_min_duration_sample
Definition: guc_tables.c:524
bool log_planner_stats
Definition: guc_tables.c:504
bool Debug_print_rewritten
Definition: guc_tables.c:500
bool Debug_print_parse
Definition: guc_tables.c:499
int log_parameter_max_length
Definition: guc_tables.c:526
double log_statement_sample_rate
Definition: guc_tables.c:529
bool log_duration
Definition: guc_tables.c:497
bool log_executor_stats
Definition: guc_tables.c:505
#define stmt
Definition: indent_codes.h:59
long val
Definition: informix.c:664
static struct @149 value
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:2215
bool IsLogicalLauncher(void)
Definition: launcher.c:1243
#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)
Assert(fmt[strlen(fmt) - 1] !='\n')
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:2830
void getTypeBinaryInputInfo(Oid type, Oid *typReceive, Oid *typIOParam)
Definition: lsyscache.c:2896
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:1587
MemoryContext MessageContext
Definition: mcxt.c:141
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:326
void MemoryContextSetParent(MemoryContext context, MemoryContext new_parent)
Definition: mcxt.c:542
char * pstrdup(const char *in)
Definition: mcxt.c:1576
void pfree(void *pointer)
Definition: mcxt.c:1401
MemoryContext TopMemoryContext
Definition: mcxt.c:137
void MemoryContextStats(MemoryContext context)
Definition: mcxt.c:708
MemoryContext PostmasterContext
Definition: mcxt.c:139
void ProcessLogMemoryContextInterrupt(void)
Definition: mcxt.c:1170
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:399
#define AllocSetContextCreate
Definition: memutils.h:128
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:152
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:135
@ NormalProcessing
Definition: miscadmin.h:446
@ InitProcessing
Definition: miscadmin.h:445
#define HOLD_CANCEL_INTERRUPTS()
Definition: miscadmin.h:141
#define INIT_PG_LOAD_SESSION_LIBS
Definition: miscadmin.h:473
#define AmAutoVacuumWorkerProcess()
Definition: miscadmin.h:372
#define RESUME_CANCEL_INTERRUPTS()
Definition: miscadmin.h:143
#define AmBackgroundWorkerProcess()
Definition: miscadmin.h:373
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:122
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:133
#define SetProcessingMode(mode)
Definition: miscadmin.h:457
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:223
@ CMD_UTILITY
Definition: nodes.h:260
#define makeNode(_type_)
Definition: nodes.h:155
char * nodeToString(const void *obj)
Definition: outfuncs.c:762
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:124
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:3510
@ TRANS_STMT_ROLLBACK
Definition: parsenodes.h:3507
@ TRANS_STMT_COMMIT
Definition: parsenodes.h:3506
@ TRANS_STMT_PREPARE
Definition: parsenodes.h:3511
#define FETCH_ALL
Definition: parsenodes.h:3174
#define CURSOR_OPT_PARALLEL_OK
Definition: parsenodes.h:3139
#define CURSOR_OPT_BINARY
Definition: parsenodes.h:3129
Query * parse_analyze_withcb(RawStmt *parseTree, const char *sourceText, ParserSetupHook parserSetup, void *parserSetupArg, QueryEnvironment *queryEnv)
Definition: analyze.c:186
bool analyze_requires_snapshot(RawStmt *parseTree)
Definition: analyze.c:486
Query * parse_analyze_varparams(RawStmt *parseTree, const char *sourceText, Oid **paramTypes, int *numParams, QueryEnvironment *queryEnv)
Definition: analyze.c:145
Query * parse_analyze_fixedparams(RawStmt *parseTree, const char *sourceText, const Oid *paramTypes, int numParams, QueryEnvironment *queryEnv)
Definition: analyze.c:105
@ 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:232
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
const char * username
Definition: pgbench.c:296
long pgstat_report_stat(bool force)
Definition: pgstat.c:579
@ 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:1641
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:1169
PlannedStmt * planner(Query *parse, const char *query_string, int cursorOptions, ParamListInfo boundParams)
Definition: planner.c:268
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:2508
struct BindParamCbData BindParamCbData
static void disable_statement_timeout(void)
Definition: postgres.c:5162
int log_statement
Definition: postgres.c:94
List * pg_parse_query(const char *query_string)
Definition: postgres.c:610
static bool IsTransactionStmtList(List *pstmts)
Definition: postgres.c:2834
void assign_transaction_timeout(int newval, void *extra)
Definition: postgres.c:3648
static bool check_log_statement(List *stmt_list)
Definition: postgres.c:2339
static void exec_describe_statement_message(const char *stmt_name)
Definition: postgres.c:2596
void process_postgres_switches(int argc, char *argv[], GucContext ctx, const char **dbname)
Definition: postgres.c:3782
void restore_stack_base(pg_stack_base_t base)
Definition: postgres.c:3506
int PostAuthDelay
Definition: postgres.c:100
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:5104
static int errdetail_abort(void)
Definition: postgres.c:2494
int max_stack_depth
Definition: postgres.c:97
static void forbidden_in_wal_sender(char firstchar)
Definition: postgres.c:4934
static void exec_execute_message(const char *portal_name, long max_rows)
Definition: postgres.c:2084
bool check_max_stack_depth(int *newval, void **extra, GucSource source)
Definition: postgres.c:3570
void PostgresSingleUserMain(int argc, char *argv[], const char *username)
Definition: postgres.c:4034
void set_debug_options(int debug_flag, GucContext context, GucSource source)
Definition: postgres.c:3671
static bool UseSemiNewlineNewline
Definition: postgres.c:162
static CachedPlanSource * unnamed_stmt_psrc
Definition: postgres.c:157
void FloatExceptionHandler(SIGNAL_ARGS)
Definition: postgres.c:3018
int client_connection_check_interval
Definition: postgres.c:103
bool check_log_stats(bool *newval, void **extra, GucSource source)
Definition: postgres.c:3633
static bool EchoQuery
Definition: postgres.c:161
void StatementCancelHandler(SIGNAL_ARGS)
Definition: postgres.c:3001
CommandDest whereToSendOutput
Definition: postgres.c:89
long get_stack_depth_rlimit(void)
Definition: postgres.c:4956
static bool ignore_till_sync
Definition: postgres.c:150
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:3700
static void enable_statement_timeout(void)
Definition: postgres.c:5140
static long max_stack_depth_bytes
Definition: postgres.c:124
int check_log_duration(char *msec_str, bool was_logged)
Definition: postgres.c:2378
static struct timeval Save_t
Definition: postgres.c:4985
const char * debug_query_string
Definition: postgres.c:86
static void exec_simple_query(const char *query_string)
Definition: postgres.c:1012
List * pg_analyze_and_rewrite_varparams(RawStmt *parsetree, const char *query_string, Oid **paramTypes, int *numParams, QueryEnvironment *queryEnv)
Definition: postgres.c:709
void HandleRecoveryConflictInterrupt(ProcSignalReason reason)
Definition: postgres.c:3034
static volatile sig_atomic_t RecoveryConflictPendingReasons[NUM_PROCSIGNALS]
Definition: postgres.c:166
static int errdetail_execute(List *raw_parsetree_list)
Definition: postgres.c:2441
List * pg_analyze_and_rewrite_withcb(RawStmt *parsetree, const char *query_string, ParserSetupHook parserSetup, void *parserSetupArg, QueryEnvironment *queryEnv)
Definition: postgres.c:763
void ShowUsage(const char *title)
Definition: postgres.c:4995
static void exec_parse_message(const char *query_string, const char *stmt_name, Oid *paramTypes, int numParams)
Definition: postgres.c:1390
List * pg_analyze_and_rewrite_fixedparams(RawStmt *parsetree, const char *query_string, const Oid *paramTypes, int numParams, QueryEnvironment *queryEnv)
Definition: postgres.c:670
static const char * userDoption
Definition: postgres.c:160
static volatile sig_atomic_t RecoveryConflictPending
Definition: postgres.c:165
static void exec_bind_message(StringInfo input_message)
Definition: postgres.c:1625
static bool DoingCommandRead
Definition: postgres.c:143
List * pg_rewrite_query(Query *query)
Definition: postgres.c:803
void die(SIGNAL_ARGS)
Definition: postgres.c:2971
const char * get_stats_option_name(const char *arg)
Definition: postgres.c:3742
static bool xact_started
Definition: postgres.c:136
static int interactive_getc(void)
Definition: postgres.c:331
bool stack_is_too_deep(void)
Definition: postgres.c:3537
static int errdetail_params(ParamListInfo params)
Definition: postgres.c:2474
static void ProcessRecoveryConflictInterrupts(void)
Definition: postgres.c:3204
static int SocketBackend(StringInfo inBuf)
Definition: postgres.c:359
void ProcessClientReadInterrupt(bool blocked)
Definition: postgres.c:508
void assign_max_stack_depth(int newval, void *extra)
Definition: postgres.c:3587
void ProcessInterrupts(void)
Definition: postgres.c:3243
static void bind_param_error_callback(void *arg)
Definition: postgres.c:2547
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:885
void PostgresMain(const char *dbname, const char *username)
Definition: postgres.c:4144
static MemoryContext row_description_context
Definition: postgres.c:169
static int InteractiveBackend(StringInfo inBuf)
Definition: postgres.c:243
static void ProcessRecoveryConflictInterrupt(ProcSignalReason reason)
Definition: postgres.c:3046
static char * stack_base_ptr
Definition: postgres.c:130
static struct rusage Save_r
Definition: postgres.c:4984
bool check_client_connection_check_interval(int *newval, void **extra, GucSource source)
Definition: postgres.c:3598
static StringInfoData row_description_buf
Definition: postgres.c:170
void ProcessClientWriteInterrupt(bool blocked)
Definition: postgres.c:554
static bool doing_extended_query_message
Definition: postgres.c:149
void ResetUsage(void)
Definition: postgres.c:4988
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:971
static void exec_describe_portal_message(const char *portal_name)
Definition: postgres.c:2690
void check_stack_depth(void)
Definition: postgres.c:3523
bool Log_disconnections
Definition: postgres.c:92
pg_stack_base_t set_stack_base(void)
Definition: postgres.c:3473
static void drop_unnamed_stmt(void)
Definition: postgres.c:2849
#define valgrind_report_error_query(query)
Definition: postgres.c:223
static int ReadCommand(StringInfo inBuf)
Definition: postgres.c:487
bool check_stage_log_stats(bool *newval, void **extra, GucSource source)
Definition: postgres.c:3619
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:559
void BaseInit(void)
Definition: postinit.c:629
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, bits32 flags, char *out_dbname)
Definition: postinit.c:720
bool ClientAuthInProgress
Definition: postmaster.c:357
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:192
int pq_getmessage(StringInfo s, int maxlen)
Definition: pqcomm.c:1218
int pq_getbyte(void)
Definition: pqcomm.c:981
bool pq_is_reading_msg(void)
Definition: pqcomm.c:1196
bool pq_check_connection(void)
Definition: pqcomm.c:2039
void pq_startmsgread(void)
Definition: pqcomm.c:1156
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:99
void SendRowDescriptionMessage(StringInfo buf, TupleDesc typeinfo, List *targetlist, int16 *formats)
Definition: printtup.c:165
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