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.469 2005/11/10 00:31:34 tgl 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 log_min_error_statement */
76 /* Note: whereToSendOutput is initialized for the bootstrap/standalone case */
77 CommandDest whereToSendOutput = DestDebug;
79 /* flag for logging end of session */
80 bool Log_disconnections = false;
82 LogStmtLevel log_statement = LOGSTMT_NONE;
84 /* GUC variable for maximum stack depth (measured in kilobytes) */
85 int max_stack_depth = 2048;
93 /* max_stack_depth converted to bytes for speed of checking */
94 static int max_stack_depth_bytes = 2048 * 1024;
96 /* stack base pointer (initialized by PostgresMain) */
97 /* Do not make static so PL/Java can modifiy it */
98 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 default) */
146 static int UseNewLine = 0; /* Use EOF as query delimiters */
147 #endif /* TCOP_DONTUSENEWLINE */
150 /* ----------------------------------------------------------------
151 * decls for routines only used in this file
152 * ----------------------------------------------------------------
154 static int InteractiveBackend(StringInfo inBuf);
155 static int SocketBackend(StringInfo inBuf);
156 static int ReadCommand(StringInfo inBuf);
157 static bool log_after_parse(List *raw_parsetree_list,
158 const char *query_string, char **prepare_string);
159 static List *pg_rewrite_queries(List *querytree_list);
160 static void start_xact_command(void);
161 static void finish_xact_command(void);
162 static bool IsTransactionExitStmt(Node *parsetree);
163 static bool IsTransactionExitStmtList(List *parseTrees);
164 static bool IsTransactionStmtList(List *parseTrees);
165 static void SigHupHandler(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 until
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 lost
301 * sync, better to say "command unknown" than to run out of memory because
302 * we used garbage as a length word.
304 * This also gives us a place to set the doing_extended_query_message flag as
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 as
375 * fatal because we have probably lost message boundary sync, and
376 * 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 next
386 * after the type code; we can read the message contents independently of
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 == DestRemote)
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 used by
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 more or
661 * 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 copyObject()
695 new_list = (List *) copyObject(querytree_list);
696 /* This checks both copyObject() and the equal() routines... */
697 if (!equal(new_list, querytree_list))
698 elog(WARNING, "copyObject() failed to produce an equal parse tree");
700 querytree_list = new_list;
703 if (Debug_print_rewritten)
704 elog_node_display(DEBUG1, "rewritten parse tree", querytree_list,
707 return querytree_list;
711 /* Generate a plan for a single already-rewritten query. */
713 pg_plan_query(Query *querytree, ParamListInfo boundParams)
717 /* Utility commands have no plans. */
718 if (querytree->commandType == CMD_UTILITY)
721 if (log_planner_stats)
724 /* call the optimizer */
725 plan = planner(querytree, false, 0, boundParams);
727 if (log_planner_stats)
728 ShowUsage("PLANNER STATISTICS");
730 #ifdef COPY_PARSE_PLAN_TREES
731 /* Optional debugging check: pass plan output through copyObject() */
733 Plan *new_plan = (Plan *) copyObject(plan);
736 * equal() currently does not have routines to compare Plan nodes, so
737 * don't try to test equality here. Perhaps fix someday?
740 /* This checks both copyObject() and the equal() routines... */
741 if (!equal(new_plan, plan))
742 elog(WARNING, "copyObject() failed to produce an equal plan tree");
750 * Print plan if debugging.
752 if (Debug_print_plan)
753 elog_node_display(DEBUG1, "plan", plan, Debug_pretty_print);
759 * Generate plans for a list of already-rewritten queries.
761 * If needSnapshot is TRUE, we haven't yet set a snapshot for the current
762 * query. A snapshot must be set before invoking the planner, since it
763 * might try to evaluate user-defined functions. But we must not set a
764 * snapshot if the list contains only utility statements, because some
765 * utility statements depend on not having frozen the snapshot yet.
766 * (We assume that such statements cannot appear together with plannable
767 * statements in the rewriter's output.)
770 pg_plan_queries(List *querytrees, ParamListInfo boundParams,
773 List *plan_list = NIL;
774 ListCell *query_list;
776 foreach(query_list, querytrees)
778 Query *query = (Query *) lfirst(query_list);
781 if (query->commandType == CMD_UTILITY)
783 /* Utility commands have no plans. */
790 ActiveSnapshot = CopySnapshot(GetTransactionSnapshot());
791 needSnapshot = false;
793 plan = pg_plan_query(query, boundParams);
796 plan_list = lappend(plan_list, plan);
806 * Execute a "simple Query" protocol message.
809 exec_simple_query(const char *query_string)
811 CommandDest dest = whereToSendOutput;
812 MemoryContext oldcontext;
813 List *parsetree_list;
814 ListCell *parsetree_item;
815 struct timeval start_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 because
833 * gettimeofday() wasn't called. Similarly, log_statement_stats has to be
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 after
846 * one of those, else bad things will happen in xact.c. (Note that this
847 * will normally change current memory context.)
849 start_xact_command();
852 * Zap any pre-existing unnamed statement. (While not strictly necessary,
853 * it seems best to define simple-Query mode as if it used the unnamed
854 * statement and portal; this ensures we recover any storage used by prior
855 * 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 if
874 * 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 the
903 * default completion tag, down inside PortalRun). Set ps_status and
904 * do any special start-of-SQL-command processing needed by the
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 try
916 * to do parse analysis, rewrite, or planning, since all those phases
917 * try to do database accesses, which may fail in abort state. (It
918 * might be safe to allow some additional utility commands in this
919 * state, but not many...)
921 if (IsAbortedTransactionBlockState() &&
922 !IsTransactionExitStmt(parsetree))
924 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
925 errmsg("current transaction is aborted, "
926 "commands ignored until end of transaction block")));
928 /* Make sure we are in a transaction command */
929 start_xact_command();
931 /* If we got a cancel signal in parsing or prior command, quit */
932 CHECK_FOR_INTERRUPTS();
935 * OK to analyze, rewrite, and plan this query.
937 * Switch to appropriate context for constructing querytrees (again,
938 * these must outlive the execution context).
940 oldcontext = MemoryContextSwitchTo(MessageContext);
942 querytree_list = pg_analyze_and_rewrite(parsetree, NULL, 0);
944 plantree_list = pg_plan_queries(querytree_list, NULL, true);
946 /* If we got a cancel signal in analysis or planning, quit */
947 CHECK_FOR_INTERRUPTS();
950 * Create unnamed portal to run the query or queries in. If there
951 * already is one, silently drop it.
953 portal = CreatePortal("", true, true);
955 PortalDefineQuery(portal,
963 * Start the portal. No parameters here.
965 PortalStart(portal, NULL, InvalidSnapshot);
968 * Select the appropriate output format: text unless we are doing a
969 * FETCH from a binary cursor. (Pretty grotty to have to do this here
970 * --- but it avoids grottiness in other places. Ah, the joys of
971 * backward compatibility...)
973 format = 0; /* TEXT is default */
974 if (IsA(parsetree, FetchStmt))
976 FetchStmt *stmt = (FetchStmt *) parsetree;
980 Portal fportal = GetPortalByName(stmt->portalname);
982 if (PortalIsValid(fportal) &&
983 (fportal->cursorOptions & CURSOR_OPT_BINARY))
984 format = 1; /* BINARY */
987 PortalSetResultFormat(portal, 1, &format);
990 * Now we can create the destination receiver object.
992 receiver = CreateDestReceiver(dest, portal);
995 * Switch back to transaction context for execution.
997 MemoryContextSwitchTo(oldcontext);
1000 * Run the portal to completion, and then drop it (and the receiver).
1002 (void) PortalRun(portal,
1008 (*receiver->rDestroy) (receiver);
1010 PortalDrop(portal, false);
1012 if (IsA(parsetree, TransactionStmt))
1015 * If this was a transaction control statement, commit it. We will
1016 * start a new xact command for the next command (if any).
1018 finish_xact_command();
1020 else if (lnext(parsetree_item) == NULL)
1023 * If this is the last parsetree of the query string, close down
1024 * transaction statement before reporting command-complete. This
1025 * is so that any end-of-transaction errors are reported before
1026 * the command-complete message is issued, to avoid confusing
1027 * clients who will expect either a command-complete message or an
1028 * error, not one and then the other. But for compatibility with
1029 * historical Postgres behavior, we do not force a transaction
1030 * boundary between queries appearing in a single query string.
1032 finish_xact_command();
1037 * We need a CommandCounterIncrement after every query, except
1038 * those that start or end a transaction block.
1040 CommandCounterIncrement();
1044 * Tell client that we're done with this query. Note we emit exactly
1045 * one EndCommand report for each raw parsetree, thus one for each SQL
1046 * command the client sent, regardless of rewriting. (But a command
1047 * aborted by error will not send an EndCommand report at all.)
1049 EndCommand(completionTag, dest);
1050 } /* end loop over parsetrees */
1053 * Close down transaction statement, if one is open.
1055 finish_xact_command();
1058 * If there were no parsetrees, return EmptyQueryResponse message.
1060 if (!parsetree_list)
1063 QueryContext = NULL;
1066 * Combine processing here as we need to calculate the query duration in
1069 if (save_log_duration || save_log_min_duration_statement != -1)
1073 gettimeofday(&stop_t, NULL);
1074 if (stop_t.tv_usec < start_t.tv_usec)
1077 stop_t.tv_usec += 1000000;
1079 usecs = (long) (stop_t.tv_sec - start_t.tv_sec) * 1000000 +
1080 (long) (stop_t.tv_usec - start_t.tv_usec);
1082 /* Only print duration if we previously printed the statement. */
1083 if (was_logged && save_log_duration)
1085 (errmsg("duration: %ld.%03ld ms",
1086 (long) ((stop_t.tv_sec - start_t.tv_sec) * 1000 +
1087 (stop_t.tv_usec - start_t.tv_usec) / 1000),
1088 (long) (stop_t.tv_usec - start_t.tv_usec) % 1000)));
1091 * Output a duration_statement to the log if the query has exceeded
1092 * the min duration, or if we are to print all durations.
1094 if (save_log_min_duration_statement == 0 ||
1095 (save_log_min_duration_statement > 0 &&
1096 usecs >= save_log_min_duration_statement * 1000))
1098 (errmsg("duration: %ld.%03ld ms statement: %s%s",
1099 (long) ((stop_t.tv_sec - start_t.tv_sec) * 1000 +
1100 (stop_t.tv_usec - start_t.tv_usec) / 1000),
1101 (long) (stop_t.tv_usec - start_t.tv_usec) % 1000,
1103 prepare_string ? prepare_string : "")));
1106 if (save_log_statement_stats)
1107 ShowUsage("QUERY STATISTICS");
1109 if (prepare_string != NULL)
1110 pfree(prepare_string);
1112 debug_query_string = NULL;
1116 * exec_parse_message
1118 * Execute a "Parse" protocol message.
1121 exec_parse_message(const char *query_string, /* string to execute */
1122 const char *stmt_name, /* name for prepared stmt */
1123 Oid *paramTypes, /* parameter types */
1124 int numParams) /* number of parameters */
1126 MemoryContext oldcontext;
1127 List *parsetree_list;
1128 const char *commandTag;
1129 List *querytree_list,
1133 bool save_log_statement_stats = log_statement_stats;
1136 * Report query to various monitoring facilities.
1138 debug_query_string = query_string;
1140 pgstat_report_activity(query_string);
1142 set_ps_display("PARSE");
1144 if (save_log_statement_stats)
1147 if (log_statement == LOGSTMT_ALL)
1149 (errmsg("statement: PREPARE %s AS %s",
1150 (*stmt_name != '\0') ? stmt_name : "<unnamed>",
1154 * Start up a transaction command so we can run parse analysis etc. (Note
1155 * that this will normally change current memory context.) Nothing happens
1156 * if we are already in one.
1158 start_xact_command();
1161 * Switch to appropriate context for constructing parsetrees.
1163 * We have two strategies depending on whether the prepared statement is
1164 * named or not. For a named prepared statement, we do parsing in
1165 * MessageContext and copy the finished trees into the prepared
1166 * statement's private context; then the reset of MessageContext releases
1167 * temporary space used by parsing and planning. For an unnamed prepared
1168 * statement, we assume the statement isn't going to hang around long, so
1169 * getting rid of temp space quickly is probably not worth the costs of
1170 * copying parse/plan trees. So in this case, we set up a special context
1171 * for the unnamed statement, and do all the parsing/planning therein.
1173 is_named = (stmt_name[0] != '\0');
1176 /* Named prepared statement --- parse in MessageContext */
1177 oldcontext = MemoryContextSwitchTo(MessageContext);
1181 /* Unnamed prepared statement --- release any prior unnamed stmt */
1182 unnamed_stmt_pstmt = NULL;
1183 if (unnamed_stmt_context)
1185 DropDependentPortals(unnamed_stmt_context);
1186 MemoryContextDelete(unnamed_stmt_context);
1188 unnamed_stmt_context = NULL;
1189 /* create context for parsing/planning */
1190 unnamed_stmt_context =
1191 AllocSetContextCreate(TopMemoryContext,
1192 "unnamed prepared statement",
1193 ALLOCSET_DEFAULT_MINSIZE,
1194 ALLOCSET_DEFAULT_INITSIZE,
1195 ALLOCSET_DEFAULT_MAXSIZE);
1196 oldcontext = MemoryContextSwitchTo(unnamed_stmt_context);
1199 QueryContext = CurrentMemoryContext;
1202 * Do basic parsing of the query or queries (this should be safe even if
1203 * we are in aborted transaction state!)
1205 parsetree_list = pg_parse_query(query_string);
1208 * We only allow a single user statement in a prepared statement. This is
1209 * mainly to keep the protocol simple --- otherwise we'd need to worry
1210 * about multiple result tupdescs and things like that.
1212 if (list_length(parsetree_list) > 1)
1214 (errcode(ERRCODE_SYNTAX_ERROR),
1215 errmsg("cannot insert multiple commands into a prepared statement")));
1217 if (parsetree_list != NIL)
1219 Node *parsetree = (Node *) linitial(parsetree_list);
1223 * Get the command name for possible use in status display.
1225 commandTag = CreateCommandTag(parsetree);
1228 * If we are in an aborted transaction, reject all commands except
1229 * COMMIT/ROLLBACK. It is important that this test occur before we
1230 * try to do parse analysis, rewrite, or planning, since all those
1231 * phases try to do database accesses, which may fail in abort state.
1232 * (It might be safe to allow some additional utility commands in this
1233 * state, but not many...)
1235 if (IsAbortedTransactionBlockState() &&
1236 !IsTransactionExitStmt(parsetree))
1238 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1239 errmsg("current transaction is aborted, "
1240 "commands ignored until end of transaction block")));
1243 * OK to analyze, rewrite, and plan this query. Note that the
1244 * originally specified parameter set is not required to be complete,
1245 * so we have to use parse_analyze_varparams().
1247 if (log_parser_stats)
1250 querytree_list = parse_analyze_varparams(parsetree,
1255 * Check all parameter types got determined, and convert array
1256 * representation to a list for storage.
1259 for (i = 0; i < numParams; i++)
1261 Oid ptype = paramTypes[i];
1263 if (ptype == InvalidOid || ptype == UNKNOWNOID)
1265 (errcode(ERRCODE_INDETERMINATE_DATATYPE),
1266 errmsg("could not determine data type of parameter $%d",
1268 param_list = lappend_oid(param_list, ptype);
1271 if (log_parser_stats)
1272 ShowUsage("PARSE ANALYSIS STATISTICS");
1274 querytree_list = pg_rewrite_queries(querytree_list);
1277 * If this is the unnamed statement and it has parameters, defer query
1278 * planning until Bind. Otherwise do it now.
1280 if (!is_named && numParams > 0)
1281 plantree_list = NIL;
1283 plantree_list = pg_plan_queries(querytree_list, NULL, true);
1287 /* Empty input string. This is legal. */
1289 querytree_list = NIL;
1290 plantree_list = NIL;
1294 /* If we got a cancel signal in analysis or planning, quit */
1295 CHECK_FOR_INTERRUPTS();
1298 * Store the query as a prepared statement. See above comments.
1302 StorePreparedStatement(stmt_name,
1311 PreparedStatement *pstmt;
1313 pstmt = (PreparedStatement *) palloc0(sizeof(PreparedStatement));
1314 /* query_string needs to be copied into unnamed_stmt_context */
1315 pstmt->query_string = pstrdup(query_string);
1316 /* the rest is there already */
1317 pstmt->commandTag = commandTag;
1318 pstmt->query_list = querytree_list;
1319 pstmt->plan_list = plantree_list;
1320 pstmt->argtype_list = param_list;
1321 pstmt->context = unnamed_stmt_context;
1322 /* Now the unnamed statement is complete and valid */
1323 unnamed_stmt_pstmt = pstmt;
1326 MemoryContextSwitchTo(oldcontext);
1328 QueryContext = NULL;
1331 * We do NOT close the open transaction command here; that only happens
1332 * when the client sends Sync. Instead, do CommandCounterIncrement just
1333 * in case something happened during parse/plan.
1335 CommandCounterIncrement();
1338 * Send ParseComplete.
1340 if (whereToSendOutput == DestRemote)
1341 pq_putemptymessage('1');
1343 if (save_log_statement_stats)
1344 ShowUsage("PARSE MESSAGE STATISTICS");
1346 debug_query_string = NULL;
1352 * Process a "Bind" message to create a portal from a prepared statement
1355 exec_bind_message(StringInfo input_message)
1357 const char *portal_name;
1358 const char *stmt_name;
1360 int16 *pformats = NULL;
1363 int16 *rformats = NULL;
1365 PreparedStatement *pstmt;
1367 ParamListInfo params;
1369 pgstat_report_activity("<BIND>");
1371 set_ps_display("BIND");
1374 * Start up a transaction command so we can call functions etc. (Note that
1375 * this will normally change current memory context.) Nothing happens if
1376 * we are already in one.
1378 start_xact_command();
1380 /* Switch back to message context */
1381 MemoryContextSwitchTo(MessageContext);
1383 /* Get the fixed part of the message */
1384 portal_name = pq_getmsgstring(input_message);
1385 stmt_name = pq_getmsgstring(input_message);
1387 /* Get the parameter format codes */
1388 numPFormats = pq_getmsgint(input_message, 2);
1389 if (numPFormats > 0)
1391 pformats = (int16 *) palloc(numPFormats * sizeof(int16));
1392 for (i = 0; i < numPFormats; i++)
1393 pformats[i] = pq_getmsgint(input_message, 2);
1396 /* Get the parameter value count */
1397 numParams = pq_getmsgint(input_message, 2);
1399 if (numPFormats > 1 && numPFormats != numParams)
1401 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1402 errmsg("bind message has %d parameter formats but %d parameters",
1403 numPFormats, numParams)));
1405 /* Find prepared statement */
1406 if (stmt_name[0] != '\0')
1407 pstmt = FetchPreparedStatement(stmt_name, true);
1410 /* special-case the unnamed statement */
1411 pstmt = unnamed_stmt_pstmt;
1414 (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
1415 errmsg("unnamed prepared statement does not exist")));
1418 if (numParams != list_length(pstmt->argtype_list))
1420 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1421 errmsg("bind message supplies %d parameters, but prepared statement \"%s\" requires %d",
1422 numParams, stmt_name, list_length(pstmt->argtype_list))));
1425 * If we are in aborted transaction state, the only portals we can
1426 * actually run are those containing COMMIT or ROLLBACK commands.
1427 * We disallow binding anything else to avoid problems with infrastructure
1428 * that expects to run inside a valid transaction. We also disallow
1429 * binding any parameters, since we can't risk calling user-defined
1432 if (IsAbortedTransactionBlockState() &&
1433 (!IsTransactionExitStmtList(pstmt->query_list) ||
1436 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1437 errmsg("current transaction is aborted, "
1438 "commands ignored until end of transaction block")));
1441 * Create the portal. Allow silent replacement of an existing portal only
1442 * if the unnamed portal is specified.
1444 if (portal_name[0] == '\0')
1445 portal = CreatePortal(portal_name, true, true);
1447 portal = CreatePortal(portal_name, false, false);
1449 /* We need to output the parameter values someday */
1450 if (log_statement == LOGSTMT_ALL)
1452 (errmsg("statement: <BIND> %s", portal_name)));
1455 * Fetch parameters, if any, and store in the portal's memory context.
1460 MemoryContext oldContext;
1462 oldContext = MemoryContextSwitchTo(PortalGetHeapMemory(portal));
1464 params = (ParamListInfo)
1465 palloc0((numParams + 1) * sizeof(ParamListInfoData));
1468 foreach(l, pstmt->argtype_list)
1470 Oid ptype = lfirst_oid(l);
1474 plength = pq_getmsgint(input_message, 4);
1475 isNull = (plength == -1);
1479 const char *pvalue = pq_getmsgbytes(input_message, plength);
1481 StringInfoData pbuf;
1484 if (numPFormats > 1)
1485 pformat = pformats[i];
1486 else if (numPFormats > 0)
1487 pformat = pformats[0];
1489 pformat = 0; /* default = text */
1492 * Rather than copying data around, we just set up a phony
1493 * StringInfo pointing to the correct portion of the
1494 * message buffer. We assume we can scribble on the
1495 * message buffer so as to maintain the convention that
1496 * StringInfos have a trailing null. This is grotty but
1497 * is a big win when dealing with very large parameter
1500 pbuf.data = (char *) pvalue;
1501 pbuf.maxlen = plength + 1;
1505 csave = pbuf.data[plength];
1506 pbuf.data[plength] = '\0';
1514 getTypeInputInfo(ptype, &typinput, &typioparam);
1517 * We have to do encoding conversion before calling
1518 * the typinput routine.
1520 pstring = pg_client_to_server(pbuf.data, plength);
1522 OidFunctionCall3(typinput,
1523 CStringGetDatum(pstring),
1524 ObjectIdGetDatum(typioparam),
1526 /* Free result of encoding conversion, if any */
1527 if (pstring != pbuf.data)
1530 else if (pformat == 1)
1536 * Call the parameter type's binary input converter
1538 getTypeBinaryInputInfo(ptype, &typreceive, &typioparam);
1541 OidFunctionCall3(typreceive,
1542 PointerGetDatum(&pbuf),
1543 ObjectIdGetDatum(typioparam),
1546 /* Trouble if it didn't eat the whole buffer */
1547 if (pbuf.cursor != pbuf.len)
1549 (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
1550 errmsg("incorrect binary data format in bind parameter %d",
1556 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1557 errmsg("unsupported format code: %d",
1561 /* Restore message buffer contents */
1562 pbuf.data[plength] = csave;
1565 params[i].kind = PARAM_NUM;
1566 params[i].id = i + 1;
1567 params[i].ptype = ptype;
1568 params[i].isnull = isNull;
1573 params[i].kind = PARAM_INVALID;
1575 MemoryContextSwitchTo(oldContext);
1580 /* Get the result format codes */
1581 numRFormats = pq_getmsgint(input_message, 2);
1582 if (numRFormats > 0)
1584 rformats = (int16 *) palloc(numRFormats * sizeof(int16));
1585 for (i = 0; i < numRFormats; i++)
1586 rformats[i] = pq_getmsgint(input_message, 2);
1589 pq_getmsgend(input_message);
1592 * If we didn't plan the query before, do it now. This allows the planner
1593 * to make use of the concrete parameter values we now have.
1595 * This happens only for unnamed statements, and so switching into the
1596 * statement context for planning is correct (see notes in
1597 * exec_parse_message).
1599 if (pstmt->plan_list == NIL && pstmt->query_list != NIL)
1601 MemoryContext oldContext = MemoryContextSwitchTo(pstmt->context);
1603 pstmt->plan_list = pg_plan_queries(pstmt->query_list, params, true);
1604 MemoryContextSwitchTo(oldContext);
1608 * Define portal and start execution.
1610 PortalDefineQuery(portal,
1611 pstmt->query_string,
1617 PortalStart(portal, params, InvalidSnapshot);
1620 * Apply the result format requests to the portal.
1622 PortalSetResultFormat(portal, numRFormats, rformats);
1625 * Send BindComplete.
1627 if (whereToSendOutput == DestRemote)
1628 pq_putemptymessage('2');
1632 * exec_execute_message
1634 * Process an "Execute" message for a portal
1637 exec_execute_message(const char *portal_name, long max_rows)
1640 DestReceiver *receiver;
1643 char completionTag[COMPLETION_TAG_BUFSIZE];
1644 struct timeval start_t,
1646 bool save_log_duration = log_duration;
1647 int save_log_min_duration_statement = log_min_duration_statement;
1648 bool save_log_statement_stats = log_statement_stats;
1649 bool execute_is_fetch = false;
1651 /* Adjust destination to tell printtup.c what to do */
1652 dest = whereToSendOutput;
1653 if (dest == DestRemote)
1654 dest = DestRemoteExecute;
1656 portal = GetPortalByName(portal_name);
1657 if (!PortalIsValid(portal))
1659 (errcode(ERRCODE_UNDEFINED_CURSOR),
1660 errmsg("portal \"%s\" does not exist", portal_name)));
1663 * If we re-issue an Execute protocol request against an existing portal,
1664 * then we are only fetching more rows rather than completely re-executing
1665 * the query from the start. atStart is never reset for a v3 portal, so we
1666 * are safe to use this check.
1668 if (!portal->atStart)
1669 execute_is_fetch = true;
1672 * If the original query was a null string, just return
1673 * EmptyQueryResponse.
1675 if (portal->commandTag == NULL)
1677 Assert(portal->parseTrees == NIL);
1682 /* Should we display the portal names here? */
1683 if (execute_is_fetch)
1685 debug_query_string = "fetch message";
1686 pgstat_report_activity("<FETCH>");
1688 else if (portal->sourceText)
1690 debug_query_string = portal->sourceText;
1691 pgstat_report_activity(portal->sourceText);
1695 debug_query_string = "execute message";
1696 pgstat_report_activity("<EXECUTE>");
1699 set_ps_display(portal->commandTag);
1702 * We use save_log_* so "SET log_duration = true" and "SET
1703 * log_min_duration_statement = true" don't report incorrect time because
1704 * gettimeofday() wasn't called. Similarly, log_statement_stats has to be
1707 if (save_log_duration || save_log_min_duration_statement != -1)
1708 gettimeofday(&start_t, NULL);
1710 if (save_log_statement_stats)
1713 if (log_statement == LOGSTMT_ALL)
1714 /* We have the portal, so output the source query. */
1716 (errmsg("statement: %sEXECUTE %s [PREPARE: %s]",
1717 (execute_is_fetch) ? "FETCH from " : "",
1718 (*portal_name != '\0') ? portal_name : "<unnamed>",
1719 portal->sourceText ? portal->sourceText : "")));
1721 BeginCommand(portal->commandTag, dest);
1724 * Create dest receiver in MessageContext (we don't want it in transaction
1725 * context, because that may get deleted if portal contains VACUUM).
1727 receiver = CreateDestReceiver(dest, portal);
1730 * Ensure we are in a transaction command (this should normally be the
1731 * case already due to prior BIND).
1733 start_xact_command();
1736 * If we are in aborted transaction state, the only portals we can
1737 * actually run are those containing COMMIT or ROLLBACK commands.
1739 if (IsAbortedTransactionBlockState() &&
1740 !IsTransactionExitStmtList(portal->parseTrees))
1742 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1743 errmsg("current transaction is aborted, "
1744 "commands ignored until end of transaction block")));
1746 /* Check for cancel signal before we start execution */
1747 CHECK_FOR_INTERRUPTS();
1750 * Okay to run the portal.
1753 max_rows = FETCH_ALL;
1755 completed = PortalRun(portal,
1761 (*receiver->rDestroy) (receiver);
1765 if (IsTransactionStmtList(portal->parseTrees))
1768 * If this was a transaction control statement, commit it. We
1769 * will start a new xact command for the next command (if any).
1771 finish_xact_command();
1776 * We need a CommandCounterIncrement after every query, except
1777 * those that start or end a transaction block.
1779 CommandCounterIncrement();
1782 /* Send appropriate CommandComplete to client */
1783 EndCommand(completionTag, dest);
1787 /* Portal run not complete, so send PortalSuspended */
1788 if (whereToSendOutput == DestRemote)
1789 pq_putemptymessage('s');
1793 * Combine processing here as we need to calculate the query duration in
1796 if (save_log_duration || save_log_min_duration_statement != -1)
1800 gettimeofday(&stop_t, NULL);
1801 if (stop_t.tv_usec < start_t.tv_usec)
1804 stop_t.tv_usec += 1000000;
1806 usecs = (long) (stop_t.tv_sec - start_t.tv_sec) * 1000000 +
1807 (long) (stop_t.tv_usec - start_t.tv_usec);
1809 /* Only print duration if we previously printed the statement. */
1810 if (log_statement == LOGSTMT_ALL && save_log_duration)
1812 (errmsg("duration: %ld.%03ld ms",
1813 (long) ((stop_t.tv_sec - start_t.tv_sec) * 1000 +
1814 (stop_t.tv_usec - start_t.tv_usec) / 1000),
1815 (long) (stop_t.tv_usec - start_t.tv_usec) % 1000)));
1818 * Output a duration_statement to the log if the query has exceeded
1819 * the min duration, or if we are to print all durations.
1821 if (save_log_min_duration_statement == 0 ||
1822 (save_log_min_duration_statement > 0 &&
1823 usecs >= save_log_min_duration_statement * 1000))
1825 (errmsg("duration: %ld.%03ld ms statement: %sEXECUTE %s [PREPARE: %s]",
1826 (long) ((stop_t.tv_sec - start_t.tv_sec) * 1000 +
1827 (stop_t.tv_usec - start_t.tv_usec) / 1000),
1828 (long) (stop_t.tv_usec - start_t.tv_usec) % 1000,
1829 (execute_is_fetch) ? "FETCH from " : "",
1830 (*portal_name != '\0') ? portal_name : "<unnamed>",
1831 portal->sourceText ? portal->sourceText : "")));
1834 if (save_log_statement_stats)
1835 ShowUsage("QUERY STATISTICS");
1837 debug_query_string = NULL;
1841 * exec_describe_statement_message
1843 * Process a "Describe" message for a prepared statement
1846 exec_describe_statement_message(const char *stmt_name)
1848 PreparedStatement *pstmt;
1853 /* Find prepared statement */
1854 if (stmt_name[0] != '\0')
1855 pstmt = FetchPreparedStatement(stmt_name, true);
1858 /* special-case the unnamed statement */
1859 pstmt = unnamed_stmt_pstmt;
1862 (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
1863 errmsg("unnamed prepared statement does not exist")));
1866 if (whereToSendOutput != DestRemote)
1867 return; /* can't actually do anything... */
1870 * First describe the parameters...
1872 pq_beginmessage(&buf, 't'); /* parameter description message type */
1873 pq_sendint(&buf, list_length(pstmt->argtype_list), 2);
1875 foreach(l, pstmt->argtype_list)
1877 Oid ptype = lfirst_oid(l);
1879 pq_sendint(&buf, (int) ptype, 4);
1881 pq_endmessage(&buf);
1884 * Next send RowDescription or NoData to describe the result...
1886 tupdesc = FetchPreparedStatementResultDesc(pstmt);
1888 SendRowDescriptionMessage(tupdesc,
1889 FetchPreparedStatementTargetList(pstmt),
1892 pq_putemptymessage('n'); /* NoData */
1897 * exec_describe_portal_message
1899 * Process a "Describe" message for a portal
1902 exec_describe_portal_message(const char *portal_name)
1906 portal = GetPortalByName(portal_name);
1907 if (!PortalIsValid(portal))
1909 (errcode(ERRCODE_UNDEFINED_CURSOR),
1910 errmsg("portal \"%s\" does not exist", portal_name)));
1912 if (whereToSendOutput != DestRemote)
1913 return; /* can't actually do anything... */
1915 if (portal->tupDesc)
1916 SendRowDescriptionMessage(portal->tupDesc,
1917 FetchPortalTargetList(portal),
1920 pq_putemptymessage('n'); /* NoData */
1925 * Convenience routines for starting/committing a single command.
1928 start_xact_command(void)
1933 (errmsg_internal("StartTransactionCommand")));
1934 StartTransactionCommand();
1936 /* Set statement timeout running, if any */
1937 if (StatementTimeout > 0)
1938 enable_sig_alarm(StatementTimeout, true);
1940 cancel_from_timeout = false;
1942 xact_started = true;
1947 finish_xact_command(void)
1951 /* Cancel any active statement timeout before committing */
1952 disable_sig_alarm(true);
1954 /* Now commit the command */
1956 (errmsg_internal("CommitTransactionCommand")));
1958 CommitTransactionCommand();
1960 #ifdef MEMORY_CONTEXT_CHECKING
1961 /* Check all memory contexts that weren't freed during commit */
1962 /* (those that were, were checked before being deleted) */
1963 MemoryContextCheck(TopMemoryContext);
1966 #ifdef SHOW_MEMORY_STATS
1967 /* Print mem stats after each commit for leak tracking */
1969 MemoryContextStats(TopMemoryContext);
1972 xact_started = false;
1978 * Convenience routines for checking whether a statement is one of the
1979 * ones that we allow in transaction-aborted state.
1983 IsTransactionExitStmt(Node *parsetree)
1985 if (parsetree && IsA(parsetree, TransactionStmt))
1987 TransactionStmt *stmt = (TransactionStmt *) parsetree;
1989 if (stmt->kind == TRANS_STMT_COMMIT ||
1990 stmt->kind == TRANS_STMT_PREPARE ||
1991 stmt->kind == TRANS_STMT_ROLLBACK ||
1992 stmt->kind == TRANS_STMT_ROLLBACK_TO)
1999 IsTransactionExitStmtList(List *parseTrees)
2001 if (list_length(parseTrees) == 1)
2003 Query *query = (Query *) linitial(parseTrees);
2005 if (query->commandType == CMD_UTILITY &&
2006 IsTransactionExitStmt(query->utilityStmt))
2013 IsTransactionStmtList(List *parseTrees)
2015 if (list_length(parseTrees) == 1)
2017 Query *query = (Query *) linitial(parseTrees);
2019 if (query->commandType == CMD_UTILITY &&
2020 query->utilityStmt && IsA(query->utilityStmt, TransactionStmt))
2027 /* --------------------------------
2028 * signal handler routines used in PostgresMain()
2029 * --------------------------------
2033 * quickdie() occurs when signalled SIGQUIT by the postmaster.
2035 * Some backend has bought the farm,
2036 * so we need to stop what we're doing and exit.
2039 quickdie(SIGNAL_ARGS)
2041 PG_SETMASK(&BlockSig);
2044 * Ideally this should be ereport(FATAL), but then we'd not get control
2048 (errcode(ERRCODE_CRASH_SHUTDOWN),
2049 errmsg("terminating connection because of crash of another server process"),
2050 errdetail("The postmaster has commanded this server process to roll back"
2051 " the current transaction and exit, because another"
2052 " server process exited abnormally and possibly corrupted"
2054 errhint("In a moment you should be able to reconnect to the"
2055 " database and repeat your command.")));
2058 * DO NOT proc_exit() -- we're here because shared memory may be
2059 * corrupted, so we don't want to try to clean up our transaction. Just
2060 * nail the windows shut and get out of town.
2062 * Note we do exit(1) not exit(0). This is to force the postmaster into a
2063 * system reset cycle if some idiot DBA sends a manual SIGQUIT to a random
2064 * backend. This is necessary precisely because we don't clean up our
2065 * shared memory state.
2071 * Shutdown signal from postmaster: abort transaction and exit
2072 * at soonest convenient time
2077 int save_errno = errno;
2079 /* Don't joggle the elbow of proc_exit */
2080 if (!proc_exit_inprogress)
2082 InterruptPending = true;
2083 ProcDiePending = true;
2086 * If it's safe to interrupt, and we're waiting for input or a lock,
2087 * service the interrupt immediately
2089 if (ImmediateInterruptOK && InterruptHoldoffCount == 0 &&
2090 CritSectionCount == 0)
2092 /* bump holdoff count to make ProcessInterrupts() a no-op */
2093 /* until we are done getting ready for it */
2094 InterruptHoldoffCount++;
2095 DisableNotifyInterrupt();
2096 DisableCatchupInterrupt();
2097 /* Make sure CheckDeadLock won't run while shutting down... */
2099 InterruptHoldoffCount--;
2100 ProcessInterrupts();
2108 * Timeout or shutdown signal from postmaster during client authentication.
2111 * XXX: possible future improvement: try to send a message indicating
2112 * why we are disconnecting. Problem is to be sure we don't block while
2113 * doing so, nor mess up the authentication message exchange.
2116 authdie(SIGNAL_ARGS)
2122 * Query-cancel signal from postmaster: abort current transaction
2123 * at soonest convenient time
2126 StatementCancelHandler(SIGNAL_ARGS)
2128 int save_errno = errno;
2131 * Don't joggle the elbow of proc_exit
2133 if (!proc_exit_inprogress)
2135 InterruptPending = true;
2136 QueryCancelPending = true;
2139 * If it's safe to interrupt, and we're waiting for a lock, service
2140 * the interrupt immediately. No point in interrupting if we're
2141 * waiting for input, however.
2143 if (ImmediateInterruptOK && InterruptHoldoffCount == 0 &&
2144 CritSectionCount == 0)
2146 /* bump holdoff count to make ProcessInterrupts() a no-op */
2147 /* until we are done getting ready for it */
2148 InterruptHoldoffCount++;
2149 if (LockWaitCancel())
2151 DisableNotifyInterrupt();
2152 DisableCatchupInterrupt();
2153 InterruptHoldoffCount--;
2154 ProcessInterrupts();
2157 InterruptHoldoffCount--;
2164 /* signal handler for floating point exception */
2166 FloatExceptionHandler(SIGNAL_ARGS)
2169 (errcode(ERRCODE_FLOATING_POINT_EXCEPTION),
2170 errmsg("floating-point exception"),
2171 errdetail("An invalid floating-point operation was signaled. "
2172 "This probably means an out-of-range result or an "
2173 "invalid operation, such as division by zero.")));
2176 /* SIGHUP: set flag to re-read config file at next convenient time */
2178 SigHupHandler(SIGNAL_ARGS)
2185 * ProcessInterrupts: out-of-line portion of CHECK_FOR_INTERRUPTS() macro
2187 * If an interrupt condition is pending, and it's safe to service it,
2188 * then clear the flag and accept the interrupt. Called only when
2189 * InterruptPending is true.
2192 ProcessInterrupts(void)
2194 /* OK to accept interrupt now? */
2195 if (InterruptHoldoffCount != 0 || CritSectionCount != 0)
2197 InterruptPending = false;
2200 ProcDiePending = false;
2201 QueryCancelPending = false; /* ProcDie trumps QueryCancel */
2202 ImmediateInterruptOK = false; /* not idle anymore */
2203 DisableNotifyInterrupt();
2204 DisableCatchupInterrupt();
2206 (errcode(ERRCODE_ADMIN_SHUTDOWN),
2207 errmsg("terminating connection due to administrator command")));
2209 if (QueryCancelPending)
2211 QueryCancelPending = false;
2212 ImmediateInterruptOK = false; /* not idle anymore */
2213 DisableNotifyInterrupt();
2214 DisableCatchupInterrupt();
2215 if (cancel_from_timeout)
2217 (errcode(ERRCODE_QUERY_CANCELED),
2218 errmsg("canceling statement due to statement timeout")));
2221 (errcode(ERRCODE_QUERY_CANCELED),
2222 errmsg("canceling statement due to user request")));
2224 /* If we get here, do nothing (probably, QueryCancelPending was reset) */
2229 * check_stack_depth: check for excessively deep recursion
2231 * This should be called someplace in any recursive routine that might possibly
2232 * recurse deep enough to overflow the stack. Most Unixen treat stack
2233 * overflow as an unrecoverable SIGSEGV, so we want to error out ourselves
2234 * before hitting the hardware limit. Unfortunately we have no direct way
2235 * to detect the hardware limit, so we have to rely on the admin to set a
2236 * GUC variable for it ...
2239 check_stack_depth(void)
2245 * Compute distance from PostgresMain's local variables to my own
2247 * Note: in theory stack_depth should be ptrdiff_t or some such, but since
2248 * the whole point of this code is to bound the value to something much
2249 * less than integer-sized, int should work fine.
2251 stack_depth = (int) (stack_base_ptr - &stack_top_loc);
2254 * Take abs value, since stacks grow up on some machines, down on others
2256 if (stack_depth < 0)
2257 stack_depth = -stack_depth;
2262 * The test on stack_base_ptr prevents us from erroring out if called during
2263 * process setup or in a non-backend process. Logically it should be done
2264 * first, but putting it here avoids wasting cycles during normal cases.
2266 if (stack_depth > max_stack_depth_bytes &&
2267 stack_base_ptr != NULL)
2270 (errcode(ERRCODE_STATEMENT_TOO_COMPLEX),
2271 errmsg("stack depth limit exceeded"),
2272 errhint("Increase the configuration parameter \"max_stack_depth\".")));
2276 /* GUC assign hook to update max_stack_depth_bytes from max_stack_depth */
2278 assign_max_stack_depth(int newval, bool doit, GucSource source)
2280 /* Range check was already handled by guc.c */
2282 max_stack_depth_bytes = newval * 1024;
2288 usage(const char *progname)
2290 printf(_("%s is the PostgreSQL stand-alone backend. It is not\nintended to be used by normal users.\n\n"), progname);
2292 printf(_("Usage:\n %s [OPTION]... [DBNAME]\n\n"), progname);
2293 printf(_("Options:\n"));
2294 #ifdef USE_ASSERT_CHECKING
2295 printf(_(" -A 1|0 enable/disable run-time assert checking\n"));
2297 printf(_(" -B NBUFFERS number of shared buffers\n"));
2298 printf(_(" -c NAME=VALUE set run-time parameter\n"));
2299 printf(_(" -d 0-5 debugging level (0 is off)\n"));
2300 printf(_(" -D DATADIR database directory\n"));
2301 printf(_(" -e use European date input format (DMY)\n"));
2302 printf(_(" -E echo query before execution\n"));
2303 printf(_(" -F turn fsync off\n"));
2304 printf(_(" -N do not use newline as interactive query delimiter\n"));
2305 printf(_(" -o FILENAME send stdout and stderr to given file\n"));
2306 printf(_(" -P disable system indexes\n"));
2307 printf(_(" -s show statistics after each query\n"));
2308 printf(_(" -S WORK-MEM set amount of memory for sorts (in kB)\n"));
2309 printf(_(" --describe-config describe configuration parameters, then exit\n"));
2310 printf(_(" --help show this help, then exit\n"));
2311 printf(_(" --version output version information, then exit\n"));
2312 printf(_("\nDeveloper options:\n"));
2313 printf(_(" -f s|i|n|m|h forbid use of some plan types\n"));
2314 printf(_(" -i do not execute queries\n"));
2315 printf(_(" -O allow system table structure changes\n"));
2316 printf(_(" -t pa|pl|ex show timings after each query\n"));
2317 printf(_(" -W NUM wait NUM seconds to allow attach from a debugger\n"));
2318 printf(_("\nReport bugs to <pgsql-bugs@postgresql.org>.\n"));
2323 * set_debug_options --- apply "-d N" command line option
2325 * -d is not quite the same as setting log_min_messages because it enables
2326 * other output options.
2329 set_debug_options(int debug_flag, GucContext context, GucSource source)
2335 sprintf(debugstr, "debug%d", debug_flag);
2336 SetConfigOption("log_min_messages", debugstr, context, source);
2339 SetConfigOption("log_min_messages", "notice", context, source);
2341 if (debug_flag >= 1 && context == PGC_POSTMASTER)
2343 SetConfigOption("log_connections", "true", context, source);
2344 SetConfigOption("log_disconnections", "true", context, source);
2346 if (debug_flag >= 2)
2347 SetConfigOption("log_statement", "all", context, source);
2348 if (debug_flag >= 3)
2349 SetConfigOption("debug_print_parse", "true", context, source);
2350 if (debug_flag >= 4)
2351 SetConfigOption("debug_print_plan", "true", context, source);
2352 if (debug_flag >= 5)
2353 SetConfigOption("debug_print_rewritten", "true", context, source);
2357 /* ----------------------------------------------------------------
2359 * postgres main loop -- all backends, interactive or otherwise start here
2361 * argc/argv are the command line arguments to be used. (When being forked
2362 * by the postmaster, these are not the original argv array of the process.)
2363 * username is the (possibly authenticated) PostgreSQL user name to be used
2365 * ----------------------------------------------------------------
2368 PostgresMain(int argc, char *argv[], const char *username)
2371 const char *dbname = NULL;
2372 char *userDoption = NULL;
2375 int debug_flag = -1; /* -1 means not given */
2376 List *guc_names = NIL; /* for SUSET options */
2377 List *guc_values = NIL;
2379 GucSource gucsource;
2384 StringInfoData input_message;
2385 sigjmp_buf local_sigjmp_buf;
2386 volatile bool send_rfq = true;
2388 #define PendingConfigOption(name,val) \
2389 (guc_names = lappend(guc_names, pstrdup(name)), \
2390 guc_values = lappend(guc_values, pstrdup(val)))
2393 * Catch standard options before doing much else. This even works on
2394 * systems without getopt_long.
2396 if (!IsUnderPostmaster && argc > 1)
2398 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
2403 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
2405 puts(PG_VERSIONSTR);
2411 * initialize globals (already done if under postmaster, but not if
2412 * standalone; cheap enough to do over)
2414 MyProcPid = getpid();
2417 * Fire up essential subsystems: error and memory management
2419 * If we are running under the postmaster, this is done already.
2421 if (!IsUnderPostmaster)
2422 MemoryContextInit();
2424 set_ps_display("startup");
2426 SetProcessingMode(InitProcessing);
2428 /* Set up reference point for stack depth checking */
2429 stack_base_ptr = &stack_base;
2431 /* Compute paths, if we didn't inherit them from postmaster */
2432 if (my_exec_path[0] == '\0')
2434 if (find_my_exec(argv[0], my_exec_path) < 0)
2435 elog(FATAL, "%s: could not locate my own executable path",
2439 if (pkglib_path[0] == '\0')
2440 get_pkglib_path(my_exec_path, pkglib_path);
2443 * Set default values for command-line options.
2447 if (!IsUnderPostmaster)
2448 InitializeGUCOptions();
2451 * parse command line arguments
2453 * There are now two styles of command line layout for the backend:
2455 * For interactive use (not started from postmaster) the format is
2456 * postgres [switches] [databasename]
2457 * If the databasename is omitted it is taken to be the user name.
2459 * When started from the postmaster, the format is
2460 * postgres [secure switches] -p databasename [insecure switches]
2461 * Switches appearing after -p came from the client (via "options"
2462 * field of connection request). For security reasons we restrict
2463 * what these switches can do.
2467 /* all options are allowed until '-p' */
2469 ctx = PGC_POSTMASTER;
2470 gucsource = PGC_S_ARGV; /* initial switches came from command line */
2472 while ((flag = getopt(argc, argv, "A:B:c:D:d:Eef:FiNOPo:p:S:st:v:W:-:")) != -1)
2477 #ifdef USE_ASSERT_CHECKING
2478 SetConfigOption("debug_assertions", optarg, ctx, gucsource);
2481 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2482 errmsg("assert checking is not compiled in")));
2489 * specify the size of buffer pool
2491 SetConfigOption("shared_buffers", optarg, ctx, gucsource);
2494 case 'D': /* PGDATA or config directory */
2496 userDoption = optarg;
2499 case 'd': /* debug level */
2500 debug_flag = atoi(optarg);
2506 * E - echo the query the user entered
2514 * Use European date input format (DMY)
2516 SetConfigOption("datestyle", "euro", ctx, gucsource);
2524 SetConfigOption("fsync", "false", ctx, gucsource);
2530 * f - forbid generation of certain plans
2535 case 's': /* seqscan */
2536 tmp = "enable_seqscan";
2538 case 'i': /* indexscan */
2539 tmp = "enable_indexscan";
2541 case 'b': /* bitmapscan */
2542 tmp = "enable_bitmapscan";
2544 case 't': /* tidscan */
2545 tmp = "enable_tidscan";
2547 case 'n': /* nestloop */
2548 tmp = "enable_nestloop";
2550 case 'm': /* mergejoin */
2551 tmp = "enable_mergejoin";
2553 case 'h': /* hashjoin */
2554 tmp = "enable_hashjoin";
2560 SetConfigOption(tmp, "false", ctx, gucsource);
2566 * N - Don't use newline as a query delimiter
2574 * allow system table structure modifications
2576 if (secure) /* XXX safe to allow from client??? */
2577 allowSystemTableMods = true;
2583 * ignore system indexes
2585 * As of PG 7.4 this is safe to allow from the client, since it
2586 * only disables reading the system indexes, not writing them.
2587 * Worst case consequence is slowness.
2589 IgnoreSystemIndexes(true);
2595 * o - send output (stdout and stderr) to the given file
2598 StrNCpy(OutputFileName, optarg, MAXPGPATH);
2604 * p - special flag passed if backend was forked by a
2609 dbname = strdup(optarg);
2611 secure = false; /* subsequent switches are NOT secure */
2613 gucsource = PGC_S_CLIENT;
2620 * S - amount of sort memory to use in 1k bytes
2622 SetConfigOption("work_mem", optarg, ctx, gucsource);
2628 * s - report usage statistics (timings) after each query
2630 * Since log options are SUSET, we need to postpone unless still
2633 if (ctx == PGC_BACKEND)
2634 PendingConfigOption("log_statement_stats", "true");
2636 SetConfigOption("log_statement_stats", "true",
2642 * tell postgres to report usage statistics (timings) for
2645 * -tpa[rser] = print stats for parser time of each query
2646 * -tpl[anner] = print stats for planner time of each query
2647 * -te[xecutor] = print stats for executor time of each query
2648 * caution: -s can not be used together with -t.
2655 if (optarg[1] == 'a')
2656 tmp = "log_parser_stats";
2657 else if (optarg[1] == 'l')
2658 tmp = "log_planner_stats";
2663 tmp = "log_executor_stats";
2671 if (ctx == PGC_BACKEND)
2672 PendingConfigOption(tmp, "true");
2674 SetConfigOption(tmp, "true", ctx, gucsource);
2680 FrontendProtocol = (ProtocolVersion) atoi(optarg);
2686 * wait N seconds to allow attach from a debugger
2688 pg_usleep(atoi(optarg) * 1000000L);
2697 ParseLongOption(optarg, &name, &value);
2702 (errcode(ERRCODE_SYNTAX_ERROR),
2703 errmsg("--%s requires a value",
2707 (errcode(ERRCODE_SYNTAX_ERROR),
2708 errmsg("-c %s requires a value",
2713 * If a SUSET option, must postpone evaluation, unless we
2714 * are still reading secure switches.
2716 if (ctx == PGC_BACKEND && IsSuperuserConfigOption(name))
2717 PendingConfigOption(name, value);
2719 SetConfigOption(name, value, ctx, gucsource);
2733 * Process any additional GUC variable settings passed in startup packet.
2734 * These are handled exactly like command-line variables.
2736 if (MyProcPort != NULL)
2738 ListCell *gucopts = list_head(MyProcPort->guc_options);
2745 name = lfirst(gucopts);
2746 gucopts = lnext(gucopts);
2748 value = lfirst(gucopts);
2749 gucopts = lnext(gucopts);
2751 if (IsSuperuserConfigOption(name))
2752 PendingConfigOption(name, value);
2754 SetConfigOption(name, value, PGC_BACKEND, PGC_S_CLIENT);
2758 /* Acquire configuration parameters, unless inherited from postmaster */
2759 if (!IsUnderPostmaster)
2761 if (!SelectConfigFiles(userDoption, argv[0]))
2763 /* If timezone is not set, determine what the OS uses */
2764 pg_timezone_initialize();
2768 * Set up signal handlers and masks.
2770 * Note that postmaster blocked all signals before forking child process, so
2771 * there is no race condition whereby we might receive a signal before we
2772 * have set up the handler.
2774 * Also note: it's best not to use any signals that are SIG_IGNored in the
2775 * postmaster. If such a signal arrives before we are able to change the
2776 * handler to non-SIG_IGN, it'll get dropped. Instead, make a dummy
2777 * handler in the postmaster to reserve the signal. (Of course, this isn't
2778 * an issue for signals that are locally generated, such as SIGALRM and
2781 pqsignal(SIGHUP, SigHupHandler); /* set flag to read config file */
2782 pqsignal(SIGINT, StatementCancelHandler); /* cancel current query */
2783 pqsignal(SIGTERM, die); /* cancel current query and exit */
2784 pqsignal(SIGQUIT, quickdie); /* hard crash time */
2785 pqsignal(SIGALRM, handle_sig_alarm); /* timeout conditions */
2788 * Ignore failure to write to frontend. Note: if frontend closes
2789 * connection, we will notice it and exit cleanly when control next
2790 * returns to outer loop. This seems safer than forcing exit in the midst
2791 * of output during who-knows-what operation...
2793 pqsignal(SIGPIPE, SIG_IGN);
2794 pqsignal(SIGUSR1, CatchupInterruptHandler);
2795 pqsignal(SIGUSR2, NotifyInterruptHandler);
2796 pqsignal(SIGFPE, FloatExceptionHandler);
2799 * Reset some signals that are accepted by postmaster but not by backend
2801 pqsignal(SIGCHLD, SIG_DFL); /* system() requires this on some platforms */
2805 /* We allow SIGQUIT (quickdie) at all times */
2806 #ifdef HAVE_SIGPROCMASK
2807 sigdelset(&BlockSig, SIGQUIT);
2809 BlockSig &= ~(sigmask(SIGQUIT));
2812 PG_SETMASK(&BlockSig); /* block everything except SIGQUIT */
2815 if (IsUnderPostmaster)
2817 /* noninteractive case: nothing should be left after switches */
2818 if (errs || argc != optind || dbname == NULL)
2821 (errcode(ERRCODE_SYNTAX_ERROR),
2822 errmsg("invalid command-line arguments for server process"),
2823 errhint("Try \"%s --help\" for more information.", argv[0])));
2830 /* interactive case: database name can be last arg on command line */
2831 if (errs || argc - optind > 1)
2834 (errcode(ERRCODE_SYNTAX_ERROR),
2835 errmsg("%s: invalid command-line arguments",
2837 errhint("Try \"%s --help\" for more information.", argv[0])));
2839 else if (argc - optind == 1)
2840 dbname = argv[optind];
2841 else if ((dbname = username) == NULL)
2844 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2845 errmsg("%s: no database nor user name specified",
2850 * Validate we have been given a reasonable-looking DataDir (if under
2851 * postmaster, assume postmaster did this already).
2854 ValidatePgVersion(DataDir);
2856 /* Change into DataDir (if under postmaster, was done already) */
2860 * Create lockfile for data directory.
2862 CreateDataDirLockFile(false);
2867 * Start up xlog for standalone backend, and register to have it
2868 * closed down at exit.
2871 on_shmem_exit(ShutdownXLOG, 0);
2874 * Read any existing FSM cache file, and register to write one out at
2878 on_shmem_exit(DumpFreeSpaceMap, 0);
2881 * We have to build the flat file for pg_database, but not for the
2882 * user and group tables, since we won't try to do authentication.
2884 BuildFlatFiles(true);
2888 * General initialization.
2890 * NOTE: if you are tempted to add code in this vicinity, consider putting it
2891 * inside InitPostgres() instead. In particular, anything that involves
2892 * database access should be there, not here.
2895 (errmsg_internal("InitPostgres")));
2896 am_superuser = InitPostgres(dbname, username);
2898 SetProcessingMode(NormalProcessing);
2901 * Now that we know if client is a superuser, we can try to apply SUSET
2902 * GUC options that came from the client.
2904 ctx = am_superuser ? PGC_SUSET : PGC_USERSET;
2906 if (debug_flag >= 0)
2907 set_debug_options(debug_flag, ctx, PGC_S_CLIENT);
2909 if (guc_names != NIL)
2914 forboth(namcell, guc_names, valcell, guc_values)
2916 char *name = (char *) lfirst(namcell);
2917 char *value = (char *) lfirst(valcell);
2919 SetConfigOption(name, value, ctx, PGC_S_CLIENT);
2926 * Now all GUC states are fully set up. Report them to client if
2929 BeginReportingGUCOptions();
2932 * Also set up handler to log session end; we have to wait till now to be
2933 * sure Log_disconnections has its final value.
2935 if (IsUnderPostmaster && Log_disconnections)
2936 on_proc_exit(log_disconnections, 0);
2939 * Send this backend's cancellation info to the frontend.
2941 if (whereToSendOutput == DestRemote &&
2942 PG_PROTOCOL_MAJOR(FrontendProtocol) >= 2)
2946 pq_beginmessage(&buf, 'K');
2947 pq_sendint(&buf, (int32) MyProcPid, sizeof(int32));
2948 pq_sendint(&buf, (int32) MyCancelKey, sizeof(int32));
2949 pq_endmessage(&buf);
2950 /* Need not flush since ReadyForQuery will do it. */
2953 /* Welcome banner for standalone case */
2954 if (whereToSendOutput == DestDebug)
2955 printf("\nPostgreSQL stand-alone backend %s\n", PG_VERSION);
2958 * Create the memory context we will use in the main loop.
2960 * MessageContext is reset once per iteration of the main loop, ie, upon
2961 * completion of processing of each command message from the client.
2963 MessageContext = AllocSetContextCreate(TopMemoryContext,
2965 ALLOCSET_DEFAULT_MINSIZE,
2966 ALLOCSET_DEFAULT_INITSIZE,
2967 ALLOCSET_DEFAULT_MAXSIZE);
2970 * Remember stand-alone backend startup time
2972 if (!IsUnderPostmaster)
2973 PgStartTime = GetCurrentTimestamp();
2976 * POSTGRES main processing loop begins here
2978 * If an exception is encountered, processing resumes here so we abort the
2979 * current transaction and start a new one.
2981 * You might wonder why this isn't coded as an infinite loop around a PG_TRY
2982 * construct. The reason is that this is the bottom of the exception
2983 * stack, and so with PG_TRY there would be no exception handler in force
2984 * at all during the CATCH part. By leaving the outermost setjmp always
2985 * active, we have at least some chance of recovering from an error during
2986 * error recovery. (If we get into an infinite loop thereby, it will soon
2987 * be stopped by overflow of elog.c's internal state stack.)
2990 if (sigsetjmp(local_sigjmp_buf, 1) != 0)
2993 * NOTE: if you are tempted to add more code in this if-block,
2994 * consider the high probability that it should be in
2995 * AbortTransaction() instead. The only stuff done directly here
2996 * should be stuff that is guaranteed to apply *only* for outer-level
2997 * error recovery, such as adjusting the FE/BE protocol status.
3000 /* Since not using PG_TRY, must reset error stack by hand */
3001 error_context_stack = NULL;
3003 /* Prevent interrupts while cleaning up */
3007 * Forget any pending QueryCancel request, since we're returning to
3008 * the idle loop anyway, and cancel the statement timer if running.
3010 QueryCancelPending = false;
3011 disable_sig_alarm(true);
3012 QueryCancelPending = false; /* again in case timeout occurred */
3015 * Turn off these interrupts too. This is only needed here and not in
3016 * other exception-catching places since these interrupts are only
3017 * enabled while we wait for client input.
3019 DoingCommandRead = false;
3020 DisableNotifyInterrupt();
3021 DisableCatchupInterrupt();
3023 /* Make sure libpq is in a good state */
3026 /* Report the error to the client and/or server log */
3030 * Make sure debug_query_string gets reset before we possibly clobber
3031 * the storage it points at.
3033 debug_query_string = NULL;
3036 * Abort the current transaction in order to recover.
3038 AbortCurrentTransaction();
3041 * Now return to normal top-level context and clear ErrorContext for
3044 MemoryContextSwitchTo(TopMemoryContext);
3046 QueryContext = NULL;
3049 * If we were handling an extended-query-protocol message, initiate
3050 * skip till next Sync. This also causes us not to issue
3051 * ReadyForQuery (until we get Sync).
3053 if (doing_extended_query_message)
3054 ignore_till_sync = true;
3056 /* We don't have a transaction command open anymore */
3057 xact_started = false;
3059 /* Now we can allow interrupts again */
3060 RESUME_INTERRUPTS();
3063 /* We can now handle ereport(ERROR) */
3064 PG_exception_stack = &local_sigjmp_buf;
3066 PG_SETMASK(&UnBlockSig);
3068 if (!ignore_till_sync)
3069 send_rfq = true; /* initially, or after error */
3072 * Non-error queries loop here.
3078 * At top of loop, reset extended-query-message flag, so that any
3079 * errors encountered in "idle" state don't provoke skip.
3081 doing_extended_query_message = false;
3084 * Release storage left over from prior query cycle, and create a new
3085 * query input buffer in the cleared MessageContext.
3087 MemoryContextSwitchTo(MessageContext);
3088 MemoryContextResetAndDeleteChildren(MessageContext);
3090 initStringInfo(&input_message);
3093 * (1) If we've reached idle state, tell the frontend we're ready for
3096 * Note: this includes fflush()'ing the last of the prior output.
3098 * This is also a good time to send collected statistics to the
3099 * collector, and to update the PS stats display. We avoid doing
3100 * those every time through the message loop because it'd slow down
3101 * processing of batched messages, and because we don't want to report
3102 * uncommitted updates (that confuses autovacuum).
3106 if (IsTransactionOrTransactionBlock())
3108 set_ps_display("idle in transaction");
3109 pgstat_report_activity("<IDLE> in transaction");
3113 pgstat_report_tabstat();
3115 set_ps_display("idle");
3116 pgstat_report_activity("<IDLE>");
3119 ReadyForQuery(whereToSendOutput);
3124 * (2) Allow asynchronous signals to be executed immediately if they
3125 * come in while we are waiting for client input. (This must be
3126 * conditional since we don't want, say, reads on behalf of COPY FROM
3127 * STDIN doing the same thing.)
3129 QueryCancelPending = false; /* forget any earlier CANCEL signal */
3130 DoingCommandRead = true;
3133 * (3) read a command (loop blocks here)
3135 firstchar = ReadCommand(&input_message);
3138 * (4) disable async signal conditions again.
3140 DoingCommandRead = false;
3143 * (5) check for any other interesting events that happened while we
3149 ProcessConfigFile(PGC_SIGHUP);
3153 * (6) process the command. But ignore it if we're skipping till
3156 if (ignore_till_sync && firstchar != EOF)
3161 case 'Q': /* simple query */
3163 const char *query_string;
3165 query_string = pq_getmsgstring(&input_message);
3166 pq_getmsgend(&input_message);
3168 exec_simple_query(query_string);
3174 case 'P': /* parse */
3176 const char *stmt_name;
3177 const char *query_string;
3179 Oid *paramTypes = NULL;
3181 stmt_name = pq_getmsgstring(&input_message);
3182 query_string = pq_getmsgstring(&input_message);
3183 numParams = pq_getmsgint(&input_message, 2);
3188 paramTypes = (Oid *) palloc(numParams * sizeof(Oid));
3189 for (i = 0; i < numParams; i++)
3190 paramTypes[i] = pq_getmsgint(&input_message, 4);
3192 pq_getmsgend(&input_message);
3194 exec_parse_message(query_string, stmt_name,
3195 paramTypes, numParams);
3199 case 'B': /* bind */
3202 * this message is complex enough that it seems best to put
3203 * the field extraction out-of-line
3205 exec_bind_message(&input_message);
3208 case 'E': /* execute */
3210 const char *portal_name;
3213 portal_name = pq_getmsgstring(&input_message);
3214 max_rows = pq_getmsgint(&input_message, 4);
3215 pq_getmsgend(&input_message);
3217 exec_execute_message(portal_name, max_rows);
3221 case 'F': /* fastpath function call */
3222 /* Tell the collector what we're doing */
3223 pgstat_report_activity("<FASTPATH> function call");
3225 /* start an xact for this function invocation */
3226 start_xact_command();
3228 /* switch back to message context */
3229 MemoryContextSwitchTo(MessageContext);
3231 /* set snapshot in case function needs one */
3232 ActiveSnapshot = CopySnapshot(GetTransactionSnapshot());
3234 if (HandleFunctionRequest(&input_message) == EOF)
3236 /* lost frontend connection during F message input */
3239 * Reset whereToSendOutput to prevent ereport from
3240 * attempting to send any more messages to client.
3242 if (whereToSendOutput == DestRemote)
3243 whereToSendOutput = DestNone;
3248 /* commit the function-invocation transaction */
3249 finish_xact_command();
3254 case 'C': /* close */
3257 const char *close_target;
3259 close_type = pq_getmsgbyte(&input_message);
3260 close_target = pq_getmsgstring(&input_message);
3261 pq_getmsgend(&input_message);
3266 if (close_target[0] != '\0')
3267 DropPreparedStatement(close_target, false);
3270 /* special-case the unnamed statement */
3271 unnamed_stmt_pstmt = NULL;
3272 if (unnamed_stmt_context)
3274 DropDependentPortals(unnamed_stmt_context);
3275 MemoryContextDelete(unnamed_stmt_context);
3277 unnamed_stmt_context = NULL;
3284 portal = GetPortalByName(close_target);
3285 if (PortalIsValid(portal))
3286 PortalDrop(portal, false);
3291 (errcode(ERRCODE_PROTOCOL_VIOLATION),
3292 errmsg("invalid CLOSE message subtype %d",
3297 if (whereToSendOutput == DestRemote)
3298 pq_putemptymessage('3'); /* CloseComplete */
3302 case 'D': /* describe */
3305 const char *describe_target;
3307 describe_type = pq_getmsgbyte(&input_message);
3308 describe_target = pq_getmsgstring(&input_message);
3309 pq_getmsgend(&input_message);
3311 switch (describe_type)
3314 exec_describe_statement_message(describe_target);
3317 exec_describe_portal_message(describe_target);
3321 (errcode(ERRCODE_PROTOCOL_VIOLATION),
3322 errmsg("invalid DESCRIBE message subtype %d",
3329 case 'H': /* flush */
3330 pq_getmsgend(&input_message);
3331 if (whereToSendOutput == DestRemote)
3335 case 'S': /* sync */
3336 pq_getmsgend(&input_message);
3337 finish_xact_command();
3342 * 'X' means that the frontend is closing down the socket. EOF
3343 * means unexpected loss of frontend connection. Either way,
3344 * perform normal shutdown.
3350 * Reset whereToSendOutput to prevent ereport from attempting
3351 * to send any more messages to client.
3353 if (whereToSendOutput == DestRemote)
3354 whereToSendOutput = DestNone;
3357 * NOTE: if you are tempted to add more code here, DON'T!
3358 * Whatever you had in mind to do should be set up as an
3359 * on_proc_exit or on_shmem_exit callback, instead. Otherwise
3360 * it will fail to be called during other backend-shutdown
3365 case 'd': /* copy data */
3366 case 'c': /* copy done */
3367 case 'f': /* copy fail */
3370 * Accept but ignore these messages, per protocol spec; we
3371 * probably got here because a COPY failed, and the frontend
3372 * is still sending data.
3378 (errcode(ERRCODE_PROTOCOL_VIOLATION),
3379 errmsg("invalid frontend message type %d",
3382 } /* end of input-reading loop */
3384 /* can't get here because the above loop never exits */
3387 return 1; /* keep compiler quiet */
3390 #ifndef HAVE_GETRUSAGE
3391 #include "rusagestub.h"
3393 #include <sys/resource.h>
3394 #endif /* HAVE_GETRUSAGE */
3396 static struct rusage Save_r;
3397 static struct timeval Save_t;
3402 getrusage(RUSAGE_SELF, &Save_r);
3403 gettimeofday(&Save_t, NULL);
3405 /* ResetTupleCount(); */
3409 ShowUsage(const char *title)
3412 struct timeval user,
3414 struct timeval elapse_t;
3418 getrusage(RUSAGE_SELF, &r);
3419 gettimeofday(&elapse_t, NULL);
3420 memcpy((char *) &user, (char *) &r.ru_utime, sizeof(user));
3421 memcpy((char *) &sys, (char *) &r.ru_stime, sizeof(sys));
3422 if (elapse_t.tv_usec < Save_t.tv_usec)
3425 elapse_t.tv_usec += 1000000;
3427 if (r.ru_utime.tv_usec < Save_r.ru_utime.tv_usec)
3429 r.ru_utime.tv_sec--;
3430 r.ru_utime.tv_usec += 1000000;
3432 if (r.ru_stime.tv_usec < Save_r.ru_stime.tv_usec)
3434 r.ru_stime.tv_sec--;
3435 r.ru_stime.tv_usec += 1000000;
3439 * the only stats we don't show here are for memory usage -- i can't
3440 * figure out how to interpret the relevant fields in the rusage struct,
3441 * and they change names across o/s platforms, anyway. if you can figure
3442 * out what the entries mean, you can somehow extract resident set size,
3443 * shared text size, and unshared data and stack sizes.
3445 initStringInfo(&str);
3447 appendStringInfo(&str, "! system usage stats:\n");
3448 appendStringInfo(&str,
3449 "!\t%ld.%06ld elapsed %ld.%06ld user %ld.%06ld system sec\n",
3450 (long) (elapse_t.tv_sec - Save_t.tv_sec),
3451 (long) (elapse_t.tv_usec - Save_t.tv_usec),
3452 (long) (r.ru_utime.tv_sec - Save_r.ru_utime.tv_sec),
3453 (long) (r.ru_utime.tv_usec - Save_r.ru_utime.tv_usec),
3454 (long) (r.ru_stime.tv_sec - Save_r.ru_stime.tv_sec),
3455 (long) (r.ru_stime.tv_usec - Save_r.ru_stime.tv_usec));
3456 appendStringInfo(&str,
3457 "!\t[%ld.%06ld user %ld.%06ld sys total]\n",
3459 (long) user.tv_usec,
3461 (long) sys.tv_usec);
3462 /* BeOS has rusage but only has some fields, and not these... */
3463 #if defined(HAVE_GETRUSAGE)
3464 appendStringInfo(&str,
3465 "!\t%ld/%ld [%ld/%ld] filesystem blocks in/out\n",
3466 r.ru_inblock - Save_r.ru_inblock,
3467 /* they only drink coffee at dec */
3468 r.ru_oublock - Save_r.ru_oublock,
3469 r.ru_inblock, r.ru_oublock);
3470 appendStringInfo(&str,
3471 "!\t%ld/%ld [%ld/%ld] page faults/reclaims, %ld [%ld] swaps\n",
3472 r.ru_majflt - Save_r.ru_majflt,
3473 r.ru_minflt - Save_r.ru_minflt,
3474 r.ru_majflt, r.ru_minflt,
3475 r.ru_nswap - Save_r.ru_nswap,
3477 appendStringInfo(&str,
3478 "!\t%ld [%ld] signals rcvd, %ld/%ld [%ld/%ld] messages rcvd/sent\n",
3479 r.ru_nsignals - Save_r.ru_nsignals,
3481 r.ru_msgrcv - Save_r.ru_msgrcv,
3482 r.ru_msgsnd - Save_r.ru_msgsnd,
3483 r.ru_msgrcv, r.ru_msgsnd);
3484 appendStringInfo(&str,
3485 "!\t%ld/%ld [%ld/%ld] voluntary/involuntary context switches\n",
3486 r.ru_nvcsw - Save_r.ru_nvcsw,
3487 r.ru_nivcsw - Save_r.ru_nivcsw,
3488 r.ru_nvcsw, r.ru_nivcsw);
3489 #endif /* HAVE_GETRUSAGE */
3491 bufusage = ShowBufferUsage();
3492 appendStringInfo(&str, "! buffer usage stats:\n%s", bufusage);
3495 /* remove trailing newline */
3496 if (str.data[str.len - 1] == '\n')
3497 str.data[--str.len] = '\0';
3500 (errmsg_internal("%s", title),
3501 errdetail("%s", str.data)));
3507 * on_proc_exit handler to log end of session
3510 log_disconnections(int code, Datum arg)
3512 Port *port = MyProcPort;
3518 gettimeofday(&end, NULL);
3519 if (end.tv_usec < port->session_start.tv_usec)
3522 end.tv_usec += 1000000;
3524 end.tv_sec -= port->session_start.tv_sec;
3525 end.tv_usec -= port->session_start.tv_usec;
3527 /* for stricter accuracy here we could round - this is close enough */
3528 hours = end.tv_sec / SECS_PER_HOUR;
3529 end.tv_sec %= SECS_PER_HOUR;
3530 minutes = end.tv_sec / SECS_PER_MINUTE;
3531 seconds = end.tv_sec % SECS_PER_MINUTE;
3534 (errmsg("disconnection: session time: %d:%02d:%02d.%02d "
3535 "user=%s database=%s host=%s%s%s",
3536 hours, minutes, seconds, (int) (end.tv_usec / 10000),
3537 port->user_name, port->database_name, port->remote_host,
3538 port->remote_port[0] ? " port=" : "", port->remote_port)));