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