Fix xslt_process() to ensure that it inserts a NULL terminator after the
[PostgreSQL.git] / src / backend / tcop / postgres.c
blobedd6ffe99b5c518195dce0dc7586cd41a77d0b80
1 /*-------------------------------------------------------------------------
3 * postgres.c
4 * POSTGRES C Backend Interface
6 * Portions Copyright (c) 1996-2009, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
10 * IDENTIFICATION
11 * $PostgreSQL$
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 <time.h>
23 #include <unistd.h>
24 #include <signal.h>
25 #include <fcntl.h>
26 #include <sys/socket.h>
27 #ifdef HAVE_SYS_SELECT_H
28 #include <sys/select.h>
29 #endif
30 #ifdef HAVE_SYS_RESOURCE_H
31 #include <sys/time.h>
32 #include <sys/resource.h>
33 #endif
34 #ifdef HAVE_GETOPT_H
35 #include <getopt.h>
36 #endif
38 #ifndef HAVE_GETRUSAGE
39 #include "rusagestub.h"
40 #endif
42 #include "access/printtup.h"
43 #include "access/xact.h"
44 #include "catalog/pg_type.h"
45 #include "commands/async.h"
46 #include "commands/prepare.h"
47 #include "libpq/libpq.h"
48 #include "libpq/pqformat.h"
49 #include "libpq/pqsignal.h"
50 #include "miscadmin.h"
51 #include "nodes/print.h"
52 #include "optimizer/planner.h"
53 #include "pgstat.h"
54 #include "pg_trace.h"
55 #include "parser/analyze.h"
56 #include "parser/parser.h"
57 #include "postmaster/autovacuum.h"
58 #include "rewrite/rewriteHandler.h"
59 #include "storage/bufmgr.h"
60 #include "storage/ipc.h"
61 #include "storage/proc.h"
62 #include "storage/sinval.h"
63 #include "tcop/fastpath.h"
64 #include "tcop/pquery.h"
65 #include "tcop/tcopprot.h"
66 #include "tcop/utility.h"
67 #include "utils/flatfiles.h"
68 #include "utils/lsyscache.h"
69 #include "utils/memutils.h"
70 #include "utils/ps_status.h"
71 #include "utils/snapmgr.h"
72 #include "mb/pg_wchar.h"
75 extern int optind;
76 extern char *optarg;
78 /* ----------------
79 * global variables
80 * ----------------
82 const char *debug_query_string; /* client-supplied query string */
84 /* Note: whereToSendOutput is initialized for the bootstrap/standalone case */
85 CommandDest whereToSendOutput = DestDebug;
87 /* flag for logging end of session */
88 bool Log_disconnections = false;
90 int log_statement = LOGSTMT_NONE;
92 /* GUC variable for maximum stack depth (measured in kilobytes) */
93 int max_stack_depth = 100;
95 /* wait N seconds to allow attach from a debugger */
96 int PostAuthDelay = 0;
100 /* ----------------
101 * private variables
102 * ----------------
105 /* max_stack_depth converted to bytes for speed of checking */
106 static long max_stack_depth_bytes = 100 * 1024L;
109 * Stack base pointer -- initialized by PostgresMain. This is not static
110 * so that PL/Java can modify it.
112 char *stack_base_ptr = NULL;
116 * Flag to mark SIGHUP. Whenever the main loop comes around it
117 * will reread the configuration file. (Better than doing the
118 * reading in the signal handler, ey?)
120 static volatile sig_atomic_t got_SIGHUP = false;
123 * Flag to keep track of whether we have started a transaction.
124 * For extended query protocol this has to be remembered across messages.
126 static bool xact_started = false;
129 * Flag to indicate that we are doing the outer loop's read-from-client,
130 * as opposed to any random read from client that might happen within
131 * commands like COPY FROM STDIN.
133 static bool DoingCommandRead = false;
136 * Flags to implement skip-till-Sync-after-error behavior for messages of
137 * the extended query protocol.
139 static bool doing_extended_query_message = false;
140 static bool ignore_till_sync = false;
143 * If an unnamed prepared statement exists, it's stored here.
144 * We keep it separate from the hashtable kept by commands/prepare.c
145 * in order to reduce overhead for short-lived queries.
147 static CachedPlanSource *unnamed_stmt_psrc = NULL;
149 /* workspace for building a new unnamed statement in */
150 static MemoryContext unnamed_stmt_context = NULL;
153 static bool EchoQuery = false; /* default don't echo */
156 * people who want to use EOF should #define DONTUSENEWLINE in
157 * tcop/tcopdebug.h
159 #ifndef TCOP_DONTUSENEWLINE
160 static int UseNewLine = 1; /* Use newlines query delimiters (the default) */
161 #else
162 static int UseNewLine = 0; /* Use EOF as query delimiters */
163 #endif /* TCOP_DONTUSENEWLINE */
166 /* ----------------------------------------------------------------
167 * decls for routines only used in this file
168 * ----------------------------------------------------------------
170 static int InteractiveBackend(StringInfo inBuf);
171 static int interactive_getc(void);
172 static int SocketBackend(StringInfo inBuf);
173 static int ReadCommand(StringInfo inBuf);
174 static List *pg_rewrite_query(Query *query);
175 static bool check_log_statement(List *stmt_list);
176 static int errdetail_execute(List *raw_parsetree_list);
177 static int errdetail_params(ParamListInfo params);
178 static void start_xact_command(void);
179 static void finish_xact_command(void);
180 static bool IsTransactionExitStmt(Node *parsetree);
181 static bool IsTransactionExitStmtList(List *parseTrees);
182 static bool IsTransactionStmtList(List *parseTrees);
183 static void drop_unnamed_stmt(void);
184 static void SigHupHandler(SIGNAL_ARGS);
185 static void log_disconnections(int code, Datum arg);
188 /* ----------------------------------------------------------------
189 * routines to obtain user input
190 * ----------------------------------------------------------------
193 /* ----------------
194 * InteractiveBackend() is called for user interactive connections
196 * the string entered by the user is placed in its parameter inBuf,
197 * and we act like a Q message was received.
199 * EOF is returned if end-of-file input is seen; time to shut down.
200 * ----------------
203 static int
204 InteractiveBackend(StringInfo inBuf)
206 int c; /* character read from getc() */
207 bool end = false; /* end-of-input flag */
208 bool backslashSeen = false; /* have we seen a \ ? */
211 * display a prompt and obtain input from the user
213 printf("backend> ");
214 fflush(stdout);
216 resetStringInfo(inBuf);
218 if (UseNewLine)
221 * if we are using \n as a delimiter, then read characters until the
222 * \n.
224 while ((c = interactive_getc()) != EOF)
226 if (c == '\n')
228 if (backslashSeen)
230 /* discard backslash from inBuf */
231 inBuf->data[--inBuf->len] = '\0';
232 backslashSeen = false;
233 continue;
235 else
237 /* keep the newline character */
238 appendStringInfoChar(inBuf, '\n');
239 break;
242 else if (c == '\\')
243 backslashSeen = true;
244 else
245 backslashSeen = false;
247 appendStringInfoChar(inBuf, (char) c);
250 if (c == EOF)
251 end = true;
253 else
256 * otherwise read characters until EOF.
258 while ((c = interactive_getc()) != EOF)
259 appendStringInfoChar(inBuf, (char) c);
261 /* No input before EOF signal means time to quit. */
262 if (inBuf->len == 0)
263 end = true;
266 if (end)
267 return EOF;
270 * otherwise we have a user query so process it.
273 /* Add '\0' to make it look the same as message case. */
274 appendStringInfoChar(inBuf, (char) '\0');
277 * if the query echo flag was given, print the query..
279 if (EchoQuery)
280 printf("statement: %s\n", inBuf->data);
281 fflush(stdout);
283 return 'Q';
287 * interactive_getc -- collect one character from stdin
289 * Even though we are not reading from a "client" process, we still want to
290 * respond to signals, particularly SIGTERM/SIGQUIT. Hence we must use
291 * prepare_for_client_read and client_read_ended.
293 static int
294 interactive_getc(void)
296 int c;
298 prepare_for_client_read();
299 c = getc(stdin);
300 client_read_ended();
301 return c;
304 /* ----------------
305 * SocketBackend() Is called for frontend-backend connections
307 * Returns the message type code, and loads message body data into inBuf.
309 * EOF is returned if the connection is lost.
310 * ----------------
312 static int
313 SocketBackend(StringInfo inBuf)
315 int qtype;
318 * Get message type code from the frontend.
320 qtype = pq_getbyte();
322 if (qtype == EOF) /* frontend disconnected */
324 ereport(COMMERROR,
325 (errcode(ERRCODE_PROTOCOL_VIOLATION),
326 errmsg("unexpected EOF on client connection")));
327 return qtype;
331 * Validate message type code before trying to read body; if we have lost
332 * sync, better to say "command unknown" than to run out of memory because
333 * we used garbage as a length word.
335 * This also gives us a place to set the doing_extended_query_message flag
336 * as soon as possible.
338 switch (qtype)
340 case 'Q': /* simple query */
341 doing_extended_query_message = false;
342 if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
344 /* old style without length word; convert */
345 if (pq_getstring(inBuf))
347 ereport(COMMERROR,
348 (errcode(ERRCODE_PROTOCOL_VIOLATION),
349 errmsg("unexpected EOF on client connection")));
350 return EOF;
353 break;
355 case 'F': /* fastpath function call */
356 /* we let fastpath.c cope with old-style input of this */
357 doing_extended_query_message = false;
358 break;
360 case 'X': /* terminate */
361 doing_extended_query_message = false;
362 ignore_till_sync = false;
363 break;
365 case 'B': /* bind */
366 case 'C': /* close */
367 case 'D': /* describe */
368 case 'E': /* execute */
369 case 'H': /* flush */
370 case 'P': /* parse */
371 doing_extended_query_message = true;
372 /* these are only legal in protocol 3 */
373 if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
374 ereport(FATAL,
375 (errcode(ERRCODE_PROTOCOL_VIOLATION),
376 errmsg("invalid frontend message type %d", qtype)));
377 break;
379 case 'S': /* sync */
380 /* stop any active skip-till-Sync */
381 ignore_till_sync = false;
382 /* mark not-extended, so that a new error doesn't begin skip */
383 doing_extended_query_message = false;
384 /* only legal in protocol 3 */
385 if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
386 ereport(FATAL,
387 (errcode(ERRCODE_PROTOCOL_VIOLATION),
388 errmsg("invalid frontend message type %d", qtype)));
389 break;
391 case 'd': /* copy data */
392 case 'c': /* copy done */
393 case 'f': /* copy fail */
394 doing_extended_query_message = false;
395 /* these are only legal in protocol 3 */
396 if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
397 ereport(FATAL,
398 (errcode(ERRCODE_PROTOCOL_VIOLATION),
399 errmsg("invalid frontend message type %d", qtype)));
400 break;
402 default:
405 * Otherwise we got garbage from the frontend. We treat this as
406 * fatal because we have probably lost message boundary sync, and
407 * there's no good way to recover.
409 ereport(FATAL,
410 (errcode(ERRCODE_PROTOCOL_VIOLATION),
411 errmsg("invalid frontend message type %d", qtype)));
412 break;
416 * In protocol version 3, all frontend messages have a length word next
417 * after the type code; we can read the message contents independently of
418 * the type.
420 if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3)
422 if (pq_getmessage(inBuf, 0))
423 return EOF; /* suitable message already logged */
426 return qtype;
429 /* ----------------
430 * ReadCommand reads a command from either the frontend or
431 * standard input, places it in inBuf, and returns the
432 * message type code (first byte of the message).
433 * EOF is returned if end of file.
434 * ----------------
436 static int
437 ReadCommand(StringInfo inBuf)
439 int result;
441 if (whereToSendOutput == DestRemote)
442 result = SocketBackend(inBuf);
443 else
444 result = InteractiveBackend(inBuf);
445 return result;
449 * prepare_for_client_read -- set up to possibly block on client input
451 * This must be called immediately before any low-level read from the
452 * client connection. It is necessary to do it at a sufficiently low level
453 * that there won't be any other operations except the read kernel call
454 * itself between this call and the subsequent client_read_ended() call.
455 * In particular there mustn't be use of malloc() or other potentially
456 * non-reentrant libc functions. This restriction makes it safe for us
457 * to allow interrupt service routines to execute nontrivial code while
458 * we are waiting for input.
460 void
461 prepare_for_client_read(void)
463 if (DoingCommandRead)
465 /* Enable immediate processing of asynchronous signals */
466 EnableNotifyInterrupt();
467 EnableCatchupInterrupt();
469 /* Allow "die" interrupt to be processed while waiting */
470 ImmediateInterruptOK = true;
472 /* And don't forget to detect one that already arrived */
473 QueryCancelPending = false;
474 CHECK_FOR_INTERRUPTS();
479 * client_read_ended -- get out of the client-input state
481 void
482 client_read_ended(void)
484 if (DoingCommandRead)
486 ImmediateInterruptOK = false;
487 QueryCancelPending = false; /* forget any CANCEL signal */
489 DisableNotifyInterrupt();
490 DisableCatchupInterrupt();
496 * Parse a query string and pass it through the rewriter.
498 * A list of Query nodes is returned, since the string might contain
499 * multiple queries and/or the rewriter might expand one query to several.
501 * NOTE: this routine is no longer used for processing interactive queries,
502 * but it is still needed for parsing of SQL function bodies.
504 List *
505 pg_parse_and_rewrite(const char *query_string, /* string to execute */
506 Oid *paramTypes, /* parameter types */
507 int numParams) /* number of parameters */
509 List *raw_parsetree_list;
510 List *querytree_list;
511 ListCell *list_item;
514 * (1) parse the request string into a list of raw parse trees.
516 raw_parsetree_list = pg_parse_query(query_string);
519 * (2) Do parse analysis and rule rewrite.
521 querytree_list = NIL;
522 foreach(list_item, raw_parsetree_list)
524 Node *parsetree = (Node *) lfirst(list_item);
526 querytree_list = list_concat(querytree_list,
527 pg_analyze_and_rewrite(parsetree,
528 query_string,
529 paramTypes,
530 numParams));
533 return querytree_list;
537 * Do raw parsing (only).
539 * A list of parsetrees is returned, since there might be multiple
540 * commands in the given string.
542 * NOTE: for interactive queries, it is important to keep this routine
543 * separate from the analysis & rewrite stages. Analysis and rewriting
544 * cannot be done in an aborted transaction, since they require access to
545 * database tables. So, we rely on the raw parser to determine whether
546 * we've seen a COMMIT or ABORT command; when we are in abort state, other
547 * commands are not processed any further than the raw parse stage.
549 List *
550 pg_parse_query(const char *query_string)
552 List *raw_parsetree_list;
554 TRACE_POSTGRESQL_QUERY_PARSE_START(query_string);
556 if (log_parser_stats)
557 ResetUsage();
559 raw_parsetree_list = raw_parser(query_string);
561 if (log_parser_stats)
562 ShowUsage("PARSER STATISTICS");
564 #ifdef COPY_PARSE_PLAN_TREES
565 /* Optional debugging check: pass raw parsetrees through copyObject() */
567 List *new_list = (List *) copyObject(raw_parsetree_list);
569 /* This checks both copyObject() and the equal() routines... */
570 if (!equal(new_list, raw_parsetree_list))
571 elog(WARNING, "copyObject() failed to produce an equal raw parse tree");
572 else
573 raw_parsetree_list = new_list;
575 #endif
577 TRACE_POSTGRESQL_QUERY_PARSE_DONE(query_string);
579 return raw_parsetree_list;
583 * Given a raw parsetree (gram.y output), and optionally information about
584 * types of parameter symbols ($n), perform parse analysis and rule rewriting.
586 * A list of Query nodes is returned, since either the analyzer or the
587 * rewriter might expand one query to several.
589 * NOTE: for reasons mentioned above, this must be separate from raw parsing.
591 List *
592 pg_analyze_and_rewrite(Node *parsetree, const char *query_string,
593 Oid *paramTypes, int numParams)
595 Query *query;
596 List *querytree_list;
598 TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
601 * (1) Perform parse analysis.
603 if (log_parser_stats)
604 ResetUsage();
606 query = parse_analyze(parsetree, query_string, paramTypes, numParams);
608 if (log_parser_stats)
609 ShowUsage("PARSE ANALYSIS STATISTICS");
612 * (2) Rewrite the queries, as necessary
614 querytree_list = pg_rewrite_query(query);
616 TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
618 return querytree_list;
622 * Perform rewriting of a query produced by parse analysis.
624 * Note: query must just have come from the parser, because we do not do
625 * AcquireRewriteLocks() on it.
627 static List *
628 pg_rewrite_query(Query *query)
630 List *querytree_list;
632 if (Debug_print_parse)
633 elog_node_display(LOG, "parse tree", query,
634 Debug_pretty_print);
636 if (log_parser_stats)
637 ResetUsage();
639 if (query->commandType == CMD_UTILITY)
641 /* don't rewrite utilities, just dump 'em into result list */
642 querytree_list = list_make1(query);
644 else
646 /* rewrite regular queries */
647 querytree_list = QueryRewrite(query);
650 if (log_parser_stats)
651 ShowUsage("REWRITER STATISTICS");
653 #ifdef COPY_PARSE_PLAN_TREES
654 /* Optional debugging check: pass querytree output through copyObject() */
656 List *new_list;
658 new_list = (List *) copyObject(querytree_list);
659 /* This checks both copyObject() and the equal() routines... */
660 if (!equal(new_list, querytree_list))
661 elog(WARNING, "copyObject() failed to produce equal parse tree");
662 else
663 querytree_list = new_list;
665 #endif
667 if (Debug_print_rewritten)
668 elog_node_display(LOG, "rewritten parse tree", querytree_list,
669 Debug_pretty_print);
671 return querytree_list;
676 * Generate a plan for a single already-rewritten query.
677 * This is a thin wrapper around planner() and takes the same parameters.
679 PlannedStmt *
680 pg_plan_query(Query *querytree, int cursorOptions, ParamListInfo boundParams)
682 PlannedStmt *plan;
684 /* Utility commands have no plans. */
685 if (querytree->commandType == CMD_UTILITY)
686 return NULL;
688 /* Planner must have a snapshot in case it calls user-defined functions. */
689 Assert(ActiveSnapshotSet());
691 TRACE_POSTGRESQL_QUERY_PLAN_START();
693 if (log_planner_stats)
694 ResetUsage();
696 /* call the optimizer */
697 plan = planner(querytree, cursorOptions, boundParams);
699 if (log_planner_stats)
700 ShowUsage("PLANNER STATISTICS");
702 #ifdef COPY_PARSE_PLAN_TREES
703 /* Optional debugging check: pass plan output through copyObject() */
705 PlannedStmt *new_plan = (PlannedStmt *) copyObject(plan);
708 * equal() currently does not have routines to compare Plan nodes, so
709 * don't try to test equality here. Perhaps fix someday?
711 #ifdef NOT_USED
712 /* This checks both copyObject() and the equal() routines... */
713 if (!equal(new_plan, plan))
714 elog(WARNING, "copyObject() failed to produce an equal plan tree");
715 else
716 #endif
717 plan = new_plan;
719 #endif
722 * Print plan if debugging.
724 if (Debug_print_plan)
725 elog_node_display(LOG, "plan", plan, Debug_pretty_print);
727 TRACE_POSTGRESQL_QUERY_PLAN_DONE();
729 return plan;
733 * Generate plans for a list of already-rewritten queries.
735 * Normal optimizable statements generate PlannedStmt entries in the result
736 * list. Utility statements are simply represented by their statement nodes.
738 List *
739 pg_plan_queries(List *querytrees, int cursorOptions, ParamListInfo boundParams)
741 List *stmt_list = NIL;
742 ListCell *query_list;
744 foreach(query_list, querytrees)
746 Query *query = (Query *) lfirst(query_list);
747 Node *stmt;
749 if (query->commandType == CMD_UTILITY)
751 /* Utility commands have no plans. */
752 stmt = query->utilityStmt;
754 else
756 stmt = (Node *) pg_plan_query(query, cursorOptions, boundParams);
759 stmt_list = lappend(stmt_list, stmt);
762 return stmt_list;
767 * exec_simple_query
769 * Execute a "simple Query" protocol message.
771 static void
772 exec_simple_query(const char *query_string)
774 CommandDest dest = whereToSendOutput;
775 MemoryContext oldcontext;
776 List *parsetree_list;
777 ListCell *parsetree_item;
778 bool save_log_statement_stats = log_statement_stats;
779 bool was_logged = false;
780 bool isTopLevel;
781 char msec_str[32];
785 * Report query to various monitoring facilities.
787 debug_query_string = query_string;
789 pgstat_report_activity(query_string);
791 TRACE_POSTGRESQL_QUERY_START(query_string);
794 * We use save_log_statement_stats so ShowUsage doesn't report incorrect
795 * results because ResetUsage wasn't called.
797 if (save_log_statement_stats)
798 ResetUsage();
801 * Start up a transaction command. All queries generated by the
802 * query_string will be in this same command block, *unless* we find a
803 * BEGIN/COMMIT/ABORT statement; we have to force a new xact command after
804 * one of those, else bad things will happen in xact.c. (Note that this
805 * will normally change current memory context.)
807 start_xact_command();
810 * Zap any pre-existing unnamed statement. (While not strictly necessary,
811 * it seems best to define simple-Query mode as if it used the unnamed
812 * statement and portal; this ensures we recover any storage used by prior
813 * unnamed operations.)
815 drop_unnamed_stmt();
818 * Switch to appropriate context for constructing parsetrees.
820 oldcontext = MemoryContextSwitchTo(MessageContext);
823 * Do basic parsing of the query or queries (this should be safe even if
824 * we are in aborted transaction state!)
826 parsetree_list = pg_parse_query(query_string);
828 /* Log immediately if dictated by log_statement */
829 if (check_log_statement(parsetree_list))
831 ereport(LOG,
832 (errmsg("statement: %s", query_string),
833 errhidestmt(true),
834 errdetail_execute(parsetree_list)));
835 was_logged = true;
839 * Switch back to transaction context to enter the loop.
841 MemoryContextSwitchTo(oldcontext);
844 * We'll tell PortalRun it's a top-level command iff there's exactly one
845 * raw parsetree. If more than one, it's effectively a transaction block
846 * and we want PreventTransactionChain to reject unsafe commands. (Note:
847 * we're assuming that query rewrite cannot add commands that are
848 * significant to PreventTransactionChain.)
850 isTopLevel = (list_length(parsetree_list) == 1);
853 * Run through the raw parsetree(s) and process each one.
855 foreach(parsetree_item, parsetree_list)
857 Node *parsetree = (Node *) lfirst(parsetree_item);
858 bool snapshot_set = false;
859 const char *commandTag;
860 char completionTag[COMPLETION_TAG_BUFSIZE];
861 List *querytree_list,
862 *plantree_list;
863 Portal portal;
864 DestReceiver *receiver;
865 int16 format;
868 * Get the command name for use in status display (it also becomes the
869 * default completion tag, down inside PortalRun). Set ps_status and
870 * do any special start-of-SQL-command processing needed by the
871 * destination.
873 commandTag = CreateCommandTag(parsetree);
875 set_ps_display(commandTag, false);
877 BeginCommand(commandTag, dest);
880 * If we are in an aborted transaction, reject all commands except
881 * COMMIT/ABORT. It is important that this test occur before we try
882 * to do parse analysis, rewrite, or planning, since all those phases
883 * try to do database accesses, which may fail in abort state. (It
884 * might be safe to allow some additional utility commands in this
885 * state, but not many...)
887 if (IsAbortedTransactionBlockState() &&
888 !IsTransactionExitStmt(parsetree))
889 ereport(ERROR,
890 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
891 errmsg("current transaction is aborted, "
892 "commands ignored until end of transaction block")));
894 /* Make sure we are in a transaction command */
895 start_xact_command();
897 /* If we got a cancel signal in parsing or prior command, quit */
898 CHECK_FOR_INTERRUPTS();
901 * Set up a snapshot if parse analysis/planning will need one.
903 if (analyze_requires_snapshot(parsetree))
905 PushActiveSnapshot(GetTransactionSnapshot());
906 snapshot_set = true;
910 * OK to analyze, rewrite, and plan this query.
912 * Switch to appropriate context for constructing querytrees (again,
913 * these must outlive the execution context).
915 oldcontext = MemoryContextSwitchTo(MessageContext);
917 querytree_list = pg_analyze_and_rewrite(parsetree, query_string,
918 NULL, 0);
920 plantree_list = pg_plan_queries(querytree_list, 0, NULL);
922 /* Done with the snapshot used for parsing/planning */
923 if (snapshot_set)
924 PopActiveSnapshot();
926 /* If we got a cancel signal in analysis or planning, quit */
927 CHECK_FOR_INTERRUPTS();
930 * Create unnamed portal to run the query or queries in. If there
931 * already is one, silently drop it.
933 portal = CreatePortal("", true, true);
934 /* Don't display the portal in pg_cursors */
935 portal->visible = false;
938 * We don't have to copy anything into the portal, because everything
939 * we are passing here is in MessageContext, which will outlive the
940 * portal anyway.
942 PortalDefineQuery(portal,
943 NULL,
944 query_string,
945 commandTag,
946 plantree_list,
947 NULL);
950 * Start the portal. No parameters here.
952 PortalStart(portal, NULL, InvalidSnapshot);
955 * Select the appropriate output format: text unless we are doing a
956 * FETCH from a binary cursor. (Pretty grotty to have to do this here
957 * --- but it avoids grottiness in other places. Ah, the joys of
958 * backward compatibility...)
960 format = 0; /* TEXT is default */
961 if (IsA(parsetree, FetchStmt))
963 FetchStmt *stmt = (FetchStmt *) parsetree;
965 if (!stmt->ismove)
967 Portal fportal = GetPortalByName(stmt->portalname);
969 if (PortalIsValid(fportal) &&
970 (fportal->cursorOptions & CURSOR_OPT_BINARY))
971 format = 1; /* BINARY */
974 PortalSetResultFormat(portal, 1, &format);
977 * Now we can create the destination receiver object.
979 receiver = CreateDestReceiver(dest);
980 if (dest == DestRemote)
981 SetRemoteDestReceiverParams(receiver, portal);
984 * Switch back to transaction context for execution.
986 MemoryContextSwitchTo(oldcontext);
989 * Run the portal to completion, and then drop it (and the receiver).
991 (void) PortalRun(portal,
992 FETCH_ALL,
993 isTopLevel,
994 receiver,
995 receiver,
996 completionTag);
998 (*receiver->rDestroy) (receiver);
1000 PortalDrop(portal, false);
1002 if (IsA(parsetree, TransactionStmt))
1005 * If this was a transaction control statement, commit it. We will
1006 * start a new xact command for the next command (if any).
1008 finish_xact_command();
1010 else if (lnext(parsetree_item) == NULL)
1013 * If this is the last parsetree of the query string, close down
1014 * transaction statement before reporting command-complete. This
1015 * is so that any end-of-transaction errors are reported before
1016 * the command-complete message is issued, to avoid confusing
1017 * clients who will expect either a command-complete message or an
1018 * error, not one and then the other. But for compatibility with
1019 * historical Postgres behavior, we do not force a transaction
1020 * boundary between queries appearing in a single query string.
1022 finish_xact_command();
1024 else
1027 * We need a CommandCounterIncrement after every query, except
1028 * those that start or end a transaction block.
1030 CommandCounterIncrement();
1034 * Tell client that we're done with this query. Note we emit exactly
1035 * one EndCommand report for each raw parsetree, thus one for each SQL
1036 * command the client sent, regardless of rewriting. (But a command
1037 * aborted by error will not send an EndCommand report at all.)
1039 EndCommand(completionTag, dest);
1040 } /* end loop over parsetrees */
1043 * Close down transaction statement, if one is open.
1045 finish_xact_command();
1048 * If there were no parsetrees, return EmptyQueryResponse message.
1050 if (!parsetree_list)
1051 NullCommand(dest);
1054 * Emit duration logging if appropriate.
1056 switch (check_log_duration(msec_str, was_logged))
1058 case 1:
1059 ereport(LOG,
1060 (errmsg("duration: %s ms", msec_str),
1061 errhidestmt(true)));
1062 break;
1063 case 2:
1064 ereport(LOG,
1065 (errmsg("duration: %s ms statement: %s",
1066 msec_str, query_string),
1067 errhidestmt(true),
1068 errdetail_execute(parsetree_list)));
1069 break;
1072 if (save_log_statement_stats)
1073 ShowUsage("QUERY STATISTICS");
1075 TRACE_POSTGRESQL_QUERY_DONE(query_string);
1077 debug_query_string = NULL;
1081 * exec_parse_message
1083 * Execute a "Parse" protocol message.
1085 static void
1086 exec_parse_message(const char *query_string, /* string to execute */
1087 const char *stmt_name, /* name for prepared stmt */
1088 Oid *paramTypes, /* parameter types */
1089 int numParams) /* number of parameters */
1091 MemoryContext oldcontext;
1092 List *parsetree_list;
1093 Node *raw_parse_tree;
1094 const char *commandTag;
1095 List *querytree_list,
1096 *stmt_list;
1097 bool is_named;
1098 bool fully_planned;
1099 bool save_log_statement_stats = log_statement_stats;
1100 char msec_str[32];
1103 * Report query to various monitoring facilities.
1105 debug_query_string = query_string;
1107 pgstat_report_activity(query_string);
1109 set_ps_display("PARSE", false);
1111 if (save_log_statement_stats)
1112 ResetUsage();
1114 ereport(DEBUG2,
1115 (errmsg("parse %s: %s",
1116 *stmt_name ? stmt_name : "<unnamed>",
1117 query_string)));
1120 * Start up a transaction command so we can run parse analysis etc. (Note
1121 * that this will normally change current memory context.) Nothing happens
1122 * if we are already in one.
1124 start_xact_command();
1127 * Switch to appropriate context for constructing parsetrees.
1129 * We have two strategies depending on whether the prepared statement is
1130 * named or not. For a named prepared statement, we do parsing in
1131 * MessageContext and copy the finished trees into the prepared
1132 * statement's plancache entry; then the reset of MessageContext releases
1133 * temporary space used by parsing and planning. For an unnamed prepared
1134 * statement, we assume the statement isn't going to hang around long, so
1135 * getting rid of temp space quickly is probably not worth the costs of
1136 * copying parse/plan trees. So in this case, we create the plancache
1137 * entry's context here, and do all the parsing work therein.
1139 is_named = (stmt_name[0] != '\0');
1140 if (is_named)
1142 /* Named prepared statement --- parse in MessageContext */
1143 oldcontext = MemoryContextSwitchTo(MessageContext);
1145 else
1147 /* Unnamed prepared statement --- release any prior unnamed stmt */
1148 drop_unnamed_stmt();
1149 /* Create context for parsing/planning */
1150 unnamed_stmt_context =
1151 AllocSetContextCreate(CacheMemoryContext,
1152 "unnamed prepared statement",
1153 ALLOCSET_DEFAULT_MINSIZE,
1154 ALLOCSET_DEFAULT_INITSIZE,
1155 ALLOCSET_DEFAULT_MAXSIZE);
1156 oldcontext = MemoryContextSwitchTo(unnamed_stmt_context);
1160 * Do basic parsing of the query or queries (this should be safe even if
1161 * we are in aborted transaction state!)
1163 parsetree_list = pg_parse_query(query_string);
1166 * We only allow a single user statement in a prepared statement. This is
1167 * mainly to keep the protocol simple --- otherwise we'd need to worry
1168 * about multiple result tupdescs and things like that.
1170 if (list_length(parsetree_list) > 1)
1171 ereport(ERROR,
1172 (errcode(ERRCODE_SYNTAX_ERROR),
1173 errmsg("cannot insert multiple commands into a prepared statement")));
1175 if (parsetree_list != NIL)
1177 Query *query;
1178 bool snapshot_set = false;
1179 int i;
1181 raw_parse_tree = (Node *) linitial(parsetree_list);
1184 * Get the command name for possible use in status display.
1186 commandTag = CreateCommandTag(raw_parse_tree);
1189 * If we are in an aborted transaction, reject all commands except
1190 * COMMIT/ROLLBACK. It is important that this test occur before we
1191 * try to do parse analysis, rewrite, or planning, since all those
1192 * phases try to do database accesses, which may fail in abort state.
1193 * (It might be safe to allow some additional utility commands in this
1194 * state, but not many...)
1196 if (IsAbortedTransactionBlockState() &&
1197 !IsTransactionExitStmt(raw_parse_tree))
1198 ereport(ERROR,
1199 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1200 errmsg("current transaction is aborted, "
1201 "commands ignored until end of transaction block")));
1204 * Set up a snapshot if parse analysis/planning will need one.
1206 if (analyze_requires_snapshot(raw_parse_tree))
1208 PushActiveSnapshot(GetTransactionSnapshot());
1209 snapshot_set = true;
1213 * OK to analyze, rewrite, and plan this query. Note that the
1214 * originally specified parameter set is not required to be complete,
1215 * so we have to use parse_analyze_varparams().
1217 * XXX must use copyObject here since parse analysis scribbles on its
1218 * input, and we need the unmodified raw parse tree for possible
1219 * replanning later.
1221 if (log_parser_stats)
1222 ResetUsage();
1224 query = parse_analyze_varparams(copyObject(raw_parse_tree),
1225 query_string,
1226 &paramTypes,
1227 &numParams);
1230 * Check all parameter types got determined.
1232 for (i = 0; i < numParams; i++)
1234 Oid ptype = paramTypes[i];
1236 if (ptype == InvalidOid || ptype == UNKNOWNOID)
1237 ereport(ERROR,
1238 (errcode(ERRCODE_INDETERMINATE_DATATYPE),
1239 errmsg("could not determine data type of parameter $%d",
1240 i + 1)));
1243 if (log_parser_stats)
1244 ShowUsage("PARSE ANALYSIS STATISTICS");
1246 querytree_list = pg_rewrite_query(query);
1249 * If this is the unnamed statement and it has parameters, defer query
1250 * planning until Bind. Otherwise do it now.
1252 if (!is_named && numParams > 0)
1254 stmt_list = querytree_list;
1255 fully_planned = false;
1257 else
1259 stmt_list = pg_plan_queries(querytree_list, 0, NULL);
1260 fully_planned = true;
1263 /* Done with the snapshot used for parsing/planning */
1264 if (snapshot_set)
1265 PopActiveSnapshot();
1267 else
1269 /* Empty input string. This is legal. */
1270 raw_parse_tree = NULL;
1271 commandTag = NULL;
1272 stmt_list = NIL;
1273 fully_planned = true;
1276 /* If we got a cancel signal in analysis or planning, quit */
1277 CHECK_FOR_INTERRUPTS();
1280 * Store the query as a prepared statement. See above comments.
1282 if (is_named)
1284 StorePreparedStatement(stmt_name,
1285 raw_parse_tree,
1286 query_string,
1287 commandTag,
1288 paramTypes,
1289 numParams,
1290 0, /* default cursor options */
1291 stmt_list,
1292 false);
1294 else
1297 * paramTypes and query_string need to be copied into
1298 * unnamed_stmt_context. The rest is there already
1300 Oid *newParamTypes;
1302 if (numParams > 0)
1304 newParamTypes = (Oid *) palloc(numParams * sizeof(Oid));
1305 memcpy(newParamTypes, paramTypes, numParams * sizeof(Oid));
1307 else
1308 newParamTypes = NULL;
1310 unnamed_stmt_psrc = FastCreateCachedPlan(raw_parse_tree,
1311 pstrdup(query_string),
1312 commandTag,
1313 newParamTypes,
1314 numParams,
1315 0, /* cursor options */
1316 stmt_list,
1317 fully_planned,
1318 true,
1319 unnamed_stmt_context);
1320 /* context now belongs to the plancache entry */
1321 unnamed_stmt_context = NULL;
1324 MemoryContextSwitchTo(oldcontext);
1327 * We do NOT close the open transaction command here; that only happens
1328 * when the client sends Sync. Instead, do CommandCounterIncrement just
1329 * in case something happened during parse/plan.
1331 CommandCounterIncrement();
1334 * Send ParseComplete.
1336 if (whereToSendOutput == DestRemote)
1337 pq_putemptymessage('1');
1340 * Emit duration logging if appropriate.
1342 switch (check_log_duration(msec_str, false))
1344 case 1:
1345 ereport(LOG,
1346 (errmsg("duration: %s ms", msec_str),
1347 errhidestmt(true)));
1348 break;
1349 case 2:
1350 ereport(LOG,
1351 (errmsg("duration: %s ms parse %s: %s",
1352 msec_str,
1353 *stmt_name ? stmt_name : "<unnamed>",
1354 query_string),
1355 errhidestmt(true)));
1356 break;
1359 if (save_log_statement_stats)
1360 ShowUsage("PARSE MESSAGE STATISTICS");
1362 debug_query_string = NULL;
1366 * exec_bind_message
1368 * Process a "Bind" message to create a portal from a prepared statement
1370 static void
1371 exec_bind_message(StringInfo input_message)
1373 const char *portal_name;
1374 const char *stmt_name;
1375 int numPFormats;
1376 int16 *pformats = NULL;
1377 int numParams;
1378 int numRFormats;
1379 int16 *rformats = NULL;
1380 CachedPlanSource *psrc;
1381 CachedPlan *cplan;
1382 Portal portal;
1383 char *query_string;
1384 char *saved_stmt_name;
1385 ParamListInfo params;
1386 List *plan_list;
1387 MemoryContext oldContext;
1388 bool save_log_statement_stats = log_statement_stats;
1389 bool snapshot_set = false;
1390 char msec_str[32];
1392 /* Get the fixed part of the message */
1393 portal_name = pq_getmsgstring(input_message);
1394 stmt_name = pq_getmsgstring(input_message);
1396 ereport(DEBUG2,
1397 (errmsg("bind %s to %s",
1398 *portal_name ? portal_name : "<unnamed>",
1399 *stmt_name ? stmt_name : "<unnamed>")));
1401 /* Find prepared statement */
1402 if (stmt_name[0] != '\0')
1404 PreparedStatement *pstmt;
1406 pstmt = FetchPreparedStatement(stmt_name, true);
1407 psrc = pstmt->plansource;
1409 else
1411 /* special-case the unnamed statement */
1412 psrc = unnamed_stmt_psrc;
1413 if (!psrc)
1414 ereport(ERROR,
1415 (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
1416 errmsg("unnamed prepared statement does not exist")));
1420 * Report query to various monitoring facilities.
1422 debug_query_string = psrc->query_string;
1424 pgstat_report_activity(psrc->query_string);
1426 set_ps_display("BIND", false);
1428 if (save_log_statement_stats)
1429 ResetUsage();
1432 * Start up a transaction command so we can call functions etc. (Note that
1433 * this will normally change current memory context.) Nothing happens if
1434 * we are already in one.
1436 start_xact_command();
1438 /* Switch back to message context */
1439 MemoryContextSwitchTo(MessageContext);
1441 /* Get the parameter format codes */
1442 numPFormats = pq_getmsgint(input_message, 2);
1443 if (numPFormats > 0)
1445 int i;
1447 pformats = (int16 *) palloc(numPFormats * sizeof(int16));
1448 for (i = 0; i < numPFormats; i++)
1449 pformats[i] = pq_getmsgint(input_message, 2);
1452 /* Get the parameter value count */
1453 numParams = pq_getmsgint(input_message, 2);
1455 if (numPFormats > 1 && numPFormats != numParams)
1456 ereport(ERROR,
1457 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1458 errmsg("bind message has %d parameter formats but %d parameters",
1459 numPFormats, numParams)));
1461 if (numParams != psrc->num_params)
1462 ereport(ERROR,
1463 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1464 errmsg("bind message supplies %d parameters, but prepared statement \"%s\" requires %d",
1465 numParams, stmt_name, psrc->num_params)));
1468 * If we are in aborted transaction state, the only portals we can
1469 * actually run are those containing COMMIT or ROLLBACK commands. We
1470 * disallow binding anything else to avoid problems with infrastructure
1471 * that expects to run inside a valid transaction. We also disallow
1472 * binding any parameters, since we can't risk calling user-defined I/O
1473 * functions.
1475 if (IsAbortedTransactionBlockState() &&
1476 (!IsTransactionExitStmt(psrc->raw_parse_tree) ||
1477 numParams != 0))
1478 ereport(ERROR,
1479 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1480 errmsg("current transaction is aborted, "
1481 "commands ignored until end of transaction block")));
1484 * Create the portal. Allow silent replacement of an existing portal only
1485 * if the unnamed portal is specified.
1487 if (portal_name[0] == '\0')
1488 portal = CreatePortal(portal_name, true, true);
1489 else
1490 portal = CreatePortal(portal_name, false, false);
1493 * Prepare to copy stuff into the portal's memory context. We do all this
1494 * copying first, because it could possibly fail (out-of-memory) and we
1495 * don't want a failure to occur between RevalidateCachedPlan and
1496 * PortalDefineQuery; that would result in leaking our plancache refcount.
1498 oldContext = MemoryContextSwitchTo(PortalGetHeapMemory(portal));
1500 /* Copy the plan's query string into the portal */
1501 query_string = pstrdup(psrc->query_string);
1503 /* Likewise make a copy of the statement name, unless it's unnamed */
1504 if (stmt_name[0])
1505 saved_stmt_name = pstrdup(stmt_name);
1506 else
1507 saved_stmt_name = NULL;
1510 * Set a snapshot if we have parameters to fetch (since the input
1511 * functions might need it) or the query isn't a utility command (and
1512 * hence could require redoing parse analysis and planning).
1514 if (numParams > 0 || analyze_requires_snapshot(psrc->raw_parse_tree))
1516 PushActiveSnapshot(GetTransactionSnapshot());
1517 snapshot_set = true;
1521 * Fetch parameters, if any, and store in the portal's memory context.
1523 if (numParams > 0)
1525 int paramno;
1527 /* sizeof(ParamListInfoData) includes the first array element */
1528 params = (ParamListInfo) palloc(sizeof(ParamListInfoData) +
1529 (numParams - 1) *sizeof(ParamExternData));
1530 params->numParams = numParams;
1532 for (paramno = 0; paramno < numParams; paramno++)
1534 Oid ptype = psrc->param_types[paramno];
1535 int32 plength;
1536 Datum pval;
1537 bool isNull;
1538 StringInfoData pbuf;
1539 char csave;
1540 int16 pformat;
1542 plength = pq_getmsgint(input_message, 4);
1543 isNull = (plength == -1);
1545 if (!isNull)
1547 const char *pvalue = pq_getmsgbytes(input_message, plength);
1550 * Rather than copying data around, we just set up a phony
1551 * StringInfo pointing to the correct portion of the message
1552 * buffer. We assume we can scribble on the message buffer so
1553 * as to maintain the convention that StringInfos have a
1554 * trailing null. This is grotty but is a big win when
1555 * dealing with very large parameter strings.
1557 pbuf.data = (char *) pvalue;
1558 pbuf.maxlen = plength + 1;
1559 pbuf.len = plength;
1560 pbuf.cursor = 0;
1562 csave = pbuf.data[plength];
1563 pbuf.data[plength] = '\0';
1565 else
1567 pbuf.data = NULL; /* keep compiler quiet */
1568 csave = 0;
1571 if (numPFormats > 1)
1572 pformat = pformats[paramno];
1573 else if (numPFormats > 0)
1574 pformat = pformats[0];
1575 else
1576 pformat = 0; /* default = text */
1578 if (pformat == 0) /* text mode */
1580 Oid typinput;
1581 Oid typioparam;
1582 char *pstring;
1584 getTypeInputInfo(ptype, &typinput, &typioparam);
1587 * We have to do encoding conversion before calling the
1588 * typinput routine.
1590 if (isNull)
1591 pstring = NULL;
1592 else
1593 pstring = pg_client_to_server(pbuf.data, plength);
1595 pval = OidInputFunctionCall(typinput, pstring, typioparam, -1);
1597 /* Free result of encoding conversion, if any */
1598 if (pstring && pstring != pbuf.data)
1599 pfree(pstring);
1601 else if (pformat == 1) /* binary mode */
1603 Oid typreceive;
1604 Oid typioparam;
1605 StringInfo bufptr;
1608 * Call the parameter type's binary input converter
1610 getTypeBinaryInputInfo(ptype, &typreceive, &typioparam);
1612 if (isNull)
1613 bufptr = NULL;
1614 else
1615 bufptr = &pbuf;
1617 pval = OidReceiveFunctionCall(typreceive, bufptr, typioparam, -1);
1619 /* Trouble if it didn't eat the whole buffer */
1620 if (!isNull && pbuf.cursor != pbuf.len)
1621 ereport(ERROR,
1622 (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
1623 errmsg("incorrect binary data format in bind parameter %d",
1624 paramno + 1)));
1626 else
1628 ereport(ERROR,
1629 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1630 errmsg("unsupported format code: %d",
1631 pformat)));
1632 pval = 0; /* keep compiler quiet */
1635 /* Restore message buffer contents */
1636 if (!isNull)
1637 pbuf.data[plength] = csave;
1639 params->params[paramno].value = pval;
1640 params->params[paramno].isnull = isNull;
1643 * We mark the params as CONST. This has no effect if we already
1644 * did planning, but if we didn't, it licenses the planner to
1645 * substitute the parameters directly into the one-shot plan we
1646 * will generate below.
1648 params->params[paramno].pflags = PARAM_FLAG_CONST;
1649 params->params[paramno].ptype = ptype;
1652 else
1653 params = NULL;
1655 /* Done storing stuff in portal's context */
1656 MemoryContextSwitchTo(oldContext);
1658 /* Get the result format codes */
1659 numRFormats = pq_getmsgint(input_message, 2);
1660 if (numRFormats > 0)
1662 int i;
1664 rformats = (int16 *) palloc(numRFormats * sizeof(int16));
1665 for (i = 0; i < numRFormats; i++)
1666 rformats[i] = pq_getmsgint(input_message, 2);
1669 pq_getmsgend(input_message);
1671 if (psrc->fully_planned)
1674 * Revalidate the cached plan; this may result in replanning. Any
1675 * cruft will be generated in MessageContext. The plan refcount will
1676 * be assigned to the Portal, so it will be released at portal
1677 * destruction.
1679 cplan = RevalidateCachedPlan(psrc, false);
1680 plan_list = cplan->stmt_list;
1682 else
1684 List *query_list;
1687 * Revalidate the cached plan; this may result in redoing parse
1688 * analysis and rewriting (but not planning). Any cruft will be
1689 * generated in MessageContext. The plan refcount is assigned to
1690 * CurrentResourceOwner.
1692 cplan = RevalidateCachedPlan(psrc, true);
1695 * We didn't plan the query before, so do it now. This allows the
1696 * planner to make use of the concrete parameter values we now have.
1697 * Because we use PARAM_FLAG_CONST, the plan is good only for this set
1698 * of param values, and so we generate the plan in the portal's own
1699 * memory context where it will be thrown away after use. As in
1700 * exec_parse_message, we make no attempt to recover planner temporary
1701 * memory until the end of the operation.
1703 * XXX because the planner has a bad habit of scribbling on its input,
1704 * we have to make a copy of the parse trees. FIXME someday.
1706 oldContext = MemoryContextSwitchTo(PortalGetHeapMemory(portal));
1707 query_list = copyObject(cplan->stmt_list);
1708 plan_list = pg_plan_queries(query_list, 0, params);
1709 MemoryContextSwitchTo(oldContext);
1711 /* We no longer need the cached plan refcount ... */
1712 ReleaseCachedPlan(cplan, true);
1713 /* ... and we don't want the portal to depend on it, either */
1714 cplan = NULL;
1718 * Now we can define the portal.
1720 * DO NOT put any code that could possibly throw an error between the
1721 * above "RevalidateCachedPlan(psrc, false)" call and here.
1723 PortalDefineQuery(portal,
1724 saved_stmt_name,
1725 query_string,
1726 psrc->commandTag,
1727 plan_list,
1728 cplan);
1730 /* Done with the snapshot used for parameter I/O and parsing/planning */
1731 if (snapshot_set)
1732 PopActiveSnapshot();
1735 * And we're ready to start portal execution.
1737 PortalStart(portal, params, InvalidSnapshot);
1740 * Apply the result format requests to the portal.
1742 PortalSetResultFormat(portal, numRFormats, rformats);
1745 * Send BindComplete.
1747 if (whereToSendOutput == DestRemote)
1748 pq_putemptymessage('2');
1751 * Emit duration logging if appropriate.
1753 switch (check_log_duration(msec_str, false))
1755 case 1:
1756 ereport(LOG,
1757 (errmsg("duration: %s ms", msec_str),
1758 errhidestmt(true)));
1759 break;
1760 case 2:
1761 ereport(LOG,
1762 (errmsg("duration: %s ms bind %s%s%s: %s",
1763 msec_str,
1764 *stmt_name ? stmt_name : "<unnamed>",
1765 *portal_name ? "/" : "",
1766 *portal_name ? portal_name : "",
1767 psrc->query_string),
1768 errhidestmt(true),
1769 errdetail_params(params)));
1770 break;
1773 if (save_log_statement_stats)
1774 ShowUsage("BIND MESSAGE STATISTICS");
1776 debug_query_string = NULL;
1780 * exec_execute_message
1782 * Process an "Execute" message for a portal
1784 static void
1785 exec_execute_message(const char *portal_name, long max_rows)
1787 CommandDest dest;
1788 DestReceiver *receiver;
1789 Portal portal;
1790 bool completed;
1791 char completionTag[COMPLETION_TAG_BUFSIZE];
1792 const char *sourceText;
1793 const char *prepStmtName;
1794 ParamListInfo portalParams;
1795 bool save_log_statement_stats = log_statement_stats;
1796 bool is_xact_command;
1797 bool execute_is_fetch;
1798 bool was_logged = false;
1799 char msec_str[32];
1801 /* Adjust destination to tell printtup.c what to do */
1802 dest = whereToSendOutput;
1803 if (dest == DestRemote)
1804 dest = DestRemoteExecute;
1806 portal = GetPortalByName(portal_name);
1807 if (!PortalIsValid(portal))
1808 ereport(ERROR,
1809 (errcode(ERRCODE_UNDEFINED_CURSOR),
1810 errmsg("portal \"%s\" does not exist", portal_name)));
1813 * If the original query was a null string, just return
1814 * EmptyQueryResponse.
1816 if (portal->commandTag == NULL)
1818 Assert(portal->stmts == NIL);
1819 NullCommand(dest);
1820 return;
1823 /* Does the portal contain a transaction command? */
1824 is_xact_command = IsTransactionStmtList(portal->stmts);
1827 * We must copy the sourceText and prepStmtName into MessageContext in
1828 * case the portal is destroyed during finish_xact_command. Can avoid the
1829 * copy if it's not an xact command, though.
1831 if (is_xact_command)
1833 sourceText = pstrdup(portal->sourceText);
1834 if (portal->prepStmtName)
1835 prepStmtName = pstrdup(portal->prepStmtName);
1836 else
1837 prepStmtName = "<unnamed>";
1840 * An xact command shouldn't have any parameters, which is a good
1841 * thing because they wouldn't be around after finish_xact_command.
1843 portalParams = NULL;
1845 else
1847 sourceText = portal->sourceText;
1848 if (portal->prepStmtName)
1849 prepStmtName = portal->prepStmtName;
1850 else
1851 prepStmtName = "<unnamed>";
1852 portalParams = portal->portalParams;
1856 * Report query to various monitoring facilities.
1858 debug_query_string = sourceText;
1860 pgstat_report_activity(sourceText);
1862 set_ps_display(portal->commandTag, false);
1864 if (save_log_statement_stats)
1865 ResetUsage();
1867 BeginCommand(portal->commandTag, dest);
1870 * Create dest receiver in MessageContext (we don't want it in transaction
1871 * context, because that may get deleted if portal contains VACUUM).
1873 receiver = CreateDestReceiver(dest);
1874 if (dest == DestRemoteExecute)
1875 SetRemoteDestReceiverParams(receiver, portal);
1878 * Ensure we are in a transaction command (this should normally be the
1879 * case already due to prior BIND).
1881 start_xact_command();
1884 * If we re-issue an Execute protocol request against an existing portal,
1885 * then we are only fetching more rows rather than completely re-executing
1886 * the query from the start. atStart is never reset for a v3 portal, so we
1887 * are safe to use this check.
1889 execute_is_fetch = !portal->atStart;
1891 /* Log immediately if dictated by log_statement */
1892 if (check_log_statement(portal->stmts))
1894 ereport(LOG,
1895 (errmsg("%s %s%s%s: %s",
1896 execute_is_fetch ?
1897 _("execute fetch from") :
1898 _("execute"),
1899 prepStmtName,
1900 *portal_name ? "/" : "",
1901 *portal_name ? portal_name : "",
1902 sourceText),
1903 errhidestmt(true),
1904 errdetail_params(portalParams)));
1905 was_logged = true;
1909 * If we are in aborted transaction state, the only portals we can
1910 * actually run are those containing COMMIT or ROLLBACK commands.
1912 if (IsAbortedTransactionBlockState() &&
1913 !IsTransactionExitStmtList(portal->stmts))
1914 ereport(ERROR,
1915 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1916 errmsg("current transaction is aborted, "
1917 "commands ignored until end of transaction block")));
1919 /* Check for cancel signal before we start execution */
1920 CHECK_FOR_INTERRUPTS();
1923 * Okay to run the portal.
1925 if (max_rows <= 0)
1926 max_rows = FETCH_ALL;
1928 completed = PortalRun(portal,
1929 max_rows,
1930 true, /* always top level */
1931 receiver,
1932 receiver,
1933 completionTag);
1935 (*receiver->rDestroy) (receiver);
1937 if (completed)
1939 if (is_xact_command)
1942 * If this was a transaction control statement, commit it. We
1943 * will start a new xact command for the next command (if any).
1945 finish_xact_command();
1947 else
1950 * We need a CommandCounterIncrement after every query, except
1951 * those that start or end a transaction block.
1953 CommandCounterIncrement();
1956 /* Send appropriate CommandComplete to client */
1957 EndCommand(completionTag, dest);
1959 else
1961 /* Portal run not complete, so send PortalSuspended */
1962 if (whereToSendOutput == DestRemote)
1963 pq_putemptymessage('s');
1967 * Emit duration logging if appropriate.
1969 switch (check_log_duration(msec_str, was_logged))
1971 case 1:
1972 ereport(LOG,
1973 (errmsg("duration: %s ms", msec_str),
1974 errhidestmt(true)));
1975 break;
1976 case 2:
1977 ereport(LOG,
1978 (errmsg("duration: %s ms %s %s%s%s: %s",
1979 msec_str,
1980 execute_is_fetch ?
1981 _("execute fetch from") :
1982 _("execute"),
1983 prepStmtName,
1984 *portal_name ? "/" : "",
1985 *portal_name ? portal_name : "",
1986 sourceText),
1987 errhidestmt(true),
1988 errdetail_params(portalParams)));
1989 break;
1992 if (save_log_statement_stats)
1993 ShowUsage("EXECUTE MESSAGE STATISTICS");
1995 debug_query_string = NULL;
1999 * check_log_statement
2000 * Determine whether command should be logged because of log_statement
2002 * parsetree_list can be either raw grammar output or a list of planned
2003 * statements
2005 static bool
2006 check_log_statement(List *stmt_list)
2008 ListCell *stmt_item;
2010 if (log_statement == LOGSTMT_NONE)
2011 return false;
2012 if (log_statement == LOGSTMT_ALL)
2013 return true;
2015 /* Else we have to inspect the statement(s) to see whether to log */
2016 foreach(stmt_item, stmt_list)
2018 Node *stmt = (Node *) lfirst(stmt_item);
2020 if (GetCommandLogLevel(stmt) <= log_statement)
2021 return true;
2024 return false;
2028 * check_log_duration
2029 * Determine whether current command's duration should be logged
2031 * Returns:
2032 * 0 if no logging is needed
2033 * 1 if just the duration should be logged
2034 * 2 if duration and query details should be logged
2036 * If logging is needed, the duration in msec is formatted into msec_str[],
2037 * which must be a 32-byte buffer.
2039 * was_logged should be TRUE if caller already logged query details (this
2040 * essentially prevents 2 from being returned).
2043 check_log_duration(char *msec_str, bool was_logged)
2045 if (log_duration || log_min_duration_statement >= 0)
2047 long secs;
2048 int usecs;
2049 int msecs;
2050 bool exceeded;
2052 TimestampDifference(GetCurrentStatementStartTimestamp(),
2053 GetCurrentTimestamp(),
2054 &secs, &usecs);
2055 msecs = usecs / 1000;
2058 * This odd-looking test for log_min_duration_statement being exceeded
2059 * is designed to avoid integer overflow with very long durations:
2060 * don't compute secs * 1000 until we've verified it will fit in int.
2062 exceeded = (log_min_duration_statement == 0 ||
2063 (log_min_duration_statement > 0 &&
2064 (secs > log_min_duration_statement / 1000 ||
2065 secs * 1000 + msecs >= log_min_duration_statement)));
2067 if (exceeded || log_duration)
2069 snprintf(msec_str, 32, "%ld.%03d",
2070 secs * 1000 + msecs, usecs % 1000);
2071 if (exceeded && !was_logged)
2072 return 2;
2073 else
2074 return 1;
2078 return 0;
2082 * errdetail_execute
2084 * Add an errdetail() line showing the query referenced by an EXECUTE, if any.
2085 * The argument is the raw parsetree list.
2087 static int
2088 errdetail_execute(List *raw_parsetree_list)
2090 ListCell *parsetree_item;
2092 foreach(parsetree_item, raw_parsetree_list)
2094 Node *parsetree = (Node *) lfirst(parsetree_item);
2096 if (IsA(parsetree, ExecuteStmt))
2098 ExecuteStmt *stmt = (ExecuteStmt *) parsetree;
2099 PreparedStatement *pstmt;
2101 pstmt = FetchPreparedStatement(stmt->name, false);
2102 if (pstmt)
2104 errdetail("prepare: %s", pstmt->plansource->query_string);
2105 return 0;
2110 return 0;
2114 * errdetail_params
2116 * Add an errdetail() line showing bind-parameter data, if available.
2118 static int
2119 errdetail_params(ParamListInfo params)
2121 /* We mustn't call user-defined I/O functions when in an aborted xact */
2122 if (params && params->numParams > 0 && !IsAbortedTransactionBlockState())
2124 StringInfoData param_str;
2125 MemoryContext oldcontext;
2126 int paramno;
2128 /* Make sure any trash is generated in MessageContext */
2129 oldcontext = MemoryContextSwitchTo(MessageContext);
2131 initStringInfo(&param_str);
2133 for (paramno = 0; paramno < params->numParams; paramno++)
2135 ParamExternData *prm = &params->params[paramno];
2136 Oid typoutput;
2137 bool typisvarlena;
2138 char *pstring;
2139 char *p;
2141 appendStringInfo(&param_str, "%s$%d = ",
2142 paramno > 0 ? ", " : "",
2143 paramno + 1);
2145 if (prm->isnull || !OidIsValid(prm->ptype))
2147 appendStringInfoString(&param_str, "NULL");
2148 continue;
2151 getTypeOutputInfo(prm->ptype, &typoutput, &typisvarlena);
2153 pstring = OidOutputFunctionCall(typoutput, prm->value);
2155 appendStringInfoCharMacro(&param_str, '\'');
2156 for (p = pstring; *p; p++)
2158 if (*p == '\'') /* double single quotes */
2159 appendStringInfoCharMacro(&param_str, *p);
2160 appendStringInfoCharMacro(&param_str, *p);
2162 appendStringInfoCharMacro(&param_str, '\'');
2164 pfree(pstring);
2167 errdetail("parameters: %s", param_str.data);
2169 pfree(param_str.data);
2171 MemoryContextSwitchTo(oldcontext);
2174 return 0;
2178 * exec_describe_statement_message
2180 * Process a "Describe" message for a prepared statement
2182 static void
2183 exec_describe_statement_message(const char *stmt_name)
2185 CachedPlanSource *psrc;
2186 StringInfoData buf;
2187 int i;
2190 * Start up a transaction command. (Note that this will normally change
2191 * current memory context.) Nothing happens if we are already in one.
2193 start_xact_command();
2195 /* Switch back to message context */
2196 MemoryContextSwitchTo(MessageContext);
2198 /* Find prepared statement */
2199 if (stmt_name[0] != '\0')
2201 PreparedStatement *pstmt;
2203 pstmt = FetchPreparedStatement(stmt_name, true);
2204 psrc = pstmt->plansource;
2206 else
2208 /* special-case the unnamed statement */
2209 psrc = unnamed_stmt_psrc;
2210 if (!psrc)
2211 ereport(ERROR,
2212 (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
2213 errmsg("unnamed prepared statement does not exist")));
2216 /* Prepared statements shouldn't have changeable result descs */
2217 Assert(psrc->fixed_result);
2220 * If we are in aborted transaction state, we can't run
2221 * SendRowDescriptionMessage(), because that needs catalog accesses. (We
2222 * can't do RevalidateCachedPlan, either, but that's a lesser problem.)
2223 * Hence, refuse to Describe statements that return data. (We shouldn't
2224 * just refuse all Describes, since that might break the ability of some
2225 * clients to issue COMMIT or ROLLBACK commands, if they use code that
2226 * blindly Describes whatever it does.) We can Describe parameters
2227 * without doing anything dangerous, so we don't restrict that.
2229 if (IsAbortedTransactionBlockState() &&
2230 psrc->resultDesc)
2231 ereport(ERROR,
2232 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2233 errmsg("current transaction is aborted, "
2234 "commands ignored until end of transaction block")));
2236 if (whereToSendOutput != DestRemote)
2237 return; /* can't actually do anything... */
2240 * First describe the parameters...
2242 pq_beginmessage(&buf, 't'); /* parameter description message type */
2243 pq_sendint(&buf, psrc->num_params, 2);
2245 for (i = 0; i < psrc->num_params; i++)
2247 Oid ptype = psrc->param_types[i];
2249 pq_sendint(&buf, (int) ptype, 4);
2251 pq_endmessage(&buf);
2254 * Next send RowDescription or NoData to describe the result...
2256 if (psrc->resultDesc)
2258 CachedPlan *cplan;
2259 List *tlist;
2261 /* Make sure the plan is up to date */
2262 cplan = RevalidateCachedPlan(psrc, true);
2264 /* Get the primary statement and find out what it returns */
2265 tlist = FetchStatementTargetList(PortalListGetPrimaryStmt(cplan->stmt_list));
2267 SendRowDescriptionMessage(psrc->resultDesc, tlist, NULL);
2269 ReleaseCachedPlan(cplan, true);
2271 else
2272 pq_putemptymessage('n'); /* NoData */
2277 * exec_describe_portal_message
2279 * Process a "Describe" message for a portal
2281 static void
2282 exec_describe_portal_message(const char *portal_name)
2284 Portal portal;
2287 * Start up a transaction command. (Note that this will normally change
2288 * current memory context.) Nothing happens if we are already in one.
2290 start_xact_command();
2292 /* Switch back to message context */
2293 MemoryContextSwitchTo(MessageContext);
2295 portal = GetPortalByName(portal_name);
2296 if (!PortalIsValid(portal))
2297 ereport(ERROR,
2298 (errcode(ERRCODE_UNDEFINED_CURSOR),
2299 errmsg("portal \"%s\" does not exist", portal_name)));
2302 * If we are in aborted transaction state, we can't run
2303 * SendRowDescriptionMessage(), because that needs catalog accesses.
2304 * Hence, refuse to Describe portals that return data. (We shouldn't just
2305 * refuse all Describes, since that might break the ability of some
2306 * clients to issue COMMIT or ROLLBACK commands, if they use code that
2307 * blindly Describes whatever it does.)
2309 if (IsAbortedTransactionBlockState() &&
2310 portal->tupDesc)
2311 ereport(ERROR,
2312 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2313 errmsg("current transaction is aborted, "
2314 "commands ignored until end of transaction block")));
2316 if (whereToSendOutput != DestRemote)
2317 return; /* can't actually do anything... */
2319 if (portal->tupDesc)
2320 SendRowDescriptionMessage(portal->tupDesc,
2321 FetchPortalTargetList(portal),
2322 portal->formats);
2323 else
2324 pq_putemptymessage('n'); /* NoData */
2329 * Convenience routines for starting/committing a single command.
2331 static void
2332 start_xact_command(void)
2334 if (!xact_started)
2336 ereport(DEBUG3,
2337 (errmsg_internal("StartTransactionCommand")));
2338 StartTransactionCommand();
2340 /* Set statement timeout running, if any */
2341 /* NB: this mustn't be enabled until we are within an xact */
2342 if (StatementTimeout > 0)
2343 enable_sig_alarm(StatementTimeout, true);
2344 else
2345 cancel_from_timeout = false;
2347 xact_started = true;
2351 static void
2352 finish_xact_command(void)
2354 if (xact_started)
2356 /* Cancel any active statement timeout before committing */
2357 disable_sig_alarm(true);
2359 /* Now commit the command */
2360 ereport(DEBUG3,
2361 (errmsg_internal("CommitTransactionCommand")));
2363 CommitTransactionCommand();
2365 #ifdef MEMORY_CONTEXT_CHECKING
2366 /* Check all memory contexts that weren't freed during commit */
2367 /* (those that were, were checked before being deleted) */
2368 MemoryContextCheck(TopMemoryContext);
2369 #endif
2371 #ifdef SHOW_MEMORY_STATS
2372 /* Print mem stats after each commit for leak tracking */
2373 MemoryContextStats(TopMemoryContext);
2374 #endif
2376 xact_started = false;
2382 * Convenience routines for checking whether a statement is one of the
2383 * ones that we allow in transaction-aborted state.
2386 /* Test a bare parsetree */
2387 static bool
2388 IsTransactionExitStmt(Node *parsetree)
2390 if (parsetree && IsA(parsetree, TransactionStmt))
2392 TransactionStmt *stmt = (TransactionStmt *) parsetree;
2394 if (stmt->kind == TRANS_STMT_COMMIT ||
2395 stmt->kind == TRANS_STMT_PREPARE ||
2396 stmt->kind == TRANS_STMT_ROLLBACK ||
2397 stmt->kind == TRANS_STMT_ROLLBACK_TO)
2398 return true;
2400 return false;
2403 /* Test a list that might contain Query nodes or bare parsetrees */
2404 static bool
2405 IsTransactionExitStmtList(List *parseTrees)
2407 if (list_length(parseTrees) == 1)
2409 Node *stmt = (Node *) linitial(parseTrees);
2411 if (IsA(stmt, Query))
2413 Query *query = (Query *) stmt;
2415 if (query->commandType == CMD_UTILITY &&
2416 IsTransactionExitStmt(query->utilityStmt))
2417 return true;
2419 else if (IsTransactionExitStmt(stmt))
2420 return true;
2422 return false;
2425 /* Test a list that might contain Query nodes or bare parsetrees */
2426 static bool
2427 IsTransactionStmtList(List *parseTrees)
2429 if (list_length(parseTrees) == 1)
2431 Node *stmt = (Node *) linitial(parseTrees);
2433 if (IsA(stmt, Query))
2435 Query *query = (Query *) stmt;
2437 if (query->commandType == CMD_UTILITY &&
2438 IsA(query->utilityStmt, TransactionStmt))
2439 return true;
2441 else if (IsA(stmt, TransactionStmt))
2442 return true;
2444 return false;
2447 /* Release any existing unnamed prepared statement */
2448 static void
2449 drop_unnamed_stmt(void)
2451 /* Release any completed unnamed statement */
2452 if (unnamed_stmt_psrc)
2453 DropCachedPlan(unnamed_stmt_psrc);
2454 unnamed_stmt_psrc = NULL;
2457 * If we failed while trying to build a prior unnamed statement, we may
2458 * have a memory context that wasn't assigned to a completed plancache
2459 * entry. If so, drop it to avoid a permanent memory leak.
2461 if (unnamed_stmt_context)
2462 MemoryContextDelete(unnamed_stmt_context);
2463 unnamed_stmt_context = NULL;
2467 /* --------------------------------
2468 * signal handler routines used in PostgresMain()
2469 * --------------------------------
2473 * quickdie() occurs when signalled SIGQUIT by the postmaster.
2475 * Some backend has bought the farm,
2476 * so we need to stop what we're doing and exit.
2478 void
2479 quickdie(SIGNAL_ARGS)
2481 PG_SETMASK(&BlockSig);
2484 * Ideally this should be ereport(FATAL), but then we'd not get control
2485 * back...
2487 ereport(WARNING,
2488 (errcode(ERRCODE_CRASH_SHUTDOWN),
2489 errmsg("terminating connection because of crash of another server process"),
2490 errdetail("The postmaster has commanded this server process to roll back"
2491 " the current transaction and exit, because another"
2492 " server process exited abnormally and possibly corrupted"
2493 " shared memory."),
2494 errhint("In a moment you should be able to reconnect to the"
2495 " database and repeat your command.")));
2498 * We DO NOT want to run proc_exit() callbacks -- we're here because
2499 * shared memory may be corrupted, so we don't want to try to clean up our
2500 * transaction. Just nail the windows shut and get out of town. Now that
2501 * there's an atexit callback to prevent third-party code from breaking
2502 * things by calling exit() directly, we have to reset the callbacks
2503 * explicitly to make this work as intended.
2505 on_exit_reset();
2508 * Note we do exit(2) not exit(0). This is to force the postmaster into a
2509 * system reset cycle if some idiot DBA sends a manual SIGQUIT to a random
2510 * backend. This is necessary precisely because we don't clean up our
2511 * shared memory state. (The "dead man switch" mechanism in pmsignal.c
2512 * should ensure the postmaster sees this as a crash, too, but no harm in
2513 * being doubly sure.)
2515 exit(2);
2519 * Shutdown signal from postmaster: abort transaction and exit
2520 * at soonest convenient time
2522 void
2523 die(SIGNAL_ARGS)
2525 int save_errno = errno;
2527 /* Don't joggle the elbow of proc_exit */
2528 if (!proc_exit_inprogress)
2530 InterruptPending = true;
2531 ProcDiePending = true;
2534 * If it's safe to interrupt, and we're waiting for input or a lock,
2535 * service the interrupt immediately
2537 if (ImmediateInterruptOK && InterruptHoldoffCount == 0 &&
2538 CritSectionCount == 0)
2540 /* bump holdoff count to make ProcessInterrupts() a no-op */
2541 /* until we are done getting ready for it */
2542 InterruptHoldoffCount++;
2543 LockWaitCancel(); /* prevent CheckDeadLock from running */
2544 DisableNotifyInterrupt();
2545 DisableCatchupInterrupt();
2546 InterruptHoldoffCount--;
2547 ProcessInterrupts();
2551 errno = save_errno;
2555 * Timeout or shutdown signal from postmaster during client authentication.
2556 * Simply exit(1).
2558 * XXX: possible future improvement: try to send a message indicating
2559 * why we are disconnecting. Problem is to be sure we don't block while
2560 * doing so, nor mess up the authentication message exchange.
2562 void
2563 authdie(SIGNAL_ARGS)
2565 proc_exit(1);
2569 * Query-cancel signal from postmaster: abort current transaction
2570 * at soonest convenient time
2572 void
2573 StatementCancelHandler(SIGNAL_ARGS)
2575 int save_errno = errno;
2578 * Don't joggle the elbow of proc_exit
2580 if (!proc_exit_inprogress)
2582 InterruptPending = true;
2583 QueryCancelPending = true;
2586 * If it's safe to interrupt, and we're waiting for a lock, service
2587 * the interrupt immediately. No point in interrupting if we're
2588 * waiting for input, however.
2590 if (ImmediateInterruptOK && InterruptHoldoffCount == 0 &&
2591 CritSectionCount == 0 && !DoingCommandRead)
2593 /* bump holdoff count to make ProcessInterrupts() a no-op */
2594 /* until we are done getting ready for it */
2595 InterruptHoldoffCount++;
2596 LockWaitCancel(); /* prevent CheckDeadLock from running */
2597 DisableNotifyInterrupt();
2598 DisableCatchupInterrupt();
2599 InterruptHoldoffCount--;
2600 ProcessInterrupts();
2604 errno = save_errno;
2607 /* signal handler for floating point exception */
2608 void
2609 FloatExceptionHandler(SIGNAL_ARGS)
2611 ereport(ERROR,
2612 (errcode(ERRCODE_FLOATING_POINT_EXCEPTION),
2613 errmsg("floating-point exception"),
2614 errdetail("An invalid floating-point operation was signaled. "
2615 "This probably means an out-of-range result or an "
2616 "invalid operation, such as division by zero.")));
2619 /* SIGHUP: set flag to re-read config file at next convenient time */
2620 static void
2621 SigHupHandler(SIGNAL_ARGS)
2623 got_SIGHUP = true;
2628 * ProcessInterrupts: out-of-line portion of CHECK_FOR_INTERRUPTS() macro
2630 * If an interrupt condition is pending, and it's safe to service it,
2631 * then clear the flag and accept the interrupt. Called only when
2632 * InterruptPending is true.
2634 void
2635 ProcessInterrupts(void)
2637 /* OK to accept interrupt now? */
2638 if (InterruptHoldoffCount != 0 || CritSectionCount != 0)
2639 return;
2640 InterruptPending = false;
2641 if (ProcDiePending)
2643 ProcDiePending = false;
2644 QueryCancelPending = false; /* ProcDie trumps QueryCancel */
2645 ImmediateInterruptOK = false; /* not idle anymore */
2646 DisableNotifyInterrupt();
2647 DisableCatchupInterrupt();
2648 if (IsAutoVacuumWorkerProcess())
2649 ereport(FATAL,
2650 (errcode(ERRCODE_ADMIN_SHUTDOWN),
2651 errmsg("terminating autovacuum process due to administrator command")));
2652 else
2653 ereport(FATAL,
2654 (errcode(ERRCODE_ADMIN_SHUTDOWN),
2655 errmsg("terminating connection due to administrator command")));
2657 if (QueryCancelPending)
2659 QueryCancelPending = false;
2660 ImmediateInterruptOK = false; /* not idle anymore */
2661 DisableNotifyInterrupt();
2662 DisableCatchupInterrupt();
2663 if (cancel_from_timeout)
2664 ereport(ERROR,
2665 (errcode(ERRCODE_QUERY_CANCELED),
2666 errmsg("canceling statement due to statement timeout")));
2667 else if (IsAutoVacuumWorkerProcess())
2668 ereport(ERROR,
2669 (errcode(ERRCODE_QUERY_CANCELED),
2670 errmsg("canceling autovacuum task")));
2671 else
2672 ereport(ERROR,
2673 (errcode(ERRCODE_QUERY_CANCELED),
2674 errmsg("canceling statement due to user request")));
2676 /* If we get here, do nothing (probably, QueryCancelPending was reset) */
2681 * check_stack_depth: check for excessively deep recursion
2683 * This should be called someplace in any recursive routine that might possibly
2684 * recurse deep enough to overflow the stack. Most Unixen treat stack
2685 * overflow as an unrecoverable SIGSEGV, so we want to error out ourselves
2686 * before hitting the hardware limit.
2688 void
2689 check_stack_depth(void)
2691 char stack_top_loc;
2692 long stack_depth;
2695 * Compute distance from PostgresMain's local variables to my own
2697 stack_depth = (long) (stack_base_ptr - &stack_top_loc);
2700 * Take abs value, since stacks grow up on some machines, down on others
2702 if (stack_depth < 0)
2703 stack_depth = -stack_depth;
2706 * Trouble?
2708 * The test on stack_base_ptr prevents us from erroring out if called
2709 * during process setup or in a non-backend process. Logically it should
2710 * be done first, but putting it here avoids wasting cycles during normal
2711 * cases.
2713 if (stack_depth > max_stack_depth_bytes &&
2714 stack_base_ptr != NULL)
2716 ereport(ERROR,
2717 (errcode(ERRCODE_STATEMENT_TOO_COMPLEX),
2718 errmsg("stack depth limit exceeded"),
2719 errhint("Increase the configuration parameter \"max_stack_depth\", "
2720 "after ensuring the platform's stack depth limit is adequate.")));
2724 /* GUC assign hook for max_stack_depth */
2725 bool
2726 assign_max_stack_depth(int newval, bool doit, GucSource source)
2728 long newval_bytes = newval * 1024L;
2729 long stack_rlimit = get_stack_depth_rlimit();
2731 if (stack_rlimit > 0 && newval_bytes > stack_rlimit - STACK_DEPTH_SLOP)
2733 ereport(GUC_complaint_elevel(source),
2734 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2735 errmsg("\"max_stack_depth\" must not exceed %ldkB",
2736 (stack_rlimit - STACK_DEPTH_SLOP) / 1024L),
2737 errhint("Increase the platform's stack depth limit via \"ulimit -s\" or local equivalent.")));
2738 return false;
2740 if (doit)
2741 max_stack_depth_bytes = newval_bytes;
2742 return true;
2747 * set_debug_options --- apply "-d N" command line option
2749 * -d is not quite the same as setting log_min_messages because it enables
2750 * other output options.
2752 void
2753 set_debug_options(int debug_flag, GucContext context, GucSource source)
2755 if (debug_flag > 0)
2757 char debugstr[64];
2759 sprintf(debugstr, "debug%d", debug_flag);
2760 SetConfigOption("log_min_messages", debugstr, context, source);
2762 else
2763 SetConfigOption("log_min_messages", "notice", context, source);
2765 if (debug_flag >= 1 && context == PGC_POSTMASTER)
2767 SetConfigOption("log_connections", "true", context, source);
2768 SetConfigOption("log_disconnections", "true", context, source);
2770 if (debug_flag >= 2)
2771 SetConfigOption("log_statement", "all", context, source);
2772 if (debug_flag >= 3)
2773 SetConfigOption("debug_print_parse", "true", context, source);
2774 if (debug_flag >= 4)
2775 SetConfigOption("debug_print_plan", "true", context, source);
2776 if (debug_flag >= 5)
2777 SetConfigOption("debug_print_rewritten", "true", context, source);
2781 bool
2782 set_plan_disabling_options(const char *arg, GucContext context, GucSource source)
2784 char *tmp = NULL;
2786 switch (arg[0])
2788 case 's': /* seqscan */
2789 tmp = "enable_seqscan";
2790 break;
2791 case 'i': /* indexscan */
2792 tmp = "enable_indexscan";
2793 break;
2794 case 'b': /* bitmapscan */
2795 tmp = "enable_bitmapscan";
2796 break;
2797 case 't': /* tidscan */
2798 tmp = "enable_tidscan";
2799 break;
2800 case 'n': /* nestloop */
2801 tmp = "enable_nestloop";
2802 break;
2803 case 'm': /* mergejoin */
2804 tmp = "enable_mergejoin";
2805 break;
2806 case 'h': /* hashjoin */
2807 tmp = "enable_hashjoin";
2808 break;
2810 if (tmp)
2812 SetConfigOption(tmp, "false", context, source);
2813 return true;
2815 else
2816 return false;
2820 const char *
2821 get_stats_option_name(const char *arg)
2823 switch (arg[0])
2825 case 'p':
2826 if (optarg[1] == 'a') /* "parser" */
2827 return "log_parser_stats";
2828 else if (optarg[1] == 'l') /* "planner" */
2829 return "log_planner_stats";
2830 break;
2832 case 'e': /* "executor" */
2833 return "log_executor_stats";
2834 break;
2837 return NULL;
2841 /* ----------------------------------------------------------------
2842 * PostgresMain
2843 * postgres main loop -- all backends, interactive or otherwise start here
2845 * argc/argv are the command line arguments to be used. (When being forked
2846 * by the postmaster, these are not the original argv array of the process.)
2847 * username is the (possibly authenticated) PostgreSQL user name to be used
2848 * for the session.
2849 * ----------------------------------------------------------------
2852 PostgresMain(int argc, char *argv[], const char *username)
2854 int flag;
2855 const char *dbname = NULL;
2856 char *userDoption = NULL;
2857 bool secure;
2858 int errs = 0;
2859 int debug_flag = -1; /* -1 means not given */
2860 List *guc_names = NIL; /* for SUSET options */
2861 List *guc_values = NIL;
2862 GucContext ctx;
2863 GucSource gucsource;
2864 bool am_superuser;
2865 int firstchar;
2866 char stack_base;
2867 StringInfoData input_message;
2868 sigjmp_buf local_sigjmp_buf;
2869 volatile bool send_ready_for_query = true;
2871 #define PendingConfigOption(name,val) \
2872 (guc_names = lappend(guc_names, pstrdup(name)), \
2873 guc_values = lappend(guc_values, pstrdup(val)))
2876 * initialize globals (already done if under postmaster, but not if
2877 * standalone; cheap enough to do over)
2879 MyProcPid = getpid();
2881 MyStartTime = time(NULL);
2884 * Fire up essential subsystems: error and memory management
2886 * If we are running under the postmaster, this is done already.
2888 if (!IsUnderPostmaster)
2889 MemoryContextInit();
2891 set_ps_display("startup", false);
2893 SetProcessingMode(InitProcessing);
2895 /* Set up reference point for stack depth checking */
2896 stack_base_ptr = &stack_base;
2898 /* Compute paths, if we didn't inherit them from postmaster */
2899 if (my_exec_path[0] == '\0')
2901 if (find_my_exec(argv[0], my_exec_path) < 0)
2902 elog(FATAL, "%s: could not locate my own executable path",
2903 argv[0]);
2906 if (pkglib_path[0] == '\0')
2907 get_pkglib_path(my_exec_path, pkglib_path);
2910 * Set default values for command-line options.
2912 EchoQuery = false;
2914 if (!IsUnderPostmaster)
2915 InitializeGUCOptions();
2917 /* ----------------
2918 * parse command line arguments
2920 * There are now two styles of command line layout for the backend:
2922 * For interactive use (not started from postmaster) the format is
2923 * postgres [switches] [databasename]
2924 * If the databasename is omitted it is taken to be the user name.
2926 * When started from the postmaster, the format is
2927 * postgres [secure switches] -y databasename [insecure switches]
2928 * Switches appearing after -y came from the client (via "options"
2929 * field of connection request). For security reasons we restrict
2930 * what these switches can do.
2931 * ----------------
2934 /* Ignore the initial --single argument, if present */
2935 if (argc > 1 && strcmp(argv[1], "--single") == 0)
2937 argv++;
2938 argc--;
2941 /* all options are allowed until '-y' */
2942 secure = true;
2943 ctx = PGC_POSTMASTER;
2944 gucsource = PGC_S_ARGV; /* initial switches came from command line */
2947 * Parse command-line options. CAUTION: keep this in sync with
2948 * postmaster/postmaster.c (the option sets should not conflict) and with
2949 * the common help() function in main/main.c.
2951 while ((flag = getopt(argc, argv, "A:B:c:D:d:EeFf:h:ijk:lN:nOo:Pp:r:S:sTt:v:W:y:-:")) != -1)
2953 switch (flag)
2955 case 'A':
2956 SetConfigOption("debug_assertions", optarg, ctx, gucsource);
2957 break;
2959 case 'B':
2960 SetConfigOption("shared_buffers", optarg, ctx, gucsource);
2961 break;
2963 case 'D':
2964 if (secure)
2965 userDoption = optarg;
2966 break;
2968 case 'd':
2969 debug_flag = atoi(optarg);
2970 break;
2972 case 'E':
2973 EchoQuery = true;
2974 break;
2976 case 'e':
2977 SetConfigOption("datestyle", "euro", ctx, gucsource);
2978 break;
2980 case 'F':
2981 SetConfigOption("fsync", "false", ctx, gucsource);
2982 break;
2984 case 'f':
2985 if (!set_plan_disabling_options(optarg, ctx, gucsource))
2986 errs++;
2987 break;
2989 case 'h':
2990 SetConfigOption("listen_addresses", optarg, ctx, gucsource);
2991 break;
2993 case 'i':
2994 SetConfigOption("listen_addresses", "*", ctx, gucsource);
2995 break;
2997 case 'j':
2998 UseNewLine = 0;
2999 break;
3001 case 'k':
3002 SetConfigOption("unix_socket_directory", optarg, ctx, gucsource);
3003 break;
3005 case 'l':
3006 SetConfigOption("ssl", "true", ctx, gucsource);
3007 break;
3009 case 'N':
3010 SetConfigOption("max_connections", optarg, ctx, gucsource);
3011 break;
3013 case 'n':
3014 /* ignored for consistency with postmaster */
3015 break;
3017 case 'O':
3018 SetConfigOption("allow_system_table_mods", "true", ctx, gucsource);
3019 break;
3021 case 'o':
3022 errs++;
3023 break;
3025 case 'P':
3026 SetConfigOption("ignore_system_indexes", "true", ctx, gucsource);
3027 break;
3029 case 'p':
3030 SetConfigOption("port", optarg, ctx, gucsource);
3031 break;
3033 case 'r':
3034 /* send output (stdout and stderr) to the given file */
3035 if (secure)
3036 strlcpy(OutputFileName, optarg, MAXPGPATH);
3037 break;
3039 case 'S':
3040 SetConfigOption("work_mem", optarg, ctx, gucsource);
3041 break;
3043 case 's':
3046 * Since log options are SUSET, we need to postpone unless
3047 * still in secure context
3049 if (ctx == PGC_BACKEND)
3050 PendingConfigOption("log_statement_stats", "true");
3051 else
3052 SetConfigOption("log_statement_stats", "true",
3053 ctx, gucsource);
3054 break;
3056 case 'T':
3057 /* ignored for consistency with postmaster */
3058 break;
3060 case 't':
3062 const char *tmp = get_stats_option_name(optarg);
3064 if (tmp)
3066 if (ctx == PGC_BACKEND)
3067 PendingConfigOption(tmp, "true");
3068 else
3069 SetConfigOption(tmp, "true", ctx, gucsource);
3071 else
3072 errs++;
3073 break;
3076 case 'v':
3077 if (secure)
3078 FrontendProtocol = (ProtocolVersion) atoi(optarg);
3079 break;
3081 case 'W':
3082 SetConfigOption("post_auth_delay", optarg, ctx, gucsource);
3083 break;
3086 case 'y':
3089 * y - special flag passed if backend was forked by a
3090 * postmaster.
3092 if (secure)
3094 dbname = strdup(optarg);
3096 secure = false; /* subsequent switches are NOT secure */
3097 ctx = PGC_BACKEND;
3098 gucsource = PGC_S_CLIENT;
3100 break;
3102 case 'c':
3103 case '-':
3105 char *name,
3106 *value;
3108 ParseLongOption(optarg, &name, &value);
3109 if (!value)
3111 if (flag == '-')
3112 ereport(ERROR,
3113 (errcode(ERRCODE_SYNTAX_ERROR),
3114 errmsg("--%s requires a value",
3115 optarg)));
3116 else
3117 ereport(ERROR,
3118 (errcode(ERRCODE_SYNTAX_ERROR),
3119 errmsg("-c %s requires a value",
3120 optarg)));
3124 * If a SUSET option, must postpone evaluation, unless we
3125 * are still reading secure switches.
3127 if (ctx == PGC_BACKEND && IsSuperuserConfigOption(name))
3128 PendingConfigOption(name, value);
3129 else
3130 SetConfigOption(name, value, ctx, gucsource);
3131 free(name);
3132 if (value)
3133 free(value);
3134 break;
3137 default:
3138 errs++;
3139 break;
3144 * Process any additional GUC variable settings passed in startup packet.
3145 * These are handled exactly like command-line variables.
3147 if (MyProcPort != NULL)
3149 ListCell *gucopts = list_head(MyProcPort->guc_options);
3151 while (gucopts)
3153 char *name;
3154 char *value;
3156 name = lfirst(gucopts);
3157 gucopts = lnext(gucopts);
3159 value = lfirst(gucopts);
3160 gucopts = lnext(gucopts);
3162 if (IsSuperuserConfigOption(name))
3163 PendingConfigOption(name, value);
3164 else
3165 SetConfigOption(name, value, PGC_BACKEND, PGC_S_CLIENT);
3169 /* Acquire configuration parameters, unless inherited from postmaster */
3170 if (!IsUnderPostmaster)
3172 if (!SelectConfigFiles(userDoption, argv[0]))
3173 proc_exit(1);
3174 /* If timezone is not set, determine what the OS uses */
3175 pg_timezone_initialize();
3176 /* If timezone_abbreviations is not set, select default */
3177 pg_timezone_abbrev_initialize();
3180 if (PostAuthDelay)
3181 pg_usleep(PostAuthDelay * 1000000L);
3184 * You might expect to see a setsid() call here, but it's not needed,
3185 * because if we are under a postmaster then BackendInitialize() did it.
3189 * Set up signal handlers and masks.
3191 * Note that postmaster blocked all signals before forking child process,
3192 * so there is no race condition whereby we might receive a signal before
3193 * we have set up the handler.
3195 * Also note: it's best not to use any signals that are SIG_IGNored in the
3196 * postmaster. If such a signal arrives before we are able to change the
3197 * handler to non-SIG_IGN, it'll get dropped. Instead, make a dummy
3198 * handler in the postmaster to reserve the signal. (Of course, this isn't
3199 * an issue for signals that are locally generated, such as SIGALRM and
3200 * SIGPIPE.)
3202 pqsignal(SIGHUP, SigHupHandler); /* set flag to read config file */
3203 pqsignal(SIGINT, StatementCancelHandler); /* cancel current query */
3204 pqsignal(SIGTERM, die); /* cancel current query and exit */
3207 * In a standalone backend, SIGQUIT can be generated from the keyboard
3208 * easily, while SIGTERM cannot, so we make both signals do die() rather
3209 * than quickdie().
3211 if (IsUnderPostmaster)
3212 pqsignal(SIGQUIT, quickdie); /* hard crash time */
3213 else
3214 pqsignal(SIGQUIT, die); /* cancel current query and exit */
3215 pqsignal(SIGALRM, handle_sig_alarm); /* timeout conditions */
3218 * Ignore failure to write to frontend. Note: if frontend closes
3219 * connection, we will notice it and exit cleanly when control next
3220 * returns to outer loop. This seems safer than forcing exit in the midst
3221 * of output during who-knows-what operation...
3223 pqsignal(SIGPIPE, SIG_IGN);
3224 pqsignal(SIGUSR1, CatchupInterruptHandler);
3225 pqsignal(SIGUSR2, NotifyInterruptHandler);
3226 pqsignal(SIGFPE, FloatExceptionHandler);
3229 * Reset some signals that are accepted by postmaster but not by backend
3231 pqsignal(SIGCHLD, SIG_DFL); /* system() requires this on some platforms */
3233 pqinitmask();
3235 if (IsUnderPostmaster)
3237 /* We allow SIGQUIT (quickdie) at all times */
3238 #ifdef HAVE_SIGPROCMASK
3239 sigdelset(&BlockSig, SIGQUIT);
3240 #else
3241 BlockSig &= ~(sigmask(SIGQUIT));
3242 #endif
3245 PG_SETMASK(&BlockSig); /* block everything except SIGQUIT */
3247 if (IsUnderPostmaster)
3249 /* noninteractive case: nothing should be left after switches */
3250 if (errs || argc != optind || dbname == NULL)
3252 ereport(FATAL,
3253 (errcode(ERRCODE_SYNTAX_ERROR),
3254 errmsg("invalid command-line arguments for server process"),
3255 errhint("Try \"%s --help\" for more information.", argv[0])));
3258 BaseInit();
3260 else
3262 /* interactive case: database name can be last arg on command line */
3263 if (errs || argc - optind > 1)
3265 ereport(FATAL,
3266 (errcode(ERRCODE_SYNTAX_ERROR),
3267 errmsg("%s: invalid command-line arguments",
3268 argv[0]),
3269 errhint("Try \"%s --help\" for more information.", argv[0])));
3271 else if (argc - optind == 1)
3272 dbname = argv[optind];
3273 else if ((dbname = username) == NULL)
3275 ereport(FATAL,
3276 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3277 errmsg("%s: no database nor user name specified",
3278 argv[0])));
3282 * Validate we have been given a reasonable-looking DataDir (if under
3283 * postmaster, assume postmaster did this already).
3285 Assert(DataDir);
3286 ValidatePgVersion(DataDir);
3288 /* Change into DataDir (if under postmaster, was done already) */
3289 ChangeToDataDir();
3292 * Create lockfile for data directory.
3294 CreateDataDirLockFile(false);
3296 BaseInit();
3299 * Start up xlog for standalone backend, and register to have it
3300 * closed down at exit.
3302 StartupXLOG();
3303 on_shmem_exit(ShutdownXLOG, 0);
3306 * We have to build the flat file for pg_database, but not for the
3307 * user and group tables, since we won't try to do authentication.
3309 BuildFlatFiles(true);
3313 * Create a per-backend PGPROC struct in shared memory, except in the
3314 * EXEC_BACKEND case where this was done in SubPostmasterMain. We must do
3315 * this before we can use LWLocks (and in the EXEC_BACKEND case we already
3316 * had to do some stuff with LWLocks).
3318 #ifdef EXEC_BACKEND
3319 if (!IsUnderPostmaster)
3320 InitProcess();
3321 #else
3322 InitProcess();
3323 #endif
3326 * General initialization.
3328 * NOTE: if you are tempted to add code in this vicinity, consider putting
3329 * it inside InitPostgres() instead. In particular, anything that
3330 * involves database access should be there, not here.
3332 ereport(DEBUG3,
3333 (errmsg_internal("InitPostgres")));
3334 am_superuser = InitPostgres(dbname, InvalidOid, username, NULL);
3336 SetProcessingMode(NormalProcessing);
3339 * Now that we know if client is a superuser, we can try to apply SUSET
3340 * GUC options that came from the client.
3342 ctx = am_superuser ? PGC_SUSET : PGC_USERSET;
3344 if (debug_flag >= 0)
3345 set_debug_options(debug_flag, ctx, PGC_S_CLIENT);
3347 if (guc_names != NIL)
3349 ListCell *namcell,
3350 *valcell;
3352 forboth(namcell, guc_names, valcell, guc_values)
3354 char *name = (char *) lfirst(namcell);
3355 char *value = (char *) lfirst(valcell);
3357 SetConfigOption(name, value, ctx, PGC_S_CLIENT);
3358 pfree(name);
3359 pfree(value);
3364 * Now all GUC states are fully set up. Report them to client if
3365 * appropriate.
3367 BeginReportingGUCOptions();
3370 * Also set up handler to log session end; we have to wait till now to be
3371 * sure Log_disconnections has its final value.
3373 if (IsUnderPostmaster && Log_disconnections)
3374 on_proc_exit(log_disconnections, 0);
3377 * process any libraries that should be preloaded at backend start (this
3378 * likewise can't be done until GUC settings are complete)
3380 process_local_preload_libraries();
3383 * Send this backend's cancellation info to the frontend.
3385 if (whereToSendOutput == DestRemote &&
3386 PG_PROTOCOL_MAJOR(FrontendProtocol) >= 2)
3388 StringInfoData buf;
3390 pq_beginmessage(&buf, 'K');
3391 pq_sendint(&buf, (int32) MyProcPid, sizeof(int32));
3392 pq_sendint(&buf, (int32) MyCancelKey, sizeof(int32));
3393 pq_endmessage(&buf);
3394 /* Need not flush since ReadyForQuery will do it. */
3397 /* Welcome banner for standalone case */
3398 if (whereToSendOutput == DestDebug)
3399 printf("\nPostgreSQL stand-alone backend %s\n", PG_VERSION);
3402 * Create the memory context we will use in the main loop.
3404 * MessageContext is reset once per iteration of the main loop, ie, upon
3405 * completion of processing of each command message from the client.
3407 MessageContext = AllocSetContextCreate(TopMemoryContext,
3408 "MessageContext",
3409 ALLOCSET_DEFAULT_MINSIZE,
3410 ALLOCSET_DEFAULT_INITSIZE,
3411 ALLOCSET_DEFAULT_MAXSIZE);
3414 * Remember stand-alone backend startup time
3416 if (!IsUnderPostmaster)
3417 PgStartTime = GetCurrentTimestamp();
3420 * POSTGRES main processing loop begins here
3422 * If an exception is encountered, processing resumes here so we abort the
3423 * current transaction and start a new one.
3425 * You might wonder why this isn't coded as an infinite loop around a
3426 * PG_TRY construct. The reason is that this is the bottom of the
3427 * exception stack, and so with PG_TRY there would be no exception handler
3428 * in force at all during the CATCH part. By leaving the outermost setjmp
3429 * always active, we have at least some chance of recovering from an error
3430 * during error recovery. (If we get into an infinite loop thereby, it
3431 * will soon be stopped by overflow of elog.c's internal state stack.)
3434 if (sigsetjmp(local_sigjmp_buf, 1) != 0)
3437 * NOTE: if you are tempted to add more code in this if-block,
3438 * consider the high probability that it should be in
3439 * AbortTransaction() instead. The only stuff done directly here
3440 * should be stuff that is guaranteed to apply *only* for outer-level
3441 * error recovery, such as adjusting the FE/BE protocol status.
3444 /* Since not using PG_TRY, must reset error stack by hand */
3445 error_context_stack = NULL;
3447 /* Prevent interrupts while cleaning up */
3448 HOLD_INTERRUPTS();
3451 * Forget any pending QueryCancel request, since we're returning to
3452 * the idle loop anyway, and cancel the statement timer if running.
3454 QueryCancelPending = false;
3455 disable_sig_alarm(true);
3456 QueryCancelPending = false; /* again in case timeout occurred */
3459 * Turn off these interrupts too. This is only needed here and not in
3460 * other exception-catching places since these interrupts are only
3461 * enabled while we wait for client input.
3463 DoingCommandRead = false;
3464 DisableNotifyInterrupt();
3465 DisableCatchupInterrupt();
3467 /* Make sure libpq is in a good state */
3468 pq_comm_reset();
3470 /* Report the error to the client and/or server log */
3471 EmitErrorReport();
3474 * Make sure debug_query_string gets reset before we possibly clobber
3475 * the storage it points at.
3477 debug_query_string = NULL;
3480 * Abort the current transaction in order to recover.
3482 AbortCurrentTransaction();
3485 * Now return to normal top-level context and clear ErrorContext for
3486 * next time.
3488 MemoryContextSwitchTo(TopMemoryContext);
3489 FlushErrorState();
3492 * If we were handling an extended-query-protocol message, initiate
3493 * skip till next Sync. This also causes us not to issue
3494 * ReadyForQuery (until we get Sync).
3496 if (doing_extended_query_message)
3497 ignore_till_sync = true;
3499 /* We don't have a transaction command open anymore */
3500 xact_started = false;
3502 /* Now we can allow interrupts again */
3503 RESUME_INTERRUPTS();
3506 /* We can now handle ereport(ERROR) */
3507 PG_exception_stack = &local_sigjmp_buf;
3509 PG_SETMASK(&UnBlockSig);
3511 if (!ignore_till_sync)
3512 send_ready_for_query = true; /* initially, or after error */
3515 * Non-error queries loop here.
3518 for (;;)
3521 * At top of loop, reset extended-query-message flag, so that any
3522 * errors encountered in "idle" state don't provoke skip.
3524 doing_extended_query_message = false;
3527 * Release storage left over from prior query cycle, and create a new
3528 * query input buffer in the cleared MessageContext.
3530 MemoryContextSwitchTo(MessageContext);
3531 MemoryContextResetAndDeleteChildren(MessageContext);
3533 initStringInfo(&input_message);
3536 * (1) If we've reached idle state, tell the frontend we're ready for
3537 * a new query.
3539 * Note: this includes fflush()'ing the last of the prior output.
3541 * This is also a good time to send collected statistics to the
3542 * collector, and to update the PS stats display. We avoid doing
3543 * those every time through the message loop because it'd slow down
3544 * processing of batched messages, and because we don't want to report
3545 * uncommitted updates (that confuses autovacuum).
3547 if (send_ready_for_query)
3549 if (IsTransactionOrTransactionBlock())
3551 set_ps_display("idle in transaction", false);
3552 pgstat_report_activity("<IDLE> in transaction");
3554 else
3556 pgstat_report_stat(false);
3558 set_ps_display("idle", false);
3559 pgstat_report_activity("<IDLE>");
3562 ReadyForQuery(whereToSendOutput);
3563 send_ready_for_query = false;
3567 * (2) Allow asynchronous signals to be executed immediately if they
3568 * come in while we are waiting for client input. (This must be
3569 * conditional since we don't want, say, reads on behalf of COPY FROM
3570 * STDIN doing the same thing.)
3572 QueryCancelPending = false; /* forget any earlier CANCEL signal */
3573 DoingCommandRead = true;
3576 * (3) read a command (loop blocks here)
3578 firstchar = ReadCommand(&input_message);
3581 * (4) disable async signal conditions again.
3583 DoingCommandRead = false;
3586 * (5) check for any other interesting events that happened while we
3587 * slept.
3589 if (got_SIGHUP)
3591 got_SIGHUP = false;
3592 ProcessConfigFile(PGC_SIGHUP);
3596 * (6) process the command. But ignore it if we're skipping till
3597 * Sync.
3599 if (ignore_till_sync && firstchar != EOF)
3600 continue;
3602 switch (firstchar)
3604 case 'Q': /* simple query */
3606 const char *query_string;
3608 /* Set statement_timestamp() */
3609 SetCurrentStatementStartTimestamp();
3611 query_string = pq_getmsgstring(&input_message);
3612 pq_getmsgend(&input_message);
3614 exec_simple_query(query_string);
3616 send_ready_for_query = true;
3618 break;
3620 case 'P': /* parse */
3622 const char *stmt_name;
3623 const char *query_string;
3624 int numParams;
3625 Oid *paramTypes = NULL;
3627 /* Set statement_timestamp() */
3628 SetCurrentStatementStartTimestamp();
3630 stmt_name = pq_getmsgstring(&input_message);
3631 query_string = pq_getmsgstring(&input_message);
3632 numParams = pq_getmsgint(&input_message, 2);
3633 if (numParams > 0)
3635 int i;
3637 paramTypes = (Oid *) palloc(numParams * sizeof(Oid));
3638 for (i = 0; i < numParams; i++)
3639 paramTypes[i] = pq_getmsgint(&input_message, 4);
3641 pq_getmsgend(&input_message);
3643 exec_parse_message(query_string, stmt_name,
3644 paramTypes, numParams);
3646 break;
3648 case 'B': /* bind */
3649 /* Set statement_timestamp() */
3650 SetCurrentStatementStartTimestamp();
3653 * this message is complex enough that it seems best to put
3654 * the field extraction out-of-line
3656 exec_bind_message(&input_message);
3657 break;
3659 case 'E': /* execute */
3661 const char *portal_name;
3662 int max_rows;
3664 /* Set statement_timestamp() */
3665 SetCurrentStatementStartTimestamp();
3667 portal_name = pq_getmsgstring(&input_message);
3668 max_rows = pq_getmsgint(&input_message, 4);
3669 pq_getmsgend(&input_message);
3671 exec_execute_message(portal_name, max_rows);
3673 break;
3675 case 'F': /* fastpath function call */
3676 /* Set statement_timestamp() */
3677 SetCurrentStatementStartTimestamp();
3679 /* Tell the collector what we're doing */
3680 pgstat_report_activity("<FASTPATH> function call");
3682 /* start an xact for this function invocation */
3683 start_xact_command();
3686 * Note: we may at this point be inside an aborted
3687 * transaction. We can't throw error for that until we've
3688 * finished reading the function-call message, so
3689 * HandleFunctionRequest() must check for it after doing so.
3690 * Be careful not to do anything that assumes we're inside a
3691 * valid transaction here.
3694 /* switch back to message context */
3695 MemoryContextSwitchTo(MessageContext);
3697 if (HandleFunctionRequest(&input_message) == EOF)
3699 /* lost frontend connection during F message input */
3702 * Reset whereToSendOutput to prevent ereport from
3703 * attempting to send any more messages to client.
3705 if (whereToSendOutput == DestRemote)
3706 whereToSendOutput = DestNone;
3708 proc_exit(0);
3711 /* commit the function-invocation transaction */
3712 finish_xact_command();
3714 send_ready_for_query = true;
3715 break;
3717 case 'C': /* close */
3719 int close_type;
3720 const char *close_target;
3722 close_type = pq_getmsgbyte(&input_message);
3723 close_target = pq_getmsgstring(&input_message);
3724 pq_getmsgend(&input_message);
3726 switch (close_type)
3728 case 'S':
3729 if (close_target[0] != '\0')
3730 DropPreparedStatement(close_target, false);
3731 else
3733 /* special-case the unnamed statement */
3734 drop_unnamed_stmt();
3736 break;
3737 case 'P':
3739 Portal portal;
3741 portal = GetPortalByName(close_target);
3742 if (PortalIsValid(portal))
3743 PortalDrop(portal, false);
3745 break;
3746 default:
3747 ereport(ERROR,
3748 (errcode(ERRCODE_PROTOCOL_VIOLATION),
3749 errmsg("invalid CLOSE message subtype %d",
3750 close_type)));
3751 break;
3754 if (whereToSendOutput == DestRemote)
3755 pq_putemptymessage('3'); /* CloseComplete */
3757 break;
3759 case 'D': /* describe */
3761 int describe_type;
3762 const char *describe_target;
3764 /* Set statement_timestamp() (needed for xact) */
3765 SetCurrentStatementStartTimestamp();
3767 describe_type = pq_getmsgbyte(&input_message);
3768 describe_target = pq_getmsgstring(&input_message);
3769 pq_getmsgend(&input_message);
3771 switch (describe_type)
3773 case 'S':
3774 exec_describe_statement_message(describe_target);
3775 break;
3776 case 'P':
3777 exec_describe_portal_message(describe_target);
3778 break;
3779 default:
3780 ereport(ERROR,
3781 (errcode(ERRCODE_PROTOCOL_VIOLATION),
3782 errmsg("invalid DESCRIBE message subtype %d",
3783 describe_type)));
3784 break;
3787 break;
3789 case 'H': /* flush */
3790 pq_getmsgend(&input_message);
3791 if (whereToSendOutput == DestRemote)
3792 pq_flush();
3793 break;
3795 case 'S': /* sync */
3796 pq_getmsgend(&input_message);
3797 finish_xact_command();
3798 send_ready_for_query = true;
3799 break;
3802 * 'X' means that the frontend is closing down the socket. EOF
3803 * means unexpected loss of frontend connection. Either way,
3804 * perform normal shutdown.
3806 case 'X':
3807 case EOF:
3810 * Reset whereToSendOutput to prevent ereport from attempting
3811 * to send any more messages to client.
3813 if (whereToSendOutput == DestRemote)
3814 whereToSendOutput = DestNone;
3817 * NOTE: if you are tempted to add more code here, DON'T!
3818 * Whatever you had in mind to do should be set up as an
3819 * on_proc_exit or on_shmem_exit callback, instead. Otherwise
3820 * it will fail to be called during other backend-shutdown
3821 * scenarios.
3823 proc_exit(0);
3825 case 'd': /* copy data */
3826 case 'c': /* copy done */
3827 case 'f': /* copy fail */
3830 * Accept but ignore these messages, per protocol spec; we
3831 * probably got here because a COPY failed, and the frontend
3832 * is still sending data.
3834 break;
3836 default:
3837 ereport(FATAL,
3838 (errcode(ERRCODE_PROTOCOL_VIOLATION),
3839 errmsg("invalid frontend message type %d",
3840 firstchar)));
3842 } /* end of input-reading loop */
3844 /* can't get here because the above loop never exits */
3845 Assert(false);
3847 return 1; /* keep compiler quiet */
3852 * Obtain platform stack depth limit (in bytes)
3854 * Return -1 if unlimited or not known
3856 long
3857 get_stack_depth_rlimit(void)
3859 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_STACK)
3860 static long val = 0;
3862 /* This won't change after process launch, so check just once */
3863 if (val == 0)
3865 struct rlimit rlim;
3867 if (getrlimit(RLIMIT_STACK, &rlim) < 0)
3868 val = -1;
3869 else if (rlim.rlim_cur == RLIM_INFINITY)
3870 val = -1;
3871 else
3872 val = rlim.rlim_cur;
3874 return val;
3875 #else /* no getrlimit */
3876 #if defined(WIN32) || defined(__CYGWIN__)
3877 /* On Windows we set the backend stack size in src/backend/Makefile */
3878 return WIN32_STACK_RLIMIT;
3879 #else /* not windows ... give up */
3880 return -1;
3881 #endif
3882 #endif
3886 static struct rusage Save_r;
3887 static struct timeval Save_t;
3889 void
3890 ResetUsage(void)
3892 getrusage(RUSAGE_SELF, &Save_r);
3893 gettimeofday(&Save_t, NULL);
3894 ResetBufferUsage();
3895 /* ResetTupleCount(); */
3898 void
3899 ShowUsage(const char *title)
3901 StringInfoData str;
3902 struct timeval user,
3903 sys;
3904 struct timeval elapse_t;
3905 struct rusage r;
3906 char *bufusage;
3908 getrusage(RUSAGE_SELF, &r);
3909 gettimeofday(&elapse_t, NULL);
3910 memcpy((char *) &user, (char *) &r.ru_utime, sizeof(user));
3911 memcpy((char *) &sys, (char *) &r.ru_stime, sizeof(sys));
3912 if (elapse_t.tv_usec < Save_t.tv_usec)
3914 elapse_t.tv_sec--;
3915 elapse_t.tv_usec += 1000000;
3917 if (r.ru_utime.tv_usec < Save_r.ru_utime.tv_usec)
3919 r.ru_utime.tv_sec--;
3920 r.ru_utime.tv_usec += 1000000;
3922 if (r.ru_stime.tv_usec < Save_r.ru_stime.tv_usec)
3924 r.ru_stime.tv_sec--;
3925 r.ru_stime.tv_usec += 1000000;
3929 * the only stats we don't show here are for memory usage -- i can't
3930 * figure out how to interpret the relevant fields in the rusage struct,
3931 * and they change names across o/s platforms, anyway. if you can figure
3932 * out what the entries mean, you can somehow extract resident set size,
3933 * shared text size, and unshared data and stack sizes.
3935 initStringInfo(&str);
3937 appendStringInfo(&str, "! system usage stats:\n");
3938 appendStringInfo(&str,
3939 "!\t%ld.%06ld elapsed %ld.%06ld user %ld.%06ld system sec\n",
3940 (long) (elapse_t.tv_sec - Save_t.tv_sec),
3941 (long) (elapse_t.tv_usec - Save_t.tv_usec),
3942 (long) (r.ru_utime.tv_sec - Save_r.ru_utime.tv_sec),
3943 (long) (r.ru_utime.tv_usec - Save_r.ru_utime.tv_usec),
3944 (long) (r.ru_stime.tv_sec - Save_r.ru_stime.tv_sec),
3945 (long) (r.ru_stime.tv_usec - Save_r.ru_stime.tv_usec));
3946 appendStringInfo(&str,
3947 "!\t[%ld.%06ld user %ld.%06ld sys total]\n",
3948 (long) user.tv_sec,
3949 (long) user.tv_usec,
3950 (long) sys.tv_sec,
3951 (long) sys.tv_usec);
3952 #if defined(HAVE_GETRUSAGE)
3953 appendStringInfo(&str,
3954 "!\t%ld/%ld [%ld/%ld] filesystem blocks in/out\n",
3955 r.ru_inblock - Save_r.ru_inblock,
3956 /* they only drink coffee at dec */
3957 r.ru_oublock - Save_r.ru_oublock,
3958 r.ru_inblock, r.ru_oublock);
3959 appendStringInfo(&str,
3960 "!\t%ld/%ld [%ld/%ld] page faults/reclaims, %ld [%ld] swaps\n",
3961 r.ru_majflt - Save_r.ru_majflt,
3962 r.ru_minflt - Save_r.ru_minflt,
3963 r.ru_majflt, r.ru_minflt,
3964 r.ru_nswap - Save_r.ru_nswap,
3965 r.ru_nswap);
3966 appendStringInfo(&str,
3967 "!\t%ld [%ld] signals rcvd, %ld/%ld [%ld/%ld] messages rcvd/sent\n",
3968 r.ru_nsignals - Save_r.ru_nsignals,
3969 r.ru_nsignals,
3970 r.ru_msgrcv - Save_r.ru_msgrcv,
3971 r.ru_msgsnd - Save_r.ru_msgsnd,
3972 r.ru_msgrcv, r.ru_msgsnd);
3973 appendStringInfo(&str,
3974 "!\t%ld/%ld [%ld/%ld] voluntary/involuntary context switches\n",
3975 r.ru_nvcsw - Save_r.ru_nvcsw,
3976 r.ru_nivcsw - Save_r.ru_nivcsw,
3977 r.ru_nvcsw, r.ru_nivcsw);
3978 #endif /* HAVE_GETRUSAGE */
3980 bufusage = ShowBufferUsage();
3981 appendStringInfo(&str, "! buffer usage stats:\n%s", bufusage);
3982 pfree(bufusage);
3984 /* remove trailing newline */
3985 if (str.data[str.len - 1] == '\n')
3986 str.data[--str.len] = '\0';
3988 ereport(LOG,
3989 (errmsg_internal("%s", title),
3990 errdetail("%s", str.data)));
3992 pfree(str.data);
3996 * on_proc_exit handler to log end of session
3998 static void
3999 log_disconnections(int code, Datum arg)
4001 Port *port = MyProcPort;
4002 long secs;
4003 int usecs;
4004 int msecs;
4005 int hours,
4006 minutes,
4007 seconds;
4009 TimestampDifference(port->SessionStartTime,
4010 GetCurrentTimestamp(),
4011 &secs, &usecs);
4012 msecs = usecs / 1000;
4014 hours = secs / SECS_PER_HOUR;
4015 secs %= SECS_PER_HOUR;
4016 minutes = secs / SECS_PER_MINUTE;
4017 seconds = secs % SECS_PER_MINUTE;
4019 ereport(LOG,
4020 (errmsg("disconnection: session time: %d:%02d:%02d.%03d "
4021 "user=%s database=%s host=%s%s%s",
4022 hours, minutes, seconds, msecs,
4023 port->user_name, port->database_name, port->remote_host,
4024 port->remote_port[0] ? " port=" : "", port->remote_port)));