Update copyright for 2022
[pgsql.git] / src / backend / tcop / postgres.c
blobfda2e9360e28abfca63110b40e2f04f8980ba649
1 /*-------------------------------------------------------------------------
3 * postgres.c
4 * POSTGRES C Backend Interface
6 * Portions Copyright (c) 1996-2022, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
10 * IDENTIFICATION
11 * src/backend/tcop/postgres.c
13 * NOTES
14 * this is the "main" module of the postgres backend and
15 * hence the main module of the "traffic cop".
17 *-------------------------------------------------------------------------
20 #include "postgres.h"
22 #include <fcntl.h>
23 #include <limits.h>
24 #include <signal.h>
25 #include <unistd.h>
26 #include <sys/socket.h>
27 #ifdef HAVE_SYS_SELECT_H
28 #include <sys/select.h>
29 #endif
30 #ifdef HAVE_SYS_RESOURCE_H
31 #include <sys/time.h>
32 #include <sys/resource.h>
33 #endif
35 #ifndef HAVE_GETRUSAGE
36 #include "rusagestub.h"
37 #endif
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 "common/pg_prng.h"
46 #include "executor/spi.h"
47 #include "jit/jit.h"
48 #include "libpq/libpq.h"
49 #include "libpq/pqformat.h"
50 #include "libpq/pqsignal.h"
51 #include "mb/pg_wchar.h"
52 #include "mb/stringinfo_mb.h"
53 #include "miscadmin.h"
54 #include "nodes/print.h"
55 #include "optimizer/optimizer.h"
56 #include "parser/analyze.h"
57 #include "parser/parser.h"
58 #include "pg_getopt.h"
59 #include "pg_trace.h"
60 #include "pgstat.h"
61 #include "postmaster/autovacuum.h"
62 #include "postmaster/interrupt.h"
63 #include "postmaster/postmaster.h"
64 #include "replication/logicallauncher.h"
65 #include "replication/logicalworker.h"
66 #include "replication/slot.h"
67 #include "replication/walsender.h"
68 #include "rewrite/rewriteHandler.h"
69 #include "storage/bufmgr.h"
70 #include "storage/ipc.h"
71 #include "storage/pmsignal.h"
72 #include "storage/proc.h"
73 #include "storage/procsignal.h"
74 #include "storage/sinval.h"
75 #include "tcop/fastpath.h"
76 #include "tcop/pquery.h"
77 #include "tcop/tcopprot.h"
78 #include "tcop/utility.h"
79 #include "utils/lsyscache.h"
80 #include "utils/memutils.h"
81 #include "utils/ps_status.h"
82 #include "utils/snapmgr.h"
83 #include "utils/timeout.h"
84 #include "utils/timestamp.h"
86 /* ----------------
87 * global variables
88 * ----------------
90 const char *debug_query_string; /* client-supplied query string */
92 /* Note: whereToSendOutput is initialized for the bootstrap/standalone case */
93 CommandDest whereToSendOutput = DestDebug;
95 /* flag for logging end of session */
96 bool Log_disconnections = false;
98 int log_statement = LOGSTMT_NONE;
100 /* GUC variable for maximum stack depth (measured in kilobytes) */
101 int max_stack_depth = 100;
103 /* wait N seconds to allow attach from a debugger */
104 int PostAuthDelay = 0;
106 /* Time between checks that the client is still connected. */
107 int client_connection_check_interval = 0;
109 /* ----------------
110 * private typedefs etc
111 * ----------------
114 /* type of argument for bind_param_error_callback */
115 typedef struct BindParamCbData
117 const char *portalName;
118 int paramno; /* zero-based param number, or -1 initially */
119 const char *paramval; /* textual input string, if available */
120 } BindParamCbData;
122 /* ----------------
123 * private variables
124 * ----------------
127 /* max_stack_depth converted to bytes for speed of checking */
128 static long max_stack_depth_bytes = 100 * 1024L;
131 * Stack base pointer -- initialized by PostmasterMain and inherited by
132 * subprocesses. This is not static because old versions of PL/Java modify
133 * it directly. Newer versions use set_stack_base(), but we want to stay
134 * binary-compatible for the time being.
136 char *stack_base_ptr = NULL;
139 * On IA64 we also have to remember the register stack base.
141 #if defined(__ia64__) || defined(__ia64)
142 char *register_stack_base_ptr = NULL;
143 #endif
146 * Flag to keep track of whether we have started a transaction.
147 * For extended query protocol this has to be remembered across messages.
149 static bool xact_started = false;
152 * Flag to indicate that we are doing the outer loop's read-from-client,
153 * as opposed to any random read from client that might happen within
154 * commands like COPY FROM STDIN.
156 static bool DoingCommandRead = false;
159 * Flags to implement skip-till-Sync-after-error behavior for messages of
160 * the extended query protocol.
162 static bool doing_extended_query_message = false;
163 static bool ignore_till_sync = false;
166 * If an unnamed prepared statement exists, it's stored here.
167 * We keep it separate from the hashtable kept by commands/prepare.c
168 * in order to reduce overhead for short-lived queries.
170 static CachedPlanSource *unnamed_stmt_psrc = NULL;
172 /* assorted command-line switches */
173 static const char *userDoption = NULL; /* -D switch */
174 static bool EchoQuery = false; /* -E switch */
175 static bool UseSemiNewlineNewline = false; /* -j switch */
177 /* whether or not, and why, we were canceled by conflict with recovery */
178 static bool RecoveryConflictPending = false;
179 static bool RecoveryConflictRetryable = true;
180 static ProcSignalReason RecoveryConflictReason;
182 /* reused buffer to pass to SendRowDescriptionMessage() */
183 static MemoryContext row_description_context = NULL;
184 static StringInfoData row_description_buf;
186 /* ----------------------------------------------------------------
187 * decls for routines only used in this file
188 * ----------------------------------------------------------------
190 static int InteractiveBackend(StringInfo inBuf);
191 static int interactive_getc(void);
192 static int SocketBackend(StringInfo inBuf);
193 static int ReadCommand(StringInfo inBuf);
194 static void forbidden_in_wal_sender(char firstchar);
195 static bool check_log_statement(List *stmt_list);
196 static int errdetail_execute(List *raw_parsetree_list);
197 static int errdetail_params(ParamListInfo params);
198 static int errdetail_abort(void);
199 static int errdetail_recovery_conflict(void);
200 static void bind_param_error_callback(void *arg);
201 static void start_xact_command(void);
202 static void finish_xact_command(void);
203 static bool IsTransactionExitStmt(Node *parsetree);
204 static bool IsTransactionExitStmtList(List *pstmts);
205 static bool IsTransactionStmtList(List *pstmts);
206 static void drop_unnamed_stmt(void);
207 static void log_disconnections(int code, Datum arg);
208 static void enable_statement_timeout(void);
209 static void disable_statement_timeout(void);
212 /* ----------------------------------------------------------------
213 * routines to obtain user input
214 * ----------------------------------------------------------------
217 /* ----------------
218 * InteractiveBackend() is called for user interactive connections
220 * the string entered by the user is placed in its parameter inBuf,
221 * and we act like a Q message was received.
223 * EOF is returned if end-of-file input is seen; time to shut down.
224 * ----------------
227 static int
228 InteractiveBackend(StringInfo inBuf)
230 int c; /* character read from getc() */
233 * display a prompt and obtain input from the user
235 printf("backend> ");
236 fflush(stdout);
238 resetStringInfo(inBuf);
241 * Read characters until EOF or the appropriate delimiter is seen.
243 while ((c = interactive_getc()) != EOF)
245 if (c == '\n')
247 if (UseSemiNewlineNewline)
250 * In -j mode, semicolon followed by two newlines ends the
251 * command; otherwise treat newline as regular character.
253 if (inBuf->len > 1 &&
254 inBuf->data[inBuf->len - 1] == '\n' &&
255 inBuf->data[inBuf->len - 2] == ';')
257 /* might as well drop the second newline */
258 break;
261 else
264 * In plain mode, newline ends the command unless preceded by
265 * backslash.
267 if (inBuf->len > 0 &&
268 inBuf->data[inBuf->len - 1] == '\\')
270 /* discard backslash from inBuf */
271 inBuf->data[--inBuf->len] = '\0';
272 /* discard newline too */
273 continue;
275 else
277 /* keep the newline character, but end the command */
278 appendStringInfoChar(inBuf, '\n');
279 break;
284 /* Not newline, or newline treated as regular character */
285 appendStringInfoChar(inBuf, (char) c);
288 /* No input before EOF signal means time to quit. */
289 if (c == EOF && inBuf->len == 0)
290 return EOF;
293 * otherwise we have a user query so process it.
296 /* Add '\0' to make it look the same as message case. */
297 appendStringInfoChar(inBuf, (char) '\0');
300 * if the query echo flag was given, print the query..
302 if (EchoQuery)
303 printf("statement: %s\n", inBuf->data);
304 fflush(stdout);
306 return 'Q';
310 * interactive_getc -- collect one character from stdin
312 * Even though we are not reading from a "client" process, we still want to
313 * respond to signals, particularly SIGTERM/SIGQUIT.
315 static int
316 interactive_getc(void)
318 int c;
321 * This will not process catchup interrupts or notifications while
322 * reading. But those can't really be relevant for a standalone backend
323 * anyway. To properly handle SIGTERM there's a hack in die() that
324 * directly processes interrupts at this stage...
326 CHECK_FOR_INTERRUPTS();
328 c = getc(stdin);
330 ProcessClientReadInterrupt(false);
332 return c;
335 /* ----------------
336 * SocketBackend() Is called for frontend-backend connections
338 * Returns the message type code, and loads message body data into inBuf.
340 * EOF is returned if the connection is lost.
341 * ----------------
343 static int
344 SocketBackend(StringInfo inBuf)
346 int qtype;
347 int maxmsglen;
350 * Get message type code from the frontend.
352 HOLD_CANCEL_INTERRUPTS();
353 pq_startmsgread();
354 qtype = pq_getbyte();
356 if (qtype == EOF) /* frontend disconnected */
358 if (IsTransactionState())
359 ereport(COMMERROR,
360 (errcode(ERRCODE_CONNECTION_FAILURE),
361 errmsg("unexpected EOF on client connection with an open transaction")));
362 else
365 * Can't send DEBUG log messages to client at this point. Since
366 * we're disconnecting right away, we don't need to restore
367 * whereToSendOutput.
369 whereToSendOutput = DestNone;
370 ereport(DEBUG1,
371 (errcode(ERRCODE_CONNECTION_DOES_NOT_EXIST),
372 errmsg_internal("unexpected EOF on client connection")));
374 return qtype;
378 * Validate message type code before trying to read body; if we have lost
379 * sync, better to say "command unknown" than to run out of memory because
380 * we used garbage as a length word. We can also select a type-dependent
381 * limit on what a sane length word could be. (The limit could be chosen
382 * more granularly, but it's not clear it's worth fussing over.)
384 * This also gives us a place to set the doing_extended_query_message flag
385 * as soon as possible.
387 switch (qtype)
389 case 'Q': /* simple query */
390 maxmsglen = PQ_LARGE_MESSAGE_LIMIT;
391 doing_extended_query_message = false;
392 break;
394 case 'F': /* fastpath function call */
395 maxmsglen = PQ_LARGE_MESSAGE_LIMIT;
396 doing_extended_query_message = false;
397 break;
399 case 'X': /* terminate */
400 maxmsglen = PQ_SMALL_MESSAGE_LIMIT;
401 doing_extended_query_message = false;
402 ignore_till_sync = false;
403 break;
405 case 'B': /* bind */
406 case 'P': /* parse */
407 maxmsglen = PQ_LARGE_MESSAGE_LIMIT;
408 doing_extended_query_message = true;
409 break;
411 case 'C': /* close */
412 case 'D': /* describe */
413 case 'E': /* execute */
414 case 'H': /* flush */
415 maxmsglen = PQ_SMALL_MESSAGE_LIMIT;
416 doing_extended_query_message = true;
417 break;
419 case 'S': /* sync */
420 maxmsglen = PQ_SMALL_MESSAGE_LIMIT;
421 /* stop any active skip-till-Sync */
422 ignore_till_sync = false;
423 /* mark not-extended, so that a new error doesn't begin skip */
424 doing_extended_query_message = false;
425 break;
427 case 'd': /* copy data */
428 maxmsglen = PQ_LARGE_MESSAGE_LIMIT;
429 doing_extended_query_message = false;
430 break;
432 case 'c': /* copy done */
433 case 'f': /* copy fail */
434 maxmsglen = PQ_SMALL_MESSAGE_LIMIT;
435 doing_extended_query_message = false;
436 break;
438 default:
441 * Otherwise we got garbage from the frontend. We treat this as
442 * fatal because we have probably lost message boundary sync, and
443 * there's no good way to recover.
445 ereport(FATAL,
446 (errcode(ERRCODE_PROTOCOL_VIOLATION),
447 errmsg("invalid frontend message type %d", qtype)));
448 maxmsglen = 0; /* keep compiler quiet */
449 break;
453 * In protocol version 3, all frontend messages have a length word next
454 * after the type code; we can read the message contents independently of
455 * the type.
457 if (pq_getmessage(inBuf, maxmsglen))
458 return EOF; /* suitable message already logged */
459 RESUME_CANCEL_INTERRUPTS();
461 return qtype;
464 /* ----------------
465 * ReadCommand reads a command from either the frontend or
466 * standard input, places it in inBuf, and returns the
467 * message type code (first byte of the message).
468 * EOF is returned if end of file.
469 * ----------------
471 static int
472 ReadCommand(StringInfo inBuf)
474 int result;
476 if (whereToSendOutput == DestRemote)
477 result = SocketBackend(inBuf);
478 else
479 result = InteractiveBackend(inBuf);
480 return result;
484 * ProcessClientReadInterrupt() - Process interrupts specific to client reads
486 * This is called just before and after low-level reads.
487 * 'blocked' is true if no data was available to read and we plan to retry,
488 * false if about to read or done reading.
490 * Must preserve errno!
492 void
493 ProcessClientReadInterrupt(bool blocked)
495 int save_errno = errno;
497 if (DoingCommandRead)
499 /* Check for general interrupts that arrived before/while reading */
500 CHECK_FOR_INTERRUPTS();
502 /* Process sinval catchup interrupts, if any */
503 if (catchupInterruptPending)
504 ProcessCatchupInterrupt();
506 /* Process notify interrupts, if any */
507 if (notifyInterruptPending)
508 ProcessNotifyInterrupt(true);
510 else if (ProcDiePending)
513 * We're dying. If there is no data available to read, then it's safe
514 * (and sane) to handle that now. If we haven't tried to read yet,
515 * make sure the process latch is set, so that if there is no data
516 * then we'll come back here and die. If we're done reading, also
517 * make sure the process latch is set, as we might've undesirably
518 * cleared it while reading.
520 if (blocked)
521 CHECK_FOR_INTERRUPTS();
522 else
523 SetLatch(MyLatch);
526 errno = save_errno;
530 * ProcessClientWriteInterrupt() - Process interrupts specific to client writes
532 * This is called just before and after low-level writes.
533 * 'blocked' is true if no data could be written and we plan to retry,
534 * false if about to write or done writing.
536 * Must preserve errno!
538 void
539 ProcessClientWriteInterrupt(bool blocked)
541 int save_errno = errno;
543 if (ProcDiePending)
546 * We're dying. If it's not possible to write, then we should handle
547 * that immediately, else a stuck client could indefinitely delay our
548 * response to the signal. If we haven't tried to write yet, make
549 * sure the process latch is set, so that if the write would block
550 * then we'll come back here and die. If we're done writing, also
551 * make sure the process latch is set, as we might've undesirably
552 * cleared it while writing.
554 if (blocked)
557 * Don't mess with whereToSendOutput if ProcessInterrupts wouldn't
558 * service ProcDiePending.
560 if (InterruptHoldoffCount == 0 && CritSectionCount == 0)
563 * We don't want to send the client the error message, as a)
564 * that would possibly block again, and b) it would likely
565 * lead to loss of protocol sync because we may have already
566 * sent a partial protocol message.
568 if (whereToSendOutput == DestRemote)
569 whereToSendOutput = DestNone;
571 CHECK_FOR_INTERRUPTS();
574 else
575 SetLatch(MyLatch);
578 errno = save_errno;
582 * Do raw parsing (only).
584 * A list of parsetrees (RawStmt nodes) is returned, since there might be
585 * multiple commands in the given string.
587 * NOTE: for interactive queries, it is important to keep this routine
588 * separate from the analysis & rewrite stages. Analysis and rewriting
589 * cannot be done in an aborted transaction, since they require access to
590 * database tables. So, we rely on the raw parser to determine whether
591 * we've seen a COMMIT or ABORT command; when we are in abort state, other
592 * commands are not processed any further than the raw parse stage.
594 List *
595 pg_parse_query(const char *query_string)
597 List *raw_parsetree_list;
599 TRACE_POSTGRESQL_QUERY_PARSE_START(query_string);
601 if (log_parser_stats)
602 ResetUsage();
604 raw_parsetree_list = raw_parser(query_string, RAW_PARSE_DEFAULT);
606 if (log_parser_stats)
607 ShowUsage("PARSER STATISTICS");
609 #ifdef COPY_PARSE_PLAN_TREES
610 /* Optional debugging check: pass raw parsetrees through copyObject() */
612 List *new_list = copyObject(raw_parsetree_list);
614 /* This checks both copyObject() and the equal() routines... */
615 if (!equal(new_list, raw_parsetree_list))
616 elog(WARNING, "copyObject() failed to produce an equal raw parse tree");
617 else
618 raw_parsetree_list = new_list;
620 #endif
623 * Currently, outfuncs/readfuncs support is missing for many raw parse
624 * tree nodes, so we don't try to implement WRITE_READ_PARSE_PLAN_TREES
625 * here.
628 TRACE_POSTGRESQL_QUERY_PARSE_DONE(query_string);
630 return raw_parsetree_list;
634 * Given a raw parsetree (gram.y output), and optionally information about
635 * types of parameter symbols ($n), perform parse analysis and rule rewriting.
637 * A list of Query nodes is returned, since either the analyzer or the
638 * rewriter might expand one query to several.
640 * NOTE: for reasons mentioned above, this must be separate from raw parsing.
642 List *
643 pg_analyze_and_rewrite(RawStmt *parsetree, const char *query_string,
644 Oid *paramTypes, int numParams,
645 QueryEnvironment *queryEnv)
647 Query *query;
648 List *querytree_list;
650 TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
653 * (1) Perform parse analysis.
655 if (log_parser_stats)
656 ResetUsage();
658 query = parse_analyze(parsetree, query_string, paramTypes, numParams,
659 queryEnv);
661 if (log_parser_stats)
662 ShowUsage("PARSE ANALYSIS STATISTICS");
665 * (2) Rewrite the queries, as necessary
667 querytree_list = pg_rewrite_query(query);
669 TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
671 return querytree_list;
675 * Do parse analysis and rewriting. This is the same as pg_analyze_and_rewrite
676 * except that external-parameter resolution is determined by parser callback
677 * hooks instead of a fixed list of parameter datatypes.
679 List *
680 pg_analyze_and_rewrite_params(RawStmt *parsetree,
681 const char *query_string,
682 ParserSetupHook parserSetup,
683 void *parserSetupArg,
684 QueryEnvironment *queryEnv)
686 ParseState *pstate;
687 Query *query;
688 List *querytree_list;
689 JumbleState *jstate = NULL;
691 Assert(query_string != NULL); /* required as of 8.4 */
693 TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
696 * (1) Perform parse analysis.
698 if (log_parser_stats)
699 ResetUsage();
701 pstate = make_parsestate(NULL);
702 pstate->p_sourcetext = query_string;
703 pstate->p_queryEnv = queryEnv;
704 (*parserSetup) (pstate, parserSetupArg);
706 query = transformTopLevelStmt(pstate, parsetree);
708 if (IsQueryIdEnabled())
709 jstate = JumbleQuery(query, query_string);
711 if (post_parse_analyze_hook)
712 (*post_parse_analyze_hook) (pstate, query, jstate);
714 free_parsestate(pstate);
716 pgstat_report_query_id(query->queryId, false);
718 if (log_parser_stats)
719 ShowUsage("PARSE ANALYSIS STATISTICS");
722 * (2) Rewrite the queries, as necessary
724 querytree_list = pg_rewrite_query(query);
726 TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
728 return querytree_list;
732 * Perform rewriting of a query produced by parse analysis.
734 * Note: query must just have come from the parser, because we do not do
735 * AcquireRewriteLocks() on it.
737 List *
738 pg_rewrite_query(Query *query)
740 List *querytree_list;
742 if (Debug_print_parse)
743 elog_node_display(LOG, "parse tree", query,
744 Debug_pretty_print);
746 if (log_parser_stats)
747 ResetUsage();
749 if (query->commandType == CMD_UTILITY)
751 /* don't rewrite utilities, just dump 'em into result list */
752 querytree_list = list_make1(query);
754 else
756 /* rewrite regular queries */
757 querytree_list = QueryRewrite(query);
760 if (log_parser_stats)
761 ShowUsage("REWRITER STATISTICS");
763 #ifdef COPY_PARSE_PLAN_TREES
764 /* Optional debugging check: pass querytree through copyObject() */
766 List *new_list;
768 new_list = copyObject(querytree_list);
769 /* This checks both copyObject() and the equal() routines... */
770 if (!equal(new_list, querytree_list))
771 elog(WARNING, "copyObject() failed to produce equal parse tree");
772 else
773 querytree_list = new_list;
775 #endif
777 #ifdef WRITE_READ_PARSE_PLAN_TREES
778 /* Optional debugging check: pass querytree through outfuncs/readfuncs */
780 List *new_list = NIL;
781 ListCell *lc;
784 * We currently lack outfuncs/readfuncs support for most utility
785 * statement types, so only attempt to write/read non-utility queries.
787 foreach(lc, querytree_list)
789 Query *query = lfirst_node(Query, lc);
791 if (query->commandType != CMD_UTILITY)
793 char *str = nodeToString(query);
794 Query *new_query = stringToNodeWithLocations(str);
797 * queryId is not saved in stored rules, but we must preserve
798 * it here to avoid breaking pg_stat_statements.
800 new_query->queryId = query->queryId;
802 new_list = lappend(new_list, new_query);
803 pfree(str);
805 else
806 new_list = lappend(new_list, query);
809 /* This checks both outfuncs/readfuncs and the equal() routines... */
810 if (!equal(new_list, querytree_list))
811 elog(WARNING, "outfuncs/readfuncs failed to produce equal parse tree");
812 else
813 querytree_list = new_list;
815 #endif
817 if (Debug_print_rewritten)
818 elog_node_display(LOG, "rewritten parse tree", querytree_list,
819 Debug_pretty_print);
821 return querytree_list;
826 * Generate a plan for a single already-rewritten query.
827 * This is a thin wrapper around planner() and takes the same parameters.
829 PlannedStmt *
830 pg_plan_query(Query *querytree, const char *query_string, int cursorOptions,
831 ParamListInfo boundParams)
833 PlannedStmt *plan;
835 /* Utility commands have no plans. */
836 if (querytree->commandType == CMD_UTILITY)
837 return NULL;
839 /* Planner must have a snapshot in case it calls user-defined functions. */
840 Assert(ActiveSnapshotSet());
842 TRACE_POSTGRESQL_QUERY_PLAN_START();
844 if (log_planner_stats)
845 ResetUsage();
847 /* call the optimizer */
848 plan = planner(querytree, query_string, cursorOptions, boundParams);
850 if (log_planner_stats)
851 ShowUsage("PLANNER STATISTICS");
853 #ifdef COPY_PARSE_PLAN_TREES
854 /* Optional debugging check: pass plan tree through copyObject() */
856 PlannedStmt *new_plan = copyObject(plan);
859 * equal() currently does not have routines to compare Plan nodes, so
860 * don't try to test equality here. Perhaps fix someday?
862 #ifdef NOT_USED
863 /* This checks both copyObject() and the equal() routines... */
864 if (!equal(new_plan, plan))
865 elog(WARNING, "copyObject() failed to produce an equal plan tree");
866 else
867 #endif
868 plan = new_plan;
870 #endif
872 #ifdef WRITE_READ_PARSE_PLAN_TREES
873 /* Optional debugging check: pass plan tree through outfuncs/readfuncs */
875 char *str;
876 PlannedStmt *new_plan;
878 str = nodeToString(plan);
879 new_plan = stringToNodeWithLocations(str);
880 pfree(str);
883 * equal() currently does not have routines to compare Plan nodes, so
884 * don't try to test equality here. Perhaps fix someday?
886 #ifdef NOT_USED
887 /* This checks both outfuncs/readfuncs and the equal() routines... */
888 if (!equal(new_plan, plan))
889 elog(WARNING, "outfuncs/readfuncs failed to produce an equal plan tree");
890 else
891 #endif
892 plan = new_plan;
894 #endif
897 * Print plan if debugging.
899 if (Debug_print_plan)
900 elog_node_display(LOG, "plan", plan, Debug_pretty_print);
902 TRACE_POSTGRESQL_QUERY_PLAN_DONE();
904 return plan;
908 * Generate plans for a list of already-rewritten queries.
910 * For normal optimizable statements, invoke the planner. For utility
911 * statements, just make a wrapper PlannedStmt node.
913 * The result is a list of PlannedStmt nodes.
915 List *
916 pg_plan_queries(List *querytrees, const char *query_string, int cursorOptions,
917 ParamListInfo boundParams)
919 List *stmt_list = NIL;
920 ListCell *query_list;
922 foreach(query_list, querytrees)
924 Query *query = lfirst_node(Query, query_list);
925 PlannedStmt *stmt;
927 if (query->commandType == CMD_UTILITY)
929 /* Utility commands require no planning. */
930 stmt = makeNode(PlannedStmt);
931 stmt->commandType = CMD_UTILITY;
932 stmt->canSetTag = query->canSetTag;
933 stmt->utilityStmt = query->utilityStmt;
934 stmt->stmt_location = query->stmt_location;
935 stmt->stmt_len = query->stmt_len;
936 stmt->queryId = query->queryId;
938 else
940 stmt = pg_plan_query(query, query_string, cursorOptions,
941 boundParams);
944 stmt_list = lappend(stmt_list, stmt);
947 return stmt_list;
952 * exec_simple_query
954 * Execute a "simple Query" protocol message.
956 static void
957 exec_simple_query(const char *query_string)
959 CommandDest dest = whereToSendOutput;
960 MemoryContext oldcontext;
961 List *parsetree_list;
962 ListCell *parsetree_item;
963 bool save_log_statement_stats = log_statement_stats;
964 bool was_logged = false;
965 bool use_implicit_block;
966 char msec_str[32];
969 * Report query to various monitoring facilities.
971 debug_query_string = query_string;
973 pgstat_report_activity(STATE_RUNNING, query_string);
975 TRACE_POSTGRESQL_QUERY_START(query_string);
978 * We use save_log_statement_stats so ShowUsage doesn't report incorrect
979 * results because ResetUsage wasn't called.
981 if (save_log_statement_stats)
982 ResetUsage();
985 * Start up a transaction command. All queries generated by the
986 * query_string will be in this same command block, *unless* we find a
987 * BEGIN/COMMIT/ABORT statement; we have to force a new xact command after
988 * one of those, else bad things will happen in xact.c. (Note that this
989 * will normally change current memory context.)
991 start_xact_command();
994 * Zap any pre-existing unnamed statement. (While not strictly necessary,
995 * it seems best to define simple-Query mode as if it used the unnamed
996 * statement and portal; this ensures we recover any storage used by prior
997 * unnamed operations.)
999 drop_unnamed_stmt();
1002 * Switch to appropriate context for constructing parsetrees.
1004 oldcontext = MemoryContextSwitchTo(MessageContext);
1007 * Do basic parsing of the query or queries (this should be safe even if
1008 * we are in aborted transaction state!)
1010 parsetree_list = pg_parse_query(query_string);
1012 /* Log immediately if dictated by log_statement */
1013 if (check_log_statement(parsetree_list))
1015 ereport(LOG,
1016 (errmsg("statement: %s", query_string),
1017 errhidestmt(true),
1018 errdetail_execute(parsetree_list)));
1019 was_logged = true;
1023 * Switch back to transaction context to enter the loop.
1025 MemoryContextSwitchTo(oldcontext);
1028 * For historical reasons, if multiple SQL statements are given in a
1029 * single "simple Query" message, we execute them as a single transaction,
1030 * unless explicit transaction control commands are included to make
1031 * portions of the list be separate transactions. To represent this
1032 * behavior properly in the transaction machinery, we use an "implicit"
1033 * transaction block.
1035 use_implicit_block = (list_length(parsetree_list) > 1);
1038 * Run through the raw parsetree(s) and process each one.
1040 foreach(parsetree_item, parsetree_list)
1042 RawStmt *parsetree = lfirst_node(RawStmt, parsetree_item);
1043 bool snapshot_set = false;
1044 CommandTag commandTag;
1045 QueryCompletion qc;
1046 MemoryContext per_parsetree_context = NULL;
1047 List *querytree_list,
1048 *plantree_list;
1049 Portal portal;
1050 DestReceiver *receiver;
1051 int16 format;
1053 pgstat_report_query_id(0, true);
1056 * Get the command name for use in status display (it also becomes the
1057 * default completion tag, down inside PortalRun). Set ps_status and
1058 * do any special start-of-SQL-command processing needed by the
1059 * destination.
1061 commandTag = CreateCommandTag(parsetree->stmt);
1063 set_ps_display(GetCommandTagName(commandTag));
1065 BeginCommand(commandTag, dest);
1068 * If we are in an aborted transaction, reject all commands except
1069 * COMMIT/ABORT. It is important that this test occur before we try
1070 * to do parse analysis, rewrite, or planning, since all those phases
1071 * try to do database accesses, which may fail in abort state. (It
1072 * might be safe to allow some additional utility commands in this
1073 * state, but not many...)
1075 if (IsAbortedTransactionBlockState() &&
1076 !IsTransactionExitStmt(parsetree->stmt))
1077 ereport(ERROR,
1078 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1079 errmsg("current transaction is aborted, "
1080 "commands ignored until end of transaction block"),
1081 errdetail_abort()));
1083 /* Make sure we are in a transaction command */
1084 start_xact_command();
1087 * If using an implicit transaction block, and we're not already in a
1088 * transaction block, start an implicit block to force this statement
1089 * to be grouped together with any following ones. (We must do this
1090 * each time through the loop; otherwise, a COMMIT/ROLLBACK in the
1091 * list would cause later statements to not be grouped.)
1093 if (use_implicit_block)
1094 BeginImplicitTransactionBlock();
1096 /* If we got a cancel signal in parsing or prior command, quit */
1097 CHECK_FOR_INTERRUPTS();
1100 * Set up a snapshot if parse analysis/planning will need one.
1102 if (analyze_requires_snapshot(parsetree))
1104 PushActiveSnapshot(GetTransactionSnapshot());
1105 snapshot_set = true;
1109 * OK to analyze, rewrite, and plan this query.
1111 * Switch to appropriate context for constructing query and plan trees
1112 * (these can't be in the transaction context, as that will get reset
1113 * when the command is COMMIT/ROLLBACK). If we have multiple
1114 * parsetrees, we use a separate context for each one, so that we can
1115 * free that memory before moving on to the next one. But for the
1116 * last (or only) parsetree, just use MessageContext, which will be
1117 * reset shortly after completion anyway. In event of an error, the
1118 * per_parsetree_context will be deleted when MessageContext is reset.
1120 if (lnext(parsetree_list, parsetree_item) != NULL)
1122 per_parsetree_context =
1123 AllocSetContextCreate(MessageContext,
1124 "per-parsetree message context",
1125 ALLOCSET_DEFAULT_SIZES);
1126 oldcontext = MemoryContextSwitchTo(per_parsetree_context);
1128 else
1129 oldcontext = MemoryContextSwitchTo(MessageContext);
1131 querytree_list = pg_analyze_and_rewrite(parsetree, query_string,
1132 NULL, 0, NULL);
1134 plantree_list = pg_plan_queries(querytree_list, query_string,
1135 CURSOR_OPT_PARALLEL_OK, NULL);
1138 * Done with the snapshot used for parsing/planning.
1140 * While it looks promising to reuse the same snapshot for query
1141 * execution (at least for simple protocol), unfortunately it causes
1142 * execution to use a snapshot that has been acquired before locking
1143 * any of the tables mentioned in the query. This creates user-
1144 * visible anomalies, so refrain. Refer to
1145 * https://postgr.es/m/flat/5075D8DF.6050500@fuzzy.cz for details.
1147 if (snapshot_set)
1148 PopActiveSnapshot();
1150 /* If we got a cancel signal in analysis or planning, quit */
1151 CHECK_FOR_INTERRUPTS();
1154 * Create unnamed portal to run the query or queries in. If there
1155 * already is one, silently drop it.
1157 portal = CreatePortal("", true, true);
1158 /* Don't display the portal in pg_cursors */
1159 portal->visible = false;
1162 * We don't have to copy anything into the portal, because everything
1163 * we are passing here is in MessageContext or the
1164 * per_parsetree_context, and so will outlive the portal anyway.
1166 PortalDefineQuery(portal,
1167 NULL,
1168 query_string,
1169 commandTag,
1170 plantree_list,
1171 NULL);
1174 * Start the portal. No parameters here.
1176 PortalStart(portal, NULL, 0, InvalidSnapshot);
1179 * Select the appropriate output format: text unless we are doing a
1180 * FETCH from a binary cursor. (Pretty grotty to have to do this here
1181 * --- but it avoids grottiness in other places. Ah, the joys of
1182 * backward compatibility...)
1184 format = 0; /* TEXT is default */
1185 if (IsA(parsetree->stmt, FetchStmt))
1187 FetchStmt *stmt = (FetchStmt *) parsetree->stmt;
1189 if (!stmt->ismove)
1191 Portal fportal = GetPortalByName(stmt->portalname);
1193 if (PortalIsValid(fportal) &&
1194 (fportal->cursorOptions & CURSOR_OPT_BINARY))
1195 format = 1; /* BINARY */
1198 PortalSetResultFormat(portal, 1, &format);
1201 * Now we can create the destination receiver object.
1203 receiver = CreateDestReceiver(dest);
1204 if (dest == DestRemote)
1205 SetRemoteDestReceiverParams(receiver, portal);
1208 * Switch back to transaction context for execution.
1210 MemoryContextSwitchTo(oldcontext);
1213 * Run the portal to completion, and then drop it (and the receiver).
1215 (void) PortalRun(portal,
1216 FETCH_ALL,
1217 true, /* always top level */
1218 true,
1219 receiver,
1220 receiver,
1221 &qc);
1223 receiver->rDestroy(receiver);
1225 PortalDrop(portal, false);
1227 if (lnext(parsetree_list, parsetree_item) == NULL)
1230 * If this is the last parsetree of the query string, close down
1231 * transaction statement before reporting command-complete. This
1232 * is so that any end-of-transaction errors are reported before
1233 * the command-complete message is issued, to avoid confusing
1234 * clients who will expect either a command-complete message or an
1235 * error, not one and then the other. Also, if we're using an
1236 * implicit transaction block, we must close that out first.
1238 if (use_implicit_block)
1239 EndImplicitTransactionBlock();
1240 finish_xact_command();
1242 else if (IsA(parsetree->stmt, TransactionStmt))
1245 * If this was a transaction control statement, commit it. We will
1246 * start a new xact command for the next command.
1248 finish_xact_command();
1250 else
1253 * We need a CommandCounterIncrement after every query, except
1254 * those that start or end a transaction block.
1256 CommandCounterIncrement();
1259 * Disable statement timeout between queries of a multi-query
1260 * string, so that the timeout applies separately to each query.
1261 * (Our next loop iteration will start a fresh timeout.)
1263 disable_statement_timeout();
1267 * Tell client that we're done with this query. Note we emit exactly
1268 * one EndCommand report for each raw parsetree, thus one for each SQL
1269 * command the client sent, regardless of rewriting. (But a command
1270 * aborted by error will not send an EndCommand report at all.)
1272 EndCommand(&qc, dest, false);
1274 /* Now we may drop the per-parsetree context, if one was created. */
1275 if (per_parsetree_context)
1276 MemoryContextDelete(per_parsetree_context);
1277 } /* end loop over parsetrees */
1280 * Close down transaction statement, if one is open. (This will only do
1281 * something if the parsetree list was empty; otherwise the last loop
1282 * iteration already did it.)
1284 finish_xact_command();
1287 * If there were no parsetrees, return EmptyQueryResponse message.
1289 if (!parsetree_list)
1290 NullCommand(dest);
1293 * Emit duration logging if appropriate.
1295 switch (check_log_duration(msec_str, was_logged))
1297 case 1:
1298 ereport(LOG,
1299 (errmsg("duration: %s ms", msec_str),
1300 errhidestmt(true)));
1301 break;
1302 case 2:
1303 ereport(LOG,
1304 (errmsg("duration: %s ms statement: %s",
1305 msec_str, query_string),
1306 errhidestmt(true),
1307 errdetail_execute(parsetree_list)));
1308 break;
1311 if (save_log_statement_stats)
1312 ShowUsage("QUERY STATISTICS");
1314 TRACE_POSTGRESQL_QUERY_DONE(query_string);
1316 debug_query_string = NULL;
1320 * exec_parse_message
1322 * Execute a "Parse" protocol message.
1324 static void
1325 exec_parse_message(const char *query_string, /* string to execute */
1326 const char *stmt_name, /* name for prepared stmt */
1327 Oid *paramTypes, /* parameter types */
1328 int numParams) /* number of parameters */
1330 MemoryContext unnamed_stmt_context = NULL;
1331 MemoryContext oldcontext;
1332 List *parsetree_list;
1333 RawStmt *raw_parse_tree;
1334 List *querytree_list;
1335 CachedPlanSource *psrc;
1336 bool is_named;
1337 bool save_log_statement_stats = log_statement_stats;
1338 char msec_str[32];
1341 * Report query to various monitoring facilities.
1343 debug_query_string = query_string;
1345 pgstat_report_activity(STATE_RUNNING, query_string);
1347 set_ps_display("PARSE");
1349 if (save_log_statement_stats)
1350 ResetUsage();
1352 ereport(DEBUG2,
1353 (errmsg_internal("parse %s: %s",
1354 *stmt_name ? stmt_name : "<unnamed>",
1355 query_string)));
1358 * Start up a transaction command so we can run parse analysis etc. (Note
1359 * that this will normally change current memory context.) Nothing happens
1360 * if we are already in one. This also arms the statement timeout if
1361 * necessary.
1363 start_xact_command();
1366 * Switch to appropriate context for constructing parsetrees.
1368 * We have two strategies depending on whether the prepared statement is
1369 * named or not. For a named prepared statement, we do parsing in
1370 * MessageContext and copy the finished trees into the prepared
1371 * statement's plancache entry; then the reset of MessageContext releases
1372 * temporary space used by parsing and rewriting. For an unnamed prepared
1373 * statement, we assume the statement isn't going to hang around long, so
1374 * getting rid of temp space quickly is probably not worth the costs of
1375 * copying parse trees. So in this case, we create the plancache entry's
1376 * query_context here, and do all the parsing work therein.
1378 is_named = (stmt_name[0] != '\0');
1379 if (is_named)
1381 /* Named prepared statement --- parse in MessageContext */
1382 oldcontext = MemoryContextSwitchTo(MessageContext);
1384 else
1386 /* Unnamed prepared statement --- release any prior unnamed stmt */
1387 drop_unnamed_stmt();
1388 /* Create context for parsing */
1389 unnamed_stmt_context =
1390 AllocSetContextCreate(MessageContext,
1391 "unnamed prepared statement",
1392 ALLOCSET_DEFAULT_SIZES);
1393 oldcontext = MemoryContextSwitchTo(unnamed_stmt_context);
1397 * Do basic parsing of the query or queries (this should be safe even if
1398 * we are in aborted transaction state!)
1400 parsetree_list = pg_parse_query(query_string);
1403 * We only allow a single user statement in a prepared statement. This is
1404 * mainly to keep the protocol simple --- otherwise we'd need to worry
1405 * about multiple result tupdescs and things like that.
1407 if (list_length(parsetree_list) > 1)
1408 ereport(ERROR,
1409 (errcode(ERRCODE_SYNTAX_ERROR),
1410 errmsg("cannot insert multiple commands into a prepared statement")));
1412 if (parsetree_list != NIL)
1414 Query *query;
1415 bool snapshot_set = false;
1417 raw_parse_tree = linitial_node(RawStmt, parsetree_list);
1420 * If we are in an aborted transaction, reject all commands except
1421 * COMMIT/ROLLBACK. It is important that this test occur before we
1422 * try to do parse analysis, rewrite, or planning, since all those
1423 * phases try to do database accesses, which may fail in abort state.
1424 * (It might be safe to allow some additional utility commands in this
1425 * state, but not many...)
1427 if (IsAbortedTransactionBlockState() &&
1428 !IsTransactionExitStmt(raw_parse_tree->stmt))
1429 ereport(ERROR,
1430 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1431 errmsg("current transaction is aborted, "
1432 "commands ignored until end of transaction block"),
1433 errdetail_abort()));
1436 * Create the CachedPlanSource before we do parse analysis, since it
1437 * needs to see the unmodified raw parse tree.
1439 psrc = CreateCachedPlan(raw_parse_tree, query_string,
1440 CreateCommandTag(raw_parse_tree->stmt));
1443 * Set up a snapshot if parse analysis will need one.
1445 if (analyze_requires_snapshot(raw_parse_tree))
1447 PushActiveSnapshot(GetTransactionSnapshot());
1448 snapshot_set = true;
1452 * Analyze and rewrite the query. Note that the originally specified
1453 * parameter set is not required to be complete, so we have to use
1454 * parse_analyze_varparams().
1456 if (log_parser_stats)
1457 ResetUsage();
1459 query = parse_analyze_varparams(raw_parse_tree,
1460 query_string,
1461 &paramTypes,
1462 &numParams);
1465 * Check all parameter types got determined.
1467 for (int i = 0; i < numParams; i++)
1469 Oid ptype = paramTypes[i];
1471 if (ptype == InvalidOid || ptype == UNKNOWNOID)
1472 ereport(ERROR,
1473 (errcode(ERRCODE_INDETERMINATE_DATATYPE),
1474 errmsg("could not determine data type of parameter $%d",
1475 i + 1)));
1478 if (log_parser_stats)
1479 ShowUsage("PARSE ANALYSIS STATISTICS");
1481 querytree_list = pg_rewrite_query(query);
1483 /* Done with the snapshot used for parsing */
1484 if (snapshot_set)
1485 PopActiveSnapshot();
1487 else
1489 /* Empty input string. This is legal. */
1490 raw_parse_tree = NULL;
1491 psrc = CreateCachedPlan(raw_parse_tree, query_string,
1492 CMDTAG_UNKNOWN);
1493 querytree_list = NIL;
1497 * CachedPlanSource must be a direct child of MessageContext before we
1498 * reparent unnamed_stmt_context under it, else we have a disconnected
1499 * circular subgraph. Klugy, but less so than flipping contexts even more
1500 * above.
1502 if (unnamed_stmt_context)
1503 MemoryContextSetParent(psrc->context, MessageContext);
1505 /* Finish filling in the CachedPlanSource */
1506 CompleteCachedPlan(psrc,
1507 querytree_list,
1508 unnamed_stmt_context,
1509 paramTypes,
1510 numParams,
1511 NULL,
1512 NULL,
1513 CURSOR_OPT_PARALLEL_OK, /* allow parallel mode */
1514 true); /* fixed result */
1516 /* If we got a cancel signal during analysis, quit */
1517 CHECK_FOR_INTERRUPTS();
1519 if (is_named)
1522 * Store the query as a prepared statement.
1524 StorePreparedStatement(stmt_name, psrc, false);
1526 else
1529 * We just save the CachedPlanSource into unnamed_stmt_psrc.
1531 SaveCachedPlan(psrc);
1532 unnamed_stmt_psrc = psrc;
1535 MemoryContextSwitchTo(oldcontext);
1538 * We do NOT close the open transaction command here; that only happens
1539 * when the client sends Sync. Instead, do CommandCounterIncrement just
1540 * in case something happened during parse/plan.
1542 CommandCounterIncrement();
1545 * Send ParseComplete.
1547 if (whereToSendOutput == DestRemote)
1548 pq_putemptymessage('1');
1551 * Emit duration logging if appropriate.
1553 switch (check_log_duration(msec_str, false))
1555 case 1:
1556 ereport(LOG,
1557 (errmsg("duration: %s ms", msec_str),
1558 errhidestmt(true)));
1559 break;
1560 case 2:
1561 ereport(LOG,
1562 (errmsg("duration: %s ms parse %s: %s",
1563 msec_str,
1564 *stmt_name ? stmt_name : "<unnamed>",
1565 query_string),
1566 errhidestmt(true)));
1567 break;
1570 if (save_log_statement_stats)
1571 ShowUsage("PARSE MESSAGE STATISTICS");
1573 debug_query_string = NULL;
1577 * exec_bind_message
1579 * Process a "Bind" message to create a portal from a prepared statement
1581 static void
1582 exec_bind_message(StringInfo input_message)
1584 const char *portal_name;
1585 const char *stmt_name;
1586 int numPFormats;
1587 int16 *pformats = NULL;
1588 int numParams;
1589 int numRFormats;
1590 int16 *rformats = NULL;
1591 CachedPlanSource *psrc;
1592 CachedPlan *cplan;
1593 Portal portal;
1594 char *query_string;
1595 char *saved_stmt_name;
1596 ParamListInfo params;
1597 MemoryContext oldContext;
1598 bool save_log_statement_stats = log_statement_stats;
1599 bool snapshot_set = false;
1600 char msec_str[32];
1601 ParamsErrorCbData params_data;
1602 ErrorContextCallback params_errcxt;
1604 /* Get the fixed part of the message */
1605 portal_name = pq_getmsgstring(input_message);
1606 stmt_name = pq_getmsgstring(input_message);
1608 ereport(DEBUG2,
1609 (errmsg_internal("bind %s to %s",
1610 *portal_name ? portal_name : "<unnamed>",
1611 *stmt_name ? stmt_name : "<unnamed>")));
1613 /* Find prepared statement */
1614 if (stmt_name[0] != '\0')
1616 PreparedStatement *pstmt;
1618 pstmt = FetchPreparedStatement(stmt_name, true);
1619 psrc = pstmt->plansource;
1621 else
1623 /* special-case the unnamed statement */
1624 psrc = unnamed_stmt_psrc;
1625 if (!psrc)
1626 ereport(ERROR,
1627 (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
1628 errmsg("unnamed prepared statement does not exist")));
1632 * Report query to various monitoring facilities.
1634 debug_query_string = psrc->query_string;
1636 pgstat_report_activity(STATE_RUNNING, psrc->query_string);
1638 set_ps_display("BIND");
1640 if (save_log_statement_stats)
1641 ResetUsage();
1644 * Start up a transaction command so we can call functions etc. (Note that
1645 * this will normally change current memory context.) Nothing happens if
1646 * we are already in one. This also arms the statement timeout if
1647 * necessary.
1649 start_xact_command();
1651 /* Switch back to message context */
1652 MemoryContextSwitchTo(MessageContext);
1654 /* Get the parameter format codes */
1655 numPFormats = pq_getmsgint(input_message, 2);
1656 if (numPFormats > 0)
1658 pformats = (int16 *) palloc(numPFormats * sizeof(int16));
1659 for (int i = 0; i < numPFormats; i++)
1660 pformats[i] = pq_getmsgint(input_message, 2);
1663 /* Get the parameter value count */
1664 numParams = pq_getmsgint(input_message, 2);
1666 if (numPFormats > 1 && numPFormats != numParams)
1667 ereport(ERROR,
1668 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1669 errmsg("bind message has %d parameter formats but %d parameters",
1670 numPFormats, numParams)));
1672 if (numParams != psrc->num_params)
1673 ereport(ERROR,
1674 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1675 errmsg("bind message supplies %d parameters, but prepared statement \"%s\" requires %d",
1676 numParams, stmt_name, psrc->num_params)));
1679 * If we are in aborted transaction state, the only portals we can
1680 * actually run are those containing COMMIT or ROLLBACK commands. We
1681 * disallow binding anything else to avoid problems with infrastructure
1682 * that expects to run inside a valid transaction. We also disallow
1683 * binding any parameters, since we can't risk calling user-defined I/O
1684 * functions.
1686 if (IsAbortedTransactionBlockState() &&
1687 (!(psrc->raw_parse_tree &&
1688 IsTransactionExitStmt(psrc->raw_parse_tree->stmt)) ||
1689 numParams != 0))
1690 ereport(ERROR,
1691 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1692 errmsg("current transaction is aborted, "
1693 "commands ignored until end of transaction block"),
1694 errdetail_abort()));
1697 * Create the portal. Allow silent replacement of an existing portal only
1698 * if the unnamed portal is specified.
1700 if (portal_name[0] == '\0')
1701 portal = CreatePortal(portal_name, true, true);
1702 else
1703 portal = CreatePortal(portal_name, false, false);
1706 * Prepare to copy stuff into the portal's memory context. We do all this
1707 * copying first, because it could possibly fail (out-of-memory) and we
1708 * don't want a failure to occur between GetCachedPlan and
1709 * PortalDefineQuery; that would result in leaking our plancache refcount.
1711 oldContext = MemoryContextSwitchTo(portal->portalContext);
1713 /* Copy the plan's query string into the portal */
1714 query_string = pstrdup(psrc->query_string);
1716 /* Likewise make a copy of the statement name, unless it's unnamed */
1717 if (stmt_name[0])
1718 saved_stmt_name = pstrdup(stmt_name);
1719 else
1720 saved_stmt_name = NULL;
1723 * Set a snapshot if we have parameters to fetch (since the input
1724 * functions might need it) or the query isn't a utility command (and
1725 * hence could require redoing parse analysis and planning). We keep the
1726 * snapshot active till we're done, so that plancache.c doesn't have to
1727 * take new ones.
1729 if (numParams > 0 ||
1730 (psrc->raw_parse_tree &&
1731 analyze_requires_snapshot(psrc->raw_parse_tree)))
1733 PushActiveSnapshot(GetTransactionSnapshot());
1734 snapshot_set = true;
1738 * Fetch parameters, if any, and store in the portal's memory context.
1740 if (numParams > 0)
1742 char **knownTextValues = NULL; /* allocate on first use */
1743 BindParamCbData one_param_data;
1746 * Set up an error callback so that if there's an error in this phase,
1747 * we can report the specific parameter causing the problem.
1749 one_param_data.portalName = portal->name;
1750 one_param_data.paramno = -1;
1751 one_param_data.paramval = NULL;
1752 params_errcxt.previous = error_context_stack;
1753 params_errcxt.callback = bind_param_error_callback;
1754 params_errcxt.arg = (void *) &one_param_data;
1755 error_context_stack = &params_errcxt;
1757 params = makeParamList(numParams);
1759 for (int paramno = 0; paramno < numParams; paramno++)
1761 Oid ptype = psrc->param_types[paramno];
1762 int32 plength;
1763 Datum pval;
1764 bool isNull;
1765 StringInfoData pbuf;
1766 char csave;
1767 int16 pformat;
1769 one_param_data.paramno = paramno;
1770 one_param_data.paramval = NULL;
1772 plength = pq_getmsgint(input_message, 4);
1773 isNull = (plength == -1);
1775 if (!isNull)
1777 const char *pvalue = pq_getmsgbytes(input_message, plength);
1780 * Rather than copying data around, we just set up a phony
1781 * StringInfo pointing to the correct portion of the message
1782 * buffer. We assume we can scribble on the message buffer so
1783 * as to maintain the convention that StringInfos have a
1784 * trailing null. This is grotty but is a big win when
1785 * dealing with very large parameter strings.
1787 pbuf.data = unconstify(char *, pvalue);
1788 pbuf.maxlen = plength + 1;
1789 pbuf.len = plength;
1790 pbuf.cursor = 0;
1792 csave = pbuf.data[plength];
1793 pbuf.data[plength] = '\0';
1795 else
1797 pbuf.data = NULL; /* keep compiler quiet */
1798 csave = 0;
1801 if (numPFormats > 1)
1802 pformat = pformats[paramno];
1803 else if (numPFormats > 0)
1804 pformat = pformats[0];
1805 else
1806 pformat = 0; /* default = text */
1808 if (pformat == 0) /* text mode */
1810 Oid typinput;
1811 Oid typioparam;
1812 char *pstring;
1814 getTypeInputInfo(ptype, &typinput, &typioparam);
1817 * We have to do encoding conversion before calling the
1818 * typinput routine.
1820 if (isNull)
1821 pstring = NULL;
1822 else
1823 pstring = pg_client_to_server(pbuf.data, plength);
1825 /* Now we can log the input string in case of error */
1826 one_param_data.paramval = pstring;
1828 pval = OidInputFunctionCall(typinput, pstring, typioparam, -1);
1830 one_param_data.paramval = NULL;
1833 * If we might need to log parameters later, save a copy of
1834 * the converted string in MessageContext; then free the
1835 * result of encoding conversion, if any was done.
1837 if (pstring)
1839 if (log_parameter_max_length_on_error != 0)
1841 MemoryContext oldcxt;
1843 oldcxt = MemoryContextSwitchTo(MessageContext);
1845 if (knownTextValues == NULL)
1846 knownTextValues =
1847 palloc0(numParams * sizeof(char *));
1849 if (log_parameter_max_length_on_error < 0)
1850 knownTextValues[paramno] = pstrdup(pstring);
1851 else
1854 * We can trim the saved string, knowing that we
1855 * won't print all of it. But we must copy at
1856 * least two more full characters than
1857 * BuildParamLogString wants to use; otherwise it
1858 * might fail to include the trailing ellipsis.
1860 knownTextValues[paramno] =
1861 pnstrdup(pstring,
1862 log_parameter_max_length_on_error
1863 + 2 * MAX_MULTIBYTE_CHAR_LEN);
1866 MemoryContextSwitchTo(oldcxt);
1868 if (pstring != pbuf.data)
1869 pfree(pstring);
1872 else if (pformat == 1) /* binary mode */
1874 Oid typreceive;
1875 Oid typioparam;
1876 StringInfo bufptr;
1879 * Call the parameter type's binary input converter
1881 getTypeBinaryInputInfo(ptype, &typreceive, &typioparam);
1883 if (isNull)
1884 bufptr = NULL;
1885 else
1886 bufptr = &pbuf;
1888 pval = OidReceiveFunctionCall(typreceive, bufptr, typioparam, -1);
1890 /* Trouble if it didn't eat the whole buffer */
1891 if (!isNull && pbuf.cursor != pbuf.len)
1892 ereport(ERROR,
1893 (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
1894 errmsg("incorrect binary data format in bind parameter %d",
1895 paramno + 1)));
1897 else
1899 ereport(ERROR,
1900 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1901 errmsg("unsupported format code: %d",
1902 pformat)));
1903 pval = 0; /* keep compiler quiet */
1906 /* Restore message buffer contents */
1907 if (!isNull)
1908 pbuf.data[plength] = csave;
1910 params->params[paramno].value = pval;
1911 params->params[paramno].isnull = isNull;
1914 * We mark the params as CONST. This ensures that any custom plan
1915 * makes full use of the parameter values.
1917 params->params[paramno].pflags = PARAM_FLAG_CONST;
1918 params->params[paramno].ptype = ptype;
1921 /* Pop the per-parameter error callback */
1922 error_context_stack = error_context_stack->previous;
1925 * Once all parameters have been received, prepare for printing them
1926 * in future errors, if configured to do so. (This is saved in the
1927 * portal, so that they'll appear when the query is executed later.)
1929 if (log_parameter_max_length_on_error != 0)
1930 params->paramValuesStr =
1931 BuildParamLogString(params,
1932 knownTextValues,
1933 log_parameter_max_length_on_error);
1935 else
1936 params = NULL;
1938 /* Done storing stuff in portal's context */
1939 MemoryContextSwitchTo(oldContext);
1942 * Set up another error callback so that all the parameters are logged if
1943 * we get an error during the rest of the BIND processing.
1945 params_data.portalName = portal->name;
1946 params_data.params = params;
1947 params_errcxt.previous = error_context_stack;
1948 params_errcxt.callback = ParamsErrorCallback;
1949 params_errcxt.arg = (void *) &params_data;
1950 error_context_stack = &params_errcxt;
1952 /* Get the result format codes */
1953 numRFormats = pq_getmsgint(input_message, 2);
1954 if (numRFormats > 0)
1956 rformats = (int16 *) palloc(numRFormats * sizeof(int16));
1957 for (int i = 0; i < numRFormats; i++)
1958 rformats[i] = pq_getmsgint(input_message, 2);
1961 pq_getmsgend(input_message);
1964 * Obtain a plan from the CachedPlanSource. Any cruft from (re)planning
1965 * will be generated in MessageContext. The plan refcount will be
1966 * assigned to the Portal, so it will be released at portal destruction.
1968 cplan = GetCachedPlan(psrc, params, NULL, NULL);
1971 * Now we can define the portal.
1973 * DO NOT put any code that could possibly throw an error between the
1974 * above GetCachedPlan call and here.
1976 PortalDefineQuery(portal,
1977 saved_stmt_name,
1978 query_string,
1979 psrc->commandTag,
1980 cplan->stmt_list,
1981 cplan);
1983 /* Done with the snapshot used for parameter I/O and parsing/planning */
1984 if (snapshot_set)
1985 PopActiveSnapshot();
1988 * And we're ready to start portal execution.
1990 PortalStart(portal, params, 0, InvalidSnapshot);
1993 * Apply the result format requests to the portal.
1995 PortalSetResultFormat(portal, numRFormats, rformats);
1998 * Done binding; remove the parameters error callback. Entries emitted
1999 * later determine independently whether to log the parameters or not.
2001 error_context_stack = error_context_stack->previous;
2004 * Send BindComplete.
2006 if (whereToSendOutput == DestRemote)
2007 pq_putemptymessage('2');
2010 * Emit duration logging if appropriate.
2012 switch (check_log_duration(msec_str, false))
2014 case 1:
2015 ereport(LOG,
2016 (errmsg("duration: %s ms", msec_str),
2017 errhidestmt(true)));
2018 break;
2019 case 2:
2020 ereport(LOG,
2021 (errmsg("duration: %s ms bind %s%s%s: %s",
2022 msec_str,
2023 *stmt_name ? stmt_name : "<unnamed>",
2024 *portal_name ? "/" : "",
2025 *portal_name ? portal_name : "",
2026 psrc->query_string),
2027 errhidestmt(true),
2028 errdetail_params(params)));
2029 break;
2032 if (save_log_statement_stats)
2033 ShowUsage("BIND MESSAGE STATISTICS");
2035 debug_query_string = NULL;
2039 * exec_execute_message
2041 * Process an "Execute" message for a portal
2043 static void
2044 exec_execute_message(const char *portal_name, long max_rows)
2046 CommandDest dest;
2047 DestReceiver *receiver;
2048 Portal portal;
2049 bool completed;
2050 QueryCompletion qc;
2051 const char *sourceText;
2052 const char *prepStmtName;
2053 ParamListInfo portalParams;
2054 bool save_log_statement_stats = log_statement_stats;
2055 bool is_xact_command;
2056 bool execute_is_fetch;
2057 bool was_logged = false;
2058 char msec_str[32];
2059 ParamsErrorCbData params_data;
2060 ErrorContextCallback params_errcxt;
2062 /* Adjust destination to tell printtup.c what to do */
2063 dest = whereToSendOutput;
2064 if (dest == DestRemote)
2065 dest = DestRemoteExecute;
2067 portal = GetPortalByName(portal_name);
2068 if (!PortalIsValid(portal))
2069 ereport(ERROR,
2070 (errcode(ERRCODE_UNDEFINED_CURSOR),
2071 errmsg("portal \"%s\" does not exist", portal_name)));
2074 * If the original query was a null string, just return
2075 * EmptyQueryResponse.
2077 if (portal->commandTag == CMDTAG_UNKNOWN)
2079 Assert(portal->stmts == NIL);
2080 NullCommand(dest);
2081 return;
2084 /* Does the portal contain a transaction command? */
2085 is_xact_command = IsTransactionStmtList(portal->stmts);
2088 * We must copy the sourceText and prepStmtName into MessageContext in
2089 * case the portal is destroyed during finish_xact_command. Can avoid the
2090 * copy if it's not an xact command, though.
2092 if (is_xact_command)
2094 sourceText = pstrdup(portal->sourceText);
2095 if (portal->prepStmtName)
2096 prepStmtName = pstrdup(portal->prepStmtName);
2097 else
2098 prepStmtName = "<unnamed>";
2101 * An xact command shouldn't have any parameters, which is a good
2102 * thing because they wouldn't be around after finish_xact_command.
2104 portalParams = NULL;
2106 else
2108 sourceText = portal->sourceText;
2109 if (portal->prepStmtName)
2110 prepStmtName = portal->prepStmtName;
2111 else
2112 prepStmtName = "<unnamed>";
2113 portalParams = portal->portalParams;
2117 * Report query to various monitoring facilities.
2119 debug_query_string = sourceText;
2121 pgstat_report_activity(STATE_RUNNING, sourceText);
2123 set_ps_display(GetCommandTagName(portal->commandTag));
2125 if (save_log_statement_stats)
2126 ResetUsage();
2128 BeginCommand(portal->commandTag, dest);
2131 * Create dest receiver in MessageContext (we don't want it in transaction
2132 * context, because that may get deleted if portal contains VACUUM).
2134 receiver = CreateDestReceiver(dest);
2135 if (dest == DestRemoteExecute)
2136 SetRemoteDestReceiverParams(receiver, portal);
2139 * Ensure we are in a transaction command (this should normally be the
2140 * case already due to prior BIND).
2142 start_xact_command();
2145 * If we re-issue an Execute protocol request against an existing portal,
2146 * then we are only fetching more rows rather than completely re-executing
2147 * the query from the start. atStart is never reset for a v3 portal, so we
2148 * are safe to use this check.
2150 execute_is_fetch = !portal->atStart;
2152 /* Log immediately if dictated by log_statement */
2153 if (check_log_statement(portal->stmts))
2155 ereport(LOG,
2156 (errmsg("%s %s%s%s: %s",
2157 execute_is_fetch ?
2158 _("execute fetch from") :
2159 _("execute"),
2160 prepStmtName,
2161 *portal_name ? "/" : "",
2162 *portal_name ? portal_name : "",
2163 sourceText),
2164 errhidestmt(true),
2165 errdetail_params(portalParams)));
2166 was_logged = true;
2170 * If we are in aborted transaction state, the only portals we can
2171 * actually run are those containing COMMIT or ROLLBACK commands.
2173 if (IsAbortedTransactionBlockState() &&
2174 !IsTransactionExitStmtList(portal->stmts))
2175 ereport(ERROR,
2176 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2177 errmsg("current transaction is aborted, "
2178 "commands ignored until end of transaction block"),
2179 errdetail_abort()));
2181 /* Check for cancel signal before we start execution */
2182 CHECK_FOR_INTERRUPTS();
2185 * Okay to run the portal. Set the error callback so that parameters are
2186 * logged. The parameters must have been saved during the bind phase.
2188 params_data.portalName = portal->name;
2189 params_data.params = portalParams;
2190 params_errcxt.previous = error_context_stack;
2191 params_errcxt.callback = ParamsErrorCallback;
2192 params_errcxt.arg = (void *) &params_data;
2193 error_context_stack = &params_errcxt;
2195 if (max_rows <= 0)
2196 max_rows = FETCH_ALL;
2198 completed = PortalRun(portal,
2199 max_rows,
2200 true, /* always top level */
2201 !execute_is_fetch && max_rows == FETCH_ALL,
2202 receiver,
2203 receiver,
2204 &qc);
2206 receiver->rDestroy(receiver);
2208 /* Done executing; remove the params error callback */
2209 error_context_stack = error_context_stack->previous;
2211 if (completed)
2213 if (is_xact_command)
2216 * If this was a transaction control statement, commit it. We
2217 * will start a new xact command for the next command (if any).
2219 finish_xact_command();
2221 else
2224 * We need a CommandCounterIncrement after every query, except
2225 * those that start or end a transaction block.
2227 CommandCounterIncrement();
2230 * Disable statement timeout whenever we complete an Execute
2231 * message. The next protocol message will start a fresh timeout.
2233 disable_statement_timeout();
2236 /* Send appropriate CommandComplete to client */
2237 EndCommand(&qc, dest, false);
2239 else
2241 /* Portal run not complete, so send PortalSuspended */
2242 if (whereToSendOutput == DestRemote)
2243 pq_putemptymessage('s');
2247 * Emit duration logging if appropriate.
2249 switch (check_log_duration(msec_str, was_logged))
2251 case 1:
2252 ereport(LOG,
2253 (errmsg("duration: %s ms", msec_str),
2254 errhidestmt(true)));
2255 break;
2256 case 2:
2257 ereport(LOG,
2258 (errmsg("duration: %s ms %s %s%s%s: %s",
2259 msec_str,
2260 execute_is_fetch ?
2261 _("execute fetch from") :
2262 _("execute"),
2263 prepStmtName,
2264 *portal_name ? "/" : "",
2265 *portal_name ? portal_name : "",
2266 sourceText),
2267 errhidestmt(true),
2268 errdetail_params(portalParams)));
2269 break;
2272 if (save_log_statement_stats)
2273 ShowUsage("EXECUTE MESSAGE STATISTICS");
2275 debug_query_string = NULL;
2279 * check_log_statement
2280 * Determine whether command should be logged because of log_statement
2282 * stmt_list can be either raw grammar output or a list of planned
2283 * statements
2285 static bool
2286 check_log_statement(List *stmt_list)
2288 ListCell *stmt_item;
2290 if (log_statement == LOGSTMT_NONE)
2291 return false;
2292 if (log_statement == LOGSTMT_ALL)
2293 return true;
2295 /* Else we have to inspect the statement(s) to see whether to log */
2296 foreach(stmt_item, stmt_list)
2298 Node *stmt = (Node *) lfirst(stmt_item);
2300 if (GetCommandLogLevel(stmt) <= log_statement)
2301 return true;
2304 return false;
2308 * check_log_duration
2309 * Determine whether current command's duration should be logged
2310 * We also check if this statement in this transaction must be logged
2311 * (regardless of its duration).
2313 * Returns:
2314 * 0 if no logging is needed
2315 * 1 if just the duration should be logged
2316 * 2 if duration and query details should be logged
2318 * If logging is needed, the duration in msec is formatted into msec_str[],
2319 * which must be a 32-byte buffer.
2321 * was_logged should be true if caller already logged query details (this
2322 * essentially prevents 2 from being returned).
2325 check_log_duration(char *msec_str, bool was_logged)
2327 if (log_duration || log_min_duration_sample >= 0 ||
2328 log_min_duration_statement >= 0 || xact_is_sampled)
2330 long secs;
2331 int usecs;
2332 int msecs;
2333 bool exceeded_duration;
2334 bool exceeded_sample_duration;
2335 bool in_sample = false;
2337 TimestampDifference(GetCurrentStatementStartTimestamp(),
2338 GetCurrentTimestamp(),
2339 &secs, &usecs);
2340 msecs = usecs / 1000;
2343 * This odd-looking test for log_min_duration_* being exceeded is
2344 * designed to avoid integer overflow with very long durations: don't
2345 * compute secs * 1000 until we've verified it will fit in int.
2347 exceeded_duration = (log_min_duration_statement == 0 ||
2348 (log_min_duration_statement > 0 &&
2349 (secs > log_min_duration_statement / 1000 ||
2350 secs * 1000 + msecs >= log_min_duration_statement)));
2352 exceeded_sample_duration = (log_min_duration_sample == 0 ||
2353 (log_min_duration_sample > 0 &&
2354 (secs > log_min_duration_sample / 1000 ||
2355 secs * 1000 + msecs >= log_min_duration_sample)));
2358 * Do not log if log_statement_sample_rate = 0. Log a sample if
2359 * log_statement_sample_rate <= 1 and avoid unnecessary PRNG call if
2360 * log_statement_sample_rate = 1.
2362 if (exceeded_sample_duration)
2363 in_sample = log_statement_sample_rate != 0 &&
2364 (log_statement_sample_rate == 1 ||
2365 pg_prng_double(&pg_global_prng_state) <= log_statement_sample_rate);
2367 if (exceeded_duration || in_sample || log_duration || xact_is_sampled)
2369 snprintf(msec_str, 32, "%ld.%03d",
2370 secs * 1000 + msecs, usecs % 1000);
2371 if ((exceeded_duration || in_sample || xact_is_sampled) && !was_logged)
2372 return 2;
2373 else
2374 return 1;
2378 return 0;
2382 * errdetail_execute
2384 * Add an errdetail() line showing the query referenced by an EXECUTE, if any.
2385 * The argument is the raw parsetree list.
2387 static int
2388 errdetail_execute(List *raw_parsetree_list)
2390 ListCell *parsetree_item;
2392 foreach(parsetree_item, raw_parsetree_list)
2394 RawStmt *parsetree = lfirst_node(RawStmt, parsetree_item);
2396 if (IsA(parsetree->stmt, ExecuteStmt))
2398 ExecuteStmt *stmt = (ExecuteStmt *) parsetree->stmt;
2399 PreparedStatement *pstmt;
2401 pstmt = FetchPreparedStatement(stmt->name, false);
2402 if (pstmt)
2404 errdetail("prepare: %s", pstmt->plansource->query_string);
2405 return 0;
2410 return 0;
2414 * errdetail_params
2416 * Add an errdetail() line showing bind-parameter data, if available.
2417 * Note that this is only used for statement logging, so it is controlled
2418 * by log_parameter_max_length not log_parameter_max_length_on_error.
2420 static int
2421 errdetail_params(ParamListInfo params)
2423 if (params && params->numParams > 0 && log_parameter_max_length != 0)
2425 char *str;
2427 str = BuildParamLogString(params, NULL, log_parameter_max_length);
2428 if (str && str[0] != '\0')
2429 errdetail("parameters: %s", str);
2432 return 0;
2436 * errdetail_abort
2438 * Add an errdetail() line showing abort reason, if any.
2440 static int
2441 errdetail_abort(void)
2443 if (MyProc->recoveryConflictPending)
2444 errdetail("abort reason: recovery conflict");
2446 return 0;
2450 * errdetail_recovery_conflict
2452 * Add an errdetail() line showing conflict source.
2454 static int
2455 errdetail_recovery_conflict(void)
2457 switch (RecoveryConflictReason)
2459 case PROCSIG_RECOVERY_CONFLICT_BUFFERPIN:
2460 errdetail("User was holding shared buffer pin for too long.");
2461 break;
2462 case PROCSIG_RECOVERY_CONFLICT_LOCK:
2463 errdetail("User was holding a relation lock for too long.");
2464 break;
2465 case PROCSIG_RECOVERY_CONFLICT_TABLESPACE:
2466 errdetail("User was or might have been using tablespace that must be dropped.");
2467 break;
2468 case PROCSIG_RECOVERY_CONFLICT_SNAPSHOT:
2469 errdetail("User query might have needed to see row versions that must be removed.");
2470 break;
2471 case PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK:
2472 errdetail("User transaction caused buffer deadlock with recovery.");
2473 break;
2474 case PROCSIG_RECOVERY_CONFLICT_DATABASE:
2475 errdetail("User was connected to a database that must be dropped.");
2476 break;
2477 default:
2478 break;
2479 /* no errdetail */
2482 return 0;
2486 * bind_param_error_callback
2488 * Error context callback used while parsing parameters in a Bind message
2490 static void
2491 bind_param_error_callback(void *arg)
2493 BindParamCbData *data = (BindParamCbData *) arg;
2494 StringInfoData buf;
2495 char *quotedval;
2497 if (data->paramno < 0)
2498 return;
2500 /* If we have a textual value, quote it, and trim if necessary */
2501 if (data->paramval)
2503 initStringInfo(&buf);
2504 appendStringInfoStringQuoted(&buf, data->paramval,
2505 log_parameter_max_length_on_error);
2506 quotedval = buf.data;
2508 else
2509 quotedval = NULL;
2511 if (data->portalName && data->portalName[0] != '\0')
2513 if (quotedval)
2514 errcontext("portal \"%s\" parameter $%d = %s",
2515 data->portalName, data->paramno + 1, quotedval);
2516 else
2517 errcontext("portal \"%s\" parameter $%d",
2518 data->portalName, data->paramno + 1);
2520 else
2522 if (quotedval)
2523 errcontext("unnamed portal parameter $%d = %s",
2524 data->paramno + 1, quotedval);
2525 else
2526 errcontext("unnamed portal parameter $%d",
2527 data->paramno + 1);
2530 if (quotedval)
2531 pfree(quotedval);
2535 * exec_describe_statement_message
2537 * Process a "Describe" message for a prepared statement
2539 static void
2540 exec_describe_statement_message(const char *stmt_name)
2542 CachedPlanSource *psrc;
2545 * Start up a transaction command. (Note that this will normally change
2546 * current memory context.) Nothing happens if we are already in one.
2548 start_xact_command();
2550 /* Switch back to message context */
2551 MemoryContextSwitchTo(MessageContext);
2553 /* Find prepared statement */
2554 if (stmt_name[0] != '\0')
2556 PreparedStatement *pstmt;
2558 pstmt = FetchPreparedStatement(stmt_name, true);
2559 psrc = pstmt->plansource;
2561 else
2563 /* special-case the unnamed statement */
2564 psrc = unnamed_stmt_psrc;
2565 if (!psrc)
2566 ereport(ERROR,
2567 (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
2568 errmsg("unnamed prepared statement does not exist")));
2571 /* Prepared statements shouldn't have changeable result descs */
2572 Assert(psrc->fixed_result);
2575 * If we are in aborted transaction state, we can't run
2576 * SendRowDescriptionMessage(), because that needs catalog accesses.
2577 * Hence, refuse to Describe statements that return data. (We shouldn't
2578 * just refuse all Describes, since that might break the ability of some
2579 * clients to issue COMMIT or ROLLBACK commands, if they use code that
2580 * blindly Describes whatever it does.) We can Describe parameters
2581 * without doing anything dangerous, so we don't restrict that.
2583 if (IsAbortedTransactionBlockState() &&
2584 psrc->resultDesc)
2585 ereport(ERROR,
2586 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2587 errmsg("current transaction is aborted, "
2588 "commands ignored until end of transaction block"),
2589 errdetail_abort()));
2591 if (whereToSendOutput != DestRemote)
2592 return; /* can't actually do anything... */
2595 * First describe the parameters...
2597 pq_beginmessage_reuse(&row_description_buf, 't'); /* parameter description
2598 * message type */
2599 pq_sendint16(&row_description_buf, psrc->num_params);
2601 for (int i = 0; i < psrc->num_params; i++)
2603 Oid ptype = psrc->param_types[i];
2605 pq_sendint32(&row_description_buf, (int) ptype);
2607 pq_endmessage_reuse(&row_description_buf);
2610 * Next send RowDescription or NoData to describe the result...
2612 if (psrc->resultDesc)
2614 List *tlist;
2616 /* Get the plan's primary targetlist */
2617 tlist = CachedPlanGetTargetList(psrc, NULL);
2619 SendRowDescriptionMessage(&row_description_buf,
2620 psrc->resultDesc,
2621 tlist,
2622 NULL);
2624 else
2625 pq_putemptymessage('n'); /* NoData */
2630 * exec_describe_portal_message
2632 * Process a "Describe" message for a portal
2634 static void
2635 exec_describe_portal_message(const char *portal_name)
2637 Portal portal;
2640 * Start up a transaction command. (Note that this will normally change
2641 * current memory context.) Nothing happens if we are already in one.
2643 start_xact_command();
2645 /* Switch back to message context */
2646 MemoryContextSwitchTo(MessageContext);
2648 portal = GetPortalByName(portal_name);
2649 if (!PortalIsValid(portal))
2650 ereport(ERROR,
2651 (errcode(ERRCODE_UNDEFINED_CURSOR),
2652 errmsg("portal \"%s\" does not exist", portal_name)));
2655 * If we are in aborted transaction state, we can't run
2656 * SendRowDescriptionMessage(), because that needs catalog accesses.
2657 * Hence, refuse to Describe portals that return data. (We shouldn't just
2658 * refuse all Describes, since that might break the ability of some
2659 * clients to issue COMMIT or ROLLBACK commands, if they use code that
2660 * blindly Describes whatever it does.)
2662 if (IsAbortedTransactionBlockState() &&
2663 portal->tupDesc)
2664 ereport(ERROR,
2665 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2666 errmsg("current transaction is aborted, "
2667 "commands ignored until end of transaction block"),
2668 errdetail_abort()));
2670 if (whereToSendOutput != DestRemote)
2671 return; /* can't actually do anything... */
2673 if (portal->tupDesc)
2674 SendRowDescriptionMessage(&row_description_buf,
2675 portal->tupDesc,
2676 FetchPortalTargetList(portal),
2677 portal->formats);
2678 else
2679 pq_putemptymessage('n'); /* NoData */
2684 * Convenience routines for starting/committing a single command.
2686 static void
2687 start_xact_command(void)
2689 if (!xact_started)
2691 StartTransactionCommand();
2693 xact_started = true;
2697 * Start statement timeout if necessary. Note that this'll intentionally
2698 * not reset the clock on an already started timeout, to avoid the timing
2699 * overhead when start_xact_command() is invoked repeatedly, without an
2700 * interceding finish_xact_command() (e.g. parse/bind/execute). If that's
2701 * not desired, the timeout has to be disabled explicitly.
2703 enable_statement_timeout();
2705 /* Start timeout for checking if the client has gone away if necessary. */
2706 if (client_connection_check_interval > 0 &&
2707 IsUnderPostmaster &&
2708 MyProcPort &&
2709 !get_timeout_active(CLIENT_CONNECTION_CHECK_TIMEOUT))
2710 enable_timeout_after(CLIENT_CONNECTION_CHECK_TIMEOUT,
2711 client_connection_check_interval);
2714 static void
2715 finish_xact_command(void)
2717 /* cancel active statement timeout after each command */
2718 disable_statement_timeout();
2720 if (xact_started)
2722 CommitTransactionCommand();
2724 #ifdef MEMORY_CONTEXT_CHECKING
2725 /* Check all memory contexts that weren't freed during commit */
2726 /* (those that were, were checked before being deleted) */
2727 MemoryContextCheck(TopMemoryContext);
2728 #endif
2730 #ifdef SHOW_MEMORY_STATS
2731 /* Print mem stats after each commit for leak tracking */
2732 MemoryContextStats(TopMemoryContext);
2733 #endif
2735 xact_started = false;
2741 * Convenience routines for checking whether a statement is one of the
2742 * ones that we allow in transaction-aborted state.
2745 /* Test a bare parsetree */
2746 static bool
2747 IsTransactionExitStmt(Node *parsetree)
2749 if (parsetree && IsA(parsetree, TransactionStmt))
2751 TransactionStmt *stmt = (TransactionStmt *) parsetree;
2753 if (stmt->kind == TRANS_STMT_COMMIT ||
2754 stmt->kind == TRANS_STMT_PREPARE ||
2755 stmt->kind == TRANS_STMT_ROLLBACK ||
2756 stmt->kind == TRANS_STMT_ROLLBACK_TO)
2757 return true;
2759 return false;
2762 /* Test a list that contains PlannedStmt nodes */
2763 static bool
2764 IsTransactionExitStmtList(List *pstmts)
2766 if (list_length(pstmts) == 1)
2768 PlannedStmt *pstmt = linitial_node(PlannedStmt, pstmts);
2770 if (pstmt->commandType == CMD_UTILITY &&
2771 IsTransactionExitStmt(pstmt->utilityStmt))
2772 return true;
2774 return false;
2777 /* Test a list that contains PlannedStmt nodes */
2778 static bool
2779 IsTransactionStmtList(List *pstmts)
2781 if (list_length(pstmts) == 1)
2783 PlannedStmt *pstmt = linitial_node(PlannedStmt, pstmts);
2785 if (pstmt->commandType == CMD_UTILITY &&
2786 IsA(pstmt->utilityStmt, TransactionStmt))
2787 return true;
2789 return false;
2792 /* Release any existing unnamed prepared statement */
2793 static void
2794 drop_unnamed_stmt(void)
2796 /* paranoia to avoid a dangling pointer in case of error */
2797 if (unnamed_stmt_psrc)
2799 CachedPlanSource *psrc = unnamed_stmt_psrc;
2801 unnamed_stmt_psrc = NULL;
2802 DropCachedPlan(psrc);
2807 /* --------------------------------
2808 * signal handler routines used in PostgresMain()
2809 * --------------------------------
2813 * quickdie() occurs when signaled SIGQUIT by the postmaster.
2815 * Either some backend has bought the farm, or we've been told to shut down
2816 * "immediately"; so we need to stop what we're doing and exit.
2818 void
2819 quickdie(SIGNAL_ARGS)
2821 sigaddset(&BlockSig, SIGQUIT); /* prevent nested calls */
2822 PG_SETMASK(&BlockSig);
2825 * Prevent interrupts while exiting; though we just blocked signals that
2826 * would queue new interrupts, one may have been pending. We don't want a
2827 * quickdie() downgraded to a mere query cancel.
2829 HOLD_INTERRUPTS();
2832 * If we're aborting out of client auth, don't risk trying to send
2833 * anything to the client; we will likely violate the protocol, not to
2834 * mention that we may have interrupted the guts of OpenSSL or some
2835 * authentication library.
2837 if (ClientAuthInProgress && whereToSendOutput == DestRemote)
2838 whereToSendOutput = DestNone;
2841 * Notify the client before exiting, to give a clue on what happened.
2843 * It's dubious to call ereport() from a signal handler. It is certainly
2844 * not async-signal safe. But it seems better to try, than to disconnect
2845 * abruptly and leave the client wondering what happened. It's remotely
2846 * possible that we crash or hang while trying to send the message, but
2847 * receiving a SIGQUIT is a sign that something has already gone badly
2848 * wrong, so there's not much to lose. Assuming the postmaster is still
2849 * running, it will SIGKILL us soon if we get stuck for some reason.
2851 * One thing we can do to make this a tad safer is to clear the error
2852 * context stack, so that context callbacks are not called. That's a lot
2853 * less code that could be reached here, and the context info is unlikely
2854 * to be very relevant to a SIGQUIT report anyway.
2856 error_context_stack = NULL;
2859 * When responding to a postmaster-issued signal, we send the message only
2860 * to the client; sending to the server log just creates log spam, plus
2861 * it's more code that we need to hope will work in a signal handler.
2863 * Ideally these should be ereport(FATAL), but then we'd not get control
2864 * back to force the correct type of process exit.
2866 switch (GetQuitSignalReason())
2868 case PMQUIT_NOT_SENT:
2869 /* Hmm, SIGQUIT arrived out of the blue */
2870 ereport(WARNING,
2871 (errcode(ERRCODE_ADMIN_SHUTDOWN),
2872 errmsg("terminating connection because of unexpected SIGQUIT signal")));
2873 break;
2874 case PMQUIT_FOR_CRASH:
2875 /* A crash-and-restart cycle is in progress */
2876 ereport(WARNING_CLIENT_ONLY,
2877 (errcode(ERRCODE_CRASH_SHUTDOWN),
2878 errmsg("terminating connection because of crash of another server process"),
2879 errdetail("The postmaster has commanded this server process to roll back"
2880 " the current transaction and exit, because another"
2881 " server process exited abnormally and possibly corrupted"
2882 " shared memory."),
2883 errhint("In a moment you should be able to reconnect to the"
2884 " database and repeat your command.")));
2885 break;
2886 case PMQUIT_FOR_STOP:
2887 /* Immediate-mode stop */
2888 ereport(WARNING_CLIENT_ONLY,
2889 (errcode(ERRCODE_ADMIN_SHUTDOWN),
2890 errmsg("terminating connection due to immediate shutdown command")));
2891 break;
2895 * We DO NOT want to run proc_exit() or atexit() callbacks -- we're here
2896 * because shared memory may be corrupted, so we don't want to try to
2897 * clean up our transaction. Just nail the windows shut and get out of
2898 * town. The callbacks wouldn't be safe to run from a signal handler,
2899 * anyway.
2901 * Note we do _exit(2) not _exit(0). This is to force the postmaster into
2902 * a system reset cycle if someone sends a manual SIGQUIT to a random
2903 * backend. This is necessary precisely because we don't clean up our
2904 * shared memory state. (The "dead man switch" mechanism in pmsignal.c
2905 * should ensure the postmaster sees this as a crash, too, but no harm in
2906 * being doubly sure.)
2908 _exit(2);
2912 * Shutdown signal from postmaster: abort transaction and exit
2913 * at soonest convenient time
2915 void
2916 die(SIGNAL_ARGS)
2918 int save_errno = errno;
2920 /* Don't joggle the elbow of proc_exit */
2921 if (!proc_exit_inprogress)
2923 InterruptPending = true;
2924 ProcDiePending = true;
2927 /* for the statistics collector */
2928 pgStatSessionEndCause = DISCONNECT_KILLED;
2930 /* If we're still here, waken anything waiting on the process latch */
2931 SetLatch(MyLatch);
2934 * If we're in single user mode, we want to quit immediately - we can't
2935 * rely on latches as they wouldn't work when stdin/stdout is a file.
2936 * Rather ugly, but it's unlikely to be worthwhile to invest much more
2937 * effort just for the benefit of single user mode.
2939 if (DoingCommandRead && whereToSendOutput != DestRemote)
2940 ProcessInterrupts();
2942 errno = save_errno;
2946 * Query-cancel signal from postmaster: abort current transaction
2947 * at soonest convenient time
2949 void
2950 StatementCancelHandler(SIGNAL_ARGS)
2952 int save_errno = errno;
2955 * Don't joggle the elbow of proc_exit
2957 if (!proc_exit_inprogress)
2959 InterruptPending = true;
2960 QueryCancelPending = true;
2963 /* If we're still here, waken anything waiting on the process latch */
2964 SetLatch(MyLatch);
2966 errno = save_errno;
2969 /* signal handler for floating point exception */
2970 void
2971 FloatExceptionHandler(SIGNAL_ARGS)
2973 /* We're not returning, so no need to save errno */
2974 ereport(ERROR,
2975 (errcode(ERRCODE_FLOATING_POINT_EXCEPTION),
2976 errmsg("floating-point exception"),
2977 errdetail("An invalid floating-point operation was signaled. "
2978 "This probably means an out-of-range result or an "
2979 "invalid operation, such as division by zero.")));
2983 * RecoveryConflictInterrupt: out-of-line portion of recovery conflict
2984 * handling following receipt of SIGUSR1. Designed to be similar to die()
2985 * and StatementCancelHandler(). Called only by a normal user backend
2986 * that begins a transaction during recovery.
2988 void
2989 RecoveryConflictInterrupt(ProcSignalReason reason)
2991 int save_errno = errno;
2994 * Don't joggle the elbow of proc_exit
2996 if (!proc_exit_inprogress)
2998 RecoveryConflictReason = reason;
2999 switch (reason)
3001 case PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK:
3004 * If we aren't waiting for a lock we can never deadlock.
3006 if (!IsWaitingForLock())
3007 return;
3009 /* Intentional fall through to check wait for pin */
3010 /* FALLTHROUGH */
3012 case PROCSIG_RECOVERY_CONFLICT_BUFFERPIN:
3015 * If PROCSIG_RECOVERY_CONFLICT_BUFFERPIN is requested but we
3016 * aren't blocking the Startup process there is nothing more
3017 * to do.
3019 * When PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK is
3020 * requested, if we're waiting for locks and the startup
3021 * process is not waiting for buffer pin (i.e., also waiting
3022 * for locks), we set the flag so that ProcSleep() will check
3023 * for deadlocks.
3025 if (!HoldingBufferPinThatDelaysRecovery())
3027 if (reason == PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK &&
3028 GetStartupBufferPinWaitBufId() < 0)
3029 CheckDeadLockAlert();
3030 return;
3033 MyProc->recoveryConflictPending = true;
3035 /* Intentional fall through to error handling */
3036 /* FALLTHROUGH */
3038 case PROCSIG_RECOVERY_CONFLICT_LOCK:
3039 case PROCSIG_RECOVERY_CONFLICT_TABLESPACE:
3040 case PROCSIG_RECOVERY_CONFLICT_SNAPSHOT:
3043 * If we aren't in a transaction any longer then ignore.
3045 if (!IsTransactionOrTransactionBlock())
3046 return;
3049 * If we can abort just the current subtransaction then we are
3050 * OK to throw an ERROR to resolve the conflict. Otherwise
3051 * drop through to the FATAL case.
3053 * XXX other times that we can throw just an ERROR *may* be
3054 * PROCSIG_RECOVERY_CONFLICT_LOCK if no locks are held in
3055 * parent transactions
3057 * PROCSIG_RECOVERY_CONFLICT_SNAPSHOT if no snapshots are held
3058 * by parent transactions and the transaction is not
3059 * transaction-snapshot mode
3061 * PROCSIG_RECOVERY_CONFLICT_TABLESPACE if no temp files or
3062 * cursors open in parent transactions
3064 if (!IsSubTransaction())
3067 * If we already aborted then we no longer need to cancel.
3068 * We do this here since we do not wish to ignore aborted
3069 * subtransactions, which must cause FATAL, currently.
3071 if (IsAbortedTransactionBlockState())
3072 return;
3074 RecoveryConflictPending = true;
3075 QueryCancelPending = true;
3076 InterruptPending = true;
3077 break;
3080 /* Intentional fall through to session cancel */
3081 /* FALLTHROUGH */
3083 case PROCSIG_RECOVERY_CONFLICT_DATABASE:
3084 RecoveryConflictPending = true;
3085 ProcDiePending = true;
3086 InterruptPending = true;
3087 break;
3089 default:
3090 elog(FATAL, "unrecognized conflict mode: %d",
3091 (int) reason);
3094 Assert(RecoveryConflictPending && (QueryCancelPending || ProcDiePending));
3097 * All conflicts apart from database cause dynamic errors where the
3098 * command or transaction can be retried at a later point with some
3099 * potential for success. No need to reset this, since non-retryable
3100 * conflict errors are currently FATAL.
3102 if (reason == PROCSIG_RECOVERY_CONFLICT_DATABASE)
3103 RecoveryConflictRetryable = false;
3107 * Set the process latch. This function essentially emulates signal
3108 * handlers like die() and StatementCancelHandler() and it seems prudent
3109 * to behave similarly as they do.
3111 SetLatch(MyLatch);
3113 errno = save_errno;
3117 * ProcessInterrupts: out-of-line portion of CHECK_FOR_INTERRUPTS() macro
3119 * If an interrupt condition is pending, and it's safe to service it,
3120 * then clear the flag and accept the interrupt. Called only when
3121 * InterruptPending is true.
3123 * Note: if INTERRUPTS_CAN_BE_PROCESSED() is true, then ProcessInterrupts
3124 * is guaranteed to clear the InterruptPending flag before returning.
3125 * (This is not the same as guaranteeing that it's still clear when we
3126 * return; another interrupt could have arrived. But we promise that
3127 * any pre-existing one will have been serviced.)
3129 void
3130 ProcessInterrupts(void)
3132 /* OK to accept any interrupts now? */
3133 if (InterruptHoldoffCount != 0 || CritSectionCount != 0)
3134 return;
3135 InterruptPending = false;
3137 if (ProcDiePending)
3139 ProcDiePending = false;
3140 QueryCancelPending = false; /* ProcDie trumps QueryCancel */
3141 LockErrorCleanup();
3142 /* As in quickdie, don't risk sending to client during auth */
3143 if (ClientAuthInProgress && whereToSendOutput == DestRemote)
3144 whereToSendOutput = DestNone;
3145 if (ClientAuthInProgress)
3146 ereport(FATAL,
3147 (errcode(ERRCODE_QUERY_CANCELED),
3148 errmsg("canceling authentication due to timeout")));
3149 else if (IsAutoVacuumWorkerProcess())
3150 ereport(FATAL,
3151 (errcode(ERRCODE_ADMIN_SHUTDOWN),
3152 errmsg("terminating autovacuum process due to administrator command")));
3153 else if (IsLogicalWorker())
3154 ereport(FATAL,
3155 (errcode(ERRCODE_ADMIN_SHUTDOWN),
3156 errmsg("terminating logical replication worker due to administrator command")));
3157 else if (IsLogicalLauncher())
3159 ereport(DEBUG1,
3160 (errmsg_internal("logical replication launcher shutting down")));
3163 * The logical replication launcher can be stopped at any time.
3164 * Use exit status 1 so the background worker is restarted.
3166 proc_exit(1);
3168 else if (RecoveryConflictPending && RecoveryConflictRetryable)
3170 pgstat_report_recovery_conflict(RecoveryConflictReason);
3171 ereport(FATAL,
3172 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
3173 errmsg("terminating connection due to conflict with recovery"),
3174 errdetail_recovery_conflict()));
3176 else if (RecoveryConflictPending)
3178 /* Currently there is only one non-retryable recovery conflict */
3179 Assert(RecoveryConflictReason == PROCSIG_RECOVERY_CONFLICT_DATABASE);
3180 pgstat_report_recovery_conflict(RecoveryConflictReason);
3181 ereport(FATAL,
3182 (errcode(ERRCODE_DATABASE_DROPPED),
3183 errmsg("terminating connection due to conflict with recovery"),
3184 errdetail_recovery_conflict()));
3186 else if (IsBackgroundWorker)
3187 ereport(FATAL,
3188 (errcode(ERRCODE_ADMIN_SHUTDOWN),
3189 errmsg("terminating background worker \"%s\" due to administrator command",
3190 MyBgworkerEntry->bgw_type)));
3191 else
3192 ereport(FATAL,
3193 (errcode(ERRCODE_ADMIN_SHUTDOWN),
3194 errmsg("terminating connection due to administrator command")));
3197 if (CheckClientConnectionPending)
3199 CheckClientConnectionPending = false;
3202 * Check for lost connection and re-arm, if still configured, but not
3203 * if we've arrived back at DoingCommandRead state. We don't want to
3204 * wake up idle sessions, and they already know how to detect lost
3205 * connections.
3207 if (!DoingCommandRead && client_connection_check_interval > 0)
3209 if (!pq_check_connection())
3210 ClientConnectionLost = true;
3211 else
3212 enable_timeout_after(CLIENT_CONNECTION_CHECK_TIMEOUT,
3213 client_connection_check_interval);
3217 if (ClientConnectionLost)
3219 QueryCancelPending = false; /* lost connection trumps QueryCancel */
3220 LockErrorCleanup();
3221 /* don't send to client, we already know the connection to be dead. */
3222 whereToSendOutput = DestNone;
3223 ereport(FATAL,
3224 (errcode(ERRCODE_CONNECTION_FAILURE),
3225 errmsg("connection to client lost")));
3229 * If a recovery conflict happens while we are waiting for input from the
3230 * client, the client is presumably just sitting idle in a transaction,
3231 * preventing recovery from making progress. Terminate the connection to
3232 * dislodge it.
3234 if (RecoveryConflictPending && DoingCommandRead)
3236 QueryCancelPending = false; /* this trumps QueryCancel */
3237 RecoveryConflictPending = false;
3238 LockErrorCleanup();
3239 pgstat_report_recovery_conflict(RecoveryConflictReason);
3240 ereport(FATAL,
3241 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
3242 errmsg("terminating connection due to conflict with recovery"),
3243 errdetail_recovery_conflict(),
3244 errhint("In a moment you should be able to reconnect to the"
3245 " database and repeat your command.")));
3249 * Don't allow query cancel interrupts while reading input from the
3250 * client, because we might lose sync in the FE/BE protocol. (Die
3251 * interrupts are OK, because we won't read any further messages from the
3252 * client in that case.)
3254 if (QueryCancelPending && QueryCancelHoldoffCount != 0)
3257 * Re-arm InterruptPending so that we process the cancel request as
3258 * soon as we're done reading the message. (XXX this is seriously
3259 * ugly: it complicates INTERRUPTS_CAN_BE_PROCESSED(), and it means we
3260 * can't use that macro directly as the initial test in this function,
3261 * meaning that this code also creates opportunities for other bugs to
3262 * appear.)
3264 InterruptPending = true;
3266 else if (QueryCancelPending)
3268 bool lock_timeout_occurred;
3269 bool stmt_timeout_occurred;
3271 QueryCancelPending = false;
3274 * If LOCK_TIMEOUT and STATEMENT_TIMEOUT indicators are both set, we
3275 * need to clear both, so always fetch both.
3277 lock_timeout_occurred = get_timeout_indicator(LOCK_TIMEOUT, true);
3278 stmt_timeout_occurred = get_timeout_indicator(STATEMENT_TIMEOUT, true);
3281 * If both were set, we want to report whichever timeout completed
3282 * earlier; this ensures consistent behavior if the machine is slow
3283 * enough that the second timeout triggers before we get here. A tie
3284 * is arbitrarily broken in favor of reporting a lock timeout.
3286 if (lock_timeout_occurred && stmt_timeout_occurred &&
3287 get_timeout_finish_time(STATEMENT_TIMEOUT) < get_timeout_finish_time(LOCK_TIMEOUT))
3288 lock_timeout_occurred = false; /* report stmt timeout */
3290 if (lock_timeout_occurred)
3292 LockErrorCleanup();
3293 ereport(ERROR,
3294 (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
3295 errmsg("canceling statement due to lock timeout")));
3297 if (stmt_timeout_occurred)
3299 LockErrorCleanup();
3300 ereport(ERROR,
3301 (errcode(ERRCODE_QUERY_CANCELED),
3302 errmsg("canceling statement due to statement timeout")));
3304 if (IsAutoVacuumWorkerProcess())
3306 LockErrorCleanup();
3307 ereport(ERROR,
3308 (errcode(ERRCODE_QUERY_CANCELED),
3309 errmsg("canceling autovacuum task")));
3311 if (RecoveryConflictPending)
3313 RecoveryConflictPending = false;
3314 LockErrorCleanup();
3315 pgstat_report_recovery_conflict(RecoveryConflictReason);
3316 ereport(ERROR,
3317 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
3318 errmsg("canceling statement due to conflict with recovery"),
3319 errdetail_recovery_conflict()));
3323 * If we are reading a command from the client, just ignore the cancel
3324 * request --- sending an extra error message won't accomplish
3325 * anything. Otherwise, go ahead and throw the error.
3327 if (!DoingCommandRead)
3329 LockErrorCleanup();
3330 ereport(ERROR,
3331 (errcode(ERRCODE_QUERY_CANCELED),
3332 errmsg("canceling statement due to user request")));
3336 if (IdleInTransactionSessionTimeoutPending)
3339 * If the GUC has been reset to zero, ignore the signal. This is
3340 * important because the GUC update itself won't disable any pending
3341 * interrupt.
3343 if (IdleInTransactionSessionTimeout > 0)
3344 ereport(FATAL,
3345 (errcode(ERRCODE_IDLE_IN_TRANSACTION_SESSION_TIMEOUT),
3346 errmsg("terminating connection due to idle-in-transaction timeout")));
3347 else
3348 IdleInTransactionSessionTimeoutPending = false;
3351 if (IdleSessionTimeoutPending)
3353 /* As above, ignore the signal if the GUC has been reset to zero. */
3354 if (IdleSessionTimeout > 0)
3355 ereport(FATAL,
3356 (errcode(ERRCODE_IDLE_SESSION_TIMEOUT),
3357 errmsg("terminating connection due to idle-session timeout")));
3358 else
3359 IdleSessionTimeoutPending = false;
3362 if (ProcSignalBarrierPending)
3363 ProcessProcSignalBarrier();
3365 if (ParallelMessagePending)
3366 HandleParallelMessages();
3368 if (LogMemoryContextPending)
3369 ProcessLogMemoryContextInterrupt();
3374 * IA64-specific code to fetch the AR.BSP register for stack depth checks.
3376 * We currently support gcc, icc, and HP-UX's native compiler here.
3378 * Note: while icc accepts gcc asm blocks on x86[_64], this is not true on
3379 * ia64 (at least not in icc versions before 12.x). So we have to carry a
3380 * separate implementation for it.
3382 #if defined(__ia64__) || defined(__ia64)
3384 #if defined(__hpux) && !defined(__GNUC__) && !defined(__INTEL_COMPILER)
3385 /* Assume it's HP-UX native compiler */
3386 #include <ia64/sys/inline.h>
3387 #define ia64_get_bsp() ((char *) (_Asm_mov_from_ar(_AREG_BSP, _NO_FENCE)))
3388 #elif defined(__INTEL_COMPILER)
3389 /* icc */
3390 #include <asm/ia64regs.h>
3391 #define ia64_get_bsp() ((char *) __getReg(_IA64_REG_AR_BSP))
3392 #else
3393 /* gcc */
3394 static __inline__ char *
3395 ia64_get_bsp(void)
3397 char *ret;
3399 /* the ;; is a "stop", seems to be required before fetching BSP */
3400 __asm__ __volatile__(
3401 ";;\n"
3402 " mov %0=ar.bsp \n"
3403 : "=r"(ret));
3405 return ret;
3407 #endif
3408 #endif /* IA64 */
3412 * set_stack_base: set up reference point for stack depth checking
3414 * Returns the old reference point, if any.
3416 pg_stack_base_t
3417 set_stack_base(void)
3419 char stack_base;
3420 pg_stack_base_t old;
3422 #if defined(__ia64__) || defined(__ia64)
3423 old.stack_base_ptr = stack_base_ptr;
3424 old.register_stack_base_ptr = register_stack_base_ptr;
3425 #else
3426 old = stack_base_ptr;
3427 #endif
3429 /* Set up reference point for stack depth checking */
3430 stack_base_ptr = &stack_base;
3431 #if defined(__ia64__) || defined(__ia64)
3432 register_stack_base_ptr = ia64_get_bsp();
3433 #endif
3435 return old;
3439 * restore_stack_base: restore reference point for stack depth checking
3441 * This can be used after set_stack_base() to restore the old value. This
3442 * is currently only used in PL/Java. When PL/Java calls a backend function
3443 * from different thread, the thread's stack is at a different location than
3444 * the main thread's stack, so it sets the base pointer before the call, and
3445 * restores it afterwards.
3447 void
3448 restore_stack_base(pg_stack_base_t base)
3450 #if defined(__ia64__) || defined(__ia64)
3451 stack_base_ptr = base.stack_base_ptr;
3452 register_stack_base_ptr = base.register_stack_base_ptr;
3453 #else
3454 stack_base_ptr = base;
3455 #endif
3459 * check_stack_depth/stack_is_too_deep: check for excessively deep recursion
3461 * This should be called someplace in any recursive routine that might possibly
3462 * recurse deep enough to overflow the stack. Most Unixen treat stack
3463 * overflow as an unrecoverable SIGSEGV, so we want to error out ourselves
3464 * before hitting the hardware limit.
3466 * check_stack_depth() just throws an error summarily. stack_is_too_deep()
3467 * can be used by code that wants to handle the error condition itself.
3469 void
3470 check_stack_depth(void)
3472 if (stack_is_too_deep())
3474 ereport(ERROR,
3475 (errcode(ERRCODE_STATEMENT_TOO_COMPLEX),
3476 errmsg("stack depth limit exceeded"),
3477 errhint("Increase the configuration parameter \"max_stack_depth\" (currently %dkB), "
3478 "after ensuring the platform's stack depth limit is adequate.",
3479 max_stack_depth)));
3483 bool
3484 stack_is_too_deep(void)
3486 char stack_top_loc;
3487 long stack_depth;
3490 * Compute distance from reference point to my local variables
3492 stack_depth = (long) (stack_base_ptr - &stack_top_loc);
3495 * Take abs value, since stacks grow up on some machines, down on others
3497 if (stack_depth < 0)
3498 stack_depth = -stack_depth;
3501 * Trouble?
3503 * The test on stack_base_ptr prevents us from erroring out if called
3504 * during process setup or in a non-backend process. Logically it should
3505 * be done first, but putting it here avoids wasting cycles during normal
3506 * cases.
3508 if (stack_depth > max_stack_depth_bytes &&
3509 stack_base_ptr != NULL)
3510 return true;
3513 * On IA64 there is a separate "register" stack that requires its own
3514 * independent check. For this, we have to measure the change in the
3515 * "BSP" pointer from PostgresMain to here. Logic is just as above,
3516 * except that we know IA64's register stack grows up.
3518 * Note we assume that the same max_stack_depth applies to both stacks.
3520 #if defined(__ia64__) || defined(__ia64)
3521 stack_depth = (long) (ia64_get_bsp() - register_stack_base_ptr);
3523 if (stack_depth > max_stack_depth_bytes &&
3524 register_stack_base_ptr != NULL)
3525 return true;
3526 #endif /* IA64 */
3528 return false;
3531 /* GUC check hook for max_stack_depth */
3532 bool
3533 check_max_stack_depth(int *newval, void **extra, GucSource source)
3535 long newval_bytes = *newval * 1024L;
3536 long stack_rlimit = get_stack_depth_rlimit();
3538 if (stack_rlimit > 0 && newval_bytes > stack_rlimit - STACK_DEPTH_SLOP)
3540 GUC_check_errdetail("\"max_stack_depth\" must not exceed %ldkB.",
3541 (stack_rlimit - STACK_DEPTH_SLOP) / 1024L);
3542 GUC_check_errhint("Increase the platform's stack depth limit via \"ulimit -s\" or local equivalent.");
3543 return false;
3545 return true;
3548 /* GUC assign hook for max_stack_depth */
3549 void
3550 assign_max_stack_depth(int newval, void *extra)
3552 long newval_bytes = newval * 1024L;
3554 max_stack_depth_bytes = newval_bytes;
3559 * set_debug_options --- apply "-d N" command line option
3561 * -d is not quite the same as setting log_min_messages because it enables
3562 * other output options.
3564 void
3565 set_debug_options(int debug_flag, GucContext context, GucSource source)
3567 if (debug_flag > 0)
3569 char debugstr[64];
3571 sprintf(debugstr, "debug%d", debug_flag);
3572 SetConfigOption("log_min_messages", debugstr, context, source);
3574 else
3575 SetConfigOption("log_min_messages", "notice", context, source);
3577 if (debug_flag >= 1 && context == PGC_POSTMASTER)
3579 SetConfigOption("log_connections", "true", context, source);
3580 SetConfigOption("log_disconnections", "true", context, source);
3582 if (debug_flag >= 2)
3583 SetConfigOption("log_statement", "all", context, source);
3584 if (debug_flag >= 3)
3585 SetConfigOption("debug_print_parse", "true", context, source);
3586 if (debug_flag >= 4)
3587 SetConfigOption("debug_print_plan", "true", context, source);
3588 if (debug_flag >= 5)
3589 SetConfigOption("debug_print_rewritten", "true", context, source);
3593 bool
3594 set_plan_disabling_options(const char *arg, GucContext context, GucSource source)
3596 const char *tmp = NULL;
3598 switch (arg[0])
3600 case 's': /* seqscan */
3601 tmp = "enable_seqscan";
3602 break;
3603 case 'i': /* indexscan */
3604 tmp = "enable_indexscan";
3605 break;
3606 case 'o': /* indexonlyscan */
3607 tmp = "enable_indexonlyscan";
3608 break;
3609 case 'b': /* bitmapscan */
3610 tmp = "enable_bitmapscan";
3611 break;
3612 case 't': /* tidscan */
3613 tmp = "enable_tidscan";
3614 break;
3615 case 'n': /* nestloop */
3616 tmp = "enable_nestloop";
3617 break;
3618 case 'm': /* mergejoin */
3619 tmp = "enable_mergejoin";
3620 break;
3621 case 'h': /* hashjoin */
3622 tmp = "enable_hashjoin";
3623 break;
3625 if (tmp)
3627 SetConfigOption(tmp, "false", context, source);
3628 return true;
3630 else
3631 return false;
3635 const char *
3636 get_stats_option_name(const char *arg)
3638 switch (arg[0])
3640 case 'p':
3641 if (optarg[1] == 'a') /* "parser" */
3642 return "log_parser_stats";
3643 else if (optarg[1] == 'l') /* "planner" */
3644 return "log_planner_stats";
3645 break;
3647 case 'e': /* "executor" */
3648 return "log_executor_stats";
3649 break;
3652 return NULL;
3656 /* ----------------------------------------------------------------
3657 * process_postgres_switches
3658 * Parse command line arguments for backends
3660 * This is called twice, once for the "secure" options coming from the
3661 * postmaster or command line, and once for the "insecure" options coming
3662 * from the client's startup packet. The latter have the same syntax but
3663 * may be restricted in what they can do.
3665 * argv[0] is ignored in either case (it's assumed to be the program name).
3667 * ctx is PGC_POSTMASTER for secure options, PGC_BACKEND for insecure options
3668 * coming from the client, or PGC_SU_BACKEND for insecure options coming from
3669 * a superuser client.
3671 * If a database name is present in the command line arguments, it's
3672 * returned into *dbname (this is allowed only if *dbname is initially NULL).
3673 * ----------------------------------------------------------------
3675 void
3676 process_postgres_switches(int argc, char *argv[], GucContext ctx,
3677 const char **dbname)
3679 bool secure = (ctx == PGC_POSTMASTER);
3680 int errs = 0;
3681 GucSource gucsource;
3682 int flag;
3684 if (secure)
3686 gucsource = PGC_S_ARGV; /* switches came from command line */
3688 /* Ignore the initial --single argument, if present */
3689 if (argc > 1 && strcmp(argv[1], "--single") == 0)
3691 argv++;
3692 argc--;
3695 else
3697 gucsource = PGC_S_CLIENT; /* switches came from client */
3700 #ifdef HAVE_INT_OPTERR
3703 * Turn this off because it's either printed to stderr and not the log
3704 * where we'd want it, or argv[0] is now "--single", which would make for
3705 * a weird error message. We print our own error message below.
3707 opterr = 0;
3708 #endif
3711 * Parse command-line options. CAUTION: keep this in sync with
3712 * postmaster/postmaster.c (the option sets should not conflict) and with
3713 * the common help() function in main/main.c.
3715 while ((flag = getopt(argc, argv, "B:bc:C:D:d:EeFf:h:ijk:lN:nOPp:r:S:sTt:v:W:-:")) != -1)
3717 switch (flag)
3719 case 'B':
3720 SetConfigOption("shared_buffers", optarg, ctx, gucsource);
3721 break;
3723 case 'b':
3724 /* Undocumented flag used for binary upgrades */
3725 if (secure)
3726 IsBinaryUpgrade = true;
3727 break;
3729 case 'C':
3730 /* ignored for consistency with the postmaster */
3731 break;
3733 case 'D':
3734 if (secure)
3735 userDoption = strdup(optarg);
3736 break;
3738 case 'd':
3739 set_debug_options(atoi(optarg), ctx, gucsource);
3740 break;
3742 case 'E':
3743 if (secure)
3744 EchoQuery = true;
3745 break;
3747 case 'e':
3748 SetConfigOption("datestyle", "euro", ctx, gucsource);
3749 break;
3751 case 'F':
3752 SetConfigOption("fsync", "false", ctx, gucsource);
3753 break;
3755 case 'f':
3756 if (!set_plan_disabling_options(optarg, ctx, gucsource))
3757 errs++;
3758 break;
3760 case 'h':
3761 SetConfigOption("listen_addresses", optarg, ctx, gucsource);
3762 break;
3764 case 'i':
3765 SetConfigOption("listen_addresses", "*", ctx, gucsource);
3766 break;
3768 case 'j':
3769 if (secure)
3770 UseSemiNewlineNewline = true;
3771 break;
3773 case 'k':
3774 SetConfigOption("unix_socket_directories", optarg, ctx, gucsource);
3775 break;
3777 case 'l':
3778 SetConfigOption("ssl", "true", ctx, gucsource);
3779 break;
3781 case 'N':
3782 SetConfigOption("max_connections", optarg, ctx, gucsource);
3783 break;
3785 case 'n':
3786 /* ignored for consistency with postmaster */
3787 break;
3789 case 'O':
3790 SetConfigOption("allow_system_table_mods", "true", ctx, gucsource);
3791 break;
3793 case 'P':
3794 SetConfigOption("ignore_system_indexes", "true", ctx, gucsource);
3795 break;
3797 case 'p':
3798 SetConfigOption("port", optarg, ctx, gucsource);
3799 break;
3801 case 'r':
3802 /* send output (stdout and stderr) to the given file */
3803 if (secure)
3804 strlcpy(OutputFileName, optarg, MAXPGPATH);
3805 break;
3807 case 'S':
3808 SetConfigOption("work_mem", optarg, ctx, gucsource);
3809 break;
3811 case 's':
3812 SetConfigOption("log_statement_stats", "true", ctx, gucsource);
3813 break;
3815 case 'T':
3816 /* ignored for consistency with the postmaster */
3817 break;
3819 case 't':
3821 const char *tmp = get_stats_option_name(optarg);
3823 if (tmp)
3824 SetConfigOption(tmp, "true", ctx, gucsource);
3825 else
3826 errs++;
3827 break;
3830 case 'v':
3833 * -v is no longer used in normal operation, since
3834 * FrontendProtocol is already set before we get here. We keep
3835 * the switch only for possible use in standalone operation,
3836 * in case we ever support using normal FE/BE protocol with a
3837 * standalone backend.
3839 if (secure)
3840 FrontendProtocol = (ProtocolVersion) atoi(optarg);
3841 break;
3843 case 'W':
3844 SetConfigOption("post_auth_delay", optarg, ctx, gucsource);
3845 break;
3847 case 'c':
3848 case '-':
3850 char *name,
3851 *value;
3853 ParseLongOption(optarg, &name, &value);
3854 if (!value)
3856 if (flag == '-')
3857 ereport(ERROR,
3858 (errcode(ERRCODE_SYNTAX_ERROR),
3859 errmsg("--%s requires a value",
3860 optarg)));
3861 else
3862 ereport(ERROR,
3863 (errcode(ERRCODE_SYNTAX_ERROR),
3864 errmsg("-c %s requires a value",
3865 optarg)));
3867 SetConfigOption(name, value, ctx, gucsource);
3868 free(name);
3869 if (value)
3870 free(value);
3871 break;
3874 default:
3875 errs++;
3876 break;
3879 if (errs)
3880 break;
3884 * Optional database name should be there only if *dbname is NULL.
3886 if (!errs && dbname && *dbname == NULL && argc - optind >= 1)
3887 *dbname = strdup(argv[optind++]);
3889 if (errs || argc != optind)
3891 if (errs)
3892 optind--; /* complain about the previous argument */
3894 /* spell the error message a bit differently depending on context */
3895 if (IsUnderPostmaster)
3896 ereport(FATAL,
3897 errcode(ERRCODE_SYNTAX_ERROR),
3898 errmsg("invalid command-line argument for server process: %s", argv[optind]),
3899 errhint("Try \"%s --help\" for more information.", progname));
3900 else
3901 ereport(FATAL,
3902 errcode(ERRCODE_SYNTAX_ERROR),
3903 errmsg("%s: invalid command-line argument: %s",
3904 progname, argv[optind]),
3905 errhint("Try \"%s --help\" for more information.", progname));
3909 * Reset getopt(3) library so that it will work correctly in subprocesses
3910 * or when this function is called a second time with another array.
3912 optind = 1;
3913 #ifdef HAVE_INT_OPTRESET
3914 optreset = 1; /* some systems need this too */
3915 #endif
3920 * PostgresSingleUserMain
3921 * Entry point for single user mode. argc/argv are the command line
3922 * arguments to be used.
3924 * Performs single user specific setup then calls PostgresMain() to actually
3925 * process queries. Single user mode specific setup should go here, rather
3926 * than PostgresMain() or InitPostgres() when reasonably possible.
3928 void
3929 PostgresSingleUserMain(int argc, char *argv[],
3930 const char *username)
3932 const char *dbname = NULL;
3934 Assert(!IsUnderPostmaster);
3936 /* Initialize startup process environment. */
3937 InitStandaloneProcess(argv[0]);
3940 * Set default values for command-line options.
3942 InitializeGUCOptions();
3945 * Parse command-line options.
3947 process_postgres_switches(argc, argv, PGC_POSTMASTER, &dbname);
3949 /* Must have gotten a database name, or have a default (the username) */
3950 if (dbname == NULL)
3952 dbname = username;
3953 if (dbname == NULL)
3954 ereport(FATAL,
3955 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3956 errmsg("%s: no database nor user name specified",
3957 progname)));
3960 /* Acquire configuration parameters */
3961 if (!SelectConfigFiles(userDoption, progname))
3962 proc_exit(1);
3965 * Validate we have been given a reasonable-looking DataDir and change
3966 * into it.
3968 checkDataDir();
3969 ChangeToDataDir();
3972 * Create lockfile for data directory.
3974 CreateDataDirLockFile(false);
3976 /* read control file (error checking and contains config ) */
3977 LocalProcessControlFile(false);
3979 /* Initialize MaxBackends */
3980 InitializeMaxBackends();
3982 CreateSharedMemoryAndSemaphores();
3985 * Remember stand-alone backend startup time,roughly at the same point
3986 * during startup that postmaster does so.
3988 PgStartTime = GetCurrentTimestamp();
3991 * Create a per-backend PGPROC struct in shared memory. We must do this
3992 * before we can use LWLocks.
3994 InitProcess();
3997 * Now that sufficient infrastructure has been initialized, PostgresMain()
3998 * can do the rest.
4000 PostgresMain(dbname, username);
4004 /* ----------------------------------------------------------------
4005 * PostgresMain
4006 * postgres main loop -- all backends, interactive or otherwise loop here
4008 * dbname is the name of the database to connect to, username is the
4009 * PostgreSQL user name to be used for the session.
4011 * NB: Single user mode specific setup should go to PostgresSingleUserMain()
4012 * if reasonably possible.
4013 * ----------------------------------------------------------------
4015 void
4016 PostgresMain(const char *dbname, const char *username)
4018 int firstchar;
4019 StringInfoData input_message;
4020 sigjmp_buf local_sigjmp_buf;
4021 volatile bool send_ready_for_query = true;
4022 bool idle_in_transaction_timeout_enabled = false;
4023 bool idle_session_timeout_enabled = false;
4025 AssertArg(dbname != NULL);
4026 AssertArg(username != NULL);
4028 SetProcessingMode(InitProcessing);
4031 * Set up signal handlers. (InitPostmasterChild or InitStandaloneProcess
4032 * has already set up BlockSig and made that the active signal mask.)
4034 * Note that postmaster blocked all signals before forking child process,
4035 * so there is no race condition whereby we might receive a signal before
4036 * we have set up the handler.
4038 * Also note: it's best not to use any signals that are SIG_IGNored in the
4039 * postmaster. If such a signal arrives before we are able to change the
4040 * handler to non-SIG_IGN, it'll get dropped. Instead, make a dummy
4041 * handler in the postmaster to reserve the signal. (Of course, this isn't
4042 * an issue for signals that are locally generated, such as SIGALRM and
4043 * SIGPIPE.)
4045 if (am_walsender)
4046 WalSndSignals();
4047 else
4049 pqsignal(SIGHUP, SignalHandlerForConfigReload);
4050 pqsignal(SIGINT, StatementCancelHandler); /* cancel current query */
4051 pqsignal(SIGTERM, die); /* cancel current query and exit */
4054 * In a postmaster child backend, replace SignalHandlerForCrashExit
4055 * with quickdie, so we can tell the client we're dying.
4057 * In a standalone backend, SIGQUIT can be generated from the keyboard
4058 * easily, while SIGTERM cannot, so we make both signals do die()
4059 * rather than quickdie().
4061 if (IsUnderPostmaster)
4062 pqsignal(SIGQUIT, quickdie); /* hard crash time */
4063 else
4064 pqsignal(SIGQUIT, die); /* cancel current query and exit */
4065 InitializeTimeouts(); /* establishes SIGALRM handler */
4068 * Ignore failure to write to frontend. Note: if frontend closes
4069 * connection, we will notice it and exit cleanly when control next
4070 * returns to outer loop. This seems safer than forcing exit in the
4071 * midst of output during who-knows-what operation...
4073 pqsignal(SIGPIPE, SIG_IGN);
4074 pqsignal(SIGUSR1, procsignal_sigusr1_handler);
4075 pqsignal(SIGUSR2, SIG_IGN);
4076 pqsignal(SIGFPE, FloatExceptionHandler);
4079 * Reset some signals that are accepted by postmaster but not by
4080 * backend
4082 pqsignal(SIGCHLD, SIG_DFL); /* system() requires this on some
4083 * platforms */
4086 /* Early initialization */
4087 BaseInit();
4089 /* We need to allow SIGINT, etc during the initial transaction */
4090 PG_SETMASK(&UnBlockSig);
4093 * General initialization.
4095 * NOTE: if you are tempted to add code in this vicinity, consider putting
4096 * it inside InitPostgres() instead. In particular, anything that
4097 * involves database access should be there, not here.
4099 InitPostgres(dbname, InvalidOid, username, InvalidOid, NULL, false);
4102 * If the PostmasterContext is still around, recycle the space; we don't
4103 * need it anymore after InitPostgres completes. Note this does not trash
4104 * *MyProcPort, because ConnCreate() allocated that space with malloc()
4105 * ... else we'd need to copy the Port data first. Also, subsidiary data
4106 * such as the username isn't lost either; see ProcessStartupPacket().
4108 if (PostmasterContext)
4110 MemoryContextDelete(PostmasterContext);
4111 PostmasterContext = NULL;
4114 SetProcessingMode(NormalProcessing);
4117 * Now all GUC states are fully set up. Report them to client if
4118 * appropriate.
4120 BeginReportingGUCOptions();
4123 * Also set up handler to log session end; we have to wait till now to be
4124 * sure Log_disconnections has its final value.
4126 if (IsUnderPostmaster && Log_disconnections)
4127 on_proc_exit(log_disconnections, 0);
4129 pgstat_report_connect(MyDatabaseId);
4131 /* Perform initialization specific to a WAL sender process. */
4132 if (am_walsender)
4133 InitWalSender();
4136 * process any libraries that should be preloaded at backend start (this
4137 * likewise can't be done until GUC settings are complete)
4139 process_session_preload_libraries();
4142 * Send this backend's cancellation info to the frontend.
4144 if (whereToSendOutput == DestRemote)
4146 StringInfoData buf;
4148 pq_beginmessage(&buf, 'K');
4149 pq_sendint32(&buf, (int32) MyProcPid);
4150 pq_sendint32(&buf, (int32) MyCancelKey);
4151 pq_endmessage(&buf);
4152 /* Need not flush since ReadyForQuery will do it. */
4155 /* Welcome banner for standalone case */
4156 if (whereToSendOutput == DestDebug)
4157 printf("\nPostgreSQL stand-alone backend %s\n", PG_VERSION);
4160 * Create the memory context we will use in the main loop.
4162 * MessageContext is reset once per iteration of the main loop, ie, upon
4163 * completion of processing of each command message from the client.
4165 MessageContext = AllocSetContextCreate(TopMemoryContext,
4166 "MessageContext",
4167 ALLOCSET_DEFAULT_SIZES);
4170 * Create memory context and buffer used for RowDescription messages. As
4171 * SendRowDescriptionMessage(), via exec_describe_statement_message(), is
4172 * frequently executed for ever single statement, we don't want to
4173 * allocate a separate buffer every time.
4175 row_description_context = AllocSetContextCreate(TopMemoryContext,
4176 "RowDescriptionContext",
4177 ALLOCSET_DEFAULT_SIZES);
4178 MemoryContextSwitchTo(row_description_context);
4179 initStringInfo(&row_description_buf);
4180 MemoryContextSwitchTo(TopMemoryContext);
4183 * POSTGRES main processing loop begins here
4185 * If an exception is encountered, processing resumes here so we abort the
4186 * current transaction and start a new one.
4188 * You might wonder why this isn't coded as an infinite loop around a
4189 * PG_TRY construct. The reason is that this is the bottom of the
4190 * exception stack, and so with PG_TRY there would be no exception handler
4191 * in force at all during the CATCH part. By leaving the outermost setjmp
4192 * always active, we have at least some chance of recovering from an error
4193 * during error recovery. (If we get into an infinite loop thereby, it
4194 * will soon be stopped by overflow of elog.c's internal state stack.)
4196 * Note that we use sigsetjmp(..., 1), so that this function's signal mask
4197 * (to wit, UnBlockSig) will be restored when longjmp'ing to here. This
4198 * is essential in case we longjmp'd out of a signal handler on a platform
4199 * where that leaves the signal blocked. It's not redundant with the
4200 * unblock in AbortTransaction() because the latter is only called if we
4201 * were inside a transaction.
4204 if (sigsetjmp(local_sigjmp_buf, 1) != 0)
4207 * NOTE: if you are tempted to add more code in this if-block,
4208 * consider the high probability that it should be in
4209 * AbortTransaction() instead. The only stuff done directly here
4210 * should be stuff that is guaranteed to apply *only* for outer-level
4211 * error recovery, such as adjusting the FE/BE protocol status.
4214 /* Since not using PG_TRY, must reset error stack by hand */
4215 error_context_stack = NULL;
4217 /* Prevent interrupts while cleaning up */
4218 HOLD_INTERRUPTS();
4221 * Forget any pending QueryCancel request, since we're returning to
4222 * the idle loop anyway, and cancel any active timeout requests. (In
4223 * future we might want to allow some timeout requests to survive, but
4224 * at minimum it'd be necessary to do reschedule_timeouts(), in case
4225 * we got here because of a query cancel interrupting the SIGALRM
4226 * interrupt handler.) Note in particular that we must clear the
4227 * statement and lock timeout indicators, to prevent any future plain
4228 * query cancels from being misreported as timeouts in case we're
4229 * forgetting a timeout cancel.
4231 disable_all_timeouts(false);
4232 QueryCancelPending = false; /* second to avoid race condition */
4234 /* Not reading from the client anymore. */
4235 DoingCommandRead = false;
4237 /* Make sure libpq is in a good state */
4238 pq_comm_reset();
4240 /* Report the error to the client and/or server log */
4241 EmitErrorReport();
4244 * Make sure debug_query_string gets reset before we possibly clobber
4245 * the storage it points at.
4247 debug_query_string = NULL;
4250 * Abort the current transaction in order to recover.
4252 AbortCurrentTransaction();
4254 if (am_walsender)
4255 WalSndErrorCleanup();
4257 PortalErrorCleanup();
4258 SPICleanup();
4261 * We can't release replication slots inside AbortTransaction() as we
4262 * need to be able to start and abort transactions while having a slot
4263 * acquired. But we never need to hold them across top level errors,
4264 * so releasing here is fine. There's another cleanup in ProcKill()
4265 * ensuring we'll correctly cleanup on FATAL errors as well.
4267 if (MyReplicationSlot != NULL)
4268 ReplicationSlotRelease();
4270 /* We also want to cleanup temporary slots on error. */
4271 ReplicationSlotCleanup();
4273 jit_reset_after_error();
4276 * Now return to normal top-level context and clear ErrorContext for
4277 * next time.
4279 MemoryContextSwitchTo(TopMemoryContext);
4280 FlushErrorState();
4283 * If we were handling an extended-query-protocol message, initiate
4284 * skip till next Sync. This also causes us not to issue
4285 * ReadyForQuery (until we get Sync).
4287 if (doing_extended_query_message)
4288 ignore_till_sync = true;
4290 /* We don't have a transaction command open anymore */
4291 xact_started = false;
4294 * If an error occurred while we were reading a message from the
4295 * client, we have potentially lost track of where the previous
4296 * message ends and the next one begins. Even though we have
4297 * otherwise recovered from the error, we cannot safely read any more
4298 * messages from the client, so there isn't much we can do with the
4299 * connection anymore.
4301 if (pq_is_reading_msg())
4302 ereport(FATAL,
4303 (errcode(ERRCODE_PROTOCOL_VIOLATION),
4304 errmsg("terminating connection because protocol synchronization was lost")));
4306 /* Now we can allow interrupts again */
4307 RESUME_INTERRUPTS();
4310 /* We can now handle ereport(ERROR) */
4311 PG_exception_stack = &local_sigjmp_buf;
4313 if (!ignore_till_sync)
4314 send_ready_for_query = true; /* initially, or after error */
4317 * Non-error queries loop here.
4320 for (;;)
4323 * At top of loop, reset extended-query-message flag, so that any
4324 * errors encountered in "idle" state don't provoke skip.
4326 doing_extended_query_message = false;
4329 * Release storage left over from prior query cycle, and create a new
4330 * query input buffer in the cleared MessageContext.
4332 MemoryContextSwitchTo(MessageContext);
4333 MemoryContextResetAndDeleteChildren(MessageContext);
4335 initStringInfo(&input_message);
4338 * Also consider releasing our catalog snapshot if any, so that it's
4339 * not preventing advance of global xmin while we wait for the client.
4341 InvalidateCatalogSnapshotConditionally();
4344 * (1) If we've reached idle state, tell the frontend we're ready for
4345 * a new query.
4347 * Note: this includes fflush()'ing the last of the prior output.
4349 * This is also a good time to send collected statistics to the
4350 * collector, and to update the PS stats display. We avoid doing
4351 * those every time through the message loop because it'd slow down
4352 * processing of batched messages, and because we don't want to report
4353 * uncommitted updates (that confuses autovacuum). The notification
4354 * processor wants a call too, if we are not in a transaction block.
4356 * Also, if an idle timeout is enabled, start the timer for that.
4358 if (send_ready_for_query)
4360 if (IsAbortedTransactionBlockState())
4362 set_ps_display("idle in transaction (aborted)");
4363 pgstat_report_activity(STATE_IDLEINTRANSACTION_ABORTED, NULL);
4365 /* Start the idle-in-transaction timer */
4366 if (IdleInTransactionSessionTimeout > 0)
4368 idle_in_transaction_timeout_enabled = true;
4369 enable_timeout_after(IDLE_IN_TRANSACTION_SESSION_TIMEOUT,
4370 IdleInTransactionSessionTimeout);
4373 else if (IsTransactionOrTransactionBlock())
4375 set_ps_display("idle in transaction");
4376 pgstat_report_activity(STATE_IDLEINTRANSACTION, NULL);
4378 /* Start the idle-in-transaction timer */
4379 if (IdleInTransactionSessionTimeout > 0)
4381 idle_in_transaction_timeout_enabled = true;
4382 enable_timeout_after(IDLE_IN_TRANSACTION_SESSION_TIMEOUT,
4383 IdleInTransactionSessionTimeout);
4386 else
4389 * Process incoming notifies (including self-notifies), if
4390 * any, and send relevant messages to the client. Doing it
4391 * here helps ensure stable behavior in tests: if any notifies
4392 * were received during the just-finished transaction, they'll
4393 * be seen by the client before ReadyForQuery is.
4395 if (notifyInterruptPending)
4396 ProcessNotifyInterrupt(false);
4398 pgstat_report_stat(false);
4400 set_ps_display("idle");
4401 pgstat_report_activity(STATE_IDLE, NULL);
4403 /* Start the idle-session timer */
4404 if (IdleSessionTimeout > 0)
4406 idle_session_timeout_enabled = true;
4407 enable_timeout_after(IDLE_SESSION_TIMEOUT,
4408 IdleSessionTimeout);
4412 /* Report any recently-changed GUC options */
4413 ReportChangedGUCOptions();
4415 ReadyForQuery(whereToSendOutput);
4416 send_ready_for_query = false;
4420 * (2) Allow asynchronous signals to be executed immediately if they
4421 * come in while we are waiting for client input. (This must be
4422 * conditional since we don't want, say, reads on behalf of COPY FROM
4423 * STDIN doing the same thing.)
4425 DoingCommandRead = true;
4428 * (3) read a command (loop blocks here)
4430 firstchar = ReadCommand(&input_message);
4433 * (4) turn off the idle-in-transaction and idle-session timeouts, if
4434 * active. We do this before step (5) so that any last-moment timeout
4435 * is certain to be detected in step (5).
4437 * At most one of these timeouts will be active, so there's no need to
4438 * worry about combining the timeout.c calls into one.
4440 if (idle_in_transaction_timeout_enabled)
4442 disable_timeout(IDLE_IN_TRANSACTION_SESSION_TIMEOUT, false);
4443 idle_in_transaction_timeout_enabled = false;
4445 if (idle_session_timeout_enabled)
4447 disable_timeout(IDLE_SESSION_TIMEOUT, false);
4448 idle_session_timeout_enabled = false;
4452 * (5) disable async signal conditions again.
4454 * Query cancel is supposed to be a no-op when there is no query in
4455 * progress, so if a query cancel arrived while we were idle, just
4456 * reset QueryCancelPending. ProcessInterrupts() has that effect when
4457 * it's called when DoingCommandRead is set, so check for interrupts
4458 * before resetting DoingCommandRead.
4460 CHECK_FOR_INTERRUPTS();
4461 DoingCommandRead = false;
4464 * (6) check for any other interesting events that happened while we
4465 * slept.
4467 if (ConfigReloadPending)
4469 ConfigReloadPending = false;
4470 ProcessConfigFile(PGC_SIGHUP);
4474 * (7) process the command. But ignore it if we're skipping till
4475 * Sync.
4477 if (ignore_till_sync && firstchar != EOF)
4478 continue;
4480 switch (firstchar)
4482 case 'Q': /* simple query */
4484 const char *query_string;
4486 /* Set statement_timestamp() */
4487 SetCurrentStatementStartTimestamp();
4489 query_string = pq_getmsgstring(&input_message);
4490 pq_getmsgend(&input_message);
4492 if (am_walsender)
4494 if (!exec_replication_command(query_string))
4495 exec_simple_query(query_string);
4497 else
4498 exec_simple_query(query_string);
4500 send_ready_for_query = true;
4502 break;
4504 case 'P': /* parse */
4506 const char *stmt_name;
4507 const char *query_string;
4508 int numParams;
4509 Oid *paramTypes = NULL;
4511 forbidden_in_wal_sender(firstchar);
4513 /* Set statement_timestamp() */
4514 SetCurrentStatementStartTimestamp();
4516 stmt_name = pq_getmsgstring(&input_message);
4517 query_string = pq_getmsgstring(&input_message);
4518 numParams = pq_getmsgint(&input_message, 2);
4519 if (numParams > 0)
4521 paramTypes = (Oid *) palloc(numParams * sizeof(Oid));
4522 for (int i = 0; i < numParams; i++)
4523 paramTypes[i] = pq_getmsgint(&input_message, 4);
4525 pq_getmsgend(&input_message);
4527 exec_parse_message(query_string, stmt_name,
4528 paramTypes, numParams);
4530 break;
4532 case 'B': /* bind */
4533 forbidden_in_wal_sender(firstchar);
4535 /* Set statement_timestamp() */
4536 SetCurrentStatementStartTimestamp();
4539 * this message is complex enough that it seems best to put
4540 * the field extraction out-of-line
4542 exec_bind_message(&input_message);
4543 break;
4545 case 'E': /* execute */
4547 const char *portal_name;
4548 int max_rows;
4550 forbidden_in_wal_sender(firstchar);
4552 /* Set statement_timestamp() */
4553 SetCurrentStatementStartTimestamp();
4555 portal_name = pq_getmsgstring(&input_message);
4556 max_rows = pq_getmsgint(&input_message, 4);
4557 pq_getmsgend(&input_message);
4559 exec_execute_message(portal_name, max_rows);
4561 break;
4563 case 'F': /* fastpath function call */
4564 forbidden_in_wal_sender(firstchar);
4566 /* Set statement_timestamp() */
4567 SetCurrentStatementStartTimestamp();
4569 /* Report query to various monitoring facilities. */
4570 pgstat_report_activity(STATE_FASTPATH, NULL);
4571 set_ps_display("<FASTPATH>");
4573 /* start an xact for this function invocation */
4574 start_xact_command();
4577 * Note: we may at this point be inside an aborted
4578 * transaction. We can't throw error for that until we've
4579 * finished reading the function-call message, so
4580 * HandleFunctionRequest() must check for it after doing so.
4581 * Be careful not to do anything that assumes we're inside a
4582 * valid transaction here.
4585 /* switch back to message context */
4586 MemoryContextSwitchTo(MessageContext);
4588 HandleFunctionRequest(&input_message);
4590 /* commit the function-invocation transaction */
4591 finish_xact_command();
4593 send_ready_for_query = true;
4594 break;
4596 case 'C': /* close */
4598 int close_type;
4599 const char *close_target;
4601 forbidden_in_wal_sender(firstchar);
4603 close_type = pq_getmsgbyte(&input_message);
4604 close_target = pq_getmsgstring(&input_message);
4605 pq_getmsgend(&input_message);
4607 switch (close_type)
4609 case 'S':
4610 if (close_target[0] != '\0')
4611 DropPreparedStatement(close_target, false);
4612 else
4614 /* special-case the unnamed statement */
4615 drop_unnamed_stmt();
4617 break;
4618 case 'P':
4620 Portal portal;
4622 portal = GetPortalByName(close_target);
4623 if (PortalIsValid(portal))
4624 PortalDrop(portal, false);
4626 break;
4627 default:
4628 ereport(ERROR,
4629 (errcode(ERRCODE_PROTOCOL_VIOLATION),
4630 errmsg("invalid CLOSE message subtype %d",
4631 close_type)));
4632 break;
4635 if (whereToSendOutput == DestRemote)
4636 pq_putemptymessage('3'); /* CloseComplete */
4638 break;
4640 case 'D': /* describe */
4642 int describe_type;
4643 const char *describe_target;
4645 forbidden_in_wal_sender(firstchar);
4647 /* Set statement_timestamp() (needed for xact) */
4648 SetCurrentStatementStartTimestamp();
4650 describe_type = pq_getmsgbyte(&input_message);
4651 describe_target = pq_getmsgstring(&input_message);
4652 pq_getmsgend(&input_message);
4654 switch (describe_type)
4656 case 'S':
4657 exec_describe_statement_message(describe_target);
4658 break;
4659 case 'P':
4660 exec_describe_portal_message(describe_target);
4661 break;
4662 default:
4663 ereport(ERROR,
4664 (errcode(ERRCODE_PROTOCOL_VIOLATION),
4665 errmsg("invalid DESCRIBE message subtype %d",
4666 describe_type)));
4667 break;
4670 break;
4672 case 'H': /* flush */
4673 pq_getmsgend(&input_message);
4674 if (whereToSendOutput == DestRemote)
4675 pq_flush();
4676 break;
4678 case 'S': /* sync */
4679 pq_getmsgend(&input_message);
4680 finish_xact_command();
4681 send_ready_for_query = true;
4682 break;
4685 * 'X' means that the frontend is closing down the socket. EOF
4686 * means unexpected loss of frontend connection. Either way,
4687 * perform normal shutdown.
4689 case EOF:
4691 /* for the statistics collector */
4692 pgStatSessionEndCause = DISCONNECT_CLIENT_EOF;
4694 /* FALLTHROUGH */
4696 case 'X':
4699 * Reset whereToSendOutput to prevent ereport from attempting
4700 * to send any more messages to client.
4702 if (whereToSendOutput == DestRemote)
4703 whereToSendOutput = DestNone;
4706 * NOTE: if you are tempted to add more code here, DON'T!
4707 * Whatever you had in mind to do should be set up as an
4708 * on_proc_exit or on_shmem_exit callback, instead. Otherwise
4709 * it will fail to be called during other backend-shutdown
4710 * scenarios.
4712 proc_exit(0);
4714 case 'd': /* copy data */
4715 case 'c': /* copy done */
4716 case 'f': /* copy fail */
4719 * Accept but ignore these messages, per protocol spec; we
4720 * probably got here because a COPY failed, and the frontend
4721 * is still sending data.
4723 break;
4725 default:
4726 ereport(FATAL,
4727 (errcode(ERRCODE_PROTOCOL_VIOLATION),
4728 errmsg("invalid frontend message type %d",
4729 firstchar)));
4731 } /* end of input-reading loop */
4735 * Throw an error if we're a WAL sender process.
4737 * This is used to forbid anything else than simple query protocol messages
4738 * in a WAL sender process. 'firstchar' specifies what kind of a forbidden
4739 * message was received, and is used to construct the error message.
4741 static void
4742 forbidden_in_wal_sender(char firstchar)
4744 if (am_walsender)
4746 if (firstchar == 'F')
4747 ereport(ERROR,
4748 (errcode(ERRCODE_PROTOCOL_VIOLATION),
4749 errmsg("fastpath function calls not supported in a replication connection")));
4750 else
4751 ereport(ERROR,
4752 (errcode(ERRCODE_PROTOCOL_VIOLATION),
4753 errmsg("extended query protocol not supported in a replication connection")));
4759 * Obtain platform stack depth limit (in bytes)
4761 * Return -1 if unknown
4763 long
4764 get_stack_depth_rlimit(void)
4766 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_STACK)
4767 static long val = 0;
4769 /* This won't change after process launch, so check just once */
4770 if (val == 0)
4772 struct rlimit rlim;
4774 if (getrlimit(RLIMIT_STACK, &rlim) < 0)
4775 val = -1;
4776 else if (rlim.rlim_cur == RLIM_INFINITY)
4777 val = LONG_MAX;
4778 /* rlim_cur is probably of an unsigned type, so check for overflow */
4779 else if (rlim.rlim_cur >= LONG_MAX)
4780 val = LONG_MAX;
4781 else
4782 val = rlim.rlim_cur;
4784 return val;
4785 #else /* no getrlimit */
4786 #if defined(WIN32) || defined(__CYGWIN__)
4787 /* On Windows we set the backend stack size in src/backend/Makefile */
4788 return WIN32_STACK_RLIMIT;
4789 #else /* not windows ... give up */
4790 return -1;
4791 #endif
4792 #endif
4796 static struct rusage Save_r;
4797 static struct timeval Save_t;
4799 void
4800 ResetUsage(void)
4802 getrusage(RUSAGE_SELF, &Save_r);
4803 gettimeofday(&Save_t, NULL);
4806 void
4807 ShowUsage(const char *title)
4809 StringInfoData str;
4810 struct timeval user,
4811 sys;
4812 struct timeval elapse_t;
4813 struct rusage r;
4815 getrusage(RUSAGE_SELF, &r);
4816 gettimeofday(&elapse_t, NULL);
4817 memcpy((char *) &user, (char *) &r.ru_utime, sizeof(user));
4818 memcpy((char *) &sys, (char *) &r.ru_stime, sizeof(sys));
4819 if (elapse_t.tv_usec < Save_t.tv_usec)
4821 elapse_t.tv_sec--;
4822 elapse_t.tv_usec += 1000000;
4824 if (r.ru_utime.tv_usec < Save_r.ru_utime.tv_usec)
4826 r.ru_utime.tv_sec--;
4827 r.ru_utime.tv_usec += 1000000;
4829 if (r.ru_stime.tv_usec < Save_r.ru_stime.tv_usec)
4831 r.ru_stime.tv_sec--;
4832 r.ru_stime.tv_usec += 1000000;
4836 * The only stats we don't show here are ixrss, idrss, isrss. It takes
4837 * some work to interpret them, and most platforms don't fill them in.
4839 initStringInfo(&str);
4841 appendStringInfoString(&str, "! system usage stats:\n");
4842 appendStringInfo(&str,
4843 "!\t%ld.%06ld s user, %ld.%06ld s system, %ld.%06ld s elapsed\n",
4844 (long) (r.ru_utime.tv_sec - Save_r.ru_utime.tv_sec),
4845 (long) (r.ru_utime.tv_usec - Save_r.ru_utime.tv_usec),
4846 (long) (r.ru_stime.tv_sec - Save_r.ru_stime.tv_sec),
4847 (long) (r.ru_stime.tv_usec - Save_r.ru_stime.tv_usec),
4848 (long) (elapse_t.tv_sec - Save_t.tv_sec),
4849 (long) (elapse_t.tv_usec - Save_t.tv_usec));
4850 appendStringInfo(&str,
4851 "!\t[%ld.%06ld s user, %ld.%06ld s system total]\n",
4852 (long) user.tv_sec,
4853 (long) user.tv_usec,
4854 (long) sys.tv_sec,
4855 (long) sys.tv_usec);
4856 #if defined(HAVE_GETRUSAGE)
4857 appendStringInfo(&str,
4858 "!\t%ld kB max resident size\n",
4859 #if defined(__darwin__)
4860 /* in bytes on macOS */
4861 r.ru_maxrss / 1024
4862 #else
4863 /* in kilobytes on most other platforms */
4864 r.ru_maxrss
4865 #endif
4867 appendStringInfo(&str,
4868 "!\t%ld/%ld [%ld/%ld] filesystem blocks in/out\n",
4869 r.ru_inblock - Save_r.ru_inblock,
4870 /* they only drink coffee at dec */
4871 r.ru_oublock - Save_r.ru_oublock,
4872 r.ru_inblock, r.ru_oublock);
4873 appendStringInfo(&str,
4874 "!\t%ld/%ld [%ld/%ld] page faults/reclaims, %ld [%ld] swaps\n",
4875 r.ru_majflt - Save_r.ru_majflt,
4876 r.ru_minflt - Save_r.ru_minflt,
4877 r.ru_majflt, r.ru_minflt,
4878 r.ru_nswap - Save_r.ru_nswap,
4879 r.ru_nswap);
4880 appendStringInfo(&str,
4881 "!\t%ld [%ld] signals rcvd, %ld/%ld [%ld/%ld] messages rcvd/sent\n",
4882 r.ru_nsignals - Save_r.ru_nsignals,
4883 r.ru_nsignals,
4884 r.ru_msgrcv - Save_r.ru_msgrcv,
4885 r.ru_msgsnd - Save_r.ru_msgsnd,
4886 r.ru_msgrcv, r.ru_msgsnd);
4887 appendStringInfo(&str,
4888 "!\t%ld/%ld [%ld/%ld] voluntary/involuntary context switches\n",
4889 r.ru_nvcsw - Save_r.ru_nvcsw,
4890 r.ru_nivcsw - Save_r.ru_nivcsw,
4891 r.ru_nvcsw, r.ru_nivcsw);
4892 #endif /* HAVE_GETRUSAGE */
4894 /* remove trailing newline */
4895 if (str.data[str.len - 1] == '\n')
4896 str.data[--str.len] = '\0';
4898 ereport(LOG,
4899 (errmsg_internal("%s", title),
4900 errdetail_internal("%s", str.data)));
4902 pfree(str.data);
4906 * on_proc_exit handler to log end of session
4908 static void
4909 log_disconnections(int code, Datum arg)
4911 Port *port = MyProcPort;
4912 long secs;
4913 int usecs;
4914 int msecs;
4915 int hours,
4916 minutes,
4917 seconds;
4919 TimestampDifference(MyStartTimestamp,
4920 GetCurrentTimestamp(),
4921 &secs, &usecs);
4922 msecs = usecs / 1000;
4924 hours = secs / SECS_PER_HOUR;
4925 secs %= SECS_PER_HOUR;
4926 minutes = secs / SECS_PER_MINUTE;
4927 seconds = secs % SECS_PER_MINUTE;
4929 ereport(LOG,
4930 (errmsg("disconnection: session time: %d:%02d:%02d.%03d "
4931 "user=%s database=%s host=%s%s%s",
4932 hours, minutes, seconds, msecs,
4933 port->user_name, port->database_name, port->remote_host,
4934 port->remote_port[0] ? " port=" : "", port->remote_port)));
4938 * Start statement timeout timer, if enabled.
4940 * If there's already a timeout running, don't restart the timer. That
4941 * enables compromises between accuracy of timeouts and cost of starting a
4942 * timeout.
4944 static void
4945 enable_statement_timeout(void)
4947 /* must be within an xact */
4948 Assert(xact_started);
4950 if (StatementTimeout > 0)
4952 if (!get_timeout_active(STATEMENT_TIMEOUT))
4953 enable_timeout_after(STATEMENT_TIMEOUT, StatementTimeout);
4955 else
4957 if (get_timeout_active(STATEMENT_TIMEOUT))
4958 disable_timeout(STATEMENT_TIMEOUT, false);
4963 * Disable statement timeout, if active.
4965 static void
4966 disable_statement_timeout(void)
4968 if (get_timeout_active(STATEMENT_TIMEOUT))
4969 disable_timeout(STATEMENT_TIMEOUT, false);