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