1 /*-------------------------------------------------------------------------
4 * POSTGRES C Backend Interface
6 * Portions Copyright (c) 1996-2007, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $PostgreSQL: pgsql/src/backend/tcop/postgres.c,v 1.523 2007/02/15 23:23:23 alvherre Exp $
14 * this is the "main" module of the postgres backend and
15 * hence the main module of the "traffic cop".
17 *-------------------------------------------------------------------------
25 #include <sys/socket.h>
26 #ifdef HAVE_SYS_SELECT_H
27 #include <sys/select.h>
29 #ifdef HAVE_SYS_RESOURCE_H
31 #include <sys/resource.h>
37 #ifndef HAVE_GETRUSAGE
38 #include "rusagestub.h"
41 #include "access/printtup.h"
42 #include "access/xact.h"
43 #include "catalog/pg_type.h"
44 #include "commands/async.h"
45 #include "commands/prepare.h"
46 #include "libpq/libpq.h"
47 #include "libpq/pqformat.h"
48 #include "libpq/pqsignal.h"
49 #include "miscadmin.h"
50 #include "nodes/print.h"
51 #include "optimizer/planner.h"
52 #include "parser/analyze.h"
53 #include "parser/parser.h"
54 #include "rewrite/rewriteHandler.h"
55 #include "storage/freespace.h"
56 #include "storage/ipc.h"
57 #include "storage/proc.h"
58 #include "storage/sinval.h"
59 #include "tcop/fastpath.h"
60 #include "tcop/pquery.h"
61 #include "tcop/tcopprot.h"
62 #include "tcop/utility.h"
63 #include "utils/flatfiles.h"
64 #include "utils/lsyscache.h"
65 #include "utils/memutils.h"
66 #include "utils/ps_status.h"
67 #include "mb/pg_wchar.h"
78 const char *debug_query_string; /* for pgmonitor and log_min_error_statement */
80 /* Note: whereToSendOutput is initialized for the bootstrap/standalone case */
81 CommandDest whereToSendOutput = DestDebug;
83 /* flag for logging end of session */
84 bool Log_disconnections = false;
86 LogStmtLevel log_statement = LOGSTMT_NONE;
88 /* GUC variable for maximum stack depth (measured in kilobytes) */
89 int max_stack_depth = 100;
91 /* wait N seconds to allow attach from a debugger */
92 int PostAuthDelay = 0;
101 /* max_stack_depth converted to bytes for speed of checking */
102 static long max_stack_depth_bytes = 100 * 1024L;
105 * Stack base pointer -- initialized by PostgresMain. This is not static
106 * so that PL/Java can modify it.
108 char *stack_base_ptr = NULL;
112 * Flag to mark SIGHUP. Whenever the main loop comes around it
113 * will reread the configuration file. (Better than doing the
114 * reading in the signal handler, ey?)
116 static volatile sig_atomic_t got_SIGHUP = false;
119 * Flag to keep track of whether we have started a transaction.
120 * For extended query protocol this has to be remembered across messages.
122 static bool xact_started = false;
125 * Flag to indicate that we are doing the outer loop's read-from-client,
126 * as opposed to any random read from client that might happen within
127 * commands like COPY FROM STDIN.
129 static bool DoingCommandRead = false;
132 * Flags to implement skip-till-Sync-after-error behavior for messages of
133 * the extended query protocol.
135 static bool doing_extended_query_message = false;
136 static bool ignore_till_sync = false;
139 * If an unnamed prepared statement exists, it's stored here.
140 * We keep it separate from the hashtable kept by commands/prepare.c
141 * in order to reduce overhead for short-lived queries.
143 static MemoryContext unnamed_stmt_context = NULL;
144 static PreparedStatement *unnamed_stmt_pstmt = NULL;
147 static bool EchoQuery = false; /* default don't echo */
150 * people who want to use EOF should #define DONTUSENEWLINE in
153 #ifndef TCOP_DONTUSENEWLINE
154 static int UseNewLine = 1; /* Use newlines query delimiters (the default) */
156 static int UseNewLine = 0; /* Use EOF as query delimiters */
157 #endif /* TCOP_DONTUSENEWLINE */
160 /* ----------------------------------------------------------------
161 * decls for routines only used in this file
162 * ----------------------------------------------------------------
164 static int InteractiveBackend(StringInfo inBuf);
165 static int SocketBackend(StringInfo inBuf);
166 static int ReadCommand(StringInfo inBuf);
167 static List *pg_rewrite_queries(List *querytree_list);
168 static bool check_log_statement_raw(List *raw_parsetree_list);
169 static bool check_log_statement_cooked(List *parsetree_list);
170 static int errdetail_execute(List *raw_parsetree_list);
171 static int errdetail_params(ParamListInfo params);
172 static void start_xact_command(void);
173 static void finish_xact_command(void);
174 static bool IsTransactionExitStmt(Node *parsetree);
175 static bool IsTransactionExitStmtList(List *parseTrees);
176 static bool IsTransactionStmtList(List *parseTrees);
177 static void SigHupHandler(SIGNAL_ARGS);
178 static void log_disconnections(int code, Datum arg);
181 /* ----------------------------------------------------------------
182 * routines to obtain user input
183 * ----------------------------------------------------------------
187 * InteractiveBackend() is called for user interactive connections
189 * the string entered by the user is placed in its parameter inBuf,
190 * and we act like a Q message was received.
192 * EOF is returned if end-of-file input is seen; time to shut down.
197 InteractiveBackend(StringInfo inBuf)
199 int c; /* character read from getc() */
200 bool end = false; /* end-of-input flag */
201 bool backslashSeen = false; /* have we seen a \ ? */
204 * display a prompt and obtain input from the user
209 /* Reset inBuf to empty */
211 inBuf->data[0] = '\0';
219 * if we are using \n as a delimiter, then read characters until
222 while ((c = getc(stdin)) != EOF)
228 /* discard backslash from inBuf */
229 inBuf->data[--inBuf->len] = '\0';
230 backslashSeen = false;
235 /* keep the newline character */
236 appendStringInfoChar(inBuf, '\n');
241 backslashSeen = true;
243 backslashSeen = false;
245 appendStringInfoChar(inBuf, (char) c);
254 * otherwise read characters until EOF.
256 while ((c = getc(stdin)) != EOF)
257 appendStringInfoChar(inBuf, (char) c);
267 * otherwise we have a user query so process it.
272 /* Add '\0' to make it look the same as message case. */
273 appendStringInfoChar(inBuf, (char) '\0');
276 * if the query echo flag was given, print the query..
279 printf("statement: %s\n", inBuf->data);
286 * SocketBackend() Is called for frontend-backend connections
288 * Returns the message type code, and loads message body data into inBuf.
290 * EOF is returned if the connection is lost.
294 SocketBackend(StringInfo inBuf)
299 * Get message type code from the frontend.
301 qtype = pq_getbyte();
303 if (qtype == EOF) /* frontend disconnected */
306 (errcode(ERRCODE_PROTOCOL_VIOLATION),
307 errmsg("unexpected EOF on client connection")));
312 * Validate message type code before trying to read body; if we have lost
313 * sync, better to say "command unknown" than to run out of memory because
314 * we used garbage as a length word.
316 * This also gives us a place to set the doing_extended_query_message flag
317 * as soon as possible.
321 case 'Q': /* simple query */
322 doing_extended_query_message = false;
323 if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
325 /* old style without length word; convert */
326 if (pq_getstring(inBuf))
329 (errcode(ERRCODE_PROTOCOL_VIOLATION),
330 errmsg("unexpected EOF on client connection")));
336 case 'F': /* fastpath function call */
337 /* we let fastpath.c cope with old-style input of this */
338 doing_extended_query_message = false;
341 case 'X': /* terminate */
342 doing_extended_query_message = false;
343 ignore_till_sync = false;
347 case 'C': /* close */
348 case 'D': /* describe */
349 case 'E': /* execute */
350 case 'H': /* flush */
351 case 'P': /* parse */
352 doing_extended_query_message = true;
353 /* these are only legal in protocol 3 */
354 if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
356 (errcode(ERRCODE_PROTOCOL_VIOLATION),
357 errmsg("invalid frontend message type %d", qtype)));
361 /* stop any active skip-till-Sync */
362 ignore_till_sync = false;
363 /* mark not-extended, so that a new error doesn't begin skip */
364 doing_extended_query_message = false;
365 /* only legal in protocol 3 */
366 if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
368 (errcode(ERRCODE_PROTOCOL_VIOLATION),
369 errmsg("invalid frontend message type %d", qtype)));
372 case 'd': /* copy data */
373 case 'c': /* copy done */
374 case 'f': /* copy fail */
375 doing_extended_query_message = false;
376 /* these are only legal in protocol 3 */
377 if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
379 (errcode(ERRCODE_PROTOCOL_VIOLATION),
380 errmsg("invalid frontend message type %d", qtype)));
386 * Otherwise we got garbage from the frontend. We treat this as
387 * fatal because we have probably lost message boundary sync, and
388 * there's no good way to recover.
391 (errcode(ERRCODE_PROTOCOL_VIOLATION),
392 errmsg("invalid frontend message type %d", qtype)));
397 * In protocol version 3, all frontend messages have a length word next
398 * after the type code; we can read the message contents independently of
401 if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3)
403 if (pq_getmessage(inBuf, 0))
404 return EOF; /* suitable message already logged */
411 * ReadCommand reads a command from either the frontend or
412 * standard input, places it in inBuf, and returns the
413 * message type code (first byte of the message).
414 * EOF is returned if end of file.
418 ReadCommand(StringInfo inBuf)
422 if (whereToSendOutput == DestRemote)
423 result = SocketBackend(inBuf);
425 result = InteractiveBackend(inBuf);
430 * prepare_for_client_read -- set up to possibly block on client input
432 * This must be called immediately before any low-level read from the
433 * client connection. It is necessary to do it at a sufficiently low level
434 * that there won't be any other operations except the read kernel call
435 * itself between this call and the subsequent client_read_ended() call.
436 * In particular there mustn't be use of malloc() or other potentially
437 * non-reentrant libc functions. This restriction makes it safe for us
438 * to allow interrupt service routines to execute nontrivial code while
439 * we are waiting for input.
442 prepare_for_client_read(void)
444 if (DoingCommandRead)
446 /* Enable immediate processing of asynchronous signals */
447 EnableNotifyInterrupt();
448 EnableCatchupInterrupt();
450 /* Allow "die" interrupt to be processed while waiting */
451 ImmediateInterruptOK = true;
453 /* And don't forget to detect one that already arrived */
454 QueryCancelPending = false;
455 CHECK_FOR_INTERRUPTS();
460 * client_read_ended -- get out of the client-input state
463 client_read_ended(void)
465 if (DoingCommandRead)
467 ImmediateInterruptOK = false;
468 QueryCancelPending = false; /* forget any CANCEL signal */
470 DisableNotifyInterrupt();
471 DisableCatchupInterrupt();
477 * Parse a query string and pass it through the rewriter.
479 * A list of Query nodes is returned, since the string might contain
480 * multiple queries and/or the rewriter might expand one query to several.
482 * NOTE: this routine is no longer used for processing interactive queries,
483 * but it is still needed for parsing of SQL function bodies.
486 pg_parse_and_rewrite(const char *query_string, /* string to execute */
487 Oid *paramTypes, /* parameter types */
488 int numParams) /* number of parameters */
490 List *raw_parsetree_list;
491 List *querytree_list;
495 * (1) parse the request string into a list of raw parse trees.
497 raw_parsetree_list = pg_parse_query(query_string);
500 * (2) Do parse analysis and rule rewrite.
502 querytree_list = NIL;
503 foreach(list_item, raw_parsetree_list)
505 Node *parsetree = (Node *) lfirst(list_item);
507 querytree_list = list_concat(querytree_list,
508 pg_analyze_and_rewrite(parsetree,
514 return querytree_list;
518 * Do raw parsing (only).
520 * A list of parsetrees is returned, since there might be multiple
521 * commands in the given string.
523 * NOTE: for interactive queries, it is important to keep this routine
524 * separate from the analysis & rewrite stages. Analysis and rewriting
525 * cannot be done in an aborted transaction, since they require access to
526 * database tables. So, we rely on the raw parser to determine whether
527 * we've seen a COMMIT or ABORT command; when we are in abort state, other
528 * commands are not processed any further than the raw parse stage.
531 pg_parse_query(const char *query_string)
533 List *raw_parsetree_list;
535 if (log_parser_stats)
538 raw_parsetree_list = raw_parser(query_string);
540 if (log_parser_stats)
541 ShowUsage("PARSER STATISTICS");
543 return raw_parsetree_list;
547 * Given a raw parsetree (gram.y output), and optionally information about
548 * types of parameter symbols ($n), perform parse analysis and rule rewriting.
550 * A list of Query nodes is returned, since either the analyzer or the
551 * rewriter might expand one query to several.
553 * NOTE: for reasons mentioned above, this must be separate from raw parsing.
556 pg_analyze_and_rewrite(Node *parsetree, const char *query_string,
557 Oid *paramTypes, int numParams)
559 List *querytree_list;
562 * (1) Perform parse analysis.
564 if (log_parser_stats)
567 querytree_list = parse_analyze(parsetree, query_string,
568 paramTypes, numParams);
570 if (log_parser_stats)
571 ShowUsage("PARSE ANALYSIS STATISTICS");
574 * (2) Rewrite the queries, as necessary
576 querytree_list = pg_rewrite_queries(querytree_list);
578 return querytree_list;
582 * Perform rewriting of a list of queries produced by parse analysis.
584 * Note: queries must just have come from the parser, because we do not do
585 * AcquireRewriteLocks() on them.
588 pg_rewrite_queries(List *querytree_list)
590 List *new_list = NIL;
593 if (log_parser_stats)
597 * rewritten queries are collected in new_list. Note there may be more or
598 * fewer than in the original list.
600 foreach(list_item, querytree_list)
602 Query *querytree = (Query *) lfirst(list_item);
604 if (Debug_print_parse)
605 elog_node_display(DEBUG1, "parse tree", querytree,
608 if (querytree->commandType == CMD_UTILITY)
610 /* don't rewrite utilities, just dump 'em into new_list */
611 new_list = lappend(new_list, querytree);
615 /* rewrite regular queries */
616 List *rewritten = QueryRewrite(querytree);
618 new_list = list_concat(new_list, rewritten);
622 querytree_list = new_list;
624 if (log_parser_stats)
625 ShowUsage("REWRITER STATISTICS");
627 #ifdef COPY_PARSE_PLAN_TREES
630 * Optional debugging check: pass querytree output through copyObject()
632 new_list = (List *) copyObject(querytree_list);
633 /* This checks both copyObject() and the equal() routines... */
634 if (!equal(new_list, querytree_list))
635 elog(WARNING, "copyObject() failed to produce an equal parse tree");
637 querytree_list = new_list;
640 if (Debug_print_rewritten)
641 elog_node_display(DEBUG1, "rewritten parse tree", querytree_list,
644 return querytree_list;
648 /* Generate a plan for a single already-rewritten query. */
650 pg_plan_query(Query *querytree, ParamListInfo boundParams)
654 /* Utility commands have no plans. */
655 if (querytree->commandType == CMD_UTILITY)
658 if (log_planner_stats)
661 /* call the optimizer */
662 plan = planner(querytree, false, 0, boundParams);
664 if (log_planner_stats)
665 ShowUsage("PLANNER STATISTICS");
667 #ifdef COPY_PARSE_PLAN_TREES
668 /* Optional debugging check: pass plan output through copyObject() */
670 Plan *new_plan = (Plan *) copyObject(plan);
673 * equal() currently does not have routines to compare Plan nodes, so
674 * don't try to test equality here. Perhaps fix someday?
677 /* This checks both copyObject() and the equal() routines... */
678 if (!equal(new_plan, plan))
679 elog(WARNING, "copyObject() failed to produce an equal plan tree");
687 * Print plan if debugging.
689 if (Debug_print_plan)
690 elog_node_display(DEBUG1, "plan", plan, Debug_pretty_print);
696 * Generate plans for a list of already-rewritten queries.
698 * If needSnapshot is TRUE, we haven't yet set a snapshot for the current
699 * query. A snapshot must be set before invoking the planner, since it
700 * might try to evaluate user-defined functions. But we must not set a
701 * snapshot if the list contains only utility statements, because some
702 * utility statements depend on not having frozen the snapshot yet.
703 * (We assume that such statements cannot appear together with plannable
704 * statements in the rewriter's output.)
707 pg_plan_queries(List *querytrees, ParamListInfo boundParams,
710 List *plan_list = NIL;
711 ListCell *query_list;
713 foreach(query_list, querytrees)
715 Query *query = (Query *) lfirst(query_list);
718 if (query->commandType == CMD_UTILITY)
720 /* Utility commands have no plans. */
727 ActiveSnapshot = CopySnapshot(GetTransactionSnapshot());
728 needSnapshot = false;
730 plan = pg_plan_query(query, boundParams);
733 plan_list = lappend(plan_list, plan);
743 * Execute a "simple Query" protocol message.
746 exec_simple_query(const char *query_string)
748 CommandDest dest = whereToSendOutput;
749 MemoryContext oldcontext;
750 List *parsetree_list;
751 ListCell *parsetree_item;
752 bool save_log_statement_stats = log_statement_stats;
753 bool was_logged = false;
757 * Report query to various monitoring facilities.
759 debug_query_string = query_string;
761 pgstat_report_activity(query_string);
764 * We use save_log_statement_stats so ShowUsage doesn't report incorrect
765 * results because ResetUsage wasn't called.
767 if (save_log_statement_stats)
771 * Start up a transaction command. All queries generated by the
772 * query_string will be in this same command block, *unless* we find a
773 * BEGIN/COMMIT/ABORT statement; we have to force a new xact command after
774 * one of those, else bad things will happen in xact.c. (Note that this
775 * will normally change current memory context.)
777 start_xact_command();
780 * Zap any pre-existing unnamed statement. (While not strictly necessary,
781 * it seems best to define simple-Query mode as if it used the unnamed
782 * statement and portal; this ensures we recover any storage used by prior
783 * unnamed operations.)
785 unnamed_stmt_pstmt = NULL;
786 if (unnamed_stmt_context)
788 DropDependentPortals(unnamed_stmt_context);
789 MemoryContextDelete(unnamed_stmt_context);
791 unnamed_stmt_context = NULL;
794 * Switch to appropriate context for constructing parsetrees.
796 oldcontext = MemoryContextSwitchTo(MessageContext);
798 QueryContext = CurrentMemoryContext;
801 * Do basic parsing of the query or queries (this should be safe even if
802 * we are in aborted transaction state!)
804 parsetree_list = pg_parse_query(query_string);
806 /* Log immediately if dictated by log_statement */
807 if (check_log_statement_raw(parsetree_list))
810 (errmsg("statement: %s", query_string),
811 errdetail_execute(parsetree_list)));
816 * Switch back to transaction context to enter the loop.
818 MemoryContextSwitchTo(oldcontext);
821 * Run through the raw parsetree(s) and process each one.
823 foreach(parsetree_item, parsetree_list)
825 Node *parsetree = (Node *) lfirst(parsetree_item);
826 const char *commandTag;
827 char completionTag[COMPLETION_TAG_BUFSIZE];
828 List *querytree_list,
831 DestReceiver *receiver;
835 * Get the command name for use in status display (it also becomes the
836 * default completion tag, down inside PortalRun). Set ps_status and
837 * do any special start-of-SQL-command processing needed by the
840 commandTag = CreateCommandTag(parsetree);
842 set_ps_display(commandTag, false);
844 BeginCommand(commandTag, dest);
847 * If we are in an aborted transaction, reject all commands except
848 * COMMIT/ABORT. It is important that this test occur before we try
849 * to do parse analysis, rewrite, or planning, since all those phases
850 * try to do database accesses, which may fail in abort state. (It
851 * might be safe to allow some additional utility commands in this
852 * state, but not many...)
854 if (IsAbortedTransactionBlockState() &&
855 !IsTransactionExitStmt(parsetree))
857 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
858 errmsg("current transaction is aborted, "
859 "commands ignored until end of transaction block")));
861 /* Make sure we are in a transaction command */
862 start_xact_command();
864 /* If we got a cancel signal in parsing or prior command, quit */
865 CHECK_FOR_INTERRUPTS();
868 * OK to analyze, rewrite, and plan this query.
870 * Switch to appropriate context for constructing querytrees (again,
871 * these must outlive the execution context).
873 oldcontext = MemoryContextSwitchTo(MessageContext);
875 querytree_list = pg_analyze_and_rewrite(parsetree, query_string,
878 plantree_list = pg_plan_queries(querytree_list, NULL, true);
880 /* If we got a cancel signal in analysis or planning, quit */
881 CHECK_FOR_INTERRUPTS();
884 * Create unnamed portal to run the query or queries in. If there
885 * already is one, silently drop it.
887 portal = CreatePortal("", true, true);
888 /* Don't display the portal in pg_cursors */
889 portal->visible = false;
891 PortalDefineQuery(portal,
900 * Start the portal. No parameters here.
902 PortalStart(portal, NULL, InvalidSnapshot);
905 * Select the appropriate output format: text unless we are doing a
906 * FETCH from a binary cursor. (Pretty grotty to have to do this here
907 * --- but it avoids grottiness in other places. Ah, the joys of
908 * backward compatibility...)
910 format = 0; /* TEXT is default */
911 if (IsA(parsetree, FetchStmt))
913 FetchStmt *stmt = (FetchStmt *) parsetree;
917 Portal fportal = GetPortalByName(stmt->portalname);
919 if (PortalIsValid(fportal) &&
920 (fportal->cursorOptions & CURSOR_OPT_BINARY))
921 format = 1; /* BINARY */
924 PortalSetResultFormat(portal, 1, &format);
927 * Now we can create the destination receiver object.
929 receiver = CreateDestReceiver(dest, portal);
932 * Switch back to transaction context for execution.
934 MemoryContextSwitchTo(oldcontext);
937 * Run the portal to completion, and then drop it (and the receiver).
939 (void) PortalRun(portal,
945 (*receiver->rDestroy) (receiver);
947 PortalDrop(portal, false);
949 if (IsA(parsetree, TransactionStmt))
952 * If this was a transaction control statement, commit it. We will
953 * start a new xact command for the next command (if any).
955 finish_xact_command();
957 else if (lnext(parsetree_item) == NULL)
960 * If this is the last parsetree of the query string, close down
961 * transaction statement before reporting command-complete. This
962 * is so that any end-of-transaction errors are reported before
963 * the command-complete message is issued, to avoid confusing
964 * clients who will expect either a command-complete message or an
965 * error, not one and then the other. But for compatibility with
966 * historical Postgres behavior, we do not force a transaction
967 * boundary between queries appearing in a single query string.
969 finish_xact_command();
974 * We need a CommandCounterIncrement after every query, except
975 * those that start or end a transaction block.
977 CommandCounterIncrement();
981 * Tell client that we're done with this query. Note we emit exactly
982 * one EndCommand report for each raw parsetree, thus one for each SQL
983 * command the client sent, regardless of rewriting. (But a command
984 * aborted by error will not send an EndCommand report at all.)
986 EndCommand(completionTag, dest);
987 } /* end loop over parsetrees */
990 * Close down transaction statement, if one is open.
992 finish_xact_command();
995 * If there were no parsetrees, return EmptyQueryResponse message.
1000 QueryContext = NULL;
1003 * Emit duration logging if appropriate.
1005 switch (check_log_duration(msec_str, was_logged))
1009 (errmsg("duration: %s ms", msec_str)));
1013 (errmsg("duration: %s ms statement: %s",
1014 msec_str, query_string),
1015 errdetail_execute(parsetree_list)));
1019 if (save_log_statement_stats)
1020 ShowUsage("QUERY STATISTICS");
1022 debug_query_string = NULL;
1026 * exec_parse_message
1028 * Execute a "Parse" protocol message.
1031 exec_parse_message(const char *query_string, /* string to execute */
1032 const char *stmt_name, /* name for prepared stmt */
1033 Oid *paramTypes, /* parameter types */
1034 int numParams) /* number of parameters */
1036 MemoryContext oldcontext;
1037 List *parsetree_list;
1038 const char *commandTag;
1039 List *querytree_list,
1043 bool save_log_statement_stats = log_statement_stats;
1047 * Report query to various monitoring facilities.
1049 debug_query_string = query_string;
1051 pgstat_report_activity(query_string);
1053 set_ps_display("PARSE", false);
1055 if (save_log_statement_stats)
1059 (errmsg("parse %s: %s",
1060 *stmt_name ? stmt_name : "<unnamed>",
1064 * Start up a transaction command so we can run parse analysis etc. (Note
1065 * that this will normally change current memory context.) Nothing happens
1066 * if we are already in one.
1068 start_xact_command();
1071 * Switch to appropriate context for constructing parsetrees.
1073 * We have two strategies depending on whether the prepared statement is
1074 * named or not. For a named prepared statement, we do parsing in
1075 * MessageContext and copy the finished trees into the prepared
1076 * statement's private context; then the reset of MessageContext releases
1077 * temporary space used by parsing and planning. For an unnamed prepared
1078 * statement, we assume the statement isn't going to hang around long, so
1079 * getting rid of temp space quickly is probably not worth the costs of
1080 * copying parse/plan trees. So in this case, we set up a special context
1081 * for the unnamed statement, and do all the parsing work therein.
1083 is_named = (stmt_name[0] != '\0');
1086 /* Named prepared statement --- parse in MessageContext */
1087 oldcontext = MemoryContextSwitchTo(MessageContext);
1091 /* Unnamed prepared statement --- release any prior unnamed stmt */
1092 unnamed_stmt_pstmt = NULL;
1093 if (unnamed_stmt_context)
1095 DropDependentPortals(unnamed_stmt_context);
1096 MemoryContextDelete(unnamed_stmt_context);
1098 unnamed_stmt_context = NULL;
1099 /* create context for parsing/planning */
1100 unnamed_stmt_context =
1101 AllocSetContextCreate(TopMemoryContext,
1102 "unnamed prepared statement",
1103 ALLOCSET_DEFAULT_MINSIZE,
1104 ALLOCSET_DEFAULT_INITSIZE,
1105 ALLOCSET_DEFAULT_MAXSIZE);
1106 oldcontext = MemoryContextSwitchTo(unnamed_stmt_context);
1109 QueryContext = CurrentMemoryContext;
1112 * Do basic parsing of the query or queries (this should be safe even if
1113 * we are in aborted transaction state!)
1115 parsetree_list = pg_parse_query(query_string);
1118 * We only allow a single user statement in a prepared statement. This is
1119 * mainly to keep the protocol simple --- otherwise we'd need to worry
1120 * about multiple result tupdescs and things like that.
1122 if (list_length(parsetree_list) > 1)
1124 (errcode(ERRCODE_SYNTAX_ERROR),
1125 errmsg("cannot insert multiple commands into a prepared statement")));
1127 if (parsetree_list != NIL)
1129 Node *parsetree = (Node *) linitial(parsetree_list);
1133 * Get the command name for possible use in status display.
1135 commandTag = CreateCommandTag(parsetree);
1138 * If we are in an aborted transaction, reject all commands except
1139 * COMMIT/ROLLBACK. It is important that this test occur before we
1140 * try to do parse analysis, rewrite, or planning, since all those
1141 * phases try to do database accesses, which may fail in abort state.
1142 * (It might be safe to allow some additional utility commands in this
1143 * state, but not many...)
1145 if (IsAbortedTransactionBlockState() &&
1146 !IsTransactionExitStmt(parsetree))
1148 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1149 errmsg("current transaction is aborted, "
1150 "commands ignored until end of transaction block")));
1153 * OK to analyze, rewrite, and plan this query. Note that the
1154 * originally specified parameter set is not required to be complete,
1155 * so we have to use parse_analyze_varparams().
1157 if (log_parser_stats)
1160 querytree_list = parse_analyze_varparams(parsetree,
1166 * Check all parameter types got determined, and convert array
1167 * representation to a list for storage.
1170 for (i = 0; i < numParams; i++)
1172 Oid ptype = paramTypes[i];
1174 if (ptype == InvalidOid || ptype == UNKNOWNOID)
1176 (errcode(ERRCODE_INDETERMINATE_DATATYPE),
1177 errmsg("could not determine data type of parameter $%d",
1179 param_list = lappend_oid(param_list, ptype);
1182 if (log_parser_stats)
1183 ShowUsage("PARSE ANALYSIS STATISTICS");
1185 querytree_list = pg_rewrite_queries(querytree_list);
1188 * If this is the unnamed statement and it has parameters, defer query
1189 * planning until Bind. Otherwise do it now.
1191 if (!is_named && numParams > 0)
1192 plantree_list = NIL;
1194 plantree_list = pg_plan_queries(querytree_list, NULL, true);
1198 /* Empty input string. This is legal. */
1200 querytree_list = NIL;
1201 plantree_list = NIL;
1205 /* If we got a cancel signal in analysis or planning, quit */
1206 CHECK_FOR_INTERRUPTS();
1209 * Store the query as a prepared statement. See above comments.
1213 StorePreparedStatement(stmt_name,
1223 PreparedStatement *pstmt;
1225 pstmt = (PreparedStatement *) palloc0(sizeof(PreparedStatement));
1226 /* query_string needs to be copied into unnamed_stmt_context */
1227 pstmt->query_string = pstrdup(query_string);
1228 /* the rest is there already */
1229 pstmt->commandTag = commandTag;
1230 pstmt->query_list = querytree_list;
1231 pstmt->plan_list = plantree_list;
1232 pstmt->argtype_list = param_list;
1233 pstmt->from_sql = false;
1234 pstmt->context = unnamed_stmt_context;
1235 /* Now the unnamed statement is complete and valid */
1236 unnamed_stmt_pstmt = pstmt;
1239 MemoryContextSwitchTo(oldcontext);
1241 QueryContext = NULL;
1244 * We do NOT close the open transaction command here; that only happens
1245 * when the client sends Sync. Instead, do CommandCounterIncrement just
1246 * in case something happened during parse/plan.
1248 CommandCounterIncrement();
1251 * Send ParseComplete.
1253 if (whereToSendOutput == DestRemote)
1254 pq_putemptymessage('1');
1257 * Emit duration logging if appropriate.
1259 switch (check_log_duration(msec_str, false))
1263 (errmsg("duration: %s ms", msec_str)));
1267 (errmsg("duration: %s ms parse %s: %s",
1269 *stmt_name ? stmt_name : "<unnamed>",
1274 if (save_log_statement_stats)
1275 ShowUsage("PARSE MESSAGE STATISTICS");
1277 debug_query_string = NULL;
1283 * Process a "Bind" message to create a portal from a prepared statement
1286 exec_bind_message(StringInfo input_message)
1288 const char *portal_name;
1289 const char *stmt_name;
1291 int16 *pformats = NULL;
1294 int16 *rformats = NULL;
1295 PreparedStatement *pstmt;
1297 ParamListInfo params;
1300 MemoryContext qContext;
1301 bool save_log_statement_stats = log_statement_stats;
1304 /* Get the fixed part of the message */
1305 portal_name = pq_getmsgstring(input_message);
1306 stmt_name = pq_getmsgstring(input_message);
1309 (errmsg("bind %s to %s",
1310 *portal_name ? portal_name : "<unnamed>",
1311 *stmt_name ? stmt_name : "<unnamed>")));
1313 /* Find prepared statement */
1314 if (stmt_name[0] != '\0')
1315 pstmt = FetchPreparedStatement(stmt_name, true);
1318 /* special-case the unnamed statement */
1319 pstmt = unnamed_stmt_pstmt;
1322 (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
1323 errmsg("unnamed prepared statement does not exist")));
1327 * Report query to various monitoring facilities.
1329 debug_query_string = pstmt->query_string ? pstmt->query_string : "<BIND>";
1331 pgstat_report_activity(debug_query_string);
1333 set_ps_display("BIND", false);
1335 if (save_log_statement_stats)
1339 * Start up a transaction command so we can call functions etc. (Note that
1340 * this will normally change current memory context.) Nothing happens if
1341 * we are already in one.
1343 start_xact_command();
1345 /* Switch back to message context */
1346 MemoryContextSwitchTo(MessageContext);
1348 /* Get the parameter format codes */
1349 numPFormats = pq_getmsgint(input_message, 2);
1350 if (numPFormats > 0)
1354 pformats = (int16 *) palloc(numPFormats * sizeof(int16));
1355 for (i = 0; i < numPFormats; i++)
1356 pformats[i] = pq_getmsgint(input_message, 2);
1359 /* Get the parameter value count */
1360 numParams = pq_getmsgint(input_message, 2);
1362 if (numPFormats > 1 && numPFormats != numParams)
1364 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1365 errmsg("bind message has %d parameter formats but %d parameters",
1366 numPFormats, numParams)));
1368 if (numParams != list_length(pstmt->argtype_list))
1370 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1371 errmsg("bind message supplies %d parameters, but prepared statement \"%s\" requires %d",
1372 numParams, stmt_name, list_length(pstmt->argtype_list))));
1375 * If we are in aborted transaction state, the only portals we can
1376 * actually run are those containing COMMIT or ROLLBACK commands. We
1377 * disallow binding anything else to avoid problems with infrastructure
1378 * that expects to run inside a valid transaction. We also disallow
1379 * binding any parameters, since we can't risk calling user-defined I/O
1382 if (IsAbortedTransactionBlockState() &&
1383 (!IsTransactionExitStmtList(pstmt->query_list) ||
1386 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1387 errmsg("current transaction is aborted, "
1388 "commands ignored until end of transaction block")));
1391 * Create the portal. Allow silent replacement of an existing portal only
1392 * if the unnamed portal is specified.
1394 if (portal_name[0] == '\0')
1395 portal = CreatePortal(portal_name, true, true);
1397 portal = CreatePortal(portal_name, false, false);
1400 * Fetch parameters, if any, and store in the portal's memory context.
1405 MemoryContext oldContext;
1408 oldContext = MemoryContextSwitchTo(PortalGetHeapMemory(portal));
1410 /* sizeof(ParamListInfoData) includes the first array element */
1411 params = (ParamListInfo) palloc(sizeof(ParamListInfoData) +
1412 (numParams - 1) *sizeof(ParamExternData));
1413 params->numParams = numParams;
1416 foreach(l, pstmt->argtype_list)
1418 Oid ptype = lfirst_oid(l);
1422 StringInfoData pbuf;
1426 plength = pq_getmsgint(input_message, 4);
1427 isNull = (plength == -1);
1431 const char *pvalue = pq_getmsgbytes(input_message, plength);
1434 * Rather than copying data around, we just set up a phony
1435 * StringInfo pointing to the correct portion of the message
1436 * buffer. We assume we can scribble on the message buffer so
1437 * as to maintain the convention that StringInfos have a
1438 * trailing null. This is grotty but is a big win when
1439 * dealing with very large parameter strings.
1441 pbuf.data = (char *) pvalue;
1442 pbuf.maxlen = plength + 1;
1446 csave = pbuf.data[plength];
1447 pbuf.data[plength] = '\0';
1451 pbuf.data = NULL; /* keep compiler quiet */
1455 if (numPFormats > 1)
1456 pformat = pformats[paramno];
1457 else if (numPFormats > 0)
1458 pformat = pformats[0];
1460 pformat = 0; /* default = text */
1462 if (pformat == 0) /* text mode */
1468 getTypeInputInfo(ptype, &typinput, &typioparam);
1471 * We have to do encoding conversion before calling the
1477 pstring = pg_client_to_server(pbuf.data, plength);
1479 pval = OidInputFunctionCall(typinput, pstring, typioparam, -1);
1481 /* Free result of encoding conversion, if any */
1482 if (pstring && pstring != pbuf.data)
1485 else if (pformat == 1) /* binary mode */
1492 * Call the parameter type's binary input converter
1494 getTypeBinaryInputInfo(ptype, &typreceive, &typioparam);
1501 pval = OidReceiveFunctionCall(typreceive, bufptr, typioparam, -1);
1503 /* Trouble if it didn't eat the whole buffer */
1504 if (!isNull && pbuf.cursor != pbuf.len)
1506 (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
1507 errmsg("incorrect binary data format in bind parameter %d",
1513 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1514 errmsg("unsupported format code: %d",
1516 pval = 0; /* keep compiler quiet */
1519 /* Restore message buffer contents */
1521 pbuf.data[plength] = csave;
1523 params->params[paramno].value = pval;
1524 params->params[paramno].isnull = isNull;
1527 * We mark the params as CONST. This has no effect if we already
1528 * did planning, but if we didn't, it licenses the planner to
1529 * substitute the parameters directly into the one-shot plan we
1530 * will generate below.
1532 params->params[paramno].pflags = PARAM_FLAG_CONST;
1533 params->params[paramno].ptype = ptype;
1538 MemoryContextSwitchTo(oldContext);
1543 /* Get the result format codes */
1544 numRFormats = pq_getmsgint(input_message, 2);
1545 if (numRFormats > 0)
1549 rformats = (int16 *) palloc(numRFormats * sizeof(int16));
1550 for (i = 0; i < numRFormats; i++)
1551 rformats[i] = pq_getmsgint(input_message, 2);
1554 pq_getmsgend(input_message);
1557 * If we didn't plan the query before, do it now. This allows the planner
1558 * to make use of the concrete parameter values we now have. Because we
1559 * use PARAM_FLAG_CONST, the plan is good only for this set of param
1560 * values, and so we generate the plan in the portal's own memory context
1561 * where it will be thrown away after use. As in exec_parse_message, we
1562 * make no attempt to recover planner temporary memory until the end of
1565 * XXX because the planner has a bad habit of scribbling on its input, we
1566 * have to make a copy of the parse trees, just in case someone binds and
1567 * executes an unnamed statement multiple times; this also means that the
1568 * portal's queryContext becomes its own heap context rather than the
1569 * prepared statement's context. FIXME someday
1571 if (pstmt->plan_list == NIL && pstmt->query_list != NIL)
1573 MemoryContext oldContext;
1575 qContext = PortalGetHeapMemory(portal);
1576 oldContext = MemoryContextSwitchTo(qContext);
1577 query_list = copyObject(pstmt->query_list);
1578 plan_list = pg_plan_queries(query_list, params, true);
1579 MemoryContextSwitchTo(oldContext);
1583 query_list = pstmt->query_list;
1584 plan_list = pstmt->plan_list;
1585 qContext = pstmt->context;
1589 * Define portal and start execution.
1591 PortalDefineQuery(portal,
1592 *pstmt->stmt_name ? pstmt->stmt_name : NULL,
1593 pstmt->query_string,
1599 PortalStart(portal, params, InvalidSnapshot);
1602 * Apply the result format requests to the portal.
1604 PortalSetResultFormat(portal, numRFormats, rformats);
1607 * Send BindComplete.
1609 if (whereToSendOutput == DestRemote)
1610 pq_putemptymessage('2');
1613 * Emit duration logging if appropriate.
1615 switch (check_log_duration(msec_str, false))
1619 (errmsg("duration: %s ms", msec_str)));
1623 (errmsg("duration: %s ms bind %s%s%s: %s",
1625 *stmt_name ? stmt_name : "<unnamed>",
1626 *portal_name ? "/" : "",
1627 *portal_name ? portal_name : "",
1628 pstmt->query_string ? pstmt->query_string : "<source not stored>"),
1629 errdetail_params(params)));
1633 if (save_log_statement_stats)
1634 ShowUsage("BIND MESSAGE STATISTICS");
1636 debug_query_string = NULL;
1640 * exec_execute_message
1642 * Process an "Execute" message for a portal
1645 exec_execute_message(const char *portal_name, long max_rows)
1648 DestReceiver *receiver;
1651 char completionTag[COMPLETION_TAG_BUFSIZE];
1652 const char *sourceText;
1653 const char *prepStmtName;
1654 ParamListInfo portalParams;
1655 bool save_log_statement_stats = log_statement_stats;
1656 bool is_xact_command;
1657 bool execute_is_fetch;
1658 bool was_logged = false;
1661 /* Adjust destination to tell printtup.c what to do */
1662 dest = whereToSendOutput;
1663 if (dest == DestRemote)
1664 dest = DestRemoteExecute;
1666 portal = GetPortalByName(portal_name);
1667 if (!PortalIsValid(portal))
1669 (errcode(ERRCODE_UNDEFINED_CURSOR),
1670 errmsg("portal \"%s\" does not exist", portal_name)));
1673 * If the original query was a null string, just return
1674 * EmptyQueryResponse.
1676 if (portal->commandTag == NULL)
1678 Assert(portal->parseTrees == NIL);
1683 /* Does the portal contain a transaction command? */
1684 is_xact_command = IsTransactionStmtList(portal->parseTrees);
1687 * We must copy the sourceText and prepStmtName into MessageContext in
1688 * case the portal is destroyed during finish_xact_command. Can avoid the
1689 * copy if it's not an xact command, though.
1691 if (is_xact_command)
1693 sourceText = portal->sourceText ? pstrdup(portal->sourceText) : NULL;
1694 if (portal->prepStmtName)
1695 prepStmtName = pstrdup(portal->prepStmtName);
1697 prepStmtName = "<unnamed>";
1700 * An xact command shouldn't have any parameters, which is a good
1701 * thing because they wouldn't be around after finish_xact_command.
1703 portalParams = NULL;
1707 sourceText = portal->sourceText;
1708 if (portal->prepStmtName)
1709 prepStmtName = portal->prepStmtName;
1711 prepStmtName = "<unnamed>";
1712 portalParams = portal->portalParams;
1716 * Report query to various monitoring facilities.
1718 debug_query_string = sourceText ? sourceText : "<EXECUTE>";
1720 pgstat_report_activity(debug_query_string);
1722 set_ps_display(portal->commandTag, false);
1724 if (save_log_statement_stats)
1727 BeginCommand(portal->commandTag, dest);
1730 * Create dest receiver in MessageContext (we don't want it in transaction
1731 * context, because that may get deleted if portal contains VACUUM).
1733 receiver = CreateDestReceiver(dest, portal);
1736 * Ensure we are in a transaction command (this should normally be the
1737 * case already due to prior BIND).
1739 start_xact_command();
1742 * If we re-issue an Execute protocol request against an existing portal,
1743 * then we are only fetching more rows rather than completely re-executing
1744 * the query from the start. atStart is never reset for a v3 portal, so we
1745 * are safe to use this check.
1747 execute_is_fetch = !portal->atStart;
1749 /* Log immediately if dictated by log_statement */
1750 if (check_log_statement_cooked(portal->parseTrees))
1753 (errmsg("%s %s%s%s%s%s",
1755 _("execute fetch from") :
1758 *portal_name ? "/" : "",
1759 *portal_name ? portal_name : "",
1760 sourceText ? ": " : "",
1761 sourceText ? sourceText : ""),
1762 errdetail_params(portalParams)));
1767 * If we are in aborted transaction state, the only portals we can
1768 * actually run are those containing COMMIT or ROLLBACK commands.
1770 if (IsAbortedTransactionBlockState() &&
1771 !IsTransactionExitStmtList(portal->parseTrees))
1773 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1774 errmsg("current transaction is aborted, "
1775 "commands ignored until end of transaction block")));
1777 /* Check for cancel signal before we start execution */
1778 CHECK_FOR_INTERRUPTS();
1781 * Okay to run the portal.
1784 max_rows = FETCH_ALL;
1786 completed = PortalRun(portal,
1792 (*receiver->rDestroy) (receiver);
1796 if (is_xact_command)
1799 * If this was a transaction control statement, commit it. We
1800 * will start a new xact command for the next command (if any).
1802 finish_xact_command();
1807 * We need a CommandCounterIncrement after every query, except
1808 * those that start or end a transaction block.
1810 CommandCounterIncrement();
1813 /* Send appropriate CommandComplete to client */
1814 EndCommand(completionTag, dest);
1818 /* Portal run not complete, so send PortalSuspended */
1819 if (whereToSendOutput == DestRemote)
1820 pq_putemptymessage('s');
1824 * Emit duration logging if appropriate.
1826 switch (check_log_duration(msec_str, was_logged))
1830 (errmsg("duration: %s ms", msec_str)));
1834 (errmsg("duration: %s ms %s %s%s%s%s%s",
1837 _("execute fetch from") :
1840 *portal_name ? "/" : "",
1841 *portal_name ? portal_name : "",
1842 sourceText ? ": " : "",
1843 sourceText ? sourceText : ""),
1844 errdetail_params(portalParams)));
1848 if (save_log_statement_stats)
1849 ShowUsage("EXECUTE MESSAGE STATISTICS");
1851 debug_query_string = NULL;
1855 * check_log_statement_raw
1856 * Determine whether command should be logged because of log_statement
1858 * raw_parsetree_list is the raw grammar output
1861 check_log_statement_raw(List *raw_parsetree_list)
1863 ListCell *parsetree_item;
1865 if (log_statement == LOGSTMT_NONE)
1867 if (log_statement == LOGSTMT_ALL)
1870 /* Else we have to inspect the statement(s) to see whether to log */
1871 foreach(parsetree_item, raw_parsetree_list)
1873 Node *parsetree = (Node *) lfirst(parsetree_item);
1875 if (GetCommandLogLevel(parsetree) <= log_statement)
1883 * check_log_statement_cooked
1884 * As above, but work from already-analyzed querytrees
1887 check_log_statement_cooked(List *parsetree_list)
1889 ListCell *parsetree_item;
1891 if (log_statement == LOGSTMT_NONE)
1893 if (log_statement == LOGSTMT_ALL)
1896 /* Else we have to inspect the statement(s) to see whether to log */
1897 foreach(parsetree_item, parsetree_list)
1899 Query *parsetree = (Query *) lfirst(parsetree_item);
1901 if (GetQueryLogLevel(parsetree) <= log_statement)
1909 * check_log_duration
1910 * Determine whether current command's duration should be logged
1913 * 0 if no logging is needed
1914 * 1 if just the duration should be logged
1915 * 2 if duration and query details should be logged
1917 * If logging is needed, the duration in msec is formatted into msec_str[],
1918 * which must be a 32-byte buffer.
1920 * was_logged should be TRUE if caller already logged query details (this
1921 * essentially prevents 2 from being returned).
1924 check_log_duration(char *msec_str, bool was_logged)
1926 if (log_duration || log_min_duration_statement >= 0)
1933 TimestampDifference(GetCurrentStatementStartTimestamp(),
1934 GetCurrentTimestamp(),
1936 msecs = usecs / 1000;
1939 * This odd-looking test for log_min_duration_statement being exceeded
1940 * is designed to avoid integer overflow with very long durations:
1941 * don't compute secs * 1000 until we've verified it will fit in int.
1943 exceeded = (log_min_duration_statement == 0 ||
1944 (log_min_duration_statement > 0 &&
1945 (secs > log_min_duration_statement / 1000 ||
1946 secs * 1000 + msecs >= log_min_duration_statement)));
1948 if (exceeded || log_duration)
1950 snprintf(msec_str, 32, "%ld.%03d",
1951 secs * 1000 + msecs, usecs % 1000);
1952 if (exceeded && !was_logged)
1965 * Add an errdetail() line showing the query referenced by an EXECUTE, if any.
1966 * The argument is the raw parsetree list.
1969 errdetail_execute(List *raw_parsetree_list)
1971 ListCell *parsetree_item;
1973 foreach(parsetree_item, raw_parsetree_list)
1975 Node *parsetree = (Node *) lfirst(parsetree_item);
1977 if (IsA(parsetree, ExecuteStmt))
1979 ExecuteStmt *stmt = (ExecuteStmt *) parsetree;
1980 PreparedStatement *pstmt;
1982 pstmt = FetchPreparedStatement(stmt->name, false);
1983 if (pstmt && pstmt->query_string)
1985 errdetail("prepare: %s", pstmt->query_string);
1997 * Add an errdetail() line showing bind-parameter data, if available.
2000 errdetail_params(ParamListInfo params)
2002 /* We mustn't call user-defined I/O functions when in an aborted xact */
2003 if (params && params->numParams > 0 && !IsAbortedTransactionBlockState())
2005 StringInfoData param_str;
2006 MemoryContext oldcontext;
2009 /* Make sure any trash is generated in MessageContext */
2010 oldcontext = MemoryContextSwitchTo(MessageContext);
2012 initStringInfo(¶m_str);
2014 for (paramno = 0; paramno < params->numParams; paramno++)
2016 ParamExternData *prm = ¶ms->params[paramno];
2022 appendStringInfo(¶m_str, "%s$%d = ",
2023 paramno > 0 ? ", " : "",
2026 if (prm->isnull || !OidIsValid(prm->ptype))
2028 appendStringInfoString(¶m_str, "NULL");
2032 getTypeOutputInfo(prm->ptype, &typoutput, &typisvarlena);
2034 pstring = OidOutputFunctionCall(typoutput, prm->value);
2036 appendStringInfoCharMacro(¶m_str, '\'');
2037 for (p = pstring; *p; p++)
2039 if (*p == '\'') /* double single quotes */
2040 appendStringInfoCharMacro(¶m_str, *p);
2041 appendStringInfoCharMacro(¶m_str, *p);
2043 appendStringInfoCharMacro(¶m_str, '\'');
2048 errdetail("parameters: %s", param_str.data);
2050 pfree(param_str.data);
2052 MemoryContextSwitchTo(oldcontext);
2059 * exec_describe_statement_message
2061 * Process a "Describe" message for a prepared statement
2064 exec_describe_statement_message(const char *stmt_name)
2066 PreparedStatement *pstmt;
2072 * Start up a transaction command. (Note that this will normally change
2073 * current memory context.) Nothing happens if we are already in one.
2075 start_xact_command();
2077 /* Switch back to message context */
2078 MemoryContextSwitchTo(MessageContext);
2080 /* Find prepared statement */
2081 if (stmt_name[0] != '\0')
2082 pstmt = FetchPreparedStatement(stmt_name, true);
2085 /* special-case the unnamed statement */
2086 pstmt = unnamed_stmt_pstmt;
2089 (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
2090 errmsg("unnamed prepared statement does not exist")));
2094 * If we are in aborted transaction state, we can't safely create a result
2095 * tupledesc, because that needs catalog accesses. Hence, refuse to
2096 * Describe statements that return data. (We shouldn't just refuse all
2097 * Describes, since that might break the ability of some clients to issue
2098 * COMMIT or ROLLBACK commands, if they use code that blindly Describes
2099 * whatever it does.) We can Describe parameters without doing anything
2100 * dangerous, so we don't restrict that.
2102 if (IsAbortedTransactionBlockState() &&
2103 PreparedStatementReturnsTuples(pstmt))
2105 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2106 errmsg("current transaction is aborted, "
2107 "commands ignored until end of transaction block")));
2109 if (whereToSendOutput != DestRemote)
2110 return; /* can't actually do anything... */
2113 * First describe the parameters...
2115 pq_beginmessage(&buf, 't'); /* parameter description message type */
2116 pq_sendint(&buf, list_length(pstmt->argtype_list), 2);
2118 foreach(l, pstmt->argtype_list)
2120 Oid ptype = lfirst_oid(l);
2122 pq_sendint(&buf, (int) ptype, 4);
2124 pq_endmessage(&buf);
2127 * Next send RowDescription or NoData to describe the result...
2129 tupdesc = FetchPreparedStatementResultDesc(pstmt);
2131 SendRowDescriptionMessage(tupdesc,
2132 FetchPreparedStatementTargetList(pstmt),
2135 pq_putemptymessage('n'); /* NoData */
2140 * exec_describe_portal_message
2142 * Process a "Describe" message for a portal
2145 exec_describe_portal_message(const char *portal_name)
2150 * Start up a transaction command. (Note that this will normally change
2151 * current memory context.) Nothing happens if we are already in one.
2153 start_xact_command();
2155 /* Switch back to message context */
2156 MemoryContextSwitchTo(MessageContext);
2158 portal = GetPortalByName(portal_name);
2159 if (!PortalIsValid(portal))
2161 (errcode(ERRCODE_UNDEFINED_CURSOR),
2162 errmsg("portal \"%s\" does not exist", portal_name)));
2165 * If we are in aborted transaction state, we can't run
2166 * SendRowDescriptionMessage(), because that needs catalog accesses.
2167 * Hence, refuse to Describe portals that return data. (We shouldn't just
2168 * refuse all Describes, since that might break the ability of some
2169 * clients to issue COMMIT or ROLLBACK commands, if they use code that
2170 * blindly Describes whatever it does.)
2172 if (IsAbortedTransactionBlockState() &&
2175 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2176 errmsg("current transaction is aborted, "
2177 "commands ignored until end of transaction block")));
2179 if (whereToSendOutput != DestRemote)
2180 return; /* can't actually do anything... */
2182 if (portal->tupDesc)
2183 SendRowDescriptionMessage(portal->tupDesc,
2184 FetchPortalTargetList(portal),
2187 pq_putemptymessage('n'); /* NoData */
2192 * Convenience routines for starting/committing a single command.
2195 start_xact_command(void)
2200 (errmsg_internal("StartTransactionCommand")));
2201 StartTransactionCommand();
2203 /* Set statement timeout running, if any */
2204 /* NB: this mustn't be enabled until we are within an xact */
2205 if (StatementTimeout > 0)
2206 enable_sig_alarm(StatementTimeout, true);
2208 cancel_from_timeout = false;
2210 xact_started = true;
2215 finish_xact_command(void)
2219 /* Cancel any active statement timeout before committing */
2220 disable_sig_alarm(true);
2222 /* Now commit the command */
2224 (errmsg_internal("CommitTransactionCommand")));
2226 CommitTransactionCommand();
2228 #ifdef MEMORY_CONTEXT_CHECKING
2229 /* Check all memory contexts that weren't freed during commit */
2230 /* (those that were, were checked before being deleted) */
2231 MemoryContextCheck(TopMemoryContext);
2234 #ifdef SHOW_MEMORY_STATS
2235 /* Print mem stats after each commit for leak tracking */
2236 MemoryContextStats(TopMemoryContext);
2239 xact_started = false;
2245 * Convenience routines for checking whether a statement is one of the
2246 * ones that we allow in transaction-aborted state.
2250 IsTransactionExitStmt(Node *parsetree)
2252 if (parsetree && IsA(parsetree, TransactionStmt))
2254 TransactionStmt *stmt = (TransactionStmt *) parsetree;
2256 if (stmt->kind == TRANS_STMT_COMMIT ||
2257 stmt->kind == TRANS_STMT_PREPARE ||
2258 stmt->kind == TRANS_STMT_ROLLBACK ||
2259 stmt->kind == TRANS_STMT_ROLLBACK_TO)
2266 IsTransactionExitStmtList(List *parseTrees)
2268 if (list_length(parseTrees) == 1)
2270 Query *query = (Query *) linitial(parseTrees);
2272 if (query->commandType == CMD_UTILITY &&
2273 IsTransactionExitStmt(query->utilityStmt))
2280 IsTransactionStmtList(List *parseTrees)
2282 if (list_length(parseTrees) == 1)
2284 Query *query = (Query *) linitial(parseTrees);
2286 if (query->commandType == CMD_UTILITY &&
2287 query->utilityStmt && IsA(query->utilityStmt, TransactionStmt))
2294 /* --------------------------------
2295 * signal handler routines used in PostgresMain()
2296 * --------------------------------
2300 * quickdie() occurs when signalled SIGQUIT by the postmaster.
2302 * Some backend has bought the farm,
2303 * so we need to stop what we're doing and exit.
2306 quickdie(SIGNAL_ARGS)
2308 PG_SETMASK(&BlockSig);
2311 * Ideally this should be ereport(FATAL), but then we'd not get control
2315 (errcode(ERRCODE_CRASH_SHUTDOWN),
2316 errmsg("terminating connection because of crash of another server process"),
2317 errdetail("The postmaster has commanded this server process to roll back"
2318 " the current transaction and exit, because another"
2319 " server process exited abnormally and possibly corrupted"
2321 errhint("In a moment you should be able to reconnect to the"
2322 " database and repeat your command.")));
2325 * DO NOT proc_exit() -- we're here because shared memory may be
2326 * corrupted, so we don't want to try to clean up our transaction. Just
2327 * nail the windows shut and get out of town.
2329 * Note we do exit(2) not exit(0). This is to force the postmaster into a
2330 * system reset cycle if some idiot DBA sends a manual SIGQUIT to a random
2331 * backend. This is necessary precisely because we don't clean up our
2332 * shared memory state.
2338 * Shutdown signal from postmaster: abort transaction and exit
2339 * at soonest convenient time
2344 int save_errno = errno;
2346 /* Don't joggle the elbow of proc_exit */
2347 if (!proc_exit_inprogress)
2349 InterruptPending = true;
2350 ProcDiePending = true;
2353 * If it's safe to interrupt, and we're waiting for input or a lock,
2354 * service the interrupt immediately
2356 if (ImmediateInterruptOK && InterruptHoldoffCount == 0 &&
2357 CritSectionCount == 0)
2359 /* bump holdoff count to make ProcessInterrupts() a no-op */
2360 /* until we are done getting ready for it */
2361 InterruptHoldoffCount++;
2362 DisableNotifyInterrupt();
2363 DisableCatchupInterrupt();
2364 /* Make sure CheckDeadLock won't run while shutting down... */
2366 InterruptHoldoffCount--;
2367 ProcessInterrupts();
2375 * Timeout or shutdown signal from postmaster during client authentication.
2378 * XXX: possible future improvement: try to send a message indicating
2379 * why we are disconnecting. Problem is to be sure we don't block while
2380 * doing so, nor mess up the authentication message exchange.
2383 authdie(SIGNAL_ARGS)
2389 * Query-cancel signal from postmaster: abort current transaction
2390 * at soonest convenient time
2393 StatementCancelHandler(SIGNAL_ARGS)
2395 int save_errno = errno;
2398 * Don't joggle the elbow of proc_exit
2400 if (!proc_exit_inprogress)
2402 InterruptPending = true;
2403 QueryCancelPending = true;
2406 * If it's safe to interrupt, and we're waiting for a lock, service
2407 * the interrupt immediately. No point in interrupting if we're
2408 * waiting for input, however.
2410 if (ImmediateInterruptOK && InterruptHoldoffCount == 0 &&
2411 CritSectionCount == 0)
2413 /* bump holdoff count to make ProcessInterrupts() a no-op */
2414 /* until we are done getting ready for it */
2415 InterruptHoldoffCount++;
2416 if (LockWaitCancel())
2418 DisableNotifyInterrupt();
2419 DisableCatchupInterrupt();
2420 InterruptHoldoffCount--;
2421 ProcessInterrupts();
2424 InterruptHoldoffCount--;
2431 /* signal handler for floating point exception */
2433 FloatExceptionHandler(SIGNAL_ARGS)
2436 (errcode(ERRCODE_FLOATING_POINT_EXCEPTION),
2437 errmsg("floating-point exception"),
2438 errdetail("An invalid floating-point operation was signaled. "
2439 "This probably means an out-of-range result or an "
2440 "invalid operation, such as division by zero.")));
2443 /* SIGHUP: set flag to re-read config file at next convenient time */
2445 SigHupHandler(SIGNAL_ARGS)
2452 * ProcessInterrupts: out-of-line portion of CHECK_FOR_INTERRUPTS() macro
2454 * If an interrupt condition is pending, and it's safe to service it,
2455 * then clear the flag and accept the interrupt. Called only when
2456 * InterruptPending is true.
2459 ProcessInterrupts(void)
2461 /* OK to accept interrupt now? */
2462 if (InterruptHoldoffCount != 0 || CritSectionCount != 0)
2464 InterruptPending = false;
2467 ProcDiePending = false;
2468 QueryCancelPending = false; /* ProcDie trumps QueryCancel */
2469 ImmediateInterruptOK = false; /* not idle anymore */
2470 DisableNotifyInterrupt();
2471 DisableCatchupInterrupt();
2473 (errcode(ERRCODE_ADMIN_SHUTDOWN),
2474 errmsg("terminating connection due to administrator command")));
2476 if (QueryCancelPending)
2478 QueryCancelPending = false;
2479 ImmediateInterruptOK = false; /* not idle anymore */
2480 DisableNotifyInterrupt();
2481 DisableCatchupInterrupt();
2482 if (cancel_from_timeout)
2484 (errcode(ERRCODE_QUERY_CANCELED),
2485 errmsg("canceling statement due to statement timeout")));
2488 (errcode(ERRCODE_QUERY_CANCELED),
2489 errmsg("canceling statement due to user request")));
2491 /* If we get here, do nothing (probably, QueryCancelPending was reset) */
2496 * check_stack_depth: check for excessively deep recursion
2498 * This should be called someplace in any recursive routine that might possibly
2499 * recurse deep enough to overflow the stack. Most Unixen treat stack
2500 * overflow as an unrecoverable SIGSEGV, so we want to error out ourselves
2501 * before hitting the hardware limit.
2504 check_stack_depth(void)
2510 * Compute distance from PostgresMain's local variables to my own
2512 stack_depth = (long) (stack_base_ptr - &stack_top_loc);
2515 * Take abs value, since stacks grow up on some machines, down on others
2517 if (stack_depth < 0)
2518 stack_depth = -stack_depth;
2523 * The test on stack_base_ptr prevents us from erroring out if called
2524 * during process setup or in a non-backend process. Logically it should
2525 * be done first, but putting it here avoids wasting cycles during normal
2528 if (stack_depth > max_stack_depth_bytes &&
2529 stack_base_ptr != NULL)
2532 (errcode(ERRCODE_STATEMENT_TOO_COMPLEX),
2533 errmsg("stack depth limit exceeded"),
2534 errhint("Increase the configuration parameter \"max_stack_depth\", "
2535 "after ensuring the platform's stack depth limit is adequate.")));
2539 /* GUC assign hook for max_stack_depth */
2541 assign_max_stack_depth(int newval, bool doit, GucSource source)
2543 long newval_bytes = newval * 1024L;
2544 long stack_rlimit = get_stack_depth_rlimit();
2546 if (stack_rlimit > 0 && newval_bytes > stack_rlimit - STACK_DEPTH_SLOP)
2548 ereport((source >= PGC_S_INTERACTIVE) ? ERROR : LOG,
2549 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2550 errmsg("\"max_stack_depth\" must not exceed %ldkB",
2551 (stack_rlimit - STACK_DEPTH_SLOP) / 1024L),
2552 errhint("Increase the platform's stack depth limit via \"ulimit -s\" or local equivalent.")));
2556 max_stack_depth_bytes = newval_bytes;
2562 * set_debug_options --- apply "-d N" command line option
2564 * -d is not quite the same as setting log_min_messages because it enables
2565 * other output options.
2568 set_debug_options(int debug_flag, GucContext context, GucSource source)
2574 sprintf(debugstr, "debug%d", debug_flag);
2575 SetConfigOption("log_min_messages", debugstr, context, source);
2578 SetConfigOption("log_min_messages", "notice", context, source);
2580 if (debug_flag >= 1 && context == PGC_POSTMASTER)
2582 SetConfigOption("log_connections", "true", context, source);
2583 SetConfigOption("log_disconnections", "true", context, source);
2585 if (debug_flag >= 2)
2586 SetConfigOption("log_statement", "all", context, source);
2587 if (debug_flag >= 3)
2588 SetConfigOption("debug_print_parse", "true", context, source);
2589 if (debug_flag >= 4)
2590 SetConfigOption("debug_print_plan", "true", context, source);
2591 if (debug_flag >= 5)
2592 SetConfigOption("debug_print_rewritten", "true", context, source);
2597 set_plan_disabling_options(const char *arg, GucContext context, GucSource source)
2603 case 's': /* seqscan */
2604 tmp = "enable_seqscan";
2606 case 'i': /* indexscan */
2607 tmp = "enable_indexscan";
2609 case 'b': /* bitmapscan */
2610 tmp = "enable_bitmapscan";
2612 case 't': /* tidscan */
2613 tmp = "enable_tidscan";
2615 case 'n': /* nestloop */
2616 tmp = "enable_nestloop";
2618 case 'm': /* mergejoin */
2619 tmp = "enable_mergejoin";
2621 case 'h': /* hashjoin */
2622 tmp = "enable_hashjoin";
2627 SetConfigOption(tmp, "false", context, source);
2636 get_stats_option_name(const char *arg)
2641 if (optarg[1] == 'a') /* "parser" */
2642 return "log_parser_stats";
2643 else if (optarg[1] == 'l') /* "planner" */
2644 return "log_planner_stats";
2647 case 'e': /* "executor" */
2648 return "log_executor_stats";
2656 /* ----------------------------------------------------------------
2658 * postgres main loop -- all backends, interactive or otherwise start here
2660 * argc/argv are the command line arguments to be used. (When being forked
2661 * by the postmaster, these are not the original argv array of the process.)
2662 * username is the (possibly authenticated) PostgreSQL user name to be used
2664 * ----------------------------------------------------------------
2667 PostgresMain(int argc, char *argv[], const char *username)
2670 const char *dbname = NULL;
2671 char *userDoption = NULL;
2674 int debug_flag = -1; /* -1 means not given */
2675 List *guc_names = NIL; /* for SUSET options */
2676 List *guc_values = NIL;
2678 GucSource gucsource;
2682 StringInfoData input_message;
2683 sigjmp_buf local_sigjmp_buf;
2684 volatile bool send_ready_for_query = true;
2686 #define PendingConfigOption(name,val) \
2687 (guc_names = lappend(guc_names, pstrdup(name)), \
2688 guc_values = lappend(guc_values, pstrdup(val)))
2691 * initialize globals (already done if under postmaster, but not if
2692 * standalone; cheap enough to do over)
2694 MyProcPid = getpid();
2697 * Fire up essential subsystems: error and memory management
2699 * If we are running under the postmaster, this is done already.
2701 if (!IsUnderPostmaster)
2702 MemoryContextInit();
2704 set_ps_display("startup", false);
2706 SetProcessingMode(InitProcessing);
2708 /* Set up reference point for stack depth checking */
2709 stack_base_ptr = &stack_base;
2711 /* Compute paths, if we didn't inherit them from postmaster */
2712 if (my_exec_path[0] == '\0')
2714 if (find_my_exec(argv[0], my_exec_path) < 0)
2715 elog(FATAL, "%s: could not locate my own executable path",
2719 if (pkglib_path[0] == '\0')
2720 get_pkglib_path(my_exec_path, pkglib_path);
2723 * Set default values for command-line options.
2727 if (!IsUnderPostmaster)
2728 InitializeGUCOptions();
2731 * parse command line arguments
2733 * There are now two styles of command line layout for the backend:
2735 * For interactive use (not started from postmaster) the format is
2736 * postgres [switches] [databasename]
2737 * If the databasename is omitted it is taken to be the user name.
2739 * When started from the postmaster, the format is
2740 * postgres [secure switches] -p databasename [insecure switches]
2741 * Switches appearing after -p came from the client (via "options"
2742 * field of connection request). For security reasons we restrict
2743 * what these switches can do.
2747 /* Ignore the initial --single argument, if present */
2748 if (argc > 1 && strcmp(argv[1], "--single") == 0)
2754 /* all options are allowed until '-p' */
2756 ctx = PGC_POSTMASTER;
2757 gucsource = PGC_S_ARGV; /* initial switches came from command line */
2760 * Parse command-line options. CAUTION: keep this in sync with
2761 * postmaster/postmaster.c (the option sets should not conflict)
2762 * and with the common help() function in main/main.c.
2764 while ((flag = getopt(argc, argv, "A:B:c:D:d:EeFf:h:ijk:lN:nOo:Pp:r:S:sTt:v:W:y:-:")) != -1)
2769 SetConfigOption("debug_assertions", optarg, ctx, gucsource);
2773 SetConfigOption("shared_buffers", optarg, ctx, gucsource);
2778 userDoption = optarg;
2782 debug_flag = atoi(optarg);
2790 SetConfigOption("datestyle", "euro", ctx, gucsource);
2794 SetConfigOption("fsync", "false", ctx, gucsource);
2798 if (!set_plan_disabling_options(optarg, ctx, gucsource))
2803 SetConfigOption("listen_addresses", optarg, ctx, gucsource);
2807 SetConfigOption("listen_addresses", "*", ctx, gucsource);
2815 SetConfigOption("unix_socket_directory", optarg, ctx, gucsource);
2819 SetConfigOption("ssl", "true", ctx, gucsource);
2823 SetConfigOption("max_connections", optarg, ctx, gucsource);
2827 /* ignored for consistency with postmaster */
2831 SetConfigOption("allow_system_table_mods", "true", ctx, gucsource);
2839 SetConfigOption("ignore_system_indexes", "true", ctx, gucsource);
2843 SetConfigOption("port", optarg, ctx, gucsource);
2847 /* send output (stdout and stderr) to the given file */
2849 strlcpy(OutputFileName, optarg, MAXPGPATH);
2853 SetConfigOption("work_mem", optarg, ctx, gucsource);
2859 * Since log options are SUSET, we need to postpone unless
2860 * still in secure context
2862 if (ctx == PGC_BACKEND)
2863 PendingConfigOption("log_statement_stats", "true");
2865 SetConfigOption("log_statement_stats", "true",
2870 /* ignored for consistency with postmaster */
2875 const char *tmp = get_stats_option_name(optarg);
2879 if (ctx == PGC_BACKEND)
2880 PendingConfigOption(tmp, "true");
2882 SetConfigOption(tmp, "true", ctx, gucsource);
2891 FrontendProtocol = (ProtocolVersion) atoi(optarg);
2895 SetConfigOption("post_auth_delay", optarg, ctx, gucsource);
2902 * y - special flag passed if backend was forked by a
2907 dbname = strdup(optarg);
2909 secure = false; /* subsequent switches are NOT secure */
2911 gucsource = PGC_S_CLIENT;
2921 ParseLongOption(optarg, &name, &value);
2926 (errcode(ERRCODE_SYNTAX_ERROR),
2927 errmsg("--%s requires a value",
2931 (errcode(ERRCODE_SYNTAX_ERROR),
2932 errmsg("-c %s requires a value",
2937 * If a SUSET option, must postpone evaluation, unless we
2938 * are still reading secure switches.
2940 if (ctx == PGC_BACKEND && IsSuperuserConfigOption(name))
2941 PendingConfigOption(name, value);
2943 SetConfigOption(name, value, ctx, gucsource);
2957 * Process any additional GUC variable settings passed in startup packet.
2958 * These are handled exactly like command-line variables.
2960 if (MyProcPort != NULL)
2962 ListCell *gucopts = list_head(MyProcPort->guc_options);
2969 name = lfirst(gucopts);
2970 gucopts = lnext(gucopts);
2972 value = lfirst(gucopts);
2973 gucopts = lnext(gucopts);
2975 if (IsSuperuserConfigOption(name))
2976 PendingConfigOption(name, value);
2978 SetConfigOption(name, value, PGC_BACKEND, PGC_S_CLIENT);
2982 /* Acquire configuration parameters, unless inherited from postmaster */
2983 if (!IsUnderPostmaster)
2985 if (!SelectConfigFiles(userDoption, argv[0]))
2987 /* If timezone is not set, determine what the OS uses */
2988 pg_timezone_initialize();
2989 /* If timezone_abbreviations is not set, select default */
2990 pg_timezone_abbrev_initialize();
2994 pg_usleep(PostAuthDelay * 1000000L);
2997 * You might expect to see a setsid() call here, but it's not needed,
2998 * because if we are under a postmaster then BackendInitialize() did it.
3002 * Set up signal handlers and masks.
3004 * Note that postmaster blocked all signals before forking child process,
3005 * so there is no race condition whereby we might receive a signal before
3006 * we have set up the handler.
3008 * Also note: it's best not to use any signals that are SIG_IGNored in the
3009 * postmaster. If such a signal arrives before we are able to change the
3010 * handler to non-SIG_IGN, it'll get dropped. Instead, make a dummy
3011 * handler in the postmaster to reserve the signal. (Of course, this isn't
3012 * an issue for signals that are locally generated, such as SIGALRM and
3015 pqsignal(SIGHUP, SigHupHandler); /* set flag to read config file */
3016 pqsignal(SIGINT, StatementCancelHandler); /* cancel current query */
3017 pqsignal(SIGTERM, die); /* cancel current query and exit */
3018 pqsignal(SIGQUIT, quickdie); /* hard crash time */
3019 pqsignal(SIGALRM, handle_sig_alarm); /* timeout conditions */
3022 * Ignore failure to write to frontend. Note: if frontend closes
3023 * connection, we will notice it and exit cleanly when control next
3024 * returns to outer loop. This seems safer than forcing exit in the midst
3025 * of output during who-knows-what operation...
3027 pqsignal(SIGPIPE, SIG_IGN);
3028 pqsignal(SIGUSR1, CatchupInterruptHandler);
3029 pqsignal(SIGUSR2, NotifyInterruptHandler);
3030 pqsignal(SIGFPE, FloatExceptionHandler);
3033 * Reset some signals that are accepted by postmaster but not by backend
3035 pqsignal(SIGCHLD, SIG_DFL); /* system() requires this on some platforms */
3039 /* We allow SIGQUIT (quickdie) at all times */
3040 #ifdef HAVE_SIGPROCMASK
3041 sigdelset(&BlockSig, SIGQUIT);
3043 BlockSig &= ~(sigmask(SIGQUIT));
3046 PG_SETMASK(&BlockSig); /* block everything except SIGQUIT */
3048 if (IsUnderPostmaster)
3050 /* noninteractive case: nothing should be left after switches */
3051 if (errs || argc != optind || dbname == NULL)
3054 (errcode(ERRCODE_SYNTAX_ERROR),
3055 errmsg("invalid command-line arguments for server process"),
3056 errhint("Try \"%s --help\" for more information.", argv[0])));
3063 /* interactive case: database name can be last arg on command line */
3064 if (errs || argc - optind > 1)
3067 (errcode(ERRCODE_SYNTAX_ERROR),
3068 errmsg("%s: invalid command-line arguments",
3070 errhint("Try \"%s --help\" for more information.", argv[0])));
3072 else if (argc - optind == 1)
3073 dbname = argv[optind];
3074 else if ((dbname = username) == NULL)
3077 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3078 errmsg("%s: no database nor user name specified",
3083 * Validate we have been given a reasonable-looking DataDir (if under
3084 * postmaster, assume postmaster did this already).
3087 ValidatePgVersion(DataDir);
3089 /* Change into DataDir (if under postmaster, was done already) */
3093 * Create lockfile for data directory.
3095 CreateDataDirLockFile(false);
3100 * Start up xlog for standalone backend, and register to have it
3101 * closed down at exit.
3104 on_shmem_exit(ShutdownXLOG, 0);
3107 * Read any existing FSM cache file, and register to write one out at
3111 on_shmem_exit(DumpFreeSpaceMap, 0);
3114 * We have to build the flat file for pg_database, but not for the
3115 * user and group tables, since we won't try to do authentication.
3117 BuildFlatFiles(true);
3121 * Create a per-backend PGPROC struct in shared memory, except in the
3122 * EXEC_BACKEND case where this was done in SubPostmasterMain. We must do
3123 * this before we can use LWLocks (and in the EXEC_BACKEND case we already
3124 * had to do some stuff with LWLocks).
3127 if (!IsUnderPostmaster)
3134 * General initialization.
3136 * NOTE: if you are tempted to add code in this vicinity, consider putting
3137 * it inside InitPostgres() instead. In particular, anything that
3138 * involves database access should be there, not here.
3141 (errmsg_internal("InitPostgres")));
3142 am_superuser = InitPostgres(dbname, InvalidOid, username, NULL);
3144 SetProcessingMode(NormalProcessing);
3147 * Now that we know if client is a superuser, we can try to apply SUSET
3148 * GUC options that came from the client.
3150 ctx = am_superuser ? PGC_SUSET : PGC_USERSET;
3152 if (debug_flag >= 0)
3153 set_debug_options(debug_flag, ctx, PGC_S_CLIENT);
3155 if (guc_names != NIL)
3160 forboth(namcell, guc_names, valcell, guc_values)
3162 char *name = (char *) lfirst(namcell);
3163 char *value = (char *) lfirst(valcell);
3165 SetConfigOption(name, value, ctx, PGC_S_CLIENT);
3172 * Now all GUC states are fully set up. Report them to client if
3175 BeginReportingGUCOptions();
3178 * Also set up handler to log session end; we have to wait till now to be
3179 * sure Log_disconnections has its final value.
3181 if (IsUnderPostmaster && Log_disconnections)
3182 on_proc_exit(log_disconnections, 0);
3185 * process any libraries that should be preloaded at backend start (this
3186 * likewise can't be done until GUC settings are complete)
3188 process_local_preload_libraries();
3191 * Send this backend's cancellation info to the frontend.
3193 if (whereToSendOutput == DestRemote &&
3194 PG_PROTOCOL_MAJOR(FrontendProtocol) >= 2)
3198 pq_beginmessage(&buf, 'K');
3199 pq_sendint(&buf, (int32) MyProcPid, sizeof(int32));
3200 pq_sendint(&buf, (int32) MyCancelKey, sizeof(int32));
3201 pq_endmessage(&buf);
3202 /* Need not flush since ReadyForQuery will do it. */
3205 /* Welcome banner for standalone case */
3206 if (whereToSendOutput == DestDebug)
3207 printf("\nPostgreSQL stand-alone backend %s\n", PG_VERSION);
3210 * Create the memory context we will use in the main loop.
3212 * MessageContext is reset once per iteration of the main loop, ie, upon
3213 * completion of processing of each command message from the client.
3215 MessageContext = AllocSetContextCreate(TopMemoryContext,
3217 ALLOCSET_DEFAULT_MINSIZE,
3218 ALLOCSET_DEFAULT_INITSIZE,
3219 ALLOCSET_DEFAULT_MAXSIZE);
3222 * Remember stand-alone backend startup time
3224 if (!IsUnderPostmaster)
3225 PgStartTime = GetCurrentTimestamp();
3228 * POSTGRES main processing loop begins here
3230 * If an exception is encountered, processing resumes here so we abort the
3231 * current transaction and start a new one.
3233 * You might wonder why this isn't coded as an infinite loop around a
3234 * PG_TRY construct. The reason is that this is the bottom of the
3235 * exception stack, and so with PG_TRY there would be no exception handler
3236 * in force at all during the CATCH part. By leaving the outermost setjmp
3237 * always active, we have at least some chance of recovering from an error
3238 * during error recovery. (If we get into an infinite loop thereby, it
3239 * will soon be stopped by overflow of elog.c's internal state stack.)
3242 if (sigsetjmp(local_sigjmp_buf, 1) != 0)
3245 * NOTE: if you are tempted to add more code in this if-block,
3246 * consider the high probability that it should be in
3247 * AbortTransaction() instead. The only stuff done directly here
3248 * should be stuff that is guaranteed to apply *only* for outer-level
3249 * error recovery, such as adjusting the FE/BE protocol status.
3252 /* Since not using PG_TRY, must reset error stack by hand */
3253 error_context_stack = NULL;
3255 /* Prevent interrupts while cleaning up */
3259 * Forget any pending QueryCancel request, since we're returning to
3260 * the idle loop anyway, and cancel the statement timer if running.
3262 QueryCancelPending = false;
3263 disable_sig_alarm(true);
3264 QueryCancelPending = false; /* again in case timeout occurred */
3267 * Turn off these interrupts too. This is only needed here and not in
3268 * other exception-catching places since these interrupts are only
3269 * enabled while we wait for client input.
3271 DoingCommandRead = false;
3272 DisableNotifyInterrupt();
3273 DisableCatchupInterrupt();
3275 /* Make sure libpq is in a good state */
3278 /* Report the error to the client and/or server log */
3282 * Make sure debug_query_string gets reset before we possibly clobber
3283 * the storage it points at.
3285 debug_query_string = NULL;
3288 * Abort the current transaction in order to recover.
3290 AbortCurrentTransaction();
3293 * Now return to normal top-level context and clear ErrorContext for
3296 MemoryContextSwitchTo(TopMemoryContext);
3298 QueryContext = NULL;
3301 * If we were handling an extended-query-protocol message, initiate
3302 * skip till next Sync. This also causes us not to issue
3303 * ReadyForQuery (until we get Sync).
3305 if (doing_extended_query_message)
3306 ignore_till_sync = true;
3308 /* We don't have a transaction command open anymore */
3309 xact_started = false;
3311 /* Now we can allow interrupts again */
3312 RESUME_INTERRUPTS();
3315 /* We can now handle ereport(ERROR) */
3316 PG_exception_stack = &local_sigjmp_buf;
3318 PG_SETMASK(&UnBlockSig);
3320 if (!ignore_till_sync)
3321 send_ready_for_query = true; /* initially, or after error */
3324 * Non-error queries loop here.
3330 * At top of loop, reset extended-query-message flag, so that any
3331 * errors encountered in "idle" state don't provoke skip.
3333 doing_extended_query_message = false;
3336 * Release storage left over from prior query cycle, and create a new
3337 * query input buffer in the cleared MessageContext.
3339 MemoryContextSwitchTo(MessageContext);
3340 MemoryContextResetAndDeleteChildren(MessageContext);
3342 initStringInfo(&input_message);
3345 * (1) If we've reached idle state, tell the frontend we're ready for
3348 * Note: this includes fflush()'ing the last of the prior output.
3350 * This is also a good time to send collected statistics to the
3351 * collector, and to update the PS stats display. We avoid doing
3352 * those every time through the message loop because it'd slow down
3353 * processing of batched messages, and because we don't want to report
3354 * uncommitted updates (that confuses autovacuum).
3356 if (send_ready_for_query)
3358 if (IsTransactionOrTransactionBlock())
3360 set_ps_display("idle in transaction", false);
3361 pgstat_report_activity("<IDLE> in transaction");
3365 pgstat_report_tabstat();
3367 set_ps_display("idle", false);
3368 pgstat_report_activity("<IDLE>");
3371 ReadyForQuery(whereToSendOutput);
3372 send_ready_for_query = false;
3376 * (2) Allow asynchronous signals to be executed immediately if they
3377 * come in while we are waiting for client input. (This must be
3378 * conditional since we don't want, say, reads on behalf of COPY FROM
3379 * STDIN doing the same thing.)
3381 QueryCancelPending = false; /* forget any earlier CANCEL signal */
3382 DoingCommandRead = true;
3385 * (3) read a command (loop blocks here)
3387 firstchar = ReadCommand(&input_message);
3390 * (4) disable async signal conditions again.
3392 DoingCommandRead = false;
3395 * (5) check for any other interesting events that happened while we
3401 ProcessConfigFile(PGC_SIGHUP);
3405 * (6) process the command. But ignore it if we're skipping till
3408 if (ignore_till_sync && firstchar != EOF)
3413 case 'Q': /* simple query */
3415 const char *query_string;
3417 /* Set statement_timestamp() */
3418 SetCurrentStatementStartTimestamp();
3420 query_string = pq_getmsgstring(&input_message);
3421 pq_getmsgend(&input_message);
3423 exec_simple_query(query_string);
3425 send_ready_for_query = true;
3429 case 'P': /* parse */
3431 const char *stmt_name;
3432 const char *query_string;
3434 Oid *paramTypes = NULL;
3436 /* Set statement_timestamp() */
3437 SetCurrentStatementStartTimestamp();
3439 stmt_name = pq_getmsgstring(&input_message);
3440 query_string = pq_getmsgstring(&input_message);
3441 numParams = pq_getmsgint(&input_message, 2);
3446 paramTypes = (Oid *) palloc(numParams * sizeof(Oid));
3447 for (i = 0; i < numParams; i++)
3448 paramTypes[i] = pq_getmsgint(&input_message, 4);
3450 pq_getmsgend(&input_message);
3452 exec_parse_message(query_string, stmt_name,
3453 paramTypes, numParams);
3457 case 'B': /* bind */
3458 /* Set statement_timestamp() */
3459 SetCurrentStatementStartTimestamp();
3462 * this message is complex enough that it seems best to put
3463 * the field extraction out-of-line
3465 exec_bind_message(&input_message);
3468 case 'E': /* execute */
3470 const char *portal_name;
3473 /* Set statement_timestamp() */
3474 SetCurrentStatementStartTimestamp();
3476 portal_name = pq_getmsgstring(&input_message);
3477 max_rows = pq_getmsgint(&input_message, 4);
3478 pq_getmsgend(&input_message);
3480 exec_execute_message(portal_name, max_rows);
3484 case 'F': /* fastpath function call */
3485 /* Set statement_timestamp() */
3486 SetCurrentStatementStartTimestamp();
3488 /* Tell the collector what we're doing */
3489 pgstat_report_activity("<FASTPATH> function call");
3491 /* start an xact for this function invocation */
3492 start_xact_command();
3495 * Note: we may at this point be inside an aborted
3496 * transaction. We can't throw error for that until we've
3497 * finished reading the function-call message, so
3498 * HandleFunctionRequest() must check for it after doing so.
3499 * Be careful not to do anything that assumes we're inside a
3500 * valid transaction here.
3503 /* switch back to message context */
3504 MemoryContextSwitchTo(MessageContext);
3506 if (HandleFunctionRequest(&input_message) == EOF)
3508 /* lost frontend connection during F message input */
3511 * Reset whereToSendOutput to prevent ereport from
3512 * attempting to send any more messages to client.
3514 if (whereToSendOutput == DestRemote)
3515 whereToSendOutput = DestNone;
3520 /* commit the function-invocation transaction */
3521 finish_xact_command();
3523 send_ready_for_query = true;
3526 case 'C': /* close */
3529 const char *close_target;
3531 close_type = pq_getmsgbyte(&input_message);
3532 close_target = pq_getmsgstring(&input_message);
3533 pq_getmsgend(&input_message);
3538 if (close_target[0] != '\0')
3539 DropPreparedStatement(close_target, false);
3542 /* special-case the unnamed statement */
3543 unnamed_stmt_pstmt = NULL;
3544 if (unnamed_stmt_context)
3546 DropDependentPortals(unnamed_stmt_context);
3547 MemoryContextDelete(unnamed_stmt_context);
3549 unnamed_stmt_context = NULL;
3556 portal = GetPortalByName(close_target);
3557 if (PortalIsValid(portal))
3558 PortalDrop(portal, false);
3563 (errcode(ERRCODE_PROTOCOL_VIOLATION),
3564 errmsg("invalid CLOSE message subtype %d",
3569 if (whereToSendOutput == DestRemote)
3570 pq_putemptymessage('3'); /* CloseComplete */
3574 case 'D': /* describe */
3577 const char *describe_target;
3579 /* Set statement_timestamp() (needed for xact) */
3580 SetCurrentStatementStartTimestamp();
3582 describe_type = pq_getmsgbyte(&input_message);
3583 describe_target = pq_getmsgstring(&input_message);
3584 pq_getmsgend(&input_message);
3586 switch (describe_type)
3589 exec_describe_statement_message(describe_target);
3592 exec_describe_portal_message(describe_target);
3596 (errcode(ERRCODE_PROTOCOL_VIOLATION),
3597 errmsg("invalid DESCRIBE message subtype %d",
3604 case 'H': /* flush */
3605 pq_getmsgend(&input_message);
3606 if (whereToSendOutput == DestRemote)
3610 case 'S': /* sync */
3611 pq_getmsgend(&input_message);
3612 finish_xact_command();
3613 send_ready_for_query = true;
3617 * 'X' means that the frontend is closing down the socket. EOF
3618 * means unexpected loss of frontend connection. Either way,
3619 * perform normal shutdown.
3625 * Reset whereToSendOutput to prevent ereport from attempting
3626 * to send any more messages to client.
3628 if (whereToSendOutput == DestRemote)
3629 whereToSendOutput = DestNone;
3632 * NOTE: if you are tempted to add more code here, DON'T!
3633 * Whatever you had in mind to do should be set up as an
3634 * on_proc_exit or on_shmem_exit callback, instead. Otherwise
3635 * it will fail to be called during other backend-shutdown
3640 case 'd': /* copy data */
3641 case 'c': /* copy done */
3642 case 'f': /* copy fail */
3645 * Accept but ignore these messages, per protocol spec; we
3646 * probably got here because a COPY failed, and the frontend
3647 * is still sending data.
3653 (errcode(ERRCODE_PROTOCOL_VIOLATION),
3654 errmsg("invalid frontend message type %d",
3657 } /* end of input-reading loop */
3659 /* can't get here because the above loop never exits */
3662 return 1; /* keep compiler quiet */
3667 * Obtain platform stack depth limit (in bytes)
3669 * Return -1 if unlimited or not known
3672 get_stack_depth_rlimit(void)
3674 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_STACK)
3675 static long val = 0;
3677 /* This won't change after process launch, so check just once */
3682 if (getrlimit(RLIMIT_STACK, &rlim) < 0)
3684 else if (rlim.rlim_cur == RLIM_INFINITY)
3687 val = rlim.rlim_cur;
3690 #else /* no getrlimit */
3691 #if defined(WIN32) || defined(__CYGWIN__)
3692 /* On Windows we set the backend stack size in src/backend/Makefile */
3693 return WIN32_STACK_RLIMIT;
3694 #else /* not windows ... give up */
3701 static struct rusage Save_r;
3702 static struct timeval Save_t;
3707 getrusage(RUSAGE_SELF, &Save_r);
3708 gettimeofday(&Save_t, NULL);
3710 /* ResetTupleCount(); */
3714 ShowUsage(const char *title)
3717 struct timeval user,
3719 struct timeval elapse_t;
3723 getrusage(RUSAGE_SELF, &r);
3724 gettimeofday(&elapse_t, NULL);
3725 memcpy((char *) &user, (char *) &r.ru_utime, sizeof(user));
3726 memcpy((char *) &sys, (char *) &r.ru_stime, sizeof(sys));
3727 if (elapse_t.tv_usec < Save_t.tv_usec)
3730 elapse_t.tv_usec += 1000000;
3732 if (r.ru_utime.tv_usec < Save_r.ru_utime.tv_usec)
3734 r.ru_utime.tv_sec--;
3735 r.ru_utime.tv_usec += 1000000;
3737 if (r.ru_stime.tv_usec < Save_r.ru_stime.tv_usec)
3739 r.ru_stime.tv_sec--;
3740 r.ru_stime.tv_usec += 1000000;
3744 * the only stats we don't show here are for memory usage -- i can't
3745 * figure out how to interpret the relevant fields in the rusage struct,
3746 * and they change names across o/s platforms, anyway. if you can figure
3747 * out what the entries mean, you can somehow extract resident set size,
3748 * shared text size, and unshared data and stack sizes.
3750 initStringInfo(&str);
3752 appendStringInfo(&str, "! system usage stats:\n");
3753 appendStringInfo(&str,
3754 "!\t%ld.%06ld elapsed %ld.%06ld user %ld.%06ld system sec\n",
3755 (long) (elapse_t.tv_sec - Save_t.tv_sec),
3756 (long) (elapse_t.tv_usec - Save_t.tv_usec),
3757 (long) (r.ru_utime.tv_sec - Save_r.ru_utime.tv_sec),
3758 (long) (r.ru_utime.tv_usec - Save_r.ru_utime.tv_usec),
3759 (long) (r.ru_stime.tv_sec - Save_r.ru_stime.tv_sec),
3760 (long) (r.ru_stime.tv_usec - Save_r.ru_stime.tv_usec));
3761 appendStringInfo(&str,
3762 "!\t[%ld.%06ld user %ld.%06ld sys total]\n",
3764 (long) user.tv_usec,
3766 (long) sys.tv_usec);
3767 #if defined(HAVE_GETRUSAGE)
3768 appendStringInfo(&str,
3769 "!\t%ld/%ld [%ld/%ld] filesystem blocks in/out\n",
3770 r.ru_inblock - Save_r.ru_inblock,
3771 /* they only drink coffee at dec */
3772 r.ru_oublock - Save_r.ru_oublock,
3773 r.ru_inblock, r.ru_oublock);
3774 appendStringInfo(&str,
3775 "!\t%ld/%ld [%ld/%ld] page faults/reclaims, %ld [%ld] swaps\n",
3776 r.ru_majflt - Save_r.ru_majflt,
3777 r.ru_minflt - Save_r.ru_minflt,
3778 r.ru_majflt, r.ru_minflt,
3779 r.ru_nswap - Save_r.ru_nswap,
3781 appendStringInfo(&str,
3782 "!\t%ld [%ld] signals rcvd, %ld/%ld [%ld/%ld] messages rcvd/sent\n",
3783 r.ru_nsignals - Save_r.ru_nsignals,
3785 r.ru_msgrcv - Save_r.ru_msgrcv,
3786 r.ru_msgsnd - Save_r.ru_msgsnd,
3787 r.ru_msgrcv, r.ru_msgsnd);
3788 appendStringInfo(&str,
3789 "!\t%ld/%ld [%ld/%ld] voluntary/involuntary context switches\n",
3790 r.ru_nvcsw - Save_r.ru_nvcsw,
3791 r.ru_nivcsw - Save_r.ru_nivcsw,
3792 r.ru_nvcsw, r.ru_nivcsw);
3793 #endif /* HAVE_GETRUSAGE */
3795 bufusage = ShowBufferUsage();
3796 appendStringInfo(&str, "! buffer usage stats:\n%s", bufusage);
3799 /* remove trailing newline */
3800 if (str.data[str.len - 1] == '\n')
3801 str.data[--str.len] = '\0';
3804 (errmsg_internal("%s", title),
3805 errdetail("%s", str.data)));
3811 * on_proc_exit handler to log end of session
3814 log_disconnections(int code, Datum arg)
3816 Port *port = MyProcPort;
3824 TimestampDifference(port->SessionStartTime,
3825 GetCurrentTimestamp(),
3827 msecs = usecs / 1000;
3829 hours = secs / SECS_PER_HOUR;
3830 secs %= SECS_PER_HOUR;
3831 minutes = secs / SECS_PER_MINUTE;
3832 seconds = secs % SECS_PER_MINUTE;
3835 (errmsg("disconnection: session time: %d:%02d:%02d.%03d "
3836 "user=%s database=%s host=%s%s%s",
3837 hours, minutes, seconds, msecs,
3838 port->user_name, port->database_name, port->remote_host,
3839 port->remote_port[0] ? " port=" : "", port->remote_port)));