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