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.455 2005/07/21 03:56:11 momjian 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/flatfiles.h"
59 #include "utils/guc.h"
60 #include "utils/lsyscache.h"
61 #include "utils/memutils.h"
62 #include "utils/ps_status.h"
63 #include "mb/pg_wchar.h"
74 const char *debug_query_string; /* for pgmonitor and
75 * log_min_error_statement */
77 /* Note: whereToSendOutput is initialized for the bootstrap/standalone case */
78 CommandDest whereToSendOutput = Debug;
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;
94 /* max_stack_depth converted to bytes for speed of checking */
95 static int max_stack_depth_bytes = 2048 * 1024;
97 /* stack base pointer (initialized by PostgresMain) */
98 static char *stack_base_ptr = NULL;
102 * Flag to mark SIGHUP. Whenever the main loop comes around it
103 * will reread the configuration file. (Better than doing the
104 * reading in the signal handler, ey?)
106 static volatile sig_atomic_t got_SIGHUP = false;
109 * Flag to keep track of whether we have started a transaction.
110 * For extended query protocol this has to be remembered across messages.
112 static bool xact_started = false;
115 * Flag to indicate that we are doing the outer loop's read-from-client,
116 * as opposed to any random read from client that might happen within
117 * commands like COPY FROM STDIN.
119 static bool DoingCommandRead = false;
122 * Flags to implement skip-till-Sync-after-error behavior for messages of
123 * the extended query protocol.
125 static bool doing_extended_query_message = false;
126 static bool ignore_till_sync = false;
129 * If an unnamed prepared statement exists, it's stored here.
130 * We keep it separate from the hashtable kept by commands/prepare.c
131 * in order to reduce overhead for short-lived queries.
133 static MemoryContext unnamed_stmt_context = NULL;
134 static PreparedStatement *unnamed_stmt_pstmt = NULL;
137 static bool EchoQuery = false; /* default don't echo */
140 * people who want to use EOF should #define DONTUSENEWLINE in
143 #ifndef TCOP_DONTUSENEWLINE
144 static int UseNewLine = 1; /* Use newlines query delimiters (the
148 static int UseNewLine = 0; /* Use EOF as query delimiters */
149 #endif /* TCOP_DONTUSENEWLINE */
152 /* ----------------------------------------------------------------
153 * decls for routines only used in this file
154 * ----------------------------------------------------------------
156 static int InteractiveBackend(StringInfo inBuf);
157 static int SocketBackend(StringInfo inBuf);
158 static int ReadCommand(StringInfo inBuf);
159 static bool log_after_parse(List *raw_parsetree_list,
160 const char *query_string, char **prepare_string);
161 static List *pg_rewrite_queries(List *querytree_list);
162 static void start_xact_command(void);
163 static void finish_xact_command(void);
164 static void SigHupHandler(SIGNAL_ARGS);
165 static void FloatExceptionHandler(SIGNAL_ARGS);
166 static void log_disconnections(int code, Datum arg);
169 /* ----------------------------------------------------------------
170 * routines to obtain user input
171 * ----------------------------------------------------------------
175 * InteractiveBackend() is called for user interactive connections
177 * the string entered by the user is placed in its parameter inBuf,
178 * and we act like a Q message was received.
180 * EOF is returned if end-of-file input is seen; time to shut down.
185 InteractiveBackend(StringInfo inBuf)
187 int c; /* character read from getc() */
188 bool end = false; /* end-of-input flag */
189 bool backslashSeen = false; /* have we seen a \ ? */
192 * display a prompt and obtain input from the user
197 /* Reset inBuf to empty */
199 inBuf->data[0] = '\0';
207 * if we are using \n as a delimiter, then read characters
210 while ((c = getc(stdin)) != EOF)
216 /* discard backslash from inBuf */
217 inBuf->data[--inBuf->len] = '\0';
218 backslashSeen = false;
223 /* keep the newline character */
224 appendStringInfoChar(inBuf, '\n');
229 backslashSeen = true;
231 backslashSeen = false;
233 appendStringInfoChar(inBuf, (char) c);
242 * otherwise read characters until EOF.
244 while ((c = getc(stdin)) != EOF)
245 appendStringInfoChar(inBuf, (char) c);
255 * otherwise we have a user query so process it.
260 /* Add '\0' to make it look the same as message case. */
261 appendStringInfoChar(inBuf, (char) '\0');
264 * if the query echo flag was given, print the query..
267 printf("statement: %s\n", inBuf->data);
274 * SocketBackend() Is called for frontend-backend connections
276 * Returns the message type code, and loads message body data into inBuf.
278 * EOF is returned if the connection is lost.
282 SocketBackend(StringInfo inBuf)
287 * Get message type code from the frontend.
289 qtype = pq_getbyte();
291 if (qtype == EOF) /* frontend disconnected */
294 (errcode(ERRCODE_PROTOCOL_VIOLATION),
295 errmsg("unexpected EOF on client connection")));
300 * Validate message type code before trying to read body; if we have
301 * lost sync, better to say "command unknown" than to run out of
302 * memory because we used garbage as a length word.
304 * This also gives us a place to set the doing_extended_query_message
305 * flag as soon as possible.
309 case 'Q': /* simple query */
310 doing_extended_query_message = false;
311 if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
313 /* old style without length word; convert */
314 if (pq_getstring(inBuf))
317 (errcode(ERRCODE_PROTOCOL_VIOLATION),
318 errmsg("unexpected EOF on client connection")));
324 case 'F': /* fastpath function call */
325 /* we let fastpath.c cope with old-style input of this */
326 doing_extended_query_message = false;
329 case 'X': /* terminate */
330 doing_extended_query_message = false;
331 ignore_till_sync = false;
335 case 'C': /* close */
336 case 'D': /* describe */
337 case 'E': /* execute */
338 case 'H': /* flush */
339 case 'P': /* parse */
340 doing_extended_query_message = true;
341 /* these are only legal in protocol 3 */
342 if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
344 (errcode(ERRCODE_PROTOCOL_VIOLATION),
345 errmsg("invalid frontend message type %d", qtype)));
349 /* stop any active skip-till-Sync */
350 ignore_till_sync = false;
351 /* mark not-extended, so that a new error doesn't begin skip */
352 doing_extended_query_message = false;
353 /* 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)));
360 case 'd': /* copy data */
361 case 'c': /* copy done */
362 case 'f': /* copy fail */
363 doing_extended_query_message = false;
364 /* these are only legal in protocol 3 */
365 if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
367 (errcode(ERRCODE_PROTOCOL_VIOLATION),
368 errmsg("invalid frontend message type %d", qtype)));
374 * Otherwise we got garbage from the frontend. We treat this
375 * as fatal because we have probably lost message boundary
376 * sync, and there's no good way to recover.
379 (errcode(ERRCODE_PROTOCOL_VIOLATION),
380 errmsg("invalid frontend message type %d", qtype)));
385 * In protocol version 3, all frontend messages have a length word
386 * next after the type code; we can read the message contents
387 * independently of the type.
389 if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3)
391 if (pq_getmessage(inBuf, 0))
392 return EOF; /* suitable message already logged */
399 * ReadCommand reads a command from either the frontend or
400 * standard input, places it in inBuf, and returns the
401 * message type code (first byte of the message).
402 * EOF is returned if end of file.
406 ReadCommand(StringInfo inBuf)
410 if (whereToSendOutput == Remote)
411 result = SocketBackend(inBuf);
413 result = InteractiveBackend(inBuf);
418 * prepare_for_client_read -- set up to possibly block on client input
420 * This must be called immediately before any low-level read from the
421 * client connection. It is necessary to do it at a sufficiently low level
422 * that there won't be any other operations except the read kernel call
423 * itself between this call and the subsequent client_read_ended() call.
424 * In particular there mustn't be use of malloc() or other potentially
425 * non-reentrant libc functions. This restriction makes it safe for us
426 * to allow interrupt service routines to execute nontrivial code while
427 * we are waiting for input.
430 prepare_for_client_read(void)
432 if (DoingCommandRead)
434 /* Enable immediate processing of asynchronous signals */
435 EnableNotifyInterrupt();
436 EnableCatchupInterrupt();
438 /* Allow "die" interrupt to be processed while waiting */
439 ImmediateInterruptOK = true;
441 /* And don't forget to detect one that already arrived */
442 QueryCancelPending = false;
443 CHECK_FOR_INTERRUPTS();
448 * client_read_ended -- get out of the client-input state
451 client_read_ended(void)
453 if (DoingCommandRead)
455 ImmediateInterruptOK = false;
456 QueryCancelPending = false; /* forget any CANCEL signal */
458 DisableNotifyInterrupt();
459 DisableCatchupInterrupt();
465 * Parse a query string and pass it through the rewriter.
467 * A list of Query nodes is returned, since the string might contain
468 * multiple queries and/or the rewriter might expand one query to several.
470 * NOTE: this routine is no longer used for processing interactive queries,
471 * but it is still needed for parsing of SQL function bodies.
474 pg_parse_and_rewrite(const char *query_string, /* string to execute */
475 Oid *paramTypes, /* parameter types */
476 int numParams) /* number of parameters */
478 List *raw_parsetree_list;
479 List *querytree_list;
483 * (1) parse the request string into a list of raw parse trees.
485 raw_parsetree_list = pg_parse_query(query_string);
488 * (2) Do parse analysis and rule rewrite.
490 querytree_list = NIL;
491 foreach(list_item, raw_parsetree_list)
493 Node *parsetree = (Node *) lfirst(list_item);
495 querytree_list = list_concat(querytree_list,
496 pg_analyze_and_rewrite(parsetree,
501 return querytree_list;
505 * Do raw parsing (only).
507 * A list of parsetrees is returned, since there might be multiple
508 * commands in the given string.
510 * NOTE: for interactive queries, it is important to keep this routine
511 * separate from the analysis & rewrite stages. Analysis and rewriting
512 * cannot be done in an aborted transaction, since they require access to
513 * database tables. So, we rely on the raw parser to determine whether
514 * we've seen a COMMIT or ABORT command; when we are in abort state, other
515 * commands are not processed any further than the raw parse stage.
518 pg_parse_query(const char *query_string)
520 List *raw_parsetree_list;
522 if (log_parser_stats)
525 raw_parsetree_list = raw_parser(query_string);
527 if (log_parser_stats)
528 ShowUsage("PARSER STATISTICS");
530 return raw_parsetree_list;
534 log_after_parse(List *raw_parsetree_list, const char *query_string,
535 char **prepare_string)
537 ListCell *parsetree_item;
538 bool log_this_statement = (log_statement == LOGSTMT_ALL);
540 *prepare_string = NULL;
542 /* Check if we need to log the statement, and get prepare_string. */
543 foreach(parsetree_item, raw_parsetree_list)
545 Node *parsetree = (Node *) lfirst(parsetree_item);
546 const char *commandTag;
548 if (IsA(parsetree, ExplainStmt) &&
549 ((ExplainStmt *) parsetree)->analyze)
550 parsetree = (Node *) (((ExplainStmt *) parsetree)->query);
552 if (IsA(parsetree, PrepareStmt))
553 parsetree = (Node *) (((PrepareStmt *) parsetree)->query);
555 if (IsA(parsetree, SelectStmt) &&
556 ((SelectStmt *) parsetree)->into == NULL)
557 continue; /* optimization for frequent command */
559 if (log_statement == LOGSTMT_MOD &&
560 (IsA(parsetree, InsertStmt) ||
561 IsA(parsetree, UpdateStmt) ||
562 IsA(parsetree, DeleteStmt) ||
563 IsA(parsetree, TruncateStmt) ||
564 (IsA(parsetree, CopyStmt) &&
565 ((CopyStmt *) parsetree)->is_from))) /* COPY FROM */
566 log_this_statement = true;
568 commandTag = CreateCommandTag(parsetree);
569 if ((log_statement == LOGSTMT_MOD ||
570 log_statement == LOGSTMT_DDL) &&
571 (strncmp(commandTag, "CREATE ", strlen("CREATE ")) == 0 ||
572 IsA(parsetree, SelectStmt) || /* SELECT INTO, CREATE AS */
573 strncmp(commandTag, "ALTER ", strlen("ALTER ")) == 0 ||
574 strncmp(commandTag, "DROP ", strlen("DROP ")) == 0 ||
575 IsA(parsetree, GrantStmt) || /* GRANT or REVOKE */
576 IsA(parsetree, CommentStmt)))
577 log_this_statement = true;
580 * For the first EXECUTE we find, record the client statement
581 * used by the PREPARE.
583 if (IsA(parsetree, ExecuteStmt))
585 ExecuteStmt *stmt = (ExecuteStmt *) parsetree;
586 PreparedStatement *entry;
588 if ((entry = FetchPreparedStatement(stmt->name, false)) != NULL &&
591 *prepare_string = palloc(strlen(entry->query_string) +
592 strlen(" [client PREPARE: %s]") - 1);
593 sprintf(*prepare_string, " [client PREPARE: %s]",
594 entry->query_string);
599 if (log_this_statement)
602 (errmsg("statement: %s%s", query_string,
603 *prepare_string ? *prepare_string : "")));
612 * Given a raw parsetree (gram.y output), and optionally information about
613 * types of parameter symbols ($n), perform parse analysis and rule rewriting.
615 * A list of Query nodes is returned, since either the analyzer or the
616 * rewriter might expand one query to several.
618 * NOTE: for reasons mentioned above, this must be separate from raw parsing.
621 pg_analyze_and_rewrite(Node *parsetree, Oid *paramTypes, int numParams)
623 List *querytree_list;
626 * (1) Perform parse analysis.
628 if (log_parser_stats)
631 querytree_list = parse_analyze(parsetree, paramTypes, numParams);
633 if (log_parser_stats)
634 ShowUsage("PARSE ANALYSIS STATISTICS");
637 * (2) Rewrite the queries, as necessary
639 querytree_list = pg_rewrite_queries(querytree_list);
641 return querytree_list;
645 * Perform rewriting of a list of queries produced by parse analysis.
647 * Note: queries must just have come from the parser, because we do not do
648 * AcquireRewriteLocks() on them.
651 pg_rewrite_queries(List *querytree_list)
653 List *new_list = NIL;
656 if (log_parser_stats)
660 * rewritten queries are collected in new_list. Note there may be
661 * more or fewer than in the original list.
663 foreach(list_item, querytree_list)
665 Query *querytree = (Query *) lfirst(list_item);
667 if (Debug_print_parse)
668 elog_node_display(DEBUG1, "parse tree", querytree,
671 if (querytree->commandType == CMD_UTILITY)
673 /* don't rewrite utilities, just dump 'em into new_list */
674 new_list = lappend(new_list, querytree);
678 /* rewrite regular queries */
679 List *rewritten = QueryRewrite(querytree);
681 new_list = list_concat(new_list, rewritten);
685 querytree_list = new_list;
687 if (log_parser_stats)
688 ShowUsage("REWRITER STATISTICS");
690 #ifdef COPY_PARSE_PLAN_TREES
693 * Optional debugging check: pass querytree output through
696 new_list = (List *) copyObject(querytree_list);
697 /* This checks both copyObject() and the equal() routines... */
698 if (!equal(new_list, querytree_list))
699 elog(WARNING, "copyObject() failed to produce an equal parse tree");
701 querytree_list = new_list;
704 if (Debug_print_rewritten)
705 elog_node_display(DEBUG1, "rewritten parse tree", querytree_list,
708 return querytree_list;
712 /* Generate a plan for a single already-rewritten query. */
714 pg_plan_query(Query *querytree, ParamListInfo boundParams)
718 /* Utility commands have no plans. */
719 if (querytree->commandType == CMD_UTILITY)
722 if (log_planner_stats)
725 /* call the optimizer */
726 plan = planner(querytree, false, 0, boundParams);
728 if (log_planner_stats)
729 ShowUsage("PLANNER STATISTICS");
731 #ifdef COPY_PARSE_PLAN_TREES
732 /* Optional debugging check: pass plan output through copyObject() */
734 Plan *new_plan = (Plan *) copyObject(plan);
737 * equal() currently does not have routines to compare Plan nodes,
738 * so don't try to test equality here. Perhaps fix someday?
741 /* This checks both copyObject() and the equal() routines... */
742 if (!equal(new_plan, plan))
743 elog(WARNING, "copyObject() failed to produce an equal plan tree");
751 * Print plan if debugging.
753 if (Debug_print_plan)
754 elog_node_display(DEBUG1, "plan", plan, Debug_pretty_print);
760 * Generate plans for a list of already-rewritten queries.
762 * If needSnapshot is TRUE, we haven't yet set a snapshot for the current
763 * query. A snapshot must be set before invoking the planner, since it
764 * might try to evaluate user-defined functions. But we must not set a
765 * snapshot if the list contains only utility statements, because some
766 * utility statements depend on not having frozen the snapshot yet.
767 * (We assume that such statements cannot appear together with plannable
768 * statements in the rewriter's output.)
771 pg_plan_queries(List *querytrees, ParamListInfo boundParams,
774 List *plan_list = NIL;
775 ListCell *query_list;
777 foreach(query_list, querytrees)
779 Query *query = (Query *) lfirst(query_list);
782 if (query->commandType == CMD_UTILITY)
784 /* Utility commands have no plans. */
791 ActiveSnapshot = CopySnapshot(GetTransactionSnapshot());
792 needSnapshot = false;
794 plan = pg_plan_query(query, boundParams);
797 plan_list = lappend(plan_list, plan);
807 * Execute a "simple Query" protocol message.
810 exec_simple_query(const char *query_string)
812 CommandDest dest = whereToSendOutput;
813 MemoryContext oldcontext;
814 List *parsetree_list;
815 ListCell *parsetree_item;
816 struct timeval start_t, stop_t;
817 bool save_log_duration = log_duration;
818 int save_log_min_duration_statement = log_min_duration_statement;
819 bool save_log_statement_stats = log_statement_stats;
820 char *prepare_string = NULL;
821 bool was_logged = false;
824 * Report query to various monitoring facilities.
826 debug_query_string = query_string;
828 pgstat_report_activity(query_string);
831 * We use save_log_* so "SET log_duration = true" and "SET
832 * log_min_duration_statement = true" don't report incorrect time
833 * because gettimeofday() wasn't called. Similarly,
834 * log_statement_stats has to be captured once.
836 if (save_log_duration || save_log_min_duration_statement != -1)
837 gettimeofday(&start_t, NULL);
839 if (save_log_statement_stats)
843 * Start up a transaction command. All queries generated by the
844 * query_string will be in this same command block, *unless* we find a
845 * BEGIN/COMMIT/ABORT statement; we have to force a new xact command
846 * after one of those, else bad things will happen in xact.c. (Note
847 * that this will normally change current memory context.)
849 start_xact_command();
852 * Zap any pre-existing unnamed statement. (While not strictly
853 * necessary, it seems best to define simple-Query mode as if it used
854 * the unnamed statement and portal; this ensures we recover any
855 * storage used by prior unnamed operations.)
857 unnamed_stmt_pstmt = NULL;
858 if (unnamed_stmt_context)
860 DropDependentPortals(unnamed_stmt_context);
861 MemoryContextDelete(unnamed_stmt_context);
863 unnamed_stmt_context = NULL;
866 * Switch to appropriate context for constructing parsetrees.
868 oldcontext = MemoryContextSwitchTo(MessageContext);
870 QueryContext = CurrentMemoryContext;
873 * Do basic parsing of the query or queries (this should be safe even
874 * if we are in aborted transaction state!)
876 parsetree_list = pg_parse_query(query_string);
878 if (log_statement != LOGSTMT_NONE || save_log_min_duration_statement != -1)
879 was_logged = log_after_parse(parsetree_list, query_string,
883 * Switch back to transaction context to enter the loop.
885 MemoryContextSwitchTo(oldcontext);
888 * Run through the raw parsetree(s) and process each one.
890 foreach(parsetree_item, parsetree_list)
892 Node *parsetree = (Node *) lfirst(parsetree_item);
893 const char *commandTag;
894 char completionTag[COMPLETION_TAG_BUFSIZE];
895 List *querytree_list,
898 DestReceiver *receiver;
902 * Get the command name for use in status display (it also becomes
903 * the default completion tag, down inside PortalRun). Set
904 * ps_status and do any special start-of-SQL-command processing
905 * needed by the destination.
907 commandTag = CreateCommandTag(parsetree);
909 set_ps_display(commandTag);
911 BeginCommand(commandTag, dest);
914 * If we are in an aborted transaction, reject all commands except
915 * COMMIT/ABORT. It is important that this test occur before we
916 * try to do parse analysis, rewrite, or planning, since all those
917 * phases try to do database accesses, which may fail in abort
918 * state. (It might be safe to allow some additional utility
919 * commands in this state, but not many...)
921 if (IsAbortedTransactionBlockState())
923 bool allowit = false;
925 if (IsA(parsetree, TransactionStmt))
927 TransactionStmt *stmt = (TransactionStmt *) parsetree;
929 if (stmt->kind == TRANS_STMT_COMMIT ||
930 stmt->kind == TRANS_STMT_PREPARE ||
931 stmt->kind == TRANS_STMT_ROLLBACK ||
932 stmt->kind == TRANS_STMT_ROLLBACK_TO)
938 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
939 errmsg("current transaction is aborted, "
940 "commands ignored until end of transaction block")));
943 /* Make sure we are in a transaction command */
944 start_xact_command();
946 /* If we got a cancel signal in parsing or prior command, quit */
947 CHECK_FOR_INTERRUPTS();
950 * OK to analyze, rewrite, and plan this query.
952 * Switch to appropriate context for constructing querytrees (again,
953 * these must outlive the execution context).
955 oldcontext = MemoryContextSwitchTo(MessageContext);
957 querytree_list = pg_analyze_and_rewrite(parsetree, NULL, 0);
959 plantree_list = pg_plan_queries(querytree_list, NULL, true);
961 /* If we got a cancel signal in analysis or planning, quit */
962 CHECK_FOR_INTERRUPTS();
965 * Create unnamed portal to run the query or queries in. If there
966 * already is one, silently drop it.
968 portal = CreatePortal("", true, true);
970 PortalDefineQuery(portal,
978 * Start the portal. No parameters here.
980 PortalStart(portal, NULL, InvalidSnapshot);
983 * Select the appropriate output format: text unless we are doing
984 * a FETCH from a binary cursor. (Pretty grotty to have to do
985 * this here --- but it avoids grottiness in other places. Ah,
986 * the joys of backward compatibility...)
988 format = 0; /* TEXT is default */
989 if (IsA(parsetree, FetchStmt))
991 FetchStmt *stmt = (FetchStmt *) parsetree;
995 Portal fportal = GetPortalByName(stmt->portalname);
997 if (PortalIsValid(fportal) &&
998 (fportal->cursorOptions & CURSOR_OPT_BINARY))
999 format = 1; /* BINARY */
1002 PortalSetResultFormat(portal, 1, &format);
1005 * Now we can create the destination receiver object.
1007 receiver = CreateDestReceiver(dest, portal);
1010 * Switch back to transaction context for execution.
1012 MemoryContextSwitchTo(oldcontext);
1015 * Run the portal to completion, and then drop it (and the
1018 (void) PortalRun(portal,
1024 (*receiver->rDestroy) (receiver);
1026 PortalDrop(portal, false);
1028 if (IsA(parsetree, TransactionStmt))
1031 * If this was a transaction control statement, commit it. We
1032 * will start a new xact command for the next command (if
1035 finish_xact_command();
1037 else if (lnext(parsetree_item) == NULL)
1040 * If this is the last parsetree of the query string, close
1041 * down transaction statement before reporting
1042 * command-complete. This is so that any end-of-transaction
1043 * errors are reported before the command-complete message is
1044 * issued, to avoid confusing clients who will expect either a
1045 * command-complete message or an error, not one and then the
1046 * other. But for compatibility with historical Postgres
1047 * behavior, we do not force a transaction boundary between
1048 * queries appearing in a single query string.
1050 finish_xact_command();
1055 * We need a CommandCounterIncrement after every query, except
1056 * those that start or end a transaction block.
1058 CommandCounterIncrement();
1062 * Tell client that we're done with this query. Note we emit
1063 * exactly one EndCommand report for each raw parsetree, thus one
1064 * for each SQL command the client sent, regardless of rewriting.
1065 * (But a command aborted by error will not send an EndCommand
1068 EndCommand(completionTag, dest);
1069 } /* end loop over parsetrees */
1072 * Close down transaction statement, if one is open.
1074 finish_xact_command();
1077 * If there were no parsetrees, return EmptyQueryResponse message.
1079 if (!parsetree_list)
1082 QueryContext = NULL;
1085 * Combine processing here as we need to calculate the query duration
1086 * in both instances.
1088 if (save_log_duration || save_log_min_duration_statement != -1)
1092 gettimeofday(&stop_t, NULL);
1093 if (stop_t.tv_usec < start_t.tv_usec)
1096 stop_t.tv_usec += 1000000;
1098 usecs = (long) (stop_t.tv_sec - start_t.tv_sec) * 1000000 +
1099 (long) (stop_t.tv_usec - start_t.tv_usec);
1101 /* Only print duration if we previously printed the statement. */
1102 if (was_logged && save_log_duration)
1104 (errmsg("duration: %ld.%03ld ms",
1105 (long) ((stop_t.tv_sec - start_t.tv_sec) * 1000 +
1106 (stop_t.tv_usec - start_t.tv_usec) / 1000),
1107 (long) (stop_t.tv_usec - start_t.tv_usec) % 1000)));
1110 * Output a duration_statement to the log if the query has
1111 * exceeded the min duration, or if we are to print all durations.
1113 if (save_log_min_duration_statement == 0 ||
1114 (save_log_min_duration_statement > 0 &&
1115 usecs >= save_log_min_duration_statement * 1000))
1117 (errmsg("duration: %ld.%03ld ms statement: %s%s",
1118 (long) ((stop_t.tv_sec - start_t.tv_sec) * 1000 +
1119 (stop_t.tv_usec - start_t.tv_usec) / 1000),
1120 (long) (stop_t.tv_usec - start_t.tv_usec) % 1000,
1122 prepare_string ? prepare_string : "")));
1125 if (save_log_statement_stats)
1126 ShowUsage("QUERY STATISTICS");
1128 if (prepare_string != NULL)
1129 pfree(prepare_string);
1131 debug_query_string = NULL;
1135 * exec_parse_message
1137 * Execute a "Parse" protocol message.
1140 exec_parse_message(const char *query_string, /* string to execute */
1141 const char *stmt_name, /* name for prepared stmt */
1142 Oid *paramTypes, /* parameter types */
1143 int numParams) /* number of parameters */
1145 MemoryContext oldcontext;
1146 List *parsetree_list;
1147 const char *commandTag;
1148 List *querytree_list,
1152 bool save_log_statement_stats = log_statement_stats;
1155 * Report query to various monitoring facilities.
1157 debug_query_string = query_string;
1159 pgstat_report_activity(query_string);
1161 set_ps_display("PARSE");
1163 if (save_log_statement_stats)
1166 if (log_statement == LOGSTMT_ALL)
1168 (errmsg("statement: PREPARE %s AS %s", stmt_name, query_string)));
1171 * Start up a transaction command so we can run parse analysis etc.
1172 * (Note that this will normally change current memory context.)
1173 * Nothing happens if we are already in one.
1175 start_xact_command();
1178 * Switch to appropriate context for constructing parsetrees.
1180 * We have two strategies depending on whether the prepared statement is
1181 * named or not. For a named prepared statement, we do parsing in
1182 * MessageContext and copy the finished trees into the prepared
1183 * statement's private context; then the reset of MessageContext
1184 * releases temporary space used by parsing and planning. For an
1185 * unnamed prepared statement, we assume the statement isn't going to
1186 * hang around long, so getting rid of temp space quickly is probably
1187 * not worth the costs of copying parse/plan trees. So in this case,
1188 * we set up a special context for the unnamed statement, and do all
1189 * the parsing/planning therein.
1191 is_named = (stmt_name[0] != '\0');
1194 /* Named prepared statement --- parse in MessageContext */
1195 oldcontext = MemoryContextSwitchTo(MessageContext);
1199 /* Unnamed prepared statement --- release any prior unnamed stmt */
1200 unnamed_stmt_pstmt = NULL;
1201 if (unnamed_stmt_context)
1203 DropDependentPortals(unnamed_stmt_context);
1204 MemoryContextDelete(unnamed_stmt_context);
1206 unnamed_stmt_context = NULL;
1207 /* create context for parsing/planning */
1208 unnamed_stmt_context =
1209 AllocSetContextCreate(TopMemoryContext,
1210 "unnamed prepared statement",
1211 ALLOCSET_DEFAULT_MINSIZE,
1212 ALLOCSET_DEFAULT_INITSIZE,
1213 ALLOCSET_DEFAULT_MAXSIZE);
1214 oldcontext = MemoryContextSwitchTo(unnamed_stmt_context);
1217 QueryContext = CurrentMemoryContext;
1220 * Do basic parsing of the query or queries (this should be safe even
1221 * if we are in aborted transaction state!)
1223 parsetree_list = pg_parse_query(query_string);
1226 * We only allow a single user statement in a prepared statement. This
1227 * is mainly to keep the protocol simple --- otherwise we'd need to
1228 * worry about multiple result tupdescs and things like that.
1230 if (list_length(parsetree_list) > 1)
1232 (errcode(ERRCODE_SYNTAX_ERROR),
1233 errmsg("cannot insert multiple commands into a prepared statement")));
1235 if (parsetree_list != NIL)
1237 Node *parsetree = (Node *) linitial(parsetree_list);
1241 * Get the command name for possible use in status display.
1243 commandTag = CreateCommandTag(parsetree);
1246 * If we are in an aborted transaction, reject all commands except
1247 * COMMIT/ROLLBACK. It is important that this test occur before
1248 * we try to do parse analysis, rewrite, or planning, since all
1249 * those phases try to do database accesses, which may fail in
1250 * abort state. (It might be safe to allow some additional utility
1251 * commands in this state, but not many...)
1253 if (IsAbortedTransactionBlockState())
1255 bool allowit = false;
1257 if (IsA(parsetree, TransactionStmt))
1259 TransactionStmt *stmt = (TransactionStmt *) parsetree;
1261 if (stmt->kind == TRANS_STMT_COMMIT ||
1262 stmt->kind == TRANS_STMT_PREPARE ||
1263 stmt->kind == TRANS_STMT_ROLLBACK ||
1264 stmt->kind == TRANS_STMT_ROLLBACK_TO)
1270 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1271 errmsg("current transaction is aborted, "
1272 "commands ignored until end of transaction block")));
1276 * OK to analyze, rewrite, and plan this query. Note that the
1277 * originally specified parameter set is not required to be
1278 * complete, so we have to use parse_analyze_varparams().
1280 if (log_parser_stats)
1283 querytree_list = parse_analyze_varparams(parsetree,
1288 * Check all parameter types got determined, and convert array
1289 * representation to a list for storage.
1292 for (i = 0; i < numParams; i++)
1294 Oid ptype = paramTypes[i];
1296 if (ptype == InvalidOid || ptype == UNKNOWNOID)
1298 (errcode(ERRCODE_INDETERMINATE_DATATYPE),
1299 errmsg("could not determine data type of parameter $%d",
1301 param_list = lappend_oid(param_list, ptype);
1304 if (log_parser_stats)
1305 ShowUsage("PARSE ANALYSIS STATISTICS");
1307 querytree_list = pg_rewrite_queries(querytree_list);
1310 * If this is the unnamed statement and it has parameters, defer
1311 * query planning until Bind. Otherwise do it now.
1313 if (!is_named && numParams > 0)
1314 plantree_list = NIL;
1316 plantree_list = pg_plan_queries(querytree_list, NULL, true);
1320 /* Empty input string. This is legal. */
1322 querytree_list = NIL;
1323 plantree_list = NIL;
1327 /* If we got a cancel signal in analysis or planning, quit */
1328 CHECK_FOR_INTERRUPTS();
1331 * Store the query as a prepared statement. See above comments.
1335 StorePreparedStatement(stmt_name,
1344 PreparedStatement *pstmt;
1346 pstmt = (PreparedStatement *) palloc0(sizeof(PreparedStatement));
1347 /* query_string needs to be copied into unnamed_stmt_context */
1348 pstmt->query_string = pstrdup(query_string);
1349 /* the rest is there already */
1350 pstmt->commandTag = commandTag;
1351 pstmt->query_list = querytree_list;
1352 pstmt->plan_list = plantree_list;
1353 pstmt->argtype_list = param_list;
1354 pstmt->context = unnamed_stmt_context;
1355 /* Now the unnamed statement is complete and valid */
1356 unnamed_stmt_pstmt = pstmt;
1359 MemoryContextSwitchTo(oldcontext);
1361 QueryContext = NULL;
1364 * We do NOT close the open transaction command here; that only
1365 * happens when the client sends Sync. Instead, do
1366 * CommandCounterIncrement just in case something happened during
1369 CommandCounterIncrement();
1372 * Send ParseComplete.
1374 if (whereToSendOutput == Remote)
1375 pq_putemptymessage('1');
1377 if (save_log_statement_stats)
1378 ShowUsage("PARSE MESSAGE STATISTICS");
1380 debug_query_string = NULL;
1386 * Process a "Bind" message to create a portal from a prepared statement
1389 exec_bind_message(StringInfo input_message)
1391 const char *portal_name;
1392 const char *stmt_name;
1394 int16 *pformats = NULL;
1397 int16 *rformats = NULL;
1399 PreparedStatement *pstmt;
1401 ParamListInfo params;
1402 bool isaborted = IsAbortedTransactionBlockState();
1404 pgstat_report_activity("<BIND>");
1406 set_ps_display("BIND");
1409 * Start up a transaction command so we can call functions etc. (Note
1410 * that this will normally change current memory context.) Nothing
1411 * happens if we are already in one.
1413 start_xact_command();
1415 /* Switch back to message context */
1416 MemoryContextSwitchTo(MessageContext);
1418 /* Get the fixed part of the message */
1419 portal_name = pq_getmsgstring(input_message);
1420 stmt_name = pq_getmsgstring(input_message);
1422 /* Get the parameter format codes */
1423 numPFormats = pq_getmsgint(input_message, 2);
1424 if (numPFormats > 0)
1426 pformats = (int16 *) palloc(numPFormats * sizeof(int16));
1427 for (i = 0; i < numPFormats; i++)
1428 pformats[i] = pq_getmsgint(input_message, 2);
1431 /* Get the parameter value count */
1432 numParams = pq_getmsgint(input_message, 2);
1434 if (numPFormats > 1 && numPFormats != numParams)
1436 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1437 errmsg("bind message has %d parameter formats but %d parameters",
1438 numPFormats, numParams)));
1440 /* Find prepared statement */
1441 if (stmt_name[0] != '\0')
1442 pstmt = FetchPreparedStatement(stmt_name, true);
1445 /* special-case the unnamed statement */
1446 pstmt = unnamed_stmt_pstmt;
1449 (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
1450 errmsg("unnamed prepared statement does not exist")));
1453 if (numParams != list_length(pstmt->argtype_list))
1455 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1456 errmsg("bind message supplies %d parameters, but prepared statement \"%s\" requires %d",
1457 numParams, stmt_name, list_length(pstmt->argtype_list))));
1460 * Create the portal. Allow silent replacement of an existing portal
1461 * only if the unnamed portal is specified.
1463 if (portal_name[0] == '\0')
1464 portal = CreatePortal(portal_name, true, true);
1466 portal = CreatePortal(portal_name, false, false);
1468 if (log_statement == LOGSTMT_ALL)
1470 (errmsg("statement: <BIND> %s", portal_name)));
1473 * Fetch parameters, if any, and store in the portal's memory context.
1475 * In an aborted transaction, we can't risk calling user-defined
1476 * functions, but we can't fail to Bind either, so bind all parameters
1482 MemoryContext oldContext;
1484 oldContext = MemoryContextSwitchTo(PortalGetHeapMemory(portal));
1486 params = (ParamListInfo)
1487 palloc0((numParams + 1) * sizeof(ParamListInfoData));
1490 foreach(l, pstmt->argtype_list)
1492 Oid ptype = lfirst_oid(l);
1496 plength = pq_getmsgint(input_message, 4);
1497 isNull = (plength == -1);
1501 const char *pvalue = pq_getmsgbytes(input_message, plength);
1505 /* We don't bother to check the format in this case */
1511 StringInfoData pbuf;
1514 if (numPFormats > 1)
1515 pformat = pformats[i];
1516 else if (numPFormats > 0)
1517 pformat = pformats[0];
1519 pformat = 0; /* default = text */
1522 * Rather than copying data around, we just set up a
1523 * phony StringInfo pointing to the correct portion of
1524 * the message buffer. We assume we can scribble on
1525 * the message buffer so as to maintain the convention
1526 * that StringInfos have a trailing null. This is
1527 * grotty but is a big win when dealing with very
1528 * large parameter strings.
1530 pbuf.data = (char *) pvalue;
1531 pbuf.maxlen = plength + 1;
1535 csave = pbuf.data[plength];
1536 pbuf.data[plength] = '\0';
1544 getTypeInputInfo(ptype, &typinput, &typioparam);
1547 * We have to do encoding conversion before
1548 * calling the typinput routine.
1551 pg_client_to_server((unsigned char *) pbuf.data,
1554 OidFunctionCall3(typinput,
1555 CStringGetDatum(pstring),
1556 ObjectIdGetDatum(typioparam),
1558 /* Free result of encoding conversion, if any */
1559 if (pstring != pbuf.data)
1562 else if (pformat == 1)
1568 * Call the parameter type's binary input
1571 getTypeBinaryInputInfo(ptype, &typreceive, &typioparam);
1574 OidFunctionCall3(typreceive,
1575 PointerGetDatum(&pbuf),
1576 ObjectIdGetDatum(typioparam),
1579 /* Trouble if it didn't eat the whole buffer */
1580 if (pbuf.cursor != pbuf.len)
1582 (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
1583 errmsg("incorrect binary data format in bind parameter %d",
1589 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1590 errmsg("unsupported format code: %d",
1594 /* Restore message buffer contents */
1595 pbuf.data[plength] = csave;
1599 params[i].kind = PARAM_NUM;
1600 params[i].id = i + 1;
1601 params[i].ptype = ptype;
1602 params[i].isnull = isNull;
1607 params[i].kind = PARAM_INVALID;
1609 MemoryContextSwitchTo(oldContext);
1614 /* Get the result format codes */
1615 numRFormats = pq_getmsgint(input_message, 2);
1616 if (numRFormats > 0)
1618 rformats = (int16 *) palloc(numRFormats * sizeof(int16));
1619 for (i = 0; i < numRFormats; i++)
1620 rformats[i] = pq_getmsgint(input_message, 2);
1623 pq_getmsgend(input_message);
1626 * If we didn't plan the query before, do it now. This allows the
1627 * planner to make use of the concrete parameter values we now have.
1629 * This happens only for unnamed statements, and so switching into the
1630 * statement context for planning is correct (see notes in
1631 * exec_parse_message).
1633 if (pstmt->plan_list == NIL && pstmt->query_list != NIL &&
1636 MemoryContext oldContext = MemoryContextSwitchTo(pstmt->context);
1638 pstmt->plan_list = pg_plan_queries(pstmt->query_list, params, true);
1639 MemoryContextSwitchTo(oldContext);
1643 * Define portal and start execution.
1645 PortalDefineQuery(portal,
1646 pstmt->query_string,
1652 PortalStart(portal, params, InvalidSnapshot);
1655 * Apply the result format requests to the portal.
1657 PortalSetResultFormat(portal, numRFormats, rformats);
1660 * Send BindComplete.
1662 if (whereToSendOutput == Remote)
1663 pq_putemptymessage('2');
1667 * exec_execute_message
1669 * Process an "Execute" message for a portal
1672 exec_execute_message(const char *portal_name, long max_rows)
1675 DestReceiver *receiver;
1677 bool is_trans_stmt = false;
1678 bool is_trans_exit = false;
1680 char completionTag[COMPLETION_TAG_BUFSIZE];
1681 struct timeval start_t, stop_t;
1682 bool save_log_duration = log_duration;
1683 int save_log_min_duration_statement = log_min_duration_statement;
1684 bool save_log_statement_stats = log_statement_stats;
1686 /* Adjust destination to tell printtup.c what to do */
1687 dest = whereToSendOutput;
1689 dest = RemoteExecute;
1691 portal = GetPortalByName(portal_name);
1692 if (!PortalIsValid(portal))
1694 (errcode(ERRCODE_UNDEFINED_CURSOR),
1695 errmsg("portal \"%s\" does not exist", portal_name)));
1698 * If the original query was a null string, just return
1699 * EmptyQueryResponse.
1701 if (portal->commandTag == NULL)
1703 Assert(portal->parseTrees == NIL);
1708 if (portal->sourceText)
1710 debug_query_string = portal->sourceText;
1711 pgstat_report_activity(portal->sourceText);
1715 debug_query_string = "execute message";
1716 pgstat_report_activity("<EXECUTE>");
1719 set_ps_display(portal->commandTag);
1722 * We use save_log_* so "SET log_duration = true" and "SET
1723 * log_min_duration_statement = true" don't report incorrect time
1724 * because gettimeofday() wasn't called. Similarly,
1725 * log_statement_stats has to be captured once.
1727 if (save_log_duration || save_log_min_duration_statement != -1)
1728 gettimeofday(&start_t, NULL);
1730 if (save_log_statement_stats)
1733 if (log_statement == LOGSTMT_ALL)
1734 /* We have the portal, so output the source query. */
1736 (errmsg("statement: EXECUTE %s [PREPARE: %s]", portal_name,
1737 portal->sourceText ? portal->sourceText : "")));
1739 BeginCommand(portal->commandTag, dest);
1741 /* Check for transaction-control commands */
1742 if (list_length(portal->parseTrees) == 1)
1744 Query *query = (Query *) linitial(portal->parseTrees);
1746 if (query->commandType == CMD_UTILITY &&
1747 query->utilityStmt != NULL &&
1748 IsA(query->utilityStmt, TransactionStmt))
1750 TransactionStmt *stmt = (TransactionStmt *) query->utilityStmt;
1752 is_trans_stmt = true;
1753 if (stmt->kind == TRANS_STMT_COMMIT ||
1754 stmt->kind == TRANS_STMT_PREPARE ||
1755 stmt->kind == TRANS_STMT_ROLLBACK ||
1756 stmt->kind == TRANS_STMT_ROLLBACK_TO)
1757 is_trans_exit = true;
1762 * Create dest receiver in MessageContext (we don't want it in
1763 * transaction context, because that may get deleted if portal
1766 receiver = CreateDestReceiver(dest, portal);
1769 * Ensure we are in a transaction command (this should normally be the
1770 * case already due to prior BIND).
1772 start_xact_command();
1775 * If we are in aborted transaction state, the only portals we can
1776 * actually run are those containing COMMIT or ROLLBACK commands.
1778 if (IsAbortedTransactionBlockState())
1782 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1783 errmsg("current transaction is aborted, "
1784 "commands ignored until end of transaction block")));
1787 /* Check for cancel signal before we start execution */
1788 CHECK_FOR_INTERRUPTS();
1791 * Okay to run the portal.
1794 max_rows = FETCH_ALL;
1796 completed = PortalRun(portal,
1802 (*receiver->rDestroy) (receiver);
1809 * If this was a transaction control statement, commit it. We
1810 * will start a new xact command for the next command (if
1813 finish_xact_command();
1818 * We need a CommandCounterIncrement after every query, except
1819 * those that start or end a transaction block.
1821 CommandCounterIncrement();
1824 /* Send appropriate CommandComplete to client */
1825 EndCommand(completionTag, dest);
1829 /* Portal run not complete, so send PortalSuspended */
1830 if (whereToSendOutput == Remote)
1831 pq_putemptymessage('s');
1835 * Combine processing here as we need to calculate the query duration
1836 * in both instances.
1838 if (save_log_duration || save_log_min_duration_statement != -1)
1842 gettimeofday(&stop_t, NULL);
1843 if (stop_t.tv_usec < start_t.tv_usec)
1846 stop_t.tv_usec += 1000000;
1848 usecs = (long) (stop_t.tv_sec - start_t.tv_sec) * 1000000 +
1849 (long) (stop_t.tv_usec - start_t.tv_usec);
1851 /* Only print duration if we previously printed the statement. */
1852 if (log_statement == LOGSTMT_ALL && save_log_duration)
1854 (errmsg("duration: %ld.%03ld ms",
1855 (long) ((stop_t.tv_sec - start_t.tv_sec) * 1000 +
1856 (stop_t.tv_usec - start_t.tv_usec) / 1000),
1857 (long) (stop_t.tv_usec - start_t.tv_usec) % 1000)));
1860 * Output a duration_statement to the log if the query has
1861 * exceeded the min duration, or if we are to print all durations.
1863 if (save_log_min_duration_statement == 0 ||
1864 (save_log_min_duration_statement > 0 &&
1865 usecs >= save_log_min_duration_statement * 1000))
1867 (errmsg("duration: %ld.%03ld ms statement: EXECUTE %s [PREPARE: %s]",
1868 (long) ((stop_t.tv_sec - start_t.tv_sec) * 1000 +
1869 (stop_t.tv_usec - start_t.tv_usec) / 1000),
1870 (long) (stop_t.tv_usec - start_t.tv_usec) % 1000,
1872 portal->sourceText ? portal->sourceText : "")));
1875 if (save_log_statement_stats)
1876 ShowUsage("QUERY STATISTICS");
1878 debug_query_string = NULL;
1882 * exec_describe_statement_message
1884 * Process a "Describe" message for a prepared statement
1887 exec_describe_statement_message(const char *stmt_name)
1889 PreparedStatement *pstmt;
1894 /* Find prepared statement */
1895 if (stmt_name[0] != '\0')
1896 pstmt = FetchPreparedStatement(stmt_name, true);
1899 /* special-case the unnamed statement */
1900 pstmt = unnamed_stmt_pstmt;
1903 (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
1904 errmsg("unnamed prepared statement does not exist")));
1907 if (whereToSendOutput != Remote)
1908 return; /* can't actually do anything... */
1911 * First describe the parameters...
1913 pq_beginmessage(&buf, 't'); /* parameter description message type */
1914 pq_sendint(&buf, list_length(pstmt->argtype_list), 2);
1916 foreach(l, pstmt->argtype_list)
1918 Oid ptype = lfirst_oid(l);
1920 pq_sendint(&buf, (int) ptype, 4);
1922 pq_endmessage(&buf);
1925 * Next send RowDescription or NoData to describe the result...
1927 tupdesc = FetchPreparedStatementResultDesc(pstmt);
1929 SendRowDescriptionMessage(tupdesc,
1930 FetchPreparedStatementTargetList(pstmt),
1933 pq_putemptymessage('n'); /* NoData */
1938 * exec_describe_portal_message
1940 * Process a "Describe" message for a portal
1943 exec_describe_portal_message(const char *portal_name)
1947 portal = GetPortalByName(portal_name);
1948 if (!PortalIsValid(portal))
1950 (errcode(ERRCODE_UNDEFINED_CURSOR),
1951 errmsg("portal \"%s\" does not exist", portal_name)));
1953 if (whereToSendOutput != Remote)
1954 return; /* can't actually do anything... */
1956 if (portal->tupDesc)
1957 SendRowDescriptionMessage(portal->tupDesc,
1958 FetchPortalTargetList(portal),
1961 pq_putemptymessage('n'); /* NoData */
1966 * Convenience routines for starting/committing a single command.
1969 start_xact_command(void)
1974 (errmsg_internal("StartTransactionCommand")));
1975 StartTransactionCommand();
1977 /* Set statement timeout running, if any */
1978 if (StatementTimeout > 0)
1979 enable_sig_alarm(StatementTimeout, true);
1981 xact_started = true;
1986 finish_xact_command(void)
1990 /* Cancel any active statement timeout before committing */
1991 disable_sig_alarm(true);
1993 /* Now commit the command */
1995 (errmsg_internal("CommitTransactionCommand")));
1997 CommitTransactionCommand();
1999 #ifdef MEMORY_CONTEXT_CHECKING
2000 /* Check all memory contexts that weren't freed during commit */
2001 /* (those that were, were checked before being deleted) */
2002 MemoryContextCheck(TopMemoryContext);
2005 #ifdef SHOW_MEMORY_STATS
2006 /* Print mem stats after each commit for leak tracking */
2008 MemoryContextStats(TopMemoryContext);
2011 xact_started = false;
2016 /* --------------------------------
2017 * signal handler routines used in PostgresMain()
2018 * --------------------------------
2022 * quickdie() occurs when signalled SIGQUIT by the postmaster.
2024 * Some backend has bought the farm,
2025 * so we need to stop what we're doing and exit.
2028 quickdie(SIGNAL_ARGS)
2030 PG_SETMASK(&BlockSig);
2033 * Ideally this should be ereport(FATAL), but then we'd not get
2037 (errcode(ERRCODE_CRASH_SHUTDOWN),
2038 errmsg("terminating connection because of crash of another server process"),
2039 errdetail("The postmaster has commanded this server process to roll back"
2040 " the current transaction and exit, because another"
2041 " server process exited abnormally and possibly corrupted"
2043 errhint("In a moment you should be able to reconnect to the"
2044 " database and repeat your command.")));
2047 * DO NOT proc_exit() -- we're here because shared memory may be
2048 * corrupted, so we don't want to try to clean up our transaction.
2049 * Just nail the windows shut and get out of town.
2051 * Note we do exit(1) not exit(0). This is to force the postmaster into
2052 * a system reset cycle if some idiot DBA sends a manual SIGQUIT to a
2053 * random backend. This is necessary precisely because we don't clean
2054 * up our shared memory state.
2060 * Shutdown signal from postmaster: abort transaction and exit
2061 * at soonest convenient time
2066 int save_errno = errno;
2068 /* Don't joggle the elbow of proc_exit */
2069 if (!proc_exit_inprogress)
2071 InterruptPending = true;
2072 ProcDiePending = true;
2075 * If it's safe to interrupt, and we're waiting for input or a
2076 * lock, service the interrupt immediately
2078 if (ImmediateInterruptOK && InterruptHoldoffCount == 0 &&
2079 CritSectionCount == 0)
2081 /* bump holdoff count to make ProcessInterrupts() a no-op */
2082 /* until we are done getting ready for it */
2083 InterruptHoldoffCount++;
2084 DisableNotifyInterrupt();
2085 DisableCatchupInterrupt();
2086 /* Make sure CheckDeadLock won't run while shutting down... */
2088 InterruptHoldoffCount--;
2089 ProcessInterrupts();
2097 * Timeout or shutdown signal from postmaster during client authentication.
2100 * XXX: possible future improvement: try to send a message indicating
2101 * why we are disconnecting. Problem is to be sure we don't block while
2102 * doing so, nor mess up the authentication message exchange.
2105 authdie(SIGNAL_ARGS)
2111 * Query-cancel signal from postmaster: abort current transaction
2112 * at soonest convenient time
2115 StatementCancelHandler(SIGNAL_ARGS)
2117 int save_errno = errno;
2120 * Don't joggle the elbow of proc_exit
2122 if (!proc_exit_inprogress)
2124 InterruptPending = true;
2125 QueryCancelPending = true;
2128 * If it's safe to interrupt, and we're waiting for a lock,
2129 * service the interrupt immediately. No point in interrupting if
2130 * we're waiting for input, however.
2132 if (ImmediateInterruptOK && InterruptHoldoffCount == 0 &&
2133 CritSectionCount == 0)
2135 /* bump holdoff count to make ProcessInterrupts() a no-op */
2136 /* until we are done getting ready for it */
2137 InterruptHoldoffCount++;
2138 if (LockWaitCancel())
2140 DisableNotifyInterrupt();
2141 DisableCatchupInterrupt();
2142 InterruptHoldoffCount--;
2143 ProcessInterrupts();
2146 InterruptHoldoffCount--;
2153 /* signal handler for floating point exception */
2155 FloatExceptionHandler(SIGNAL_ARGS)
2158 (errcode(ERRCODE_FLOATING_POINT_EXCEPTION),
2159 errmsg("floating-point exception"),
2160 errdetail("An invalid floating-point operation was signaled. "
2161 "This probably means an out-of-range result or an "
2162 "invalid operation, such as division by zero.")));
2165 /* SIGHUP: set flag to re-read config file at next convenient time */
2167 SigHupHandler(SIGNAL_ARGS)
2174 * ProcessInterrupts: out-of-line portion of CHECK_FOR_INTERRUPTS() macro
2176 * If an interrupt condition is pending, and it's safe to service it,
2177 * then clear the flag and accept the interrupt. Called only when
2178 * InterruptPending is true.
2181 ProcessInterrupts(void)
2183 /* OK to accept interrupt now? */
2184 if (InterruptHoldoffCount != 0 || CritSectionCount != 0)
2186 InterruptPending = false;
2189 ProcDiePending = false;
2190 QueryCancelPending = false; /* ProcDie trumps QueryCancel */
2191 ImmediateInterruptOK = false; /* not idle anymore */
2192 DisableNotifyInterrupt();
2193 DisableCatchupInterrupt();
2195 (errcode(ERRCODE_ADMIN_SHUTDOWN),
2196 errmsg("terminating connection due to administrator command")));
2198 if (QueryCancelPending)
2200 QueryCancelPending = false;
2201 ImmediateInterruptOK = false; /* not idle anymore */
2202 DisableNotifyInterrupt();
2203 DisableCatchupInterrupt();
2205 (errcode(ERRCODE_QUERY_CANCELED),
2206 errmsg("canceling query due to user request")));
2208 /* If we get here, do nothing (probably, QueryCancelPending was reset) */
2213 * check_stack_depth: check for excessively deep recursion
2215 * This should be called someplace in any recursive routine that might possibly
2216 * recurse deep enough to overflow the stack. Most Unixen treat stack
2217 * overflow as an unrecoverable SIGSEGV, so we want to error out ourselves
2218 * before hitting the hardware limit. Unfortunately we have no direct way
2219 * to detect the hardware limit, so we have to rely on the admin to set a
2220 * GUC variable for it ...
2223 check_stack_depth(void)
2229 * Compute distance from PostgresMain's local variables to my own
2231 * Note: in theory stack_depth should be ptrdiff_t or some such, but
2232 * since the whole point of this code is to bound the value to
2233 * something much less than integer-sized, int should work fine.
2235 stack_depth = (int) (stack_base_ptr - &stack_top_loc);
2238 * Take abs value, since stacks grow up on some machines, down on
2241 if (stack_depth < 0)
2242 stack_depth = -stack_depth;
2247 * The test on stack_base_ptr prevents us from erroring out if called
2248 * during process setup or in a non-backend process. Logically it
2249 * should be done first, but putting it here avoids wasting cycles
2250 * during normal cases.
2252 if (stack_depth > max_stack_depth_bytes &&
2253 stack_base_ptr != NULL)
2256 (errcode(ERRCODE_STATEMENT_TOO_COMPLEX),
2257 errmsg("stack depth limit exceeded"),
2258 errhint("Increase the configuration parameter \"max_stack_depth\".")));
2262 /* GUC assign hook to update max_stack_depth_bytes from max_stack_depth */
2264 assign_max_stack_depth(int newval, bool doit, GucSource source)
2266 /* Range check was already handled by guc.c */
2268 max_stack_depth_bytes = newval * 1024;
2274 usage(const char *progname)
2276 printf(_("%s is the PostgreSQL stand-alone backend. It is not\nintended to be used by normal users.\n\n"), progname);
2278 printf(_("Usage:\n %s [OPTION]... [DBNAME]\n\n"), progname);
2279 printf(_("Options:\n"));
2280 #ifdef USE_ASSERT_CHECKING
2281 printf(_(" -A 1|0 enable/disable run-time assert checking\n"));
2283 printf(_(" -B NBUFFERS number of shared buffers\n"));
2284 printf(_(" -c NAME=VALUE set run-time parameter\n"));
2285 printf(_(" -d 0-5 debugging level (0 is off)\n"));
2286 printf(_(" -D DATADIR database directory\n"));
2287 printf(_(" -e use European date input format (DMY)\n"));
2288 printf(_(" -E echo query before execution\n"));
2289 printf(_(" -F turn fsync off\n"));
2290 printf(_(" -N do not use newline as interactive query delimiter\n"));
2291 printf(_(" -o FILENAME send stdout and stderr to given file\n"));
2292 printf(_(" -P disable system indexes\n"));
2293 printf(_(" -s show statistics after each query\n"));
2294 printf(_(" -S WORK-MEM set amount of memory for sorts (in kB)\n"));
2295 printf(_(" --describe-config describe configuration parameters, then exit\n"));
2296 printf(_(" --help show this help, then exit\n"));
2297 printf(_(" --version output version information, then exit\n"));
2298 printf(_("\nDeveloper options:\n"));
2299 printf(_(" -f s|i|n|m|h forbid use of some plan types\n"));
2300 printf(_(" -i do not execute queries\n"));
2301 printf(_(" -O allow system table structure changes\n"));
2302 printf(_(" -t pa|pl|ex show timings after each query\n"));
2303 printf(_(" -W NUM wait NUM seconds to allow attach from a debugger\n"));
2304 printf(_("\nReport bugs to <pgsql-bugs@postgresql.org>.\n"));
2309 * set_debug_options --- apply "-d N" command line option
2311 * -d is not quite the same as setting log_min_messages because it enables
2312 * other output options.
2315 set_debug_options(int debug_flag, GucContext context, GucSource source)
2321 sprintf(debugstr, "debug%d", debug_flag);
2322 SetConfigOption("log_min_messages", debugstr, context, source);
2325 SetConfigOption("log_min_messages", "notice", context, source);
2327 if (debug_flag >= 1 && context == PGC_POSTMASTER)
2329 SetConfigOption("log_connections", "true", context, source);
2330 SetConfigOption("log_disconnections", "true", context, source);
2332 if (debug_flag >= 2)
2333 SetConfigOption("log_statement", "all", context, source);
2334 if (debug_flag >= 3)
2335 SetConfigOption("debug_print_parse", "true", context, source);
2336 if (debug_flag >= 4)
2337 SetConfigOption("debug_print_plan", "true", context, source);
2338 if (debug_flag >= 5)
2339 SetConfigOption("debug_print_rewritten", "true", context, source);
2343 /* ----------------------------------------------------------------
2345 * postgres main loop -- all backends, interactive or otherwise start here
2347 * argc/argv are the command line arguments to be used. (When being forked
2348 * by the postmaster, these are not the original argv array of the process.)
2349 * username is the (possibly authenticated) PostgreSQL user name to be used
2351 * ----------------------------------------------------------------
2354 PostgresMain(int argc, char *argv[], const char *username)
2357 const char *dbname = NULL;
2358 char *userDoption = NULL;
2361 int debug_flag = -1; /* -1 means not given */
2362 List *guc_names = NIL; /* for SUSET options */
2363 List *guc_values = NIL;
2365 GucSource gucsource;
2370 StringInfoData input_message;
2371 sigjmp_buf local_sigjmp_buf;
2372 volatile bool send_rfq = true;
2374 #define PendingConfigOption(name,val) \
2375 (guc_names = lappend(guc_names, pstrdup(name)), \
2376 guc_values = lappend(guc_values, pstrdup(val)))
2379 * Catch standard options before doing much else. This even works on
2380 * systems without getopt_long.
2382 if (!IsUnderPostmaster && argc > 1)
2384 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
2389 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
2391 puts(PG_VERSIONSTR);
2397 * initialize globals (already done if under postmaster, but not if
2398 * standalone; cheap enough to do over)
2400 MyProcPid = getpid();
2403 * Fire up essential subsystems: error and memory management
2405 * If we are running under the postmaster, this is done already.
2407 if (!IsUnderPostmaster)
2408 MemoryContextInit();
2410 set_ps_display("startup");
2412 SetProcessingMode(InitProcessing);
2414 /* Set up reference point for stack depth checking */
2415 stack_base_ptr = &stack_base;
2417 /* Compute paths, if we didn't inherit them from postmaster */
2418 if (my_exec_path[0] == '\0')
2420 if (find_my_exec(argv[0], my_exec_path) < 0)
2421 elog(FATAL, "%s: could not locate my own executable path",
2425 if (pkglib_path[0] == '\0')
2426 get_pkglib_path(my_exec_path, pkglib_path);
2429 * Set default values for command-line options.
2433 if (!IsUnderPostmaster)
2434 InitializeGUCOptions();
2437 * parse command line arguments
2439 * There are now two styles of command line layout for the backend:
2441 * For interactive use (not started from postmaster) the format is
2442 * postgres [switches] [databasename]
2443 * If the databasename is omitted it is taken to be the user name.
2445 * When started from the postmaster, the format is
2446 * postgres [secure switches] -p databasename [insecure switches]
2447 * Switches appearing after -p came from the client (via "options"
2448 * field of connection request). For security reasons we restrict
2449 * what these switches can do.
2453 /* all options are allowed until '-p' */
2455 ctx = PGC_POSTMASTER;
2456 gucsource = PGC_S_ARGV; /* initial switches came from command line */
2458 while ((flag = getopt(argc, argv, "A:B:c:D:d:Eef:FiNOPo:p:S:st:v:W:-:")) != -1)
2463 #ifdef USE_ASSERT_CHECKING
2464 SetConfigOption("debug_assertions", optarg, ctx, gucsource);
2467 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2468 errmsg("assert checking is not compiled in")));
2475 * specify the size of buffer pool
2477 SetConfigOption("shared_buffers", optarg, ctx, gucsource);
2480 case 'D': /* PGDATA or config directory */
2482 userDoption = optarg;
2485 case 'd': /* debug level */
2486 debug_flag = atoi(optarg);
2492 * E - echo the query the user entered
2500 * Use European date input format (DMY)
2502 SetConfigOption("datestyle", "euro", ctx, gucsource);
2510 SetConfigOption("fsync", "false", ctx, gucsource);
2516 * f - forbid generation of certain plans
2521 case 's': /* seqscan */
2522 tmp = "enable_seqscan";
2524 case 'i': /* indexscan */
2525 tmp = "enable_indexscan";
2527 case 'b': /* bitmapscan */
2528 tmp = "enable_bitmapscan";
2530 case 't': /* tidscan */
2531 tmp = "enable_tidscan";
2533 case 'n': /* nestloop */
2534 tmp = "enable_nestloop";
2536 case 'm': /* mergejoin */
2537 tmp = "enable_mergejoin";
2539 case 'h': /* hashjoin */
2540 tmp = "enable_hashjoin";
2546 SetConfigOption(tmp, "false", ctx, gucsource);
2552 * N - Don't use newline as a query delimiter
2560 * allow system table structure modifications
2562 if (secure) /* XXX safe to allow from client??? */
2563 allowSystemTableMods = true;
2569 * ignore system indexes
2571 * As of PG 7.4 this is safe to allow from the client, since
2572 * it only disables reading the system indexes, not
2573 * writing them. Worst case consequence is slowness.
2575 IgnoreSystemIndexes(true);
2581 * o - send output (stdout and stderr) to the given file
2584 StrNCpy(OutputFileName, optarg, MAXPGPATH);
2590 * p - special flag passed if backend was forked by a
2595 dbname = strdup(optarg);
2597 secure = false; /* subsequent switches are NOT
2600 gucsource = PGC_S_CLIENT;
2607 * S - amount of sort memory to use in 1k bytes
2609 SetConfigOption("work_mem", optarg, ctx, gucsource);
2615 * s - report usage statistics (timings) after each query
2617 * Since log options are SUSET, we need to postpone unless
2618 * still in secure context
2620 if (ctx == PGC_BACKEND)
2621 PendingConfigOption("log_statement_stats", "true");
2623 SetConfigOption("log_statement_stats", "true",
2629 * tell postgres to report usage statistics (timings) for
2632 * -tpa[rser] = print stats for parser time of each query
2633 * -tpl[anner] = print stats for planner time of each query
2634 * -te[xecutor] = print stats for executor time of each query
2635 * caution: -s can not be used together with -t.
2642 if (optarg[1] == 'a')
2643 tmp = "log_parser_stats";
2644 else if (optarg[1] == 'l')
2645 tmp = "log_planner_stats";
2650 tmp = "log_executor_stats";
2658 if (ctx == PGC_BACKEND)
2659 PendingConfigOption(tmp, "true");
2661 SetConfigOption(tmp, "true", ctx, gucsource);
2667 FrontendProtocol = (ProtocolVersion) atoi(optarg);
2673 * wait N seconds to allow attach from a debugger
2675 pg_usleep(atoi(optarg) * 1000000L);
2684 ParseLongOption(optarg, &name, &value);
2689 (errcode(ERRCODE_SYNTAX_ERROR),
2690 errmsg("--%s requires a value",
2694 (errcode(ERRCODE_SYNTAX_ERROR),
2695 errmsg("-c %s requires a value",
2700 * If a SUSET option, must postpone evaluation, unless
2701 * we are still reading secure switches.
2703 if (ctx == PGC_BACKEND && IsSuperuserConfigOption(name))
2704 PendingConfigOption(name, value);
2706 SetConfigOption(name, value, ctx, gucsource);
2720 * Process any additional GUC variable settings passed in startup
2721 * packet. These are handled exactly like command-line variables.
2723 if (MyProcPort != NULL)
2725 ListCell *gucopts = list_head(MyProcPort->guc_options);
2732 name = lfirst(gucopts);
2733 gucopts = lnext(gucopts);
2735 value = lfirst(gucopts);
2736 gucopts = lnext(gucopts);
2738 if (IsSuperuserConfigOption(name))
2739 PendingConfigOption(name, value);
2741 SetConfigOption(name, value, PGC_BACKEND, PGC_S_CLIENT);
2745 /* Acquire configuration parameters, unless inherited from postmaster */
2746 if (!IsUnderPostmaster)
2748 if (!SelectConfigFiles(userDoption, argv[0]))
2753 * Set up signal handlers and masks.
2755 * Note that postmaster blocked all signals before forking child process,
2756 * so there is no race condition whereby we might receive a signal
2757 * before we have set up the handler.
2759 * Also note: it's best not to use any signals that are SIG_IGNored in
2760 * the postmaster. If such a signal arrives before we are able to
2761 * change the handler to non-SIG_IGN, it'll get dropped. Instead,
2762 * make a dummy handler in the postmaster to reserve the signal. (Of
2763 * course, this isn't an issue for signals that are locally generated,
2764 * such as SIGALRM and SIGPIPE.)
2766 pqsignal(SIGHUP, SigHupHandler); /* set flag to read config file */
2767 pqsignal(SIGINT, StatementCancelHandler); /* cancel current query */
2768 pqsignal(SIGTERM, die); /* cancel current query and exit */
2769 pqsignal(SIGQUIT, quickdie); /* hard crash time */
2770 pqsignal(SIGALRM, handle_sig_alarm); /* timeout conditions */
2773 * Ignore failure to write to frontend. Note: if frontend closes
2774 * connection, we will notice it and exit cleanly when control next
2775 * returns to outer loop. This seems safer than forcing exit in the
2776 * midst of output during who-knows-what operation...
2778 pqsignal(SIGPIPE, SIG_IGN);
2779 pqsignal(SIGUSR1, CatchupInterruptHandler);
2780 pqsignal(SIGUSR2, NotifyInterruptHandler);
2781 pqsignal(SIGFPE, FloatExceptionHandler);
2784 * Reset some signals that are accepted by postmaster but not by
2787 pqsignal(SIGCHLD, SIG_DFL); /* system() requires this on some
2792 /* We allow SIGQUIT (quickdie) at all times */
2793 #ifdef HAVE_SIGPROCMASK
2794 sigdelset(&BlockSig, SIGQUIT);
2796 BlockSig &= ~(sigmask(SIGQUIT));
2799 PG_SETMASK(&BlockSig); /* block everything except SIGQUIT */
2802 if (IsUnderPostmaster)
2804 /* noninteractive case: nothing should be left after switches */
2805 if (errs || argc != optind || dbname == NULL)
2808 (errcode(ERRCODE_SYNTAX_ERROR),
2809 errmsg("invalid command-line arguments for server process"),
2810 errhint("Try \"%s --help\" for more information.", argv[0])));
2817 /* interactive case: database name can be last arg on command line */
2818 if (errs || argc - optind > 1)
2821 (errcode(ERRCODE_SYNTAX_ERROR),
2822 errmsg("%s: invalid command-line arguments",
2824 errhint("Try \"%s --help\" for more information.", argv[0])));
2826 else if (argc - optind == 1)
2827 dbname = argv[optind];
2828 else if ((dbname = username) == NULL)
2831 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2832 errmsg("%s: no database nor user name specified",
2837 * Validate we have been given a reasonable-looking DataDir (if
2838 * under postmaster, assume postmaster did this already).
2841 ValidatePgVersion(DataDir);
2843 /* Change into DataDir (if under postmaster, was done already) */
2847 * Create lockfile for data directory.
2849 CreateDataDirLockFile(false);
2854 * Start up xlog for standalone backend, and register to have it
2855 * closed down at exit.
2858 on_shmem_exit(ShutdownXLOG, 0);
2861 * Read any existing FSM cache file, and register to write one out
2865 on_shmem_exit(DumpFreeSpaceMap, 0);
2868 * We have to build the flat file for pg_database, but not for
2869 * the user and group tables, since we won't try to do authentication.
2871 BuildFlatFiles(true);
2875 * General initialization.
2877 * NOTE: if you are tempted to add code in this vicinity, consider
2878 * putting it inside InitPostgres() instead. In particular, anything
2879 * that involves database access should be there, not here.
2882 (errmsg_internal("InitPostgres")));
2883 am_superuser = InitPostgres(dbname, username);
2885 SetProcessingMode(NormalProcessing);
2888 * Now that we know if client is a superuser, we can try to apply SUSET
2889 * GUC options that came from the client.
2891 ctx = am_superuser ? PGC_SUSET : PGC_USERSET;
2893 if (debug_flag >= 0)
2894 set_debug_options(debug_flag, ctx, PGC_S_CLIENT);
2896 if (guc_names != NIL)
2901 forboth(namcell, guc_names, valcell, guc_values)
2903 char *name = (char *) lfirst(namcell);
2904 char *value = (char *) lfirst(valcell);
2906 SetConfigOption(name, value, ctx, PGC_S_CLIENT);
2913 * Now all GUC states are fully set up. Report them to client if
2916 BeginReportingGUCOptions();
2919 * Also set up handler to log session end; we have to wait till now
2920 * to be sure Log_disconnections has its final value.
2922 if (IsUnderPostmaster && Log_disconnections)
2923 on_proc_exit(log_disconnections, 0);
2926 * Send this backend's cancellation info to the frontend.
2928 if (whereToSendOutput == Remote &&
2929 PG_PROTOCOL_MAJOR(FrontendProtocol) >= 2)
2933 pq_beginmessage(&buf, 'K');
2934 pq_sendint(&buf, (int32) MyProcPid, sizeof(int32));
2935 pq_sendint(&buf, (int32) MyCancelKey, sizeof(int32));
2936 pq_endmessage(&buf);
2937 /* Need not flush since ReadyForQuery will do it. */
2940 /* Welcome banner for standalone case */
2941 if (whereToSendOutput == Debug)
2942 printf("\nPostgreSQL stand-alone backend %s\n", PG_VERSION);
2945 * Create the memory context we will use in the main loop.
2947 * MessageContext is reset once per iteration of the main loop, ie, upon
2948 * completion of processing of each command message from the client.
2950 MessageContext = AllocSetContextCreate(TopMemoryContext,
2952 ALLOCSET_DEFAULT_MINSIZE,
2953 ALLOCSET_DEFAULT_INITSIZE,
2954 ALLOCSET_DEFAULT_MAXSIZE);
2957 * Tell the statistics collector that we're alive and
2958 * to which database we belong.
2964 * Remember stand-alone backend startup time
2966 if (!IsUnderPostmaster)
2967 PgStartTime = GetCurrentTimestamp();
2970 * POSTGRES main processing loop begins here
2972 * If an exception is encountered, processing resumes here so we abort
2973 * the current transaction and start a new one.
2975 * You might wonder why this isn't coded as an infinite loop around a
2976 * PG_TRY construct. The reason is that this is the bottom of the
2977 * exception stack, and so with PG_TRY there would be no exception
2978 * handler in force at all during the CATCH part. By leaving the
2979 * outermost setjmp always active, we have at least some chance of
2980 * recovering from an error during error recovery. (If we get into an
2981 * infinite loop thereby, it will soon be stopped by overflow of
2982 * elog.c's internal state stack.)
2985 if (sigsetjmp(local_sigjmp_buf, 1) != 0)
2988 * NOTE: if you are tempted to add more code in this if-block,
2989 * consider the high probability that it should be in
2990 * AbortTransaction() instead. The only stuff done directly here
2991 * should be stuff that is guaranteed to apply *only* for
2992 * outer-level error recovery, such as adjusting the FE/BE
2996 /* Since not using PG_TRY, must reset error stack by hand */
2997 error_context_stack = NULL;
2999 /* Prevent interrupts while cleaning up */
3003 * Forget any pending QueryCancel request, since we're returning
3004 * to the idle loop anyway, and cancel the statement timer if
3007 QueryCancelPending = false;
3008 disable_sig_alarm(true);
3009 QueryCancelPending = false; /* again in case timeout occurred */
3012 * Turn off these interrupts too. This is only needed here and
3013 * not in other exception-catching places since these interrupts
3014 * are only enabled while we wait for client input.
3016 DoingCommandRead = false;
3017 DisableNotifyInterrupt();
3018 DisableCatchupInterrupt();
3020 /* Make sure libpq is in a good state */
3023 /* Report the error to the client and/or server log */
3027 * Make sure debug_query_string gets reset before we possibly
3028 * clobber the storage it points at.
3030 debug_query_string = NULL;
3033 * Abort the current transaction in order to recover.
3035 AbortCurrentTransaction();
3038 * Now return to normal top-level context and clear ErrorContext
3041 MemoryContextSwitchTo(TopMemoryContext);
3043 QueryContext = NULL;
3046 * If we were handling an extended-query-protocol message,
3047 * initiate skip till next Sync. This also causes us not to issue
3048 * ReadyForQuery (until we get Sync).
3050 if (doing_extended_query_message)
3051 ignore_till_sync = true;
3053 /* We don't have a transaction command open anymore */
3054 xact_started = false;
3056 /* Now we can allow interrupts again */
3057 RESUME_INTERRUPTS();
3060 /* We can now handle ereport(ERROR) */
3061 PG_exception_stack = &local_sigjmp_buf;
3063 PG_SETMASK(&UnBlockSig);
3065 if (!ignore_till_sync)
3066 send_rfq = true; /* initially, or after error */
3069 * Non-error queries loop here.
3075 * At top of loop, reset extended-query-message flag, so that any
3076 * errors encountered in "idle" state don't provoke skip.
3078 doing_extended_query_message = false;
3081 * Release storage left over from prior query cycle, and create a
3082 * new query input buffer in the cleared MessageContext.
3084 MemoryContextSwitchTo(MessageContext);
3085 MemoryContextResetAndDeleteChildren(MessageContext);
3087 initStringInfo(&input_message);
3090 * (1) If we've reached idle state, tell the frontend we're ready
3093 * Note: this includes fflush()'ing the last of the prior output.
3095 * This is also a good time to send collected statistics to the
3096 * collector, and to update the PS stats display. We avoid doing
3097 * those every time through the message loop because it'd slow
3098 * down processing of batched messages, and because we don't want
3099 * to report uncommitted updates (that confuses autovacuum).
3103 if (IsTransactionOrTransactionBlock())
3105 set_ps_display("idle in transaction");
3106 pgstat_report_activity("<IDLE> in transaction");
3110 pgstat_report_tabstat();
3112 set_ps_display("idle");
3113 pgstat_report_activity("<IDLE>");
3116 ReadyForQuery(whereToSendOutput);
3121 * (2) Allow asynchronous signals to be executed immediately
3122 * if they come in while we are waiting for client input.
3123 * (This must be conditional since we don't want, say, reads on
3124 * behalf of COPY FROM STDIN doing the same thing.)
3126 QueryCancelPending = false; /* forget any earlier CANCEL signal */
3127 DoingCommandRead = true;
3130 * (3) read a command (loop blocks here)
3132 firstchar = ReadCommand(&input_message);
3135 * (4) disable async signal conditions again.
3137 DoingCommandRead = false;
3140 * (5) check for any other interesting events that happened while
3146 ProcessConfigFile(PGC_SIGHUP);
3150 * (6) process the command. But ignore it if we're skipping till
3153 if (ignore_till_sync && firstchar != EOF)
3158 case 'Q': /* simple query */
3160 const char *query_string;
3162 query_string = pq_getmsgstring(&input_message);
3163 pq_getmsgend(&input_message);
3165 exec_simple_query(query_string);
3171 case 'P': /* parse */
3173 const char *stmt_name;
3174 const char *query_string;
3176 Oid *paramTypes = NULL;
3178 stmt_name = pq_getmsgstring(&input_message);
3179 query_string = pq_getmsgstring(&input_message);
3180 numParams = pq_getmsgint(&input_message, 2);
3185 paramTypes = (Oid *) palloc(numParams * sizeof(Oid));
3186 for (i = 0; i < numParams; i++)
3187 paramTypes[i] = pq_getmsgint(&input_message, 4);
3189 pq_getmsgend(&input_message);
3191 exec_parse_message(query_string, stmt_name,
3192 paramTypes, numParams);
3196 case 'B': /* bind */
3199 * this message is complex enough that it seems best to
3200 * put the field extraction out-of-line
3202 exec_bind_message(&input_message);
3205 case 'E': /* execute */
3207 const char *portal_name;
3210 portal_name = pq_getmsgstring(&input_message);
3211 max_rows = pq_getmsgint(&input_message, 4);
3212 pq_getmsgend(&input_message);
3214 exec_execute_message(portal_name, max_rows);
3218 case 'F': /* fastpath function call */
3219 /* Tell the collector what we're doing */
3220 pgstat_report_activity("<FASTPATH> function call");
3222 /* start an xact for this function invocation */
3223 start_xact_command();
3225 /* switch back to message context */
3226 MemoryContextSwitchTo(MessageContext);
3228 /* set snapshot in case function needs one */
3229 ActiveSnapshot = CopySnapshot(GetTransactionSnapshot());
3231 if (HandleFunctionRequest(&input_message) == EOF)
3233 /* lost frontend connection during F message input */
3236 * Reset whereToSendOutput to prevent ereport from
3237 * attempting to send any more messages to client.
3239 if (whereToSendOutput == Remote)
3240 whereToSendOutput = None;
3245 /* commit the function-invocation transaction */
3246 finish_xact_command();
3251 case 'C': /* close */
3254 const char *close_target;
3256 close_type = pq_getmsgbyte(&input_message);
3257 close_target = pq_getmsgstring(&input_message);
3258 pq_getmsgend(&input_message);
3263 if (close_target[0] != '\0')
3264 DropPreparedStatement(close_target, false);
3267 /* special-case the unnamed statement */
3268 unnamed_stmt_pstmt = NULL;
3269 if (unnamed_stmt_context)
3271 DropDependentPortals(unnamed_stmt_context);
3272 MemoryContextDelete(unnamed_stmt_context);
3274 unnamed_stmt_context = NULL;
3281 portal = GetPortalByName(close_target);
3282 if (PortalIsValid(portal))
3283 PortalDrop(portal, false);
3288 (errcode(ERRCODE_PROTOCOL_VIOLATION),
3289 errmsg("invalid CLOSE message subtype %d",
3294 if (whereToSendOutput == Remote)
3295 pq_putemptymessage('3'); /* CloseComplete */
3299 case 'D': /* describe */
3302 const char *describe_target;
3304 describe_type = pq_getmsgbyte(&input_message);
3305 describe_target = pq_getmsgstring(&input_message);
3306 pq_getmsgend(&input_message);
3308 switch (describe_type)
3311 exec_describe_statement_message(describe_target);
3314 exec_describe_portal_message(describe_target);
3318 (errcode(ERRCODE_PROTOCOL_VIOLATION),
3319 errmsg("invalid DESCRIBE message subtype %d",
3326 case 'H': /* flush */
3327 pq_getmsgend(&input_message);
3328 if (whereToSendOutput == Remote)
3332 case 'S': /* sync */
3333 pq_getmsgend(&input_message);
3334 finish_xact_command();
3339 * 'X' means that the frontend is closing down the socket.
3340 * EOF means unexpected loss of frontend connection.
3341 * Either way, perform normal shutdown.
3347 * Reset whereToSendOutput to prevent ereport from
3348 * attempting to send any more messages to client.
3350 if (whereToSendOutput == Remote)
3351 whereToSendOutput = None;
3354 * NOTE: if you are tempted to add more code here, DON'T!
3355 * Whatever you had in mind to do should be set up as an
3356 * on_proc_exit or on_shmem_exit callback, instead.
3357 * Otherwise it will fail to be called during other
3358 * backend-shutdown scenarios.
3362 case 'd': /* copy data */
3363 case 'c': /* copy done */
3364 case 'f': /* copy fail */
3367 * Accept but ignore these messages, per protocol spec; we
3368 * probably got here because a COPY failed, and the
3369 * frontend is still sending data.
3375 (errcode(ERRCODE_PROTOCOL_VIOLATION),
3376 errmsg("invalid frontend message type %d",
3379 } /* end of input-reading loop */
3381 /* can't get here because the above loop never exits */
3384 return 1; /* keep compiler quiet */
3387 #ifndef HAVE_GETRUSAGE
3388 #include "rusagestub.h"
3390 #include <sys/resource.h>
3391 #endif /* HAVE_GETRUSAGE */
3393 static struct rusage Save_r;
3394 static struct timeval Save_t;
3399 getrusage(RUSAGE_SELF, &Save_r);
3400 gettimeofday(&Save_t, NULL);
3402 /* ResetTupleCount(); */
3406 ShowUsage(const char *title)
3409 struct timeval user,
3411 struct timeval elapse_t;
3415 getrusage(RUSAGE_SELF, &r);
3416 gettimeofday(&elapse_t, NULL);
3417 memcpy((char *) &user, (char *) &r.ru_utime, sizeof(user));
3418 memcpy((char *) &sys, (char *) &r.ru_stime, sizeof(sys));
3419 if (elapse_t.tv_usec < Save_t.tv_usec)
3422 elapse_t.tv_usec += 1000000;
3424 if (r.ru_utime.tv_usec < Save_r.ru_utime.tv_usec)
3426 r.ru_utime.tv_sec--;
3427 r.ru_utime.tv_usec += 1000000;
3429 if (r.ru_stime.tv_usec < Save_r.ru_stime.tv_usec)
3431 r.ru_stime.tv_sec--;
3432 r.ru_stime.tv_usec += 1000000;
3436 * the only stats we don't show here are for memory usage -- i can't
3437 * figure out how to interpret the relevant fields in the rusage
3438 * struct, and they change names across o/s platforms, anyway. if you
3439 * can figure out what the entries mean, you can somehow extract
3440 * resident set size, shared text size, and unshared data and stack
3443 initStringInfo(&str);
3445 appendStringInfo(&str, "! system usage stats:\n");
3446 appendStringInfo(&str,
3447 "!\t%ld.%06ld elapsed %ld.%06ld user %ld.%06ld system sec\n",
3448 (long) (elapse_t.tv_sec - Save_t.tv_sec),
3449 (long) (elapse_t.tv_usec - Save_t.tv_usec),
3450 (long) (r.ru_utime.tv_sec - Save_r.ru_utime.tv_sec),
3451 (long) (r.ru_utime.tv_usec - Save_r.ru_utime.tv_usec),
3452 (long) (r.ru_stime.tv_sec - Save_r.ru_stime.tv_sec),
3453 (long) (r.ru_stime.tv_usec - Save_r.ru_stime.tv_usec));
3454 appendStringInfo(&str,
3455 "!\t[%ld.%06ld user %ld.%06ld sys total]\n",
3457 (long) user.tv_usec,
3459 (long) sys.tv_usec);
3460 /* BeOS has rusage but only has some fields, and not these... */
3461 #if defined(HAVE_GETRUSAGE)
3462 appendStringInfo(&str,
3463 "!\t%ld/%ld [%ld/%ld] filesystem blocks in/out\n",
3464 r.ru_inblock - Save_r.ru_inblock,
3465 /* they only drink coffee at dec */
3466 r.ru_oublock - Save_r.ru_oublock,
3467 r.ru_inblock, r.ru_oublock);
3468 appendStringInfo(&str,
3469 "!\t%ld/%ld [%ld/%ld] page faults/reclaims, %ld [%ld] swaps\n",
3470 r.ru_majflt - Save_r.ru_majflt,
3471 r.ru_minflt - Save_r.ru_minflt,
3472 r.ru_majflt, r.ru_minflt,
3473 r.ru_nswap - Save_r.ru_nswap,
3475 appendStringInfo(&str,
3476 "!\t%ld [%ld] signals rcvd, %ld/%ld [%ld/%ld] messages rcvd/sent\n",
3477 r.ru_nsignals - Save_r.ru_nsignals,
3479 r.ru_msgrcv - Save_r.ru_msgrcv,
3480 r.ru_msgsnd - Save_r.ru_msgsnd,
3481 r.ru_msgrcv, r.ru_msgsnd);
3482 appendStringInfo(&str,
3483 "!\t%ld/%ld [%ld/%ld] voluntary/involuntary context switches\n",
3484 r.ru_nvcsw - Save_r.ru_nvcsw,
3485 r.ru_nivcsw - Save_r.ru_nivcsw,
3486 r.ru_nvcsw, r.ru_nivcsw);
3487 #endif /* HAVE_GETRUSAGE */
3489 bufusage = ShowBufferUsage();
3490 appendStringInfo(&str, "! buffer usage stats:\n%s", bufusage);
3493 /* remove trailing newline */
3494 if (str.data[str.len - 1] == '\n')
3495 str.data[--str.len] = '\0';
3498 (errmsg_internal("%s", title),
3499 errdetail("%s", str.data)));
3505 * on_proc_exit handler to log end of session
3508 log_disconnections(int code, Datum arg)
3510 Port *port = MyProcPort;
3516 char session_time[20];
3517 char uname[6 + NAMEDATALEN];
3518 char dbname[10 + NAMEDATALEN];
3519 char remote_host[7 + NI_MAXHOST];
3520 char remote_port[7 + NI_MAXSERV];
3522 snprintf(uname, sizeof(uname), " user=%s", port->user_name);
3523 snprintf(dbname, sizeof(dbname), " database=%s", port->database_name);
3524 snprintf(remote_host, sizeof(remote_host), " host=%s",
3526 snprintf(remote_port, sizeof(remote_port), " port=%s", port->remote_port);
3529 gettimeofday(&end, NULL);
3531 if (end.tv_usec < port->session_start.tv_usec)
3534 end.tv_usec += 1000000;
3536 end.tv_sec -= port->session_start.tv_sec;
3537 end.tv_usec -= port->session_start.tv_usec;
3539 hours = end.tv_sec / SECS_PER_HOUR;
3540 end.tv_sec %= SECS_PER_HOUR;
3541 minutes = end.tv_sec / SECS_PER_MINUTE;
3542 seconds = end.tv_sec % SECS_PER_MINUTE;
3544 /* if time has gone backwards for some reason say so, or print time */
3547 snprintf(session_time, sizeof(session_time), "negative!");
3551 * for stricter accuracy here we could round - this is close
3554 snprintf(session_time, sizeof(session_time),
3555 "%d:%02d:%02d.%02d",
3556 hours, minutes, seconds, (int) (end.tv_usec / 10000));
3560 (errmsg("disconnection: session time: %s%s%s%s%s",
3561 session_time, uname, dbname, remote_host, remote_port)));