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