1 /*-------------------------------------------------------------------------
4 * POSTGRES C Backend Interface
6 * Portions Copyright (c) 1996-2016, 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 *parseTrees);
187 static bool IsTransactionStmtList(List *parseTrees);
188 static void drop_unnamed_stmt(void);
189 static void SigHupHandler(SIGNAL_ARGS);
190 static void log_disconnections(int code, Datum arg);
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 is returned, since there might be multiple
592 * 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(Node *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(Node *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 * Normal optimizable statements generate PlannedStmt entries in the result
837 * list. Utility statements are simply represented by their statement nodes.
840 pg_plan_queries(List *querytrees, int cursorOptions, ParamListInfo boundParams)
842 List *stmt_list = NIL;
843 ListCell *query_list;
845 foreach(query_list, querytrees)
847 Query *query = (Query *) lfirst(query_list);
850 if (query->commandType == CMD_UTILITY)
852 /* Utility commands have no plans. */
853 stmt = query->utilityStmt;
857 stmt = (Node *) pg_plan_query(query, cursorOptions, boundParams);
860 stmt_list = lappend(stmt_list, stmt);
870 * Execute a "simple Query" protocol message.
873 exec_simple_query(const char *query_string)
875 CommandDest dest = whereToSendOutput;
876 MemoryContext oldcontext;
877 List *parsetree_list;
878 ListCell *parsetree_item;
879 bool save_log_statement_stats = log_statement_stats;
880 bool was_logged = false;
886 * Report query to various monitoring facilities.
888 debug_query_string = query_string;
890 pgstat_report_activity(STATE_RUNNING, query_string);
892 TRACE_POSTGRESQL_QUERY_START(query_string);
895 * We use save_log_statement_stats so ShowUsage doesn't report incorrect
896 * results because ResetUsage wasn't called.
898 if (save_log_statement_stats)
902 * Start up a transaction command. All queries generated by the
903 * query_string will be in this same command block, *unless* we find a
904 * BEGIN/COMMIT/ABORT statement; we have to force a new xact command after
905 * one of those, else bad things will happen in xact.c. (Note that this
906 * will normally change current memory context.)
908 start_xact_command();
911 * Zap any pre-existing unnamed statement. (While not strictly necessary,
912 * it seems best to define simple-Query mode as if it used the unnamed
913 * statement and portal; this ensures we recover any storage used by prior
914 * unnamed operations.)
919 * Switch to appropriate context for constructing parsetrees.
921 oldcontext = MemoryContextSwitchTo(MessageContext);
924 * Do basic parsing of the query or queries (this should be safe even if
925 * we are in aborted transaction state!)
927 parsetree_list = pg_parse_query(query_string);
929 /* Log immediately if dictated by log_statement */
930 if (check_log_statement(parsetree_list))
933 (errmsg("statement: %s", query_string),
935 errdetail_execute(parsetree_list)));
940 * Switch back to transaction context to enter the loop.
942 MemoryContextSwitchTo(oldcontext);
945 * We'll tell PortalRun it's a top-level command iff there's exactly one
946 * raw parsetree. If more than one, it's effectively a transaction block
947 * and we want PreventTransactionChain to reject unsafe commands. (Note:
948 * we're assuming that query rewrite cannot add commands that are
949 * significant to PreventTransactionChain.)
951 isTopLevel = (list_length(parsetree_list) == 1);
954 * Run through the raw parsetree(s) and process each one.
956 foreach(parsetree_item, parsetree_list)
958 Node *parsetree = (Node *) lfirst(parsetree_item);
959 bool snapshot_set = false;
960 const char *commandTag;
961 char completionTag[COMPLETION_TAG_BUFSIZE];
962 List *querytree_list,
965 DestReceiver *receiver;
969 * Get the command name for use in status display (it also becomes the
970 * default completion tag, down inside PortalRun). Set ps_status and
971 * do any special start-of-SQL-command processing needed by the
974 commandTag = CreateCommandTag(parsetree);
976 set_ps_display(commandTag, false);
978 BeginCommand(commandTag, dest);
981 * If we are in an aborted transaction, reject all commands except
982 * COMMIT/ABORT. It is important that this test occur before we try
983 * to do parse analysis, rewrite, or planning, since all those phases
984 * try to do database accesses, which may fail in abort state. (It
985 * might be safe to allow some additional utility commands in this
986 * state, but not many...)
988 if (IsAbortedTransactionBlockState() &&
989 !IsTransactionExitStmt(parsetree))
991 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
992 errmsg("current transaction is aborted, "
993 "commands ignored until end of transaction block"),
996 /* Make sure we are in a transaction command */
997 start_xact_command();
999 /* If we got a cancel signal in parsing or prior command, quit */
1000 CHECK_FOR_INTERRUPTS();
1003 * Set up a snapshot if parse analysis/planning will need one.
1005 if (analyze_requires_snapshot(parsetree))
1007 PushActiveSnapshot(GetTransactionSnapshot());
1008 snapshot_set = true;
1012 * OK to analyze, rewrite, and plan this query.
1014 * Switch to appropriate context for constructing querytrees (again,
1015 * these must outlive the execution context).
1017 oldcontext = MemoryContextSwitchTo(MessageContext);
1019 querytree_list = pg_analyze_and_rewrite(parsetree, query_string,
1022 plantree_list = pg_plan_queries(querytree_list,
1023 CURSOR_OPT_PARALLEL_OK, NULL);
1025 /* Done with the snapshot used for parsing/planning */
1027 PopActiveSnapshot();
1029 /* If we got a cancel signal in analysis or planning, quit */
1030 CHECK_FOR_INTERRUPTS();
1033 * Create unnamed portal to run the query or queries in. If there
1034 * already is one, silently drop it.
1036 portal = CreatePortal("", true, true);
1037 /* Don't display the portal in pg_cursors */
1038 portal->visible = false;
1041 * We don't have to copy anything into the portal, because everything
1042 * we are passing here is in MessageContext, which will outlive the
1045 PortalDefineQuery(portal,
1053 * Start the portal. No parameters here.
1055 PortalStart(portal, NULL, 0, InvalidSnapshot);
1058 * Select the appropriate output format: text unless we are doing a
1059 * FETCH from a binary cursor. (Pretty grotty to have to do this here
1060 * --- but it avoids grottiness in other places. Ah, the joys of
1061 * backward compatibility...)
1063 format = 0; /* TEXT is default */
1064 if (IsA(parsetree, FetchStmt))
1066 FetchStmt *stmt = (FetchStmt *) parsetree;
1070 Portal fportal = GetPortalByName(stmt->portalname);
1072 if (PortalIsValid(fportal) &&
1073 (fportal->cursorOptions & CURSOR_OPT_BINARY))
1074 format = 1; /* BINARY */
1077 PortalSetResultFormat(portal, 1, &format);
1080 * Now we can create the destination receiver object.
1082 receiver = CreateDestReceiver(dest);
1083 if (dest == DestRemote)
1084 SetRemoteDestReceiverParams(receiver, portal);
1087 * Switch back to transaction context for execution.
1089 MemoryContextSwitchTo(oldcontext);
1092 * Run the portal to completion, and then drop it (and the receiver).
1094 (void) PortalRun(portal,
1101 (*receiver->rDestroy) (receiver);
1103 PortalDrop(portal, false);
1105 if (IsA(parsetree, TransactionStmt))
1108 * If this was a transaction control statement, commit it. We will
1109 * start a new xact command for the next command (if any).
1111 finish_xact_command();
1113 else if (lnext(parsetree_item) == NULL)
1116 * If this is the last parsetree of the query string, close down
1117 * transaction statement before reporting command-complete. This
1118 * is so that any end-of-transaction errors are reported before
1119 * the command-complete message is issued, to avoid confusing
1120 * clients who will expect either a command-complete message or an
1121 * error, not one and then the other. But for compatibility with
1122 * historical Postgres behavior, we do not force a transaction
1123 * boundary between queries appearing in a single query string.
1125 finish_xact_command();
1130 * We need a CommandCounterIncrement after every query, except
1131 * those that start or end a transaction block.
1133 CommandCounterIncrement();
1137 * Tell client that we're done with this query. Note we emit exactly
1138 * one EndCommand report for each raw parsetree, thus one for each SQL
1139 * command the client sent, regardless of rewriting. (But a command
1140 * aborted by error will not send an EndCommand report at all.)
1142 EndCommand(completionTag, dest);
1143 } /* end loop over parsetrees */
1146 * Close down transaction statement, if one is open.
1148 finish_xact_command();
1151 * If there were no parsetrees, return EmptyQueryResponse message.
1153 if (!parsetree_list)
1157 * Emit duration logging if appropriate.
1159 switch (check_log_duration(msec_str, was_logged))
1163 (errmsg("duration: %s ms", msec_str),
1164 errhidestmt(true)));
1168 (errmsg("duration: %s ms statement: %s",
1169 msec_str, query_string),
1171 errdetail_execute(parsetree_list)));
1175 if (save_log_statement_stats)
1176 ShowUsage("QUERY STATISTICS");
1178 TRACE_POSTGRESQL_QUERY_DONE(query_string);
1180 debug_query_string = NULL;
1184 * exec_parse_message
1186 * Execute a "Parse" protocol message.
1189 exec_parse_message(const char *query_string, /* string to execute */
1190 const char *stmt_name, /* name for prepared stmt */
1191 Oid *paramTypes, /* parameter types */
1192 int numParams) /* number of parameters */
1194 MemoryContext unnamed_stmt_context = NULL;
1195 MemoryContext oldcontext;
1196 List *parsetree_list;
1197 Node *raw_parse_tree;
1198 const char *commandTag;
1199 List *querytree_list;
1200 CachedPlanSource *psrc;
1202 bool save_log_statement_stats = log_statement_stats;
1206 * Report query to various monitoring facilities.
1208 debug_query_string = query_string;
1210 pgstat_report_activity(STATE_RUNNING, query_string);
1212 set_ps_display("PARSE", false);
1214 if (save_log_statement_stats)
1218 (errmsg("parse %s: %s",
1219 *stmt_name ? stmt_name : "<unnamed>",
1223 * Start up a transaction command so we can run parse analysis etc. (Note
1224 * that this will normally change current memory context.) Nothing happens
1225 * if we are already in one.
1227 start_xact_command();
1230 * Switch to appropriate context for constructing parsetrees.
1232 * We have two strategies depending on whether the prepared statement is
1233 * named or not. For a named prepared statement, we do parsing in
1234 * MessageContext and copy the finished trees into the prepared
1235 * statement's plancache entry; then the reset of MessageContext releases
1236 * temporary space used by parsing and rewriting. For an unnamed prepared
1237 * statement, we assume the statement isn't going to hang around long, so
1238 * getting rid of temp space quickly is probably not worth the costs of
1239 * copying parse trees. So in this case, we create the plancache entry's
1240 * query_context here, and do all the parsing work therein.
1242 is_named = (stmt_name[0] != '\0');
1245 /* Named prepared statement --- parse in MessageContext */
1246 oldcontext = MemoryContextSwitchTo(MessageContext);
1250 /* Unnamed prepared statement --- release any prior unnamed stmt */
1251 drop_unnamed_stmt();
1252 /* Create context for parsing */
1253 unnamed_stmt_context =
1254 AllocSetContextCreate(MessageContext,
1255 "unnamed prepared statement",
1256 ALLOCSET_DEFAULT_SIZES);
1257 oldcontext = MemoryContextSwitchTo(unnamed_stmt_context);
1261 * Do basic parsing of the query or queries (this should be safe even if
1262 * we are in aborted transaction state!)
1264 parsetree_list = pg_parse_query(query_string);
1267 * We only allow a single user statement in a prepared statement. This is
1268 * mainly to keep the protocol simple --- otherwise we'd need to worry
1269 * about multiple result tupdescs and things like that.
1271 if (list_length(parsetree_list) > 1)
1273 (errcode(ERRCODE_SYNTAX_ERROR),
1274 errmsg("cannot insert multiple commands into a prepared statement")));
1276 if (parsetree_list != NIL)
1279 bool snapshot_set = false;
1282 raw_parse_tree = (Node *) linitial(parsetree_list);
1285 * Get the command name for possible use in status display.
1287 commandTag = CreateCommandTag(raw_parse_tree);
1290 * If we are in an aborted transaction, reject all commands except
1291 * COMMIT/ROLLBACK. It is important that this test occur before we
1292 * try to do parse analysis, rewrite, or planning, since all those
1293 * phases try to do database accesses, which may fail in abort state.
1294 * (It might be safe to allow some additional utility commands in this
1295 * state, but not many...)
1297 if (IsAbortedTransactionBlockState() &&
1298 !IsTransactionExitStmt(raw_parse_tree))
1300 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1301 errmsg("current transaction is aborted, "
1302 "commands ignored until end of transaction block"),
1303 errdetail_abort()));
1306 * Create the CachedPlanSource before we do parse analysis, since it
1307 * needs to see the unmodified raw parse tree.
1309 psrc = CreateCachedPlan(raw_parse_tree, query_string, commandTag);
1312 * Set up a snapshot if parse analysis will need one.
1314 if (analyze_requires_snapshot(raw_parse_tree))
1316 PushActiveSnapshot(GetTransactionSnapshot());
1317 snapshot_set = true;
1321 * Analyze and rewrite the query. Note that the originally specified
1322 * parameter set is not required to be complete, so we have to use
1323 * parse_analyze_varparams().
1325 if (log_parser_stats)
1328 query = parse_analyze_varparams(raw_parse_tree,
1334 * Check all parameter types got determined.
1336 for (i = 0; i < numParams; i++)
1338 Oid ptype = paramTypes[i];
1340 if (ptype == InvalidOid || ptype == UNKNOWNOID)
1342 (errcode(ERRCODE_INDETERMINATE_DATATYPE),
1343 errmsg("could not determine data type of parameter $%d",
1347 if (log_parser_stats)
1348 ShowUsage("PARSE ANALYSIS STATISTICS");
1350 querytree_list = pg_rewrite_query(query);
1352 /* Done with the snapshot used for parsing */
1354 PopActiveSnapshot();
1358 /* Empty input string. This is legal. */
1359 raw_parse_tree = NULL;
1361 psrc = CreateCachedPlan(raw_parse_tree, query_string, commandTag);
1362 querytree_list = NIL;
1366 * CachedPlanSource must be a direct child of MessageContext before we
1367 * reparent unnamed_stmt_context under it, else we have a disconnected
1368 * circular subgraph. Klugy, but less so than flipping contexts even more
1371 if (unnamed_stmt_context)
1372 MemoryContextSetParent(psrc->context, MessageContext);
1374 /* Finish filling in the CachedPlanSource */
1375 CompleteCachedPlan(psrc,
1377 unnamed_stmt_context,
1382 CURSOR_OPT_PARALLEL_OK, /* allow parallel mode */
1383 true); /* fixed result */
1385 /* If we got a cancel signal during analysis, quit */
1386 CHECK_FOR_INTERRUPTS();
1391 * Store the query as a prepared statement.
1393 StorePreparedStatement(stmt_name, psrc, false);
1398 * We just save the CachedPlanSource into unnamed_stmt_psrc.
1400 SaveCachedPlan(psrc);
1401 unnamed_stmt_psrc = psrc;
1404 MemoryContextSwitchTo(oldcontext);
1407 * We do NOT close the open transaction command here; that only happens
1408 * when the client sends Sync. Instead, do CommandCounterIncrement just
1409 * in case something happened during parse/plan.
1411 CommandCounterIncrement();
1414 * Send ParseComplete.
1416 if (whereToSendOutput == DestRemote)
1417 pq_putemptymessage('1');
1420 * Emit duration logging if appropriate.
1422 switch (check_log_duration(msec_str, false))
1426 (errmsg("duration: %s ms", msec_str),
1427 errhidestmt(true)));
1431 (errmsg("duration: %s ms parse %s: %s",
1433 *stmt_name ? stmt_name : "<unnamed>",
1435 errhidestmt(true)));
1439 if (save_log_statement_stats)
1440 ShowUsage("PARSE MESSAGE STATISTICS");
1442 debug_query_string = NULL;
1448 * Process a "Bind" message to create a portal from a prepared statement
1451 exec_bind_message(StringInfo input_message)
1453 const char *portal_name;
1454 const char *stmt_name;
1456 int16 *pformats = NULL;
1459 int16 *rformats = NULL;
1460 CachedPlanSource *psrc;
1464 char *saved_stmt_name;
1465 ParamListInfo params;
1466 MemoryContext oldContext;
1467 bool save_log_statement_stats = log_statement_stats;
1468 bool snapshot_set = false;
1471 /* Get the fixed part of the message */
1472 portal_name = pq_getmsgstring(input_message);
1473 stmt_name = pq_getmsgstring(input_message);
1476 (errmsg("bind %s to %s",
1477 *portal_name ? portal_name : "<unnamed>",
1478 *stmt_name ? stmt_name : "<unnamed>")));
1480 /* Find prepared statement */
1481 if (stmt_name[0] != '\0')
1483 PreparedStatement *pstmt;
1485 pstmt = FetchPreparedStatement(stmt_name, true);
1486 psrc = pstmt->plansource;
1490 /* special-case the unnamed statement */
1491 psrc = unnamed_stmt_psrc;
1494 (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
1495 errmsg("unnamed prepared statement does not exist")));
1499 * Report query to various monitoring facilities.
1501 debug_query_string = psrc->query_string;
1503 pgstat_report_activity(STATE_RUNNING, psrc->query_string);
1505 set_ps_display("BIND", false);
1507 if (save_log_statement_stats)
1511 * Start up a transaction command so we can call functions etc. (Note that
1512 * this will normally change current memory context.) Nothing happens if
1513 * we are already in one.
1515 start_xact_command();
1517 /* Switch back to message context */
1518 MemoryContextSwitchTo(MessageContext);
1520 /* Get the parameter format codes */
1521 numPFormats = pq_getmsgint(input_message, 2);
1522 if (numPFormats > 0)
1526 pformats = (int16 *) palloc(numPFormats * sizeof(int16));
1527 for (i = 0; i < numPFormats; i++)
1528 pformats[i] = pq_getmsgint(input_message, 2);
1531 /* Get the parameter value count */
1532 numParams = pq_getmsgint(input_message, 2);
1534 if (numPFormats > 1 && numPFormats != numParams)
1536 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1537 errmsg("bind message has %d parameter formats but %d parameters",
1538 numPFormats, numParams)));
1540 if (numParams != psrc->num_params)
1542 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1543 errmsg("bind message supplies %d parameters, but prepared statement \"%s\" requires %d",
1544 numParams, stmt_name, psrc->num_params)));
1547 * If we are in aborted transaction state, the only portals we can
1548 * actually run are those containing COMMIT or ROLLBACK commands. We
1549 * disallow binding anything else to avoid problems with infrastructure
1550 * that expects to run inside a valid transaction. We also disallow
1551 * binding any parameters, since we can't risk calling user-defined I/O
1554 if (IsAbortedTransactionBlockState() &&
1555 (!IsTransactionExitStmt(psrc->raw_parse_tree) ||
1558 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1559 errmsg("current transaction is aborted, "
1560 "commands ignored until end of transaction block"),
1561 errdetail_abort()));
1564 * Create the portal. Allow silent replacement of an existing portal only
1565 * if the unnamed portal is specified.
1567 if (portal_name[0] == '\0')
1568 portal = CreatePortal(portal_name, true, true);
1570 portal = CreatePortal(portal_name, false, false);
1573 * Prepare to copy stuff into the portal's memory context. We do all this
1574 * copying first, because it could possibly fail (out-of-memory) and we
1575 * don't want a failure to occur between GetCachedPlan and
1576 * PortalDefineQuery; that would result in leaking our plancache refcount.
1578 oldContext = MemoryContextSwitchTo(PortalGetHeapMemory(portal));
1580 /* Copy the plan's query string into the portal */
1581 query_string = pstrdup(psrc->query_string);
1583 /* Likewise make a copy of the statement name, unless it's unnamed */
1585 saved_stmt_name = pstrdup(stmt_name);
1587 saved_stmt_name = NULL;
1590 * Set a snapshot if we have parameters to fetch (since the input
1591 * functions might need it) or the query isn't a utility command (and
1592 * hence could require redoing parse analysis and planning). We keep the
1593 * snapshot active till we're done, so that plancache.c doesn't have to
1596 if (numParams > 0 ||
1597 (psrc->raw_parse_tree &&
1598 analyze_requires_snapshot(psrc->raw_parse_tree)))
1600 PushActiveSnapshot(GetTransactionSnapshot());
1601 snapshot_set = true;
1605 * Fetch parameters, if any, and store in the portal's memory context.
1611 params = (ParamListInfo) palloc(offsetof(ParamListInfoData, params) +
1612 numParams * sizeof(ParamExternData));
1613 /* we have static list of params, so no hooks needed */
1614 params->paramFetch = NULL;
1615 params->paramFetchArg = NULL;
1616 params->parserSetup = NULL;
1617 params->parserSetupArg = NULL;
1618 params->numParams = numParams;
1619 params->paramMask = NULL;
1621 for (paramno = 0; paramno < numParams; paramno++)
1623 Oid ptype = psrc->param_types[paramno];
1627 StringInfoData pbuf;
1631 plength = pq_getmsgint(input_message, 4);
1632 isNull = (plength == -1);
1636 const char *pvalue = pq_getmsgbytes(input_message, plength);
1639 * Rather than copying data around, we just set up a phony
1640 * StringInfo pointing to the correct portion of the message
1641 * buffer. We assume we can scribble on the message buffer so
1642 * as to maintain the convention that StringInfos have a
1643 * trailing null. This is grotty but is a big win when
1644 * dealing with very large parameter strings.
1646 pbuf.data = (char *) pvalue;
1647 pbuf.maxlen = plength + 1;
1651 csave = pbuf.data[plength];
1652 pbuf.data[plength] = '\0';
1656 pbuf.data = NULL; /* keep compiler quiet */
1660 if (numPFormats > 1)
1661 pformat = pformats[paramno];
1662 else if (numPFormats > 0)
1663 pformat = pformats[0];
1665 pformat = 0; /* default = text */
1667 if (pformat == 0) /* text mode */
1673 getTypeInputInfo(ptype, &typinput, &typioparam);
1676 * We have to do encoding conversion before calling the
1682 pstring = pg_client_to_server(pbuf.data, plength);
1684 pval = OidInputFunctionCall(typinput, pstring, typioparam, -1);
1686 /* Free result of encoding conversion, if any */
1687 if (pstring && pstring != pbuf.data)
1690 else if (pformat == 1) /* binary mode */
1697 * Call the parameter type's binary input converter
1699 getTypeBinaryInputInfo(ptype, &typreceive, &typioparam);
1706 pval = OidReceiveFunctionCall(typreceive, bufptr, typioparam, -1);
1708 /* Trouble if it didn't eat the whole buffer */
1709 if (!isNull && pbuf.cursor != pbuf.len)
1711 (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
1712 errmsg("incorrect binary data format in bind parameter %d",
1718 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1719 errmsg("unsupported format code: %d",
1721 pval = 0; /* keep compiler quiet */
1724 /* Restore message buffer contents */
1726 pbuf.data[plength] = csave;
1728 params->params[paramno].value = pval;
1729 params->params[paramno].isnull = isNull;
1732 * We mark the params as CONST. This ensures that any custom plan
1733 * makes full use of the parameter values.
1735 params->params[paramno].pflags = PARAM_FLAG_CONST;
1736 params->params[paramno].ptype = ptype;
1742 /* Done storing stuff in portal's context */
1743 MemoryContextSwitchTo(oldContext);
1745 /* Get the result format codes */
1746 numRFormats = pq_getmsgint(input_message, 2);
1747 if (numRFormats > 0)
1751 rformats = (int16 *) palloc(numRFormats * sizeof(int16));
1752 for (i = 0; i < numRFormats; i++)
1753 rformats[i] = pq_getmsgint(input_message, 2);
1756 pq_getmsgend(input_message);
1759 * Obtain a plan from the CachedPlanSource. Any cruft from (re)planning
1760 * will be generated in MessageContext. The plan refcount will be
1761 * assigned to the Portal, so it will be released at portal destruction.
1763 cplan = GetCachedPlan(psrc, params, false);
1766 * Now we can define the portal.
1768 * DO NOT put any code that could possibly throw an error between the
1769 * above GetCachedPlan call and here.
1771 PortalDefineQuery(portal,
1778 /* Done with the snapshot used for parameter I/O and parsing/planning */
1780 PopActiveSnapshot();
1783 * And we're ready to start portal execution.
1785 PortalStart(portal, params, 0, InvalidSnapshot);
1788 * Apply the result format requests to the portal.
1790 PortalSetResultFormat(portal, numRFormats, rformats);
1793 * Send BindComplete.
1795 if (whereToSendOutput == DestRemote)
1796 pq_putemptymessage('2');
1799 * Emit duration logging if appropriate.
1801 switch (check_log_duration(msec_str, false))
1805 (errmsg("duration: %s ms", msec_str),
1806 errhidestmt(true)));
1810 (errmsg("duration: %s ms bind %s%s%s: %s",
1812 *stmt_name ? stmt_name : "<unnamed>",
1813 *portal_name ? "/" : "",
1814 *portal_name ? portal_name : "",
1815 psrc->query_string),
1817 errdetail_params(params)));
1821 if (save_log_statement_stats)
1822 ShowUsage("BIND MESSAGE STATISTICS");
1824 debug_query_string = NULL;
1828 * exec_execute_message
1830 * Process an "Execute" message for a portal
1833 exec_execute_message(const char *portal_name, long max_rows)
1836 DestReceiver *receiver;
1839 char completionTag[COMPLETION_TAG_BUFSIZE];
1840 const char *sourceText;
1841 const char *prepStmtName;
1842 ParamListInfo portalParams;
1843 bool save_log_statement_stats = log_statement_stats;
1844 bool is_xact_command;
1845 bool execute_is_fetch;
1846 bool was_logged = false;
1849 /* Adjust destination to tell printtup.c what to do */
1850 dest = whereToSendOutput;
1851 if (dest == DestRemote)
1852 dest = DestRemoteExecute;
1854 portal = GetPortalByName(portal_name);
1855 if (!PortalIsValid(portal))
1857 (errcode(ERRCODE_UNDEFINED_CURSOR),
1858 errmsg("portal \"%s\" does not exist", portal_name)));
1861 * If the original query was a null string, just return
1862 * EmptyQueryResponse.
1864 if (portal->commandTag == NULL)
1866 Assert(portal->stmts == NIL);
1871 /* Does the portal contain a transaction command? */
1872 is_xact_command = IsTransactionStmtList(portal->stmts);
1875 * We must copy the sourceText and prepStmtName into MessageContext in
1876 * case the portal is destroyed during finish_xact_command. Can avoid the
1877 * copy if it's not an xact command, though.
1879 if (is_xact_command)
1881 sourceText = pstrdup(portal->sourceText);
1882 if (portal->prepStmtName)
1883 prepStmtName = pstrdup(portal->prepStmtName);
1885 prepStmtName = "<unnamed>";
1888 * An xact command shouldn't have any parameters, which is a good
1889 * thing because they wouldn't be around after finish_xact_command.
1891 portalParams = NULL;
1895 sourceText = portal->sourceText;
1896 if (portal->prepStmtName)
1897 prepStmtName = portal->prepStmtName;
1899 prepStmtName = "<unnamed>";
1900 portalParams = portal->portalParams;
1904 * Report query to various monitoring facilities.
1906 debug_query_string = sourceText;
1908 pgstat_report_activity(STATE_RUNNING, sourceText);
1910 set_ps_display(portal->commandTag, false);
1912 if (save_log_statement_stats)
1915 BeginCommand(portal->commandTag, dest);
1918 * Create dest receiver in MessageContext (we don't want it in transaction
1919 * context, because that may get deleted if portal contains VACUUM).
1921 receiver = CreateDestReceiver(dest);
1922 if (dest == DestRemoteExecute)
1923 SetRemoteDestReceiverParams(receiver, portal);
1926 * Ensure we are in a transaction command (this should normally be the
1927 * case already due to prior BIND).
1929 start_xact_command();
1932 * If we re-issue an Execute protocol request against an existing portal,
1933 * then we are only fetching more rows rather than completely re-executing
1934 * the query from the start. atStart is never reset for a v3 portal, so we
1935 * are safe to use this check.
1937 execute_is_fetch = !portal->atStart;
1939 /* Log immediately if dictated by log_statement */
1940 if (check_log_statement(portal->stmts))
1943 (errmsg("%s %s%s%s: %s",
1945 _("execute fetch from") :
1948 *portal_name ? "/" : "",
1949 *portal_name ? portal_name : "",
1952 errdetail_params(portalParams)));
1957 * If we are in aborted transaction state, the only portals we can
1958 * actually run are those containing COMMIT or ROLLBACK commands.
1960 if (IsAbortedTransactionBlockState() &&
1961 !IsTransactionExitStmtList(portal->stmts))
1963 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1964 errmsg("current transaction is aborted, "
1965 "commands ignored until end of transaction block"),
1966 errdetail_abort()));
1968 /* Check for cancel signal before we start execution */
1969 CHECK_FOR_INTERRUPTS();
1972 * Okay to run the portal.
1975 max_rows = FETCH_ALL;
1977 completed = PortalRun(portal,
1979 true, /* always top level */
1984 (*receiver->rDestroy) (receiver);
1988 if (is_xact_command)
1991 * If this was a transaction control statement, commit it. We
1992 * will start a new xact command for the next command (if any).
1994 finish_xact_command();
1999 * We need a CommandCounterIncrement after every query, except
2000 * those that start or end a transaction block.
2002 CommandCounterIncrement();
2005 /* Send appropriate CommandComplete to client */
2006 EndCommand(completionTag, dest);
2010 /* Portal run not complete, so send PortalSuspended */
2011 if (whereToSendOutput == DestRemote)
2012 pq_putemptymessage('s');
2016 * Emit duration logging if appropriate.
2018 switch (check_log_duration(msec_str, was_logged))
2022 (errmsg("duration: %s ms", msec_str),
2023 errhidestmt(true)));
2027 (errmsg("duration: %s ms %s %s%s%s: %s",
2030 _("execute fetch from") :
2033 *portal_name ? "/" : "",
2034 *portal_name ? portal_name : "",
2037 errdetail_params(portalParams)));
2041 if (save_log_statement_stats)
2042 ShowUsage("EXECUTE MESSAGE STATISTICS");
2044 debug_query_string = NULL;
2048 * check_log_statement
2049 * Determine whether command should be logged because of log_statement
2051 * stmt_list can be either raw grammar output or a list of planned
2055 check_log_statement(List *stmt_list)
2057 ListCell *stmt_item;
2059 if (log_statement == LOGSTMT_NONE)
2061 if (log_statement == LOGSTMT_ALL)
2064 /* Else we have to inspect the statement(s) to see whether to log */
2065 foreach(stmt_item, stmt_list)
2067 Node *stmt = (Node *) lfirst(stmt_item);
2069 if (GetCommandLogLevel(stmt) <= log_statement)
2077 * check_log_duration
2078 * Determine whether current command's duration should be logged
2081 * 0 if no logging is needed
2082 * 1 if just the duration should be logged
2083 * 2 if duration and query details should be logged
2085 * If logging is needed, the duration in msec is formatted into msec_str[],
2086 * which must be a 32-byte buffer.
2088 * was_logged should be TRUE if caller already logged query details (this
2089 * essentially prevents 2 from being returned).
2092 check_log_duration(char *msec_str, bool was_logged)
2094 if (log_duration || log_min_duration_statement >= 0)
2101 TimestampDifference(GetCurrentStatementStartTimestamp(),
2102 GetCurrentTimestamp(),
2104 msecs = usecs / 1000;
2107 * This odd-looking test for log_min_duration_statement being exceeded
2108 * is designed to avoid integer overflow with very long durations:
2109 * don't compute secs * 1000 until we've verified it will fit in int.
2111 exceeded = (log_min_duration_statement == 0 ||
2112 (log_min_duration_statement > 0 &&
2113 (secs > log_min_duration_statement / 1000 ||
2114 secs * 1000 + msecs >= log_min_duration_statement)));
2116 if (exceeded || log_duration)
2118 snprintf(msec_str, 32, "%ld.%03d",
2119 secs * 1000 + msecs, usecs % 1000);
2120 if (exceeded && !was_logged)
2133 * Add an errdetail() line showing the query referenced by an EXECUTE, if any.
2134 * The argument is the raw parsetree list.
2137 errdetail_execute(List *raw_parsetree_list)
2139 ListCell *parsetree_item;
2141 foreach(parsetree_item, raw_parsetree_list)
2143 Node *parsetree = (Node *) lfirst(parsetree_item);
2145 if (IsA(parsetree, ExecuteStmt))
2147 ExecuteStmt *stmt = (ExecuteStmt *) parsetree;
2148 PreparedStatement *pstmt;
2150 pstmt = FetchPreparedStatement(stmt->name, false);
2153 errdetail("prepare: %s", pstmt->plansource->query_string);
2165 * Add an errdetail() line showing bind-parameter data, if available.
2168 errdetail_params(ParamListInfo params)
2170 /* We mustn't call user-defined I/O functions when in an aborted xact */
2171 if (params && params->numParams > 0 && !IsAbortedTransactionBlockState())
2173 StringInfoData param_str;
2174 MemoryContext oldcontext;
2177 /* Make sure any trash is generated in MessageContext */
2178 oldcontext = MemoryContextSwitchTo(MessageContext);
2180 initStringInfo(¶m_str);
2182 for (paramno = 0; paramno < params->numParams; paramno++)
2184 ParamExternData *prm = ¶ms->params[paramno];
2190 appendStringInfo(¶m_str, "%s$%d = ",
2191 paramno > 0 ? ", " : "",
2194 if (prm->isnull || !OidIsValid(prm->ptype))
2196 appendStringInfoString(¶m_str, "NULL");
2200 getTypeOutputInfo(prm->ptype, &typoutput, &typisvarlena);
2202 pstring = OidOutputFunctionCall(typoutput, prm->value);
2204 appendStringInfoCharMacro(¶m_str, '\'');
2205 for (p = pstring; *p; p++)
2207 if (*p == '\'') /* double single quotes */
2208 appendStringInfoCharMacro(¶m_str, *p);
2209 appendStringInfoCharMacro(¶m_str, *p);
2211 appendStringInfoCharMacro(¶m_str, '\'');
2216 errdetail("parameters: %s", param_str.data);
2218 pfree(param_str.data);
2220 MemoryContextSwitchTo(oldcontext);
2229 * Add an errdetail() line showing abort reason, if any.
2232 errdetail_abort(void)
2234 if (MyProc->recoveryConflictPending)
2235 errdetail("abort reason: recovery conflict");
2241 * errdetail_recovery_conflict
2243 * Add an errdetail() line showing conflict source.
2246 errdetail_recovery_conflict(void)
2248 switch (RecoveryConflictReason)
2250 case PROCSIG_RECOVERY_CONFLICT_BUFFERPIN:
2251 errdetail("User was holding shared buffer pin for too long.");
2253 case PROCSIG_RECOVERY_CONFLICT_LOCK:
2254 errdetail("User was holding a relation lock for too long.");
2256 case PROCSIG_RECOVERY_CONFLICT_TABLESPACE:
2257 errdetail("User was or might have been using tablespace that must be dropped.");
2259 case PROCSIG_RECOVERY_CONFLICT_SNAPSHOT:
2260 errdetail("User query might have needed to see row versions that must be removed.");
2262 case PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK:
2263 errdetail("User transaction caused buffer deadlock with recovery.");
2265 case PROCSIG_RECOVERY_CONFLICT_DATABASE:
2266 errdetail("User was connected to a database that must be dropped.");
2277 * exec_describe_statement_message
2279 * Process a "Describe" message for a prepared statement
2282 exec_describe_statement_message(const char *stmt_name)
2284 CachedPlanSource *psrc;
2289 * Start up a transaction command. (Note that this will normally change
2290 * current memory context.) Nothing happens if we are already in one.
2292 start_xact_command();
2294 /* Switch back to message context */
2295 MemoryContextSwitchTo(MessageContext);
2297 /* Find prepared statement */
2298 if (stmt_name[0] != '\0')
2300 PreparedStatement *pstmt;
2302 pstmt = FetchPreparedStatement(stmt_name, true);
2303 psrc = pstmt->plansource;
2307 /* special-case the unnamed statement */
2308 psrc = unnamed_stmt_psrc;
2311 (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
2312 errmsg("unnamed prepared statement does not exist")));
2315 /* Prepared statements shouldn't have changeable result descs */
2316 Assert(psrc->fixed_result);
2319 * If we are in aborted transaction state, we can't run
2320 * SendRowDescriptionMessage(), because that needs catalog accesses.
2321 * Hence, refuse to Describe statements that return data. (We shouldn't
2322 * just refuse all Describes, since that might break the ability of some
2323 * clients to issue COMMIT or ROLLBACK commands, if they use code that
2324 * blindly Describes whatever it does.) We can Describe parameters
2325 * without doing anything dangerous, so we don't restrict that.
2327 if (IsAbortedTransactionBlockState() &&
2330 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2331 errmsg("current transaction is aborted, "
2332 "commands ignored until end of transaction block"),
2333 errdetail_abort()));
2335 if (whereToSendOutput != DestRemote)
2336 return; /* can't actually do anything... */
2339 * First describe the parameters...
2341 pq_beginmessage(&buf, 't'); /* parameter description message type */
2342 pq_sendint(&buf, psrc->num_params, 2);
2344 for (i = 0; i < psrc->num_params; i++)
2346 Oid ptype = psrc->param_types[i];
2348 pq_sendint(&buf, (int) ptype, 4);
2350 pq_endmessage(&buf);
2353 * Next send RowDescription or NoData to describe the result...
2355 if (psrc->resultDesc)
2359 /* Get the plan's primary targetlist */
2360 tlist = CachedPlanGetTargetList(psrc);
2362 SendRowDescriptionMessage(psrc->resultDesc, tlist, NULL);
2365 pq_putemptymessage('n'); /* NoData */
2370 * exec_describe_portal_message
2372 * Process a "Describe" message for a portal
2375 exec_describe_portal_message(const char *portal_name)
2380 * Start up a transaction command. (Note that this will normally change
2381 * current memory context.) Nothing happens if we are already in one.
2383 start_xact_command();
2385 /* Switch back to message context */
2386 MemoryContextSwitchTo(MessageContext);
2388 portal = GetPortalByName(portal_name);
2389 if (!PortalIsValid(portal))
2391 (errcode(ERRCODE_UNDEFINED_CURSOR),
2392 errmsg("portal \"%s\" does not exist", portal_name)));
2395 * If we are in aborted transaction state, we can't run
2396 * SendRowDescriptionMessage(), because that needs catalog accesses.
2397 * Hence, refuse to Describe portals that return data. (We shouldn't just
2398 * refuse all Describes, since that might break the ability of some
2399 * clients to issue COMMIT or ROLLBACK commands, if they use code that
2400 * blindly Describes whatever it does.)
2402 if (IsAbortedTransactionBlockState() &&
2405 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2406 errmsg("current transaction is aborted, "
2407 "commands ignored until end of transaction block"),
2408 errdetail_abort()));
2410 if (whereToSendOutput != DestRemote)
2411 return; /* can't actually do anything... */
2413 if (portal->tupDesc)
2414 SendRowDescriptionMessage(portal->tupDesc,
2415 FetchPortalTargetList(portal),
2418 pq_putemptymessage('n'); /* NoData */
2423 * Convenience routines for starting/committing a single command.
2426 start_xact_command(void)
2431 (errmsg_internal("StartTransactionCommand")));
2432 StartTransactionCommand();
2434 /* Set statement timeout running, if any */
2435 /* NB: this mustn't be enabled until we are within an xact */
2436 if (StatementTimeout > 0)
2437 enable_timeout_after(STATEMENT_TIMEOUT, StatementTimeout);
2439 disable_timeout(STATEMENT_TIMEOUT, false);
2441 xact_started = true;
2446 finish_xact_command(void)
2450 /* Cancel any active statement timeout before committing */
2451 disable_timeout(STATEMENT_TIMEOUT, false);
2453 /* Now commit the command */
2455 (errmsg_internal("CommitTransactionCommand")));
2457 CommitTransactionCommand();
2459 #ifdef MEMORY_CONTEXT_CHECKING
2460 /* Check all memory contexts that weren't freed during commit */
2461 /* (those that were, were checked before being deleted) */
2462 MemoryContextCheck(TopMemoryContext);
2465 #ifdef SHOW_MEMORY_STATS
2466 /* Print mem stats after each commit for leak tracking */
2467 MemoryContextStats(TopMemoryContext);
2470 xact_started = false;
2476 * Convenience routines for checking whether a statement is one of the
2477 * ones that we allow in transaction-aborted state.
2480 /* Test a bare parsetree */
2482 IsTransactionExitStmt(Node *parsetree)
2484 if (parsetree && IsA(parsetree, TransactionStmt))
2486 TransactionStmt *stmt = (TransactionStmt *) parsetree;
2488 if (stmt->kind == TRANS_STMT_COMMIT ||
2489 stmt->kind == TRANS_STMT_PREPARE ||
2490 stmt->kind == TRANS_STMT_ROLLBACK ||
2491 stmt->kind == TRANS_STMT_ROLLBACK_TO)
2497 /* Test a list that might contain Query nodes or bare parsetrees */
2499 IsTransactionExitStmtList(List *parseTrees)
2501 if (list_length(parseTrees) == 1)
2503 Node *stmt = (Node *) linitial(parseTrees);
2505 if (IsA(stmt, Query))
2507 Query *query = (Query *) stmt;
2509 if (query->commandType == CMD_UTILITY &&
2510 IsTransactionExitStmt(query->utilityStmt))
2513 else if (IsTransactionExitStmt(stmt))
2519 /* Test a list that might contain Query nodes or bare parsetrees */
2521 IsTransactionStmtList(List *parseTrees)
2523 if (list_length(parseTrees) == 1)
2525 Node *stmt = (Node *) linitial(parseTrees);
2527 if (IsA(stmt, Query))
2529 Query *query = (Query *) stmt;
2531 if (query->commandType == CMD_UTILITY &&
2532 IsA(query->utilityStmt, TransactionStmt))
2535 else if (IsA(stmt, TransactionStmt))
2541 /* Release any existing unnamed prepared statement */
2543 drop_unnamed_stmt(void)
2545 /* paranoia to avoid a dangling pointer in case of error */
2546 if (unnamed_stmt_psrc)
2548 CachedPlanSource *psrc = unnamed_stmt_psrc;
2550 unnamed_stmt_psrc = NULL;
2551 DropCachedPlan(psrc);
2556 /* --------------------------------
2557 * signal handler routines used in PostgresMain()
2558 * --------------------------------
2562 * quickdie() occurs when signalled SIGQUIT by the postmaster.
2564 * Some backend has bought the farm,
2565 * so we need to stop what we're doing and exit.
2568 quickdie(SIGNAL_ARGS)
2570 sigaddset(&BlockSig, SIGQUIT); /* prevent nested calls */
2571 PG_SETMASK(&BlockSig);
2574 * Prevent interrupts while exiting; though we just blocked signals that
2575 * would queue new interrupts, one may have been pending. We don't want a
2576 * quickdie() downgraded to a mere query cancel.
2581 * If we're aborting out of client auth, don't risk trying to send
2582 * anything to the client; we will likely violate the protocol, not to
2583 * mention that we may have interrupted the guts of OpenSSL or some
2584 * authentication library.
2586 if (ClientAuthInProgress && whereToSendOutput == DestRemote)
2587 whereToSendOutput = DestNone;
2590 * Ideally this should be ereport(FATAL), but then we'd not get control
2594 (errcode(ERRCODE_CRASH_SHUTDOWN),
2595 errmsg("terminating connection because of crash of another server process"),
2596 errdetail("The postmaster has commanded this server process to roll back"
2597 " the current transaction and exit, because another"
2598 " server process exited abnormally and possibly corrupted"
2600 errhint("In a moment you should be able to reconnect to the"
2601 " database and repeat your command.")));
2604 * We DO NOT want to run proc_exit() callbacks -- we're here because
2605 * shared memory may be corrupted, so we don't want to try to clean up our
2606 * transaction. Just nail the windows shut and get out of town. Now that
2607 * there's an atexit callback to prevent third-party code from breaking
2608 * things by calling exit() directly, we have to reset the callbacks
2609 * explicitly to make this work as intended.
2614 * Note we do exit(2) not exit(0). This is to force the postmaster into a
2615 * system reset cycle if some idiot DBA sends a manual SIGQUIT to a random
2616 * backend. This is necessary precisely because we don't clean up our
2617 * shared memory state. (The "dead man switch" mechanism in pmsignal.c
2618 * should ensure the postmaster sees this as a crash, too, but no harm in
2619 * being doubly sure.)
2625 * Shutdown signal from postmaster: abort transaction and exit
2626 * at soonest convenient time
2631 int save_errno = errno;
2633 /* Don't joggle the elbow of proc_exit */
2634 if (!proc_exit_inprogress)
2636 InterruptPending = true;
2637 ProcDiePending = true;
2640 /* If we're still here, waken anything waiting on the process latch */
2644 * If we're in single user mode, we want to quit immediately - we can't
2645 * rely on latches as they wouldn't work when stdin/stdout is a file.
2646 * Rather ugly, but it's unlikely to be worthwhile to invest much more
2647 * effort just for the benefit of single user mode.
2649 if (DoingCommandRead && whereToSendOutput != DestRemote)
2650 ProcessInterrupts();
2656 * Query-cancel signal from postmaster: abort current transaction
2657 * at soonest convenient time
2660 StatementCancelHandler(SIGNAL_ARGS)
2662 int save_errno = errno;
2665 * Don't joggle the elbow of proc_exit
2667 if (!proc_exit_inprogress)
2669 InterruptPending = true;
2670 QueryCancelPending = true;
2673 /* If we're still here, waken anything waiting on the process latch */
2679 /* signal handler for floating point exception */
2681 FloatExceptionHandler(SIGNAL_ARGS)
2683 /* We're not returning, so no need to save errno */
2685 (errcode(ERRCODE_FLOATING_POINT_EXCEPTION),
2686 errmsg("floating-point exception"),
2687 errdetail("An invalid floating-point operation was signaled. "
2688 "This probably means an out-of-range result or an "
2689 "invalid operation, such as division by zero.")));
2692 /* SIGHUP: set flag to re-read config file at next convenient time */
2694 SigHupHandler(SIGNAL_ARGS)
2696 int save_errno = errno;
2705 * RecoveryConflictInterrupt: out-of-line portion of recovery conflict
2706 * handling following receipt of SIGUSR1. Designed to be similar to die()
2707 * and StatementCancelHandler(). Called only by a normal user backend
2708 * that begins a transaction during recovery.
2711 RecoveryConflictInterrupt(ProcSignalReason reason)
2713 int save_errno = errno;
2716 * Don't joggle the elbow of proc_exit
2718 if (!proc_exit_inprogress)
2720 RecoveryConflictReason = reason;
2723 case PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK:
2726 * If we aren't waiting for a lock we can never deadlock.
2728 if (!IsWaitingForLock())
2731 /* Intentional drop through to check wait for pin */
2733 case PROCSIG_RECOVERY_CONFLICT_BUFFERPIN:
2736 * If we aren't blocking the Startup process there is nothing
2739 if (!HoldingBufferPinThatDelaysRecovery())
2742 MyProc->recoveryConflictPending = true;
2744 /* Intentional drop through to error handling */
2746 case PROCSIG_RECOVERY_CONFLICT_LOCK:
2747 case PROCSIG_RECOVERY_CONFLICT_TABLESPACE:
2748 case PROCSIG_RECOVERY_CONFLICT_SNAPSHOT:
2751 * If we aren't in a transaction any longer then ignore.
2753 if (!IsTransactionOrTransactionBlock())
2757 * If we can abort just the current subtransaction then we are
2758 * OK to throw an ERROR to resolve the conflict. Otherwise
2759 * drop through to the FATAL case.
2761 * XXX other times that we can throw just an ERROR *may* be
2762 * PROCSIG_RECOVERY_CONFLICT_LOCK if no locks are held in
2763 * parent transactions
2765 * PROCSIG_RECOVERY_CONFLICT_SNAPSHOT if no snapshots are held
2766 * by parent transactions and the transaction is not
2767 * transaction-snapshot mode
2769 * PROCSIG_RECOVERY_CONFLICT_TABLESPACE if no temp files or
2770 * cursors open in parent transactions
2772 if (!IsSubTransaction())
2775 * If we already aborted then we no longer need to cancel.
2776 * We do this here since we do not wish to ignore aborted
2777 * subtransactions, which must cause FATAL, currently.
2779 if (IsAbortedTransactionBlockState())
2782 RecoveryConflictPending = true;
2783 QueryCancelPending = true;
2784 InterruptPending = true;
2788 /* Intentional drop through to session cancel */
2790 case PROCSIG_RECOVERY_CONFLICT_DATABASE:
2791 RecoveryConflictPending = true;
2792 ProcDiePending = true;
2793 InterruptPending = true;
2797 elog(FATAL, "unrecognized conflict mode: %d",
2801 Assert(RecoveryConflictPending && (QueryCancelPending || ProcDiePending));
2804 * All conflicts apart from database cause dynamic errors where the
2805 * command or transaction can be retried at a later point with some
2806 * potential for success. No need to reset this, since non-retryable
2807 * conflict errors are currently FATAL.
2809 if (reason == PROCSIG_RECOVERY_CONFLICT_DATABASE)
2810 RecoveryConflictRetryable = false;
2814 * Set the process latch. This function essentially emulates signal
2815 * handlers like die() and StatementCancelHandler() and it seems prudent
2816 * to behave similarly as they do.
2824 * ProcessInterrupts: out-of-line portion of CHECK_FOR_INTERRUPTS() macro
2826 * If an interrupt condition is pending, and it's safe to service it,
2827 * then clear the flag and accept the interrupt. Called only when
2828 * InterruptPending is true.
2831 ProcessInterrupts(void)
2833 /* OK to accept any interrupts now? */
2834 if (InterruptHoldoffCount != 0 || CritSectionCount != 0)
2836 InterruptPending = false;
2840 ProcDiePending = false;
2841 QueryCancelPending = false; /* ProcDie trumps QueryCancel */
2843 /* As in quickdie, don't risk sending to client during auth */
2844 if (ClientAuthInProgress && whereToSendOutput == DestRemote)
2845 whereToSendOutput = DestNone;
2846 if (ClientAuthInProgress)
2848 (errcode(ERRCODE_QUERY_CANCELED),
2849 errmsg("canceling authentication due to timeout")));
2850 else if (IsAutoVacuumWorkerProcess())
2852 (errcode(ERRCODE_ADMIN_SHUTDOWN),
2853 errmsg("terminating autovacuum process due to administrator command")));
2854 else if (RecoveryConflictPending && RecoveryConflictRetryable)
2856 pgstat_report_recovery_conflict(RecoveryConflictReason);
2858 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
2859 errmsg("terminating connection due to conflict with recovery"),
2860 errdetail_recovery_conflict()));
2862 else if (RecoveryConflictPending)
2864 /* Currently there is only one non-retryable recovery conflict */
2865 Assert(RecoveryConflictReason == PROCSIG_RECOVERY_CONFLICT_DATABASE);
2866 pgstat_report_recovery_conflict(RecoveryConflictReason);
2868 (errcode(ERRCODE_DATABASE_DROPPED),
2869 errmsg("terminating connection due to conflict with recovery"),
2870 errdetail_recovery_conflict()));
2874 (errcode(ERRCODE_ADMIN_SHUTDOWN),
2875 errmsg("terminating connection due to administrator command")));
2877 if (ClientConnectionLost)
2879 QueryCancelPending = false; /* lost connection trumps QueryCancel */
2881 /* don't send to client, we already know the connection to be dead. */
2882 whereToSendOutput = DestNone;
2884 (errcode(ERRCODE_CONNECTION_FAILURE),
2885 errmsg("connection to client lost")));
2889 * If a recovery conflict happens while we are waiting for input from the
2890 * client, the client is presumably just sitting idle in a transaction,
2891 * preventing recovery from making progress. Terminate the connection to
2894 if (RecoveryConflictPending && DoingCommandRead)
2896 QueryCancelPending = false; /* this trumps QueryCancel */
2897 RecoveryConflictPending = false;
2899 pgstat_report_recovery_conflict(RecoveryConflictReason);
2901 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
2902 errmsg("terminating connection due to conflict with recovery"),
2903 errdetail_recovery_conflict(),
2904 errhint("In a moment you should be able to reconnect to the"
2905 " database and repeat your command.")));
2908 if (QueryCancelPending)
2910 bool lock_timeout_occurred;
2911 bool stmt_timeout_occurred;
2914 * Don't allow query cancel interrupts while reading input from the
2915 * client, because we might lose sync in the FE/BE protocol. (Die
2916 * interrupts are OK, because we won't read any further messages from
2917 * the client in that case.)
2919 if (QueryCancelHoldoffCount != 0)
2922 * Re-arm InterruptPending so that we process the cancel request
2923 * as soon as we're done reading the message.
2925 InterruptPending = true;
2929 QueryCancelPending = false;
2932 * If LOCK_TIMEOUT and STATEMENT_TIMEOUT indicators are both set, we
2933 * need to clear both, so always fetch both.
2935 lock_timeout_occurred = get_timeout_indicator(LOCK_TIMEOUT, true);
2936 stmt_timeout_occurred = get_timeout_indicator(STATEMENT_TIMEOUT, true);
2939 * If both were set, we want to report whichever timeout completed
2940 * earlier; this ensures consistent behavior if the machine is slow
2941 * enough that the second timeout triggers before we get here. A tie
2942 * is arbitrarily broken in favor of reporting a lock timeout.
2944 if (lock_timeout_occurred && stmt_timeout_occurred &&
2945 get_timeout_finish_time(STATEMENT_TIMEOUT) < get_timeout_finish_time(LOCK_TIMEOUT))
2946 lock_timeout_occurred = false; /* report stmt timeout */
2948 if (lock_timeout_occurred)
2952 (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
2953 errmsg("canceling statement due to lock timeout")));
2955 if (stmt_timeout_occurred)
2959 (errcode(ERRCODE_QUERY_CANCELED),
2960 errmsg("canceling statement due to statement timeout")));
2962 if (IsAutoVacuumWorkerProcess())
2966 (errcode(ERRCODE_QUERY_CANCELED),
2967 errmsg("canceling autovacuum task")));
2969 if (RecoveryConflictPending)
2971 RecoveryConflictPending = false;
2973 pgstat_report_recovery_conflict(RecoveryConflictReason);
2975 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
2976 errmsg("canceling statement due to conflict with recovery"),
2977 errdetail_recovery_conflict()));
2981 * If we are reading a command from the client, just ignore the cancel
2982 * request --- sending an extra error message won't accomplish
2983 * anything. Otherwise, go ahead and throw the error.
2985 if (!DoingCommandRead)
2989 (errcode(ERRCODE_QUERY_CANCELED),
2990 errmsg("canceling statement due to user request")));
2994 if (IdleInTransactionSessionTimeoutPending)
2996 /* Has the timeout setting changed since last we looked? */
2997 if (IdleInTransactionSessionTimeout > 0)
2999 (errcode(ERRCODE_IDLE_IN_TRANSACTION_SESSION_TIMEOUT),
3000 errmsg("terminating connection due to idle-in-transaction timeout")));
3002 IdleInTransactionSessionTimeoutPending = false;
3006 if (ParallelMessagePending)
3007 HandleParallelMessages();
3012 * IA64-specific code to fetch the AR.BSP register for stack depth checks.
3014 * We currently support gcc, icc, and HP-UX's native compiler here.
3016 * Note: while icc accepts gcc asm blocks on x86[_64], this is not true on
3017 * ia64 (at least not in icc versions before 12.x). So we have to carry a
3018 * separate implementation for it.
3020 #if defined(__ia64__) || defined(__ia64)
3022 #if defined(__hpux) && !defined(__GNUC__) && !defined(__INTEL_COMPILER)
3023 /* Assume it's HP-UX native compiler */
3024 #include <ia64/sys/inline.h>
3025 #define ia64_get_bsp() ((char *) (_Asm_mov_from_ar(_AREG_BSP, _NO_FENCE)))
3026 #elif defined(__INTEL_COMPILER)
3028 #include <asm/ia64regs.h>
3029 #define ia64_get_bsp() ((char *) __getReg(_IA64_REG_AR_BSP))
3032 static __inline__ char *
3037 /* the ;; is a "stop", seems to be required before fetching BSP */
3038 __asm__ __volatile__(
3050 * set_stack_base: set up reference point for stack depth checking
3052 * Returns the old reference point, if any.
3055 set_stack_base(void)
3058 pg_stack_base_t old;
3060 #if defined(__ia64__) || defined(__ia64)
3061 old.stack_base_ptr = stack_base_ptr;
3062 old.register_stack_base_ptr = register_stack_base_ptr;
3064 old = stack_base_ptr;
3067 /* Set up reference point for stack depth checking */
3068 stack_base_ptr = &stack_base;
3069 #if defined(__ia64__) || defined(__ia64)
3070 register_stack_base_ptr = ia64_get_bsp();
3077 * restore_stack_base: restore reference point for stack depth checking
3079 * This can be used after set_stack_base() to restore the old value. This
3080 * is currently only used in PL/Java. When PL/Java calls a backend function
3081 * from different thread, the thread's stack is at a different location than
3082 * the main thread's stack, so it sets the base pointer before the call, and
3083 * restores it afterwards.
3086 restore_stack_base(pg_stack_base_t base)
3088 #if defined(__ia64__) || defined(__ia64)
3089 stack_base_ptr = base.stack_base_ptr;
3090 register_stack_base_ptr = base.register_stack_base_ptr;
3092 stack_base_ptr = base;
3097 * check_stack_depth/stack_is_too_deep: check for excessively deep recursion
3099 * This should be called someplace in any recursive routine that might possibly
3100 * recurse deep enough to overflow the stack. Most Unixen treat stack
3101 * overflow as an unrecoverable SIGSEGV, so we want to error out ourselves
3102 * before hitting the hardware limit.
3104 * check_stack_depth() just throws an error summarily. stack_is_too_deep()
3105 * can be used by code that wants to handle the error condition itself.
3108 check_stack_depth(void)
3110 if (stack_is_too_deep())
3113 (errcode(ERRCODE_STATEMENT_TOO_COMPLEX),
3114 errmsg("stack depth limit exceeded"),
3115 errhint("Increase the configuration parameter \"max_stack_depth\" (currently %dkB), "
3116 "after ensuring the platform's stack depth limit is adequate.",
3122 stack_is_too_deep(void)
3128 * Compute distance from reference point to my local variables
3130 stack_depth = (long) (stack_base_ptr - &stack_top_loc);
3133 * Take abs value, since stacks grow up on some machines, down on others
3135 if (stack_depth < 0)
3136 stack_depth = -stack_depth;
3141 * The test on stack_base_ptr prevents us from erroring out if called
3142 * during process setup or in a non-backend process. Logically it should
3143 * be done first, but putting it here avoids wasting cycles during normal
3146 if (stack_depth > max_stack_depth_bytes &&
3147 stack_base_ptr != NULL)
3151 * On IA64 there is a separate "register" stack that requires its own
3152 * independent check. For this, we have to measure the change in the
3153 * "BSP" pointer from PostgresMain to here. Logic is just as above,
3154 * except that we know IA64's register stack grows up.
3156 * Note we assume that the same max_stack_depth applies to both stacks.
3158 #if defined(__ia64__) || defined(__ia64)
3159 stack_depth = (long) (ia64_get_bsp() - register_stack_base_ptr);
3161 if (stack_depth > max_stack_depth_bytes &&
3162 register_stack_base_ptr != NULL)
3169 /* GUC check hook for max_stack_depth */
3171 check_max_stack_depth(int *newval, void **extra, GucSource source)
3173 long newval_bytes = *newval * 1024L;
3174 long stack_rlimit = get_stack_depth_rlimit();
3176 if (stack_rlimit > 0 && newval_bytes > stack_rlimit - STACK_DEPTH_SLOP)
3178 GUC_check_errdetail("\"max_stack_depth\" must not exceed %ldkB.",
3179 (stack_rlimit - STACK_DEPTH_SLOP) / 1024L);
3180 GUC_check_errhint("Increase the platform's stack depth limit via \"ulimit -s\" or local equivalent.");
3186 /* GUC assign hook for max_stack_depth */
3188 assign_max_stack_depth(int newval, void *extra)
3190 long newval_bytes = newval * 1024L;
3192 max_stack_depth_bytes = newval_bytes;
3197 * set_debug_options --- apply "-d N" command line option
3199 * -d is not quite the same as setting log_min_messages because it enables
3200 * other output options.
3203 set_debug_options(int debug_flag, GucContext context, GucSource source)
3209 sprintf(debugstr, "debug%d", debug_flag);
3210 SetConfigOption("log_min_messages", debugstr, context, source);
3213 SetConfigOption("log_min_messages", "notice", context, source);
3215 if (debug_flag >= 1 && context == PGC_POSTMASTER)
3217 SetConfigOption("log_connections", "true", context, source);
3218 SetConfigOption("log_disconnections", "true", context, source);
3220 if (debug_flag >= 2)
3221 SetConfigOption("log_statement", "all", context, source);
3222 if (debug_flag >= 3)
3223 SetConfigOption("debug_print_parse", "true", context, source);
3224 if (debug_flag >= 4)
3225 SetConfigOption("debug_print_plan", "true", context, source);
3226 if (debug_flag >= 5)
3227 SetConfigOption("debug_print_rewritten", "true", context, source);
3232 set_plan_disabling_options(const char *arg, GucContext context, GucSource source)
3234 const char *tmp = NULL;
3238 case 's': /* seqscan */
3239 tmp = "enable_seqscan";
3241 case 'i': /* indexscan */
3242 tmp = "enable_indexscan";
3244 case 'o': /* indexonlyscan */
3245 tmp = "enable_indexonlyscan";
3247 case 'b': /* bitmapscan */
3248 tmp = "enable_bitmapscan";
3250 case 't': /* tidscan */
3251 tmp = "enable_tidscan";
3253 case 'n': /* nestloop */
3254 tmp = "enable_nestloop";
3256 case 'm': /* mergejoin */
3257 tmp = "enable_mergejoin";
3259 case 'h': /* hashjoin */
3260 tmp = "enable_hashjoin";
3265 SetConfigOption(tmp, "false", context, source);
3274 get_stats_option_name(const char *arg)
3279 if (optarg[1] == 'a') /* "parser" */
3280 return "log_parser_stats";
3281 else if (optarg[1] == 'l') /* "planner" */
3282 return "log_planner_stats";
3285 case 'e': /* "executor" */
3286 return "log_executor_stats";
3294 /* ----------------------------------------------------------------
3295 * process_postgres_switches
3296 * Parse command line arguments for PostgresMain
3298 * This is called twice, once for the "secure" options coming from the
3299 * postmaster or command line, and once for the "insecure" options coming
3300 * from the client's startup packet. The latter have the same syntax but
3301 * may be restricted in what they can do.
3303 * argv[0] is ignored in either case (it's assumed to be the program name).
3305 * ctx is PGC_POSTMASTER for secure options, PGC_BACKEND for insecure options
3306 * coming from the client, or PGC_SU_BACKEND for insecure options coming from
3307 * a superuser client.
3309 * If a database name is present in the command line arguments, it's
3310 * returned into *dbname (this is allowed only if *dbname is initially NULL).
3311 * ----------------------------------------------------------------
3314 process_postgres_switches(int argc, char *argv[], GucContext ctx,
3315 const char **dbname)
3317 bool secure = (ctx == PGC_POSTMASTER);
3319 GucSource gucsource;
3324 gucsource = PGC_S_ARGV; /* switches came from command line */
3326 /* Ignore the initial --single argument, if present */
3327 if (argc > 1 && strcmp(argv[1], "--single") == 0)
3335 gucsource = PGC_S_CLIENT; /* switches came from client */
3338 #ifdef HAVE_INT_OPTERR
3341 * Turn this off because it's either printed to stderr and not the log
3342 * where we'd want it, or argv[0] is now "--single", which would make for
3343 * a weird error message. We print our own error message below.
3349 * Parse command-line options. CAUTION: keep this in sync with
3350 * postmaster/postmaster.c (the option sets should not conflict) and with
3351 * the common help() function in main/main.c.
3353 while ((flag = getopt(argc, argv, "B:bc:C:D:d:EeFf:h:ijk:lN:nOo:Pp:r:S:sTt:v:W:-:")) != -1)
3358 SetConfigOption("shared_buffers", optarg, ctx, gucsource);
3362 /* Undocumented flag used for binary upgrades */
3364 IsBinaryUpgrade = true;
3368 /* ignored for consistency with the postmaster */
3373 userDoption = strdup(optarg);
3377 set_debug_options(atoi(optarg), ctx, gucsource);
3386 SetConfigOption("datestyle", "euro", ctx, gucsource);
3390 SetConfigOption("fsync", "false", ctx, gucsource);
3394 if (!set_plan_disabling_options(optarg, ctx, gucsource))
3399 SetConfigOption("listen_addresses", optarg, ctx, gucsource);
3403 SetConfigOption("listen_addresses", "*", ctx, gucsource);
3408 UseSemiNewlineNewline = true;
3412 SetConfigOption("unix_socket_directories", optarg, ctx, gucsource);
3416 SetConfigOption("ssl", "true", ctx, gucsource);
3420 SetConfigOption("max_connections", optarg, ctx, gucsource);
3424 /* ignored for consistency with postmaster */
3428 SetConfigOption("allow_system_table_mods", "true", ctx, gucsource);
3436 SetConfigOption("ignore_system_indexes", "true", ctx, gucsource);
3440 SetConfigOption("port", optarg, ctx, gucsource);
3444 /* send output (stdout and stderr) to the given file */
3446 strlcpy(OutputFileName, optarg, MAXPGPATH);
3450 SetConfigOption("work_mem", optarg, ctx, gucsource);
3454 SetConfigOption("log_statement_stats", "true", ctx, gucsource);
3458 /* ignored for consistency with the postmaster */
3463 const char *tmp = get_stats_option_name(optarg);
3466 SetConfigOption(tmp, "true", ctx, gucsource);
3475 * -v is no longer used in normal operation, since
3476 * FrontendProtocol is already set before we get here. We keep
3477 * the switch only for possible use in standalone operation,
3478 * in case we ever support using normal FE/BE protocol with a
3479 * standalone backend.
3482 FrontendProtocol = (ProtocolVersion) atoi(optarg);
3486 SetConfigOption("post_auth_delay", optarg, ctx, gucsource);
3495 ParseLongOption(optarg, &name, &value);
3500 (errcode(ERRCODE_SYNTAX_ERROR),
3501 errmsg("--%s requires a value",
3505 (errcode(ERRCODE_SYNTAX_ERROR),
3506 errmsg("-c %s requires a value",
3509 SetConfigOption(name, value, ctx, gucsource);
3526 * Optional database name should be there only if *dbname is NULL.
3528 if (!errs && dbname && *dbname == NULL && argc - optind >= 1)
3529 *dbname = strdup(argv[optind++]);
3531 if (errs || argc != optind)
3534 optind--; /* complain about the previous argument */
3536 /* spell the error message a bit differently depending on context */
3537 if (IsUnderPostmaster)
3539 (errcode(ERRCODE_SYNTAX_ERROR),
3540 errmsg("invalid command-line argument for server process: %s", argv[optind]),
3541 errhint("Try \"%s --help\" for more information.", progname)));
3544 (errcode(ERRCODE_SYNTAX_ERROR),
3545 errmsg("%s: invalid command-line argument: %s",
3546 progname, argv[optind]),
3547 errhint("Try \"%s --help\" for more information.", progname)));
3551 * Reset getopt(3) library so that it will work correctly in subprocesses
3552 * or when this function is called a second time with another array.
3555 #ifdef HAVE_INT_OPTRESET
3556 optreset = 1; /* some systems need this too */
3561 /* ----------------------------------------------------------------
3563 * postgres main loop -- all backends, interactive or otherwise start here
3565 * argc/argv are the command line arguments to be used. (When being forked
3566 * by the postmaster, these are not the original argv array of the process.)
3567 * dbname is the name of the database to connect to, or NULL if the database
3568 * name should be extracted from the command line arguments or defaulted.
3569 * username is the PostgreSQL user name to be used for the session.
3570 * ----------------------------------------------------------------
3573 PostgresMain(int argc, char *argv[],
3575 const char *username)
3578 StringInfoData input_message;
3579 sigjmp_buf local_sigjmp_buf;
3580 volatile bool send_ready_for_query = true;
3581 bool disable_idle_in_transaction_timeout = false;
3583 /* Initialize startup process environment if necessary. */
3584 if (!IsUnderPostmaster)
3585 InitStandaloneProcess(argv[0]);
3587 SetProcessingMode(InitProcessing);
3590 * Set default values for command-line options.
3592 if (!IsUnderPostmaster)
3593 InitializeGUCOptions();
3596 * Parse command-line options.
3598 process_postgres_switches(argc, argv, PGC_POSTMASTER, &dbname);
3600 /* Must have gotten a database name, or have a default (the username) */
3606 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3607 errmsg("%s: no database nor user name specified",
3611 /* Acquire configuration parameters, unless inherited from postmaster */
3612 if (!IsUnderPostmaster)
3614 if (!SelectConfigFiles(userDoption, progname))
3619 * Set up signal handlers and masks.
3621 * Note that postmaster blocked all signals before forking child process,
3622 * so there is no race condition whereby we might receive a signal before
3623 * we have set up the handler.
3625 * Also note: it's best not to use any signals that are SIG_IGNored in the
3626 * postmaster. If such a signal arrives before we are able to change the
3627 * handler to non-SIG_IGN, it'll get dropped. Instead, make a dummy
3628 * handler in the postmaster to reserve the signal. (Of course, this isn't
3629 * an issue for signals that are locally generated, such as SIGALRM and
3636 pqsignal(SIGHUP, SigHupHandler); /* set flag to read config
3638 pqsignal(SIGINT, StatementCancelHandler); /* cancel current query */
3639 pqsignal(SIGTERM, die); /* cancel current query and exit */
3642 * In a standalone backend, SIGQUIT can be generated from the keyboard
3643 * easily, while SIGTERM cannot, so we make both signals do die()
3644 * rather than quickdie().
3646 if (IsUnderPostmaster)
3647 pqsignal(SIGQUIT, quickdie); /* hard crash time */
3649 pqsignal(SIGQUIT, die); /* cancel current query and exit */
3650 InitializeTimeouts(); /* establishes SIGALRM handler */
3653 * Ignore failure to write to frontend. Note: if frontend closes
3654 * connection, we will notice it and exit cleanly when control next
3655 * returns to outer loop. This seems safer than forcing exit in the
3656 * midst of output during who-knows-what operation...
3658 pqsignal(SIGPIPE, SIG_IGN);
3659 pqsignal(SIGUSR1, procsignal_sigusr1_handler);
3660 pqsignal(SIGUSR2, SIG_IGN);
3661 pqsignal(SIGFPE, FloatExceptionHandler);
3664 * Reset some signals that are accepted by postmaster but not by
3667 pqsignal(SIGCHLD, SIG_DFL); /* system() requires this on some
3673 if (IsUnderPostmaster)
3675 /* We allow SIGQUIT (quickdie) at all times */
3676 sigdelset(&BlockSig, SIGQUIT);
3679 PG_SETMASK(&BlockSig); /* block everything except SIGQUIT */
3681 if (!IsUnderPostmaster)
3684 * Validate we have been given a reasonable-looking DataDir (if under
3685 * postmaster, assume postmaster did this already).
3688 ValidatePgVersion(DataDir);
3690 /* Change into DataDir (if under postmaster, was done already) */
3694 * Create lockfile for data directory.
3696 CreateDataDirLockFile(false);
3698 /* Initialize MaxBackends (if under postmaster, was done already) */
3699 InitializeMaxBackends();
3702 /* Early initialization */
3706 * Create a per-backend PGPROC struct in shared memory, except in the
3707 * EXEC_BACKEND case where this was done in SubPostmasterMain. We must do
3708 * this before we can use LWLocks (and in the EXEC_BACKEND case we already
3709 * had to do some stuff with LWLocks).
3712 if (!IsUnderPostmaster)
3718 /* We need to allow SIGINT, etc during the initial transaction */
3719 PG_SETMASK(&UnBlockSig);
3722 * General initialization.
3724 * NOTE: if you are tempted to add code in this vicinity, consider putting
3725 * it inside InitPostgres() instead. In particular, anything that
3726 * involves database access should be there, not here.
3728 InitPostgres(dbname, InvalidOid, username, InvalidOid, NULL);
3731 * If the PostmasterContext is still around, recycle the space; we don't
3732 * need it anymore after InitPostgres completes. Note this does not trash
3733 * *MyProcPort, because ConnCreate() allocated that space with malloc()
3734 * ... else we'd need to copy the Port data first. Also, subsidiary data
3735 * such as the username isn't lost either; see ProcessStartupPacket().
3737 if (PostmasterContext)
3739 MemoryContextDelete(PostmasterContext);
3740 PostmasterContext = NULL;
3743 SetProcessingMode(NormalProcessing);
3746 * Now all GUC states are fully set up. Report them to client if
3749 BeginReportingGUCOptions();
3752 * Also set up handler to log session end; we have to wait till now to be
3753 * sure Log_disconnections has its final value.
3755 if (IsUnderPostmaster && Log_disconnections)
3756 on_proc_exit(log_disconnections, 0);
3758 /* Perform initialization specific to a WAL sender process. */
3763 * process any libraries that should be preloaded at backend start (this
3764 * likewise can't be done until GUC settings are complete)
3766 process_session_preload_libraries();
3769 * Send this backend's cancellation info to the frontend.
3771 if (whereToSendOutput == DestRemote &&
3772 PG_PROTOCOL_MAJOR(FrontendProtocol) >= 2)
3776 pq_beginmessage(&buf, 'K');
3777 pq_sendint(&buf, (int32) MyProcPid, sizeof(int32));
3778 pq_sendint(&buf, (int32) MyCancelKey, sizeof(int32));
3779 pq_endmessage(&buf);
3780 /* Need not flush since ReadyForQuery will do it. */
3783 /* Welcome banner for standalone case */
3784 if (whereToSendOutput == DestDebug)
3785 printf("\nPostgreSQL stand-alone backend %s\n", PG_VERSION);
3788 * Create the memory context we will use in the main loop.
3790 * MessageContext is reset once per iteration of the main loop, ie, upon
3791 * completion of processing of each command message from the client.
3793 MessageContext = AllocSetContextCreate(TopMemoryContext,
3795 ALLOCSET_DEFAULT_SIZES);
3798 * Remember stand-alone backend startup time
3800 if (!IsUnderPostmaster)
3801 PgStartTime = GetCurrentTimestamp();
3804 * POSTGRES main processing loop begins here
3806 * If an exception is encountered, processing resumes here so we abort the
3807 * current transaction and start a new one.
3809 * You might wonder why this isn't coded as an infinite loop around a
3810 * PG_TRY construct. The reason is that this is the bottom of the
3811 * exception stack, and so with PG_TRY there would be no exception handler
3812 * in force at all during the CATCH part. By leaving the outermost setjmp
3813 * always active, we have at least some chance of recovering from an error
3814 * during error recovery. (If we get into an infinite loop thereby, it
3815 * will soon be stopped by overflow of elog.c's internal state stack.)
3817 * Note that we use sigsetjmp(..., 1), so that this function's signal mask
3818 * (to wit, UnBlockSig) will be restored when longjmp'ing to here. This
3819 * is essential in case we longjmp'd out of a signal handler on a platform
3820 * where that leaves the signal blocked. It's not redundant with the
3821 * unblock in AbortTransaction() because the latter is only called if we
3822 * were inside a transaction.
3825 if (sigsetjmp(local_sigjmp_buf, 1) != 0)
3828 * NOTE: if you are tempted to add more code in this if-block,
3829 * consider the high probability that it should be in
3830 * AbortTransaction() instead. The only stuff done directly here
3831 * should be stuff that is guaranteed to apply *only* for outer-level
3832 * error recovery, such as adjusting the FE/BE protocol status.
3835 /* Since not using PG_TRY, must reset error stack by hand */
3836 error_context_stack = NULL;
3838 /* Prevent interrupts while cleaning up */
3842 * Forget any pending QueryCancel request, since we're returning to
3843 * the idle loop anyway, and cancel any active timeout requests. (In
3844 * future we might want to allow some timeout requests to survive, but
3845 * at minimum it'd be necessary to do reschedule_timeouts(), in case
3846 * we got here because of a query cancel interrupting the SIGALRM
3847 * interrupt handler.) Note in particular that we must clear the
3848 * statement and lock timeout indicators, to prevent any future plain
3849 * query cancels from being misreported as timeouts in case we're
3850 * forgetting a timeout cancel.
3852 disable_all_timeouts(false);
3853 QueryCancelPending = false; /* second to avoid race condition */
3855 /* Not reading from the client anymore. */
3856 DoingCommandRead = false;
3858 /* Make sure libpq is in a good state */
3861 /* Report the error to the client and/or server log */
3865 * Make sure debug_query_string gets reset before we possibly clobber
3866 * the storage it points at.
3868 debug_query_string = NULL;
3871 * Abort the current transaction in order to recover.
3873 AbortCurrentTransaction();
3876 WalSndErrorCleanup();
3879 * We can't release replication slots inside AbortTransaction() as we
3880 * need to be able to start and abort transactions while having a slot
3881 * acquired. But we never need to hold them across top level errors,
3882 * so releasing here is fine. There's another cleanup in ProcKill()
3883 * ensuring we'll correctly cleanup on FATAL errors as well.
3885 if (MyReplicationSlot != NULL)
3886 ReplicationSlotRelease();
3889 * Now return to normal top-level context and clear ErrorContext for
3892 MemoryContextSwitchTo(TopMemoryContext);
3896 * If we were handling an extended-query-protocol message, initiate
3897 * skip till next Sync. This also causes us not to issue
3898 * ReadyForQuery (until we get Sync).
3900 if (doing_extended_query_message)
3901 ignore_till_sync = true;
3903 /* We don't have a transaction command open anymore */
3904 xact_started = false;
3907 * If an error occurred while we were reading a message from the
3908 * client, we have potentially lost track of where the previous
3909 * message ends and the next one begins. Even though we have
3910 * otherwise recovered from the error, we cannot safely read any more
3911 * messages from the client, so there isn't much we can do with the
3912 * connection anymore.
3914 if (pq_is_reading_msg())
3916 (errcode(ERRCODE_PROTOCOL_VIOLATION),
3917 errmsg("terminating connection because protocol synchronization was lost")));
3919 /* Now we can allow interrupts again */
3920 RESUME_INTERRUPTS();
3923 /* We can now handle ereport(ERROR) */
3924 PG_exception_stack = &local_sigjmp_buf;
3926 if (!ignore_till_sync)
3927 send_ready_for_query = true; /* initially, or after error */
3930 * Non-error queries loop here.
3936 * At top of loop, reset extended-query-message flag, so that any
3937 * errors encountered in "idle" state don't provoke skip.
3939 doing_extended_query_message = false;
3942 * Release storage left over from prior query cycle, and create a new
3943 * query input buffer in the cleared MessageContext.
3945 MemoryContextSwitchTo(MessageContext);
3946 MemoryContextResetAndDeleteChildren(MessageContext);
3948 initStringInfo(&input_message);
3951 * (1) If we've reached idle state, tell the frontend we're ready for
3954 * Note: this includes fflush()'ing the last of the prior output.
3956 * This is also a good time to send collected statistics to the
3957 * collector, and to update the PS stats display. We avoid doing
3958 * those every time through the message loop because it'd slow down
3959 * processing of batched messages, and because we don't want to report
3960 * uncommitted updates (that confuses autovacuum). The notification
3961 * processor wants a call too, if we are not in a transaction block.
3963 if (send_ready_for_query)
3965 if (IsAbortedTransactionBlockState())
3967 set_ps_display("idle in transaction (aborted)", false);
3968 pgstat_report_activity(STATE_IDLEINTRANSACTION_ABORTED, NULL);
3970 /* Start the idle-in-transaction timer */
3971 if (IdleInTransactionSessionTimeout > 0)
3973 disable_idle_in_transaction_timeout = true;
3974 enable_timeout_after(IDLE_IN_TRANSACTION_SESSION_TIMEOUT,
3975 IdleInTransactionSessionTimeout);
3978 else if (IsTransactionOrTransactionBlock())
3980 set_ps_display("idle in transaction", false);
3981 pgstat_report_activity(STATE_IDLEINTRANSACTION, NULL);
3983 /* Start the idle-in-transaction timer */
3984 if (IdleInTransactionSessionTimeout > 0)
3986 disable_idle_in_transaction_timeout = true;
3987 enable_timeout_after(IDLE_IN_TRANSACTION_SESSION_TIMEOUT,
3988 IdleInTransactionSessionTimeout);
3993 ProcessCompletedNotifies();
3994 pgstat_report_stat(false);
3996 set_ps_display("idle", false);
3997 pgstat_report_activity(STATE_IDLE, NULL);
4000 ReadyForQuery(whereToSendOutput);
4001 send_ready_for_query = false;
4005 * (2) Allow asynchronous signals to be executed immediately if they
4006 * come in while we are waiting for client input. (This must be
4007 * conditional since we don't want, say, reads on behalf of COPY FROM
4008 * STDIN doing the same thing.)
4010 DoingCommandRead = true;
4013 * (3) read a command (loop blocks here)
4015 firstchar = ReadCommand(&input_message);
4018 * (4) disable async signal conditions again.
4020 * Query cancel is supposed to be a no-op when there is no query in
4021 * progress, so if a query cancel arrived while we were idle, just
4022 * reset QueryCancelPending. ProcessInterrupts() has that effect when
4023 * it's called when DoingCommandRead is set, so check for interrupts
4024 * before resetting DoingCommandRead.
4026 CHECK_FOR_INTERRUPTS();
4027 DoingCommandRead = false;
4030 * (5) turn off the idle-in-transaction timeout
4032 if (disable_idle_in_transaction_timeout)
4034 disable_timeout(IDLE_IN_TRANSACTION_SESSION_TIMEOUT, false);
4035 disable_idle_in_transaction_timeout = false;
4039 * (6) check for any other interesting events that happened while we
4045 ProcessConfigFile(PGC_SIGHUP);
4049 * (7) process the command. But ignore it if we're skipping till
4052 if (ignore_till_sync && firstchar != EOF)
4057 case 'Q': /* simple query */
4059 const char *query_string;
4061 /* Set statement_timestamp() */
4062 SetCurrentStatementStartTimestamp();
4064 query_string = pq_getmsgstring(&input_message);
4065 pq_getmsgend(&input_message);
4068 exec_replication_command(query_string);
4070 exec_simple_query(query_string);
4072 send_ready_for_query = true;
4076 case 'P': /* parse */
4078 const char *stmt_name;
4079 const char *query_string;
4081 Oid *paramTypes = NULL;
4083 forbidden_in_wal_sender(firstchar);
4085 /* Set statement_timestamp() */
4086 SetCurrentStatementStartTimestamp();
4088 stmt_name = pq_getmsgstring(&input_message);
4089 query_string = pq_getmsgstring(&input_message);
4090 numParams = pq_getmsgint(&input_message, 2);
4095 paramTypes = (Oid *) palloc(numParams * sizeof(Oid));
4096 for (i = 0; i < numParams; i++)
4097 paramTypes[i] = pq_getmsgint(&input_message, 4);
4099 pq_getmsgend(&input_message);
4101 exec_parse_message(query_string, stmt_name,
4102 paramTypes, numParams);
4106 case 'B': /* bind */
4107 forbidden_in_wal_sender(firstchar);
4109 /* Set statement_timestamp() */
4110 SetCurrentStatementStartTimestamp();
4113 * this message is complex enough that it seems best to put
4114 * the field extraction out-of-line
4116 exec_bind_message(&input_message);
4119 case 'E': /* execute */
4121 const char *portal_name;
4124 forbidden_in_wal_sender(firstchar);
4126 /* Set statement_timestamp() */
4127 SetCurrentStatementStartTimestamp();
4129 portal_name = pq_getmsgstring(&input_message);
4130 max_rows = pq_getmsgint(&input_message, 4);
4131 pq_getmsgend(&input_message);
4133 exec_execute_message(portal_name, max_rows);
4137 case 'F': /* fastpath function call */
4138 forbidden_in_wal_sender(firstchar);
4140 /* Set statement_timestamp() */
4141 SetCurrentStatementStartTimestamp();
4143 /* Report query to various monitoring facilities. */
4144 pgstat_report_activity(STATE_FASTPATH, NULL);
4145 set_ps_display("<FASTPATH>", false);
4147 /* start an xact for this function invocation */
4148 start_xact_command();
4151 * Note: we may at this point be inside an aborted
4152 * transaction. We can't throw error for that until we've
4153 * finished reading the function-call message, so
4154 * HandleFunctionRequest() must check for it after doing so.
4155 * Be careful not to do anything that assumes we're inside a
4156 * valid transaction here.
4159 /* switch back to message context */
4160 MemoryContextSwitchTo(MessageContext);
4162 if (HandleFunctionRequest(&input_message) == EOF)
4164 /* lost frontend connection during F message input */
4167 * Reset whereToSendOutput to prevent ereport from
4168 * attempting to send any more messages to client.
4170 if (whereToSendOutput == DestRemote)
4171 whereToSendOutput = DestNone;
4176 /* commit the function-invocation transaction */
4177 finish_xact_command();
4179 send_ready_for_query = true;
4182 case 'C': /* close */
4185 const char *close_target;
4187 forbidden_in_wal_sender(firstchar);
4189 close_type = pq_getmsgbyte(&input_message);
4190 close_target = pq_getmsgstring(&input_message);
4191 pq_getmsgend(&input_message);
4196 if (close_target[0] != '\0')
4197 DropPreparedStatement(close_target, false);
4200 /* special-case the unnamed statement */
4201 drop_unnamed_stmt();
4208 portal = GetPortalByName(close_target);
4209 if (PortalIsValid(portal))
4210 PortalDrop(portal, false);
4215 (errcode(ERRCODE_PROTOCOL_VIOLATION),
4216 errmsg("invalid CLOSE message subtype %d",
4221 if (whereToSendOutput == DestRemote)
4222 pq_putemptymessage('3'); /* CloseComplete */
4226 case 'D': /* describe */
4229 const char *describe_target;
4231 forbidden_in_wal_sender(firstchar);
4233 /* Set statement_timestamp() (needed for xact) */
4234 SetCurrentStatementStartTimestamp();
4236 describe_type = pq_getmsgbyte(&input_message);
4237 describe_target = pq_getmsgstring(&input_message);
4238 pq_getmsgend(&input_message);
4240 switch (describe_type)
4243 exec_describe_statement_message(describe_target);
4246 exec_describe_portal_message(describe_target);
4250 (errcode(ERRCODE_PROTOCOL_VIOLATION),
4251 errmsg("invalid DESCRIBE message subtype %d",
4258 case 'H': /* flush */
4259 pq_getmsgend(&input_message);
4260 if (whereToSendOutput == DestRemote)
4264 case 'S': /* sync */
4265 pq_getmsgend(&input_message);
4266 finish_xact_command();
4267 send_ready_for_query = true;
4271 * 'X' means that the frontend is closing down the socket. EOF
4272 * means unexpected loss of frontend connection. Either way,
4273 * perform normal shutdown.
4279 * Reset whereToSendOutput to prevent ereport from attempting
4280 * to send any more messages to client.
4282 if (whereToSendOutput == DestRemote)
4283 whereToSendOutput = DestNone;
4286 * NOTE: if you are tempted to add more code here, DON'T!
4287 * Whatever you had in mind to do should be set up as an
4288 * on_proc_exit or on_shmem_exit callback, instead. Otherwise
4289 * it will fail to be called during other backend-shutdown
4294 case 'd': /* copy data */
4295 case 'c': /* copy done */
4296 case 'f': /* copy fail */
4299 * Accept but ignore these messages, per protocol spec; we
4300 * probably got here because a COPY failed, and the frontend
4301 * is still sending data.
4307 (errcode(ERRCODE_PROTOCOL_VIOLATION),
4308 errmsg("invalid frontend message type %d",
4311 } /* end of input-reading loop */
4315 * Throw an error if we're a WAL sender process.
4317 * This is used to forbid anything else than simple query protocol messages
4318 * in a WAL sender process. 'firstchar' specifies what kind of a forbidden
4319 * message was received, and is used to construct the error message.
4322 forbidden_in_wal_sender(char firstchar)
4326 if (firstchar == 'F')
4328 (errcode(ERRCODE_PROTOCOL_VIOLATION),
4329 errmsg("fastpath function calls not supported in a replication connection")));
4332 (errcode(ERRCODE_PROTOCOL_VIOLATION),
4333 errmsg("extended query protocol not supported in a replication connection")));
4339 * Obtain platform stack depth limit (in bytes)
4341 * Return -1 if unknown
4344 get_stack_depth_rlimit(void)
4346 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_STACK)
4347 static long val = 0;
4349 /* This won't change after process launch, so check just once */
4354 if (getrlimit(RLIMIT_STACK, &rlim) < 0)
4356 else if (rlim.rlim_cur == RLIM_INFINITY)
4358 /* rlim_cur is probably of an unsigned type, so check for overflow */
4359 else if (rlim.rlim_cur >= LONG_MAX)
4362 val = rlim.rlim_cur;
4365 #else /* no getrlimit */
4366 #if defined(WIN32) || defined(__CYGWIN__)
4367 /* On Windows we set the backend stack size in src/backend/Makefile */
4368 return WIN32_STACK_RLIMIT;
4369 #else /* not windows ... give up */
4376 static struct rusage Save_r;
4377 static struct timeval Save_t;
4382 getrusage(RUSAGE_SELF, &Save_r);
4383 gettimeofday(&Save_t, NULL);
4387 ShowUsage(const char *title)
4390 struct timeval user,
4392 struct timeval elapse_t;
4395 getrusage(RUSAGE_SELF, &r);
4396 gettimeofday(&elapse_t, NULL);
4397 memcpy((char *) &user, (char *) &r.ru_utime, sizeof(user));
4398 memcpy((char *) &sys, (char *) &r.ru_stime, sizeof(sys));
4399 if (elapse_t.tv_usec < Save_t.tv_usec)
4402 elapse_t.tv_usec += 1000000;
4404 if (r.ru_utime.tv_usec < Save_r.ru_utime.tv_usec)
4406 r.ru_utime.tv_sec--;
4407 r.ru_utime.tv_usec += 1000000;
4409 if (r.ru_stime.tv_usec < Save_r.ru_stime.tv_usec)
4411 r.ru_stime.tv_sec--;
4412 r.ru_stime.tv_usec += 1000000;
4416 * the only stats we don't show here are for memory usage -- i can't
4417 * figure out how to interpret the relevant fields in the rusage struct,
4418 * and they change names across o/s platforms, anyway. if you can figure
4419 * out what the entries mean, you can somehow extract resident set size,
4420 * shared text size, and unshared data and stack sizes.
4422 initStringInfo(&str);
4424 appendStringInfoString(&str, "! system usage stats:\n");
4425 appendStringInfo(&str,
4426 "!\t%ld.%06ld elapsed %ld.%06ld user %ld.%06ld system sec\n",
4427 (long) (elapse_t.tv_sec - Save_t.tv_sec),
4428 (long) (elapse_t.tv_usec - Save_t.tv_usec),
4429 (long) (r.ru_utime.tv_sec - Save_r.ru_utime.tv_sec),
4430 (long) (r.ru_utime.tv_usec - Save_r.ru_utime.tv_usec),
4431 (long) (r.ru_stime.tv_sec - Save_r.ru_stime.tv_sec),
4432 (long) (r.ru_stime.tv_usec - Save_r.ru_stime.tv_usec));
4433 appendStringInfo(&str,
4434 "!\t[%ld.%06ld user %ld.%06ld sys total]\n",
4436 (long) user.tv_usec,
4438 (long) sys.tv_usec);
4439 #if defined(HAVE_GETRUSAGE)
4440 appendStringInfo(&str,
4441 "!\t%ld/%ld [%ld/%ld] filesystem blocks in/out\n",
4442 r.ru_inblock - Save_r.ru_inblock,
4443 /* they only drink coffee at dec */
4444 r.ru_oublock - Save_r.ru_oublock,
4445 r.ru_inblock, r.ru_oublock);
4446 appendStringInfo(&str,
4447 "!\t%ld/%ld [%ld/%ld] page faults/reclaims, %ld [%ld] swaps\n",
4448 r.ru_majflt - Save_r.ru_majflt,
4449 r.ru_minflt - Save_r.ru_minflt,
4450 r.ru_majflt, r.ru_minflt,
4451 r.ru_nswap - Save_r.ru_nswap,
4453 appendStringInfo(&str,
4454 "!\t%ld [%ld] signals rcvd, %ld/%ld [%ld/%ld] messages rcvd/sent\n",
4455 r.ru_nsignals - Save_r.ru_nsignals,
4457 r.ru_msgrcv - Save_r.ru_msgrcv,
4458 r.ru_msgsnd - Save_r.ru_msgsnd,
4459 r.ru_msgrcv, r.ru_msgsnd);
4460 appendStringInfo(&str,
4461 "!\t%ld/%ld [%ld/%ld] voluntary/involuntary context switches\n",
4462 r.ru_nvcsw - Save_r.ru_nvcsw,
4463 r.ru_nivcsw - Save_r.ru_nivcsw,
4464 r.ru_nvcsw, r.ru_nivcsw);
4465 #endif /* HAVE_GETRUSAGE */
4467 /* remove trailing newline */
4468 if (str.data[str.len - 1] == '\n')
4469 str.data[--str.len] = '\0';
4472 (errmsg_internal("%s", title),
4473 errdetail_internal("%s", str.data)));
4479 * on_proc_exit handler to log end of session
4482 log_disconnections(int code, Datum arg)
4484 Port *port = MyProcPort;
4492 TimestampDifference(port->SessionStartTime,
4493 GetCurrentTimestamp(),
4495 msecs = usecs / 1000;
4497 hours = secs / SECS_PER_HOUR;
4498 secs %= SECS_PER_HOUR;
4499 minutes = secs / SECS_PER_MINUTE;
4500 seconds = secs % SECS_PER_MINUTE;
4503 (errmsg("disconnection: session time: %d:%02d:%02d.%03d "
4504 "user=%s database=%s host=%s%s%s",
4505 hours, minutes, seconds, msecs,
4506 port->user_name, port->database_name, port->remote_host,
4507 port->remote_port[0] ? " port=" : "", port->remote_port)));