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