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