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