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