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