1 /*-------------------------------------------------------------------------
4 * POSTGRES C Backend Interface
6 * Portions Copyright (c) 1996-2017, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * src/backend/tcop/postgres.c
14 * this is the "main" module of the postgres backend and
15 * hence the main module of the "traffic cop".
17 *-------------------------------------------------------------------------
26 #include <sys/socket.h>
27 #ifdef HAVE_SYS_SELECT_H
28 #include <sys/select.h>
30 #ifdef HAVE_SYS_RESOURCE_H
32 #include <sys/resource.h>
35 #ifndef HAVE_GETRUSAGE
36 #include "rusagestub.h"
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"
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"
83 const char *debug_query_string; /* client-supplied query string */
85 /* Note: whereToSendOutput is initialized for the bootstrap/standalone case */
86 CommandDest whereToSendOutput = DestDebug;
88 /* flag for logging end of session */
89 bool Log_disconnections = false;
91 int log_statement = LOGSTMT_NONE;
93 /* GUC variable for maximum stack depth (measured in kilobytes) */
94 int max_stack_depth = 100;
96 /* wait N seconds to allow attach from a debugger */
97 int PostAuthDelay = 0;
106 /* max_stack_depth converted to bytes for speed of checking */
107 static long max_stack_depth_bytes = 100 * 1024L;
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.
115 char *stack_base_ptr = NULL;
118 * On IA64 we also have to remember the register stack base.
120 #if defined(__ia64__) || defined(__ia64)
121 char *register_stack_base_ptr = NULL;
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?)
129 static volatile sig_atomic_t got_SIGHUP = false;
132 * Flag to keep track of whether we have started a transaction.
133 * For extended query protocol this has to be remembered across messages.
135 static bool xact_started = false;
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.
142 static bool DoingCommandRead = false;
145 * Flags to implement skip-till-Sync-after-error behavior for messages of
146 * the extended query protocol.
148 static bool doing_extended_query_message = false;
149 static bool ignore_till_sync = false;
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.
156 static CachedPlanSource *unnamed_stmt_psrc = NULL;
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 */
163 /* whether or not, and why, we were canceled by conflict with recovery */
164 static bool RecoveryConflictPending = false;
165 static bool RecoveryConflictRetryable = true;
166 static ProcSignalReason RecoveryConflictReason;
168 /* ----------------------------------------------------------------
169 * decls for routines only used in this file
170 * ----------------------------------------------------------------
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);
193 /* ----------------------------------------------------------------
194 * routines to obtain user input
195 * ----------------------------------------------------------------
199 * InteractiveBackend() is called for user interactive connections
201 * the string entered by the user is placed in its parameter inBuf,
202 * and we act like a Q message was received.
204 * EOF is returned if end-of-file input is seen; time to shut down.
209 InteractiveBackend(StringInfo inBuf)
211 int c; /* character read from getc() */
214 * display a prompt and obtain input from the user
219 resetStringInfo(inBuf);
222 * Read characters until EOF or the appropriate delimiter is seen.
224 while ((c = interactive_getc()) != EOF)
228 if (UseSemiNewlineNewline)
231 * In -j mode, semicolon followed by two newlines ends the
232 * command; otherwise treat newline as regular character.
234 if (inBuf->len > 1 &&
235 inBuf->data[inBuf->len - 1] == '\n' &&
236 inBuf->data[inBuf->len - 2] == ';')
238 /* might as well drop the second newline */
245 * In plain mode, newline ends the command unless preceded by
248 if (inBuf->len > 0 &&
249 inBuf->data[inBuf->len - 1] == '\\')
251 /* discard backslash from inBuf */
252 inBuf->data[--inBuf->len] = '\0';
253 /* discard newline too */
258 /* keep the newline character, but end the command */
259 appendStringInfoChar(inBuf, '\n');
265 /* Not newline, or newline treated as regular character */
266 appendStringInfoChar(inBuf, (char) c);
269 /* No input before EOF signal means time to quit. */
270 if (c == EOF && inBuf->len == 0)
274 * otherwise we have a user query so process it.
277 /* Add '\0' to make it look the same as message case. */
278 appendStringInfoChar(inBuf, (char) '\0');
281 * if the query echo flag was given, print the query..
284 printf("statement: %s\n", inBuf->data);
291 * interactive_getc -- collect one character from stdin
293 * Even though we are not reading from a "client" process, we still want to
294 * respond to signals, particularly SIGTERM/SIGQUIT.
297 interactive_getc(void)
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...
307 CHECK_FOR_INTERRUPTS();
311 ProcessClientReadInterrupt(true);
317 * SocketBackend() Is called for frontend-backend connections
319 * Returns the message type code, and loads message body data into inBuf.
321 * EOF is returned if the connection is lost.
325 SocketBackend(StringInfo inBuf)
330 * Get message type code from the frontend.
332 HOLD_CANCEL_INTERRUPTS();
334 qtype = pq_getbyte();
336 if (qtype == EOF) /* frontend disconnected */
338 if (IsTransactionState())
340 (errcode(ERRCODE_CONNECTION_FAILURE),
341 errmsg("unexpected EOF on client connection with an open transaction")));
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
349 whereToSendOutput = DestNone;
351 (errcode(ERRCODE_CONNECTION_DOES_NOT_EXIST),
352 errmsg("unexpected EOF on client connection")));
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.
362 * This also gives us a place to set the doing_extended_query_message flag
363 * as soon as possible.
367 case 'Q': /* simple query */
368 doing_extended_query_message = false;
369 if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
371 /* old style without length word; convert */
372 if (pq_getstring(inBuf))
374 if (IsTransactionState())
376 (errcode(ERRCODE_CONNECTION_FAILURE),
377 errmsg("unexpected EOF on client connection with an open transaction")));
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.
385 whereToSendOutput = DestNone;
387 (errcode(ERRCODE_CONNECTION_DOES_NOT_EXIST),
388 errmsg("unexpected EOF on client connection")));
395 case 'F': /* fastpath function call */
396 doing_extended_query_message = false;
397 if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
399 if (GetOldFunctionMessage(inBuf))
401 if (IsTransactionState())
403 (errcode(ERRCODE_CONNECTION_FAILURE),
404 errmsg("unexpected EOF on client connection with an open transaction")));
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.
412 whereToSendOutput = DestNone;
414 (errcode(ERRCODE_CONNECTION_DOES_NOT_EXIST),
415 errmsg("unexpected EOF on client connection")));
422 case 'X': /* terminate */
423 doing_extended_query_message = false;
424 ignore_till_sync = false;
428 case 'C': /* close */
429 case 'D': /* describe */
430 case 'E': /* execute */
431 case 'H': /* flush */
432 case 'P': /* parse */
433 doing_extended_query_message = true;
434 /* these are only legal in protocol 3 */
435 if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
437 (errcode(ERRCODE_PROTOCOL_VIOLATION),
438 errmsg("invalid frontend message type %d", qtype)));
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 */
445 doing_extended_query_message = false;
446 /* only legal in protocol 3 */
447 if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
449 (errcode(ERRCODE_PROTOCOL_VIOLATION),
450 errmsg("invalid frontend message type %d", qtype)));
453 case 'd': /* copy data */
454 case 'c': /* copy done */
455 case 'f': /* copy fail */
456 doing_extended_query_message = false;
457 /* these are only legal in protocol 3 */
458 if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
460 (errcode(ERRCODE_PROTOCOL_VIOLATION),
461 errmsg("invalid frontend message type %d", qtype)));
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.
472 (errcode(ERRCODE_PROTOCOL_VIOLATION),
473 errmsg("invalid frontend message type %d", qtype)));
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
482 if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3)
484 if (pq_getmessage(inBuf, 0))
485 return EOF; /* suitable message already logged */
489 RESUME_CANCEL_INTERRUPTS();
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.
502 ReadCommand(StringInfo inBuf)
506 if (whereToSendOutput == DestRemote)
507 result = SocketBackend(inBuf);
509 result = InteractiveBackend(inBuf);
514 * ProcessClientReadInterrupt() - Process interrupts specific to client reads
516 * This is called just after low-level reads. That might be after the read
517 * finished successfully, or it was interrupted via interrupt.
519 * Must preserve errno!
522 ProcessClientReadInterrupt(bool blocked)
524 int save_errno = errno;
526 if (DoingCommandRead)
528 /* Check for general interrupts that arrived while reading */
529 CHECK_FOR_INTERRUPTS();
531 /* Process sinval catchup interrupts that happened while reading */
532 if (catchupInterruptPending)
533 ProcessCatchupInterrupt();
535 /* Process sinval catchup interrupts that happened while reading */
536 if (notifyInterruptPending)
537 ProcessNotifyInterrupt();
539 else if (ProcDiePending && blocked)
542 * We're dying. It's safe (and sane) to handle that now.
544 CHECK_FOR_INTERRUPTS();
551 * ProcessClientWriteInterrupt() - Process interrupts specific to client writes
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
557 * Must preserve errno!
560 ProcessClientWriteInterrupt(bool blocked)
562 int save_errno = errno;
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
571 if (ProcDiePending && blocked)
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.
579 if (whereToSendOutput == DestRemote)
580 whereToSendOutput = DestNone;
582 CHECK_FOR_INTERRUPTS();
589 * Do raw parsing (only).
591 * A list of parsetrees (RawStmt nodes) is returned, since there might be
592 * multiple commands in the given string.
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.
602 pg_parse_query(const char *query_string)
604 List *raw_parsetree_list;
606 TRACE_POSTGRESQL_QUERY_PARSE_START(query_string);
608 if (log_parser_stats)
611 raw_parsetree_list = raw_parser(query_string);
613 if (log_parser_stats)
614 ShowUsage("PARSER STATISTICS");
616 #ifdef COPY_PARSE_PLAN_TREES
617 /* Optional debugging check: pass raw parsetrees through copyObject() */
619 List *new_list = (List *) copyObject(raw_parsetree_list);
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");
625 raw_parsetree_list = new_list;
629 TRACE_POSTGRESQL_QUERY_PARSE_DONE(query_string);
631 return raw_parsetree_list;
635 * Given a raw parsetree (gram.y output), and optionally information about
636 * types of parameter symbols ($n), perform parse analysis and rule rewriting.
638 * A list of Query nodes is returned, since either the analyzer or the
639 * rewriter might expand one query to several.
641 * NOTE: for reasons mentioned above, this must be separate from raw parsing.
644 pg_analyze_and_rewrite(RawStmt *parsetree, const char *query_string,
645 Oid *paramTypes, int numParams)
648 List *querytree_list;
650 TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
653 * (1) Perform parse analysis.
655 if (log_parser_stats)
658 query = parse_analyze(parsetree, query_string, paramTypes, numParams);
660 if (log_parser_stats)
661 ShowUsage("PARSE ANALYSIS STATISTICS");
664 * (2) Rewrite the queries, as necessary
666 querytree_list = pg_rewrite_query(query);
668 TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
670 return querytree_list;
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.
679 pg_analyze_and_rewrite_params(RawStmt *parsetree,
680 const char *query_string,
681 ParserSetupHook parserSetup,
682 void *parserSetupArg)
686 List *querytree_list;
688 Assert(query_string != NULL); /* required as of 8.4 */
690 TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
693 * (1) Perform parse analysis.
695 if (log_parser_stats)
698 pstate = make_parsestate(NULL);
699 pstate->p_sourcetext = query_string;
700 (*parserSetup) (pstate, parserSetupArg);
702 query = transformTopLevelStmt(pstate, parsetree);
704 if (post_parse_analyze_hook)
705 (*post_parse_analyze_hook) (pstate, query);
707 free_parsestate(pstate);
709 if (log_parser_stats)
710 ShowUsage("PARSE ANALYSIS STATISTICS");
713 * (2) Rewrite the queries, as necessary
715 querytree_list = pg_rewrite_query(query);
717 TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
719 return querytree_list;
723 * Perform rewriting of a query produced by parse analysis.
725 * Note: query must just have come from the parser, because we do not do
726 * AcquireRewriteLocks() on it.
729 pg_rewrite_query(Query *query)
731 List *querytree_list;
733 if (Debug_print_parse)
734 elog_node_display(LOG, "parse tree", query,
737 if (log_parser_stats)
740 if (query->commandType == CMD_UTILITY)
742 /* don't rewrite utilities, just dump 'em into result list */
743 querytree_list = list_make1(query);
747 /* rewrite regular queries */
748 querytree_list = QueryRewrite(query);
751 if (log_parser_stats)
752 ShowUsage("REWRITER STATISTICS");
754 #ifdef COPY_PARSE_PLAN_TREES
755 /* Optional debugging check: pass querytree output through copyObject() */
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");
764 querytree_list = new_list;
768 if (Debug_print_rewritten)
769 elog_node_display(LOG, "rewritten parse tree", querytree_list,
772 return querytree_list;
777 * Generate a plan for a single already-rewritten query.
778 * This is a thin wrapper around planner() and takes the same parameters.
781 pg_plan_query(Query *querytree, int cursorOptions, ParamListInfo boundParams)
785 /* Utility commands have no plans. */
786 if (querytree->commandType == CMD_UTILITY)
789 /* Planner must have a snapshot in case it calls user-defined functions. */
790 Assert(ActiveSnapshotSet());
792 TRACE_POSTGRESQL_QUERY_PLAN_START();
794 if (log_planner_stats)
797 /* call the optimizer */
798 plan = planner(querytree, cursorOptions, boundParams);
800 if (log_planner_stats)
801 ShowUsage("PLANNER STATISTICS");
803 #ifdef COPY_PARSE_PLAN_TREES
804 /* Optional debugging check: pass plan output through copyObject() */
806 PlannedStmt *new_plan = (PlannedStmt *) copyObject(plan);
809 * equal() currently does not have routines to compare Plan nodes, so
810 * don't try to test equality here. Perhaps fix someday?
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");
823 * Print plan if debugging.
825 if (Debug_print_plan)
826 elog_node_display(LOG, "plan", plan, Debug_pretty_print);
828 TRACE_POSTGRESQL_QUERY_PLAN_DONE();
834 * Generate plans for a list of already-rewritten queries.
836 * For normal optimizable statements, invoke the planner. For utility
837 * statements, just make a wrapper PlannedStmt node.
839 * The result is a list of PlannedStmt nodes.
842 pg_plan_queries(List *querytrees, int cursorOptions, ParamListInfo boundParams)
844 List *stmt_list = NIL;
845 ListCell *query_list;
847 foreach(query_list, querytrees)
849 Query *query = (Query *) lfirst(query_list);
852 if (query->commandType == CMD_UTILITY)
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;
864 stmt = pg_plan_query(query, cursorOptions, boundParams);
867 stmt_list = lappend(stmt_list, stmt);
877 * Execute a "simple Query" protocol message.
880 exec_simple_query(const char *query_string)
882 CommandDest dest = whereToSendOutput;
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;
893 * Report query to various monitoring facilities.
895 debug_query_string = query_string;
897 pgstat_report_activity(STATE_RUNNING, query_string);
899 TRACE_POSTGRESQL_QUERY_START(query_string);
902 * We use save_log_statement_stats so ShowUsage doesn't report incorrect
903 * results because ResetUsage wasn't called.
905 if (save_log_statement_stats)
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.)
915 start_xact_command();
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.)
926 * Switch to appropriate context for constructing parsetrees.
928 oldcontext = MemoryContextSwitchTo(MessageContext);
931 * Do basic parsing of the query or queries (this should be safe even if
932 * we are in aborted transaction state!)
934 parsetree_list = pg_parse_query(query_string);
936 /* Log immediately if dictated by log_statement */
937 if (check_log_statement(parsetree_list))
940 (errmsg("statement: %s", query_string),
942 errdetail_execute(parsetree_list)));
947 * Switch back to transaction context to enter the loop.
949 MemoryContextSwitchTo(oldcontext);
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.)
958 isTopLevel = (list_length(parsetree_list) == 1);
961 * Run through the raw parsetree(s) and process each one.
963 foreach(parsetree_item, parsetree_list)
965 RawStmt *parsetree = (RawStmt *) lfirst(parsetree_item);
966 bool snapshot_set = false;
967 const char *commandTag;
968 char completionTag[COMPLETION_TAG_BUFSIZE];
969 List *querytree_list,
972 DestReceiver *receiver;
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
981 commandTag = CreateCommandTag(parsetree->stmt);
983 set_ps_display(commandTag, false);
985 BeginCommand(commandTag, dest);
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...)
995 if (IsAbortedTransactionBlockState() &&
996 !IsTransactionExitStmt(parsetree->stmt))
998 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
999 errmsg("current transaction is aborted, "
1000 "commands ignored until end of transaction block"),
1001 errdetail_abort()));
1003 /* Make sure we are in a transaction command */
1004 start_xact_command();
1006 /* If we got a cancel signal in parsing or prior command, quit */
1007 CHECK_FOR_INTERRUPTS();
1010 * Set up a snapshot if parse analysis/planning will need one.
1012 if (analyze_requires_snapshot(parsetree))
1014 PushActiveSnapshot(GetTransactionSnapshot());
1015 snapshot_set = true;
1019 * OK to analyze, rewrite, and plan this query.
1021 * Switch to appropriate context for constructing querytrees (again,
1022 * these must outlive the execution context).
1024 oldcontext = MemoryContextSwitchTo(MessageContext);
1026 querytree_list = pg_analyze_and_rewrite(parsetree, query_string,
1029 plantree_list = pg_plan_queries(querytree_list,
1030 CURSOR_OPT_PARALLEL_OK, NULL);
1032 /* Done with the snapshot used for parsing/planning */
1034 PopActiveSnapshot();
1036 /* If we got a cancel signal in analysis or planning, quit */
1037 CHECK_FOR_INTERRUPTS();
1040 * Create unnamed portal to run the query or queries in. If there
1041 * already is one, silently drop it.
1043 portal = CreatePortal("", true, true);
1044 /* Don't display the portal in pg_cursors */
1045 portal->visible = false;
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
1052 PortalDefineQuery(portal,
1060 * Start the portal. No parameters here.
1062 PortalStart(portal, NULL, 0, InvalidSnapshot);
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...)
1070 format = 0; /* TEXT is default */
1071 if (IsA(parsetree->stmt, FetchStmt))
1073 FetchStmt *stmt = (FetchStmt *) parsetree->stmt;
1077 Portal fportal = GetPortalByName(stmt->portalname);
1079 if (PortalIsValid(fportal) &&
1080 (fportal->cursorOptions & CURSOR_OPT_BINARY))
1081 format = 1; /* BINARY */
1084 PortalSetResultFormat(portal, 1, &format);
1087 * Now we can create the destination receiver object.
1089 receiver = CreateDestReceiver(dest);
1090 if (dest == DestRemote)
1091 SetRemoteDestReceiverParams(receiver, portal);
1094 * Switch back to transaction context for execution.
1096 MemoryContextSwitchTo(oldcontext);
1099 * Run the portal to completion, and then drop it (and the receiver).
1101 (void) PortalRun(portal,
1108 (*receiver->rDestroy) (receiver);
1110 PortalDrop(portal, false);
1112 if (IsA(parsetree->stmt, TransactionStmt))
1115 * If this was a transaction control statement, commit it. We will
1116 * start a new xact command for the next command (if any).
1118 finish_xact_command();
1120 else if (lnext(parsetree_item) == NULL)
1123 * If this is the last parsetree of the query string, close down
1124 * transaction statement before reporting command-complete. This
1125 * is so that any end-of-transaction errors are reported before
1126 * the command-complete message is issued, to avoid confusing
1127 * clients who will expect either a command-complete message or an
1128 * error, not one and then the other. But for compatibility with
1129 * historical Postgres behavior, we do not force a transaction
1130 * boundary between queries appearing in a single query string.
1132 finish_xact_command();
1137 * We need a CommandCounterIncrement after every query, except
1138 * those that start or end a transaction block.
1140 CommandCounterIncrement();
1144 * Tell client that we're done with this query. Note we emit exactly
1145 * one EndCommand report for each raw parsetree, thus one for each SQL
1146 * command the client sent, regardless of rewriting. (But a command
1147 * aborted by error will not send an EndCommand report at all.)
1149 EndCommand(completionTag, dest);
1150 } /* end loop over parsetrees */
1153 * Close down transaction statement, if one is open.
1155 finish_xact_command();
1158 * If there were no parsetrees, return EmptyQueryResponse message.
1160 if (!parsetree_list)
1164 * Emit duration logging if appropriate.
1166 switch (check_log_duration(msec_str, was_logged))
1170 (errmsg("duration: %s ms", msec_str),
1171 errhidestmt(true)));
1175 (errmsg("duration: %s ms statement: %s",
1176 msec_str, query_string),
1178 errdetail_execute(parsetree_list)));
1182 if (save_log_statement_stats)
1183 ShowUsage("QUERY STATISTICS");
1185 TRACE_POSTGRESQL_QUERY_DONE(query_string);
1187 debug_query_string = NULL;
1191 * exec_parse_message
1193 * Execute a "Parse" protocol message.
1196 exec_parse_message(const char *query_string, /* string to execute */
1197 const char *stmt_name, /* name for prepared stmt */
1198 Oid *paramTypes, /* parameter types */
1199 int numParams) /* number of parameters */
1201 MemoryContext unnamed_stmt_context = NULL;
1202 MemoryContext oldcontext;
1203 List *parsetree_list;
1204 RawStmt *raw_parse_tree;
1205 const char *commandTag;
1206 List *querytree_list;
1207 CachedPlanSource *psrc;
1209 bool save_log_statement_stats = log_statement_stats;
1213 * Report query to various monitoring facilities.
1215 debug_query_string = query_string;
1217 pgstat_report_activity(STATE_RUNNING, query_string);
1219 set_ps_display("PARSE", false);
1221 if (save_log_statement_stats)
1225 (errmsg("parse %s: %s",
1226 *stmt_name ? stmt_name : "<unnamed>",
1230 * Start up a transaction command so we can run parse analysis etc. (Note
1231 * that this will normally change current memory context.) Nothing happens
1232 * if we are already in one.
1234 start_xact_command();
1237 * Switch to appropriate context for constructing parsetrees.
1239 * We have two strategies depending on whether the prepared statement is
1240 * named or not. For a named prepared statement, we do parsing in
1241 * MessageContext and copy the finished trees into the prepared
1242 * statement's plancache entry; then the reset of MessageContext releases
1243 * temporary space used by parsing and rewriting. For an unnamed prepared
1244 * statement, we assume the statement isn't going to hang around long, so
1245 * getting rid of temp space quickly is probably not worth the costs of
1246 * copying parse trees. So in this case, we create the plancache entry's
1247 * query_context here, and do all the parsing work therein.
1249 is_named = (stmt_name[0] != '\0');
1252 /* Named prepared statement --- parse in MessageContext */
1253 oldcontext = MemoryContextSwitchTo(MessageContext);
1257 /* Unnamed prepared statement --- release any prior unnamed stmt */
1258 drop_unnamed_stmt();
1259 /* Create context for parsing */
1260 unnamed_stmt_context =
1261 AllocSetContextCreate(MessageContext,
1262 "unnamed prepared statement",
1263 ALLOCSET_DEFAULT_SIZES);
1264 oldcontext = MemoryContextSwitchTo(unnamed_stmt_context);
1268 * Do basic parsing of the query or queries (this should be safe even if
1269 * we are in aborted transaction state!)
1271 parsetree_list = pg_parse_query(query_string);
1274 * We only allow a single user statement in a prepared statement. This is
1275 * mainly to keep the protocol simple --- otherwise we'd need to worry
1276 * about multiple result tupdescs and things like that.
1278 if (list_length(parsetree_list) > 1)
1280 (errcode(ERRCODE_SYNTAX_ERROR),
1281 errmsg("cannot insert multiple commands into a prepared statement")));
1283 if (parsetree_list != NIL)
1286 bool snapshot_set = false;
1289 raw_parse_tree = (RawStmt *) linitial(parsetree_list);
1292 * Get the command name for possible use in status display.
1294 commandTag = CreateCommandTag(raw_parse_tree->stmt);
1297 * If we are in an aborted transaction, reject all commands except
1298 * COMMIT/ROLLBACK. It is important that this test occur before we
1299 * try to do parse analysis, rewrite, or planning, since all those
1300 * phases try to do database accesses, which may fail in abort state.
1301 * (It might be safe to allow some additional utility commands in this
1302 * state, but not many...)
1304 if (IsAbortedTransactionBlockState() &&
1305 !IsTransactionExitStmt(raw_parse_tree->stmt))
1307 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1308 errmsg("current transaction is aborted, "
1309 "commands ignored until end of transaction block"),
1310 errdetail_abort()));
1313 * Create the CachedPlanSource before we do parse analysis, since it
1314 * needs to see the unmodified raw parse tree.
1316 psrc = CreateCachedPlan(raw_parse_tree, query_string, commandTag);
1319 * Set up a snapshot if parse analysis will need one.
1321 if (analyze_requires_snapshot(raw_parse_tree))
1323 PushActiveSnapshot(GetTransactionSnapshot());
1324 snapshot_set = true;
1328 * Analyze and rewrite the query. Note that the originally specified
1329 * parameter set is not required to be complete, so we have to use
1330 * parse_analyze_varparams().
1332 if (log_parser_stats)
1335 query = parse_analyze_varparams(raw_parse_tree,
1341 * Check all parameter types got determined.
1343 for (i = 0; i < numParams; i++)
1345 Oid ptype = paramTypes[i];
1347 if (ptype == InvalidOid || ptype == UNKNOWNOID)
1349 (errcode(ERRCODE_INDETERMINATE_DATATYPE),
1350 errmsg("could not determine data type of parameter $%d",
1354 if (log_parser_stats)
1355 ShowUsage("PARSE ANALYSIS STATISTICS");
1357 querytree_list = pg_rewrite_query(query);
1359 /* Done with the snapshot used for parsing */
1361 PopActiveSnapshot();
1365 /* Empty input string. This is legal. */
1366 raw_parse_tree = NULL;
1368 psrc = CreateCachedPlan(raw_parse_tree, query_string, commandTag);
1369 querytree_list = NIL;
1373 * CachedPlanSource must be a direct child of MessageContext before we
1374 * reparent unnamed_stmt_context under it, else we have a disconnected
1375 * circular subgraph. Klugy, but less so than flipping contexts even more
1378 if (unnamed_stmt_context)
1379 MemoryContextSetParent(psrc->context, MessageContext);
1381 /* Finish filling in the CachedPlanSource */
1382 CompleteCachedPlan(psrc,
1384 unnamed_stmt_context,
1389 CURSOR_OPT_PARALLEL_OK, /* allow parallel mode */
1390 true); /* fixed result */
1392 /* If we got a cancel signal during analysis, quit */
1393 CHECK_FOR_INTERRUPTS();
1398 * Store the query as a prepared statement.
1400 StorePreparedStatement(stmt_name, psrc, false);
1405 * We just save the CachedPlanSource into unnamed_stmt_psrc.
1407 SaveCachedPlan(psrc);
1408 unnamed_stmt_psrc = psrc;
1411 MemoryContextSwitchTo(oldcontext);
1414 * We do NOT close the open transaction command here; that only happens
1415 * when the client sends Sync. Instead, do CommandCounterIncrement just
1416 * in case something happened during parse/plan.
1418 CommandCounterIncrement();
1421 * Send ParseComplete.
1423 if (whereToSendOutput == DestRemote)
1424 pq_putemptymessage('1');
1427 * Emit duration logging if appropriate.
1429 switch (check_log_duration(msec_str, false))
1433 (errmsg("duration: %s ms", msec_str),
1434 errhidestmt(true)));
1438 (errmsg("duration: %s ms parse %s: %s",
1440 *stmt_name ? stmt_name : "<unnamed>",
1442 errhidestmt(true)));
1446 if (save_log_statement_stats)
1447 ShowUsage("PARSE MESSAGE STATISTICS");
1449 debug_query_string = NULL;
1455 * Process a "Bind" message to create a portal from a prepared statement
1458 exec_bind_message(StringInfo input_message)
1460 const char *portal_name;
1461 const char *stmt_name;
1463 int16 *pformats = NULL;
1466 int16 *rformats = NULL;
1467 CachedPlanSource *psrc;
1471 char *saved_stmt_name;
1472 ParamListInfo params;
1473 MemoryContext oldContext;
1474 bool save_log_statement_stats = log_statement_stats;
1475 bool snapshot_set = false;
1478 /* Get the fixed part of the message */
1479 portal_name = pq_getmsgstring(input_message);
1480 stmt_name = pq_getmsgstring(input_message);
1483 (errmsg("bind %s to %s",
1484 *portal_name ? portal_name : "<unnamed>",
1485 *stmt_name ? stmt_name : "<unnamed>")));
1487 /* Find prepared statement */
1488 if (stmt_name[0] != '\0')
1490 PreparedStatement *pstmt;
1492 pstmt = FetchPreparedStatement(stmt_name, true);
1493 psrc = pstmt->plansource;
1497 /* special-case the unnamed statement */
1498 psrc = unnamed_stmt_psrc;
1501 (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
1502 errmsg("unnamed prepared statement does not exist")));
1506 * Report query to various monitoring facilities.
1508 debug_query_string = psrc->query_string;
1510 pgstat_report_activity(STATE_RUNNING, psrc->query_string);
1512 set_ps_display("BIND", false);
1514 if (save_log_statement_stats)
1518 * Start up a transaction command so we can call functions etc. (Note that
1519 * this will normally change current memory context.) Nothing happens if
1520 * we are already in one.
1522 start_xact_command();
1524 /* Switch back to message context */
1525 MemoryContextSwitchTo(MessageContext);
1527 /* Get the parameter format codes */
1528 numPFormats = pq_getmsgint(input_message, 2);
1529 if (numPFormats > 0)
1533 pformats = (int16 *) palloc(numPFormats * sizeof(int16));
1534 for (i = 0; i < numPFormats; i++)
1535 pformats[i] = pq_getmsgint(input_message, 2);
1538 /* Get the parameter value count */
1539 numParams = pq_getmsgint(input_message, 2);
1541 if (numPFormats > 1 && numPFormats != numParams)
1543 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1544 errmsg("bind message has %d parameter formats but %d parameters",
1545 numPFormats, numParams)));
1547 if (numParams != psrc->num_params)
1549 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1550 errmsg("bind message supplies %d parameters, but prepared statement \"%s\" requires %d",
1551 numParams, stmt_name, psrc->num_params)));
1554 * If we are in aborted transaction state, the only portals we can
1555 * actually run are those containing COMMIT or ROLLBACK commands. We
1556 * disallow binding anything else to avoid problems with infrastructure
1557 * that expects to run inside a valid transaction. We also disallow
1558 * binding any parameters, since we can't risk calling user-defined I/O
1561 if (IsAbortedTransactionBlockState() &&
1562 (!IsTransactionExitStmt(psrc->raw_parse_tree->stmt) ||
1565 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1566 errmsg("current transaction is aborted, "
1567 "commands ignored until end of transaction block"),
1568 errdetail_abort()));
1571 * Create the portal. Allow silent replacement of an existing portal only
1572 * if the unnamed portal is specified.
1574 if (portal_name[0] == '\0')
1575 portal = CreatePortal(portal_name, true, true);
1577 portal = CreatePortal(portal_name, false, false);
1580 * Prepare to copy stuff into the portal's memory context. We do all this
1581 * copying first, because it could possibly fail (out-of-memory) and we
1582 * don't want a failure to occur between GetCachedPlan and
1583 * PortalDefineQuery; that would result in leaking our plancache refcount.
1585 oldContext = MemoryContextSwitchTo(PortalGetHeapMemory(portal));
1587 /* Copy the plan's query string into the portal */
1588 query_string = pstrdup(psrc->query_string);
1590 /* Likewise make a copy of the statement name, unless it's unnamed */
1592 saved_stmt_name = pstrdup(stmt_name);
1594 saved_stmt_name = NULL;
1597 * Set a snapshot if we have parameters to fetch (since the input
1598 * functions might need it) or the query isn't a utility command (and
1599 * hence could require redoing parse analysis and planning). We keep the
1600 * snapshot active till we're done, so that plancache.c doesn't have to
1603 if (numParams > 0 ||
1604 (psrc->raw_parse_tree &&
1605 analyze_requires_snapshot(psrc->raw_parse_tree)))
1607 PushActiveSnapshot(GetTransactionSnapshot());
1608 snapshot_set = true;
1612 * Fetch parameters, if any, and store in the portal's memory context.
1618 params = (ParamListInfo) palloc(offsetof(ParamListInfoData, params) +
1619 numParams * sizeof(ParamExternData));
1620 /* we have static list of params, so no hooks needed */
1621 params->paramFetch = NULL;
1622 params->paramFetchArg = NULL;
1623 params->parserSetup = NULL;
1624 params->parserSetupArg = NULL;
1625 params->numParams = numParams;
1626 params->paramMask = NULL;
1628 for (paramno = 0; paramno < numParams; paramno++)
1630 Oid ptype = psrc->param_types[paramno];
1634 StringInfoData pbuf;
1638 plength = pq_getmsgint(input_message, 4);
1639 isNull = (plength == -1);
1643 const char *pvalue = pq_getmsgbytes(input_message, plength);
1646 * Rather than copying data around, we just set up a phony
1647 * StringInfo pointing to the correct portion of the message
1648 * buffer. We assume we can scribble on the message buffer so
1649 * as to maintain the convention that StringInfos have a
1650 * trailing null. This is grotty but is a big win when
1651 * dealing with very large parameter strings.
1653 pbuf.data = (char *) pvalue;
1654 pbuf.maxlen = plength + 1;
1658 csave = pbuf.data[plength];
1659 pbuf.data[plength] = '\0';
1663 pbuf.data = NULL; /* keep compiler quiet */
1667 if (numPFormats > 1)
1668 pformat = pformats[paramno];
1669 else if (numPFormats > 0)
1670 pformat = pformats[0];
1672 pformat = 0; /* default = text */
1674 if (pformat == 0) /* text mode */
1680 getTypeInputInfo(ptype, &typinput, &typioparam);
1683 * We have to do encoding conversion before calling the
1689 pstring = pg_client_to_server(pbuf.data, plength);
1691 pval = OidInputFunctionCall(typinput, pstring, typioparam, -1);
1693 /* Free result of encoding conversion, if any */
1694 if (pstring && pstring != pbuf.data)
1697 else if (pformat == 1) /* binary mode */
1704 * Call the parameter type's binary input converter
1706 getTypeBinaryInputInfo(ptype, &typreceive, &typioparam);
1713 pval = OidReceiveFunctionCall(typreceive, bufptr, typioparam, -1);
1715 /* Trouble if it didn't eat the whole buffer */
1716 if (!isNull && pbuf.cursor != pbuf.len)
1718 (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
1719 errmsg("incorrect binary data format in bind parameter %d",
1725 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1726 errmsg("unsupported format code: %d",
1728 pval = 0; /* keep compiler quiet */
1731 /* Restore message buffer contents */
1733 pbuf.data[plength] = csave;
1735 params->params[paramno].value = pval;
1736 params->params[paramno].isnull = isNull;
1739 * We mark the params as CONST. This ensures that any custom plan
1740 * makes full use of the parameter values.
1742 params->params[paramno].pflags = PARAM_FLAG_CONST;
1743 params->params[paramno].ptype = ptype;
1749 /* Done storing stuff in portal's context */
1750 MemoryContextSwitchTo(oldContext);
1752 /* Get the result format codes */
1753 numRFormats = pq_getmsgint(input_message, 2);
1754 if (numRFormats > 0)
1758 rformats = (int16 *) palloc(numRFormats * sizeof(int16));
1759 for (i = 0; i < numRFormats; i++)
1760 rformats[i] = pq_getmsgint(input_message, 2);
1763 pq_getmsgend(input_message);
1766 * Obtain a plan from the CachedPlanSource. Any cruft from (re)planning
1767 * will be generated in MessageContext. The plan refcount will be
1768 * assigned to the Portal, so it will be released at portal destruction.
1770 cplan = GetCachedPlan(psrc, params, false);
1773 * Now we can define the portal.
1775 * DO NOT put any code that could possibly throw an error between the
1776 * above GetCachedPlan call and here.
1778 PortalDefineQuery(portal,
1785 /* Done with the snapshot used for parameter I/O and parsing/planning */
1787 PopActiveSnapshot();
1790 * And we're ready to start portal execution.
1792 PortalStart(portal, params, 0, InvalidSnapshot);
1795 * Apply the result format requests to the portal.
1797 PortalSetResultFormat(portal, numRFormats, rformats);
1800 * Send BindComplete.
1802 if (whereToSendOutput == DestRemote)
1803 pq_putemptymessage('2');
1806 * Emit duration logging if appropriate.
1808 switch (check_log_duration(msec_str, false))
1812 (errmsg("duration: %s ms", msec_str),
1813 errhidestmt(true)));
1817 (errmsg("duration: %s ms bind %s%s%s: %s",
1819 *stmt_name ? stmt_name : "<unnamed>",
1820 *portal_name ? "/" : "",
1821 *portal_name ? portal_name : "",
1822 psrc->query_string),
1824 errdetail_params(params)));
1828 if (save_log_statement_stats)
1829 ShowUsage("BIND MESSAGE STATISTICS");
1831 debug_query_string = NULL;
1835 * exec_execute_message
1837 * Process an "Execute" message for a portal
1840 exec_execute_message(const char *portal_name, long max_rows)
1843 DestReceiver *receiver;
1846 char completionTag[COMPLETION_TAG_BUFSIZE];
1847 const char *sourceText;
1848 const char *prepStmtName;
1849 ParamListInfo portalParams;
1850 bool save_log_statement_stats = log_statement_stats;
1851 bool is_xact_command;
1852 bool execute_is_fetch;
1853 bool was_logged = false;
1856 /* Adjust destination to tell printtup.c what to do */
1857 dest = whereToSendOutput;
1858 if (dest == DestRemote)
1859 dest = DestRemoteExecute;
1861 portal = GetPortalByName(portal_name);
1862 if (!PortalIsValid(portal))
1864 (errcode(ERRCODE_UNDEFINED_CURSOR),
1865 errmsg("portal \"%s\" does not exist", portal_name)));
1868 * If the original query was a null string, just return
1869 * EmptyQueryResponse.
1871 if (portal->commandTag == NULL)
1873 Assert(portal->stmts == NIL);
1878 /* Does the portal contain a transaction command? */
1879 is_xact_command = IsTransactionStmtList(portal->stmts);
1882 * We must copy the sourceText and prepStmtName into MessageContext in
1883 * case the portal is destroyed during finish_xact_command. Can avoid the
1884 * copy if it's not an xact command, though.
1886 if (is_xact_command)
1888 sourceText = pstrdup(portal->sourceText);
1889 if (portal->prepStmtName)
1890 prepStmtName = pstrdup(portal->prepStmtName);
1892 prepStmtName = "<unnamed>";
1895 * An xact command shouldn't have any parameters, which is a good
1896 * thing because they wouldn't be around after finish_xact_command.
1898 portalParams = NULL;
1902 sourceText = portal->sourceText;
1903 if (portal->prepStmtName)
1904 prepStmtName = portal->prepStmtName;
1906 prepStmtName = "<unnamed>";
1907 portalParams = portal->portalParams;
1911 * Report query to various monitoring facilities.
1913 debug_query_string = sourceText;
1915 pgstat_report_activity(STATE_RUNNING, sourceText);
1917 set_ps_display(portal->commandTag, false);
1919 if (save_log_statement_stats)
1922 BeginCommand(portal->commandTag, dest);
1925 * Create dest receiver in MessageContext (we don't want it in transaction
1926 * context, because that may get deleted if portal contains VACUUM).
1928 receiver = CreateDestReceiver(dest);
1929 if (dest == DestRemoteExecute)
1930 SetRemoteDestReceiverParams(receiver, portal);
1933 * Ensure we are in a transaction command (this should normally be the
1934 * case already due to prior BIND).
1936 start_xact_command();
1939 * If we re-issue an Execute protocol request against an existing portal,
1940 * then we are only fetching more rows rather than completely re-executing
1941 * the query from the start. atStart is never reset for a v3 portal, so we
1942 * are safe to use this check.
1944 execute_is_fetch = !portal->atStart;
1946 /* Log immediately if dictated by log_statement */
1947 if (check_log_statement(portal->stmts))
1950 (errmsg("%s %s%s%s: %s",
1952 _("execute fetch from") :
1955 *portal_name ? "/" : "",
1956 *portal_name ? portal_name : "",
1959 errdetail_params(portalParams)));
1964 * If we are in aborted transaction state, the only portals we can
1965 * actually run are those containing COMMIT or ROLLBACK commands.
1967 if (IsAbortedTransactionBlockState() &&
1968 !IsTransactionExitStmtList(portal->stmts))
1970 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1971 errmsg("current transaction is aborted, "
1972 "commands ignored until end of transaction block"),
1973 errdetail_abort()));
1975 /* Check for cancel signal before we start execution */
1976 CHECK_FOR_INTERRUPTS();
1979 * Okay to run the portal.
1982 max_rows = FETCH_ALL;
1984 completed = PortalRun(portal,
1986 true, /* always top level */
1991 (*receiver->rDestroy) (receiver);
1995 if (is_xact_command)
1998 * If this was a transaction control statement, commit it. We
1999 * will start a new xact command for the next command (if any).
2001 finish_xact_command();
2006 * We need a CommandCounterIncrement after every query, except
2007 * those that start or end a transaction block.
2009 CommandCounterIncrement();
2012 /* Send appropriate CommandComplete to client */
2013 EndCommand(completionTag, dest);
2017 /* Portal run not complete, so send PortalSuspended */
2018 if (whereToSendOutput == DestRemote)
2019 pq_putemptymessage('s');
2023 * Emit duration logging if appropriate.
2025 switch (check_log_duration(msec_str, was_logged))
2029 (errmsg("duration: %s ms", msec_str),
2030 errhidestmt(true)));
2034 (errmsg("duration: %s ms %s %s%s%s: %s",
2037 _("execute fetch from") :
2040 *portal_name ? "/" : "",
2041 *portal_name ? portal_name : "",
2044 errdetail_params(portalParams)));
2048 if (save_log_statement_stats)
2049 ShowUsage("EXECUTE MESSAGE STATISTICS");
2051 debug_query_string = NULL;
2055 * check_log_statement
2056 * Determine whether command should be logged because of log_statement
2058 * stmt_list can be either raw grammar output or a list of planned
2062 check_log_statement(List *stmt_list)
2064 ListCell *stmt_item;
2066 if (log_statement == LOGSTMT_NONE)
2068 if (log_statement == LOGSTMT_ALL)
2071 /* Else we have to inspect the statement(s) to see whether to log */
2072 foreach(stmt_item, stmt_list)
2074 Node *stmt = (Node *) lfirst(stmt_item);
2076 if (GetCommandLogLevel(stmt) <= log_statement)
2084 * check_log_duration
2085 * Determine whether current command's duration should be logged
2088 * 0 if no logging is needed
2089 * 1 if just the duration should be logged
2090 * 2 if duration and query details should be logged
2092 * If logging is needed, the duration in msec is formatted into msec_str[],
2093 * which must be a 32-byte buffer.
2095 * was_logged should be TRUE if caller already logged query details (this
2096 * essentially prevents 2 from being returned).
2099 check_log_duration(char *msec_str, bool was_logged)
2101 if (log_duration || log_min_duration_statement >= 0)
2108 TimestampDifference(GetCurrentStatementStartTimestamp(),
2109 GetCurrentTimestamp(),
2111 msecs = usecs / 1000;
2114 * This odd-looking test for log_min_duration_statement being exceeded
2115 * is designed to avoid integer overflow with very long durations:
2116 * don't compute secs * 1000 until we've verified it will fit in int.
2118 exceeded = (log_min_duration_statement == 0 ||
2119 (log_min_duration_statement > 0 &&
2120 (secs > log_min_duration_statement / 1000 ||
2121 secs * 1000 + msecs >= log_min_duration_statement)));
2123 if (exceeded || log_duration)
2125 snprintf(msec_str, 32, "%ld.%03d",
2126 secs * 1000 + msecs, usecs % 1000);
2127 if (exceeded && !was_logged)
2140 * Add an errdetail() line showing the query referenced by an EXECUTE, if any.
2141 * The argument is the raw parsetree list.
2144 errdetail_execute(List *raw_parsetree_list)
2146 ListCell *parsetree_item;
2148 foreach(parsetree_item, raw_parsetree_list)
2150 RawStmt *parsetree = (RawStmt *) lfirst(parsetree_item);
2152 if (IsA(parsetree->stmt, ExecuteStmt))
2154 ExecuteStmt *stmt = (ExecuteStmt *) parsetree->stmt;
2155 PreparedStatement *pstmt;
2157 pstmt = FetchPreparedStatement(stmt->name, false);
2160 errdetail("prepare: %s", pstmt->plansource->query_string);
2172 * Add an errdetail() line showing bind-parameter data, if available.
2175 errdetail_params(ParamListInfo params)
2177 /* We mustn't call user-defined I/O functions when in an aborted xact */
2178 if (params && params->numParams > 0 && !IsAbortedTransactionBlockState())
2180 StringInfoData param_str;
2181 MemoryContext oldcontext;
2184 /* Make sure any trash is generated in MessageContext */
2185 oldcontext = MemoryContextSwitchTo(MessageContext);
2187 initStringInfo(¶m_str);
2189 for (paramno = 0; paramno < params->numParams; paramno++)
2191 ParamExternData *prm = ¶ms->params[paramno];
2197 appendStringInfo(¶m_str, "%s$%d = ",
2198 paramno > 0 ? ", " : "",
2201 if (prm->isnull || !OidIsValid(prm->ptype))
2203 appendStringInfoString(¶m_str, "NULL");
2207 getTypeOutputInfo(prm->ptype, &typoutput, &typisvarlena);
2209 pstring = OidOutputFunctionCall(typoutput, prm->value);
2211 appendStringInfoCharMacro(¶m_str, '\'');
2212 for (p = pstring; *p; p++)
2214 if (*p == '\'') /* double single quotes */
2215 appendStringInfoCharMacro(¶m_str, *p);
2216 appendStringInfoCharMacro(¶m_str, *p);
2218 appendStringInfoCharMacro(¶m_str, '\'');
2223 errdetail("parameters: %s", param_str.data);
2225 pfree(param_str.data);
2227 MemoryContextSwitchTo(oldcontext);
2236 * Add an errdetail() line showing abort reason, if any.
2239 errdetail_abort(void)
2241 if (MyProc->recoveryConflictPending)
2242 errdetail("abort reason: recovery conflict");
2248 * errdetail_recovery_conflict
2250 * Add an errdetail() line showing conflict source.
2253 errdetail_recovery_conflict(void)
2255 switch (RecoveryConflictReason)
2257 case PROCSIG_RECOVERY_CONFLICT_BUFFERPIN:
2258 errdetail("User was holding shared buffer pin for too long.");
2260 case PROCSIG_RECOVERY_CONFLICT_LOCK:
2261 errdetail("User was holding a relation lock for too long.");
2263 case PROCSIG_RECOVERY_CONFLICT_TABLESPACE:
2264 errdetail("User was or might have been using tablespace that must be dropped.");
2266 case PROCSIG_RECOVERY_CONFLICT_SNAPSHOT:
2267 errdetail("User query might have needed to see row versions that must be removed.");
2269 case PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK:
2270 errdetail("User transaction caused buffer deadlock with recovery.");
2272 case PROCSIG_RECOVERY_CONFLICT_DATABASE:
2273 errdetail("User was connected to a database that must be dropped.");
2284 * exec_describe_statement_message
2286 * Process a "Describe" message for a prepared statement
2289 exec_describe_statement_message(const char *stmt_name)
2291 CachedPlanSource *psrc;
2296 * Start up a transaction command. (Note that this will normally change
2297 * current memory context.) Nothing happens if we are already in one.
2299 start_xact_command();
2301 /* Switch back to message context */
2302 MemoryContextSwitchTo(MessageContext);
2304 /* Find prepared statement */
2305 if (stmt_name[0] != '\0')
2307 PreparedStatement *pstmt;
2309 pstmt = FetchPreparedStatement(stmt_name, true);
2310 psrc = pstmt->plansource;
2314 /* special-case the unnamed statement */
2315 psrc = unnamed_stmt_psrc;
2318 (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
2319 errmsg("unnamed prepared statement does not exist")));
2322 /* Prepared statements shouldn't have changeable result descs */
2323 Assert(psrc->fixed_result);
2326 * If we are in aborted transaction state, we can't run
2327 * SendRowDescriptionMessage(), because that needs catalog accesses.
2328 * Hence, refuse to Describe statements that return data. (We shouldn't
2329 * just refuse all Describes, since that might break the ability of some
2330 * clients to issue COMMIT or ROLLBACK commands, if they use code that
2331 * blindly Describes whatever it does.) We can Describe parameters
2332 * without doing anything dangerous, so we don't restrict that.
2334 if (IsAbortedTransactionBlockState() &&
2337 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2338 errmsg("current transaction is aborted, "
2339 "commands ignored until end of transaction block"),
2340 errdetail_abort()));
2342 if (whereToSendOutput != DestRemote)
2343 return; /* can't actually do anything... */
2346 * First describe the parameters...
2348 pq_beginmessage(&buf, 't'); /* parameter description message type */
2349 pq_sendint(&buf, psrc->num_params, 2);
2351 for (i = 0; i < psrc->num_params; i++)
2353 Oid ptype = psrc->param_types[i];
2355 pq_sendint(&buf, (int) ptype, 4);
2357 pq_endmessage(&buf);
2360 * Next send RowDescription or NoData to describe the result...
2362 if (psrc->resultDesc)
2366 /* Get the plan's primary targetlist */
2367 tlist = CachedPlanGetTargetList(psrc);
2369 SendRowDescriptionMessage(psrc->resultDesc, tlist, NULL);
2372 pq_putemptymessage('n'); /* NoData */
2377 * exec_describe_portal_message
2379 * Process a "Describe" message for a portal
2382 exec_describe_portal_message(const char *portal_name)
2387 * Start up a transaction command. (Note that this will normally change
2388 * current memory context.) Nothing happens if we are already in one.
2390 start_xact_command();
2392 /* Switch back to message context */
2393 MemoryContextSwitchTo(MessageContext);
2395 portal = GetPortalByName(portal_name);
2396 if (!PortalIsValid(portal))
2398 (errcode(ERRCODE_UNDEFINED_CURSOR),
2399 errmsg("portal \"%s\" does not exist", portal_name)));
2402 * If we are in aborted transaction state, we can't run
2403 * SendRowDescriptionMessage(), because that needs catalog accesses.
2404 * Hence, refuse to Describe portals that return data. (We shouldn't just
2405 * refuse all Describes, since that might break the ability of some
2406 * clients to issue COMMIT or ROLLBACK commands, if they use code that
2407 * blindly Describes whatever it does.)
2409 if (IsAbortedTransactionBlockState() &&
2412 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2413 errmsg("current transaction is aborted, "
2414 "commands ignored until end of transaction block"),
2415 errdetail_abort()));
2417 if (whereToSendOutput != DestRemote)
2418 return; /* can't actually do anything... */
2420 if (portal->tupDesc)
2421 SendRowDescriptionMessage(portal->tupDesc,
2422 FetchPortalTargetList(portal),
2425 pq_putemptymessage('n'); /* NoData */
2430 * Convenience routines for starting/committing a single command.
2433 start_xact_command(void)
2437 StartTransactionCommand();
2439 /* Set statement timeout running, if any */
2440 /* NB: this mustn't be enabled until we are within an xact */
2441 if (StatementTimeout > 0)
2442 enable_timeout_after(STATEMENT_TIMEOUT, StatementTimeout);
2444 disable_timeout(STATEMENT_TIMEOUT, false);
2446 xact_started = true;
2451 finish_xact_command(void)
2455 /* Cancel any active statement timeout before committing */
2456 disable_timeout(STATEMENT_TIMEOUT, false);
2458 CommitTransactionCommand();
2460 #ifdef MEMORY_CONTEXT_CHECKING
2461 /* Check all memory contexts that weren't freed during commit */
2462 /* (those that were, were checked before being deleted) */
2463 MemoryContextCheck(TopMemoryContext);
2466 #ifdef SHOW_MEMORY_STATS
2467 /* Print mem stats after each commit for leak tracking */
2468 MemoryContextStats(TopMemoryContext);
2471 xact_started = false;
2477 * Convenience routines for checking whether a statement is one of the
2478 * ones that we allow in transaction-aborted state.
2481 /* Test a bare parsetree */
2483 IsTransactionExitStmt(Node *parsetree)
2485 if (parsetree && IsA(parsetree, TransactionStmt))
2487 TransactionStmt *stmt = (TransactionStmt *) parsetree;
2489 if (stmt->kind == TRANS_STMT_COMMIT ||
2490 stmt->kind == TRANS_STMT_PREPARE ||
2491 stmt->kind == TRANS_STMT_ROLLBACK ||
2492 stmt->kind == TRANS_STMT_ROLLBACK_TO)
2498 /* Test a list that contains PlannedStmt nodes */
2500 IsTransactionExitStmtList(List *pstmts)
2502 if (list_length(pstmts) == 1)
2504 PlannedStmt *pstmt = (PlannedStmt *) linitial(pstmts);
2506 Assert(IsA(pstmt, PlannedStmt));
2507 if (pstmt->commandType == CMD_UTILITY &&
2508 IsTransactionExitStmt(pstmt->utilityStmt))
2514 /* Test a list that contains PlannedStmt nodes */
2516 IsTransactionStmtList(List *pstmts)
2518 if (list_length(pstmts) == 1)
2520 PlannedStmt *pstmt = (PlannedStmt *) linitial(pstmts);
2522 Assert(IsA(pstmt, PlannedStmt));
2523 if (pstmt->commandType == CMD_UTILITY &&
2524 IsA(pstmt->utilityStmt, TransactionStmt))
2530 /* Release any existing unnamed prepared statement */
2532 drop_unnamed_stmt(void)
2534 /* paranoia to avoid a dangling pointer in case of error */
2535 if (unnamed_stmt_psrc)
2537 CachedPlanSource *psrc = unnamed_stmt_psrc;
2539 unnamed_stmt_psrc = NULL;
2540 DropCachedPlan(psrc);
2545 /* --------------------------------
2546 * signal handler routines used in PostgresMain()
2547 * --------------------------------
2551 * quickdie() occurs when signalled SIGQUIT by the postmaster.
2553 * Some backend has bought the farm,
2554 * so we need to stop what we're doing and exit.
2557 quickdie(SIGNAL_ARGS)
2559 sigaddset(&BlockSig, SIGQUIT); /* prevent nested calls */
2560 PG_SETMASK(&BlockSig);
2563 * Prevent interrupts while exiting; though we just blocked signals that
2564 * would queue new interrupts, one may have been pending. We don't want a
2565 * quickdie() downgraded to a mere query cancel.
2570 * If we're aborting out of client auth, don't risk trying to send
2571 * anything to the client; we will likely violate the protocol, not to
2572 * mention that we may have interrupted the guts of OpenSSL or some
2573 * authentication library.
2575 if (ClientAuthInProgress && whereToSendOutput == DestRemote)
2576 whereToSendOutput = DestNone;
2579 * Ideally this should be ereport(FATAL), but then we'd not get control
2583 (errcode(ERRCODE_CRASH_SHUTDOWN),
2584 errmsg("terminating connection because of crash of another server process"),
2585 errdetail("The postmaster has commanded this server process to roll back"
2586 " the current transaction and exit, because another"
2587 " server process exited abnormally and possibly corrupted"
2589 errhint("In a moment you should be able to reconnect to the"
2590 " database and repeat your command.")));
2593 * We DO NOT want to run proc_exit() callbacks -- we're here because
2594 * shared memory may be corrupted, so we don't want to try to clean up our
2595 * transaction. Just nail the windows shut and get out of town. Now that
2596 * there's an atexit callback to prevent third-party code from breaking
2597 * things by calling exit() directly, we have to reset the callbacks
2598 * explicitly to make this work as intended.
2603 * Note we do exit(2) not exit(0). This is to force the postmaster into a
2604 * system reset cycle if some idiot DBA sends a manual SIGQUIT to a random
2605 * backend. This is necessary precisely because we don't clean up our
2606 * shared memory state. (The "dead man switch" mechanism in pmsignal.c
2607 * should ensure the postmaster sees this as a crash, too, but no harm in
2608 * being doubly sure.)
2614 * Shutdown signal from postmaster: abort transaction and exit
2615 * at soonest convenient time
2620 int save_errno = errno;
2622 /* Don't joggle the elbow of proc_exit */
2623 if (!proc_exit_inprogress)
2625 InterruptPending = true;
2626 ProcDiePending = true;
2629 /* If we're still here, waken anything waiting on the process latch */
2633 * If we're in single user mode, we want to quit immediately - we can't
2634 * rely on latches as they wouldn't work when stdin/stdout is a file.
2635 * Rather ugly, but it's unlikely to be worthwhile to invest much more
2636 * effort just for the benefit of single user mode.
2638 if (DoingCommandRead && whereToSendOutput != DestRemote)
2639 ProcessInterrupts();
2645 * Query-cancel signal from postmaster: abort current transaction
2646 * at soonest convenient time
2649 StatementCancelHandler(SIGNAL_ARGS)
2651 int save_errno = errno;
2654 * Don't joggle the elbow of proc_exit
2656 if (!proc_exit_inprogress)
2658 InterruptPending = true;
2659 QueryCancelPending = true;
2662 /* If we're still here, waken anything waiting on the process latch */
2668 /* signal handler for floating point exception */
2670 FloatExceptionHandler(SIGNAL_ARGS)
2672 /* We're not returning, so no need to save errno */
2674 (errcode(ERRCODE_FLOATING_POINT_EXCEPTION),
2675 errmsg("floating-point exception"),
2676 errdetail("An invalid floating-point operation was signaled. "
2677 "This probably means an out-of-range result or an "
2678 "invalid operation, such as division by zero.")));
2681 /* SIGHUP: set flag to re-read config file at next convenient time */
2683 SigHupHandler(SIGNAL_ARGS)
2685 int save_errno = errno;
2694 * RecoveryConflictInterrupt: out-of-line portion of recovery conflict
2695 * handling following receipt of SIGUSR1. Designed to be similar to die()
2696 * and StatementCancelHandler(). Called only by a normal user backend
2697 * that begins a transaction during recovery.
2700 RecoveryConflictInterrupt(ProcSignalReason reason)
2702 int save_errno = errno;
2705 * Don't joggle the elbow of proc_exit
2707 if (!proc_exit_inprogress)
2709 RecoveryConflictReason = reason;
2712 case PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK:
2715 * If we aren't waiting for a lock we can never deadlock.
2717 if (!IsWaitingForLock())
2720 /* Intentional drop through to check wait for pin */
2722 case PROCSIG_RECOVERY_CONFLICT_BUFFERPIN:
2725 * If we aren't blocking the Startup process there is nothing
2728 if (!HoldingBufferPinThatDelaysRecovery())
2731 MyProc->recoveryConflictPending = true;
2733 /* Intentional drop through to error handling */
2735 case PROCSIG_RECOVERY_CONFLICT_LOCK:
2736 case PROCSIG_RECOVERY_CONFLICT_TABLESPACE:
2737 case PROCSIG_RECOVERY_CONFLICT_SNAPSHOT:
2740 * If we aren't in a transaction any longer then ignore.
2742 if (!IsTransactionOrTransactionBlock())
2746 * If we can abort just the current subtransaction then we are
2747 * OK to throw an ERROR to resolve the conflict. Otherwise
2748 * drop through to the FATAL case.
2750 * XXX other times that we can throw just an ERROR *may* be
2751 * PROCSIG_RECOVERY_CONFLICT_LOCK if no locks are held in
2752 * parent transactions
2754 * PROCSIG_RECOVERY_CONFLICT_SNAPSHOT if no snapshots are held
2755 * by parent transactions and the transaction is not
2756 * transaction-snapshot mode
2758 * PROCSIG_RECOVERY_CONFLICT_TABLESPACE if no temp files or
2759 * cursors open in parent transactions
2761 if (!IsSubTransaction())
2764 * If we already aborted then we no longer need to cancel.
2765 * We do this here since we do not wish to ignore aborted
2766 * subtransactions, which must cause FATAL, currently.
2768 if (IsAbortedTransactionBlockState())
2771 RecoveryConflictPending = true;
2772 QueryCancelPending = true;
2773 InterruptPending = true;
2777 /* Intentional drop through to session cancel */
2779 case PROCSIG_RECOVERY_CONFLICT_DATABASE:
2780 RecoveryConflictPending = true;
2781 ProcDiePending = true;
2782 InterruptPending = true;
2786 elog(FATAL, "unrecognized conflict mode: %d",
2790 Assert(RecoveryConflictPending && (QueryCancelPending || ProcDiePending));
2793 * All conflicts apart from database cause dynamic errors where the
2794 * command or transaction can be retried at a later point with some
2795 * potential for success. No need to reset this, since non-retryable
2796 * conflict errors are currently FATAL.
2798 if (reason == PROCSIG_RECOVERY_CONFLICT_DATABASE)
2799 RecoveryConflictRetryable = false;
2803 * Set the process latch. This function essentially emulates signal
2804 * handlers like die() and StatementCancelHandler() and it seems prudent
2805 * to behave similarly as they do.
2813 * ProcessInterrupts: out-of-line portion of CHECK_FOR_INTERRUPTS() macro
2815 * If an interrupt condition is pending, and it's safe to service it,
2816 * then clear the flag and accept the interrupt. Called only when
2817 * InterruptPending is true.
2820 ProcessInterrupts(void)
2822 /* OK to accept any interrupts now? */
2823 if (InterruptHoldoffCount != 0 || CritSectionCount != 0)
2825 InterruptPending = false;
2829 ProcDiePending = false;
2830 QueryCancelPending = false; /* ProcDie trumps QueryCancel */
2832 /* As in quickdie, don't risk sending to client during auth */
2833 if (ClientAuthInProgress && whereToSendOutput == DestRemote)
2834 whereToSendOutput = DestNone;
2835 if (ClientAuthInProgress)
2837 (errcode(ERRCODE_QUERY_CANCELED),
2838 errmsg("canceling authentication due to timeout")));
2839 else if (IsAutoVacuumWorkerProcess())
2841 (errcode(ERRCODE_ADMIN_SHUTDOWN),
2842 errmsg("terminating autovacuum process due to administrator command")));
2843 else if (RecoveryConflictPending && RecoveryConflictRetryable)
2845 pgstat_report_recovery_conflict(RecoveryConflictReason);
2847 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
2848 errmsg("terminating connection due to conflict with recovery"),
2849 errdetail_recovery_conflict()));
2851 else if (RecoveryConflictPending)
2853 /* Currently there is only one non-retryable recovery conflict */
2854 Assert(RecoveryConflictReason == PROCSIG_RECOVERY_CONFLICT_DATABASE);
2855 pgstat_report_recovery_conflict(RecoveryConflictReason);
2857 (errcode(ERRCODE_DATABASE_DROPPED),
2858 errmsg("terminating connection due to conflict with recovery"),
2859 errdetail_recovery_conflict()));
2863 (errcode(ERRCODE_ADMIN_SHUTDOWN),
2864 errmsg("terminating connection due to administrator command")));
2866 if (ClientConnectionLost)
2868 QueryCancelPending = false; /* lost connection trumps QueryCancel */
2870 /* don't send to client, we already know the connection to be dead. */
2871 whereToSendOutput = DestNone;
2873 (errcode(ERRCODE_CONNECTION_FAILURE),
2874 errmsg("connection to client lost")));
2878 * If a recovery conflict happens while we are waiting for input from the
2879 * client, the client is presumably just sitting idle in a transaction,
2880 * preventing recovery from making progress. Terminate the connection to
2883 if (RecoveryConflictPending && DoingCommandRead)
2885 QueryCancelPending = false; /* this trumps QueryCancel */
2886 RecoveryConflictPending = false;
2888 pgstat_report_recovery_conflict(RecoveryConflictReason);
2890 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
2891 errmsg("terminating connection due to conflict with recovery"),
2892 errdetail_recovery_conflict(),
2893 errhint("In a moment you should be able to reconnect to the"
2894 " database and repeat your command.")));
2897 if (QueryCancelPending)
2899 bool lock_timeout_occurred;
2900 bool stmt_timeout_occurred;
2903 * Don't allow query cancel interrupts while reading input from the
2904 * client, because we might lose sync in the FE/BE protocol. (Die
2905 * interrupts are OK, because we won't read any further messages from
2906 * the client in that case.)
2908 if (QueryCancelHoldoffCount != 0)
2911 * Re-arm InterruptPending so that we process the cancel request
2912 * as soon as we're done reading the message.
2914 InterruptPending = true;
2918 QueryCancelPending = false;
2921 * If LOCK_TIMEOUT and STATEMENT_TIMEOUT indicators are both set, we
2922 * need to clear both, so always fetch both.
2924 lock_timeout_occurred = get_timeout_indicator(LOCK_TIMEOUT, true);
2925 stmt_timeout_occurred = get_timeout_indicator(STATEMENT_TIMEOUT, true);
2928 * If both were set, we want to report whichever timeout completed
2929 * earlier; this ensures consistent behavior if the machine is slow
2930 * enough that the second timeout triggers before we get here. A tie
2931 * is arbitrarily broken in favor of reporting a lock timeout.
2933 if (lock_timeout_occurred && stmt_timeout_occurred &&
2934 get_timeout_finish_time(STATEMENT_TIMEOUT) < get_timeout_finish_time(LOCK_TIMEOUT))
2935 lock_timeout_occurred = false; /* report stmt timeout */
2937 if (lock_timeout_occurred)
2941 (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
2942 errmsg("canceling statement due to lock timeout")));
2944 if (stmt_timeout_occurred)
2948 (errcode(ERRCODE_QUERY_CANCELED),
2949 errmsg("canceling statement due to statement timeout")));
2951 if (IsAutoVacuumWorkerProcess())
2955 (errcode(ERRCODE_QUERY_CANCELED),
2956 errmsg("canceling autovacuum task")));
2958 if (RecoveryConflictPending)
2960 RecoveryConflictPending = false;
2962 pgstat_report_recovery_conflict(RecoveryConflictReason);
2964 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
2965 errmsg("canceling statement due to conflict with recovery"),
2966 errdetail_recovery_conflict()));
2970 * If we are reading a command from the client, just ignore the cancel
2971 * request --- sending an extra error message won't accomplish
2972 * anything. Otherwise, go ahead and throw the error.
2974 if (!DoingCommandRead)
2978 (errcode(ERRCODE_QUERY_CANCELED),
2979 errmsg("canceling statement due to user request")));
2983 if (IdleInTransactionSessionTimeoutPending)
2985 /* Has the timeout setting changed since last we looked? */
2986 if (IdleInTransactionSessionTimeout > 0)
2988 (errcode(ERRCODE_IDLE_IN_TRANSACTION_SESSION_TIMEOUT),
2989 errmsg("terminating connection due to idle-in-transaction timeout")));
2991 IdleInTransactionSessionTimeoutPending = false;
2995 if (ParallelMessagePending)
2996 HandleParallelMessages();
3001 * IA64-specific code to fetch the AR.BSP register for stack depth checks.
3003 * We currently support gcc, icc, and HP-UX's native compiler here.
3005 * Note: while icc accepts gcc asm blocks on x86[_64], this is not true on
3006 * ia64 (at least not in icc versions before 12.x). So we have to carry a
3007 * separate implementation for it.
3009 #if defined(__ia64__) || defined(__ia64)
3011 #if defined(__hpux) && !defined(__GNUC__) && !defined(__INTEL_COMPILER)
3012 /* Assume it's HP-UX native compiler */
3013 #include <ia64/sys/inline.h>
3014 #define ia64_get_bsp() ((char *) (_Asm_mov_from_ar(_AREG_BSP, _NO_FENCE)))
3015 #elif defined(__INTEL_COMPILER)
3017 #include <asm/ia64regs.h>
3018 #define ia64_get_bsp() ((char *) __getReg(_IA64_REG_AR_BSP))
3021 static __inline__ char *
3026 /* the ;; is a "stop", seems to be required before fetching BSP */
3027 __asm__ __volatile__(
3039 * set_stack_base: set up reference point for stack depth checking
3041 * Returns the old reference point, if any.
3044 set_stack_base(void)
3047 pg_stack_base_t old;
3049 #if defined(__ia64__) || defined(__ia64)
3050 old.stack_base_ptr = stack_base_ptr;
3051 old.register_stack_base_ptr = register_stack_base_ptr;
3053 old = stack_base_ptr;
3056 /* Set up reference point for stack depth checking */
3057 stack_base_ptr = &stack_base;
3058 #if defined(__ia64__) || defined(__ia64)
3059 register_stack_base_ptr = ia64_get_bsp();
3066 * restore_stack_base: restore reference point for stack depth checking
3068 * This can be used after set_stack_base() to restore the old value. This
3069 * is currently only used in PL/Java. When PL/Java calls a backend function
3070 * from different thread, the thread's stack is at a different location than
3071 * the main thread's stack, so it sets the base pointer before the call, and
3072 * restores it afterwards.
3075 restore_stack_base(pg_stack_base_t base)
3077 #if defined(__ia64__) || defined(__ia64)
3078 stack_base_ptr = base.stack_base_ptr;
3079 register_stack_base_ptr = base.register_stack_base_ptr;
3081 stack_base_ptr = base;
3086 * check_stack_depth/stack_is_too_deep: check for excessively deep recursion
3088 * This should be called someplace in any recursive routine that might possibly
3089 * recurse deep enough to overflow the stack. Most Unixen treat stack
3090 * overflow as an unrecoverable SIGSEGV, so we want to error out ourselves
3091 * before hitting the hardware limit.
3093 * check_stack_depth() just throws an error summarily. stack_is_too_deep()
3094 * can be used by code that wants to handle the error condition itself.
3097 check_stack_depth(void)
3099 if (stack_is_too_deep())
3102 (errcode(ERRCODE_STATEMENT_TOO_COMPLEX),
3103 errmsg("stack depth limit exceeded"),
3104 errhint("Increase the configuration parameter \"max_stack_depth\" (currently %dkB), "
3105 "after ensuring the platform's stack depth limit is adequate.",
3111 stack_is_too_deep(void)
3117 * Compute distance from reference point to my local variables
3119 stack_depth = (long) (stack_base_ptr - &stack_top_loc);
3122 * Take abs value, since stacks grow up on some machines, down on others
3124 if (stack_depth < 0)
3125 stack_depth = -stack_depth;
3130 * The test on stack_base_ptr prevents us from erroring out if called
3131 * during process setup or in a non-backend process. Logically it should
3132 * be done first, but putting it here avoids wasting cycles during normal
3135 if (stack_depth > max_stack_depth_bytes &&
3136 stack_base_ptr != NULL)
3140 * On IA64 there is a separate "register" stack that requires its own
3141 * independent check. For this, we have to measure the change in the
3142 * "BSP" pointer from PostgresMain to here. Logic is just as above,
3143 * except that we know IA64's register stack grows up.
3145 * Note we assume that the same max_stack_depth applies to both stacks.
3147 #if defined(__ia64__) || defined(__ia64)
3148 stack_depth = (long) (ia64_get_bsp() - register_stack_base_ptr);
3150 if (stack_depth > max_stack_depth_bytes &&
3151 register_stack_base_ptr != NULL)
3158 /* GUC check hook for max_stack_depth */
3160 check_max_stack_depth(int *newval, void **extra, GucSource source)
3162 long newval_bytes = *newval * 1024L;
3163 long stack_rlimit = get_stack_depth_rlimit();
3165 if (stack_rlimit > 0 && newval_bytes > stack_rlimit - STACK_DEPTH_SLOP)
3167 GUC_check_errdetail("\"max_stack_depth\" must not exceed %ldkB.",
3168 (stack_rlimit - STACK_DEPTH_SLOP) / 1024L);
3169 GUC_check_errhint("Increase the platform's stack depth limit via \"ulimit -s\" or local equivalent.");
3175 /* GUC assign hook for max_stack_depth */
3177 assign_max_stack_depth(int newval, void *extra)
3179 long newval_bytes = newval * 1024L;
3181 max_stack_depth_bytes = newval_bytes;
3186 * set_debug_options --- apply "-d N" command line option
3188 * -d is not quite the same as setting log_min_messages because it enables
3189 * other output options.
3192 set_debug_options(int debug_flag, GucContext context, GucSource source)
3198 sprintf(debugstr, "debug%d", debug_flag);
3199 SetConfigOption("log_min_messages", debugstr, context, source);
3202 SetConfigOption("log_min_messages", "notice", context, source);
3204 if (debug_flag >= 1 && context == PGC_POSTMASTER)
3206 SetConfigOption("log_connections", "true", context, source);
3207 SetConfigOption("log_disconnections", "true", context, source);
3209 if (debug_flag >= 2)
3210 SetConfigOption("log_statement", "all", context, source);
3211 if (debug_flag >= 3)
3212 SetConfigOption("debug_print_parse", "true", context, source);
3213 if (debug_flag >= 4)
3214 SetConfigOption("debug_print_plan", "true", context, source);
3215 if (debug_flag >= 5)
3216 SetConfigOption("debug_print_rewritten", "true", context, source);
3221 set_plan_disabling_options(const char *arg, GucContext context, GucSource source)
3223 const char *tmp = NULL;
3227 case 's': /* seqscan */
3228 tmp = "enable_seqscan";
3230 case 'i': /* indexscan */
3231 tmp = "enable_indexscan";
3233 case 'o': /* indexonlyscan */
3234 tmp = "enable_indexonlyscan";
3236 case 'b': /* bitmapscan */
3237 tmp = "enable_bitmapscan";
3239 case 't': /* tidscan */
3240 tmp = "enable_tidscan";
3242 case 'n': /* nestloop */
3243 tmp = "enable_nestloop";
3245 case 'm': /* mergejoin */
3246 tmp = "enable_mergejoin";
3248 case 'h': /* hashjoin */
3249 tmp = "enable_hashjoin";
3254 SetConfigOption(tmp, "false", context, source);
3263 get_stats_option_name(const char *arg)
3268 if (optarg[1] == 'a') /* "parser" */
3269 return "log_parser_stats";
3270 else if (optarg[1] == 'l') /* "planner" */
3271 return "log_planner_stats";
3274 case 'e': /* "executor" */
3275 return "log_executor_stats";
3283 /* ----------------------------------------------------------------
3284 * process_postgres_switches
3285 * Parse command line arguments for PostgresMain
3287 * This is called twice, once for the "secure" options coming from the
3288 * postmaster or command line, and once for the "insecure" options coming
3289 * from the client's startup packet. The latter have the same syntax but
3290 * may be restricted in what they can do.
3292 * argv[0] is ignored in either case (it's assumed to be the program name).
3294 * ctx is PGC_POSTMASTER for secure options, PGC_BACKEND for insecure options
3295 * coming from the client, or PGC_SU_BACKEND for insecure options coming from
3296 * a superuser client.
3298 * If a database name is present in the command line arguments, it's
3299 * returned into *dbname (this is allowed only if *dbname is initially NULL).
3300 * ----------------------------------------------------------------
3303 process_postgres_switches(int argc, char *argv[], GucContext ctx,
3304 const char **dbname)
3306 bool secure = (ctx == PGC_POSTMASTER);
3308 GucSource gucsource;
3313 gucsource = PGC_S_ARGV; /* switches came from command line */
3315 /* Ignore the initial --single argument, if present */
3316 if (argc > 1 && strcmp(argv[1], "--single") == 0)
3324 gucsource = PGC_S_CLIENT; /* switches came from client */
3327 #ifdef HAVE_INT_OPTERR
3330 * Turn this off because it's either printed to stderr and not the log
3331 * where we'd want it, or argv[0] is now "--single", which would make for
3332 * a weird error message. We print our own error message below.
3338 * Parse command-line options. CAUTION: keep this in sync with
3339 * postmaster/postmaster.c (the option sets should not conflict) and with
3340 * the common help() function in main/main.c.
3342 while ((flag = getopt(argc, argv, "B:bc:C:D:d:EeFf:h:ijk:lN:nOo:Pp:r:S:sTt:v:W:-:")) != -1)
3347 SetConfigOption("shared_buffers", optarg, ctx, gucsource);
3351 /* Undocumented flag used for binary upgrades */
3353 IsBinaryUpgrade = true;
3357 /* ignored for consistency with the postmaster */
3362 userDoption = strdup(optarg);
3366 set_debug_options(atoi(optarg), ctx, gucsource);
3375 SetConfigOption("datestyle", "euro", ctx, gucsource);
3379 SetConfigOption("fsync", "false", ctx, gucsource);
3383 if (!set_plan_disabling_options(optarg, ctx, gucsource))
3388 SetConfigOption("listen_addresses", optarg, ctx, gucsource);
3392 SetConfigOption("listen_addresses", "*", ctx, gucsource);
3397 UseSemiNewlineNewline = true;
3401 SetConfigOption("unix_socket_directories", optarg, ctx, gucsource);
3405 SetConfigOption("ssl", "true", ctx, gucsource);
3409 SetConfigOption("max_connections", optarg, ctx, gucsource);
3413 /* ignored for consistency with postmaster */
3417 SetConfigOption("allow_system_table_mods", "true", ctx, gucsource);
3425 SetConfigOption("ignore_system_indexes", "true", ctx, gucsource);
3429 SetConfigOption("port", optarg, ctx, gucsource);
3433 /* send output (stdout and stderr) to the given file */
3435 strlcpy(OutputFileName, optarg, MAXPGPATH);
3439 SetConfigOption("work_mem", optarg, ctx, gucsource);
3443 SetConfigOption("log_statement_stats", "true", ctx, gucsource);
3447 /* ignored for consistency with the postmaster */
3452 const char *tmp = get_stats_option_name(optarg);
3455 SetConfigOption(tmp, "true", ctx, gucsource);
3464 * -v is no longer used in normal operation, since
3465 * FrontendProtocol is already set before we get here. We keep
3466 * the switch only for possible use in standalone operation,
3467 * in case we ever support using normal FE/BE protocol with a
3468 * standalone backend.
3471 FrontendProtocol = (ProtocolVersion) atoi(optarg);
3475 SetConfigOption("post_auth_delay", optarg, ctx, gucsource);
3484 ParseLongOption(optarg, &name, &value);
3489 (errcode(ERRCODE_SYNTAX_ERROR),
3490 errmsg("--%s requires a value",
3494 (errcode(ERRCODE_SYNTAX_ERROR),
3495 errmsg("-c %s requires a value",
3498 SetConfigOption(name, value, ctx, gucsource);
3515 * Optional database name should be there only if *dbname is NULL.
3517 if (!errs && dbname && *dbname == NULL && argc - optind >= 1)
3518 *dbname = strdup(argv[optind++]);
3520 if (errs || argc != optind)
3523 optind--; /* complain about the previous argument */
3525 /* spell the error message a bit differently depending on context */
3526 if (IsUnderPostmaster)
3528 (errcode(ERRCODE_SYNTAX_ERROR),
3529 errmsg("invalid command-line argument for server process: %s", argv[optind]),
3530 errhint("Try \"%s --help\" for more information.", progname)));
3533 (errcode(ERRCODE_SYNTAX_ERROR),
3534 errmsg("%s: invalid command-line argument: %s",
3535 progname, argv[optind]),
3536 errhint("Try \"%s --help\" for more information.", progname)));
3540 * Reset getopt(3) library so that it will work correctly in subprocesses
3541 * or when this function is called a second time with another array.
3544 #ifdef HAVE_INT_OPTRESET
3545 optreset = 1; /* some systems need this too */
3550 /* ----------------------------------------------------------------
3552 * postgres main loop -- all backends, interactive or otherwise start here
3554 * argc/argv are the command line arguments to be used. (When being forked
3555 * by the postmaster, these are not the original argv array of the process.)
3556 * dbname is the name of the database to connect to, or NULL if the database
3557 * name should be extracted from the command line arguments or defaulted.
3558 * username is the PostgreSQL user name to be used for the session.
3559 * ----------------------------------------------------------------
3562 PostgresMain(int argc, char *argv[],
3564 const char *username)
3567 StringInfoData input_message;
3568 sigjmp_buf local_sigjmp_buf;
3569 volatile bool send_ready_for_query = true;
3570 bool disable_idle_in_transaction_timeout = false;
3572 /* Initialize startup process environment if necessary. */
3573 if (!IsUnderPostmaster)
3574 InitStandaloneProcess(argv[0]);
3576 SetProcessingMode(InitProcessing);
3579 * Set default values for command-line options.
3581 if (!IsUnderPostmaster)
3582 InitializeGUCOptions();
3585 * Parse command-line options.
3587 process_postgres_switches(argc, argv, PGC_POSTMASTER, &dbname);
3589 /* Must have gotten a database name, or have a default (the username) */
3595 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3596 errmsg("%s: no database nor user name specified",
3600 /* Acquire configuration parameters, unless inherited from postmaster */
3601 if (!IsUnderPostmaster)
3603 if (!SelectConfigFiles(userDoption, progname))
3608 * Set up signal handlers and masks.
3610 * Note that postmaster blocked all signals before forking child process,
3611 * so there is no race condition whereby we might receive a signal before
3612 * we have set up the handler.
3614 * Also note: it's best not to use any signals that are SIG_IGNored in the
3615 * postmaster. If such a signal arrives before we are able to change the
3616 * handler to non-SIG_IGN, it'll get dropped. Instead, make a dummy
3617 * handler in the postmaster to reserve the signal. (Of course, this isn't
3618 * an issue for signals that are locally generated, such as SIGALRM and
3625 pqsignal(SIGHUP, SigHupHandler); /* set flag to read config
3627 pqsignal(SIGINT, StatementCancelHandler); /* cancel current query */
3628 pqsignal(SIGTERM, die); /* cancel current query and exit */
3631 * In a standalone backend, SIGQUIT can be generated from the keyboard
3632 * easily, while SIGTERM cannot, so we make both signals do die()
3633 * rather than quickdie().
3635 if (IsUnderPostmaster)
3636 pqsignal(SIGQUIT, quickdie); /* hard crash time */
3638 pqsignal(SIGQUIT, die); /* cancel current query and exit */
3639 InitializeTimeouts(); /* establishes SIGALRM handler */
3642 * Ignore failure to write to frontend. Note: if frontend closes
3643 * connection, we will notice it and exit cleanly when control next
3644 * returns to outer loop. This seems safer than forcing exit in the
3645 * midst of output during who-knows-what operation...
3647 pqsignal(SIGPIPE, SIG_IGN);
3648 pqsignal(SIGUSR1, procsignal_sigusr1_handler);
3649 pqsignal(SIGUSR2, SIG_IGN);
3650 pqsignal(SIGFPE, FloatExceptionHandler);
3653 * Reset some signals that are accepted by postmaster but not by
3656 pqsignal(SIGCHLD, SIG_DFL); /* system() requires this on some
3662 if (IsUnderPostmaster)
3664 /* We allow SIGQUIT (quickdie) at all times */
3665 sigdelset(&BlockSig, SIGQUIT);
3668 PG_SETMASK(&BlockSig); /* block everything except SIGQUIT */
3670 if (!IsUnderPostmaster)
3673 * Validate we have been given a reasonable-looking DataDir (if under
3674 * postmaster, assume postmaster did this already).
3677 ValidatePgVersion(DataDir);
3679 /* Change into DataDir (if under postmaster, was done already) */
3683 * Create lockfile for data directory.
3685 CreateDataDirLockFile(false);
3687 /* Initialize MaxBackends (if under postmaster, was done already) */
3688 InitializeMaxBackends();
3691 /* Early initialization */
3695 * Create a per-backend PGPROC struct in shared memory, except in the
3696 * EXEC_BACKEND case where this was done in SubPostmasterMain. We must do
3697 * this before we can use LWLocks (and in the EXEC_BACKEND case we already
3698 * had to do some stuff with LWLocks).
3701 if (!IsUnderPostmaster)
3707 /* We need to allow SIGINT, etc during the initial transaction */
3708 PG_SETMASK(&UnBlockSig);
3711 * General initialization.
3713 * NOTE: if you are tempted to add code in this vicinity, consider putting
3714 * it inside InitPostgres() instead. In particular, anything that
3715 * involves database access should be there, not here.
3717 InitPostgres(dbname, InvalidOid, username, InvalidOid, NULL);
3720 * If the PostmasterContext is still around, recycle the space; we don't
3721 * need it anymore after InitPostgres completes. Note this does not trash
3722 * *MyProcPort, because ConnCreate() allocated that space with malloc()
3723 * ... else we'd need to copy the Port data first. Also, subsidiary data
3724 * such as the username isn't lost either; see ProcessStartupPacket().
3726 if (PostmasterContext)
3728 MemoryContextDelete(PostmasterContext);
3729 PostmasterContext = NULL;
3732 SetProcessingMode(NormalProcessing);
3735 * Now all GUC states are fully set up. Report them to client if
3738 BeginReportingGUCOptions();
3741 * Also set up handler to log session end; we have to wait till now to be
3742 * sure Log_disconnections has its final value.
3744 if (IsUnderPostmaster && Log_disconnections)
3745 on_proc_exit(log_disconnections, 0);
3747 /* Perform initialization specific to a WAL sender process. */
3752 * process any libraries that should be preloaded at backend start (this
3753 * likewise can't be done until GUC settings are complete)
3755 process_session_preload_libraries();
3758 * Send this backend's cancellation info to the frontend.
3760 if (whereToSendOutput == DestRemote)
3764 pq_beginmessage(&buf, 'K');
3765 pq_sendint(&buf, (int32) MyProcPid, sizeof(int32));
3766 pq_sendint(&buf, (int32) MyCancelKey, sizeof(int32));
3767 pq_endmessage(&buf);
3768 /* Need not flush since ReadyForQuery will do it. */
3771 /* Welcome banner for standalone case */
3772 if (whereToSendOutput == DestDebug)
3773 printf("\nPostgreSQL stand-alone backend %s\n", PG_VERSION);
3776 * Create the memory context we will use in the main loop.
3778 * MessageContext is reset once per iteration of the main loop, ie, upon
3779 * completion of processing of each command message from the client.
3781 MessageContext = AllocSetContextCreate(TopMemoryContext,
3783 ALLOCSET_DEFAULT_SIZES);
3786 * Remember stand-alone backend startup time
3788 if (!IsUnderPostmaster)
3789 PgStartTime = GetCurrentTimestamp();
3792 * POSTGRES main processing loop begins here
3794 * If an exception is encountered, processing resumes here so we abort the
3795 * current transaction and start a new one.
3797 * You might wonder why this isn't coded as an infinite loop around a
3798 * PG_TRY construct. The reason is that this is the bottom of the
3799 * exception stack, and so with PG_TRY there would be no exception handler
3800 * in force at all during the CATCH part. By leaving the outermost setjmp
3801 * always active, we have at least some chance of recovering from an error
3802 * during error recovery. (If we get into an infinite loop thereby, it
3803 * will soon be stopped by overflow of elog.c's internal state stack.)
3805 * Note that we use sigsetjmp(..., 1), so that this function's signal mask
3806 * (to wit, UnBlockSig) will be restored when longjmp'ing to here. This
3807 * is essential in case we longjmp'd out of a signal handler on a platform
3808 * where that leaves the signal blocked. It's not redundant with the
3809 * unblock in AbortTransaction() because the latter is only called if we
3810 * were inside a transaction.
3813 if (sigsetjmp(local_sigjmp_buf, 1) != 0)
3816 * NOTE: if you are tempted to add more code in this if-block,
3817 * consider the high probability that it should be in
3818 * AbortTransaction() instead. The only stuff done directly here
3819 * should be stuff that is guaranteed to apply *only* for outer-level
3820 * error recovery, such as adjusting the FE/BE protocol status.
3823 /* Since not using PG_TRY, must reset error stack by hand */
3824 error_context_stack = NULL;
3826 /* Prevent interrupts while cleaning up */
3830 * Forget any pending QueryCancel request, since we're returning to
3831 * the idle loop anyway, and cancel any active timeout requests. (In
3832 * future we might want to allow some timeout requests to survive, but
3833 * at minimum it'd be necessary to do reschedule_timeouts(), in case
3834 * we got here because of a query cancel interrupting the SIGALRM
3835 * interrupt handler.) Note in particular that we must clear the
3836 * statement and lock timeout indicators, to prevent any future plain
3837 * query cancels from being misreported as timeouts in case we're
3838 * forgetting a timeout cancel.
3840 disable_all_timeouts(false);
3841 QueryCancelPending = false; /* second to avoid race condition */
3843 /* Not reading from the client anymore. */
3844 DoingCommandRead = false;
3846 /* Make sure libpq is in a good state */
3849 /* Report the error to the client and/or server log */
3853 * Make sure debug_query_string gets reset before we possibly clobber
3854 * the storage it points at.
3856 debug_query_string = NULL;
3859 * Abort the current transaction in order to recover.
3861 AbortCurrentTransaction();
3864 WalSndErrorCleanup();
3867 * We can't release replication slots inside AbortTransaction() as we
3868 * need to be able to start and abort transactions while having a slot
3869 * acquired. But we never need to hold them across top level errors,
3870 * so releasing here is fine. There's another cleanup in ProcKill()
3871 * ensuring we'll correctly cleanup on FATAL errors as well.
3873 if (MyReplicationSlot != NULL)
3874 ReplicationSlotRelease();
3876 /* We also want to cleanup temporary slots on error. */
3877 ReplicationSlotCleanup();
3880 * Now return to normal top-level context and clear ErrorContext for
3883 MemoryContextSwitchTo(TopMemoryContext);
3887 * If we were handling an extended-query-protocol message, initiate
3888 * skip till next Sync. This also causes us not to issue
3889 * ReadyForQuery (until we get Sync).
3891 if (doing_extended_query_message)
3892 ignore_till_sync = true;
3894 /* We don't have a transaction command open anymore */
3895 xact_started = false;
3898 * If an error occurred while we were reading a message from the
3899 * client, we have potentially lost track of where the previous
3900 * message ends and the next one begins. Even though we have
3901 * otherwise recovered from the error, we cannot safely read any more
3902 * messages from the client, so there isn't much we can do with the
3903 * connection anymore.
3905 if (pq_is_reading_msg())
3907 (errcode(ERRCODE_PROTOCOL_VIOLATION),
3908 errmsg("terminating connection because protocol synchronization was lost")));
3910 /* Now we can allow interrupts again */
3911 RESUME_INTERRUPTS();
3914 /* We can now handle ereport(ERROR) */
3915 PG_exception_stack = &local_sigjmp_buf;
3917 if (!ignore_till_sync)
3918 send_ready_for_query = true; /* initially, or after error */
3921 * Non-error queries loop here.
3927 * At top of loop, reset extended-query-message flag, so that any
3928 * errors encountered in "idle" state don't provoke skip.
3930 doing_extended_query_message = false;
3933 * Release storage left over from prior query cycle, and create a new
3934 * query input buffer in the cleared MessageContext.
3936 MemoryContextSwitchTo(MessageContext);
3937 MemoryContextResetAndDeleteChildren(MessageContext);
3939 initStringInfo(&input_message);
3942 * Also consider releasing our catalog snapshot if any, so that it's
3943 * not preventing advance of global xmin while we wait for the client.
3945 InvalidateCatalogSnapshotConditionally();
3948 * (1) If we've reached idle state, tell the frontend we're ready for
3951 * Note: this includes fflush()'ing the last of the prior output.
3953 * This is also a good time to send collected statistics to the
3954 * collector, and to update the PS stats display. We avoid doing
3955 * those every time through the message loop because it'd slow down
3956 * processing of batched messages, and because we don't want to report
3957 * uncommitted updates (that confuses autovacuum). The notification
3958 * processor wants a call too, if we are not in a transaction block.
3960 if (send_ready_for_query)
3962 if (IsAbortedTransactionBlockState())
3964 set_ps_display("idle in transaction (aborted)", false);
3965 pgstat_report_activity(STATE_IDLEINTRANSACTION_ABORTED, NULL);
3967 /* Start the idle-in-transaction timer */
3968 if (IdleInTransactionSessionTimeout > 0)
3970 disable_idle_in_transaction_timeout = true;
3971 enable_timeout_after(IDLE_IN_TRANSACTION_SESSION_TIMEOUT,
3972 IdleInTransactionSessionTimeout);
3975 else if (IsTransactionOrTransactionBlock())
3977 set_ps_display("idle in transaction", false);
3978 pgstat_report_activity(STATE_IDLEINTRANSACTION, NULL);
3980 /* Start the idle-in-transaction timer */
3981 if (IdleInTransactionSessionTimeout > 0)
3983 disable_idle_in_transaction_timeout = true;
3984 enable_timeout_after(IDLE_IN_TRANSACTION_SESSION_TIMEOUT,
3985 IdleInTransactionSessionTimeout);
3990 ProcessCompletedNotifies();
3991 pgstat_report_stat(false);
3993 set_ps_display("idle", false);
3994 pgstat_report_activity(STATE_IDLE, NULL);
3997 ReadyForQuery(whereToSendOutput);
3998 send_ready_for_query = false;
4002 * (2) Allow asynchronous signals to be executed immediately if they
4003 * come in while we are waiting for client input. (This must be
4004 * conditional since we don't want, say, reads on behalf of COPY FROM
4005 * STDIN doing the same thing.)
4007 DoingCommandRead = true;
4010 * (3) read a command (loop blocks here)
4012 firstchar = ReadCommand(&input_message);
4015 * (4) disable async signal conditions again.
4017 * Query cancel is supposed to be a no-op when there is no query in
4018 * progress, so if a query cancel arrived while we were idle, just
4019 * reset QueryCancelPending. ProcessInterrupts() has that effect when
4020 * it's called when DoingCommandRead is set, so check for interrupts
4021 * before resetting DoingCommandRead.
4023 CHECK_FOR_INTERRUPTS();
4024 DoingCommandRead = false;
4027 * (5) turn off the idle-in-transaction timeout
4029 if (disable_idle_in_transaction_timeout)
4031 disable_timeout(IDLE_IN_TRANSACTION_SESSION_TIMEOUT, false);
4032 disable_idle_in_transaction_timeout = false;
4036 * (6) check for any other interesting events that happened while we
4042 ProcessConfigFile(PGC_SIGHUP);
4046 * (7) process the command. But ignore it if we're skipping till
4049 if (ignore_till_sync && firstchar != EOF)
4054 case 'Q': /* simple query */
4056 const char *query_string;
4058 /* Set statement_timestamp() */
4059 SetCurrentStatementStartTimestamp();
4061 query_string = pq_getmsgstring(&input_message);
4062 pq_getmsgend(&input_message);
4065 exec_replication_command(query_string);
4067 exec_simple_query(query_string);
4069 send_ready_for_query = true;
4073 case 'P': /* parse */
4075 const char *stmt_name;
4076 const char *query_string;
4078 Oid *paramTypes = NULL;
4080 forbidden_in_wal_sender(firstchar);
4082 /* Set statement_timestamp() */
4083 SetCurrentStatementStartTimestamp();
4085 stmt_name = pq_getmsgstring(&input_message);
4086 query_string = pq_getmsgstring(&input_message);
4087 numParams = pq_getmsgint(&input_message, 2);
4092 paramTypes = (Oid *) palloc(numParams * sizeof(Oid));
4093 for (i = 0; i < numParams; i++)
4094 paramTypes[i] = pq_getmsgint(&input_message, 4);
4096 pq_getmsgend(&input_message);
4098 exec_parse_message(query_string, stmt_name,
4099 paramTypes, numParams);
4103 case 'B': /* bind */
4104 forbidden_in_wal_sender(firstchar);
4106 /* Set statement_timestamp() */
4107 SetCurrentStatementStartTimestamp();
4110 * this message is complex enough that it seems best to put
4111 * the field extraction out-of-line
4113 exec_bind_message(&input_message);
4116 case 'E': /* execute */
4118 const char *portal_name;
4121 forbidden_in_wal_sender(firstchar);
4123 /* Set statement_timestamp() */
4124 SetCurrentStatementStartTimestamp();
4126 portal_name = pq_getmsgstring(&input_message);
4127 max_rows = pq_getmsgint(&input_message, 4);
4128 pq_getmsgend(&input_message);
4130 exec_execute_message(portal_name, max_rows);
4134 case 'F': /* fastpath function call */
4135 forbidden_in_wal_sender(firstchar);
4137 /* Set statement_timestamp() */
4138 SetCurrentStatementStartTimestamp();
4140 /* Report query to various monitoring facilities. */
4141 pgstat_report_activity(STATE_FASTPATH, NULL);
4142 set_ps_display("<FASTPATH>", false);
4144 /* start an xact for this function invocation */
4145 start_xact_command();
4148 * Note: we may at this point be inside an aborted
4149 * transaction. We can't throw error for that until we've
4150 * finished reading the function-call message, so
4151 * HandleFunctionRequest() must check for it after doing so.
4152 * Be careful not to do anything that assumes we're inside a
4153 * valid transaction here.
4156 /* switch back to message context */
4157 MemoryContextSwitchTo(MessageContext);
4159 if (HandleFunctionRequest(&input_message) == EOF)
4161 /* lost frontend connection during F message input */
4164 * Reset whereToSendOutput to prevent ereport from
4165 * attempting to send any more messages to client.
4167 if (whereToSendOutput == DestRemote)
4168 whereToSendOutput = DestNone;
4173 /* commit the function-invocation transaction */
4174 finish_xact_command();
4176 send_ready_for_query = true;
4179 case 'C': /* close */
4182 const char *close_target;
4184 forbidden_in_wal_sender(firstchar);
4186 close_type = pq_getmsgbyte(&input_message);
4187 close_target = pq_getmsgstring(&input_message);
4188 pq_getmsgend(&input_message);
4193 if (close_target[0] != '\0')
4194 DropPreparedStatement(close_target, false);
4197 /* special-case the unnamed statement */
4198 drop_unnamed_stmt();
4205 portal = GetPortalByName(close_target);
4206 if (PortalIsValid(portal))
4207 PortalDrop(portal, false);
4212 (errcode(ERRCODE_PROTOCOL_VIOLATION),
4213 errmsg("invalid CLOSE message subtype %d",
4218 if (whereToSendOutput == DestRemote)
4219 pq_putemptymessage('3'); /* CloseComplete */
4223 case 'D': /* describe */
4226 const char *describe_target;
4228 forbidden_in_wal_sender(firstchar);
4230 /* Set statement_timestamp() (needed for xact) */
4231 SetCurrentStatementStartTimestamp();
4233 describe_type = pq_getmsgbyte(&input_message);
4234 describe_target = pq_getmsgstring(&input_message);
4235 pq_getmsgend(&input_message);
4237 switch (describe_type)
4240 exec_describe_statement_message(describe_target);
4243 exec_describe_portal_message(describe_target);
4247 (errcode(ERRCODE_PROTOCOL_VIOLATION),
4248 errmsg("invalid DESCRIBE message subtype %d",
4255 case 'H': /* flush */
4256 pq_getmsgend(&input_message);
4257 if (whereToSendOutput == DestRemote)
4261 case 'S': /* sync */
4262 pq_getmsgend(&input_message);
4263 finish_xact_command();
4264 send_ready_for_query = true;
4268 * 'X' means that the frontend is closing down the socket. EOF
4269 * means unexpected loss of frontend connection. Either way,
4270 * perform normal shutdown.
4276 * Reset whereToSendOutput to prevent ereport from attempting
4277 * to send any more messages to client.
4279 if (whereToSendOutput == DestRemote)
4280 whereToSendOutput = DestNone;
4283 * NOTE: if you are tempted to add more code here, DON'T!
4284 * Whatever you had in mind to do should be set up as an
4285 * on_proc_exit or on_shmem_exit callback, instead. Otherwise
4286 * it will fail to be called during other backend-shutdown
4291 case 'd': /* copy data */
4292 case 'c': /* copy done */
4293 case 'f': /* copy fail */
4296 * Accept but ignore these messages, per protocol spec; we
4297 * probably got here because a COPY failed, and the frontend
4298 * is still sending data.
4304 (errcode(ERRCODE_PROTOCOL_VIOLATION),
4305 errmsg("invalid frontend message type %d",
4308 } /* end of input-reading loop */
4312 * Throw an error if we're a WAL sender process.
4314 * This is used to forbid anything else than simple query protocol messages
4315 * in a WAL sender process. 'firstchar' specifies what kind of a forbidden
4316 * message was received, and is used to construct the error message.
4319 forbidden_in_wal_sender(char firstchar)
4323 if (firstchar == 'F')
4325 (errcode(ERRCODE_PROTOCOL_VIOLATION),
4326 errmsg("fastpath function calls not supported in a replication connection")));
4329 (errcode(ERRCODE_PROTOCOL_VIOLATION),
4330 errmsg("extended query protocol not supported in a replication connection")));
4336 * Obtain platform stack depth limit (in bytes)
4338 * Return -1 if unknown
4341 get_stack_depth_rlimit(void)
4343 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_STACK)
4344 static long val = 0;
4346 /* This won't change after process launch, so check just once */
4351 if (getrlimit(RLIMIT_STACK, &rlim) < 0)
4353 else if (rlim.rlim_cur == RLIM_INFINITY)
4355 /* rlim_cur is probably of an unsigned type, so check for overflow */
4356 else if (rlim.rlim_cur >= LONG_MAX)
4359 val = rlim.rlim_cur;
4362 #else /* no getrlimit */
4363 #if defined(WIN32) || defined(__CYGWIN__)
4364 /* On Windows we set the backend stack size in src/backend/Makefile */
4365 return WIN32_STACK_RLIMIT;
4366 #else /* not windows ... give up */
4373 static struct rusage Save_r;
4374 static struct timeval Save_t;
4379 getrusage(RUSAGE_SELF, &Save_r);
4380 gettimeofday(&Save_t, NULL);
4384 ShowUsage(const char *title)
4387 struct timeval user,
4389 struct timeval elapse_t;
4392 getrusage(RUSAGE_SELF, &r);
4393 gettimeofday(&elapse_t, NULL);
4394 memcpy((char *) &user, (char *) &r.ru_utime, sizeof(user));
4395 memcpy((char *) &sys, (char *) &r.ru_stime, sizeof(sys));
4396 if (elapse_t.tv_usec < Save_t.tv_usec)
4399 elapse_t.tv_usec += 1000000;
4401 if (r.ru_utime.tv_usec < Save_r.ru_utime.tv_usec)
4403 r.ru_utime.tv_sec--;
4404 r.ru_utime.tv_usec += 1000000;
4406 if (r.ru_stime.tv_usec < Save_r.ru_stime.tv_usec)
4408 r.ru_stime.tv_sec--;
4409 r.ru_stime.tv_usec += 1000000;
4413 * the only stats we don't show here are for memory usage -- i can't
4414 * figure out how to interpret the relevant fields in the rusage struct,
4415 * and they change names across o/s platforms, anyway. if you can figure
4416 * out what the entries mean, you can somehow extract resident set size,
4417 * shared text size, and unshared data and stack sizes.
4419 initStringInfo(&str);
4421 appendStringInfoString(&str, "! system usage stats:\n");
4422 appendStringInfo(&str,
4423 "!\t%ld.%06ld s user, %ld.%06ld s system, %ld.%06ld s elapsed\n",
4424 (long) (r.ru_utime.tv_sec - Save_r.ru_utime.tv_sec),
4425 (long) (r.ru_utime.tv_usec - Save_r.ru_utime.tv_usec),
4426 (long) (r.ru_stime.tv_sec - Save_r.ru_stime.tv_sec),
4427 (long) (r.ru_stime.tv_usec - Save_r.ru_stime.tv_usec),
4428 (long) (elapse_t.tv_sec - Save_t.tv_sec),
4429 (long) (elapse_t.tv_usec - Save_t.tv_usec));
4430 appendStringInfo(&str,
4431 "!\t[%ld.%06ld s user, %ld.%06ld s system total]\n",
4433 (long) user.tv_usec,
4435 (long) sys.tv_usec);
4436 #if defined(HAVE_GETRUSAGE)
4437 appendStringInfo(&str,
4438 "!\t%ld/%ld [%ld/%ld] filesystem blocks in/out\n",
4439 r.ru_inblock - Save_r.ru_inblock,
4440 /* they only drink coffee at dec */
4441 r.ru_oublock - Save_r.ru_oublock,
4442 r.ru_inblock, r.ru_oublock);
4443 appendStringInfo(&str,
4444 "!\t%ld/%ld [%ld/%ld] page faults/reclaims, %ld [%ld] swaps\n",
4445 r.ru_majflt - Save_r.ru_majflt,
4446 r.ru_minflt - Save_r.ru_minflt,
4447 r.ru_majflt, r.ru_minflt,
4448 r.ru_nswap - Save_r.ru_nswap,
4450 appendStringInfo(&str,
4451 "!\t%ld [%ld] signals rcvd, %ld/%ld [%ld/%ld] messages rcvd/sent\n",
4452 r.ru_nsignals - Save_r.ru_nsignals,
4454 r.ru_msgrcv - Save_r.ru_msgrcv,
4455 r.ru_msgsnd - Save_r.ru_msgsnd,
4456 r.ru_msgrcv, r.ru_msgsnd);
4457 appendStringInfo(&str,
4458 "!\t%ld/%ld [%ld/%ld] voluntary/involuntary context switches\n",
4459 r.ru_nvcsw - Save_r.ru_nvcsw,
4460 r.ru_nivcsw - Save_r.ru_nivcsw,
4461 r.ru_nvcsw, r.ru_nivcsw);
4462 #endif /* HAVE_GETRUSAGE */
4464 /* remove trailing newline */
4465 if (str.data[str.len - 1] == '\n')
4466 str.data[--str.len] = '\0';
4469 (errmsg_internal("%s", title),
4470 errdetail_internal("%s", str.data)));
4476 * on_proc_exit handler to log end of session
4479 log_disconnections(int code, Datum arg)
4481 Port *port = MyProcPort;
4489 TimestampDifference(port->SessionStartTime,
4490 GetCurrentTimestamp(),
4492 msecs = usecs / 1000;
4494 hours = secs / SECS_PER_HOUR;
4495 secs %= SECS_PER_HOUR;
4496 minutes = secs / SECS_PER_MINUTE;
4497 seconds = secs % SECS_PER_MINUTE;
4500 (errmsg("disconnection: session time: %d:%02d:%02d.%03d "
4501 "user=%s database=%s host=%s%s%s",
4502 hours, minutes, seconds, msecs,
4503 port->user_name, port->database_name, port->remote_host,
4504 port->remote_port[0] ? " port=" : "", port->remote_port)));