1 /*-------------------------------------------------------------------------
4 * POSTGRES C Backend Interface
6 * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $Header: /cvsroot/pgsql/src/backend/tcop/postgres.c,v 1.291 2002/09/04 20:31:26 momjian Exp $
14 * this is the "main" module of the postgres backend and
15 * hence the main module of the "traffic cop".
17 *-------------------------------------------------------------------------
27 #include <sys/socket.h>
30 #include <sys/select.h>
36 #include "access/xlog.h"
37 #include "commands/async.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/parse.h"
48 #include "parser/parser.h"
49 #include "rewrite/rewriteHandler.h"
50 #include "storage/ipc.h"
51 #include "storage/proc.h"
52 #include "tcop/fastpath.h"
53 #include "tcop/pquery.h"
54 #include "tcop/tcopprot.h"
55 #include "tcop/utility.h"
56 #include "utils/guc.h"
57 #include "utils/memutils.h"
58 #include "utils/ps_status.h"
59 #include "mb/pg_wchar.h"
72 char *debug_query_string; /* for pgmonitor and
73 * log_min_error_statement */
75 /* Note: whereToSendOutput is initialized for the bootstrap/standalone case */
76 CommandDest whereToSendOutput = Debug;
78 extern int StatementTimeout;
80 static bool dontExecute = false;
82 /* note: these declarations had better match tcopprot.h */
83 sigjmp_buf Warn_restart;
85 bool Warn_restart_ready = false;
88 static bool EchoQuery = false; /* default don't echo */
91 * Flag to mark SIGHUP. Whenever the main loop comes around it
92 * will reread the configuration file. (Better than doing the
93 * reading in the signal handler, ey?)
95 static volatile bool got_SIGHUP = false;
98 * people who want to use EOF should #define DONTUSENEWLINE in
102 #ifndef TCOP_DONTUSENEWLINE
103 int UseNewLine = 1; /* Use newlines query delimiters (the
107 int UseNewLine = 0; /* Use EOF as query delimiters */
108 #endif /* TCOP_DONTUSENEWLINE */
111 ** Flags for expensive function optimization -- JMH 3/9/92
115 /* ----------------------------------------------------------------
116 * decls for routines only used in this file
117 * ----------------------------------------------------------------
119 static int InteractiveBackend(StringInfo inBuf);
120 static int SocketBackend(StringInfo inBuf);
121 static int ReadCommand(StringInfo inBuf);
122 static List *pg_parse_query(StringInfo query_string, Oid *typev, int nargs);
123 static List *pg_analyze_and_rewrite(Node *parsetree);
124 static void start_xact_command(void);
125 static void finish_xact_command(void);
126 static void SigHupHandler(SIGNAL_ARGS);
127 static void FloatExceptionHandler(SIGNAL_ARGS);
128 static const char *CreateCommandTag(Node *parsetree);
131 /* ----------------------------------------------------------------
132 * routines to obtain user input
133 * ----------------------------------------------------------------
137 * InteractiveBackend() is called for user interactive connections
138 * the string entered by the user is placed in its parameter inBuf.
140 * EOF is returned if end-of-file input is seen; time to shut down.
145 InteractiveBackend(StringInfo inBuf)
147 int c; /* character read from getc() */
148 bool end = false; /* end-of-input flag */
149 bool backslashSeen = false; /* have we seen a \ ? */
152 * display a prompt and obtain input from the user
157 /* Reset inBuf to empty */
159 inBuf->data[0] = '\0';
166 * if we are using \n as a delimiter, then read characters
169 while ((c = getc(stdin)) != EOF)
175 /* discard backslash from inBuf */
176 inBuf->data[--inBuf->len] = '\0';
177 backslashSeen = false;
182 /* keep the newline character */
183 appendStringInfoChar(inBuf, '\n');
188 backslashSeen = true;
190 backslashSeen = false;
192 appendStringInfoChar(inBuf, (char) c);
201 * otherwise read characters until EOF.
203 while ((c = getc(stdin)) != EOF)
204 appendStringInfoChar(inBuf, (char) c);
214 * otherwise we have a user query so process it.
220 * if the query echo flag was given, print the query..
223 printf("statement: %s\n", inBuf->data);
230 * SocketBackend() Is called for frontend-backend connections
232 * If the input is a query (case 'Q') then the string entered by
233 * the user is placed in its parameter inBuf.
235 * If the input is a fastpath function call (case 'F') then
236 * the function call is processed in HandleFunctionRequest()
237 * (now called from PostgresMain()).
239 * EOF is returned if the connection is lost.
244 SocketBackend(StringInfo inBuf)
249 * get input from the frontend
251 qtype = pq_getbyte();
256 /* frontend disconnected */
260 * 'Q': user entered a query
263 if (pq_getstr(inBuf))
268 * 'F': calling user/system functions
271 if (pq_getstr(inBuf))
272 return EOF; /* ignore "string" at start of F message */
276 * 'X': frontend is exiting
282 * otherwise we got garbage from the frontend.
284 * XXX are we certain that we want to do an elog(FATAL) here?
288 elog(FATAL, "Socket command type %c unknown", qtype);
296 * ReadCommand reads a command from either the frontend or
297 * standard input, places it in inBuf, and returns a char
298 * representing whether the string is a 'Q'uery or a 'F'astpath
299 * call. EOF is returned if end of file.
303 ReadCommand(StringInfo inBuf)
307 if (IsUnderPostmaster)
308 result = SocketBackend(inBuf);
310 result = InteractiveBackend(inBuf);
316 * Parse a query string and pass it through the rewriter.
318 * A list of Query nodes is returned, since the string might contain
319 * multiple queries and/or the rewriter might expand one query to several.
321 * NOTE: this routine is no longer used for processing interactive queries,
322 * but it is still needed for parsing of SQL function bodies.
325 pg_parse_and_rewrite(char *query_string, /* string to execute */
326 Oid *typev, /* parameter types */
327 int nargs) /* number of parameters */
329 List *raw_parsetree_list;
330 List *querytree_list;
334 initStringInfo(&stri);
335 appendStringInfo(&stri, "%s", query_string);
338 * (1) parse the request string into a list of raw parse trees.
340 raw_parsetree_list = pg_parse_query(&stri, typev, nargs);
343 * (2) Do parse analysis and rule rewrite.
345 querytree_list = NIL;
346 foreach(list_item, raw_parsetree_list)
348 Node *parsetree = (Node *) lfirst(list_item);
350 querytree_list = nconc(querytree_list,
351 pg_analyze_and_rewrite(parsetree));
354 return querytree_list;
358 * Do raw parsing (only).
360 * A list of parsetrees is returned, since there might be multiple
361 * commands in the given string.
363 * NOTE: for interactive queries, it is important to keep this routine
364 * separate from the analysis & rewrite stages. Analysis and rewriting
365 * cannot be done in an aborted transaction, since they require access to
366 * database tables. So, we rely on the raw parser to determine whether
367 * we've seen a COMMIT or ABORT command; when we are in abort state, other
368 * commands are not processed any further than the raw parse stage.
371 pg_parse_query(StringInfo query_string, Oid *typev, int nargs)
373 List *raw_parsetree_list;
376 elog(LOG, "query: %s", query_string->data);
378 if (Show_parser_stats)
381 raw_parsetree_list = parser(query_string, typev, nargs);
383 if (Show_parser_stats)
384 ShowUsage("PARSER STATISTICS");
386 return raw_parsetree_list;
390 * Given a raw parsetree (gram.y output), perform parse analysis and
393 * A list of Query nodes is returned, since either the analyzer or the
394 * rewriter might expand one query to several.
396 * NOTE: for reasons mentioned above, this must be separate from raw parsing.
399 pg_analyze_and_rewrite(Node *parsetree)
401 List *querytree_list;
407 * (1) Perform parse analysis.
409 if (Show_parser_stats)
412 querytree_list = parse_analyze(parsetree, NULL);
414 if (Show_parser_stats)
416 ShowUsage("PARSE ANALYSIS STATISTICS");
421 * (2) Rewrite the queries, as necessary
423 * rewritten queries are collected in new_list. Note there may be more
424 * or fewer than in the original list.
427 foreach(list_item, querytree_list)
429 querytree = (Query *) lfirst(list_item);
431 if (Debug_print_parse)
432 elog_node_display(LOG, "parse tree", querytree,
435 if (querytree->commandType == CMD_UTILITY)
437 /* don't rewrite utilities, just dump 'em into new_list */
438 new_list = lappend(new_list, querytree);
442 /* rewrite regular queries */
443 List *rewritten = QueryRewrite(querytree);
445 new_list = nconc(new_list, rewritten);
449 querytree_list = new_list;
451 if (Show_parser_stats)
452 ShowUsage("REWRITER STATISTICS");
454 #ifdef COPY_PARSE_PLAN_TREES
457 * Optional debugging check: pass querytree output through
460 new_list = (List *) copyObject(querytree_list);
461 /* This checks both copyObject() and the equal() routines... */
462 if (!equal(new_list, querytree_list))
463 elog(WARNING, "pg_analyze_and_rewrite: copyObject failed on parse tree");
465 querytree_list = new_list;
468 if (Debug_print_rewritten)
469 elog_node_display(LOG, "rewritten parse tree", querytree_list,
472 return querytree_list;
476 /* Generate a plan for a single query. */
478 pg_plan_query(Query *querytree)
482 /* Utility commands have no plans. */
483 if (querytree->commandType == CMD_UTILITY)
486 if (Show_planner_stats)
489 /* call that optimizer */
490 plan = planner(querytree);
492 if (Show_planner_stats)
493 ShowUsage("PLANNER STATISTICS");
495 #ifdef COPY_PARSE_PLAN_TREES
496 /* Optional debugging check: pass plan output through copyObject() */
498 Plan *new_plan = (Plan *) copyObject(plan);
501 * equal() currently does not have routines to compare Plan nodes,
502 * so don't try to test equality here. Perhaps fix someday?
505 /* This checks both copyObject() and the equal() routines... */
506 if (!equal(new_plan, plan))
507 elog(WARNING, "pg_plan_query: copyObject failed on plan tree");
515 * Print plan if debugging.
517 if (Debug_print_plan)
518 elog_node_display(LOG, "plan", plan, Debug_pretty_print);
524 /* ----------------------------------------------------------------
525 * pg_exec_query_string()
527 * Takes a querystring, runs the parser/utilities or
528 * parser/planner/executor over it as necessary.
532 * At call, we are not inside a transaction command.
534 * The CurrentMemoryContext after starting a transaction command must be
535 * appropriate for execution of individual queries (typically this will be
536 * TransactionCommandContext). Note that this routine resets that context
537 * after each individual query, so don't store anything there that
538 * must outlive the call!
540 * parse_context references a context suitable for holding the
541 * parse/rewrite trees (typically this will be QueryContext).
542 * This context *must* be longer-lived than the transaction context!
543 * In fact, if the query string might contain BEGIN/COMMIT commands,
544 * parse_context had better outlive TopTransactionContext!
546 * We could have hard-wired knowledge about QueryContext and
547 * TransactionCommandContext into this routine, but it seems better
548 * not to, in case callers from outside this module need to use some
551 * ----------------------------------------------------------------
555 pg_exec_query_string(StringInfo query_string, /* string to execute */
556 CommandDest dest, /* where results should go */
557 MemoryContext parse_context) /* context for
561 MemoryContext oldcontext;
562 List *parsetree_list,
565 struct timeval start_t,
567 bool save_Log_duration = Log_duration;
569 debug_query_string = query_string->data;
572 * We use save_Log_duration so setting Log_duration to true doesn't
573 * report incorrect time because gettimeofday() wasn't called.
575 if (save_Log_duration)
576 gettimeofday(&start_t, &tz);
579 * Start up a transaction command. All queries generated by the
580 * query_string will be in this same command block, *unless* we find a
581 * BEGIN/COMMIT/ABORT statement; we have to force a new xact command
582 * after one of those, else bad things will happen in xact.c. (Note
583 * that this will possibly change current memory context.)
585 start_xact_command();
588 if (StatementTimeout)
589 enable_sig_alarm(StatementTimeout, true);
592 * parse_context *must* be different from the execution memory
593 * context, else the context reset at the bottom of the loop will
594 * destroy the parsetree list. (We really ought to check that
595 * parse_context isn't a child of CurrentMemoryContext either, but
596 * that would take more cycles than it's likely to be worth.)
598 Assert(parse_context != CurrentMemoryContext);
601 * Switch to appropriate context for constructing parsetrees.
603 oldcontext = MemoryContextSwitchTo(parse_context);
606 * Do basic parsing of the query or queries (this should be safe even
607 * if we are in aborted transaction state!)
609 parsetree_list = pg_parse_query(query_string, NULL, 0);
612 * Switch back to execution context to enter the loop.
614 MemoryContextSwitchTo(oldcontext);
617 * Run through the parsetree(s) and process each one.
619 foreach(parsetree_item, parsetree_list)
621 Node *parsetree = (Node *) lfirst(parsetree_item);
622 bool isTransactionStmt;
623 const char *commandTag;
624 char completionTag[COMPLETION_TAG_BUFSIZE];
625 List *querytree_list,
628 /* Transaction control statements need some special handling */
629 isTransactionStmt = IsA(parsetree, TransactionStmt);
632 * First we set the command-completion tag to the main query (as
633 * opposed to each of the others that may be generated by analyze
634 * and rewrite). Also set ps_status and do any special
635 * start-of-SQL-command processing needed by the destination.
637 commandTag = CreateCommandTag(parsetree);
639 set_ps_display(commandTag);
641 BeginCommand(commandTag, dest);
644 * If we are in an aborted transaction, ignore all commands except
645 * COMMIT/ABORT. It is important that this test occur before we
646 * try to do parse analysis, rewrite, or planning, since all those
647 * phases try to do database accesses, which may fail in abort
648 * state. (It might be safe to allow some additional utility
649 * commands in this state, but not many...)
651 if (IsAbortedTransactionBlockState())
653 bool allowit = false;
655 if (isTransactionStmt)
657 TransactionStmt *stmt = (TransactionStmt *) parsetree;
659 if (stmt->command == COMMIT || stmt->command == ROLLBACK)
664 elog(ERROR, "current transaction is aborted, "
665 "queries ignored until end of transaction block");
668 /* Make sure we are in a transaction command */
671 start_xact_command();
675 /* If we got a cancel signal in parsing or prior command, quit */
676 CHECK_FOR_INTERRUPTS();
679 * OK to analyze and rewrite this query.
681 * Switch to appropriate context for constructing querytrees (again,
682 * these must outlive the execution context).
684 oldcontext = MemoryContextSwitchTo(parse_context);
686 querytree_list = pg_analyze_and_rewrite(parsetree);
689 * Switch back to execution context for planning and execution.
691 MemoryContextSwitchTo(oldcontext);
694 * Inner loop handles the individual queries generated from a
695 * single parsetree by analysis and rewrite.
697 foreach(querytree_item, querytree_list)
699 Query *querytree = (Query *) lfirst(querytree_item);
701 /* Make sure we are in a transaction command */
704 start_xact_command();
709 * If we got a cancel signal in analysis or prior command,
712 CHECK_FOR_INTERRUPTS();
714 if (querytree->commandType == CMD_UTILITY)
717 * process utility functions (create, destroy, etc..)
719 elog(DEBUG2, "ProcessUtility");
721 if (querytree->originalQuery)
723 /* utility statement can override default tag string */
724 ProcessUtility(querytree->utilityStmt, dest,
726 if (completionTag[0])
727 commandTag = completionTag;
731 /* utility added by rewrite cannot override tag */
732 ProcessUtility(querytree->utilityStmt, dest, NULL);
738 * process a plannable query.
742 plan = pg_plan_query(querytree);
744 /* if we got a cancel signal whilst planning, quit */
745 CHECK_FOR_INTERRUPTS();
747 /* Initialize snapshot state for query */
753 if (Show_executor_stats)
758 /* don't execute it, just show the query plan */
759 print_plan(plan, querytree);
763 elog(DEBUG2, "ProcessQuery");
765 if (querytree->originalQuery || length(querytree_list) == 1)
767 /* original stmt can override default tag string */
768 ProcessQuery(querytree, plan, dest, completionTag);
769 commandTag = completionTag;
773 /* stmt added by rewrite cannot override tag */
774 ProcessQuery(querytree, plan, dest, NULL);
778 if (Show_executor_stats)
779 ShowUsage("EXECUTOR STATISTICS");
783 * In a query block, we want to increment the command counter
784 * between queries so that the effects of early queries are
785 * visible to subsequent ones. In particular we'd better do
786 * so before checking constraints.
788 if (!isTransactionStmt)
789 CommandCounterIncrement();
792 * Clear the execution context to recover temporary memory
793 * used by the query. NOTE: if query string contains
794 * BEGIN/COMMIT transaction commands, execution context may
795 * now be different from what we were originally passed; so be
796 * careful to clear current context not "oldcontext".
798 Assert(parse_context != CurrentMemoryContext);
800 MemoryContextResetAndDeleteChildren(CurrentMemoryContext);
803 * If this was a transaction control statement, commit it and
804 * arrange to start a new xact command for the next command
807 if (isTransactionStmt)
809 finish_xact_command();
810 xact_started = false;
812 } /* end loop over queries generated from a
816 * If this is the last parsetree of the query string, close down
817 * transaction statement before reporting command-complete. This
818 * is so that any end-of-transaction errors are reported before
819 * the command-complete message is issued, to avoid confusing
820 * clients who will expect either a command-complete message or an
821 * error, not one and then the other. But for compatibility with
822 * historical Postgres behavior, we do not force a transaction
823 * boundary between queries appearing in a single query string.
825 if (lnext(parsetree_item) == NIL && xact_started)
827 finish_xact_command();
828 xact_started = false;
832 * It is possible that the original query was removed due to a DO
833 * INSTEAD rewrite rule. In that case we will still have the
834 * default completion tag, which is fine for most purposes, but it
835 * may confuse clients if it's INSERT/UPDATE/DELETE. Clients
836 * expect those tags to have counts after them (cf. ProcessQuery).
838 if (strcmp(commandTag, "INSERT") == 0)
839 commandTag = "INSERT 0 0";
840 else if (strcmp(commandTag, "UPDATE") == 0)
841 commandTag = "UPDATE 0";
842 else if (strcmp(commandTag, "DELETE") == 0)
843 commandTag = "DELETE 0";
846 * Tell client that we're done with this query. Note we emit
847 * exactly one EndCommand report for each raw parsetree, thus one
848 * for each SQL command the client sent, regardless of rewriting.
849 * (But a command aborted by error will not send an EndCommand
852 EndCommand(commandTag, dest);
853 } /* end loop over parsetrees */
855 disable_sig_alarm(true);
858 * Close down transaction statement, if one is open. (Note that this
859 * will only happen if the querystring was empty.)
862 finish_xact_command();
864 if (save_Log_duration)
866 gettimeofday(&stop_t, &tz);
867 if (stop_t.tv_usec < start_t.tv_usec)
870 stop_t.tv_usec += 1000000;
872 elog(LOG, "duration: %ld.%06ld sec",
873 (long int) stop_t.tv_sec - start_t.tv_sec,
874 (long int) stop_t.tv_usec - start_t.tv_usec);
877 debug_query_string = NULL;
881 * Convenience routines for starting/committing a single command.
884 start_xact_command(void)
886 elog(DEBUG1, "StartTransactionCommand");
887 StartTransactionCommand(false);
891 finish_xact_command(void)
893 /* Invoke IMMEDIATE constraint triggers */
894 DeferredTriggerEndQuery();
896 /* Now commit the command */
897 elog(DEBUG1, "CommitTransactionCommand");
899 CommitTransactionCommand(false);
901 #ifdef SHOW_MEMORY_STATS
902 /* Print mem stats at each commit for leak tracking */
904 MemoryContextStats(TopMemoryContext);
909 /* --------------------------------
910 * signal handler routines used in PostgresMain()
911 * --------------------------------
915 * quickdie() occurs when signalled SIGQUIT by the postmaster.
917 * Some backend has bought the farm,
918 * so we need to stop what we're doing and exit.
921 quickdie(SIGNAL_ARGS)
923 PG_SETMASK(&BlockSig);
924 elog(WARNING, "Message from PostgreSQL backend:"
925 "\n\tThe Postmaster has informed me that some other backend"
926 "\n\tdied abnormally and possibly corrupted shared memory."
927 "\n\tI have rolled back the current transaction and am"
928 "\n\tgoing to terminate your database system connection and exit."
929 "\n\tPlease reconnect to the database system and repeat your query.");
932 * DO NOT proc_exit() -- we're here because shared memory may be
933 * corrupted, so we don't want to try to clean up our transaction.
934 * Just nail the windows shut and get out of town.
936 * Note we do exit(1) not exit(0). This is to force the postmaster into
937 * a system reset cycle if some idiot DBA sends a manual SIGQUIT to a
938 * random backend. This is necessary precisely because we don't clean
939 * up our shared memory state.
946 * Shutdown signal from postmaster: abort transaction and exit
947 * at soonest convenient time
952 int save_errno = errno;
954 /* Don't joggle the elbow of proc_exit */
955 if (!proc_exit_inprogress)
957 InterruptPending = true;
958 ProcDiePending = true;
961 * If it's safe to interrupt, and we're waiting for input or a
962 * lock, service the interrupt immediately
964 if (ImmediateInterruptOK && InterruptHoldoffCount == 0 &&
965 CritSectionCount == 0)
967 /* bump holdoff count to make ProcessInterrupts() a no-op */
968 /* until we are done getting ready for it */
969 InterruptHoldoffCount++;
970 DisableNotifyInterrupt();
971 /* Make sure HandleDeadLock won't run while shutting down... */
973 InterruptHoldoffCount--;
982 * Timeout or shutdown signal from postmaster during client authentication.
985 * XXX: possible future improvement: try to send a message indicating
986 * why we are disconnecting. Problem is to be sure we don't block while
987 * doing so, nor mess up the authentication message exchange.
996 * Query-cancel signal from postmaster: abort current transaction
997 * at soonest convenient time
1000 StatementCancelHandler(SIGNAL_ARGS)
1002 int save_errno = errno;
1005 * Don't joggle the elbow of proc_exit, nor an already-in-progress
1008 if (!proc_exit_inprogress && !InError)
1010 InterruptPending = true;
1011 QueryCancelPending = true;
1014 * If it's safe to interrupt, and we're waiting for a lock,
1015 * service the interrupt immediately. No point in interrupting if
1016 * we're waiting for input, however.
1018 if (ImmediateInterruptOK && InterruptHoldoffCount == 0 &&
1019 CritSectionCount == 0)
1021 /* bump holdoff count to make ProcessInterrupts() a no-op */
1022 /* until we are done getting ready for it */
1023 InterruptHoldoffCount++;
1024 if (LockWaitCancel())
1026 DisableNotifyInterrupt();
1027 InterruptHoldoffCount--;
1028 ProcessInterrupts();
1031 InterruptHoldoffCount--;
1038 /* signal handler for floating point exception */
1040 FloatExceptionHandler(SIGNAL_ARGS)
1042 elog(ERROR, "floating point exception!"
1043 " The last floating point operation either exceeded legal ranges"
1044 " or was a divide by zero");
1047 /* SIGHUP: set flag to re-read config file at next convenient time */
1049 SigHupHandler(SIGNAL_ARGS)
1056 * ProcessInterrupts: out-of-line portion of CHECK_FOR_INTERRUPTS() macro
1058 * If an interrupt condition is pending, and it's safe to service it,
1059 * then clear the flag and accept the interrupt. Called only when
1060 * InterruptPending is true.
1063 ProcessInterrupts(void)
1065 /* OK to accept interrupt now? */
1066 if (InterruptHoldoffCount != 0 || CritSectionCount != 0)
1068 InterruptPending = false;
1071 ProcDiePending = false;
1072 QueryCancelPending = false; /* ProcDie trumps QueryCancel */
1073 ImmediateInterruptOK = false; /* not idle anymore */
1074 elog(FATAL, "This connection has been terminated by the administrator.");
1076 if (QueryCancelPending)
1078 QueryCancelPending = false;
1079 ImmediateInterruptOK = false; /* not idle anymore */
1080 elog(ERROR, "Query was cancelled.");
1082 /* If we get here, do nothing (probably, QueryCancelPending was reset) */
1087 usage(char *progname)
1089 printf("%s is the PostgreSQL stand-alone backend. It is not\nintended to be used by normal users.\n\n", progname);
1091 printf("Usage:\n %s [options...] [dbname]\n\n", progname);
1092 printf("Options:\n");
1093 #ifdef USE_ASSERT_CHECKING
1094 printf(" -A 1|0 enable/disable run-time assert checking\n");
1096 printf(" -B NBUFFERS number of shared buffers (default %d)\n", DEF_NBUFFERS);
1097 printf(" -c NAME=VALUE set run-time parameter\n");
1098 printf(" -d 1-5,0 debugging level (0 is off)\n");
1099 printf(" -D DATADIR database directory\n");
1100 printf(" -e use European date format\n");
1101 printf(" -E echo query before execution\n");
1102 printf(" -F turn fsync off\n");
1103 printf(" -N do not use newline as interactive query delimiter\n");
1104 printf(" -o FILENAME send stdout and stderr to given file\n");
1105 printf(" -P disable system indexes\n");
1106 printf(" -s show statistics after each query\n");
1107 printf(" -S SORT-MEM set amount of memory for sorts (in kbytes)\n");
1108 printf("Developer options:\n");
1109 printf(" -f [s|i|n|m|h] forbid use of some plan types\n");
1110 printf(" -i do not execute queries\n");
1111 printf(" -O allow system table structure changes\n");
1112 printf(" -t [pa|pl|ex] show timings after each query\n");
1113 printf(" -W NUM wait NUM seconds to allow attach from a debugger\n");
1114 printf("\nReport bugs to <pgsql-bugs@postgresql.org>.\n");
1119 /* ----------------------------------------------------------------
1121 * postgres main loop -- all backends, interactive or otherwise start here
1123 * argc/argv are the command line arguments to be used. (When being forked
1124 * by the postmaster, these are not the original argv array of the process.)
1125 * username is the (possibly authenticated) PostgreSQL user name to be used
1127 * ----------------------------------------------------------------
1130 PostgresMain(int argc, char *argv[], const char *username)
1134 const char *DBName = NULL;
1138 GucSource gucsource;
1142 StringInfo parser_input;
1144 char *potential_DataDir = NULL;
1147 * Catch standard options before doing much else. This even works on
1148 * systems without getopt_long.
1150 if (!IsUnderPostmaster && argc > 1)
1152 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
1157 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
1159 puts("postgres (PostgreSQL) " PG_VERSION);
1165 * Fire up essential subsystems: error and memory management
1167 * If we are running under the postmaster, this is done already.
1169 if (!IsUnderPostmaster)
1170 MemoryContextInit();
1172 set_ps_display("startup");
1174 SetProcessingMode(InitProcessing);
1177 * Set default values for command-line options.
1182 if (!IsUnderPostmaster)
1184 InitializeGUCOptions();
1185 potential_DataDir = getenv("PGDATA");
1189 * parse command line arguments
1191 * There are now two styles of command line layout for the backend:
1193 * For interactive use (not started from postmaster) the format is
1194 * postgres [switches] [databasename]
1195 * If the databasename is omitted it is taken to be the user name.
1197 * When started from the postmaster, the format is
1198 * postgres [secure switches] -p databasename [insecure switches]
1199 * Switches appearing after -p came from the client (via "options"
1200 * field of connection request). For security reasons we restrict
1201 * what these switches can do.
1205 /* all options are allowed until '-p' */
1207 ctx = PGC_POSTMASTER;
1208 gucsource = PGC_S_ARGV; /* initial switches came from command line */
1210 while ((flag = getopt(argc, argv, "A:B:c:CD:d:Eef:FiNOPo:p:S:st:v:W:x:-:")) != -1)
1214 #ifdef USE_ASSERT_CHECKING
1215 SetConfigOption("debug_assertions", optarg, ctx, gucsource);
1217 elog(WARNING, "Assert checking is not compiled in");
1224 * specify the size of buffer pool
1226 SetConfigOption("shared_buffers", optarg, ctx, gucsource);
1232 * don't print version string
1237 case 'D': /* PGDATA directory */
1239 potential_DataDir = optarg;
1242 case 'd': /* debug level */
1244 /* Set server debugging level. */
1245 if (atoi(optarg) != 0)
1247 char *debugstr = palloc(strlen("debug") + strlen(optarg) + 1);
1249 sprintf(debugstr, "debug%s", optarg);
1250 SetConfigOption("server_min_messages", debugstr, ctx, gucsource);
1254 * -d is not the same as setting
1255 * client_min_messages because it enables other
1258 if (atoi(optarg) >= 1)
1259 SetConfigOption("log_connections", "true", ctx, gucsource);
1260 if (atoi(optarg) >= 2)
1261 SetConfigOption("log_statement", "true", ctx, gucsource);
1262 if (atoi(optarg) >= 3)
1263 SetConfigOption("debug_print_parse", "true", ctx, gucsource);
1264 if (atoi(optarg) >= 4)
1265 SetConfigOption("debug_print_plan", "true", ctx, gucsource);
1266 if (atoi(optarg) >= 5)
1267 SetConfigOption("debug_print_rewritten", "true", ctx, gucsource);
1272 * -d 0 allows user to prevent postmaster debug
1273 * from propagating to backend.
1275 SetConfigOption("server_min_messages", "notice",
1283 * E - echo the query the user entered
1291 * Use european date formats.
1293 SetConfigOption("datestyle", "euro", ctx, gucsource);
1301 SetConfigOption("fsync", "false", ctx, gucsource);
1307 * f - forbid generation of certain plans
1312 case 's': /* seqscan */
1313 tmp = "enable_seqscan";
1315 case 'i': /* indexscan */
1316 tmp = "enable_indexscan";
1318 case 't': /* tidscan */
1319 tmp = "enable_tidscan";
1321 case 'n': /* nestloop */
1322 tmp = "enable_nestloop";
1324 case 'm': /* mergejoin */
1325 tmp = "enable_mergejoin";
1327 case 'h': /* hashjoin */
1328 tmp = "enable_hashjoin";
1334 SetConfigOption(tmp, "false", ctx, gucsource);
1344 * N - Don't use newline as a query delimiter
1352 * allow system table structure modifications
1354 if (secure) /* XXX safe to allow from client??? */
1355 allowSystemTableMods = true;
1361 * ignore system indexes
1363 if (secure) /* XXX safe to allow from client??? */
1364 IgnoreSystemIndexes(true);
1370 * o - send output (stdout and stderr) to the given file
1373 StrNCpy(OutputFileName, optarg, MAXPGPATH);
1379 * p - special flag passed if backend was forked by a
1384 DBName = strdup(optarg);
1385 secure = false; /* subsequent switches are NOT
1388 gucsource = PGC_S_CLIENT;
1395 * S - amount of sort memory to use in 1k bytes
1397 SetConfigOption("sort_mem", optarg, ctx, gucsource);
1403 * s - report usage statistics (timings) after each query
1405 SetConfigOption("show_statement_stats", "true", ctx, gucsource);
1410 * tell postgres to report usage statistics (timings) for
1413 * -tpa[rser] = print stats for parser time of each query
1414 * -tpl[anner] = print stats for planner time of each query
1415 * -te[xecutor] = print stats for executor time of each query
1416 * caution: -s can not be used together with -t.
1423 if (optarg[1] == 'a')
1424 tmp = "show_parser_stats";
1425 else if (optarg[1] == 'l')
1426 tmp = "show_planner_stats";
1431 tmp = "show_executor_stats";
1438 SetConfigOption(tmp, "true", ctx, gucsource);
1443 FrontendProtocol = (ProtocolVersion) atoi(optarg);
1449 * wait N seconds to allow attach from a debugger
1451 sleep(atoi(optarg));
1455 #ifdef NOT_USED /* planner/xfunc.h */
1458 * control joey hellerstein's expensive function
1463 elog(WARNING, "only one -x flag is allowed");
1467 if (strcmp(optarg, "off") == 0)
1468 XfuncMode = XFUNC_OFF;
1469 else if (strcmp(optarg, "nor") == 0)
1470 XfuncMode = XFUNC_NOR;
1471 else if (strcmp(optarg, "nopull") == 0)
1472 XfuncMode = XFUNC_NOPULL;
1473 else if (strcmp(optarg, "nopm") == 0)
1474 XfuncMode = XFUNC_NOPM;
1475 else if (strcmp(optarg, "pullall") == 0)
1476 XfuncMode = XFUNC_PULLALL;
1477 else if (strcmp(optarg, "wait") == 0)
1478 XfuncMode = XFUNC_WAIT;
1481 elog(WARNING, "use -x {off,nor,nopull,nopm,pullall,wait}");
1493 ParseLongOption(optarg, &name, &value);
1497 elog(ERROR, "--%s requires argument", optarg);
1499 elog(ERROR, "-c %s requires argument", optarg);
1502 SetConfigOption(name, value, ctx, gucsource);
1515 * Post-processing for command line options.
1517 if (Show_statement_stats &&
1518 (Show_parser_stats || Show_planner_stats || Show_executor_stats))
1520 elog(WARNING, "Query statistics are disabled because parser, planner, or executor statistics are on.");
1521 SetConfigOption("show_statement_stats", "false", ctx, gucsource);
1524 if (!IsUnderPostmaster)
1526 if (!potential_DataDir)
1528 fprintf(stderr, "%s does not know where to find the database system "
1529 "data. You must specify the directory that contains the "
1530 "database system either by specifying the -D invocation "
1531 "option or by setting the PGDATA environment variable.\n\n",
1535 SetDataDir(potential_DataDir);
1540 * Set up signal handlers and masks.
1542 * Note that postmaster blocked all signals before forking child process,
1543 * so there is no race condition whereby we might receive a signal
1544 * before we have set up the handler.
1546 * Also note: it's best not to use any signals that are SIG_IGNored in
1547 * the postmaster. If such a signal arrives before we are able to
1548 * change the handler to non-SIG_IGN, it'll get dropped. Instead,
1549 * make a dummy handler in the postmaster to reserve the signal. (Of
1550 * course, this isn't an issue for signals that are locally generated,
1551 * such as SIGALRM and SIGPIPE.)
1554 pqsignal(SIGHUP, SigHupHandler); /* set flag to read config file */
1555 pqsignal(SIGINT, StatementCancelHandler); /* cancel current query */
1556 pqsignal(SIGTERM, die); /* cancel current query and exit */
1557 pqsignal(SIGQUIT, quickdie); /* hard crash time */
1558 pqsignal(SIGALRM, handle_sig_alarm); /* check for deadlock
1562 * Ignore failure to write to frontend. Note: if frontend closes
1563 * connection, we will notice it and exit cleanly when control next
1564 * returns to outer loop. This seems safer than forcing exit in the
1565 * midst of output during who-knows-what operation...
1567 pqsignal(SIGPIPE, SIG_IGN);
1568 pqsignal(SIGUSR1, SIG_IGN); /* this signal available for use */
1570 pqsignal(SIGUSR2, Async_NotifyHandler); /* flush also sinval cache */
1571 pqsignal(SIGFPE, FloatExceptionHandler);
1574 * Reset some signals that are accepted by postmaster but not by
1577 pqsignal(SIGCHLD, SIG_DFL); /* system() requires this on some
1582 /* We allow SIGQUIT (quickdie) at all times */
1583 #ifdef HAVE_SIGPROCMASK
1584 sigdelset(&BlockSig, SIGQUIT);
1586 BlockSig &= ~(sigmask(SIGQUIT));
1589 PG_SETMASK(&BlockSig); /* block everything except SIGQUIT */
1592 if (IsUnderPostmaster)
1594 /* noninteractive case: nothing should be left after switches */
1595 if (errs || argc != optind || DBName == NULL)
1597 elog(WARNING, "%s: invalid command line arguments\nTry -? for help.",
1599 proc_exit(0); /* not 1, that causes system-wide
1606 /* interactive case: database name can be last arg on command line */
1607 if (errs || argc - optind > 1)
1609 elog(WARNING, "%s: invalid command line arguments\nTry -? for help.",
1613 else if (argc - optind == 1)
1614 DBName = argv[optind];
1615 else if ((DBName = username) == NULL)
1617 elog(WARNING, "%s: user name undefined and no database specified",
1623 * On some systems our dynloader code needs the executable's
1624 * pathname. (If under postmaster, this was done already.)
1626 if (FindExec(pg_pathname, argv[0], "postgres") < 0)
1627 elog(FATAL, "%s: could not locate executable, bailing out...",
1631 * Validate we have been given a reasonable-looking DataDir (if
1632 * under postmaster, assume postmaster did this already).
1634 ValidatePgVersion(DataDir);
1637 * Create lockfile for data directory.
1639 if (!CreateDataDirLockFile(DataDir, false))
1646 * Start up xlog for standalone backend, and register to have it
1647 * closed down at exit.
1650 on_shmem_exit(ShutdownXLOG, 0);
1654 * Set up additional info.
1662 * General initialization.
1664 * NOTE: if you are tempted to add code in this vicinity, consider
1665 * putting it inside InitPostgres() instead. In particular, anything
1666 * that involves database access should be there, not here.
1668 elog(DEBUG2, "InitPostgres");
1669 InitPostgres(DBName, username);
1671 SetProcessingMode(NormalProcessing);
1674 * Send this backend's cancellation info to the frontend.
1676 if (whereToSendOutput == Remote &&
1677 PG_PROTOCOL_MAJOR(FrontendProtocol) >= 2)
1681 pq_beginmessage(&buf);
1682 pq_sendbyte(&buf, 'K');
1683 pq_sendint(&buf, (int32) MyProcPid, sizeof(int32));
1684 pq_sendint(&buf, (int32) MyCancelKey, sizeof(int32));
1685 pq_endmessage(&buf);
1686 /* Need not flush since ReadyForQuery will do it. */
1689 if (!IsUnderPostmaster)
1691 puts("\nPOSTGRES backend interactive interface ");
1692 puts("$Revision: 1.291 $ $Date: 2002/09/04 20:31:26 $\n");
1696 * Create the memory context we will use in the main loop.
1698 * QueryContext is reset once per iteration of the main loop, ie, upon
1699 * completion of processing of each supplied query string. It can
1700 * therefore be used for any data that should live just as long as the
1701 * query string --- parse trees, for example.
1703 QueryContext = AllocSetContextCreate(TopMemoryContext,
1705 ALLOCSET_DEFAULT_MINSIZE,
1706 ALLOCSET_DEFAULT_INITSIZE,
1707 ALLOCSET_DEFAULT_MAXSIZE);
1710 * Tell the statistics collector that we're alive and
1711 * to which database we belong.
1717 * POSTGRES main processing loop begins here
1719 * If an exception is encountered, processing resumes here so we abort
1720 * the current transaction and start a new one.
1723 if (sigsetjmp(Warn_restart, 1) != 0)
1726 * NOTE: if you are tempted to add more code in this if-block,
1727 * consider the probability that it should be in
1728 * AbortTransaction() instead.
1730 * Make sure we're not interrupted while cleaning up. Also forget
1731 * any pending QueryCancel request, since we're aborting anyway.
1732 * Force InterruptHoldoffCount to a known state in case we elog'd
1733 * from inside a holdoff section.
1735 ImmediateInterruptOK = false;
1736 QueryCancelPending = false;
1737 InterruptHoldoffCount = 1;
1738 CritSectionCount = 0; /* should be unnecessary, but... */
1739 debug_query_string = NULL;
1742 * Make sure we are in a valid memory context during recovery.
1744 * We use ErrorContext in hopes that it will have some free space
1745 * even if we're otherwise up against it...
1747 MemoryContextSwitchTo(ErrorContext);
1749 /* Do the recovery */
1750 elog(DEBUG1, "AbortCurrentTransaction");
1751 AbortCurrentTransaction();
1754 * Now return to normal top-level context and clear ErrorContext
1757 MemoryContextSwitchTo(TopMemoryContext);
1758 MemoryContextResetAndDeleteChildren(ErrorContext);
1761 * Clear flag to indicate that we got out of error recovery mode
1762 * successfully. (Flag was set in elog.c before longjmp().)
1767 * Exit interrupt holdoff section we implicitly established above.
1769 RESUME_INTERRUPTS();
1772 Warn_restart_ready = true; /* we can now handle elog(ERROR) */
1774 PG_SETMASK(&UnBlockSig);
1777 * Non-error queries loop here.
1783 * Release storage left over from prior query cycle, and create a
1784 * new query input buffer in the cleared QueryContext.
1786 MemoryContextSwitchTo(QueryContext);
1787 MemoryContextResetAndDeleteChildren(QueryContext);
1789 parser_input = makeStringInfo();
1792 * (1) tell the frontend we're ready for a new query.
1794 * Note: this includes fflush()'ing the last of the prior output.
1796 ReadyForQuery(whereToSendOutput);
1799 * Tell the statistics collector what we've collected
1803 pgstat_report_tabstat();
1805 if (IsTransactionBlock())
1807 set_ps_display("idle in transaction");
1808 pgstat_report_activity("<IDLE> in transaction");
1812 set_ps_display("idle");
1813 pgstat_report_activity("<IDLE>");
1817 * (2) deal with pending asynchronous NOTIFY from other backends,
1818 * and enable async.c's signal handler to execute NOTIFY directly.
1819 * Then set up other stuff needed before blocking for input.
1821 QueryCancelPending = false; /* forget any earlier CANCEL
1824 /* Stop any statement timer */
1825 disable_sig_alarm(true);
1827 EnableNotifyInterrupt();
1829 /* Allow "die" interrupt to be processed while waiting */
1830 ImmediateInterruptOK = true;
1831 /* and don't forget to detect one that already arrived */
1832 QueryCancelPending = false;
1833 CHECK_FOR_INTERRUPTS();
1836 * (3) read a command (loop blocks here)
1838 firstchar = ReadCommand(parser_input);
1841 * (4) disable async signal conditions again.
1843 ImmediateInterruptOK = false;
1844 QueryCancelPending = false; /* forget any CANCEL signal */
1846 DisableNotifyInterrupt();
1849 * (5) check for any other interesting events that happened while
1855 ProcessConfigFile(PGC_SIGHUP);
1859 * (6) process the command.
1864 * 'F' indicates a fastpath call.
1868 * Tell the collector what we're doing
1871 pgstat_report_activity("<FASTPATH> function call");
1873 /* start an xact for this function invocation */
1874 start_xact_command();
1876 if (HandleFunctionRequest() == EOF)
1878 /* lost frontend connection during F message input */
1881 * Reset whereToSendOutput to prevent elog from
1882 * attempting to send any more messages to client.
1884 if (whereToSendOutput == Remote)
1885 whereToSendOutput = None;
1890 /* commit the function-invocation transaction */
1891 finish_xact_command();
1895 * 'Q' indicates a user query
1898 if (strspn(parser_input->data, " \t\r\n") == parser_input->len)
1901 * if there is nothing in the input buffer, don't
1902 * bother trying to parse and execute anything; just
1903 * send back a quick NullCommand response.
1905 if (IsUnderPostmaster)
1906 NullCommand(Remote);
1911 * otherwise, process the input string.
1913 * Note: transaction command start/end is now done within
1914 * pg_exec_query_string(), not here.
1916 if (Show_statement_stats)
1919 pgstat_report_activity(parser_input->data);
1921 pg_exec_query_string(parser_input,
1925 if (Show_statement_stats)
1926 ShowUsage("QUERY STATISTICS");
1931 * 'X' means that the frontend is closing down the socket.
1932 * EOF means unexpected loss of frontend connection.
1933 * Either way, perform normal shutdown.
1939 * Reset whereToSendOutput to prevent elog from attempting
1940 * to send any more messages to client.
1942 if (whereToSendOutput == Remote)
1943 whereToSendOutput = None;
1946 * NOTE: if you are tempted to add more code here, DON'T!
1947 * Whatever you had in mind to do should be set up as an
1948 * on_proc_exit or on_shmem_exit callback, instead.
1949 * Otherwise it will fail to be called during other
1950 * backend-shutdown scenarios.
1955 elog(ERROR, "unknown frontend message was received");
1958 #ifdef MEMORY_CONTEXT_CHECKING
1961 * Check all memory after each backend loop. This is a rather
1962 * weird place to do it, perhaps.
1964 MemoryContextCheck(TopMemoryContext);
1966 } /* end of input-reading loop */
1968 /* can't get here because the above loop never exits */
1971 return 1; /* keep compiler quiet */
1974 #ifndef HAVE_GETRUSAGE
1975 #include "rusagestub.h"
1977 #include <sys/resource.h>
1978 #endif /* HAVE_GETRUSAGE */
1980 struct rusage Save_r;
1981 struct timeval Save_t;
1988 getrusage(RUSAGE_SELF, &Save_r);
1989 gettimeofday(&Save_t, &tz);
1991 /* ResetTupleCount(); */
1995 ShowUsage(const char *title)
1998 struct timeval user,
2000 struct timeval elapse_t;
2005 getrusage(RUSAGE_SELF, &r);
2006 gettimeofday(&elapse_t, &tz);
2007 memcpy((char *) &user, (char *) &r.ru_utime, sizeof(user));
2008 memcpy((char *) &sys, (char *) &r.ru_stime, sizeof(sys));
2009 if (elapse_t.tv_usec < Save_t.tv_usec)
2012 elapse_t.tv_usec += 1000000;
2014 if (r.ru_utime.tv_usec < Save_r.ru_utime.tv_usec)
2016 r.ru_utime.tv_sec--;
2017 r.ru_utime.tv_usec += 1000000;
2019 if (r.ru_stime.tv_usec < Save_r.ru_stime.tv_usec)
2021 r.ru_stime.tv_sec--;
2022 r.ru_stime.tv_usec += 1000000;
2026 * the only stats we don't show here are for memory usage -- i can't
2027 * figure out how to interpret the relevant fields in the rusage
2028 * struct, and they change names across o/s platforms, anyway. if you
2029 * can figure out what the entries mean, you can somehow extract
2030 * resident set size, shared text size, and unshared data and stack
2033 initStringInfo(&str);
2035 appendStringInfo(&str, "! system usage stats:\n");
2036 appendStringInfo(&str,
2037 "!\t%ld.%06ld elapsed %ld.%06ld user %ld.%06ld system sec\n",
2038 (long int) elapse_t.tv_sec - Save_t.tv_sec,
2039 (long int) elapse_t.tv_usec - Save_t.tv_usec,
2040 (long int) r.ru_utime.tv_sec - Save_r.ru_utime.tv_sec,
2041 (long int) r.ru_utime.tv_usec - Save_r.ru_utime.tv_usec,
2042 (long int) r.ru_stime.tv_sec - Save_r.ru_stime.tv_sec,
2043 (long int) r.ru_stime.tv_usec - Save_r.ru_stime.tv_usec);
2044 appendStringInfo(&str,
2045 "!\t[%ld.%06ld user %ld.%06ld sys total]\n",
2046 (long int) user.tv_sec,
2047 (long int) user.tv_usec,
2048 (long int) sys.tv_sec,
2049 (long int) sys.tv_usec);
2050 /* BeOS has rusage but only has some fields, and not these... */
2051 #if defined(HAVE_GETRUSAGE)
2052 appendStringInfo(&str,
2053 "!\t%ld/%ld [%ld/%ld] filesystem blocks in/out\n",
2054 r.ru_inblock - Save_r.ru_inblock,
2055 /* they only drink coffee at dec */
2056 r.ru_oublock - Save_r.ru_oublock,
2057 r.ru_inblock, r.ru_oublock);
2058 appendStringInfo(&str,
2059 "!\t%ld/%ld [%ld/%ld] page faults/reclaims, %ld [%ld] swaps\n",
2060 r.ru_majflt - Save_r.ru_majflt,
2061 r.ru_minflt - Save_r.ru_minflt,
2062 r.ru_majflt, r.ru_minflt,
2063 r.ru_nswap - Save_r.ru_nswap,
2065 appendStringInfo(&str,
2066 "!\t%ld [%ld] signals rcvd, %ld/%ld [%ld/%ld] messages rcvd/sent\n",
2067 r.ru_nsignals - Save_r.ru_nsignals,
2069 r.ru_msgrcv - Save_r.ru_msgrcv,
2070 r.ru_msgsnd - Save_r.ru_msgsnd,
2071 r.ru_msgrcv, r.ru_msgsnd);
2072 appendStringInfo(&str,
2073 "!\t%ld/%ld [%ld/%ld] voluntary/involuntary context switches\n",
2074 r.ru_nvcsw - Save_r.ru_nvcsw,
2075 r.ru_nivcsw - Save_r.ru_nivcsw,
2076 r.ru_nvcsw, r.ru_nivcsw);
2077 #endif /* HAVE_GETRUSAGE */
2079 bufusage = ShowBufferUsage();
2080 appendStringInfo(&str, "! postgres usage stats:\n%s", bufusage);
2083 /* remove trailing newline */
2084 if (str.data[str.len - 1] == '\n')
2085 str.data[--str.len] = '\0';
2087 elog(LOG, "%s\n%s", title, str.data);
2092 /* ----------------------------------------------------------------
2095 * utility to get a string representation of the
2096 * command operation.
2097 * ----------------------------------------------------------------
2100 CreateCommandTag(Node *parsetree)
2104 switch (nodeTag(parsetree))
2122 case T_TransactionStmt:
2124 TransactionStmt *stmt = (TransactionStmt *) parsetree;
2126 switch (stmt->command)
2133 tag = "START TRANSACTION";
2151 case T_ClosePortalStmt:
2152 tag = "CLOSE CURSOR";
2157 FetchStmt *stmt = (FetchStmt *) parsetree;
2159 tag = (stmt->ismove) ? "MOVE" : "FETCH";
2163 case T_CreateDomainStmt:
2164 tag = "CREATE DOMAIN";
2167 case T_CreateSchemaStmt:
2168 tag = "CREATE SCHEMA";
2172 tag = "CREATE TABLE";
2176 switch (((DropStmt *) parsetree)->removeType)
2182 tag = "DROP SEQUENCE";
2194 tag = "DROP DOMAIN";
2196 case DROP_CONVERSION:
2197 tag = "DROP CONVERSION";
2200 tag = "DROP SCHEMA";
2207 case T_TruncateStmt:
2208 tag = "TRUNCATE TABLE";
2220 if (((RenameStmt *) parsetree)->renameType == RENAME_TRIGGER)
2221 tag = "ALTER TRIGGER";
2223 tag = "ALTER TABLE";
2226 case T_AlterTableStmt:
2227 tag = "ALTER TABLE";
2232 GrantStmt *stmt = (GrantStmt *) parsetree;
2234 tag = (stmt->is_grant) ? "GRANT" : "REVOKE";
2239 switch (((DefineStmt *) parsetree)->defType)
2242 tag = "CREATE AGGREGATE";
2245 tag = "CREATE OPERATOR";
2248 tag = "CREATE TYPE";
2255 case T_CompositeTypeStmt:
2256 tag = "CREATE TYPE";
2260 tag = "CREATE VIEW";
2263 case T_CreateFunctionStmt:
2264 tag = "CREATE FUNCTION";
2268 tag = "CREATE INDEX";
2272 tag = "CREATE RULE";
2275 case T_CreateSeqStmt:
2276 tag = "CREATE SEQUENCE";
2279 case T_RemoveAggrStmt:
2280 tag = "DROP AGGREGATE";
2283 case T_RemoveFuncStmt:
2284 tag = "DROP FUNCTION";
2287 case T_RemoveOperStmt:
2288 tag = "DROP OPERATOR";
2291 case T_CreatedbStmt:
2292 tag = "CREATE DATABASE";
2295 case T_AlterDatabaseSetStmt:
2296 tag = "ALTER DATABASE";
2300 tag = "DROP DATABASE";
2311 case T_UnlistenStmt:
2324 if (((VacuumStmt *) parsetree)->vacuum)
2334 case T_VariableSetStmt:
2338 case T_VariableShowStmt:
2342 case T_VariableResetStmt:
2346 case T_CreateTrigStmt:
2347 tag = "CREATE TRIGGER";
2350 case T_DropPropertyStmt:
2351 switch (((DropPropertyStmt *) parsetree)->removeType)
2354 tag = "DROP TRIGGER";
2364 case T_CreatePLangStmt:
2365 tag = "CREATE LANGUAGE";
2368 case T_DropPLangStmt:
2369 tag = "DROP LANGUAGE";
2372 case T_CreateUserStmt:
2373 tag = "CREATE USER";
2376 case T_AlterUserStmt:
2380 case T_AlterUserSetStmt:
2384 case T_DropUserStmt:
2392 case T_ConstraintsSetStmt:
2393 tag = "SET CONSTRAINTS";
2396 case T_CreateGroupStmt:
2397 tag = "CREATE GROUP";
2400 case T_AlterGroupStmt:
2401 tag = "ALTER GROUP";
2404 case T_DropGroupStmt:
2408 case T_CheckPointStmt:
2416 case T_CreateConversionStmt:
2417 tag = "CREATE CONVERSION";
2420 case T_CreateCastStmt:
2421 tag = "CREATE CAST";
2424 case T_DropCastStmt:
2428 case T_CreateOpClassStmt:
2429 tag = "CREATE OPERATOR CLASS";
2432 case T_RemoveOpClassStmt:
2433 tag = "DROP OPERATOR CLASS";
2444 case T_DeallocateStmt:
2449 elog(LOG, "CreateCommandTag: unknown parse node type %d",
2450 nodeTag(parsetree));