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