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