1 /*-------------------------------------------------------------------------
4 * POSTGRES C Backend Interface
6 * Portions Copyright (c) 1996-2005, 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.479 2006/01/18 06:49:27 neilc 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>
27 #include <sys/select.h>
33 #include "access/printtup.h"
34 #include "access/xlog.h"
35 #include "catalog/pg_type.h"
36 #include "commands/async.h"
37 #include "commands/prepare.h"
38 #include "commands/trigger.h"
39 #include "libpq/libpq.h"
40 #include "libpq/pqformat.h"
41 #include "libpq/pqsignal.h"
42 #include "miscadmin.h"
43 #include "nodes/print.h"
44 #include "optimizer/cost.h"
45 #include "optimizer/planner.h"
46 #include "parser/analyze.h"
47 #include "parser/parser.h"
48 #include "rewrite/rewriteHandler.h"
49 #include "storage/freespace.h"
50 #include "storage/ipc.h"
51 #include "storage/pg_shmem.h"
52 #include "storage/proc.h"
53 #include "storage/sinval.h"
54 #include "tcop/fastpath.h"
55 #include "tcop/pquery.h"
56 #include "tcop/tcopprot.h"
57 #include "tcop/utility.h"
58 #include "utils/builtins.h"
59 #include "utils/flatfiles.h"
60 #include "utils/guc.h"
61 #include "utils/lsyscache.h"
62 #include "utils/memutils.h"
63 #include "utils/ps_status.h"
64 #include "mb/pg_wchar.h"
75 const char *debug_query_string; /* for pgmonitor and log_min_error_statement */
77 /* Note: whereToSendOutput is initialized for the bootstrap/standalone case */
78 CommandDest whereToSendOutput = DestDebug;
80 /* flag for logging end of session */
81 bool Log_disconnections = false;
83 LogStmtLevel log_statement = LOGSTMT_NONE;
85 /* GUC variable for maximum stack depth (measured in kilobytes) */
86 int max_stack_depth = 2048;
88 /* wait N seconds to allow attach from a debugger */
89 int PostAuthDelay = 0;
98 /* max_stack_depth converted to bytes for speed of checking */
99 static int max_stack_depth_bytes = 2048 * 1024;
101 /* stack base pointer (initialized by PostgresMain) */
102 /* Do not make static so PL/Java can modifiy it */
103 char *stack_base_ptr = NULL;
107 * Flag to mark SIGHUP. Whenever the main loop comes around it
108 * will reread the configuration file. (Better than doing the
109 * reading in the signal handler, ey?)
111 static volatile sig_atomic_t got_SIGHUP = false;
114 * Flag to keep track of whether we have started a transaction.
115 * For extended query protocol this has to be remembered across messages.
117 static bool xact_started = false;
120 * Flag to indicate that we are doing the outer loop's read-from-client,
121 * as opposed to any random read from client that might happen within
122 * commands like COPY FROM STDIN.
124 static bool DoingCommandRead = false;
127 * Flags to implement skip-till-Sync-after-error behavior for messages of
128 * the extended query protocol.
130 static bool doing_extended_query_message = false;
131 static bool ignore_till_sync = false;
134 * If an unnamed prepared statement exists, it's stored here.
135 * We keep it separate from the hashtable kept by commands/prepare.c
136 * in order to reduce overhead for short-lived queries.
138 static MemoryContext unnamed_stmt_context = NULL;
139 static PreparedStatement *unnamed_stmt_pstmt = NULL;
142 static bool EchoQuery = false; /* default don't echo */
145 * people who want to use EOF should #define DONTUSENEWLINE in
148 #ifndef TCOP_DONTUSENEWLINE
149 static int UseNewLine = 1; /* Use newlines query delimiters (the default) */
151 static int UseNewLine = 0; /* Use EOF as query delimiters */
152 #endif /* TCOP_DONTUSENEWLINE */
155 /* ----------------------------------------------------------------
156 * decls for routines only used in this file
157 * ----------------------------------------------------------------
159 static int InteractiveBackend(StringInfo inBuf);
160 static int SocketBackend(StringInfo inBuf);
161 static int ReadCommand(StringInfo inBuf);
162 static bool log_after_parse(List *raw_parsetree_list,
163 const char *query_string, char **prepare_string);
164 static List *pg_rewrite_queries(List *querytree_list);
165 static void start_xact_command(void);
166 static void finish_xact_command(void);
167 static bool IsTransactionExitStmt(Node *parsetree);
168 static bool IsTransactionExitStmtList(List *parseTrees);
169 static bool IsTransactionStmtList(List *parseTrees);
170 static void SigHupHandler(SIGNAL_ARGS);
171 static void log_disconnections(int code, Datum arg);
174 /* ----------------------------------------------------------------
175 * routines to obtain user input
176 * ----------------------------------------------------------------
180 * InteractiveBackend() is called for user interactive connections
182 * the string entered by the user is placed in its parameter inBuf,
183 * and we act like a Q message was received.
185 * EOF is returned if end-of-file input is seen; time to shut down.
190 InteractiveBackend(StringInfo inBuf)
192 int c; /* character read from getc() */
193 bool end = false; /* end-of-input flag */
194 bool backslashSeen = false; /* have we seen a \ ? */
197 * display a prompt and obtain input from the user
202 /* Reset inBuf to empty */
204 inBuf->data[0] = '\0';
212 * if we are using \n as a delimiter, then read characters until
215 while ((c = getc(stdin)) != EOF)
221 /* discard backslash from inBuf */
222 inBuf->data[--inBuf->len] = '\0';
223 backslashSeen = false;
228 /* keep the newline character */
229 appendStringInfoChar(inBuf, '\n');
234 backslashSeen = true;
236 backslashSeen = false;
238 appendStringInfoChar(inBuf, (char) c);
247 * otherwise read characters until EOF.
249 while ((c = getc(stdin)) != EOF)
250 appendStringInfoChar(inBuf, (char) c);
260 * otherwise we have a user query so process it.
265 /* Add '\0' to make it look the same as message case. */
266 appendStringInfoChar(inBuf, (char) '\0');
269 * if the query echo flag was given, print the query..
272 printf("statement: %s\n", inBuf->data);
279 * SocketBackend() Is called for frontend-backend connections
281 * Returns the message type code, and loads message body data into inBuf.
283 * EOF is returned if the connection is lost.
287 SocketBackend(StringInfo inBuf)
292 * Get message type code from the frontend.
294 qtype = pq_getbyte();
296 if (qtype == EOF) /* frontend disconnected */
299 (errcode(ERRCODE_PROTOCOL_VIOLATION),
300 errmsg("unexpected EOF on client connection")));
305 * Validate message type code before trying to read body; if we have lost
306 * sync, better to say "command unknown" than to run out of memory because
307 * we used garbage as a length word.
309 * This also gives us a place to set the doing_extended_query_message flag
310 * as soon as possible.
314 case 'Q': /* simple query */
315 doing_extended_query_message = false;
316 if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
318 /* old style without length word; convert */
319 if (pq_getstring(inBuf))
322 (errcode(ERRCODE_PROTOCOL_VIOLATION),
323 errmsg("unexpected EOF on client connection")));
329 case 'F': /* fastpath function call */
330 /* we let fastpath.c cope with old-style input of this */
331 doing_extended_query_message = false;
334 case 'X': /* terminate */
335 doing_extended_query_message = false;
336 ignore_till_sync = false;
340 case 'C': /* close */
341 case 'D': /* describe */
342 case 'E': /* execute */
343 case 'H': /* flush */
344 case 'P': /* parse */
345 doing_extended_query_message = true;
346 /* these are only legal in protocol 3 */
347 if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
349 (errcode(ERRCODE_PROTOCOL_VIOLATION),
350 errmsg("invalid frontend message type %d", qtype)));
354 /* stop any active skip-till-Sync */
355 ignore_till_sync = false;
356 /* mark not-extended, so that a new error doesn't begin skip */
357 doing_extended_query_message = false;
358 /* only legal in protocol 3 */
359 if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
361 (errcode(ERRCODE_PROTOCOL_VIOLATION),
362 errmsg("invalid frontend message type %d", qtype)));
365 case 'd': /* copy data */
366 case 'c': /* copy done */
367 case 'f': /* copy fail */
368 doing_extended_query_message = false;
369 /* these are only legal in protocol 3 */
370 if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
372 (errcode(ERRCODE_PROTOCOL_VIOLATION),
373 errmsg("invalid frontend message type %d", qtype)));
379 * Otherwise we got garbage from the frontend. We treat this as
380 * fatal because we have probably lost message boundary sync, and
381 * there's no good way to recover.
384 (errcode(ERRCODE_PROTOCOL_VIOLATION),
385 errmsg("invalid frontend message type %d", qtype)));
390 * In protocol version 3, all frontend messages have a length word next
391 * after the type code; we can read the message contents independently of
394 if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3)
396 if (pq_getmessage(inBuf, 0))
397 return EOF; /* suitable message already logged */
404 * ReadCommand reads a command from either the frontend or
405 * standard input, places it in inBuf, and returns the
406 * message type code (first byte of the message).
407 * EOF is returned if end of file.
411 ReadCommand(StringInfo inBuf)
415 if (whereToSendOutput == DestRemote)
416 result = SocketBackend(inBuf);
418 result = InteractiveBackend(inBuf);
423 * prepare_for_client_read -- set up to possibly block on client input
425 * This must be called immediately before any low-level read from the
426 * client connection. It is necessary to do it at a sufficiently low level
427 * that there won't be any other operations except the read kernel call
428 * itself between this call and the subsequent client_read_ended() call.
429 * In particular there mustn't be use of malloc() or other potentially
430 * non-reentrant libc functions. This restriction makes it safe for us
431 * to allow interrupt service routines to execute nontrivial code while
432 * we are waiting for input.
435 prepare_for_client_read(void)
437 if (DoingCommandRead)
439 /* Enable immediate processing of asynchronous signals */
440 EnableNotifyInterrupt();
441 EnableCatchupInterrupt();
443 /* Allow "die" interrupt to be processed while waiting */
444 ImmediateInterruptOK = true;
446 /* And don't forget to detect one that already arrived */
447 QueryCancelPending = false;
448 CHECK_FOR_INTERRUPTS();
453 * client_read_ended -- get out of the client-input state
456 client_read_ended(void)
458 if (DoingCommandRead)
460 ImmediateInterruptOK = false;
461 QueryCancelPending = false; /* forget any CANCEL signal */
463 DisableNotifyInterrupt();
464 DisableCatchupInterrupt();
470 * Parse a query string and pass it through the rewriter.
472 * A list of Query nodes is returned, since the string might contain
473 * multiple queries and/or the rewriter might expand one query to several.
475 * NOTE: this routine is no longer used for processing interactive queries,
476 * but it is still needed for parsing of SQL function bodies.
479 pg_parse_and_rewrite(const char *query_string, /* string to execute */
480 Oid *paramTypes, /* parameter types */
481 int numParams) /* number of parameters */
483 List *raw_parsetree_list;
484 List *querytree_list;
488 * (1) parse the request string into a list of raw parse trees.
490 raw_parsetree_list = pg_parse_query(query_string);
493 * (2) Do parse analysis and rule rewrite.
495 querytree_list = NIL;
496 foreach(list_item, raw_parsetree_list)
498 Node *parsetree = (Node *) lfirst(list_item);
500 querytree_list = list_concat(querytree_list,
501 pg_analyze_and_rewrite(parsetree,
506 return querytree_list;
510 * Do raw parsing (only).
512 * A list of parsetrees is returned, since there might be multiple
513 * commands in the given string.
515 * NOTE: for interactive queries, it is important to keep this routine
516 * separate from the analysis & rewrite stages. Analysis and rewriting
517 * cannot be done in an aborted transaction, since they require access to
518 * database tables. So, we rely on the raw parser to determine whether
519 * we've seen a COMMIT or ABORT command; when we are in abort state, other
520 * commands are not processed any further than the raw parse stage.
523 pg_parse_query(const char *query_string)
525 List *raw_parsetree_list;
527 if (log_parser_stats)
530 raw_parsetree_list = raw_parser(query_string);
532 if (log_parser_stats)
533 ShowUsage("PARSER STATISTICS");
535 return raw_parsetree_list;
539 log_after_parse(List *raw_parsetree_list, const char *query_string,
540 char **prepare_string)
542 ListCell *parsetree_item;
543 bool log_this_statement = (log_statement == LOGSTMT_ALL);
545 *prepare_string = NULL;
547 /* Check if we need to log the statement, and get prepare_string. */
548 foreach(parsetree_item, raw_parsetree_list)
550 Node *parsetree = (Node *) lfirst(parsetree_item);
551 const char *commandTag;
553 if (IsA(parsetree, ExplainStmt) &&
554 ((ExplainStmt *) parsetree)->analyze)
555 parsetree = (Node *) (((ExplainStmt *) parsetree)->query);
557 if (IsA(parsetree, PrepareStmt))
558 parsetree = (Node *) (((PrepareStmt *) parsetree)->query);
560 if (IsA(parsetree, SelectStmt) &&
561 ((SelectStmt *) parsetree)->into == NULL)
562 continue; /* optimization for frequent command */
564 if (log_statement == LOGSTMT_MOD &&
565 (IsA(parsetree, InsertStmt) ||
566 IsA(parsetree, UpdateStmt) ||
567 IsA(parsetree, DeleteStmt) ||
568 IsA(parsetree, TruncateStmt) ||
569 (IsA(parsetree, CopyStmt) &&
570 ((CopyStmt *) parsetree)->is_from))) /* COPY FROM */
571 log_this_statement = true;
573 commandTag = CreateCommandTag(parsetree);
574 if ((log_statement == LOGSTMT_MOD ||
575 log_statement == LOGSTMT_DDL) &&
576 (strncmp(commandTag, "CREATE ", strlen("CREATE ")) == 0 ||
577 IsA(parsetree, SelectStmt) || /* SELECT INTO, CREATE AS */
578 strncmp(commandTag, "ALTER ", strlen("ALTER ")) == 0 ||
579 strncmp(commandTag, "DROP ", strlen("DROP ")) == 0 ||
580 IsA(parsetree, GrantStmt) || /* GRANT or REVOKE */
581 IsA(parsetree, CommentStmt)))
582 log_this_statement = true;
585 * For the first EXECUTE we find, record the client statement used by
588 if (IsA(parsetree, ExecuteStmt))
590 ExecuteStmt *stmt = (ExecuteStmt *) parsetree;
591 PreparedStatement *entry;
593 if ((entry = FetchPreparedStatement(stmt->name, false)) != NULL &&
596 *prepare_string = palloc(strlen(entry->query_string) +
597 strlen(" [protocol PREPARE: %s]") - 1);
598 sprintf(*prepare_string, " [protocol PREPARE: %s]",
599 entry->query_string);
604 if (log_this_statement)
607 (errmsg("statement: %s%s", query_string,
608 *prepare_string ? *prepare_string : "")));
617 * Given a raw parsetree (gram.y output), and optionally information about
618 * types of parameter symbols ($n), perform parse analysis and rule rewriting.
620 * A list of Query nodes is returned, since either the analyzer or the
621 * rewriter might expand one query to several.
623 * NOTE: for reasons mentioned above, this must be separate from raw parsing.
626 pg_analyze_and_rewrite(Node *parsetree, Oid *paramTypes, int numParams)
628 List *querytree_list;
631 * (1) Perform parse analysis.
633 if (log_parser_stats)
636 querytree_list = parse_analyze(parsetree, paramTypes, numParams);
638 if (log_parser_stats)
639 ShowUsage("PARSE ANALYSIS STATISTICS");
642 * (2) Rewrite the queries, as necessary
644 querytree_list = pg_rewrite_queries(querytree_list);
646 return querytree_list;
650 * Perform rewriting of a list of queries produced by parse analysis.
652 * Note: queries must just have come from the parser, because we do not do
653 * AcquireRewriteLocks() on them.
656 pg_rewrite_queries(List *querytree_list)
658 List *new_list = NIL;
661 if (log_parser_stats)
665 * rewritten queries are collected in new_list. Note there may be more or
666 * fewer than in the original list.
668 foreach(list_item, querytree_list)
670 Query *querytree = (Query *) lfirst(list_item);
672 if (Debug_print_parse)
673 elog_node_display(DEBUG1, "parse tree", querytree,
676 if (querytree->commandType == CMD_UTILITY)
678 /* don't rewrite utilities, just dump 'em into new_list */
679 new_list = lappend(new_list, querytree);
683 /* rewrite regular queries */
684 List *rewritten = QueryRewrite(querytree);
686 new_list = list_concat(new_list, rewritten);
690 querytree_list = new_list;
692 if (log_parser_stats)
693 ShowUsage("REWRITER STATISTICS");
695 #ifdef COPY_PARSE_PLAN_TREES
698 * Optional debugging check: pass querytree output through copyObject()
700 new_list = (List *) copyObject(querytree_list);
701 /* This checks both copyObject() and the equal() routines... */
702 if (!equal(new_list, querytree_list))
703 elog(WARNING, "copyObject() failed to produce an equal parse tree");
705 querytree_list = new_list;
708 if (Debug_print_rewritten)
709 elog_node_display(DEBUG1, "rewritten parse tree", querytree_list,
712 return querytree_list;
716 /* Generate a plan for a single already-rewritten query. */
718 pg_plan_query(Query *querytree, ParamListInfo boundParams)
722 /* Utility commands have no plans. */
723 if (querytree->commandType == CMD_UTILITY)
726 if (log_planner_stats)
729 /* call the optimizer */
730 plan = planner(querytree, false, 0, boundParams);
732 if (log_planner_stats)
733 ShowUsage("PLANNER STATISTICS");
735 #ifdef COPY_PARSE_PLAN_TREES
736 /* Optional debugging check: pass plan output through copyObject() */
738 Plan *new_plan = (Plan *) copyObject(plan);
741 * equal() currently does not have routines to compare Plan nodes, so
742 * don't try to test equality here. Perhaps fix someday?
745 /* This checks both copyObject() and the equal() routines... */
746 if (!equal(new_plan, plan))
747 elog(WARNING, "copyObject() failed to produce an equal plan tree");
755 * Print plan if debugging.
757 if (Debug_print_plan)
758 elog_node_display(DEBUG1, "plan", plan, Debug_pretty_print);
764 * Generate plans for a list of already-rewritten queries.
766 * If needSnapshot is TRUE, we haven't yet set a snapshot for the current
767 * query. A snapshot must be set before invoking the planner, since it
768 * might try to evaluate user-defined functions. But we must not set a
769 * snapshot if the list contains only utility statements, because some
770 * utility statements depend on not having frozen the snapshot yet.
771 * (We assume that such statements cannot appear together with plannable
772 * statements in the rewriter's output.)
775 pg_plan_queries(List *querytrees, ParamListInfo boundParams,
778 List *plan_list = NIL;
779 ListCell *query_list;
781 foreach(query_list, querytrees)
783 Query *query = (Query *) lfirst(query_list);
786 if (query->commandType == CMD_UTILITY)
788 /* Utility commands have no plans. */
795 ActiveSnapshot = CopySnapshot(GetTransactionSnapshot());
796 needSnapshot = false;
798 plan = pg_plan_query(query, boundParams);
801 plan_list = lappend(plan_list, plan);
811 * Execute a "simple Query" protocol message.
814 exec_simple_query(const char *query_string)
816 CommandDest dest = whereToSendOutput;
817 MemoryContext oldcontext;
818 List *parsetree_list;
819 ListCell *parsetree_item;
820 struct timeval start_t,
822 bool save_log_duration = log_duration;
823 int save_log_min_duration_statement = log_min_duration_statement;
824 bool save_log_statement_stats = log_statement_stats;
825 char *prepare_string = NULL;
826 bool was_logged = false;
829 * Report query to various monitoring facilities.
831 debug_query_string = query_string;
833 pgstat_report_activity(query_string);
836 * We use save_log_* so "SET log_duration = true" and "SET
837 * log_min_duration_statement = true" don't report incorrect time because
838 * gettimeofday() wasn't called. Similarly, log_statement_stats has to be
841 if (save_log_duration || save_log_min_duration_statement != -1)
842 gettimeofday(&start_t, NULL);
844 if (save_log_statement_stats)
848 * Start up a transaction command. All queries generated by the
849 * query_string will be in this same command block, *unless* we find a
850 * BEGIN/COMMIT/ABORT statement; we have to force a new xact command after
851 * one of those, else bad things will happen in xact.c. (Note that this
852 * will normally change current memory context.)
854 start_xact_command();
857 * Zap any pre-existing unnamed statement. (While not strictly necessary,
858 * it seems best to define simple-Query mode as if it used the unnamed
859 * statement and portal; this ensures we recover any storage used by prior
860 * unnamed operations.)
862 unnamed_stmt_pstmt = NULL;
863 if (unnamed_stmt_context)
865 DropDependentPortals(unnamed_stmt_context);
866 MemoryContextDelete(unnamed_stmt_context);
868 unnamed_stmt_context = NULL;
871 * Switch to appropriate context for constructing parsetrees.
873 oldcontext = MemoryContextSwitchTo(MessageContext);
875 QueryContext = CurrentMemoryContext;
878 * Do basic parsing of the query or queries (this should be safe even if
879 * we are in aborted transaction state!)
881 parsetree_list = pg_parse_query(query_string);
883 if (log_statement != LOGSTMT_NONE || save_log_min_duration_statement != -1)
884 was_logged = log_after_parse(parsetree_list, query_string,
888 * Switch back to transaction context to enter the loop.
890 MemoryContextSwitchTo(oldcontext);
893 * Run through the raw parsetree(s) and process each one.
895 foreach(parsetree_item, parsetree_list)
897 Node *parsetree = (Node *) lfirst(parsetree_item);
898 const char *commandTag;
899 char completionTag[COMPLETION_TAG_BUFSIZE];
900 List *querytree_list,
903 DestReceiver *receiver;
907 * Get the command name for use in status display (it also becomes the
908 * default completion tag, down inside PortalRun). Set ps_status and
909 * do any special start-of-SQL-command processing needed by the
912 commandTag = CreateCommandTag(parsetree);
914 set_ps_display(commandTag);
916 BeginCommand(commandTag, dest);
919 * If we are in an aborted transaction, reject all commands except
920 * COMMIT/ABORT. It is important that this test occur before we try
921 * to do parse analysis, rewrite, or planning, since all those phases
922 * try to do database accesses, which may fail in abort state. (It
923 * might be safe to allow some additional utility commands in this
924 * state, but not many...)
926 if (IsAbortedTransactionBlockState() &&
927 !IsTransactionExitStmt(parsetree))
929 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
930 errmsg("current transaction is aborted, "
931 "commands ignored until end of transaction block")));
933 /* Make sure we are in a transaction command */
934 start_xact_command();
936 /* If we got a cancel signal in parsing or prior command, quit */
937 CHECK_FOR_INTERRUPTS();
940 * OK to analyze, rewrite, and plan this query.
942 * Switch to appropriate context for constructing querytrees (again,
943 * these must outlive the execution context).
945 oldcontext = MemoryContextSwitchTo(MessageContext);
947 querytree_list = pg_analyze_and_rewrite(parsetree, NULL, 0);
949 plantree_list = pg_plan_queries(querytree_list, NULL, true);
951 /* If we got a cancel signal in analysis or planning, quit */
952 CHECK_FOR_INTERRUPTS();
955 * Create unnamed portal to run the query or queries in. If there
956 * already is one, silently drop it.
958 portal = CreatePortal("", true, true);
959 /* Don't display the portal in pg_cursors */
960 portal->visible = false;
962 PortalDefineQuery(portal,
970 * Start the portal. No parameters here.
972 PortalStart(portal, NULL, InvalidSnapshot);
975 * Select the appropriate output format: text unless we are doing a
976 * FETCH from a binary cursor. (Pretty grotty to have to do this here
977 * --- but it avoids grottiness in other places. Ah, the joys of
978 * backward compatibility...)
980 format = 0; /* TEXT is default */
981 if (IsA(parsetree, FetchStmt))
983 FetchStmt *stmt = (FetchStmt *) parsetree;
987 Portal fportal = GetPortalByName(stmt->portalname);
989 if (PortalIsValid(fportal) &&
990 (fportal->cursorOptions & CURSOR_OPT_BINARY))
991 format = 1; /* BINARY */
994 PortalSetResultFormat(portal, 1, &format);
997 * Now we can create the destination receiver object.
999 receiver = CreateDestReceiver(dest, portal);
1002 * Switch back to transaction context for execution.
1004 MemoryContextSwitchTo(oldcontext);
1007 * Run the portal to completion, and then drop it (and the receiver).
1009 (void) PortalRun(portal,
1015 (*receiver->rDestroy) (receiver);
1017 PortalDrop(portal, false);
1019 if (IsA(parsetree, TransactionStmt))
1022 * If this was a transaction control statement, commit it. We will
1023 * start a new xact command for the next command (if any).
1025 finish_xact_command();
1027 else if (lnext(parsetree_item) == NULL)
1030 * If this is the last parsetree of the query string, close down
1031 * transaction statement before reporting command-complete. This
1032 * is so that any end-of-transaction errors are reported before
1033 * the command-complete message is issued, to avoid confusing
1034 * clients who will expect either a command-complete message or an
1035 * error, not one and then the other. But for compatibility with
1036 * historical Postgres behavior, we do not force a transaction
1037 * boundary between queries appearing in a single query string.
1039 finish_xact_command();
1044 * We need a CommandCounterIncrement after every query, except
1045 * those that start or end a transaction block.
1047 CommandCounterIncrement();
1051 * Tell client that we're done with this query. Note we emit exactly
1052 * one EndCommand report for each raw parsetree, thus one for each SQL
1053 * command the client sent, regardless of rewriting. (But a command
1054 * aborted by error will not send an EndCommand report at all.)
1056 EndCommand(completionTag, dest);
1057 } /* end loop over parsetrees */
1060 * Close down transaction statement, if one is open.
1062 finish_xact_command();
1065 * If there were no parsetrees, return EmptyQueryResponse message.
1067 if (!parsetree_list)
1070 QueryContext = NULL;
1073 * Combine processing here as we need to calculate the query duration in
1076 if (save_log_duration || save_log_min_duration_statement != -1)
1080 gettimeofday(&stop_t, NULL);
1081 if (stop_t.tv_usec < start_t.tv_usec)
1084 stop_t.tv_usec += 1000000;
1086 usecs = (long) (stop_t.tv_sec - start_t.tv_sec) * 1000000 +
1087 (long) (stop_t.tv_usec - start_t.tv_usec);
1089 /* Only print duration if we previously printed the statement. */
1090 if (was_logged && save_log_duration)
1092 (errmsg("duration: %ld.%03ld ms",
1093 (long) ((stop_t.tv_sec - start_t.tv_sec) * 1000 +
1094 (stop_t.tv_usec - start_t.tv_usec) / 1000),
1095 (long) (stop_t.tv_usec - start_t.tv_usec) % 1000)));
1098 * Output a duration_statement to the log if the query has exceeded
1099 * the min duration, or if we are to print all durations.
1101 if (save_log_min_duration_statement == 0 ||
1102 (save_log_min_duration_statement > 0 &&
1103 usecs >= save_log_min_duration_statement * 1000))
1105 (errmsg("duration: %ld.%03ld ms statement: %s%s",
1106 (long) ((stop_t.tv_sec - start_t.tv_sec) * 1000 +
1107 (stop_t.tv_usec - start_t.tv_usec) / 1000),
1108 (long) (stop_t.tv_usec - start_t.tv_usec) % 1000,
1110 prepare_string ? prepare_string : "")));
1113 if (save_log_statement_stats)
1114 ShowUsage("QUERY STATISTICS");
1116 if (prepare_string != NULL)
1117 pfree(prepare_string);
1119 debug_query_string = NULL;
1123 * exec_parse_message
1125 * Execute a "Parse" protocol message.
1128 exec_parse_message(const char *query_string, /* string to execute */
1129 const char *stmt_name, /* name for prepared stmt */
1130 Oid *paramTypes, /* parameter types */
1131 int numParams) /* number of parameters */
1133 MemoryContext oldcontext;
1134 List *parsetree_list;
1135 const char *commandTag;
1136 List *querytree_list,
1140 bool save_log_statement_stats = log_statement_stats;
1143 * Report query to various monitoring facilities.
1145 debug_query_string = query_string;
1147 pgstat_report_activity(query_string);
1149 set_ps_display("PARSE");
1151 if (save_log_statement_stats)
1154 if (log_statement == LOGSTMT_ALL)
1156 (errmsg("statement: [protocol] PREPARE %s AS %s",
1157 (*stmt_name != '\0') ? stmt_name : "<unnamed>",
1161 * Start up a transaction command so we can run parse analysis etc. (Note
1162 * that this will normally change current memory context.) Nothing happens
1163 * if we are already in one.
1165 start_xact_command();
1168 * Switch to appropriate context for constructing parsetrees.
1170 * We have two strategies depending on whether the prepared statement is
1171 * named or not. For a named prepared statement, we do parsing in
1172 * MessageContext and copy the finished trees into the prepared
1173 * statement's private context; then the reset of MessageContext releases
1174 * temporary space used by parsing and planning. For an unnamed prepared
1175 * statement, we assume the statement isn't going to hang around long, so
1176 * getting rid of temp space quickly is probably not worth the costs of
1177 * copying parse/plan trees. So in this case, we set up a special context
1178 * for the unnamed statement, and do all the parsing/planning therein.
1180 is_named = (stmt_name[0] != '\0');
1183 /* Named prepared statement --- parse in MessageContext */
1184 oldcontext = MemoryContextSwitchTo(MessageContext);
1188 /* Unnamed prepared statement --- release any prior unnamed stmt */
1189 unnamed_stmt_pstmt = NULL;
1190 if (unnamed_stmt_context)
1192 DropDependentPortals(unnamed_stmt_context);
1193 MemoryContextDelete(unnamed_stmt_context);
1195 unnamed_stmt_context = NULL;
1196 /* create context for parsing/planning */
1197 unnamed_stmt_context =
1198 AllocSetContextCreate(TopMemoryContext,
1199 "unnamed prepared statement",
1200 ALLOCSET_DEFAULT_MINSIZE,
1201 ALLOCSET_DEFAULT_INITSIZE,
1202 ALLOCSET_DEFAULT_MAXSIZE);
1203 oldcontext = MemoryContextSwitchTo(unnamed_stmt_context);
1206 QueryContext = CurrentMemoryContext;
1209 * Do basic parsing of the query or queries (this should be safe even if
1210 * we are in aborted transaction state!)
1212 parsetree_list = pg_parse_query(query_string);
1215 * We only allow a single user statement in a prepared statement. This is
1216 * mainly to keep the protocol simple --- otherwise we'd need to worry
1217 * about multiple result tupdescs and things like that.
1219 if (list_length(parsetree_list) > 1)
1221 (errcode(ERRCODE_SYNTAX_ERROR),
1222 errmsg("cannot insert multiple commands into a prepared statement")));
1224 if (parsetree_list != NIL)
1226 Node *parsetree = (Node *) linitial(parsetree_list);
1230 * Get the command name for possible use in status display.
1232 commandTag = CreateCommandTag(parsetree);
1235 * If we are in an aborted transaction, reject all commands except
1236 * COMMIT/ROLLBACK. It is important that this test occur before we
1237 * try to do parse analysis, rewrite, or planning, since all those
1238 * phases try to do database accesses, which may fail in abort state.
1239 * (It might be safe to allow some additional utility commands in this
1240 * state, but not many...)
1242 if (IsAbortedTransactionBlockState() &&
1243 !IsTransactionExitStmt(parsetree))
1245 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1246 errmsg("current transaction is aborted, "
1247 "commands ignored until end of transaction block")));
1250 * OK to analyze, rewrite, and plan this query. Note that the
1251 * originally specified parameter set is not required to be complete,
1252 * so we have to use parse_analyze_varparams().
1254 if (log_parser_stats)
1257 querytree_list = parse_analyze_varparams(parsetree,
1262 * Check all parameter types got determined, and convert array
1263 * representation to a list for storage.
1266 for (i = 0; i < numParams; i++)
1268 Oid ptype = paramTypes[i];
1270 if (ptype == InvalidOid || ptype == UNKNOWNOID)
1272 (errcode(ERRCODE_INDETERMINATE_DATATYPE),
1273 errmsg("could not determine data type of parameter $%d",
1275 param_list = lappend_oid(param_list, ptype);
1278 if (log_parser_stats)
1279 ShowUsage("PARSE ANALYSIS STATISTICS");
1281 querytree_list = pg_rewrite_queries(querytree_list);
1284 * If this is the unnamed statement and it has parameters, defer query
1285 * planning until Bind. Otherwise do it now.
1287 if (!is_named && numParams > 0)
1288 plantree_list = NIL;
1290 plantree_list = pg_plan_queries(querytree_list, NULL, true);
1294 /* Empty input string. This is legal. */
1296 querytree_list = NIL;
1297 plantree_list = NIL;
1301 /* If we got a cancel signal in analysis or planning, quit */
1302 CHECK_FOR_INTERRUPTS();
1305 * Store the query as a prepared statement. See above comments.
1309 StorePreparedStatement(stmt_name,
1319 PreparedStatement *pstmt;
1321 pstmt = (PreparedStatement *) palloc0(sizeof(PreparedStatement));
1322 /* query_string needs to be copied into unnamed_stmt_context */
1323 pstmt->query_string = pstrdup(query_string);
1324 /* the rest is there already */
1325 pstmt->commandTag = commandTag;
1326 pstmt->query_list = querytree_list;
1327 pstmt->plan_list = plantree_list;
1328 pstmt->argtype_list = param_list;
1329 pstmt->from_sql = false;
1330 pstmt->context = unnamed_stmt_context;
1331 /* Now the unnamed statement is complete and valid */
1332 unnamed_stmt_pstmt = pstmt;
1335 MemoryContextSwitchTo(oldcontext);
1337 QueryContext = NULL;
1340 * We do NOT close the open transaction command here; that only happens
1341 * when the client sends Sync. Instead, do CommandCounterIncrement just
1342 * in case something happened during parse/plan.
1344 CommandCounterIncrement();
1347 * Send ParseComplete.
1349 if (whereToSendOutput == DestRemote)
1350 pq_putemptymessage('1');
1352 if (save_log_statement_stats)
1353 ShowUsage("PARSE MESSAGE STATISTICS");
1355 debug_query_string = NULL;
1361 * Process a "Bind" message to create a portal from a prepared statement
1364 exec_bind_message(StringInfo input_message)
1366 const char *portal_name;
1367 const char *stmt_name;
1369 int16 *pformats = NULL;
1372 int16 *rformats = NULL;
1374 PreparedStatement *pstmt;
1376 ParamListInfo params;
1378 pgstat_report_activity("<BIND>");
1380 set_ps_display("BIND");
1383 * Start up a transaction command so we can call functions etc. (Note that
1384 * this will normally change current memory context.) Nothing happens if
1385 * we are already in one.
1387 start_xact_command();
1389 /* Switch back to message context */
1390 MemoryContextSwitchTo(MessageContext);
1392 /* Get the fixed part of the message */
1393 portal_name = pq_getmsgstring(input_message);
1394 stmt_name = pq_getmsgstring(input_message);
1396 /* Get the parameter format codes */
1397 numPFormats = pq_getmsgint(input_message, 2);
1398 if (numPFormats > 0)
1400 pformats = (int16 *) palloc(numPFormats * sizeof(int16));
1401 for (i = 0; i < numPFormats; i++)
1402 pformats[i] = pq_getmsgint(input_message, 2);
1405 /* Get the parameter value count */
1406 numParams = pq_getmsgint(input_message, 2);
1408 if (numPFormats > 1 && numPFormats != numParams)
1410 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1411 errmsg("bind message has %d parameter formats but %d parameters",
1412 numPFormats, numParams)));
1414 /* Find prepared statement */
1415 if (stmt_name[0] != '\0')
1416 pstmt = FetchPreparedStatement(stmt_name, true);
1419 /* special-case the unnamed statement */
1420 pstmt = unnamed_stmt_pstmt;
1423 (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
1424 errmsg("unnamed prepared statement does not exist")));
1427 if (numParams != list_length(pstmt->argtype_list))
1429 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1430 errmsg("bind message supplies %d parameters, but prepared statement \"%s\" requires %d",
1431 numParams, stmt_name, list_length(pstmt->argtype_list))));
1434 * If we are in aborted transaction state, the only portals we can
1435 * actually run are those containing COMMIT or ROLLBACK commands. We
1436 * disallow binding anything else to avoid problems with infrastructure
1437 * that expects to run inside a valid transaction. We also disallow
1438 * binding any parameters, since we can't risk calling user-defined I/O
1441 if (IsAbortedTransactionBlockState() &&
1442 (!IsTransactionExitStmtList(pstmt->query_list) ||
1445 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1446 errmsg("current transaction is aborted, "
1447 "commands ignored until end of transaction block")));
1450 * Create the portal. Allow silent replacement of an existing portal only
1451 * if the unnamed portal is specified.
1453 if (portal_name[0] == '\0')
1454 portal = CreatePortal(portal_name, true, true);
1456 portal = CreatePortal(portal_name, false, false);
1458 /* We need to output the parameter values someday */
1459 if (log_statement == LOGSTMT_ALL)
1461 (errmsg("statement: [protocol] <BIND> %s", portal_name)));
1464 * Fetch parameters, if any, and store in the portal's memory context.
1469 MemoryContext oldContext;
1471 oldContext = MemoryContextSwitchTo(PortalGetHeapMemory(portal));
1473 params = (ParamListInfo)
1474 palloc0((numParams + 1) * sizeof(ParamListInfoData));
1477 foreach(l, pstmt->argtype_list)
1479 Oid ptype = lfirst_oid(l);
1483 plength = pq_getmsgint(input_message, 4);
1484 isNull = (plength == -1);
1488 const char *pvalue = pq_getmsgbytes(input_message, plength);
1490 StringInfoData pbuf;
1493 if (numPFormats > 1)
1494 pformat = pformats[i];
1495 else if (numPFormats > 0)
1496 pformat = pformats[0];
1498 pformat = 0; /* default = text */
1501 * Rather than copying data around, we just set up a phony
1502 * StringInfo pointing to the correct portion of the message
1503 * buffer. We assume we can scribble on the message buffer so
1504 * as to maintain the convention that StringInfos have a
1505 * trailing null. This is grotty but is a big win when
1506 * dealing with very large parameter strings.
1508 pbuf.data = (char *) pvalue;
1509 pbuf.maxlen = plength + 1;
1513 csave = pbuf.data[plength];
1514 pbuf.data[plength] = '\0';
1522 getTypeInputInfo(ptype, &typinput, &typioparam);
1525 * We have to do encoding conversion before calling the
1528 pstring = pg_client_to_server(pbuf.data, plength);
1530 OidFunctionCall3(typinput,
1531 CStringGetDatum(pstring),
1532 ObjectIdGetDatum(typioparam),
1534 /* Free result of encoding conversion, if any */
1535 if (pstring != pbuf.data)
1538 else if (pformat == 1)
1544 * Call the parameter type's binary input converter
1546 getTypeBinaryInputInfo(ptype, &typreceive, &typioparam);
1549 OidFunctionCall3(typreceive,
1550 PointerGetDatum(&pbuf),
1551 ObjectIdGetDatum(typioparam),
1554 /* Trouble if it didn't eat the whole buffer */
1555 if (pbuf.cursor != pbuf.len)
1557 (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
1558 errmsg("incorrect binary data format in bind parameter %d",
1564 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1565 errmsg("unsupported format code: %d",
1569 /* Restore message buffer contents */
1570 pbuf.data[plength] = csave;
1573 params[i].kind = PARAM_NUM;
1574 params[i].id = i + 1;
1575 params[i].ptype = ptype;
1576 params[i].isnull = isNull;
1581 params[i].kind = PARAM_INVALID;
1583 MemoryContextSwitchTo(oldContext);
1588 /* Get the result format codes */
1589 numRFormats = pq_getmsgint(input_message, 2);
1590 if (numRFormats > 0)
1592 rformats = (int16 *) palloc(numRFormats * sizeof(int16));
1593 for (i = 0; i < numRFormats; i++)
1594 rformats[i] = pq_getmsgint(input_message, 2);
1597 pq_getmsgend(input_message);
1600 * If we didn't plan the query before, do it now. This allows the planner
1601 * to make use of the concrete parameter values we now have.
1603 * This happens only for unnamed statements, and so switching into the
1604 * statement context for planning is correct (see notes in
1605 * exec_parse_message).
1607 if (pstmt->plan_list == NIL && pstmt->query_list != NIL)
1609 MemoryContext oldContext = MemoryContextSwitchTo(pstmt->context);
1611 pstmt->plan_list = pg_plan_queries(pstmt->query_list, params, true);
1612 MemoryContextSwitchTo(oldContext);
1616 * Define portal and start execution.
1618 PortalDefineQuery(portal,
1619 pstmt->query_string,
1625 PortalStart(portal, params, InvalidSnapshot);
1628 * Apply the result format requests to the portal.
1630 PortalSetResultFormat(portal, numRFormats, rformats);
1633 * Send BindComplete.
1635 if (whereToSendOutput == DestRemote)
1636 pq_putemptymessage('2');
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 struct timeval start_t,
1654 bool save_log_duration = log_duration;
1655 int save_log_min_duration_statement = log_min_duration_statement;
1656 bool save_log_statement_stats = log_statement_stats;
1657 bool execute_is_fetch = false;
1659 /* Adjust destination to tell printtup.c what to do */
1660 dest = whereToSendOutput;
1661 if (dest == DestRemote)
1662 dest = DestRemoteExecute;
1664 portal = GetPortalByName(portal_name);
1665 if (!PortalIsValid(portal))
1667 (errcode(ERRCODE_UNDEFINED_CURSOR),
1668 errmsg("portal \"%s\" does not exist", portal_name)));
1671 * If we re-issue an Execute protocol request against an existing portal,
1672 * then we are only fetching more rows rather than completely re-executing
1673 * the query from the start. atStart is never reset for a v3 portal, so we
1674 * are safe to use this check.
1676 if (!portal->atStart)
1677 execute_is_fetch = true;
1680 * If the original query was a null string, just return
1681 * EmptyQueryResponse.
1683 if (portal->commandTag == NULL)
1685 Assert(portal->parseTrees == NIL);
1690 /* Should we display the portal names here? */
1691 if (execute_is_fetch)
1693 debug_query_string = "fetch message";
1694 pgstat_report_activity("<FETCH>");
1696 else if (portal->sourceText)
1698 debug_query_string = portal->sourceText;
1699 pgstat_report_activity(portal->sourceText);
1703 debug_query_string = "execute message";
1704 pgstat_report_activity("<EXECUTE>");
1707 set_ps_display(portal->commandTag);
1710 * We use save_log_* so "SET log_duration = true" and "SET
1711 * log_min_duration_statement = true" don't report incorrect time because
1712 * gettimeofday() wasn't called. Similarly, log_statement_stats has to be
1715 if (save_log_duration || save_log_min_duration_statement != -1)
1716 gettimeofday(&start_t, NULL);
1718 if (save_log_statement_stats)
1721 if (log_statement == LOGSTMT_ALL)
1722 /* We have the portal, so output the source query. */
1724 (errmsg("statement: [protocol] %sEXECUTE %s [PREPARE: %s]",
1725 (execute_is_fetch) ? "FETCH from " : "",
1726 (*portal_name != '\0') ? portal_name : "<unnamed>",
1727 portal->sourceText ? portal->sourceText : "")));
1729 BeginCommand(portal->commandTag, dest);
1732 * Create dest receiver in MessageContext (we don't want it in transaction
1733 * context, because that may get deleted if portal contains VACUUM).
1735 receiver = CreateDestReceiver(dest, portal);
1738 * Ensure we are in a transaction command (this should normally be the
1739 * case already due to prior BIND).
1741 start_xact_command();
1744 * If we are in aborted transaction state, the only portals we can
1745 * actually run are those containing COMMIT or ROLLBACK commands.
1747 if (IsAbortedTransactionBlockState() &&
1748 !IsTransactionExitStmtList(portal->parseTrees))
1750 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1751 errmsg("current transaction is aborted, "
1752 "commands ignored until end of transaction block")));
1754 /* Check for cancel signal before we start execution */
1755 CHECK_FOR_INTERRUPTS();
1758 * Okay to run the portal.
1761 max_rows = FETCH_ALL;
1763 completed = PortalRun(portal,
1769 (*receiver->rDestroy) (receiver);
1773 if (IsTransactionStmtList(portal->parseTrees))
1776 * If this was a transaction control statement, commit it. We
1777 * will start a new xact command for the next command (if any).
1779 finish_xact_command();
1784 * We need a CommandCounterIncrement after every query, except
1785 * those that start or end a transaction block.
1787 CommandCounterIncrement();
1790 /* Send appropriate CommandComplete to client */
1791 EndCommand(completionTag, dest);
1795 /* Portal run not complete, so send PortalSuspended */
1796 if (whereToSendOutput == DestRemote)
1797 pq_putemptymessage('s');
1801 * Combine processing here as we need to calculate the query duration in
1804 if (save_log_duration || save_log_min_duration_statement != -1)
1808 gettimeofday(&stop_t, NULL);
1809 if (stop_t.tv_usec < start_t.tv_usec)
1812 stop_t.tv_usec += 1000000;
1814 usecs = (long) (stop_t.tv_sec - start_t.tv_sec) * 1000000 +
1815 (long) (stop_t.tv_usec - start_t.tv_usec);
1817 /* Only print duration if we previously printed the statement. */
1818 if (log_statement == LOGSTMT_ALL && save_log_duration)
1820 (errmsg("duration: %ld.%03ld ms",
1821 (long) ((stop_t.tv_sec - start_t.tv_sec) * 1000 +
1822 (stop_t.tv_usec - start_t.tv_usec) / 1000),
1823 (long) (stop_t.tv_usec - start_t.tv_usec) % 1000)));
1826 * Output a duration_statement to the log if the query has exceeded
1827 * the min duration, or if we are to print all durations.
1829 if (save_log_min_duration_statement == 0 ||
1830 (save_log_min_duration_statement > 0 &&
1831 usecs >= save_log_min_duration_statement * 1000))
1833 (errmsg("duration: %ld.%03ld ms statement: [protocol] %sEXECUTE %s [PREPARE: %s]",
1834 (long) ((stop_t.tv_sec - start_t.tv_sec) * 1000 +
1835 (stop_t.tv_usec - start_t.tv_usec) / 1000),
1836 (long) (stop_t.tv_usec - start_t.tv_usec) % 1000,
1837 (execute_is_fetch) ? "FETCH from " : "",
1838 (*portal_name != '\0') ? portal_name : "<unnamed>",
1839 portal->sourceText ? portal->sourceText : "")));
1842 if (save_log_statement_stats)
1843 ShowUsage("QUERY STATISTICS");
1845 debug_query_string = NULL;
1849 * exec_describe_statement_message
1851 * Process a "Describe" message for a prepared statement
1854 exec_describe_statement_message(const char *stmt_name)
1856 PreparedStatement *pstmt;
1862 * Start up a transaction command. (Note that this will normally change
1863 * current memory context.) Nothing happens if we are already in one.
1865 start_xact_command();
1867 /* Switch back to message context */
1868 MemoryContextSwitchTo(MessageContext);
1870 /* Find prepared statement */
1871 if (stmt_name[0] != '\0')
1872 pstmt = FetchPreparedStatement(stmt_name, true);
1875 /* special-case the unnamed statement */
1876 pstmt = unnamed_stmt_pstmt;
1879 (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
1880 errmsg("unnamed prepared statement does not exist")));
1884 * If we are in aborted transaction state, we can't safely create a result
1885 * tupledesc, because that needs catalog accesses. Hence, refuse to
1886 * Describe statements that return data. (We shouldn't just refuse all
1887 * Describes, since that might break the ability of some clients to issue
1888 * COMMIT or ROLLBACK commands, if they use code that blindly Describes
1889 * whatever it does.) We can Describe parameters without doing anything
1890 * dangerous, so we don't restrict that.
1892 if (IsAbortedTransactionBlockState() &&
1893 PreparedStatementReturnsTuples(pstmt))
1895 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1896 errmsg("current transaction is aborted, "
1897 "commands ignored until end of transaction block")));
1899 if (whereToSendOutput != DestRemote)
1900 return; /* can't actually do anything... */
1903 * First describe the parameters...
1905 pq_beginmessage(&buf, 't'); /* parameter description message type */
1906 pq_sendint(&buf, list_length(pstmt->argtype_list), 2);
1908 foreach(l, pstmt->argtype_list)
1910 Oid ptype = lfirst_oid(l);
1912 pq_sendint(&buf, (int) ptype, 4);
1914 pq_endmessage(&buf);
1917 * Next send RowDescription or NoData to describe the result...
1919 tupdesc = FetchPreparedStatementResultDesc(pstmt);
1921 SendRowDescriptionMessage(tupdesc,
1922 FetchPreparedStatementTargetList(pstmt),
1925 pq_putemptymessage('n'); /* NoData */
1930 * exec_describe_portal_message
1932 * Process a "Describe" message for a portal
1935 exec_describe_portal_message(const char *portal_name)
1940 * Start up a transaction command. (Note that this will normally change
1941 * current memory context.) Nothing happens if we are already in one.
1943 start_xact_command();
1945 /* Switch back to message context */
1946 MemoryContextSwitchTo(MessageContext);
1948 portal = GetPortalByName(portal_name);
1949 if (!PortalIsValid(portal))
1951 (errcode(ERRCODE_UNDEFINED_CURSOR),
1952 errmsg("portal \"%s\" does not exist", portal_name)));
1955 * If we are in aborted transaction state, we can't run
1956 * SendRowDescriptionMessage(), because that needs catalog accesses.
1957 * Hence, refuse to Describe portals that return data. (We shouldn't just
1958 * refuse all Describes, since that might break the ability of some
1959 * clients to issue COMMIT or ROLLBACK commands, if they use code that
1960 * blindly Describes whatever it does.)
1962 if (IsAbortedTransactionBlockState() &&
1965 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1966 errmsg("current transaction is aborted, "
1967 "commands ignored until end of transaction block")));
1969 if (whereToSendOutput != DestRemote)
1970 return; /* can't actually do anything... */
1972 if (portal->tupDesc)
1973 SendRowDescriptionMessage(portal->tupDesc,
1974 FetchPortalTargetList(portal),
1977 pq_putemptymessage('n'); /* NoData */
1982 * Convenience routines for starting/committing a single command.
1985 start_xact_command(void)
1990 (errmsg_internal("StartTransactionCommand")));
1991 StartTransactionCommand();
1993 /* Set statement timeout running, if any */
1994 if (StatementTimeout > 0)
1995 enable_sig_alarm(StatementTimeout, true);
1997 cancel_from_timeout = false;
1999 xact_started = true;
2004 finish_xact_command(void)
2008 /* Cancel any active statement timeout before committing */
2009 disable_sig_alarm(true);
2011 /* Now commit the command */
2013 (errmsg_internal("CommitTransactionCommand")));
2015 CommitTransactionCommand();
2017 #ifdef MEMORY_CONTEXT_CHECKING
2018 /* Check all memory contexts that weren't freed during commit */
2019 /* (those that were, were checked before being deleted) */
2020 MemoryContextCheck(TopMemoryContext);
2023 #ifdef SHOW_MEMORY_STATS
2024 /* Print mem stats after each commit for leak tracking */
2026 MemoryContextStats(TopMemoryContext);
2029 xact_started = false;
2035 * Convenience routines for checking whether a statement is one of the
2036 * ones that we allow in transaction-aborted state.
2040 IsTransactionExitStmt(Node *parsetree)
2042 if (parsetree && IsA(parsetree, TransactionStmt))
2044 TransactionStmt *stmt = (TransactionStmt *) parsetree;
2046 if (stmt->kind == TRANS_STMT_COMMIT ||
2047 stmt->kind == TRANS_STMT_PREPARE ||
2048 stmt->kind == TRANS_STMT_ROLLBACK ||
2049 stmt->kind == TRANS_STMT_ROLLBACK_TO)
2056 IsTransactionExitStmtList(List *parseTrees)
2058 if (list_length(parseTrees) == 1)
2060 Query *query = (Query *) linitial(parseTrees);
2062 if (query->commandType == CMD_UTILITY &&
2063 IsTransactionExitStmt(query->utilityStmt))
2070 IsTransactionStmtList(List *parseTrees)
2072 if (list_length(parseTrees) == 1)
2074 Query *query = (Query *) linitial(parseTrees);
2076 if (query->commandType == CMD_UTILITY &&
2077 query->utilityStmt && IsA(query->utilityStmt, TransactionStmt))
2084 /* --------------------------------
2085 * signal handler routines used in PostgresMain()
2086 * --------------------------------
2090 * quickdie() occurs when signalled SIGQUIT by the postmaster.
2092 * Some backend has bought the farm,
2093 * so we need to stop what we're doing and exit.
2096 quickdie(SIGNAL_ARGS)
2098 PG_SETMASK(&BlockSig);
2101 * Ideally this should be ereport(FATAL), but then we'd not get control
2105 (errcode(ERRCODE_CRASH_SHUTDOWN),
2106 errmsg("terminating connection because of crash of another server process"),
2107 errdetail("The postmaster has commanded this server process to roll back"
2108 " the current transaction and exit, because another"
2109 " server process exited abnormally and possibly corrupted"
2111 errhint("In a moment you should be able to reconnect to the"
2112 " database and repeat your command.")));
2115 * DO NOT proc_exit() -- we're here because shared memory may be
2116 * corrupted, so we don't want to try to clean up our transaction. Just
2117 * nail the windows shut and get out of town.
2119 * Note we do exit(1) not exit(0). This is to force the postmaster into a
2120 * system reset cycle if some idiot DBA sends a manual SIGQUIT to a random
2121 * backend. This is necessary precisely because we don't clean up our
2122 * shared memory state.
2128 * Shutdown signal from postmaster: abort transaction and exit
2129 * at soonest convenient time
2134 int save_errno = errno;
2136 /* Don't joggle the elbow of proc_exit */
2137 if (!proc_exit_inprogress)
2139 InterruptPending = true;
2140 ProcDiePending = true;
2143 * If it's safe to interrupt, and we're waiting for input or a lock,
2144 * service the interrupt immediately
2146 if (ImmediateInterruptOK && InterruptHoldoffCount == 0 &&
2147 CritSectionCount == 0)
2149 /* bump holdoff count to make ProcessInterrupts() a no-op */
2150 /* until we are done getting ready for it */
2151 InterruptHoldoffCount++;
2152 DisableNotifyInterrupt();
2153 DisableCatchupInterrupt();
2154 /* Make sure CheckDeadLock won't run while shutting down... */
2156 InterruptHoldoffCount--;
2157 ProcessInterrupts();
2165 * Timeout or shutdown signal from postmaster during client authentication.
2168 * XXX: possible future improvement: try to send a message indicating
2169 * why we are disconnecting. Problem is to be sure we don't block while
2170 * doing so, nor mess up the authentication message exchange.
2173 authdie(SIGNAL_ARGS)
2179 * Query-cancel signal from postmaster: abort current transaction
2180 * at soonest convenient time
2183 StatementCancelHandler(SIGNAL_ARGS)
2185 int save_errno = errno;
2188 * Don't joggle the elbow of proc_exit
2190 if (!proc_exit_inprogress)
2192 InterruptPending = true;
2193 QueryCancelPending = true;
2196 * If it's safe to interrupt, and we're waiting for a lock, service
2197 * the interrupt immediately. No point in interrupting if we're
2198 * waiting for input, however.
2200 if (ImmediateInterruptOK && InterruptHoldoffCount == 0 &&
2201 CritSectionCount == 0)
2203 /* bump holdoff count to make ProcessInterrupts() a no-op */
2204 /* until we are done getting ready for it */
2205 InterruptHoldoffCount++;
2206 if (LockWaitCancel())
2208 DisableNotifyInterrupt();
2209 DisableCatchupInterrupt();
2210 InterruptHoldoffCount--;
2211 ProcessInterrupts();
2214 InterruptHoldoffCount--;
2221 /* signal handler for floating point exception */
2223 FloatExceptionHandler(SIGNAL_ARGS)
2226 (errcode(ERRCODE_FLOATING_POINT_EXCEPTION),
2227 errmsg("floating-point exception"),
2228 errdetail("An invalid floating-point operation was signaled. "
2229 "This probably means an out-of-range result or an "
2230 "invalid operation, such as division by zero.")));
2233 /* SIGHUP: set flag to re-read config file at next convenient time */
2235 SigHupHandler(SIGNAL_ARGS)
2242 * ProcessInterrupts: out-of-line portion of CHECK_FOR_INTERRUPTS() macro
2244 * If an interrupt condition is pending, and it's safe to service it,
2245 * then clear the flag and accept the interrupt. Called only when
2246 * InterruptPending is true.
2249 ProcessInterrupts(void)
2251 /* OK to accept interrupt now? */
2252 if (InterruptHoldoffCount != 0 || CritSectionCount != 0)
2254 InterruptPending = false;
2257 ProcDiePending = false;
2258 QueryCancelPending = false; /* ProcDie trumps QueryCancel */
2259 ImmediateInterruptOK = false; /* not idle anymore */
2260 DisableNotifyInterrupt();
2261 DisableCatchupInterrupt();
2263 (errcode(ERRCODE_ADMIN_SHUTDOWN),
2264 errmsg("terminating connection due to administrator command")));
2266 if (QueryCancelPending)
2268 QueryCancelPending = false;
2269 ImmediateInterruptOK = false; /* not idle anymore */
2270 DisableNotifyInterrupt();
2271 DisableCatchupInterrupt();
2272 if (cancel_from_timeout)
2274 (errcode(ERRCODE_QUERY_CANCELED),
2275 errmsg("canceling statement due to statement timeout")));
2278 (errcode(ERRCODE_QUERY_CANCELED),
2279 errmsg("canceling statement due to user request")));
2281 /* If we get here, do nothing (probably, QueryCancelPending was reset) */
2286 * check_stack_depth: check for excessively deep recursion
2288 * This should be called someplace in any recursive routine that might possibly
2289 * recurse deep enough to overflow the stack. Most Unixen treat stack
2290 * overflow as an unrecoverable SIGSEGV, so we want to error out ourselves
2291 * before hitting the hardware limit. Unfortunately we have no direct way
2292 * to detect the hardware limit, so we have to rely on the admin to set a
2293 * GUC variable for it ...
2296 check_stack_depth(void)
2302 * Compute distance from PostgresMain's local variables to my own
2304 * Note: in theory stack_depth should be ptrdiff_t or some such, but since
2305 * the whole point of this code is to bound the value to something much
2306 * less than integer-sized, int should work fine.
2308 stack_depth = (int) (stack_base_ptr - &stack_top_loc);
2311 * Take abs value, since stacks grow up on some machines, down on others
2313 if (stack_depth < 0)
2314 stack_depth = -stack_depth;
2319 * The test on stack_base_ptr prevents us from erroring out if called
2320 * during process setup or in a non-backend process. Logically it should
2321 * be done first, but putting it here avoids wasting cycles during normal
2324 if (stack_depth > max_stack_depth_bytes &&
2325 stack_base_ptr != NULL)
2328 (errcode(ERRCODE_STATEMENT_TOO_COMPLEX),
2329 errmsg("stack depth limit exceeded"),
2330 errhint("Increase the configuration parameter \"max_stack_depth\".")));
2334 /* GUC assign hook to update max_stack_depth_bytes from max_stack_depth */
2336 assign_max_stack_depth(int newval, bool doit, GucSource source)
2338 /* Range check was already handled by guc.c */
2340 max_stack_depth_bytes = newval * 1024;
2346 usage(const char *progname)
2348 printf(_("%s is the PostgreSQL stand-alone backend. It is not\nintended to be used by normal users.\n\n"), progname);
2350 printf(_("Usage:\n %s [OPTION]... DBNAME\n\n"), progname);
2351 printf(_("Options:\n"));
2352 #ifdef USE_ASSERT_CHECKING
2353 printf(_(" -A 1|0 enable/disable run-time assert checking\n"));
2355 printf(_(" -B NBUFFERS number of shared buffers\n"));
2356 printf(_(" -c NAME=VALUE set run-time parameter\n"));
2357 printf(_(" -d 0-5 debugging level\n"));
2358 printf(_(" -D DATADIR database directory\n"));
2359 printf(_(" -e use European date input format (DMY)\n"));
2360 printf(_(" -E echo statement before execution\n"));
2361 printf(_(" -F turn fsync off\n"));
2362 printf(_(" -j do not use newline as interactive query delimiter\n"));
2363 printf(_(" -r FILENAME send stdout and stderr to given file\n"));
2364 printf(_(" -s show statistics after each query\n"));
2365 printf(_(" -S WORK-MEM set amount of memory for sorts (in kB)\n"));
2366 printf(_(" --NAME=VALUE set run-time parameter\n"));
2367 printf(_(" --describe-config describe configuration parameters, then exit\n"));
2368 printf(_(" --help show this help, then exit\n"));
2369 printf(_(" --version output version information, then exit\n"));
2370 printf(_("\nDeveloper options:\n"));
2371 printf(_(" -f s|i|n|m|h forbid use of some plan types\n"));
2372 printf(_(" -O allow system table structure changes\n"));
2373 printf(_(" -P disable system indexes\n"));
2374 printf(_(" -t pa|pl|ex show timings after each query\n"));
2375 printf(_(" -W NUM wait NUM seconds to allow attach from a debugger\n"));
2376 printf(_("\nReport bugs to <pgsql-bugs@postgresql.org>.\n"));
2381 * set_debug_options --- apply "-d N" command line option
2383 * -d is not quite the same as setting log_min_messages because it enables
2384 * other output options.
2387 set_debug_options(int debug_flag, GucContext context, GucSource source)
2393 sprintf(debugstr, "debug%d", debug_flag);
2394 SetConfigOption("log_min_messages", debugstr, context, source);
2397 SetConfigOption("log_min_messages", "notice", context, source);
2399 if (debug_flag >= 1 && context == PGC_POSTMASTER)
2401 SetConfigOption("log_connections", "true", context, source);
2402 SetConfigOption("log_disconnections", "true", context, source);
2404 if (debug_flag >= 2)
2405 SetConfigOption("log_statement", "all", context, source);
2406 if (debug_flag >= 3)
2407 SetConfigOption("debug_print_parse", "true", context, source);
2408 if (debug_flag >= 4)
2409 SetConfigOption("debug_print_plan", "true", context, source);
2410 if (debug_flag >= 5)
2411 SetConfigOption("debug_print_rewritten", "true", context, source);
2416 set_plan_disabling_options(const char *arg, GucContext context, GucSource source)
2422 case 's': /* seqscan */
2423 tmp = "enable_seqscan";
2425 case 'i': /* indexscan */
2426 tmp = "enable_indexscan";
2428 case 'b': /* bitmapscan */
2429 tmp = "enable_bitmapscan";
2431 case 't': /* tidscan */
2432 tmp = "enable_tidscan";
2434 case 'n': /* nestloop */
2435 tmp = "enable_nestloop";
2437 case 'm': /* mergejoin */
2438 tmp = "enable_mergejoin";
2440 case 'h': /* hashjoin */
2441 tmp = "enable_hashjoin";
2446 SetConfigOption(tmp, "false", context, source);
2455 get_stats_option_name(const char *arg)
2460 if (optarg[1] == 'a') /* "parser" */
2461 return "log_parser_stats";
2462 else if (optarg[1] == 'l') /* "planner" */
2463 return "log_planner_stats";
2466 case 'e': /* "executor" */
2467 return "log_executor_stats";
2475 /* ----------------------------------------------------------------
2477 * postgres main loop -- all backends, interactive or otherwise start here
2479 * argc/argv are the command line arguments to be used. (When being forked
2480 * by the postmaster, these are not the original argv array of the process.)
2481 * username is the (possibly authenticated) PostgreSQL user name to be used
2483 * ----------------------------------------------------------------
2486 PostgresMain(int argc, char *argv[], const char *username)
2489 const char *dbname = NULL;
2490 char *userDoption = NULL;
2493 int debug_flag = -1; /* -1 means not given */
2494 List *guc_names = NIL; /* for SUSET options */
2495 List *guc_values = NIL;
2497 GucSource gucsource;
2501 StringInfoData input_message;
2502 sigjmp_buf local_sigjmp_buf;
2503 volatile bool send_ready_for_query = true;
2505 #define PendingConfigOption(name,val) \
2506 (guc_names = lappend(guc_names, pstrdup(name)), \
2507 guc_values = lappend(guc_values, pstrdup(val)))
2510 * Catch standard options before doing much else. This even works on
2511 * systems without getopt_long.
2513 if (!IsUnderPostmaster && argc > 1)
2515 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
2520 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
2522 puts(PG_VERSIONSTR);
2528 * initialize globals (already done if under postmaster, but not if
2529 * standalone; cheap enough to do over)
2531 MyProcPid = getpid();
2534 * Fire up essential subsystems: error and memory management
2536 * If we are running under the postmaster, this is done already.
2538 if (!IsUnderPostmaster)
2539 MemoryContextInit();
2541 set_ps_display("startup");
2543 SetProcessingMode(InitProcessing);
2545 /* Set up reference point for stack depth checking */
2546 stack_base_ptr = &stack_base;
2548 /* Compute paths, if we didn't inherit them from postmaster */
2549 if (my_exec_path[0] == '\0')
2551 if (find_my_exec(argv[0], my_exec_path) < 0)
2552 elog(FATAL, "%s: could not locate my own executable path",
2556 if (pkglib_path[0] == '\0')
2557 get_pkglib_path(my_exec_path, pkglib_path);
2560 * Set default values for command-line options.
2564 if (!IsUnderPostmaster)
2565 InitializeGUCOptions();
2568 * parse command line arguments
2570 * There are now two styles of command line layout for the backend:
2572 * For interactive use (not started from postmaster) the format is
2573 * postgres [switches] [databasename]
2574 * If the databasename is omitted it is taken to be the user name.
2576 * When started from the postmaster, the format is
2577 * postgres [secure switches] -p databasename [insecure switches]
2578 * Switches appearing after -p came from the client (via "options"
2579 * field of connection request). For security reasons we restrict
2580 * what these switches can do.
2584 /* all options are allowed until '-p' */
2586 ctx = PGC_POSTMASTER;
2587 gucsource = PGC_S_ARGV; /* initial switches came from command line */
2589 while ((flag = getopt(argc, argv, "A:B:c:D:d:EeFf:h:ijk:lN:nOo:Pp:r:S:sTt:v:W:y:-:")) != -1)
2594 SetConfigOption("debug_assertions", optarg, ctx, gucsource);
2598 SetConfigOption("shared_buffers", optarg, ctx, gucsource);
2603 userDoption = optarg;
2607 debug_flag = atoi(optarg);
2615 SetConfigOption("datestyle", "euro", ctx, gucsource);
2619 SetConfigOption("fsync", "false", ctx, gucsource);
2623 if (!set_plan_disabling_options(optarg, ctx, gucsource))
2628 SetConfigOption("listen_addresses", optarg, ctx, gucsource);
2632 SetConfigOption("listen_addresses", "*", ctx, gucsource);
2640 SetConfigOption("unix_socket_directory", optarg, ctx, gucsource);
2644 SetConfigOption("ssl", "true", ctx, gucsource);
2648 SetConfigOption("max_connections", optarg, ctx, gucsource);
2652 /* ignored for consistency with postmaster */
2656 SetConfigOption("allow_system_table_mods", "true", ctx, gucsource);
2664 SetConfigOption("ignore_system_indexes", "true", ctx, gucsource);
2668 SetConfigOption("port", optarg, ctx, gucsource);
2672 /* send output (stdout and stderr) to the given file */
2674 StrNCpy(OutputFileName, optarg, MAXPGPATH);
2678 SetConfigOption("work_mem", optarg, ctx, gucsource);
2683 * Since log options are SUSET, we need to postpone unless
2684 * still in secure context
2686 if (ctx == PGC_BACKEND)
2687 PendingConfigOption("log_statement_stats", "true");
2689 SetConfigOption("log_statement_stats", "true",
2694 /* ignored for consistency with postmaster */
2699 const char *tmp = get_stats_option_name(optarg);
2702 if (ctx == PGC_BACKEND)
2703 PendingConfigOption(tmp, "true");
2705 SetConfigOption(tmp, "true", ctx, gucsource);
2714 FrontendProtocol = (ProtocolVersion) atoi(optarg);
2718 SetConfigOption("post_auth_delay", optarg, ctx, gucsource);
2724 * y - special flag passed if backend was forked by a
2729 dbname = strdup(optarg);
2731 secure = false; /* subsequent switches are NOT secure */
2733 gucsource = PGC_S_CLIENT;
2743 ParseLongOption(optarg, &name, &value);
2748 (errcode(ERRCODE_SYNTAX_ERROR),
2749 errmsg("--%s requires a value",
2753 (errcode(ERRCODE_SYNTAX_ERROR),
2754 errmsg("-c %s requires a value",
2759 * If a SUSET option, must postpone evaluation, unless we
2760 * are still reading secure switches.
2762 if (ctx == PGC_BACKEND && IsSuperuserConfigOption(name))
2763 PendingConfigOption(name, value);
2765 SetConfigOption(name, value, ctx, gucsource);
2779 * Process any additional GUC variable settings passed in startup packet.
2780 * These are handled exactly like command-line variables.
2782 if (MyProcPort != NULL)
2784 ListCell *gucopts = list_head(MyProcPort->guc_options);
2791 name = lfirst(gucopts);
2792 gucopts = lnext(gucopts);
2794 value = lfirst(gucopts);
2795 gucopts = lnext(gucopts);
2797 if (IsSuperuserConfigOption(name))
2798 PendingConfigOption(name, value);
2800 SetConfigOption(name, value, PGC_BACKEND, PGC_S_CLIENT);
2804 /* Acquire configuration parameters, unless inherited from postmaster */
2805 if (!IsUnderPostmaster)
2807 if (!SelectConfigFiles(userDoption, argv[0]))
2809 /* If timezone is not set, determine what the OS uses */
2810 pg_timezone_initialize();
2814 pg_usleep(PostAuthDelay * 1000000L);
2817 * Set up signal handlers and masks.
2819 * Note that postmaster blocked all signals before forking child process,
2820 * so there is no race condition whereby we might receive a signal before
2821 * we have set up the handler.
2823 * Also note: it's best not to use any signals that are SIG_IGNored in the
2824 * postmaster. If such a signal arrives before we are able to change the
2825 * handler to non-SIG_IGN, it'll get dropped. Instead, make a dummy
2826 * handler in the postmaster to reserve the signal. (Of course, this isn't
2827 * an issue for signals that are locally generated, such as SIGALRM and
2830 pqsignal(SIGHUP, SigHupHandler); /* set flag to read config file */
2831 pqsignal(SIGINT, StatementCancelHandler); /* cancel current query */
2832 pqsignal(SIGTERM, die); /* cancel current query and exit */
2833 pqsignal(SIGQUIT, quickdie); /* hard crash time */
2834 pqsignal(SIGALRM, handle_sig_alarm); /* timeout conditions */
2837 * Ignore failure to write to frontend. Note: if frontend closes
2838 * connection, we will notice it and exit cleanly when control next
2839 * returns to outer loop. This seems safer than forcing exit in the midst
2840 * of output during who-knows-what operation...
2842 pqsignal(SIGPIPE, SIG_IGN);
2843 pqsignal(SIGUSR1, CatchupInterruptHandler);
2844 pqsignal(SIGUSR2, NotifyInterruptHandler);
2845 pqsignal(SIGFPE, FloatExceptionHandler);
2848 * Reset some signals that are accepted by postmaster but not by backend
2850 pqsignal(SIGCHLD, SIG_DFL); /* system() requires this on some platforms */
2854 /* We allow SIGQUIT (quickdie) at all times */
2855 #ifdef HAVE_SIGPROCMASK
2856 sigdelset(&BlockSig, SIGQUIT);
2858 BlockSig &= ~(sigmask(SIGQUIT));
2861 PG_SETMASK(&BlockSig); /* block everything except SIGQUIT */
2863 if (IsUnderPostmaster)
2865 /* noninteractive case: nothing should be left after switches */
2866 if (errs || argc != optind || dbname == NULL)
2869 (errcode(ERRCODE_SYNTAX_ERROR),
2870 errmsg("invalid command-line arguments for server process"),
2871 errhint("Try \"%s --help\" for more information.", argv[0])));
2878 /* interactive case: database name can be last arg on command line */
2879 if (errs || argc - optind > 1)
2882 (errcode(ERRCODE_SYNTAX_ERROR),
2883 errmsg("%s: invalid command-line arguments",
2885 errhint("Try \"%s --help\" for more information.", argv[0])));
2887 else if (argc - optind == 1)
2888 dbname = argv[optind];
2889 else if ((dbname = username) == NULL)
2892 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2893 errmsg("%s: no database nor user name specified",
2898 * Validate we have been given a reasonable-looking DataDir (if under
2899 * postmaster, assume postmaster did this already).
2902 ValidatePgVersion(DataDir);
2904 /* Change into DataDir (if under postmaster, was done already) */
2908 * Create lockfile for data directory.
2910 CreateDataDirLockFile(false);
2915 * Start up xlog for standalone backend, and register to have it
2916 * closed down at exit.
2919 on_shmem_exit(ShutdownXLOG, 0);
2922 * Read any existing FSM cache file, and register to write one out at
2926 on_shmem_exit(DumpFreeSpaceMap, 0);
2929 * We have to build the flat file for pg_database, but not for the
2930 * user and group tables, since we won't try to do authentication.
2932 BuildFlatFiles(true);
2936 * Create a per-backend PGPROC struct in shared memory, except in
2937 * the EXEC_BACKEND case where this was done in SubPostmasterMain.
2938 * We must do this before we can use LWLocks (and in the EXEC_BACKEND
2939 * case we already had to do some stuff with LWLocks).
2942 if (!IsUnderPostmaster)
2949 * General initialization.
2951 * NOTE: if you are tempted to add code in this vicinity, consider putting
2952 * it inside InitPostgres() instead. In particular, anything that
2953 * involves database access should be there, not here.
2956 (errmsg_internal("InitPostgres")));
2957 am_superuser = InitPostgres(dbname, username);
2959 SetProcessingMode(NormalProcessing);
2962 * Now that we know if client is a superuser, we can try to apply SUSET
2963 * GUC options that came from the client.
2965 ctx = am_superuser ? PGC_SUSET : PGC_USERSET;
2967 if (debug_flag >= 0)
2968 set_debug_options(debug_flag, ctx, PGC_S_CLIENT);
2970 if (guc_names != NIL)
2975 forboth(namcell, guc_names, valcell, guc_values)
2977 char *name = (char *) lfirst(namcell);
2978 char *value = (char *) lfirst(valcell);
2980 SetConfigOption(name, value, ctx, PGC_S_CLIENT);
2987 * Now all GUC states are fully set up. Report them to client if
2990 BeginReportingGUCOptions();
2993 * Also set up handler to log session end; we have to wait till now to be
2994 * sure Log_disconnections has its final value.
2996 if (IsUnderPostmaster && Log_disconnections)
2997 on_proc_exit(log_disconnections, 0);
3000 * Send this backend's cancellation info to the frontend.
3002 if (whereToSendOutput == DestRemote &&
3003 PG_PROTOCOL_MAJOR(FrontendProtocol) >= 2)
3007 pq_beginmessage(&buf, 'K');
3008 pq_sendint(&buf, (int32) MyProcPid, sizeof(int32));
3009 pq_sendint(&buf, (int32) MyCancelKey, sizeof(int32));
3010 pq_endmessage(&buf);
3011 /* Need not flush since ReadyForQuery will do it. */
3014 /* Welcome banner for standalone case */
3015 if (whereToSendOutput == DestDebug)
3016 printf("\nPostgreSQL stand-alone backend %s\n", PG_VERSION);
3019 * Create the memory context we will use in the main loop.
3021 * MessageContext is reset once per iteration of the main loop, ie, upon
3022 * completion of processing of each command message from the client.
3024 MessageContext = AllocSetContextCreate(TopMemoryContext,
3026 ALLOCSET_DEFAULT_MINSIZE,
3027 ALLOCSET_DEFAULT_INITSIZE,
3028 ALLOCSET_DEFAULT_MAXSIZE);
3031 * Remember stand-alone backend startup time
3033 if (!IsUnderPostmaster)
3034 PgStartTime = GetCurrentTimestamp();
3037 * POSTGRES main processing loop begins here
3039 * If an exception is encountered, processing resumes here so we abort the
3040 * current transaction and start a new one.
3042 * You might wonder why this isn't coded as an infinite loop around a
3043 * PG_TRY construct. The reason is that this is the bottom of the
3044 * exception stack, and so with PG_TRY there would be no exception handler
3045 * in force at all during the CATCH part. By leaving the outermost setjmp
3046 * always active, we have at least some chance of recovering from an error
3047 * during error recovery. (If we get into an infinite loop thereby, it
3048 * will soon be stopped by overflow of elog.c's internal state stack.)
3051 if (sigsetjmp(local_sigjmp_buf, 1) != 0)
3054 * NOTE: if you are tempted to add more code in this if-block,
3055 * consider the high probability that it should be in
3056 * AbortTransaction() instead. The only stuff done directly here
3057 * should be stuff that is guaranteed to apply *only* for outer-level
3058 * error recovery, such as adjusting the FE/BE protocol status.
3061 /* Since not using PG_TRY, must reset error stack by hand */
3062 error_context_stack = NULL;
3064 /* Prevent interrupts while cleaning up */
3068 * Forget any pending QueryCancel request, since we're returning to
3069 * the idle loop anyway, and cancel the statement timer if running.
3071 QueryCancelPending = false;
3072 disable_sig_alarm(true);
3073 QueryCancelPending = false; /* again in case timeout occurred */
3076 * Turn off these interrupts too. This is only needed here and not in
3077 * other exception-catching places since these interrupts are only
3078 * enabled while we wait for client input.
3080 DoingCommandRead = false;
3081 DisableNotifyInterrupt();
3082 DisableCatchupInterrupt();
3084 /* Make sure libpq is in a good state */
3087 /* Report the error to the client and/or server log */
3091 * Make sure debug_query_string gets reset before we possibly clobber
3092 * the storage it points at.
3094 debug_query_string = NULL;
3097 * Abort the current transaction in order to recover.
3099 AbortCurrentTransaction();
3102 * Now return to normal top-level context and clear ErrorContext for
3105 MemoryContextSwitchTo(TopMemoryContext);
3107 QueryContext = NULL;
3110 * If we were handling an extended-query-protocol message, initiate
3111 * skip till next Sync. This also causes us not to issue
3112 * ReadyForQuery (until we get Sync).
3114 if (doing_extended_query_message)
3115 ignore_till_sync = true;
3117 /* We don't have a transaction command open anymore */
3118 xact_started = false;
3120 /* Now we can allow interrupts again */
3121 RESUME_INTERRUPTS();
3124 /* We can now handle ereport(ERROR) */
3125 PG_exception_stack = &local_sigjmp_buf;
3127 PG_SETMASK(&UnBlockSig);
3129 if (!ignore_till_sync)
3130 send_ready_for_query = true; /* initially, or after error */
3133 * Non-error queries loop here.
3139 * At top of loop, reset extended-query-message flag, so that any
3140 * errors encountered in "idle" state don't provoke skip.
3142 doing_extended_query_message = false;
3145 * Release storage left over from prior query cycle, and create a new
3146 * query input buffer in the cleared MessageContext.
3148 MemoryContextSwitchTo(MessageContext);
3149 MemoryContextResetAndDeleteChildren(MessageContext);
3151 initStringInfo(&input_message);
3154 * (1) If we've reached idle state, tell the frontend we're ready for
3157 * Note: this includes fflush()'ing the last of the prior output.
3159 * This is also a good time to send collected statistics to the
3160 * collector, and to update the PS stats display. We avoid doing
3161 * those every time through the message loop because it'd slow down
3162 * processing of batched messages, and because we don't want to report
3163 * uncommitted updates (that confuses autovacuum).
3165 if (send_ready_for_query)
3167 if (IsTransactionOrTransactionBlock())
3169 set_ps_display("idle in transaction");
3170 pgstat_report_activity("<IDLE> in transaction");
3174 pgstat_report_tabstat();
3176 set_ps_display("idle");
3177 pgstat_report_activity("<IDLE>");
3180 ReadyForQuery(whereToSendOutput);
3181 send_ready_for_query = false;
3185 * (2) Allow asynchronous signals to be executed immediately if they
3186 * come in while we are waiting for client input. (This must be
3187 * conditional since we don't want, say, reads on behalf of COPY FROM
3188 * STDIN doing the same thing.)
3190 QueryCancelPending = false; /* forget any earlier CANCEL signal */
3191 DoingCommandRead = true;
3194 * (3) read a command (loop blocks here)
3196 firstchar = ReadCommand(&input_message);
3199 * (4) disable async signal conditions again.
3201 DoingCommandRead = false;
3204 * (5) check for any other interesting events that happened while we
3210 ProcessConfigFile(PGC_SIGHUP);
3214 * (6) process the command. But ignore it if we're skipping till
3217 if (ignore_till_sync && firstchar != EOF)
3222 case 'Q': /* simple query */
3224 const char *query_string;
3226 query_string = pq_getmsgstring(&input_message);
3227 pq_getmsgend(&input_message);
3229 exec_simple_query(query_string);
3231 send_ready_for_query = true;
3235 case 'P': /* parse */
3237 const char *stmt_name;
3238 const char *query_string;
3240 Oid *paramTypes = NULL;
3242 stmt_name = pq_getmsgstring(&input_message);
3243 query_string = pq_getmsgstring(&input_message);
3244 numParams = pq_getmsgint(&input_message, 2);
3249 paramTypes = (Oid *) palloc(numParams * sizeof(Oid));
3250 for (i = 0; i < numParams; i++)
3251 paramTypes[i] = pq_getmsgint(&input_message, 4);
3253 pq_getmsgend(&input_message);
3255 exec_parse_message(query_string, stmt_name,
3256 paramTypes, numParams);
3260 case 'B': /* bind */
3263 * this message is complex enough that it seems best to put
3264 * the field extraction out-of-line
3266 exec_bind_message(&input_message);
3269 case 'E': /* execute */
3271 const char *portal_name;
3274 portal_name = pq_getmsgstring(&input_message);
3275 max_rows = pq_getmsgint(&input_message, 4);
3276 pq_getmsgend(&input_message);
3278 exec_execute_message(portal_name, max_rows);
3282 case 'F': /* fastpath function call */
3283 /* Tell the collector what we're doing */
3284 pgstat_report_activity("<FASTPATH> function call");
3286 /* start an xact for this function invocation */
3287 start_xact_command();
3289 /* switch back to message context */
3290 MemoryContextSwitchTo(MessageContext);
3292 /* set snapshot in case function needs one */
3293 ActiveSnapshot = CopySnapshot(GetTransactionSnapshot());
3295 if (HandleFunctionRequest(&input_message) == EOF)
3297 /* lost frontend connection during F message input */
3300 * Reset whereToSendOutput to prevent ereport from
3301 * attempting to send any more messages to client.
3303 if (whereToSendOutput == DestRemote)
3304 whereToSendOutput = DestNone;
3309 /* commit the function-invocation transaction */
3310 finish_xact_command();
3312 send_ready_for_query = true;
3315 case 'C': /* close */
3318 const char *close_target;
3320 close_type = pq_getmsgbyte(&input_message);
3321 close_target = pq_getmsgstring(&input_message);
3322 pq_getmsgend(&input_message);
3327 if (close_target[0] != '\0')
3328 DropPreparedStatement(close_target, false);
3331 /* special-case the unnamed statement */
3332 unnamed_stmt_pstmt = NULL;
3333 if (unnamed_stmt_context)
3335 DropDependentPortals(unnamed_stmt_context);
3336 MemoryContextDelete(unnamed_stmt_context);
3338 unnamed_stmt_context = NULL;
3345 portal = GetPortalByName(close_target);
3346 if (PortalIsValid(portal))
3347 PortalDrop(portal, false);
3352 (errcode(ERRCODE_PROTOCOL_VIOLATION),
3353 errmsg("invalid CLOSE message subtype %d",
3358 if (whereToSendOutput == DestRemote)
3359 pq_putemptymessage('3'); /* CloseComplete */
3363 case 'D': /* describe */
3366 const char *describe_target;
3368 describe_type = pq_getmsgbyte(&input_message);
3369 describe_target = pq_getmsgstring(&input_message);
3370 pq_getmsgend(&input_message);
3372 switch (describe_type)
3375 exec_describe_statement_message(describe_target);
3378 exec_describe_portal_message(describe_target);
3382 (errcode(ERRCODE_PROTOCOL_VIOLATION),
3383 errmsg("invalid DESCRIBE message subtype %d",
3390 case 'H': /* flush */
3391 pq_getmsgend(&input_message);
3392 if (whereToSendOutput == DestRemote)
3396 case 'S': /* sync */
3397 pq_getmsgend(&input_message);
3398 finish_xact_command();
3399 send_ready_for_query = true;
3403 * 'X' means that the frontend is closing down the socket. EOF
3404 * means unexpected loss of frontend connection. Either way,
3405 * perform normal shutdown.
3411 * Reset whereToSendOutput to prevent ereport from attempting
3412 * to send any more messages to client.
3414 if (whereToSendOutput == DestRemote)
3415 whereToSendOutput = DestNone;
3418 * NOTE: if you are tempted to add more code here, DON'T!
3419 * Whatever you had in mind to do should be set up as an
3420 * on_proc_exit or on_shmem_exit callback, instead. Otherwise
3421 * it will fail to be called during other backend-shutdown
3426 case 'd': /* copy data */
3427 case 'c': /* copy done */
3428 case 'f': /* copy fail */
3431 * Accept but ignore these messages, per protocol spec; we
3432 * probably got here because a COPY failed, and the frontend
3433 * is still sending data.
3439 (errcode(ERRCODE_PROTOCOL_VIOLATION),
3440 errmsg("invalid frontend message type %d",
3443 } /* end of input-reading loop */
3445 /* can't get here because the above loop never exits */
3448 return 1; /* keep compiler quiet */
3451 #ifndef HAVE_GETRUSAGE
3452 #include "rusagestub.h"
3454 #include <sys/resource.h>
3455 #endif /* HAVE_GETRUSAGE */
3457 static struct rusage Save_r;
3458 static struct timeval Save_t;
3463 getrusage(RUSAGE_SELF, &Save_r);
3464 gettimeofday(&Save_t, NULL);
3466 /* ResetTupleCount(); */
3470 ShowUsage(const char *title)
3473 struct timeval user,
3475 struct timeval elapse_t;
3479 getrusage(RUSAGE_SELF, &r);
3480 gettimeofday(&elapse_t, NULL);
3481 memcpy((char *) &user, (char *) &r.ru_utime, sizeof(user));
3482 memcpy((char *) &sys, (char *) &r.ru_stime, sizeof(sys));
3483 if (elapse_t.tv_usec < Save_t.tv_usec)
3486 elapse_t.tv_usec += 1000000;
3488 if (r.ru_utime.tv_usec < Save_r.ru_utime.tv_usec)
3490 r.ru_utime.tv_sec--;
3491 r.ru_utime.tv_usec += 1000000;
3493 if (r.ru_stime.tv_usec < Save_r.ru_stime.tv_usec)
3495 r.ru_stime.tv_sec--;
3496 r.ru_stime.tv_usec += 1000000;
3500 * the only stats we don't show here are for memory usage -- i can't
3501 * figure out how to interpret the relevant fields in the rusage struct,
3502 * and they change names across o/s platforms, anyway. if you can figure
3503 * out what the entries mean, you can somehow extract resident set size,
3504 * shared text size, and unshared data and stack sizes.
3506 initStringInfo(&str);
3508 appendStringInfo(&str, "! system usage stats:\n");
3509 appendStringInfo(&str,
3510 "!\t%ld.%06ld elapsed %ld.%06ld user %ld.%06ld system sec\n",
3511 (long) (elapse_t.tv_sec - Save_t.tv_sec),
3512 (long) (elapse_t.tv_usec - Save_t.tv_usec),
3513 (long) (r.ru_utime.tv_sec - Save_r.ru_utime.tv_sec),
3514 (long) (r.ru_utime.tv_usec - Save_r.ru_utime.tv_usec),
3515 (long) (r.ru_stime.tv_sec - Save_r.ru_stime.tv_sec),
3516 (long) (r.ru_stime.tv_usec - Save_r.ru_stime.tv_usec));
3517 appendStringInfo(&str,
3518 "!\t[%ld.%06ld user %ld.%06ld sys total]\n",
3520 (long) user.tv_usec,
3522 (long) sys.tv_usec);
3523 #if defined(HAVE_GETRUSAGE)
3524 appendStringInfo(&str,
3525 "!\t%ld/%ld [%ld/%ld] filesystem blocks in/out\n",
3526 r.ru_inblock - Save_r.ru_inblock,
3527 /* they only drink coffee at dec */
3528 r.ru_oublock - Save_r.ru_oublock,
3529 r.ru_inblock, r.ru_oublock);
3530 appendStringInfo(&str,
3531 "!\t%ld/%ld [%ld/%ld] page faults/reclaims, %ld [%ld] swaps\n",
3532 r.ru_majflt - Save_r.ru_majflt,
3533 r.ru_minflt - Save_r.ru_minflt,
3534 r.ru_majflt, r.ru_minflt,
3535 r.ru_nswap - Save_r.ru_nswap,
3537 appendStringInfo(&str,
3538 "!\t%ld [%ld] signals rcvd, %ld/%ld [%ld/%ld] messages rcvd/sent\n",
3539 r.ru_nsignals - Save_r.ru_nsignals,
3541 r.ru_msgrcv - Save_r.ru_msgrcv,
3542 r.ru_msgsnd - Save_r.ru_msgsnd,
3543 r.ru_msgrcv, r.ru_msgsnd);
3544 appendStringInfo(&str,
3545 "!\t%ld/%ld [%ld/%ld] voluntary/involuntary context switches\n",
3546 r.ru_nvcsw - Save_r.ru_nvcsw,
3547 r.ru_nivcsw - Save_r.ru_nivcsw,
3548 r.ru_nvcsw, r.ru_nivcsw);
3549 #endif /* HAVE_GETRUSAGE */
3551 bufusage = ShowBufferUsage();
3552 appendStringInfo(&str, "! buffer usage stats:\n%s", bufusage);
3555 /* remove trailing newline */
3556 if (str.data[str.len - 1] == '\n')
3557 str.data[--str.len] = '\0';
3560 (errmsg_internal("%s", title),
3561 errdetail("%s", str.data)));
3567 * on_proc_exit handler to log end of session
3570 log_disconnections(int code, Datum arg)
3572 Port *port = MyProcPort;
3578 gettimeofday(&end, NULL);
3579 if (end.tv_usec < port->session_start.tv_usec)
3582 end.tv_usec += 1000000;
3584 end.tv_sec -= port->session_start.tv_sec;
3585 end.tv_usec -= port->session_start.tv_usec;
3587 /* for stricter accuracy here we could round - this is close enough */
3588 hours = end.tv_sec / SECS_PER_HOUR;
3589 end.tv_sec %= SECS_PER_HOUR;
3590 minutes = end.tv_sec / SECS_PER_MINUTE;
3591 seconds = end.tv_sec % SECS_PER_MINUTE;
3594 (errmsg("disconnection: session time: %d:%02d:%02d.%02d "
3595 "user=%s database=%s host=%s%s%s",
3596 hours, minutes, seconds, (int) (end.tv_usec / 10000),
3597 port->user_name, port->database_name, port->remote_host,
3598 port->remote_port[0] ? " port=" : "", port->remote_port)));