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