Force a checkpoint in CREATE DATABASE before starting to copy the files,
[PostgreSQL.git] / src / backend / tcop / postgres.c
blob09892780ba24e77d64ed4be0d4700e2c3afc832f
1 /*-------------------------------------------------------------------------
3 * postgres.c
4 * POSTGRES C Backend Interface
6 * Portions Copyright (c) 1996-2008, 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; /* for pgmonitor and log_min_error_statement */
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 TRACE_POSTGRESQL_QUERY_PLAN_START();
690 if (log_planner_stats)
691 ResetUsage();
693 /* call the optimizer */
694 plan = planner(querytree, cursorOptions, boundParams);
696 if (log_planner_stats)
697 ShowUsage("PLANNER STATISTICS");
699 #ifdef COPY_PARSE_PLAN_TREES
700 /* Optional debugging check: pass plan output through copyObject() */
702 PlannedStmt *new_plan = (PlannedStmt *) copyObject(plan);
705 * equal() currently does not have routines to compare Plan nodes, so
706 * don't try to test equality here. Perhaps fix someday?
708 #ifdef NOT_USED
709 /* This checks both copyObject() and the equal() routines... */
710 if (!equal(new_plan, plan))
711 elog(WARNING, "copyObject() failed to produce an equal plan tree");
712 else
713 #endif
714 plan = new_plan;
716 #endif
719 * Print plan if debugging.
721 if (Debug_print_plan)
722 elog_node_display(LOG, "plan", plan, Debug_pretty_print);
724 TRACE_POSTGRESQL_QUERY_PLAN_DONE();
726 return plan;
730 * Generate plans for a list of already-rewritten queries.
732 * If needSnapshot is TRUE, we haven't yet set a snapshot for the current
733 * query. A snapshot must be set before invoking the planner, since it
734 * might try to evaluate user-defined functions. But we must not set a
735 * snapshot if the list contains only utility statements, because some
736 * utility statements depend on not having frozen the snapshot yet.
737 * (We assume that such statements cannot appear together with plannable
738 * statements in the rewriter's output.)
740 * Normal optimizable statements generate PlannedStmt entries in the result
741 * list. Utility statements are simply represented by their statement nodes.
743 List *
744 pg_plan_queries(List *querytrees, int cursorOptions, ParamListInfo boundParams,
745 bool needSnapshot)
747 List *stmt_list = NIL;
748 ListCell *query_list;
749 bool snapshot_set = false;
751 foreach(query_list, querytrees)
753 Query *query = (Query *) lfirst(query_list);
754 Node *stmt;
756 if (query->commandType == CMD_UTILITY)
758 /* Utility commands have no plans. */
759 stmt = query->utilityStmt;
761 else
763 if (needSnapshot && !snapshot_set)
765 PushActiveSnapshot(GetTransactionSnapshot());
766 snapshot_set = true;
769 stmt = (Node *) pg_plan_query(query, cursorOptions,
770 boundParams);
773 stmt_list = lappend(stmt_list, stmt);
776 if (snapshot_set)
777 PopActiveSnapshot();
779 return stmt_list;
784 * exec_simple_query
786 * Execute a "simple Query" protocol message.
788 static void
789 exec_simple_query(const char *query_string)
791 CommandDest dest = whereToSendOutput;
792 MemoryContext oldcontext;
793 List *parsetree_list;
794 ListCell *parsetree_item;
795 bool save_log_statement_stats = log_statement_stats;
796 bool was_logged = false;
797 bool isTopLevel;
798 char msec_str[32];
802 * Report query to various monitoring facilities.
804 debug_query_string = query_string;
806 pgstat_report_activity(query_string);
808 TRACE_POSTGRESQL_QUERY_START(query_string);
811 * We use save_log_statement_stats so ShowUsage doesn't report incorrect
812 * results because ResetUsage wasn't called.
814 if (save_log_statement_stats)
815 ResetUsage();
818 * Start up a transaction command. All queries generated by the
819 * query_string will be in this same command block, *unless* we find a
820 * BEGIN/COMMIT/ABORT statement; we have to force a new xact command after
821 * one of those, else bad things will happen in xact.c. (Note that this
822 * will normally change current memory context.)
824 start_xact_command();
827 * Zap any pre-existing unnamed statement. (While not strictly necessary,
828 * it seems best to define simple-Query mode as if it used the unnamed
829 * statement and portal; this ensures we recover any storage used by prior
830 * unnamed operations.)
832 drop_unnamed_stmt();
835 * Switch to appropriate context for constructing parsetrees.
837 oldcontext = MemoryContextSwitchTo(MessageContext);
840 * Do basic parsing of the query or queries (this should be safe even if
841 * we are in aborted transaction state!)
843 parsetree_list = pg_parse_query(query_string);
845 /* Log immediately if dictated by log_statement */
846 if (check_log_statement(parsetree_list))
848 ereport(LOG,
849 (errmsg("statement: %s", query_string),
850 errhidestmt(true),
851 errdetail_execute(parsetree_list)));
852 was_logged = true;
856 * Switch back to transaction context to enter the loop.
858 MemoryContextSwitchTo(oldcontext);
861 * We'll tell PortalRun it's a top-level command iff there's exactly one
862 * raw parsetree. If more than one, it's effectively a transaction block
863 * and we want PreventTransactionChain to reject unsafe commands. (Note:
864 * we're assuming that query rewrite cannot add commands that are
865 * significant to PreventTransactionChain.)
867 isTopLevel = (list_length(parsetree_list) == 1);
870 * Run through the raw parsetree(s) and process each one.
872 foreach(parsetree_item, parsetree_list)
874 Node *parsetree = (Node *) lfirst(parsetree_item);
875 const char *commandTag;
876 char completionTag[COMPLETION_TAG_BUFSIZE];
877 List *querytree_list,
878 *plantree_list;
879 Portal portal;
880 DestReceiver *receiver;
881 int16 format;
884 * Get the command name for use in status display (it also becomes the
885 * default completion tag, down inside PortalRun). Set ps_status and
886 * do any special start-of-SQL-command processing needed by the
887 * destination.
889 commandTag = CreateCommandTag(parsetree);
891 set_ps_display(commandTag, false);
893 BeginCommand(commandTag, dest);
896 * If we are in an aborted transaction, reject all commands except
897 * COMMIT/ABORT. It is important that this test occur before we try
898 * to do parse analysis, rewrite, or planning, since all those phases
899 * try to do database accesses, which may fail in abort state. (It
900 * might be safe to allow some additional utility commands in this
901 * state, but not many...)
903 if (IsAbortedTransactionBlockState() &&
904 !IsTransactionExitStmt(parsetree))
905 ereport(ERROR,
906 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
907 errmsg("current transaction is aborted, "
908 "commands ignored until end of transaction block")));
910 /* Make sure we are in a transaction command */
911 start_xact_command();
913 /* If we got a cancel signal in parsing or prior command, quit */
914 CHECK_FOR_INTERRUPTS();
917 * OK to analyze, rewrite, and plan this query.
919 * Switch to appropriate context for constructing querytrees (again,
920 * these must outlive the execution context).
922 oldcontext = MemoryContextSwitchTo(MessageContext);
924 querytree_list = pg_analyze_and_rewrite(parsetree, query_string,
925 NULL, 0);
927 plantree_list = pg_plan_queries(querytree_list, 0, NULL, true);
929 /* If we got a cancel signal in analysis or planning, quit */
930 CHECK_FOR_INTERRUPTS();
933 * Create unnamed portal to run the query or queries in. If there
934 * already is one, silently drop it.
936 portal = CreatePortal("", true, true);
937 /* Don't display the portal in pg_cursors */
938 portal->visible = false;
941 * We don't have to copy anything into the portal, because everything
942 * we are passsing here is in MessageContext, which will outlive the
943 * portal anyway.
945 PortalDefineQuery(portal,
946 NULL,
947 query_string,
948 commandTag,
949 plantree_list,
950 NULL);
953 * Start the portal. No parameters here.
955 PortalStart(portal, NULL, InvalidSnapshot);
958 * Select the appropriate output format: text unless we are doing a
959 * FETCH from a binary cursor. (Pretty grotty to have to do this here
960 * --- but it avoids grottiness in other places. Ah, the joys of
961 * backward compatibility...)
963 format = 0; /* TEXT is default */
964 if (IsA(parsetree, FetchStmt))
966 FetchStmt *stmt = (FetchStmt *) parsetree;
968 if (!stmt->ismove)
970 Portal fportal = GetPortalByName(stmt->portalname);
972 if (PortalIsValid(fportal) &&
973 (fportal->cursorOptions & CURSOR_OPT_BINARY))
974 format = 1; /* BINARY */
977 PortalSetResultFormat(portal, 1, &format);
980 * Now we can create the destination receiver object.
982 receiver = CreateDestReceiver(dest, portal);
985 * Switch back to transaction context for execution.
987 MemoryContextSwitchTo(oldcontext);
990 * Run the portal to completion, and then drop it (and the receiver).
992 (void) PortalRun(portal,
993 FETCH_ALL,
994 isTopLevel,
995 receiver,
996 receiver,
997 completionTag);
999 (*receiver->rDestroy) (receiver);
1001 PortalDrop(portal, false);
1003 if (IsA(parsetree, TransactionStmt))
1006 * If this was a transaction control statement, commit it. We will
1007 * start a new xact command for the next command (if any).
1009 finish_xact_command();
1011 else if (lnext(parsetree_item) == NULL)
1014 * If this is the last parsetree of the query string, close down
1015 * transaction statement before reporting command-complete. This
1016 * is so that any end-of-transaction errors are reported before
1017 * the command-complete message is issued, to avoid confusing
1018 * clients who will expect either a command-complete message or an
1019 * error, not one and then the other. But for compatibility with
1020 * historical Postgres behavior, we do not force a transaction
1021 * boundary between queries appearing in a single query string.
1023 finish_xact_command();
1025 else
1028 * We need a CommandCounterIncrement after every query, except
1029 * those that start or end a transaction block.
1031 CommandCounterIncrement();
1035 * Tell client that we're done with this query. Note we emit exactly
1036 * one EndCommand report for each raw parsetree, thus one for each SQL
1037 * command the client sent, regardless of rewriting. (But a command
1038 * aborted by error will not send an EndCommand report at all.)
1040 EndCommand(completionTag, dest);
1041 } /* end loop over parsetrees */
1044 * Close down transaction statement, if one is open.
1046 finish_xact_command();
1049 * If there were no parsetrees, return EmptyQueryResponse message.
1051 if (!parsetree_list)
1052 NullCommand(dest);
1055 * Emit duration logging if appropriate.
1057 switch (check_log_duration(msec_str, was_logged))
1059 case 1:
1060 ereport(LOG,
1061 (errmsg("duration: %s ms", msec_str),
1062 errhidestmt(true)));
1063 break;
1064 case 2:
1065 ereport(LOG,
1066 (errmsg("duration: %s ms statement: %s",
1067 msec_str, query_string),
1068 errhidestmt(true),
1069 errdetail_execute(parsetree_list)));
1070 break;
1073 if (save_log_statement_stats)
1074 ShowUsage("QUERY STATISTICS");
1076 TRACE_POSTGRESQL_QUERY_DONE(query_string);
1078 debug_query_string = NULL;
1082 * exec_parse_message
1084 * Execute a "Parse" protocol message.
1086 static void
1087 exec_parse_message(const char *query_string, /* string to execute */
1088 const char *stmt_name, /* name for prepared stmt */
1089 Oid *paramTypes, /* parameter types */
1090 int numParams) /* number of parameters */
1092 MemoryContext oldcontext;
1093 List *parsetree_list;
1094 Node *raw_parse_tree;
1095 const char *commandTag;
1096 List *querytree_list,
1097 *stmt_list;
1098 bool is_named;
1099 bool fully_planned;
1100 bool save_log_statement_stats = log_statement_stats;
1101 char msec_str[32];
1104 * Report query to various monitoring facilities.
1106 debug_query_string = query_string;
1108 pgstat_report_activity(query_string);
1110 set_ps_display("PARSE", false);
1112 if (save_log_statement_stats)
1113 ResetUsage();
1115 ereport(DEBUG2,
1116 (errmsg("parse %s: %s",
1117 *stmt_name ? stmt_name : "<unnamed>",
1118 query_string)));
1121 * Start up a transaction command so we can run parse analysis etc. (Note
1122 * that this will normally change current memory context.) Nothing happens
1123 * if we are already in one.
1125 start_xact_command();
1128 * Switch to appropriate context for constructing parsetrees.
1130 * We have two strategies depending on whether the prepared statement is
1131 * named or not. For a named prepared statement, we do parsing in
1132 * MessageContext and copy the finished trees into the prepared
1133 * statement's plancache entry; then the reset of MessageContext releases
1134 * temporary space used by parsing and planning. For an unnamed prepared
1135 * statement, we assume the statement isn't going to hang around long, so
1136 * getting rid of temp space quickly is probably not worth the costs of
1137 * copying parse/plan trees. So in this case, we create the plancache
1138 * entry's context here, and do all the parsing work therein.
1140 is_named = (stmt_name[0] != '\0');
1141 if (is_named)
1143 /* Named prepared statement --- parse in MessageContext */
1144 oldcontext = MemoryContextSwitchTo(MessageContext);
1146 else
1148 /* Unnamed prepared statement --- release any prior unnamed stmt */
1149 drop_unnamed_stmt();
1150 /* Create context for parsing/planning */
1151 unnamed_stmt_context =
1152 AllocSetContextCreate(CacheMemoryContext,
1153 "unnamed prepared statement",
1154 ALLOCSET_DEFAULT_MINSIZE,
1155 ALLOCSET_DEFAULT_INITSIZE,
1156 ALLOCSET_DEFAULT_MAXSIZE);
1157 oldcontext = MemoryContextSwitchTo(unnamed_stmt_context);
1161 * Do basic parsing of the query or queries (this should be safe even if
1162 * we are in aborted transaction state!)
1164 parsetree_list = pg_parse_query(query_string);
1167 * We only allow a single user statement in a prepared statement. This is
1168 * mainly to keep the protocol simple --- otherwise we'd need to worry
1169 * about multiple result tupdescs and things like that.
1171 if (list_length(parsetree_list) > 1)
1172 ereport(ERROR,
1173 (errcode(ERRCODE_SYNTAX_ERROR),
1174 errmsg("cannot insert multiple commands into a prepared statement")));
1176 if (parsetree_list != NIL)
1178 Query *query;
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 * OK to analyze, rewrite, and plan this query. Note that the
1205 * originally specified parameter set is not required to be complete,
1206 * so we have to use parse_analyze_varparams().
1208 * XXX must use copyObject here since parse analysis scribbles on its
1209 * input, and we need the unmodified raw parse tree for possible
1210 * replanning later.
1212 if (log_parser_stats)
1213 ResetUsage();
1215 query = parse_analyze_varparams(copyObject(raw_parse_tree),
1216 query_string,
1217 &paramTypes,
1218 &numParams);
1221 * Check all parameter types got determined.
1223 for (i = 0; i < numParams; i++)
1225 Oid ptype = paramTypes[i];
1227 if (ptype == InvalidOid || ptype == UNKNOWNOID)
1228 ereport(ERROR,
1229 (errcode(ERRCODE_INDETERMINATE_DATATYPE),
1230 errmsg("could not determine data type of parameter $%d",
1231 i + 1)));
1234 if (log_parser_stats)
1235 ShowUsage("PARSE ANALYSIS STATISTICS");
1237 querytree_list = pg_rewrite_query(query);
1240 * If this is the unnamed statement and it has parameters, defer query
1241 * planning until Bind. Otherwise do it now.
1243 if (!is_named && numParams > 0)
1245 stmt_list = querytree_list;
1246 fully_planned = false;
1248 else
1250 stmt_list = pg_plan_queries(querytree_list, 0, NULL, true);
1251 fully_planned = true;
1254 else
1256 /* Empty input string. This is legal. */
1257 raw_parse_tree = NULL;
1258 commandTag = NULL;
1259 stmt_list = NIL;
1260 fully_planned = true;
1263 /* If we got a cancel signal in analysis or planning, quit */
1264 CHECK_FOR_INTERRUPTS();
1267 * Store the query as a prepared statement. See above comments.
1269 if (is_named)
1271 StorePreparedStatement(stmt_name,
1272 raw_parse_tree,
1273 query_string,
1274 commandTag,
1275 paramTypes,
1276 numParams,
1277 0, /* default cursor options */
1278 stmt_list,
1279 false);
1281 else
1284 * paramTypes and query_string need to be copied into
1285 * unnamed_stmt_context. The rest is there already
1287 Oid *newParamTypes;
1289 if (numParams > 0)
1291 newParamTypes = (Oid *) palloc(numParams * sizeof(Oid));
1292 memcpy(newParamTypes, paramTypes, numParams * sizeof(Oid));
1294 else
1295 newParamTypes = NULL;
1297 unnamed_stmt_psrc = FastCreateCachedPlan(raw_parse_tree,
1298 pstrdup(query_string),
1299 commandTag,
1300 newParamTypes,
1301 numParams,
1302 0, /* cursor options */
1303 stmt_list,
1304 fully_planned,
1305 true,
1306 unnamed_stmt_context);
1307 /* context now belongs to the plancache entry */
1308 unnamed_stmt_context = NULL;
1311 MemoryContextSwitchTo(oldcontext);
1314 * We do NOT close the open transaction command here; that only happens
1315 * when the client sends Sync. Instead, do CommandCounterIncrement just
1316 * in case something happened during parse/plan.
1318 CommandCounterIncrement();
1321 * Send ParseComplete.
1323 if (whereToSendOutput == DestRemote)
1324 pq_putemptymessage('1');
1327 * Emit duration logging if appropriate.
1329 switch (check_log_duration(msec_str, false))
1331 case 1:
1332 ereport(LOG,
1333 (errmsg("duration: %s ms", msec_str),
1334 errhidestmt(true)));
1335 break;
1336 case 2:
1337 ereport(LOG,
1338 (errmsg("duration: %s ms parse %s: %s",
1339 msec_str,
1340 *stmt_name ? stmt_name : "<unnamed>",
1341 query_string),
1342 errhidestmt(true)));
1343 break;
1346 if (save_log_statement_stats)
1347 ShowUsage("PARSE MESSAGE STATISTICS");
1349 debug_query_string = NULL;
1353 * exec_bind_message
1355 * Process a "Bind" message to create a portal from a prepared statement
1357 static void
1358 exec_bind_message(StringInfo input_message)
1360 const char *portal_name;
1361 const char *stmt_name;
1362 int numPFormats;
1363 int16 *pformats = NULL;
1364 int numParams;
1365 int numRFormats;
1366 int16 *rformats = NULL;
1367 CachedPlanSource *psrc;
1368 CachedPlan *cplan;
1369 Portal portal;
1370 char *query_string;
1371 char *saved_stmt_name;
1372 ParamListInfo params;
1373 List *plan_list;
1374 MemoryContext oldContext;
1375 bool save_log_statement_stats = log_statement_stats;
1376 char msec_str[32];
1378 /* Get the fixed part of the message */
1379 portal_name = pq_getmsgstring(input_message);
1380 stmt_name = pq_getmsgstring(input_message);
1382 ereport(DEBUG2,
1383 (errmsg("bind %s to %s",
1384 *portal_name ? portal_name : "<unnamed>",
1385 *stmt_name ? stmt_name : "<unnamed>")));
1387 /* Find prepared statement */
1388 if (stmt_name[0] != '\0')
1390 PreparedStatement *pstmt;
1392 pstmt = FetchPreparedStatement(stmt_name, true);
1393 psrc = pstmt->plansource;
1395 else
1397 /* special-case the unnamed statement */
1398 psrc = unnamed_stmt_psrc;
1399 if (!psrc)
1400 ereport(ERROR,
1401 (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
1402 errmsg("unnamed prepared statement does not exist")));
1406 * Report query to various monitoring facilities.
1408 debug_query_string = psrc->query_string;
1410 pgstat_report_activity(psrc->query_string);
1412 set_ps_display("BIND", false);
1414 if (save_log_statement_stats)
1415 ResetUsage();
1418 * Start up a transaction command so we can call functions etc. (Note that
1419 * this will normally change current memory context.) Nothing happens if
1420 * we are already in one.
1422 start_xact_command();
1424 /* Switch back to message context */
1425 MemoryContextSwitchTo(MessageContext);
1427 /* Get the parameter format codes */
1428 numPFormats = pq_getmsgint(input_message, 2);
1429 if (numPFormats > 0)
1431 int i;
1433 pformats = (int16 *) palloc(numPFormats * sizeof(int16));
1434 for (i = 0; i < numPFormats; i++)
1435 pformats[i] = pq_getmsgint(input_message, 2);
1438 /* Get the parameter value count */
1439 numParams = pq_getmsgint(input_message, 2);
1441 if (numPFormats > 1 && numPFormats != numParams)
1442 ereport(ERROR,
1443 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1444 errmsg("bind message has %d parameter formats but %d parameters",
1445 numPFormats, numParams)));
1447 if (numParams != psrc->num_params)
1448 ereport(ERROR,
1449 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1450 errmsg("bind message supplies %d parameters, but prepared statement \"%s\" requires %d",
1451 numParams, stmt_name, psrc->num_params)));
1454 * If we are in aborted transaction state, the only portals we can
1455 * actually run are those containing COMMIT or ROLLBACK commands. We
1456 * disallow binding anything else to avoid problems with infrastructure
1457 * that expects to run inside a valid transaction. We also disallow
1458 * binding any parameters, since we can't risk calling user-defined I/O
1459 * functions.
1461 if (IsAbortedTransactionBlockState() &&
1462 (!IsTransactionExitStmt(psrc->raw_parse_tree) ||
1463 numParams != 0))
1464 ereport(ERROR,
1465 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1466 errmsg("current transaction is aborted, "
1467 "commands ignored until end of transaction block")));
1470 * Create the portal. Allow silent replacement of an existing portal only
1471 * if the unnamed portal is specified.
1473 if (portal_name[0] == '\0')
1474 portal = CreatePortal(portal_name, true, true);
1475 else
1476 portal = CreatePortal(portal_name, false, false);
1479 * Prepare to copy stuff into the portal's memory context. We do all this
1480 * copying first, because it could possibly fail (out-of-memory) and we
1481 * don't want a failure to occur between RevalidateCachedPlan and
1482 * PortalDefineQuery; that would result in leaking our plancache refcount.
1484 oldContext = MemoryContextSwitchTo(PortalGetHeapMemory(portal));
1486 /* Copy the plan's query string into the portal */
1487 query_string = pstrdup(psrc->query_string);
1489 /* Likewise make a copy of the statement name, unless it's unnamed */
1490 if (stmt_name[0])
1491 saved_stmt_name = pstrdup(stmt_name);
1492 else
1493 saved_stmt_name = NULL;
1496 * Fetch parameters, if any, and store in the portal's memory context.
1498 if (numParams > 0)
1500 int paramno;
1502 /* sizeof(ParamListInfoData) includes the first array element */
1503 params = (ParamListInfo) palloc(sizeof(ParamListInfoData) +
1504 (numParams - 1) *sizeof(ParamExternData));
1505 params->numParams = numParams;
1507 for (paramno = 0; paramno < numParams; paramno++)
1509 Oid ptype = psrc->param_types[paramno];
1510 int32 plength;
1511 Datum pval;
1512 bool isNull;
1513 StringInfoData pbuf;
1514 char csave;
1515 int16 pformat;
1517 plength = pq_getmsgint(input_message, 4);
1518 isNull = (plength == -1);
1520 if (!isNull)
1522 const char *pvalue = pq_getmsgbytes(input_message, plength);
1525 * Rather than copying data around, we just set up a phony
1526 * StringInfo pointing to the correct portion of the message
1527 * buffer. We assume we can scribble on the message buffer so
1528 * as to maintain the convention that StringInfos have a
1529 * trailing null. This is grotty but is a big win when
1530 * dealing with very large parameter strings.
1532 pbuf.data = (char *) pvalue;
1533 pbuf.maxlen = plength + 1;
1534 pbuf.len = plength;
1535 pbuf.cursor = 0;
1537 csave = pbuf.data[plength];
1538 pbuf.data[plength] = '\0';
1540 else
1542 pbuf.data = NULL; /* keep compiler quiet */
1543 csave = 0;
1546 if (numPFormats > 1)
1547 pformat = pformats[paramno];
1548 else if (numPFormats > 0)
1549 pformat = pformats[0];
1550 else
1551 pformat = 0; /* default = text */
1553 if (pformat == 0) /* text mode */
1555 Oid typinput;
1556 Oid typioparam;
1557 char *pstring;
1559 getTypeInputInfo(ptype, &typinput, &typioparam);
1562 * We have to do encoding conversion before calling the
1563 * typinput routine.
1565 if (isNull)
1566 pstring = NULL;
1567 else
1568 pstring = pg_client_to_server(pbuf.data, plength);
1570 pval = OidInputFunctionCall(typinput, pstring, typioparam, -1);
1572 /* Free result of encoding conversion, if any */
1573 if (pstring && pstring != pbuf.data)
1574 pfree(pstring);
1576 else if (pformat == 1) /* binary mode */
1578 Oid typreceive;
1579 Oid typioparam;
1580 StringInfo bufptr;
1583 * Call the parameter type's binary input converter
1585 getTypeBinaryInputInfo(ptype, &typreceive, &typioparam);
1587 if (isNull)
1588 bufptr = NULL;
1589 else
1590 bufptr = &pbuf;
1592 pval = OidReceiveFunctionCall(typreceive, bufptr, typioparam, -1);
1594 /* Trouble if it didn't eat the whole buffer */
1595 if (!isNull && pbuf.cursor != pbuf.len)
1596 ereport(ERROR,
1597 (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
1598 errmsg("incorrect binary data format in bind parameter %d",
1599 paramno + 1)));
1601 else
1603 ereport(ERROR,
1604 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1605 errmsg("unsupported format code: %d",
1606 pformat)));
1607 pval = 0; /* keep compiler quiet */
1610 /* Restore message buffer contents */
1611 if (!isNull)
1612 pbuf.data[plength] = csave;
1614 params->params[paramno].value = pval;
1615 params->params[paramno].isnull = isNull;
1618 * We mark the params as CONST. This has no effect if we already
1619 * did planning, but if we didn't, it licenses the planner to
1620 * substitute the parameters directly into the one-shot plan we
1621 * will generate below.
1623 params->params[paramno].pflags = PARAM_FLAG_CONST;
1624 params->params[paramno].ptype = ptype;
1627 else
1628 params = NULL;
1630 /* Done storing stuff in portal's context */
1631 MemoryContextSwitchTo(oldContext);
1633 /* Get the result format codes */
1634 numRFormats = pq_getmsgint(input_message, 2);
1635 if (numRFormats > 0)
1637 int i;
1639 rformats = (int16 *) palloc(numRFormats * sizeof(int16));
1640 for (i = 0; i < numRFormats; i++)
1641 rformats[i] = pq_getmsgint(input_message, 2);
1644 pq_getmsgend(input_message);
1646 if (psrc->fully_planned)
1649 * Revalidate the cached plan; this may result in replanning. Any
1650 * cruft will be generated in MessageContext. The plan refcount will
1651 * be assigned to the Portal, so it will be released at portal
1652 * destruction.
1654 cplan = RevalidateCachedPlan(psrc, false);
1655 plan_list = cplan->stmt_list;
1657 else
1659 List *query_list;
1662 * Revalidate the cached plan; this may result in redoing parse
1663 * analysis and rewriting (but not planning). Any cruft will be
1664 * generated in MessageContext. The plan refcount is assigned to
1665 * CurrentResourceOwner.
1667 cplan = RevalidateCachedPlan(psrc, true);
1670 * We didn't plan the query before, so do it now. This allows the
1671 * planner to make use of the concrete parameter values we now have.
1672 * Because we use PARAM_FLAG_CONST, the plan is good only for this set
1673 * of param values, and so we generate the plan in the portal's own
1674 * memory context where it will be thrown away after use. As in
1675 * exec_parse_message, we make no attempt to recover planner temporary
1676 * memory until the end of the operation.
1678 * XXX because the planner has a bad habit of scribbling on its input,
1679 * we have to make a copy of the parse trees. FIXME someday.
1681 oldContext = MemoryContextSwitchTo(PortalGetHeapMemory(portal));
1682 query_list = copyObject(cplan->stmt_list);
1683 plan_list = pg_plan_queries(query_list, 0, params, true);
1684 MemoryContextSwitchTo(oldContext);
1686 /* We no longer need the cached plan refcount ... */
1687 ReleaseCachedPlan(cplan, true);
1688 /* ... and we don't want the portal to depend on it, either */
1689 cplan = NULL;
1693 * Define portal and start execution.
1695 PortalDefineQuery(portal,
1696 saved_stmt_name,
1697 query_string,
1698 psrc->commandTag,
1699 plan_list,
1700 cplan);
1702 PortalStart(portal, params, InvalidSnapshot);
1705 * Apply the result format requests to the portal.
1707 PortalSetResultFormat(portal, numRFormats, rformats);
1710 * Send BindComplete.
1712 if (whereToSendOutput == DestRemote)
1713 pq_putemptymessage('2');
1716 * Emit duration logging if appropriate.
1718 switch (check_log_duration(msec_str, false))
1720 case 1:
1721 ereport(LOG,
1722 (errmsg("duration: %s ms", msec_str),
1723 errhidestmt(true)));
1724 break;
1725 case 2:
1726 ereport(LOG,
1727 (errmsg("duration: %s ms bind %s%s%s: %s",
1728 msec_str,
1729 *stmt_name ? stmt_name : "<unnamed>",
1730 *portal_name ? "/" : "",
1731 *portal_name ? portal_name : "",
1732 psrc->query_string),
1733 errhidestmt(true),
1734 errdetail_params(params)));
1735 break;
1738 if (save_log_statement_stats)
1739 ShowUsage("BIND MESSAGE STATISTICS");
1741 debug_query_string = NULL;
1745 * exec_execute_message
1747 * Process an "Execute" message for a portal
1749 static void
1750 exec_execute_message(const char *portal_name, long max_rows)
1752 CommandDest dest;
1753 DestReceiver *receiver;
1754 Portal portal;
1755 bool completed;
1756 char completionTag[COMPLETION_TAG_BUFSIZE];
1757 const char *sourceText;
1758 const char *prepStmtName;
1759 ParamListInfo portalParams;
1760 bool save_log_statement_stats = log_statement_stats;
1761 bool is_xact_command;
1762 bool execute_is_fetch;
1763 bool was_logged = false;
1764 char msec_str[32];
1766 /* Adjust destination to tell printtup.c what to do */
1767 dest = whereToSendOutput;
1768 if (dest == DestRemote)
1769 dest = DestRemoteExecute;
1771 portal = GetPortalByName(portal_name);
1772 if (!PortalIsValid(portal))
1773 ereport(ERROR,
1774 (errcode(ERRCODE_UNDEFINED_CURSOR),
1775 errmsg("portal \"%s\" does not exist", portal_name)));
1778 * If the original query was a null string, just return
1779 * EmptyQueryResponse.
1781 if (portal->commandTag == NULL)
1783 Assert(portal->stmts == NIL);
1784 NullCommand(dest);
1785 return;
1788 /* Does the portal contain a transaction command? */
1789 is_xact_command = IsTransactionStmtList(portal->stmts);
1792 * We must copy the sourceText and prepStmtName into MessageContext in
1793 * case the portal is destroyed during finish_xact_command. Can avoid the
1794 * copy if it's not an xact command, though.
1796 if (is_xact_command)
1798 sourceText = pstrdup(portal->sourceText);
1799 if (portal->prepStmtName)
1800 prepStmtName = pstrdup(portal->prepStmtName);
1801 else
1802 prepStmtName = "<unnamed>";
1805 * An xact command shouldn't have any parameters, which is a good
1806 * thing because they wouldn't be around after finish_xact_command.
1808 portalParams = NULL;
1810 else
1812 sourceText = portal->sourceText;
1813 if (portal->prepStmtName)
1814 prepStmtName = portal->prepStmtName;
1815 else
1816 prepStmtName = "<unnamed>";
1817 portalParams = portal->portalParams;
1821 * Report query to various monitoring facilities.
1823 debug_query_string = sourceText;
1825 pgstat_report_activity(sourceText);
1827 set_ps_display(portal->commandTag, false);
1829 if (save_log_statement_stats)
1830 ResetUsage();
1832 BeginCommand(portal->commandTag, dest);
1835 * Create dest receiver in MessageContext (we don't want it in transaction
1836 * context, because that may get deleted if portal contains VACUUM).
1838 receiver = CreateDestReceiver(dest, portal);
1841 * Ensure we are in a transaction command (this should normally be the
1842 * case already due to prior BIND).
1844 start_xact_command();
1847 * If we re-issue an Execute protocol request against an existing portal,
1848 * then we are only fetching more rows rather than completely re-executing
1849 * the query from the start. atStart is never reset for a v3 portal, so we
1850 * are safe to use this check.
1852 execute_is_fetch = !portal->atStart;
1854 /* Log immediately if dictated by log_statement */
1855 if (check_log_statement(portal->stmts))
1857 ereport(LOG,
1858 (errmsg("%s %s%s%s: %s",
1859 execute_is_fetch ?
1860 _("execute fetch from") :
1861 _("execute"),
1862 prepStmtName,
1863 *portal_name ? "/" : "",
1864 *portal_name ? portal_name : "",
1865 sourceText),
1866 errhidestmt(true),
1867 errdetail_params(portalParams)));
1868 was_logged = true;
1872 * If we are in aborted transaction state, the only portals we can
1873 * actually run are those containing COMMIT or ROLLBACK commands.
1875 if (IsAbortedTransactionBlockState() &&
1876 !IsTransactionExitStmtList(portal->stmts))
1877 ereport(ERROR,
1878 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1879 errmsg("current transaction is aborted, "
1880 "commands ignored until end of transaction block")));
1882 /* Check for cancel signal before we start execution */
1883 CHECK_FOR_INTERRUPTS();
1886 * Okay to run the portal.
1888 if (max_rows <= 0)
1889 max_rows = FETCH_ALL;
1891 completed = PortalRun(portal,
1892 max_rows,
1893 true, /* always top level */
1894 receiver,
1895 receiver,
1896 completionTag);
1898 (*receiver->rDestroy) (receiver);
1900 if (completed)
1902 if (is_xact_command)
1905 * If this was a transaction control statement, commit it. We
1906 * will start a new xact command for the next command (if any).
1908 finish_xact_command();
1910 else
1913 * We need a CommandCounterIncrement after every query, except
1914 * those that start or end a transaction block.
1916 CommandCounterIncrement();
1919 /* Send appropriate CommandComplete to client */
1920 EndCommand(completionTag, dest);
1922 else
1924 /* Portal run not complete, so send PortalSuspended */
1925 if (whereToSendOutput == DestRemote)
1926 pq_putemptymessage('s');
1930 * Emit duration logging if appropriate.
1932 switch (check_log_duration(msec_str, was_logged))
1934 case 1:
1935 ereport(LOG,
1936 (errmsg("duration: %s ms", msec_str),
1937 errhidestmt(true)));
1938 break;
1939 case 2:
1940 ereport(LOG,
1941 (errmsg("duration: %s ms %s %s%s%s: %s",
1942 msec_str,
1943 execute_is_fetch ?
1944 _("execute fetch from") :
1945 _("execute"),
1946 prepStmtName,
1947 *portal_name ? "/" : "",
1948 *portal_name ? portal_name : "",
1949 sourceText),
1950 errhidestmt(true),
1951 errdetail_params(portalParams)));
1952 break;
1955 if (save_log_statement_stats)
1956 ShowUsage("EXECUTE MESSAGE STATISTICS");
1958 debug_query_string = NULL;
1962 * check_log_statement
1963 * Determine whether command should be logged because of log_statement
1965 * parsetree_list can be either raw grammar output or a list of planned
1966 * statements
1968 static bool
1969 check_log_statement(List *stmt_list)
1971 ListCell *stmt_item;
1973 if (log_statement == LOGSTMT_NONE)
1974 return false;
1975 if (log_statement == LOGSTMT_ALL)
1976 return true;
1978 /* Else we have to inspect the statement(s) to see whether to log */
1979 foreach(stmt_item, stmt_list)
1981 Node *stmt = (Node *) lfirst(stmt_item);
1983 if (GetCommandLogLevel(stmt) <= log_statement)
1984 return true;
1987 return false;
1991 * check_log_duration
1992 * Determine whether current command's duration should be logged
1994 * Returns:
1995 * 0 if no logging is needed
1996 * 1 if just the duration should be logged
1997 * 2 if duration and query details should be logged
1999 * If logging is needed, the duration in msec is formatted into msec_str[],
2000 * which must be a 32-byte buffer.
2002 * was_logged should be TRUE if caller already logged query details (this
2003 * essentially prevents 2 from being returned).
2006 check_log_duration(char *msec_str, bool was_logged)
2008 if (log_duration || log_min_duration_statement >= 0)
2010 long secs;
2011 int usecs;
2012 int msecs;
2013 bool exceeded;
2015 TimestampDifference(GetCurrentStatementStartTimestamp(),
2016 GetCurrentTimestamp(),
2017 &secs, &usecs);
2018 msecs = usecs / 1000;
2021 * This odd-looking test for log_min_duration_statement being exceeded
2022 * is designed to avoid integer overflow with very long durations:
2023 * don't compute secs * 1000 until we've verified it will fit in int.
2025 exceeded = (log_min_duration_statement == 0 ||
2026 (log_min_duration_statement > 0 &&
2027 (secs > log_min_duration_statement / 1000 ||
2028 secs * 1000 + msecs >= log_min_duration_statement)));
2030 if (exceeded || log_duration)
2032 snprintf(msec_str, 32, "%ld.%03d",
2033 secs * 1000 + msecs, usecs % 1000);
2034 if (exceeded && !was_logged)
2035 return 2;
2036 else
2037 return 1;
2041 return 0;
2045 * errdetail_execute
2047 * Add an errdetail() line showing the query referenced by an EXECUTE, if any.
2048 * The argument is the raw parsetree list.
2050 static int
2051 errdetail_execute(List *raw_parsetree_list)
2053 ListCell *parsetree_item;
2055 foreach(parsetree_item, raw_parsetree_list)
2057 Node *parsetree = (Node *) lfirst(parsetree_item);
2059 if (IsA(parsetree, ExecuteStmt))
2061 ExecuteStmt *stmt = (ExecuteStmt *) parsetree;
2062 PreparedStatement *pstmt;
2064 pstmt = FetchPreparedStatement(stmt->name, false);
2065 if (pstmt)
2067 errdetail("prepare: %s", pstmt->plansource->query_string);
2068 return 0;
2073 return 0;
2077 * errdetail_params
2079 * Add an errdetail() line showing bind-parameter data, if available.
2081 static int
2082 errdetail_params(ParamListInfo params)
2084 /* We mustn't call user-defined I/O functions when in an aborted xact */
2085 if (params && params->numParams > 0 && !IsAbortedTransactionBlockState())
2087 StringInfoData param_str;
2088 MemoryContext oldcontext;
2089 int paramno;
2091 /* Make sure any trash is generated in MessageContext */
2092 oldcontext = MemoryContextSwitchTo(MessageContext);
2094 initStringInfo(&param_str);
2096 for (paramno = 0; paramno < params->numParams; paramno++)
2098 ParamExternData *prm = &params->params[paramno];
2099 Oid typoutput;
2100 bool typisvarlena;
2101 char *pstring;
2102 char *p;
2104 appendStringInfo(&param_str, "%s$%d = ",
2105 paramno > 0 ? ", " : "",
2106 paramno + 1);
2108 if (prm->isnull || !OidIsValid(prm->ptype))
2110 appendStringInfoString(&param_str, "NULL");
2111 continue;
2114 getTypeOutputInfo(prm->ptype, &typoutput, &typisvarlena);
2116 pstring = OidOutputFunctionCall(typoutput, prm->value);
2118 appendStringInfoCharMacro(&param_str, '\'');
2119 for (p = pstring; *p; p++)
2121 if (*p == '\'') /* double single quotes */
2122 appendStringInfoCharMacro(&param_str, *p);
2123 appendStringInfoCharMacro(&param_str, *p);
2125 appendStringInfoCharMacro(&param_str, '\'');
2127 pfree(pstring);
2130 errdetail("parameters: %s", param_str.data);
2132 pfree(param_str.data);
2134 MemoryContextSwitchTo(oldcontext);
2137 return 0;
2141 * exec_describe_statement_message
2143 * Process a "Describe" message for a prepared statement
2145 static void
2146 exec_describe_statement_message(const char *stmt_name)
2148 CachedPlanSource *psrc;
2149 StringInfoData buf;
2150 int i;
2153 * Start up a transaction command. (Note that this will normally change
2154 * current memory context.) Nothing happens if we are already in one.
2156 start_xact_command();
2158 /* Switch back to message context */
2159 MemoryContextSwitchTo(MessageContext);
2161 /* Find prepared statement */
2162 if (stmt_name[0] != '\0')
2164 PreparedStatement *pstmt;
2166 pstmt = FetchPreparedStatement(stmt_name, true);
2167 psrc = pstmt->plansource;
2169 else
2171 /* special-case the unnamed statement */
2172 psrc = unnamed_stmt_psrc;
2173 if (!psrc)
2174 ereport(ERROR,
2175 (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
2176 errmsg("unnamed prepared statement does not exist")));
2179 /* Prepared statements shouldn't have changeable result descs */
2180 Assert(psrc->fixed_result);
2183 * If we are in aborted transaction state, we can't run
2184 * SendRowDescriptionMessage(), because that needs catalog accesses. (We
2185 * can't do RevalidateCachedPlan, either, but that's a lesser problem.)
2186 * Hence, refuse to Describe statements that return data. (We shouldn't
2187 * just refuse all Describes, since that might break the ability of some
2188 * clients to issue COMMIT or ROLLBACK commands, if they use code that
2189 * blindly Describes whatever it does.) We can Describe parameters
2190 * without doing anything dangerous, so we don't restrict that.
2192 if (IsAbortedTransactionBlockState() &&
2193 psrc->resultDesc)
2194 ereport(ERROR,
2195 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2196 errmsg("current transaction is aborted, "
2197 "commands ignored until end of transaction block")));
2199 if (whereToSendOutput != DestRemote)
2200 return; /* can't actually do anything... */
2203 * First describe the parameters...
2205 pq_beginmessage(&buf, 't'); /* parameter description message type */
2206 pq_sendint(&buf, psrc->num_params, 2);
2208 for (i = 0; i < psrc->num_params; i++)
2210 Oid ptype = psrc->param_types[i];
2212 pq_sendint(&buf, (int) ptype, 4);
2214 pq_endmessage(&buf);
2217 * Next send RowDescription or NoData to describe the result...
2219 if (psrc->resultDesc)
2221 CachedPlan *cplan;
2222 List *tlist;
2224 /* Make sure the plan is up to date */
2225 cplan = RevalidateCachedPlan(psrc, true);
2227 /* Get the primary statement and find out what it returns */
2228 tlist = FetchStatementTargetList(PortalListGetPrimaryStmt(cplan->stmt_list));
2230 SendRowDescriptionMessage(psrc->resultDesc, tlist, NULL);
2232 ReleaseCachedPlan(cplan, true);
2234 else
2235 pq_putemptymessage('n'); /* NoData */
2240 * exec_describe_portal_message
2242 * Process a "Describe" message for a portal
2244 static void
2245 exec_describe_portal_message(const char *portal_name)
2247 Portal portal;
2250 * Start up a transaction command. (Note that this will normally change
2251 * current memory context.) Nothing happens if we are already in one.
2253 start_xact_command();
2255 /* Switch back to message context */
2256 MemoryContextSwitchTo(MessageContext);
2258 portal = GetPortalByName(portal_name);
2259 if (!PortalIsValid(portal))
2260 ereport(ERROR,
2261 (errcode(ERRCODE_UNDEFINED_CURSOR),
2262 errmsg("portal \"%s\" does not exist", portal_name)));
2265 * If we are in aborted transaction state, we can't run
2266 * SendRowDescriptionMessage(), because that needs catalog accesses.
2267 * Hence, refuse to Describe portals that return data. (We shouldn't just
2268 * refuse all Describes, since that might break the ability of some
2269 * clients to issue COMMIT or ROLLBACK commands, if they use code that
2270 * blindly Describes whatever it does.)
2272 if (IsAbortedTransactionBlockState() &&
2273 portal->tupDesc)
2274 ereport(ERROR,
2275 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2276 errmsg("current transaction is aborted, "
2277 "commands ignored until end of transaction block")));
2279 if (whereToSendOutput != DestRemote)
2280 return; /* can't actually do anything... */
2282 if (portal->tupDesc)
2283 SendRowDescriptionMessage(portal->tupDesc,
2284 FetchPortalTargetList(portal),
2285 portal->formats);
2286 else
2287 pq_putemptymessage('n'); /* NoData */
2292 * Convenience routines for starting/committing a single command.
2294 static void
2295 start_xact_command(void)
2297 if (!xact_started)
2299 ereport(DEBUG3,
2300 (errmsg_internal("StartTransactionCommand")));
2301 StartTransactionCommand();
2303 /* Set statement timeout running, if any */
2304 /* NB: this mustn't be enabled until we are within an xact */
2305 if (StatementTimeout > 0)
2306 enable_sig_alarm(StatementTimeout, true);
2307 else
2308 cancel_from_timeout = false;
2310 xact_started = true;
2314 static void
2315 finish_xact_command(void)
2317 if (xact_started)
2319 /* Cancel any active statement timeout before committing */
2320 disable_sig_alarm(true);
2322 /* Now commit the command */
2323 ereport(DEBUG3,
2324 (errmsg_internal("CommitTransactionCommand")));
2326 CommitTransactionCommand();
2328 #ifdef MEMORY_CONTEXT_CHECKING
2329 /* Check all memory contexts that weren't freed during commit */
2330 /* (those that were, were checked before being deleted) */
2331 MemoryContextCheck(TopMemoryContext);
2332 #endif
2334 #ifdef SHOW_MEMORY_STATS
2335 /* Print mem stats after each commit for leak tracking */
2336 MemoryContextStats(TopMemoryContext);
2337 #endif
2339 xact_started = false;
2345 * Convenience routines for checking whether a statement is one of the
2346 * ones that we allow in transaction-aborted state.
2349 /* Test a bare parsetree */
2350 static bool
2351 IsTransactionExitStmt(Node *parsetree)
2353 if (parsetree && IsA(parsetree, TransactionStmt))
2355 TransactionStmt *stmt = (TransactionStmt *) parsetree;
2357 if (stmt->kind == TRANS_STMT_COMMIT ||
2358 stmt->kind == TRANS_STMT_PREPARE ||
2359 stmt->kind == TRANS_STMT_ROLLBACK ||
2360 stmt->kind == TRANS_STMT_ROLLBACK_TO)
2361 return true;
2363 return false;
2366 /* Test a list that might contain Query nodes or bare parsetrees */
2367 static bool
2368 IsTransactionExitStmtList(List *parseTrees)
2370 if (list_length(parseTrees) == 1)
2372 Node *stmt = (Node *) linitial(parseTrees);
2374 if (IsA(stmt, Query))
2376 Query *query = (Query *) stmt;
2378 if (query->commandType == CMD_UTILITY &&
2379 IsTransactionExitStmt(query->utilityStmt))
2380 return true;
2382 else if (IsTransactionExitStmt(stmt))
2383 return true;
2385 return false;
2388 /* Test a list that might contain Query nodes or bare parsetrees */
2389 static bool
2390 IsTransactionStmtList(List *parseTrees)
2392 if (list_length(parseTrees) == 1)
2394 Node *stmt = (Node *) linitial(parseTrees);
2396 if (IsA(stmt, Query))
2398 Query *query = (Query *) stmt;
2400 if (query->commandType == CMD_UTILITY &&
2401 IsA(query->utilityStmt, TransactionStmt))
2402 return true;
2404 else if (IsA(stmt, TransactionStmt))
2405 return true;
2407 return false;
2410 /* Release any existing unnamed prepared statement */
2411 static void
2412 drop_unnamed_stmt(void)
2414 /* Release any completed unnamed statement */
2415 if (unnamed_stmt_psrc)
2416 DropCachedPlan(unnamed_stmt_psrc);
2417 unnamed_stmt_psrc = NULL;
2420 * If we failed while trying to build a prior unnamed statement, we may
2421 * have a memory context that wasn't assigned to a completed plancache
2422 * entry. If so, drop it to avoid a permanent memory leak.
2424 if (unnamed_stmt_context)
2425 MemoryContextDelete(unnamed_stmt_context);
2426 unnamed_stmt_context = NULL;
2430 /* --------------------------------
2431 * signal handler routines used in PostgresMain()
2432 * --------------------------------
2436 * quickdie() occurs when signalled SIGQUIT by the postmaster.
2438 * Some backend has bought the farm,
2439 * so we need to stop what we're doing and exit.
2441 void
2442 quickdie(SIGNAL_ARGS)
2444 PG_SETMASK(&BlockSig);
2447 * Ideally this should be ereport(FATAL), but then we'd not get control
2448 * back...
2450 ereport(WARNING,
2451 (errcode(ERRCODE_CRASH_SHUTDOWN),
2452 errmsg("terminating connection because of crash of another server process"),
2453 errdetail("The postmaster has commanded this server process to roll back"
2454 " the current transaction and exit, because another"
2455 " server process exited abnormally and possibly corrupted"
2456 " shared memory."),
2457 errhint("In a moment you should be able to reconnect to the"
2458 " database and repeat your command.")));
2461 * DO NOT proc_exit() -- we're here because shared memory may be
2462 * corrupted, so we don't want to try to clean up our transaction. Just
2463 * nail the windows shut and get out of town.
2465 * Note we do exit(2) not exit(0). This is to force the postmaster into a
2466 * system reset cycle if some idiot DBA sends a manual SIGQUIT to a random
2467 * backend. This is necessary precisely because we don't clean up our
2468 * shared memory state.
2470 exit(2);
2474 * Shutdown signal from postmaster: abort transaction and exit
2475 * at soonest convenient time
2477 void
2478 die(SIGNAL_ARGS)
2480 int save_errno = errno;
2482 /* Don't joggle the elbow of proc_exit */
2483 if (!proc_exit_inprogress)
2485 InterruptPending = true;
2486 ProcDiePending = true;
2489 * If it's safe to interrupt, and we're waiting for input or a lock,
2490 * service the interrupt immediately
2492 if (ImmediateInterruptOK && InterruptHoldoffCount == 0 &&
2493 CritSectionCount == 0)
2495 /* bump holdoff count to make ProcessInterrupts() a no-op */
2496 /* until we are done getting ready for it */
2497 InterruptHoldoffCount++;
2498 LockWaitCancel(); /* prevent CheckDeadLock from running */
2499 DisableNotifyInterrupt();
2500 DisableCatchupInterrupt();
2501 InterruptHoldoffCount--;
2502 ProcessInterrupts();
2506 errno = save_errno;
2510 * Timeout or shutdown signal from postmaster during client authentication.
2511 * Simply exit(1).
2513 * XXX: possible future improvement: try to send a message indicating
2514 * why we are disconnecting. Problem is to be sure we don't block while
2515 * doing so, nor mess up the authentication message exchange.
2517 void
2518 authdie(SIGNAL_ARGS)
2520 exit(1);
2524 * Query-cancel signal from postmaster: abort current transaction
2525 * at soonest convenient time
2527 void
2528 StatementCancelHandler(SIGNAL_ARGS)
2530 int save_errno = errno;
2533 * Don't joggle the elbow of proc_exit
2535 if (!proc_exit_inprogress)
2537 InterruptPending = true;
2538 QueryCancelPending = true;
2541 * If it's safe to interrupt, and we're waiting for a lock, service
2542 * the interrupt immediately. No point in interrupting if we're
2543 * waiting for input, however.
2545 if (ImmediateInterruptOK && InterruptHoldoffCount == 0 &&
2546 CritSectionCount == 0 && !DoingCommandRead)
2548 /* bump holdoff count to make ProcessInterrupts() a no-op */
2549 /* until we are done getting ready for it */
2550 InterruptHoldoffCount++;
2551 LockWaitCancel(); /* prevent CheckDeadLock from running */
2552 DisableNotifyInterrupt();
2553 DisableCatchupInterrupt();
2554 InterruptHoldoffCount--;
2555 ProcessInterrupts();
2559 errno = save_errno;
2562 /* signal handler for floating point exception */
2563 void
2564 FloatExceptionHandler(SIGNAL_ARGS)
2566 ereport(ERROR,
2567 (errcode(ERRCODE_FLOATING_POINT_EXCEPTION),
2568 errmsg("floating-point exception"),
2569 errdetail("An invalid floating-point operation was signaled. "
2570 "This probably means an out-of-range result or an "
2571 "invalid operation, such as division by zero.")));
2574 /* SIGHUP: set flag to re-read config file at next convenient time */
2575 static void
2576 SigHupHandler(SIGNAL_ARGS)
2578 got_SIGHUP = true;
2583 * ProcessInterrupts: out-of-line portion of CHECK_FOR_INTERRUPTS() macro
2585 * If an interrupt condition is pending, and it's safe to service it,
2586 * then clear the flag and accept the interrupt. Called only when
2587 * InterruptPending is true.
2589 void
2590 ProcessInterrupts(void)
2592 /* OK to accept interrupt now? */
2593 if (InterruptHoldoffCount != 0 || CritSectionCount != 0)
2594 return;
2595 InterruptPending = false;
2596 if (ProcDiePending)
2598 ProcDiePending = false;
2599 QueryCancelPending = false; /* ProcDie trumps QueryCancel */
2600 ImmediateInterruptOK = false; /* not idle anymore */
2601 DisableNotifyInterrupt();
2602 DisableCatchupInterrupt();
2603 if (IsAutoVacuumWorkerProcess())
2604 ereport(FATAL,
2605 (errcode(ERRCODE_ADMIN_SHUTDOWN),
2606 errmsg("terminating autovacuum process due to administrator command")));
2607 else
2608 ereport(FATAL,
2609 (errcode(ERRCODE_ADMIN_SHUTDOWN),
2610 errmsg("terminating connection due to administrator command")));
2612 if (QueryCancelPending)
2614 QueryCancelPending = false;
2615 ImmediateInterruptOK = false; /* not idle anymore */
2616 DisableNotifyInterrupt();
2617 DisableCatchupInterrupt();
2618 if (cancel_from_timeout)
2619 ereport(ERROR,
2620 (errcode(ERRCODE_QUERY_CANCELED),
2621 errmsg("canceling statement due to statement timeout")));
2622 else if (IsAutoVacuumWorkerProcess())
2623 ereport(ERROR,
2624 (errcode(ERRCODE_QUERY_CANCELED),
2625 errmsg("canceling autovacuum task")));
2626 else
2627 ereport(ERROR,
2628 (errcode(ERRCODE_QUERY_CANCELED),
2629 errmsg("canceling statement due to user request")));
2631 /* If we get here, do nothing (probably, QueryCancelPending was reset) */
2636 * check_stack_depth: check for excessively deep recursion
2638 * This should be called someplace in any recursive routine that might possibly
2639 * recurse deep enough to overflow the stack. Most Unixen treat stack
2640 * overflow as an unrecoverable SIGSEGV, so we want to error out ourselves
2641 * before hitting the hardware limit.
2643 void
2644 check_stack_depth(void)
2646 char stack_top_loc;
2647 long stack_depth;
2650 * Compute distance from PostgresMain's local variables to my own
2652 stack_depth = (long) (stack_base_ptr - &stack_top_loc);
2655 * Take abs value, since stacks grow up on some machines, down on others
2657 if (stack_depth < 0)
2658 stack_depth = -stack_depth;
2661 * Trouble?
2663 * The test on stack_base_ptr prevents us from erroring out if called
2664 * during process setup or in a non-backend process. Logically it should
2665 * be done first, but putting it here avoids wasting cycles during normal
2666 * cases.
2668 if (stack_depth > max_stack_depth_bytes &&
2669 stack_base_ptr != NULL)
2671 ereport(ERROR,
2672 (errcode(ERRCODE_STATEMENT_TOO_COMPLEX),
2673 errmsg("stack depth limit exceeded"),
2674 errhint("Increase the configuration parameter \"max_stack_depth\", "
2675 "after ensuring the platform's stack depth limit is adequate.")));
2679 /* GUC assign hook for max_stack_depth */
2680 bool
2681 assign_max_stack_depth(int newval, bool doit, GucSource source)
2683 long newval_bytes = newval * 1024L;
2684 long stack_rlimit = get_stack_depth_rlimit();
2686 if (stack_rlimit > 0 && newval_bytes > stack_rlimit - STACK_DEPTH_SLOP)
2688 ereport(GUC_complaint_elevel(source),
2689 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2690 errmsg("\"max_stack_depth\" must not exceed %ldkB",
2691 (stack_rlimit - STACK_DEPTH_SLOP) / 1024L),
2692 errhint("Increase the platform's stack depth limit via \"ulimit -s\" or local equivalent.")));
2693 return false;
2695 if (doit)
2696 max_stack_depth_bytes = newval_bytes;
2697 return true;
2702 * set_debug_options --- apply "-d N" command line option
2704 * -d is not quite the same as setting log_min_messages because it enables
2705 * other output options.
2707 void
2708 set_debug_options(int debug_flag, GucContext context, GucSource source)
2710 if (debug_flag > 0)
2712 char debugstr[64];
2714 sprintf(debugstr, "debug%d", debug_flag);
2715 SetConfigOption("log_min_messages", debugstr, context, source);
2717 else
2718 SetConfigOption("log_min_messages", "notice", context, source);
2720 if (debug_flag >= 1 && context == PGC_POSTMASTER)
2722 SetConfigOption("log_connections", "true", context, source);
2723 SetConfigOption("log_disconnections", "true", context, source);
2725 if (debug_flag >= 2)
2726 SetConfigOption("log_statement", "all", context, source);
2727 if (debug_flag >= 3)
2728 SetConfigOption("debug_print_parse", "true", context, source);
2729 if (debug_flag >= 4)
2730 SetConfigOption("debug_print_plan", "true", context, source);
2731 if (debug_flag >= 5)
2732 SetConfigOption("debug_print_rewritten", "true", context, source);
2736 bool
2737 set_plan_disabling_options(const char *arg, GucContext context, GucSource source)
2739 char *tmp = NULL;
2741 switch (arg[0])
2743 case 's': /* seqscan */
2744 tmp = "enable_seqscan";
2745 break;
2746 case 'i': /* indexscan */
2747 tmp = "enable_indexscan";
2748 break;
2749 case 'b': /* bitmapscan */
2750 tmp = "enable_bitmapscan";
2751 break;
2752 case 't': /* tidscan */
2753 tmp = "enable_tidscan";
2754 break;
2755 case 'n': /* nestloop */
2756 tmp = "enable_nestloop";
2757 break;
2758 case 'm': /* mergejoin */
2759 tmp = "enable_mergejoin";
2760 break;
2761 case 'h': /* hashjoin */
2762 tmp = "enable_hashjoin";
2763 break;
2765 if (tmp)
2767 SetConfigOption(tmp, "false", context, source);
2768 return true;
2770 else
2771 return false;
2775 const char *
2776 get_stats_option_name(const char *arg)
2778 switch (arg[0])
2780 case 'p':
2781 if (optarg[1] == 'a') /* "parser" */
2782 return "log_parser_stats";
2783 else if (optarg[1] == 'l') /* "planner" */
2784 return "log_planner_stats";
2785 break;
2787 case 'e': /* "executor" */
2788 return "log_executor_stats";
2789 break;
2792 return NULL;
2796 /* ----------------------------------------------------------------
2797 * PostgresMain
2798 * postgres main loop -- all backends, interactive or otherwise start here
2800 * argc/argv are the command line arguments to be used. (When being forked
2801 * by the postmaster, these are not the original argv array of the process.)
2802 * username is the (possibly authenticated) PostgreSQL user name to be used
2803 * for the session.
2804 * ----------------------------------------------------------------
2807 PostgresMain(int argc, char *argv[], const char *username)
2809 int flag;
2810 const char *dbname = NULL;
2811 char *userDoption = NULL;
2812 bool secure;
2813 int errs = 0;
2814 int debug_flag = -1; /* -1 means not given */
2815 List *guc_names = NIL; /* for SUSET options */
2816 List *guc_values = NIL;
2817 GucContext ctx;
2818 GucSource gucsource;
2819 bool am_superuser;
2820 int firstchar;
2821 char stack_base;
2822 StringInfoData input_message;
2823 sigjmp_buf local_sigjmp_buf;
2824 volatile bool send_ready_for_query = true;
2826 #define PendingConfigOption(name,val) \
2827 (guc_names = lappend(guc_names, pstrdup(name)), \
2828 guc_values = lappend(guc_values, pstrdup(val)))
2831 * initialize globals (already done if under postmaster, but not if
2832 * standalone; cheap enough to do over)
2834 MyProcPid = getpid();
2836 MyStartTime = time(NULL);
2839 * Fire up essential subsystems: error and memory management
2841 * If we are running under the postmaster, this is done already.
2843 if (!IsUnderPostmaster)
2844 MemoryContextInit();
2846 set_ps_display("startup", false);
2848 SetProcessingMode(InitProcessing);
2850 /* Set up reference point for stack depth checking */
2851 stack_base_ptr = &stack_base;
2853 /* Compute paths, if we didn't inherit them from postmaster */
2854 if (my_exec_path[0] == '\0')
2856 if (find_my_exec(argv[0], my_exec_path) < 0)
2857 elog(FATAL, "%s: could not locate my own executable path",
2858 argv[0]);
2861 if (pkglib_path[0] == '\0')
2862 get_pkglib_path(my_exec_path, pkglib_path);
2865 * Set default values for command-line options.
2867 EchoQuery = false;
2869 if (!IsUnderPostmaster)
2870 InitializeGUCOptions();
2872 /* ----------------
2873 * parse command line arguments
2875 * There are now two styles of command line layout for the backend:
2877 * For interactive use (not started from postmaster) the format is
2878 * postgres [switches] [databasename]
2879 * If the databasename is omitted it is taken to be the user name.
2881 * When started from the postmaster, the format is
2882 * postgres [secure switches] -p databasename [insecure switches]
2883 * Switches appearing after -p came from the client (via "options"
2884 * field of connection request). For security reasons we restrict
2885 * what these switches can do.
2886 * ----------------
2889 /* Ignore the initial --single argument, if present */
2890 if (argc > 1 && strcmp(argv[1], "--single") == 0)
2892 argv++;
2893 argc--;
2896 /* all options are allowed until '-p' */
2897 secure = true;
2898 ctx = PGC_POSTMASTER;
2899 gucsource = PGC_S_ARGV; /* initial switches came from command line */
2902 * Parse command-line options. CAUTION: keep this in sync with
2903 * postmaster/postmaster.c (the option sets should not conflict) and with
2904 * the common help() function in main/main.c.
2906 while ((flag = getopt(argc, argv, "A:B:c:D:d:EeFf:h:ijk:lN:nOo:Pp:r:S:sTt:v:W:y:-:")) != -1)
2908 switch (flag)
2910 case 'A':
2911 SetConfigOption("debug_assertions", optarg, ctx, gucsource);
2912 break;
2914 case 'B':
2915 SetConfigOption("shared_buffers", optarg, ctx, gucsource);
2916 break;
2918 case 'D':
2919 if (secure)
2920 userDoption = optarg;
2921 break;
2923 case 'd':
2924 debug_flag = atoi(optarg);
2925 break;
2927 case 'E':
2928 EchoQuery = true;
2929 break;
2931 case 'e':
2932 SetConfigOption("datestyle", "euro", ctx, gucsource);
2933 break;
2935 case 'F':
2936 SetConfigOption("fsync", "false", ctx, gucsource);
2937 break;
2939 case 'f':
2940 if (!set_plan_disabling_options(optarg, ctx, gucsource))
2941 errs++;
2942 break;
2944 case 'h':
2945 SetConfigOption("listen_addresses", optarg, ctx, gucsource);
2946 break;
2948 case 'i':
2949 SetConfigOption("listen_addresses", "*", ctx, gucsource);
2950 break;
2952 case 'j':
2953 UseNewLine = 0;
2954 break;
2956 case 'k':
2957 SetConfigOption("unix_socket_directory", optarg, ctx, gucsource);
2958 break;
2960 case 'l':
2961 SetConfigOption("ssl", "true", ctx, gucsource);
2962 break;
2964 case 'N':
2965 SetConfigOption("max_connections", optarg, ctx, gucsource);
2966 break;
2968 case 'n':
2969 /* ignored for consistency with postmaster */
2970 break;
2972 case 'O':
2973 SetConfigOption("allow_system_table_mods", "true", ctx, gucsource);
2974 break;
2976 case 'o':
2977 errs++;
2978 break;
2980 case 'P':
2981 SetConfigOption("ignore_system_indexes", "true", ctx, gucsource);
2982 break;
2984 case 'p':
2985 SetConfigOption("port", optarg, ctx, gucsource);
2986 break;
2988 case 'r':
2989 /* send output (stdout and stderr) to the given file */
2990 if (secure)
2991 strlcpy(OutputFileName, optarg, MAXPGPATH);
2992 break;
2994 case 'S':
2995 SetConfigOption("work_mem", optarg, ctx, gucsource);
2996 break;
2998 case 's':
3001 * Since log options are SUSET, we need to postpone unless
3002 * still in secure context
3004 if (ctx == PGC_BACKEND)
3005 PendingConfigOption("log_statement_stats", "true");
3006 else
3007 SetConfigOption("log_statement_stats", "true",
3008 ctx, gucsource);
3009 break;
3011 case 'T':
3012 /* ignored for consistency with postmaster */
3013 break;
3015 case 't':
3017 const char *tmp = get_stats_option_name(optarg);
3019 if (tmp)
3021 if (ctx == PGC_BACKEND)
3022 PendingConfigOption(tmp, "true");
3023 else
3024 SetConfigOption(tmp, "true", ctx, gucsource);
3026 else
3027 errs++;
3028 break;
3031 case 'v':
3032 if (secure)
3033 FrontendProtocol = (ProtocolVersion) atoi(optarg);
3034 break;
3036 case 'W':
3037 SetConfigOption("post_auth_delay", optarg, ctx, gucsource);
3038 break;
3041 case 'y':
3044 * y - special flag passed if backend was forked by a
3045 * postmaster.
3047 if (secure)
3049 dbname = strdup(optarg);
3051 secure = false; /* subsequent switches are NOT secure */
3052 ctx = PGC_BACKEND;
3053 gucsource = PGC_S_CLIENT;
3055 break;
3057 case 'c':
3058 case '-':
3060 char *name,
3061 *value;
3063 ParseLongOption(optarg, &name, &value);
3064 if (!value)
3066 if (flag == '-')
3067 ereport(ERROR,
3068 (errcode(ERRCODE_SYNTAX_ERROR),
3069 errmsg("--%s requires a value",
3070 optarg)));
3071 else
3072 ereport(ERROR,
3073 (errcode(ERRCODE_SYNTAX_ERROR),
3074 errmsg("-c %s requires a value",
3075 optarg)));
3079 * If a SUSET option, must postpone evaluation, unless we
3080 * are still reading secure switches.
3082 if (ctx == PGC_BACKEND && IsSuperuserConfigOption(name))
3083 PendingConfigOption(name, value);
3084 else
3085 SetConfigOption(name, value, ctx, gucsource);
3086 free(name);
3087 if (value)
3088 free(value);
3089 break;
3092 default:
3093 errs++;
3094 break;
3099 * Process any additional GUC variable settings passed in startup packet.
3100 * These are handled exactly like command-line variables.
3102 if (MyProcPort != NULL)
3104 ListCell *gucopts = list_head(MyProcPort->guc_options);
3106 while (gucopts)
3108 char *name;
3109 char *value;
3111 name = lfirst(gucopts);
3112 gucopts = lnext(gucopts);
3114 value = lfirst(gucopts);
3115 gucopts = lnext(gucopts);
3117 if (IsSuperuserConfigOption(name))
3118 PendingConfigOption(name, value);
3119 else
3120 SetConfigOption(name, value, PGC_BACKEND, PGC_S_CLIENT);
3124 /* Acquire configuration parameters, unless inherited from postmaster */
3125 if (!IsUnderPostmaster)
3127 if (!SelectConfigFiles(userDoption, argv[0]))
3128 proc_exit(1);
3129 /* If timezone is not set, determine what the OS uses */
3130 pg_timezone_initialize();
3131 /* If timezone_abbreviations is not set, select default */
3132 pg_timezone_abbrev_initialize();
3135 if (PostAuthDelay)
3136 pg_usleep(PostAuthDelay * 1000000L);
3139 * You might expect to see a setsid() call here, but it's not needed,
3140 * because if we are under a postmaster then BackendInitialize() did it.
3144 * Set up signal handlers and masks.
3146 * Note that postmaster blocked all signals before forking child process,
3147 * so there is no race condition whereby we might receive a signal before
3148 * we have set up the handler.
3150 * Also note: it's best not to use any signals that are SIG_IGNored in the
3151 * postmaster. If such a signal arrives before we are able to change the
3152 * handler to non-SIG_IGN, it'll get dropped. Instead, make a dummy
3153 * handler in the postmaster to reserve the signal. (Of course, this isn't
3154 * an issue for signals that are locally generated, such as SIGALRM and
3155 * SIGPIPE.)
3157 pqsignal(SIGHUP, SigHupHandler); /* set flag to read config file */
3158 pqsignal(SIGINT, StatementCancelHandler); /* cancel current query */
3159 pqsignal(SIGTERM, die); /* cancel current query and exit */
3162 * In a standalone backend, SIGQUIT can be generated from the keyboard
3163 * easily, while SIGTERM cannot, so we make both signals do die() rather
3164 * than quickdie().
3166 if (IsUnderPostmaster)
3167 pqsignal(SIGQUIT, quickdie); /* hard crash time */
3168 else
3169 pqsignal(SIGQUIT, die); /* cancel current query and exit */
3170 pqsignal(SIGALRM, handle_sig_alarm); /* timeout conditions */
3173 * Ignore failure to write to frontend. Note: if frontend closes
3174 * connection, we will notice it and exit cleanly when control next
3175 * returns to outer loop. This seems safer than forcing exit in the midst
3176 * of output during who-knows-what operation...
3178 pqsignal(SIGPIPE, SIG_IGN);
3179 pqsignal(SIGUSR1, CatchupInterruptHandler);
3180 pqsignal(SIGUSR2, NotifyInterruptHandler);
3181 pqsignal(SIGFPE, FloatExceptionHandler);
3184 * Reset some signals that are accepted by postmaster but not by backend
3186 pqsignal(SIGCHLD, SIG_DFL); /* system() requires this on some platforms */
3188 pqinitmask();
3190 if (IsUnderPostmaster)
3192 /* We allow SIGQUIT (quickdie) at all times */
3193 #ifdef HAVE_SIGPROCMASK
3194 sigdelset(&BlockSig, SIGQUIT);
3195 #else
3196 BlockSig &= ~(sigmask(SIGQUIT));
3197 #endif
3200 PG_SETMASK(&BlockSig); /* block everything except SIGQUIT */
3202 if (IsUnderPostmaster)
3204 /* noninteractive case: nothing should be left after switches */
3205 if (errs || argc != optind || dbname == NULL)
3207 ereport(FATAL,
3208 (errcode(ERRCODE_SYNTAX_ERROR),
3209 errmsg("invalid command-line arguments for server process"),
3210 errhint("Try \"%s --help\" for more information.", argv[0])));
3213 BaseInit();
3215 else
3217 /* interactive case: database name can be last arg on command line */
3218 if (errs || argc - optind > 1)
3220 ereport(FATAL,
3221 (errcode(ERRCODE_SYNTAX_ERROR),
3222 errmsg("%s: invalid command-line arguments",
3223 argv[0]),
3224 errhint("Try \"%s --help\" for more information.", argv[0])));
3226 else if (argc - optind == 1)
3227 dbname = argv[optind];
3228 else if ((dbname = username) == NULL)
3230 ereport(FATAL,
3231 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3232 errmsg("%s: no database nor user name specified",
3233 argv[0])));
3237 * Validate we have been given a reasonable-looking DataDir (if under
3238 * postmaster, assume postmaster did this already).
3240 Assert(DataDir);
3241 ValidatePgVersion(DataDir);
3243 /* Change into DataDir (if under postmaster, was done already) */
3244 ChangeToDataDir();
3247 * Create lockfile for data directory.
3249 CreateDataDirLockFile(false);
3251 BaseInit();
3254 * Start up xlog for standalone backend, and register to have it
3255 * closed down at exit.
3257 StartupXLOG();
3258 on_shmem_exit(ShutdownXLOG, 0);
3261 * We have to build the flat file for pg_database, but not for the
3262 * user and group tables, since we won't try to do authentication.
3264 BuildFlatFiles(true);
3268 * Create a per-backend PGPROC struct in shared memory, except in the
3269 * EXEC_BACKEND case where this was done in SubPostmasterMain. We must do
3270 * this before we can use LWLocks (and in the EXEC_BACKEND case we already
3271 * had to do some stuff with LWLocks).
3273 #ifdef EXEC_BACKEND
3274 if (!IsUnderPostmaster)
3275 InitProcess();
3276 #else
3277 InitProcess();
3278 #endif
3281 * General initialization.
3283 * NOTE: if you are tempted to add code in this vicinity, consider putting
3284 * it inside InitPostgres() instead. In particular, anything that
3285 * involves database access should be there, not here.
3287 ereport(DEBUG3,
3288 (errmsg_internal("InitPostgres")));
3289 am_superuser = InitPostgres(dbname, InvalidOid, username, NULL);
3291 SetProcessingMode(NormalProcessing);
3294 * Now that we know if client is a superuser, we can try to apply SUSET
3295 * GUC options that came from the client.
3297 ctx = am_superuser ? PGC_SUSET : PGC_USERSET;
3299 if (debug_flag >= 0)
3300 set_debug_options(debug_flag, ctx, PGC_S_CLIENT);
3302 if (guc_names != NIL)
3304 ListCell *namcell,
3305 *valcell;
3307 forboth(namcell, guc_names, valcell, guc_values)
3309 char *name = (char *) lfirst(namcell);
3310 char *value = (char *) lfirst(valcell);
3312 SetConfigOption(name, value, ctx, PGC_S_CLIENT);
3313 pfree(name);
3314 pfree(value);
3319 * Now all GUC states are fully set up. Report them to client if
3320 * appropriate.
3322 BeginReportingGUCOptions();
3325 * Also set up handler to log session end; we have to wait till now to be
3326 * sure Log_disconnections has its final value.
3328 if (IsUnderPostmaster && Log_disconnections)
3329 on_proc_exit(log_disconnections, 0);
3332 * process any libraries that should be preloaded at backend start (this
3333 * likewise can't be done until GUC settings are complete)
3335 process_local_preload_libraries();
3338 * Send this backend's cancellation info to the frontend.
3340 if (whereToSendOutput == DestRemote &&
3341 PG_PROTOCOL_MAJOR(FrontendProtocol) >= 2)
3343 StringInfoData buf;
3345 pq_beginmessage(&buf, 'K');
3346 pq_sendint(&buf, (int32) MyProcPid, sizeof(int32));
3347 pq_sendint(&buf, (int32) MyCancelKey, sizeof(int32));
3348 pq_endmessage(&buf);
3349 /* Need not flush since ReadyForQuery will do it. */
3352 /* Welcome banner for standalone case */
3353 if (whereToSendOutput == DestDebug)
3354 printf("\nPostgreSQL stand-alone backend %s\n", PG_VERSION);
3357 * Create the memory context we will use in the main loop.
3359 * MessageContext is reset once per iteration of the main loop, ie, upon
3360 * completion of processing of each command message from the client.
3362 MessageContext = AllocSetContextCreate(TopMemoryContext,
3363 "MessageContext",
3364 ALLOCSET_DEFAULT_MINSIZE,
3365 ALLOCSET_DEFAULT_INITSIZE,
3366 ALLOCSET_DEFAULT_MAXSIZE);
3369 * Remember stand-alone backend startup time
3371 if (!IsUnderPostmaster)
3372 PgStartTime = GetCurrentTimestamp();
3375 * POSTGRES main processing loop begins here
3377 * If an exception is encountered, processing resumes here so we abort the
3378 * current transaction and start a new one.
3380 * You might wonder why this isn't coded as an infinite loop around a
3381 * PG_TRY construct. The reason is that this is the bottom of the
3382 * exception stack, and so with PG_TRY there would be no exception handler
3383 * in force at all during the CATCH part. By leaving the outermost setjmp
3384 * always active, we have at least some chance of recovering from an error
3385 * during error recovery. (If we get into an infinite loop thereby, it
3386 * will soon be stopped by overflow of elog.c's internal state stack.)
3389 if (sigsetjmp(local_sigjmp_buf, 1) != 0)
3392 * NOTE: if you are tempted to add more code in this if-block,
3393 * consider the high probability that it should be in
3394 * AbortTransaction() instead. The only stuff done directly here
3395 * should be stuff that is guaranteed to apply *only* for outer-level
3396 * error recovery, such as adjusting the FE/BE protocol status.
3399 /* Since not using PG_TRY, must reset error stack by hand */
3400 error_context_stack = NULL;
3402 /* Prevent interrupts while cleaning up */
3403 HOLD_INTERRUPTS();
3406 * Forget any pending QueryCancel request, since we're returning to
3407 * the idle loop anyway, and cancel the statement timer if running.
3409 QueryCancelPending = false;
3410 disable_sig_alarm(true);
3411 QueryCancelPending = false; /* again in case timeout occurred */
3414 * Turn off these interrupts too. This is only needed here and not in
3415 * other exception-catching places since these interrupts are only
3416 * enabled while we wait for client input.
3418 DoingCommandRead = false;
3419 DisableNotifyInterrupt();
3420 DisableCatchupInterrupt();
3422 /* Make sure libpq is in a good state */
3423 pq_comm_reset();
3425 /* Report the error to the client and/or server log */
3426 EmitErrorReport();
3429 * Make sure debug_query_string gets reset before we possibly clobber
3430 * the storage it points at.
3432 debug_query_string = NULL;
3435 * Abort the current transaction in order to recover.
3437 AbortCurrentTransaction();
3440 * Now return to normal top-level context and clear ErrorContext for
3441 * next time.
3443 MemoryContextSwitchTo(TopMemoryContext);
3444 FlushErrorState();
3447 * If we were handling an extended-query-protocol message, initiate
3448 * skip till next Sync. This also causes us not to issue
3449 * ReadyForQuery (until we get Sync).
3451 if (doing_extended_query_message)
3452 ignore_till_sync = true;
3454 /* We don't have a transaction command open anymore */
3455 xact_started = false;
3457 /* Now we can allow interrupts again */
3458 RESUME_INTERRUPTS();
3461 /* We can now handle ereport(ERROR) */
3462 PG_exception_stack = &local_sigjmp_buf;
3464 PG_SETMASK(&UnBlockSig);
3466 if (!ignore_till_sync)
3467 send_ready_for_query = true; /* initially, or after error */
3470 * Non-error queries loop here.
3473 for (;;)
3476 * At top of loop, reset extended-query-message flag, so that any
3477 * errors encountered in "idle" state don't provoke skip.
3479 doing_extended_query_message = false;
3482 * Release storage left over from prior query cycle, and create a new
3483 * query input buffer in the cleared MessageContext.
3485 MemoryContextSwitchTo(MessageContext);
3486 MemoryContextResetAndDeleteChildren(MessageContext);
3488 initStringInfo(&input_message);
3491 * (1) If we've reached idle state, tell the frontend we're ready for
3492 * a new query.
3494 * Note: this includes fflush()'ing the last of the prior output.
3496 * This is also a good time to send collected statistics to the
3497 * collector, and to update the PS stats display. We avoid doing
3498 * those every time through the message loop because it'd slow down
3499 * processing of batched messages, and because we don't want to report
3500 * uncommitted updates (that confuses autovacuum).
3502 if (send_ready_for_query)
3504 if (IsTransactionOrTransactionBlock())
3506 set_ps_display("idle in transaction", false);
3507 pgstat_report_activity("<IDLE> in transaction");
3509 else
3511 pgstat_report_stat(false);
3513 set_ps_display("idle", false);
3514 pgstat_report_activity("<IDLE>");
3517 ReadyForQuery(whereToSendOutput);
3518 send_ready_for_query = false;
3522 * (2) Allow asynchronous signals to be executed immediately if they
3523 * come in while we are waiting for client input. (This must be
3524 * conditional since we don't want, say, reads on behalf of COPY FROM
3525 * STDIN doing the same thing.)
3527 QueryCancelPending = false; /* forget any earlier CANCEL signal */
3528 DoingCommandRead = true;
3531 * (3) read a command (loop blocks here)
3533 firstchar = ReadCommand(&input_message);
3536 * (4) disable async signal conditions again.
3538 DoingCommandRead = false;
3541 * (5) check for any other interesting events that happened while we
3542 * slept.
3544 if (got_SIGHUP)
3546 got_SIGHUP = false;
3547 ProcessConfigFile(PGC_SIGHUP);
3551 * (6) process the command. But ignore it if we're skipping till
3552 * Sync.
3554 if (ignore_till_sync && firstchar != EOF)
3555 continue;
3557 switch (firstchar)
3559 case 'Q': /* simple query */
3561 const char *query_string;
3563 /* Set statement_timestamp() */
3564 SetCurrentStatementStartTimestamp();
3566 query_string = pq_getmsgstring(&input_message);
3567 pq_getmsgend(&input_message);
3569 exec_simple_query(query_string);
3571 send_ready_for_query = true;
3573 break;
3575 case 'P': /* parse */
3577 const char *stmt_name;
3578 const char *query_string;
3579 int numParams;
3580 Oid *paramTypes = NULL;
3582 /* Set statement_timestamp() */
3583 SetCurrentStatementStartTimestamp();
3585 stmt_name = pq_getmsgstring(&input_message);
3586 query_string = pq_getmsgstring(&input_message);
3587 numParams = pq_getmsgint(&input_message, 2);
3588 if (numParams > 0)
3590 int i;
3592 paramTypes = (Oid *) palloc(numParams * sizeof(Oid));
3593 for (i = 0; i < numParams; i++)
3594 paramTypes[i] = pq_getmsgint(&input_message, 4);
3596 pq_getmsgend(&input_message);
3598 exec_parse_message(query_string, stmt_name,
3599 paramTypes, numParams);
3601 break;
3603 case 'B': /* bind */
3604 /* Set statement_timestamp() */
3605 SetCurrentStatementStartTimestamp();
3608 * this message is complex enough that it seems best to put
3609 * the field extraction out-of-line
3611 exec_bind_message(&input_message);
3612 break;
3614 case 'E': /* execute */
3616 const char *portal_name;
3617 int max_rows;
3619 /* Set statement_timestamp() */
3620 SetCurrentStatementStartTimestamp();
3622 portal_name = pq_getmsgstring(&input_message);
3623 max_rows = pq_getmsgint(&input_message, 4);
3624 pq_getmsgend(&input_message);
3626 exec_execute_message(portal_name, max_rows);
3628 break;
3630 case 'F': /* fastpath function call */
3631 /* Set statement_timestamp() */
3632 SetCurrentStatementStartTimestamp();
3634 /* Tell the collector what we're doing */
3635 pgstat_report_activity("<FASTPATH> function call");
3637 /* start an xact for this function invocation */
3638 start_xact_command();
3641 * Note: we may at this point be inside an aborted
3642 * transaction. We can't throw error for that until we've
3643 * finished reading the function-call message, so
3644 * HandleFunctionRequest() must check for it after doing so.
3645 * Be careful not to do anything that assumes we're inside a
3646 * valid transaction here.
3649 /* switch back to message context */
3650 MemoryContextSwitchTo(MessageContext);
3652 if (HandleFunctionRequest(&input_message) == EOF)
3654 /* lost frontend connection during F message input */
3657 * Reset whereToSendOutput to prevent ereport from
3658 * attempting to send any more messages to client.
3660 if (whereToSendOutput == DestRemote)
3661 whereToSendOutput = DestNone;
3663 proc_exit(0);
3666 /* commit the function-invocation transaction */
3667 finish_xact_command();
3669 send_ready_for_query = true;
3670 break;
3672 case 'C': /* close */
3674 int close_type;
3675 const char *close_target;
3677 close_type = pq_getmsgbyte(&input_message);
3678 close_target = pq_getmsgstring(&input_message);
3679 pq_getmsgend(&input_message);
3681 switch (close_type)
3683 case 'S':
3684 if (close_target[0] != '\0')
3685 DropPreparedStatement(close_target, false);
3686 else
3688 /* special-case the unnamed statement */
3689 drop_unnamed_stmt();
3691 break;
3692 case 'P':
3694 Portal portal;
3696 portal = GetPortalByName(close_target);
3697 if (PortalIsValid(portal))
3698 PortalDrop(portal, false);
3700 break;
3701 default:
3702 ereport(ERROR,
3703 (errcode(ERRCODE_PROTOCOL_VIOLATION),
3704 errmsg("invalid CLOSE message subtype %d",
3705 close_type)));
3706 break;
3709 if (whereToSendOutput == DestRemote)
3710 pq_putemptymessage('3'); /* CloseComplete */
3712 break;
3714 case 'D': /* describe */
3716 int describe_type;
3717 const char *describe_target;
3719 /* Set statement_timestamp() (needed for xact) */
3720 SetCurrentStatementStartTimestamp();
3722 describe_type = pq_getmsgbyte(&input_message);
3723 describe_target = pq_getmsgstring(&input_message);
3724 pq_getmsgend(&input_message);
3726 switch (describe_type)
3728 case 'S':
3729 exec_describe_statement_message(describe_target);
3730 break;
3731 case 'P':
3732 exec_describe_portal_message(describe_target);
3733 break;
3734 default:
3735 ereport(ERROR,
3736 (errcode(ERRCODE_PROTOCOL_VIOLATION),
3737 errmsg("invalid DESCRIBE message subtype %d",
3738 describe_type)));
3739 break;
3742 break;
3744 case 'H': /* flush */
3745 pq_getmsgend(&input_message);
3746 if (whereToSendOutput == DestRemote)
3747 pq_flush();
3748 break;
3750 case 'S': /* sync */
3751 pq_getmsgend(&input_message);
3752 finish_xact_command();
3753 send_ready_for_query = true;
3754 break;
3757 * 'X' means that the frontend is closing down the socket. EOF
3758 * means unexpected loss of frontend connection. Either way,
3759 * perform normal shutdown.
3761 case 'X':
3762 case EOF:
3765 * Reset whereToSendOutput to prevent ereport from attempting
3766 * to send any more messages to client.
3768 if (whereToSendOutput == DestRemote)
3769 whereToSendOutput = DestNone;
3772 * NOTE: if you are tempted to add more code here, DON'T!
3773 * Whatever you had in mind to do should be set up as an
3774 * on_proc_exit or on_shmem_exit callback, instead. Otherwise
3775 * it will fail to be called during other backend-shutdown
3776 * scenarios.
3778 proc_exit(0);
3780 case 'd': /* copy data */
3781 case 'c': /* copy done */
3782 case 'f': /* copy fail */
3785 * Accept but ignore these messages, per protocol spec; we
3786 * probably got here because a COPY failed, and the frontend
3787 * is still sending data.
3789 break;
3791 default:
3792 ereport(FATAL,
3793 (errcode(ERRCODE_PROTOCOL_VIOLATION),
3794 errmsg("invalid frontend message type %d",
3795 firstchar)));
3797 } /* end of input-reading loop */
3799 /* can't get here because the above loop never exits */
3800 Assert(false);
3802 return 1; /* keep compiler quiet */
3807 * Obtain platform stack depth limit (in bytes)
3809 * Return -1 if unlimited or not known
3811 long
3812 get_stack_depth_rlimit(void)
3814 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_STACK)
3815 static long val = 0;
3817 /* This won't change after process launch, so check just once */
3818 if (val == 0)
3820 struct rlimit rlim;
3822 if (getrlimit(RLIMIT_STACK, &rlim) < 0)
3823 val = -1;
3824 else if (rlim.rlim_cur == RLIM_INFINITY)
3825 val = -1;
3826 else
3827 val = rlim.rlim_cur;
3829 return val;
3830 #else /* no getrlimit */
3831 #if defined(WIN32) || defined(__CYGWIN__)
3832 /* On Windows we set the backend stack size in src/backend/Makefile */
3833 return WIN32_STACK_RLIMIT;
3834 #else /* not windows ... give up */
3835 return -1;
3836 #endif
3837 #endif
3841 static struct rusage Save_r;
3842 static struct timeval Save_t;
3844 void
3845 ResetUsage(void)
3847 getrusage(RUSAGE_SELF, &Save_r);
3848 gettimeofday(&Save_t, NULL);
3849 ResetBufferUsage();
3850 /* ResetTupleCount(); */
3853 void
3854 ShowUsage(const char *title)
3856 StringInfoData str;
3857 struct timeval user,
3858 sys;
3859 struct timeval elapse_t;
3860 struct rusage r;
3861 char *bufusage;
3863 getrusage(RUSAGE_SELF, &r);
3864 gettimeofday(&elapse_t, NULL);
3865 memcpy((char *) &user, (char *) &r.ru_utime, sizeof(user));
3866 memcpy((char *) &sys, (char *) &r.ru_stime, sizeof(sys));
3867 if (elapse_t.tv_usec < Save_t.tv_usec)
3869 elapse_t.tv_sec--;
3870 elapse_t.tv_usec += 1000000;
3872 if (r.ru_utime.tv_usec < Save_r.ru_utime.tv_usec)
3874 r.ru_utime.tv_sec--;
3875 r.ru_utime.tv_usec += 1000000;
3877 if (r.ru_stime.tv_usec < Save_r.ru_stime.tv_usec)
3879 r.ru_stime.tv_sec--;
3880 r.ru_stime.tv_usec += 1000000;
3884 * the only stats we don't show here are for memory usage -- i can't
3885 * figure out how to interpret the relevant fields in the rusage struct,
3886 * and they change names across o/s platforms, anyway. if you can figure
3887 * out what the entries mean, you can somehow extract resident set size,
3888 * shared text size, and unshared data and stack sizes.
3890 initStringInfo(&str);
3892 appendStringInfo(&str, "! system usage stats:\n");
3893 appendStringInfo(&str,
3894 "!\t%ld.%06ld elapsed %ld.%06ld user %ld.%06ld system sec\n",
3895 (long) (elapse_t.tv_sec - Save_t.tv_sec),
3896 (long) (elapse_t.tv_usec - Save_t.tv_usec),
3897 (long) (r.ru_utime.tv_sec - Save_r.ru_utime.tv_sec),
3898 (long) (r.ru_utime.tv_usec - Save_r.ru_utime.tv_usec),
3899 (long) (r.ru_stime.tv_sec - Save_r.ru_stime.tv_sec),
3900 (long) (r.ru_stime.tv_usec - Save_r.ru_stime.tv_usec));
3901 appendStringInfo(&str,
3902 "!\t[%ld.%06ld user %ld.%06ld sys total]\n",
3903 (long) user.tv_sec,
3904 (long) user.tv_usec,
3905 (long) sys.tv_sec,
3906 (long) sys.tv_usec);
3907 #if defined(HAVE_GETRUSAGE)
3908 appendStringInfo(&str,
3909 "!\t%ld/%ld [%ld/%ld] filesystem blocks in/out\n",
3910 r.ru_inblock - Save_r.ru_inblock,
3911 /* they only drink coffee at dec */
3912 r.ru_oublock - Save_r.ru_oublock,
3913 r.ru_inblock, r.ru_oublock);
3914 appendStringInfo(&str,
3915 "!\t%ld/%ld [%ld/%ld] page faults/reclaims, %ld [%ld] swaps\n",
3916 r.ru_majflt - Save_r.ru_majflt,
3917 r.ru_minflt - Save_r.ru_minflt,
3918 r.ru_majflt, r.ru_minflt,
3919 r.ru_nswap - Save_r.ru_nswap,
3920 r.ru_nswap);
3921 appendStringInfo(&str,
3922 "!\t%ld [%ld] signals rcvd, %ld/%ld [%ld/%ld] messages rcvd/sent\n",
3923 r.ru_nsignals - Save_r.ru_nsignals,
3924 r.ru_nsignals,
3925 r.ru_msgrcv - Save_r.ru_msgrcv,
3926 r.ru_msgsnd - Save_r.ru_msgsnd,
3927 r.ru_msgrcv, r.ru_msgsnd);
3928 appendStringInfo(&str,
3929 "!\t%ld/%ld [%ld/%ld] voluntary/involuntary context switches\n",
3930 r.ru_nvcsw - Save_r.ru_nvcsw,
3931 r.ru_nivcsw - Save_r.ru_nivcsw,
3932 r.ru_nvcsw, r.ru_nivcsw);
3933 #endif /* HAVE_GETRUSAGE */
3935 bufusage = ShowBufferUsage();
3936 appendStringInfo(&str, "! buffer usage stats:\n%s", bufusage);
3937 pfree(bufusage);
3939 /* remove trailing newline */
3940 if (str.data[str.len - 1] == '\n')
3941 str.data[--str.len] = '\0';
3943 ereport(LOG,
3944 (errmsg_internal("%s", title),
3945 errdetail("%s", str.data)));
3947 pfree(str.data);
3951 * on_proc_exit handler to log end of session
3953 static void
3954 log_disconnections(int code, Datum arg)
3956 Port *port = MyProcPort;
3957 long secs;
3958 int usecs;
3959 int msecs;
3960 int hours,
3961 minutes,
3962 seconds;
3964 TimestampDifference(port->SessionStartTime,
3965 GetCurrentTimestamp(),
3966 &secs, &usecs);
3967 msecs = usecs / 1000;
3969 hours = secs / SECS_PER_HOUR;
3970 secs %= SECS_PER_HOUR;
3971 minutes = secs / SECS_PER_MINUTE;
3972 seconds = secs % SECS_PER_MINUTE;
3974 ereport(LOG,
3975 (errmsg("disconnection: session time: %d:%02d:%02d.%03d "
3976 "user=%s database=%s host=%s%s%s",
3977 hours, minutes, seconds, msecs,
3978 port->user_name, port->database_name, port->remote_host,
3979 port->remote_port[0] ? " port=" : "", port->remote_port)));