1 /*-------------------------------------------------------------------------
4 * POSTGRES C Backend Interface
6 * Portions Copyright (c) 1996-2000, PostgreSQL, Inc
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $Header: /cvsroot/pgsql/src/backend/tcop/postgres.c,v 1.179 2000/10/07 04:00:41 tgl Exp $
14 * this is the "main" module of the postgres backend and
15 * hence the main module of the "traffic cop".
17 *-------------------------------------------------------------------------
26 #include <sys/types.h>
28 #include <sys/socket.h>
31 #include <sys/select.h>
33 #include <netinet/in.h>
34 #include <arpa/inet.h>
40 #include "commands/async.h"
41 #include "commands/trigger.h"
42 #include "commands/variable.h"
43 #include "libpq/libpq.h"
44 #include "libpq/pqformat.h"
45 #include "libpq/pqsignal.h"
46 #include "miscadmin.h"
47 #include "nodes/print.h"
48 #include "optimizer/cost.h"
49 #include "optimizer/planner.h"
50 #include "parser/analyze.h"
51 #include "parser/parse.h"
52 #include "parser/parser.h"
53 #include "rewrite/rewriteHandler.h"
54 #include "tcop/fastpath.h"
55 #include "tcop/pquery.h"
56 #include "tcop/tcopprot.h"
57 #include "tcop/utility.h"
58 #include "storage/proc.h"
59 #include "utils/exc.h"
60 #include "utils/guc.h"
61 #include "utils/memutils.h"
62 #include "utils/ps_status.h"
63 #include "utils/temprel.h"
65 #include "mb/pg_wchar.h"
75 * XXX For ps display. That stuff needs to be cleaned up.
80 bool Log_connections = false;
82 CommandDest whereToSendOutput = Debug;
85 extern void StartupXLOG(void);
86 extern void ShutdownXLOG(void);
88 extern void HandleDeadLock(SIGNAL_ARGS);
90 extern char XLogDir[];
91 extern char ControlFilePath[];
93 static bool dontExecute = false;
95 /* note: these declarations had better match tcopprot.h */
96 DLLIMPORT sigjmp_buf Warn_restart;
98 bool Warn_restart_ready = false;
100 bool ExitAfterAbort = false;
102 static bool EchoQuery = false; /* default don't echo */
103 char pg_pathname[MAXPGPATH];
107 * people who want to use EOF should #define DONTUSENEWLINE in
111 #ifndef TCOP_DONTUSENEWLINE
112 int UseNewLine = 1; /* Use newlines query delimiters (the
116 int UseNewLine = 0; /* Use EOF as query delimiters */
118 #endif /* TCOP_DONTUSENEWLINE */
121 ** Flags for expensive function optimization -- JMH 3/9/92
125 /* ----------------------------------------------------------------
126 * decls for routines only used in this file
127 * ----------------------------------------------------------------
129 static int InteractiveBackend(StringInfo inBuf);
130 static int SocketBackend(StringInfo inBuf);
131 static int ReadCommand(StringInfo inBuf);
132 static List *pg_parse_query(char *query_string, Oid *typev, int nargs);
133 static List *pg_analyze_and_rewrite(Node *parsetree);
134 static void start_xact_command(void);
135 static void finish_xact_command(void);
136 static void SigHupHandler(SIGNAL_ARGS);
137 static void FloatExceptionHandler(SIGNAL_ARGS);
138 static void quickdie(SIGNAL_ARGS);
141 * Flag to mark SIGHUP. Whenever the main loop comes around it
142 * will reread the configuration file. (Better than doing the
143 * reading in the signal handler, ey?)
145 static volatile bool got_SIGHUP = false;
148 /* ----------------------------------------------------------------
149 * routines to obtain user input
150 * ----------------------------------------------------------------
154 * InteractiveBackend() is called for user interactive connections
155 * the string entered by the user is placed in its parameter inBuf.
157 * EOF is returned if end-of-file input is seen; time to shut down.
162 InteractiveBackend(StringInfo inBuf)
164 int c; /* character read from getc() */
165 bool end = false; /* end-of-input flag */
166 bool backslashSeen = false; /* have we seen a \ ? */
169 * display a prompt and obtain input from the user
175 /* Reset inBuf to empty */
177 inBuf->data[0] = '\0';
184 * if we are using \n as a delimiter, then read
185 * characters until the \n.
188 while ((c = getc(stdin)) != EOF)
194 /* discard backslash from inBuf */
195 inBuf->data[--inBuf->len] = '\0';
196 backslashSeen = false;
201 /* keep the newline character */
202 appendStringInfoChar(inBuf, '\n');
207 backslashSeen = true;
209 backslashSeen = false;
211 appendStringInfoChar(inBuf, (char) c);
220 * otherwise read characters until EOF.
223 while ((c = getc(stdin)) != EOF)
224 appendStringInfoChar(inBuf, (char) c);
234 * otherwise we have a user query so process it.
241 * if the query echo flag was given, print the query..
245 printf("query: %s\n", inBuf->data);
252 * SocketBackend() Is called for frontend-backend connections
254 * If the input is a query (case 'Q') then the string entered by
255 * the user is placed in its parameter inBuf.
257 * If the input is a fastpath function call (case 'F') then
258 * the function call is processed in HandleFunctionRequest()
259 * (now called from PostgresMain()).
261 * EOF is returned if the connection is lost.
266 SocketBackend(StringInfo inBuf)
272 * get input from the frontend
276 if (pq_getbytes(&qtype, 1) == EOF)
282 * 'Q': user entered a query
286 if (pq_getstr(inBuf))
292 * 'F': calling user/system functions
296 if (pq_getstr(inBuf))
297 return EOF; /* ignore "string" at start of F message */
302 * 'X': frontend is exiting
310 * otherwise we got garbage from the frontend.
312 * XXX are we certain that we want to do an elog(FATAL) here?
317 elog(FATAL, "Socket command type %c unknown", qtype);
324 * ReadCommand reads a command from either the frontend or
325 * standard input, places it in inBuf, and returns a char
326 * representing whether the string is a 'Q'uery or a 'F'astpath
327 * call. EOF is returned if end of file.
331 ReadCommand(StringInfo inBuf)
335 if (IsUnderPostmaster)
336 result = SocketBackend(inBuf);
338 result = InteractiveBackend(inBuf);
344 * Parse a query string and pass it through the rewriter.
346 * A list of Query nodes is returned, since the string might contain
347 * multiple queries and/or the rewriter might expand one query to several.
349 * NOTE: this routine is no longer used for processing interactive queries,
350 * but it is still needed for parsing of SQL function bodies.
353 pg_parse_and_rewrite(char *query_string, /* string to execute */
354 Oid *typev, /* parameter types */
355 int nargs) /* number of parameters */
357 List *raw_parsetree_list;
358 List *querytree_list;
362 * (1) parse the request string into a list of raw parse trees.
365 raw_parsetree_list = pg_parse_query(query_string, typev, nargs);
368 * (2) Do parse analysis and rule rewrite.
371 querytree_list = NIL;
372 foreach(list_item, raw_parsetree_list)
374 Node *parsetree = (Node *) lfirst(list_item);
376 querytree_list = nconc(querytree_list,
377 pg_analyze_and_rewrite(parsetree));
380 return querytree_list;
384 * Do raw parsing (only).
386 * A list of parsetrees is returned, since there might be multiple
387 * commands in the given string.
389 * NOTE: for interactive queries, it is important to keep this routine
390 * separate from the analysis & rewrite stages. Analysis and rewriting
391 * cannot be done in an aborted transaction, since they require access to
392 * database tables. So, we rely on the raw parser to determine whether
393 * we've seen a COMMIT or ABORT command; when we are in abort state, other
394 * commands are not processed any further than the raw parse stage.
397 pg_parse_query(char *query_string, Oid *typev, int nargs)
399 List *raw_parsetree_list;
401 if (Debug_print_query)
402 elog(DEBUG, "query: %s", query_string);
404 if (Show_parser_stats)
407 raw_parsetree_list = parser(query_string, typev, nargs);
409 if (Show_parser_stats)
411 fprintf(StatFp, "PARSER STATISTICS\n");
415 return raw_parsetree_list;
419 * Given a raw parsetree (gram.y output), perform parse analysis and
422 * A list of Query nodes is returned, since either the analyzer or the
423 * rewriter might expand one query to several.
425 * NOTE: for reasons mentioned above, this must be separate from raw parsing.
428 pg_analyze_and_rewrite(Node *parsetree)
430 List *querytree_list;
436 * (1) Perform parse analysis.
439 if (Show_parser_stats)
442 querytree_list = parse_analyze(parsetree, NULL);
444 if (Show_parser_stats)
446 fprintf(StatFp, "PARSE ANALYSIS STATISTICS\n");
452 * (2) Rewrite the queries, as necessary
454 * rewritten queries are collected in new_list. Note there may be
455 * more or fewer than in the original list.
459 foreach(list_item, querytree_list)
461 querytree = (Query *) lfirst(list_item);
463 if (Debug_print_parse)
465 if (Debug_pretty_print)
467 elog(DEBUG, "parse tree:");
468 nodeDisplay(querytree);
471 elog(DEBUG, "parse tree: %s", nodeToString(querytree));
474 if (querytree->commandType == CMD_UTILITY)
476 /* don't rewrite utilities, just dump 'em into new_list */
477 new_list = lappend(new_list, querytree);
481 /* rewrite regular queries */
482 List *rewritten = QueryRewrite(querytree);
484 new_list = nconc(new_list, rewritten);
488 querytree_list = new_list;
490 if (Show_parser_stats)
492 fprintf(StatFp, "REWRITER STATISTICS\n");
496 #ifdef COPY_PARSE_PLAN_TREES
497 /* Optional debugging check: pass querytree output through copyObject() */
498 new_list = (List *) copyObject(querytree_list);
499 /* This checks both copyObject() and the equal() routines... */
500 if (! equal(new_list, querytree_list))
501 elog(NOTICE, "pg_analyze_and_rewrite: copyObject failed on parse tree");
503 querytree_list = new_list;
506 if (Debug_print_rewritten)
508 if (Debug_pretty_print)
510 elog(DEBUG, "rewritten parse tree:");
511 foreach(list_item, querytree_list)
513 querytree = (Query *) lfirst(list_item);
514 nodeDisplay(querytree);
520 elog(DEBUG, "rewritten parse tree:");
521 foreach(list_item, querytree_list)
523 querytree = (Query *) lfirst(list_item);
524 elog(DEBUG, "%s", nodeToString(querytree));
529 return querytree_list;
533 /* Generate a plan for a single query. */
535 pg_plan_query(Query *querytree)
539 /* Utility commands have no plans. */
540 if (querytree->commandType == CMD_UTILITY)
543 if (Show_planner_stats)
546 /* call that optimizer */
547 plan = planner(querytree);
549 if (Show_planner_stats)
551 fprintf(stderr, "PLANNER STATISTICS\n");
555 #ifdef COPY_PARSE_PLAN_TREES
556 /* Optional debugging check: pass plan output through copyObject() */
558 Plan *new_plan = (Plan *) copyObject(plan);
560 /* equal() currently does not have routines to compare Plan nodes,
561 * so don't try to test equality here. Perhaps fix someday?
564 /* This checks both copyObject() and the equal() routines... */
565 if (! equal(new_plan, plan))
566 elog(NOTICE, "pg_plan_query: copyObject failed on plan tree");
574 * Print plan if debugging.
577 if (Debug_print_plan)
579 if (Debug_pretty_print)
581 elog(DEBUG, "plan:");
585 elog(DEBUG, "plan: %s", nodeToString(plan));
592 /* ----------------------------------------------------------------
593 * pg_exec_query_string()
595 * Takes a querystring, runs the parser/utilities or
596 * parser/planner/executor over it as necessary.
600 * At call, we are not inside a transaction command.
602 * The CurrentMemoryContext after starting a transaction command must be
603 * appropriate for execution of individual queries (typically this will be
604 * TransactionCommandContext). Note that this routine resets that context
605 * after each individual query, so don't store anything there that
606 * must outlive the call!
608 * parse_context references a context suitable for holding the
609 * parse/rewrite trees (typically this will be QueryContext).
610 * This context *must* be longer-lived than the transaction context!
611 * In fact, if the query string might contain BEGIN/COMMIT commands,
612 * parse_context had better outlive TopTransactionContext!
614 * We could have hard-wired knowledge about QueryContext and
615 * TransactionCommandContext into this routine, but it seems better
616 * not to, in case callers from outside this module need to use some
619 * ----------------------------------------------------------------
623 pg_exec_query_string(char *query_string, /* string to execute */
624 CommandDest dest, /* where results should go */
625 MemoryContext parse_context) /* context for parsetrees */
628 MemoryContext oldcontext;
629 List *parsetree_list,
633 * Start up a transaction command. All queries generated by the
634 * query_string will be in this same command block, *unless* we find
635 * a BEGIN/COMMIT/ABORT statement; we have to force a new xact command
636 * after one of those, else bad things will happen in xact.c.
637 * (Note that this will possibly change current memory context.)
639 start_xact_command();
643 * parse_context *must* be different from the execution memory context,
644 * else the context reset at the bottom of the loop will destroy the
645 * parsetree list. (We really ought to check that parse_context isn't a
646 * child of CurrentMemoryContext either, but that would take more cycles
647 * than it's likely to be worth.)
649 Assert(parse_context != CurrentMemoryContext);
652 * Switch to appropriate context for constructing parsetrees.
654 oldcontext = MemoryContextSwitchTo(parse_context);
657 * Do basic parsing of the query or queries (this should be safe
658 * even if we are in aborted transaction state!)
660 parsetree_list = pg_parse_query(query_string, NULL, 0);
663 * Switch back to execution context to enter the loop.
665 MemoryContextSwitchTo(oldcontext);
668 * Run through the parsetree(s) and process each one.
670 foreach(parsetree_item, parsetree_list)
672 Node *parsetree = (Node *) lfirst(parsetree_item);
673 bool isTransactionStmt;
674 List *querytree_list,
677 /* Transaction control statements need some special handling */
678 isTransactionStmt = IsA(parsetree, TransactionStmt);
681 * If we are in an aborted transaction, ignore all commands except
682 * COMMIT/ABORT. It is important that this test occur before we
683 * try to do parse analysis, rewrite, or planning, since all those
684 * phases try to do database accesses, which may fail in abort state.
685 * (It might be safe to allow some additional utility commands in
686 * this state, but not many...)
688 if (IsAbortedTransactionBlockState())
690 bool allowit = false;
692 if (isTransactionStmt)
694 TransactionStmt *stmt = (TransactionStmt *) parsetree;
696 switch (stmt->command)
710 * the EndCommand() stuff is to tell the frontend
711 * that the command ended. -cim 6/1/90
714 char *tag = "*ABORT STATE*";
716 elog(NOTICE, "current transaction is aborted, "
717 "queries ignored until end of transaction block");
719 EndCommand(tag, dest);
722 * We continue in the loop, on the off chance that there
723 * is a COMMIT or ROLLBACK utility command later in the
730 /* Make sure we are in a transaction command */
733 start_xact_command();
737 /* If we got a cancel signal in parsing or prior command, quit */
742 * OK to analyze and rewrite this query.
744 * Switch to appropriate context for constructing querytrees
745 * (again, these must outlive the execution context).
747 oldcontext = MemoryContextSwitchTo(parse_context);
749 querytree_list = pg_analyze_and_rewrite(parsetree);
752 * Switch back to execution context for planning and execution.
754 MemoryContextSwitchTo(oldcontext);
757 * Inner loop handles the individual queries generated from a
758 * single parsetree by analysis and rewrite.
760 foreach(querytree_item, querytree_list)
762 Query *querytree = (Query *) lfirst(querytree_item);
764 /* Make sure we are in a transaction command */
767 start_xact_command();
771 /* If we got a cancel signal in analysis or prior command, quit */
775 if (querytree->commandType == CMD_UTILITY)
778 * process utility functions (create, destroy, etc..)
781 if (Debug_print_query)
782 elog(DEBUG, "ProcessUtility: %s", query_string);
783 else if (DebugLvl > 1)
784 elog(DEBUG, "ProcessUtility");
786 ProcessUtility(querytree->utilityStmt, dest);
791 * process a plannable query.
796 plan = pg_plan_query(querytree);
798 /* if we got a cancel signal whilst planning, quit */
802 /* Initialize snapshot state for query */
808 if (Show_executor_stats)
813 /* don't execute it, just show the query plan */
814 print_plan(plan, querytree);
819 elog(DEBUG, "ProcessQuery");
820 ProcessQuery(querytree, plan, dest);
823 if (Show_executor_stats)
825 fprintf(stderr, "EXECUTOR STATISTICS\n");
831 * In a query block, we want to increment the command counter
832 * between queries so that the effects of early queries are
833 * visible to subsequent ones. In particular we'd better
834 * do so before checking constraints.
836 if (!isTransactionStmt)
837 CommandCounterIncrement();
840 * Clear the execution context to recover temporary
841 * memory used by the query. NOTE: if query string contains
842 * BEGIN/COMMIT transaction commands, execution context may
843 * now be different from what we were originally passed;
844 * so be careful to clear current context not "oldcontext".
846 Assert(parse_context != CurrentMemoryContext);
848 MemoryContextResetAndDeleteChildren(CurrentMemoryContext);
851 * If this was a transaction control statement, commit it
852 * and arrange to start a new xact command for the next
855 if (isTransactionStmt)
857 finish_xact_command();
858 xact_started = false;
861 } /* end loop over queries generated from a parsetree */
862 } /* end loop over parsetrees */
865 * Close down transaction statement, if one is open.
868 finish_xact_command();
872 * Convenience routines for starting/committing a single command.
875 start_xact_command(void)
878 elog(DEBUG, "StartTransactionCommand");
879 StartTransactionCommand();
883 finish_xact_command(void)
885 /* Invoke IMMEDIATE constraint triggers */
886 DeferredTriggerEndQuery();
888 /* Now commit the command */
890 elog(DEBUG, "CommitTransactionCommand");
891 set_ps_display("commit"); /* XXX probably the wrong place to do this */
892 CommitTransactionCommand();
894 #ifdef SHOW_MEMORY_STATS
895 /* Print mem stats at each commit for leak tracking */
897 MemoryContextStats(TopMemoryContext);
902 /* --------------------------------
903 * signal handler routines used in PostgresMain()
905 * handle_warn() catches SIGQUIT. It forces control back to the main
906 * loop, just as if an internal error (elog(ERROR,...)) had occurred.
907 * elog() used to actually use kill(2) to induce a SIGQUIT to get here!
908 * But that's not 100% reliable on some systems, so now it does its own
909 * siglongjmp() instead.
910 * We still provide the signal catcher so that an error quit can be
911 * forced externally. This should be done only with great caution,
912 * however, since an asynchronous signal could leave the system in
913 * who-knows-what inconsistent state.
915 * quickdie() occurs when signalled by the postmaster.
916 * Some backend has bought the farm,
917 * so we need to stop what we're doing and exit.
919 * die() performs an orderly cleanup via proc_exit()
920 * --------------------------------
924 handle_warn(SIGNAL_ARGS)
926 siglongjmp(Warn_restart, 1);
930 quickdie(SIGNAL_ARGS)
932 PG_SETMASK(&BlockSig);
933 elog(NOTICE, "Message from PostgreSQL backend:"
934 "\n\tThe Postmaster has informed me that some other backend"
935 " died abnormally and possibly corrupted shared memory."
936 "\n\tI have rolled back the current transaction and am"
937 " going to terminate your database system connection and exit."
938 "\n\tPlease reconnect to the database system and repeat your query.");
942 * DO NOT proc_exit(0) -- we're here because shared memory may be
943 * corrupted, so we don't want to flush any shared state to stable
944 * storage. Just nail the windows shut and get out of town.
951 * Abort transaction and exit
956 PG_SETMASK(&BlockSig);
959 * If ERROR/FATAL is in progress...
963 ExitAfterAbort = true;
966 elog(FATAL, "The system is shutting down");
969 /* signal handler for floating point exception */
971 FloatExceptionHandler(SIGNAL_ARGS)
973 elog(ERROR, "floating point exception!"
974 " The last floating point operation either exceeded legal ranges"
975 " or was a divide by zero");
978 /* signal handler for query cancel signal from postmaster */
980 QueryCancelHandler(SIGNAL_ARGS)
991 * QueryCancel flag will be reset in main loop, which we reach by
992 * longjmp from elog().
994 elog(ERROR, "Query was cancelled.");
998 SigHupHandler(SIGNAL_ARGS)
1005 usage(char *progname)
1008 "Usage: %s [options] [dbname]\n", progname);
1009 #ifdef USE_ASSERT_CHECKING
1010 fprintf(stderr, "\t-A on\t\tenable/disable assert checking\n");
1012 fprintf(stderr, "\t-B buffers\tset number of buffers in buffer pool\n");
1013 fprintf(stderr, "\t-C \t\tsuppress version info\n");
1014 fprintf(stderr, "\t-D dir\t\tdata directory\n");
1015 fprintf(stderr, "\t-E \t\techo query before execution\n");
1016 fprintf(stderr, "\t-F \t\tturn fsync off\n");
1017 fprintf(stderr, "\t-L \t\tturn off locking\n");
1018 fprintf(stderr, "\t-N \t\tdon't use newline as interactive query delimiter\n");
1019 fprintf(stderr, "\t-O \t\tallow system table structure changes\n");
1020 fprintf(stderr, "\t-Q \t\tsuppress informational messages\n");
1021 fprintf(stderr, "\t-S kbytes\tset amount of memory for sorts (in kbytes)\n");
1022 fprintf(stderr, "\t-T options\tspecify pg_options\n");
1023 fprintf(stderr, "\t-W sec\t\twait N seconds to allow attach from a debugger\n");
1024 fprintf(stderr, "\t-d [1-5]\tset debug level\n");
1025 fprintf(stderr, "\t-e \t\tturn on European date format\n");
1026 fprintf(stderr, "\t-f [s|i|n|m|h]\tforbid use of some plan types\n");
1027 fprintf(stderr, "\t-i \t\tdon't execute queries\n");
1028 fprintf(stderr, "\t-o file\t\tsend stdout and stderr to given filename\n");
1029 fprintf(stderr, "\t-p database\tbackend is started under a postmaster\n");
1030 fprintf(stderr, "\t-s \t\tshow stats after each query\n");
1031 fprintf(stderr, "\t-t [pa|pl|ex]\tshow timings after each query\n");
1032 fprintf(stderr, "\t-v version\tset protocol version being used by frontend\n");
1035 /* ----------------------------------------------------------------
1037 * postgres main loop -- all backends, interactive or otherwise start here
1039 * argc/argv are the command line arguments to be used. When being forked
1040 * by the postmaster, these are not the original argv array of the process.
1041 * real_argc/real_argv point to the original argv array, which is needed by
1042 * `ps' display on some platforms. username is the (possibly authenticated)
1043 * PostgreSQL user name to be used for the session.
1044 * ----------------------------------------------------------------
1047 PostgresMain(int argc, char *argv[], int real_argc, char *real_argv[], const char * username)
1051 const char *DBName = NULL;
1056 StringInfo parser_input;
1059 unsigned short remote_port;
1062 extern char *optarg;
1063 extern int DebugLvl;
1066 * Fire up essential subsystems: error and memory management
1068 * If we are running under the postmaster, this is done already.
1070 if (!IsUnderPostmaster)
1072 EnableExceptionHandling(true);
1073 MemoryContextInit();
1077 * Set default values for command-line options.
1082 if (!IsUnderPostmaster)
1085 if (getenv("PGDATA"))
1086 DataDir = strdup(getenv("PGDATA"));
1090 SetProcessingMode(InitProcessing);
1092 /* Check for PGDATESTYLE environment variable */
1093 set_default_datestyle();
1096 * parse command line arguments
1098 * There are now two styles of command line layout for the backend:
1100 * For interactive use (not started from postmaster) the format is
1101 * postgres [switches] [databasename]
1102 * If the databasename is omitted it is taken to be the user name.
1104 * When started from the postmaster, the format is
1105 * postgres [secure switches] -p databasename [insecure switches]
1106 * Switches appearing after -p came from the client (via "options"
1107 * field of connection request). For security reasons we restrict
1108 * what these switches can do.
1112 optind = 1; /* reset after postmaster's usage */
1114 while ((flag = getopt(argc, argv, "A:B:CD:d:Eef:FiLNOPo:p:S:st:v:W:x:-:")) != EOF)
1118 #ifdef USE_ASSERT_CHECKING
1119 assert_enabled = atoi(optarg);
1121 fprintf(stderr, "Assert checking is not compiled in\n");
1127 * specify the size of buffer pool
1131 NBuffers = atoi(optarg);
1136 * don't print version string
1142 case 'D': /* PGDATA directory */
1147 DataDir = strdup(optarg);
1151 case 'd': /* debug level */
1152 DebugLvl = atoi(optarg);
1154 Log_connections = true;
1156 Debug_print_query = true;
1158 Debug_print_parse = true;
1160 Debug_print_plan = true;
1162 Debug_print_rewritten = true;
1167 * E - echo the query the user entered
1174 /* --------------------------
1175 * Use european date formats.
1176 * --------------------------
1182 /* --------------------
1185 * 7.0 buffer manager can support different backends running
1186 * with different fsync settings, so this no longer needs
1187 * to be "if (secure)".
1188 * --------------------
1190 enableFsync = false;
1194 /* -----------------
1195 * f - forbid generation of certain plans
1200 case 's': /* seqscan */
1201 enable_seqscan = false;
1203 case 'i': /* indexscan */
1204 enable_indexscan = false;
1206 case 't': /* tidscan */
1207 enable_tidscan = false;
1209 case 'n': /* nestloop */
1210 enable_nestloop = false;
1212 case 'm': /* mergejoin */
1213 enable_mergejoin = false;
1215 case 'h': /* hashjoin */
1216 enable_hashjoin = false;
1228 /* --------------------
1230 * --------------------
1238 * N - Don't use newline as a query delimiter
1245 /* --------------------
1246 * allow system table structure modifications
1247 * --------------------
1249 if (secure) /* XXX safe to allow from client??? */
1250 allowSystemTableMods = true;
1254 /* --------------------
1255 * ignore system indexes
1256 * --------------------
1258 if (secure) /* XXX safe to allow from client??? */
1259 IgnoreSystemIndexes(true);
1264 * o - send output (stdout and stderr) to the given file
1268 StrNCpy(OutputFileName, optarg, MAXPGPATH);
1273 * p - special flag passed if backend was forked
1279 DBName = strdup(optarg);
1280 secure = false; /* subsequent switches are NOT
1287 * S - amount of sort memory to use in 1k bytes
1294 if (S >= 4 * BLCKSZ / 1024)
1301 * s - report usage statistics (timings) after each query
1304 Show_query_stats = 1;
1309 * tell postgres to report usage statistics (timings) for
1312 * -tpa[rser] = print stats for parser time of each query
1313 * -tpl[anner] = print stats for planner time of each query
1314 * -te[xecutor] = print stats for executor time of each query
1315 * caution: -s can not be used together with -t.
1321 if (optarg[1] == 'a')
1322 Show_parser_stats = 1;
1323 else if (optarg[1] == 'l')
1324 Show_planner_stats = 1;
1329 Show_executor_stats = 1;
1339 FrontendProtocol = (ProtocolVersion) atoi(optarg);
1344 * wait N seconds to allow attach from a debugger
1347 sleep(atoi(optarg));
1351 #ifdef NOT_USED /* planner/xfunc.h */
1354 * control joey hellerstein's expensive function
1359 fprintf(stderr, "only one -x flag is allowed\n");
1363 if (strcmp(optarg, "off") == 0)
1364 XfuncMode = XFUNC_OFF;
1365 else if (strcmp(optarg, "nor") == 0)
1366 XfuncMode = XFUNC_NOR;
1367 else if (strcmp(optarg, "nopull") == 0)
1368 XfuncMode = XFUNC_NOPULL;
1369 else if (strcmp(optarg, "nopm") == 0)
1370 XfuncMode = XFUNC_NOPM;
1371 else if (strcmp(optarg, "pullall") == 0)
1372 XfuncMode = XFUNC_PULLALL;
1373 else if (strcmp(optarg, "wait") == 0)
1374 XfuncMode = XFUNC_WAIT;
1377 fprintf(stderr, "use -x {off,nor,nopull,nopm,pullall,wait}\n");
1387 ParseLongOption(optarg, &name, &value);
1389 elog(ERROR, "--%s requires argument", optarg);
1391 SetConfigOption(name, value, PGC_BACKEND);
1400 * default: bad command line option
1407 if (Show_query_stats &&
1408 (Show_parser_stats || Show_planner_stats || Show_executor_stats))
1410 elog(NOTICE, "Query statistics are disabled because parser, planner, or executor statistics are on.");
1411 Show_query_stats = false;
1416 fprintf(stderr, "%s does not know where to find the database system "
1417 "data. You must specify the directory that contains the "
1418 "database system either by specifying the -D invocation "
1419 "option or by setting the PGDATA environment variable.\n\n",
1425 * 1. Set BlockSig and UnBlockSig masks. 2. Set up signal handlers. 3.
1426 * Allow only SIGUSR1 signal (we never block it) during
1429 * Note that postmaster already blocked ALL signals to make us happy.
1433 #ifdef HAVE_SIGPROCMASK
1434 sigdelset(&BlockSig, SIGUSR1);
1436 BlockSig &= ~(sigmask(SIGUSR1));
1439 PG_SETMASK(&BlockSig); /* block everything except SIGUSR1 */
1441 pqsignal(SIGHUP, SigHupHandler); /* set flag to read config file */
1442 pqsignal(SIGINT, QueryCancelHandler); /* cancel current query */
1443 pqsignal(SIGQUIT, handle_warn); /* handle error */
1444 pqsignal(SIGTERM, die);
1445 pqsignal(SIGALRM, HandleDeadLock);
1448 * Ignore failure to write to frontend. Note: if frontend closes
1449 * connection, we will notice it and exit cleanly when control next
1450 * returns to outer loop. This seems safer than forcing exit in the
1451 * midst of output during who-knows-what operation...
1453 pqsignal(SIGPIPE, SIG_IGN);
1454 pqsignal(SIGUSR1, quickdie);
1455 pqsignal(SIGUSR2, Async_NotifyHandler); /* flush also sinval cache */
1456 pqsignal(SIGFPE, FloatExceptionHandler);
1457 pqsignal(SIGCHLD, SIG_IGN); /* ignored, sent by LockOwners */
1458 pqsignal(SIGTTIN, SIG_DFL);
1459 pqsignal(SIGTTOU, SIG_DFL);
1460 pqsignal(SIGCONT, SIG_DFL);
1463 if (IsUnderPostmaster)
1465 /* noninteractive case: nothing should be left after switches */
1466 if (errs || argc != optind || DBName == NULL)
1471 pq_init(); /* initialize libpq at backend startup */
1472 whereToSendOutput = Remote;
1477 /* interactive case: database name can be last arg on command line */
1478 whereToSendOutput = Debug;
1479 if (errs || argc - optind > 1)
1484 else if (argc - optind == 1)
1485 DBName = argv[optind];
1486 else if ((DBName = username) == NULL)
1488 fprintf(stderr, "%s: user name undefined and no database specified\n",
1494 * Try to create pid file.
1496 SetPidFname(DataDir);
1497 if (SetPidFile(-getpid()))
1501 * Register clean up proc.
1503 on_proc_exit(UnlinkPidFile, 0);
1506 snprintf(XLogDir, MAXPGPATH, "%s/pg_xlog", DataDir);
1507 snprintf(ControlFilePath, MAXPGPATH, "%s/global/pg_control", DataDir);
1512 * Set up additional info.
1519 /* On some systems our dynloader code needs the executable's pathname */
1520 if (FindExec(pg_pathname, real_argv[0], "postgres") < 0)
1521 elog(FATAL, "%s: could not locate executable, bailing out...",
1525 * Find remote host name or address.
1529 if (IsUnderPostmaster)
1531 if (MyProcPort->raddr.sa.sa_family == AF_INET)
1533 struct hostent *host_ent;
1536 remote_port = ntohs(MyProcPort->raddr.in.sin_port);
1537 host_addr = inet_ntoa(MyProcPort->raddr.in.sin_addr);
1541 host_ent = gethostbyaddr((char *) &MyProcPort->raddr.in.sin_addr, sizeof(MyProcPort->raddr.in.sin_addr), AF_INET);
1545 remote_host = palloc(strlen(host_addr) + strlen(host_ent->h_name) + 3);
1546 sprintf(remote_host, "%s[%s]", host_ent->h_name, host_addr);
1550 if (remote_host == NULL)
1551 remote_host = pstrdup(host_addr);
1555 char * str = palloc(strlen(remote_host) + 7);
1556 sprintf(str, "%s:%hu", remote_host, remote_port);
1561 else /* not AF_INET */
1562 remote_host = "[local]";
1566 * Set process parameters for ps
1568 * WARNING: On some platforms the environment will be moved
1569 * around to make room for the ps display string. So any
1570 * references to optarg or getenv() from above will be invalid
1571 * after this call. Better use strdup or something similar.
1573 init_ps_display(real_argc, real_argv, username, DBName, remote_host);
1574 set_ps_display("startup");
1577 if (Log_connections)
1578 elog(DEBUG, "connection: host=%s user=%s database=%s",
1579 remote_host, username, DBName);
1582 * general initialization
1585 elog(DEBUG, "InitPostgres");
1586 InitPostgres(DBName, username);
1589 /* set default client encoding */
1591 elog(DEBUG, "reset_client_encoding");
1592 reset_client_encoding();
1595 on_shmem_exit(remove_all_temp_relations, 0);
1598 * Send this backend's cancellation info to the frontend.
1600 if (whereToSendOutput == Remote &&
1601 PG_PROTOCOL_MAJOR(FrontendProtocol) >= 2)
1605 pq_beginmessage(&buf);
1606 pq_sendbyte(&buf, 'K');
1607 pq_sendint(&buf, (int32) MyProcPid, sizeof(int32));
1608 pq_sendint(&buf, (int32) MyCancelKey, sizeof(int32));
1609 pq_endmessage(&buf);
1610 /* Need not flush since ReadyForQuery will do it. */
1613 if (!IsUnderPostmaster)
1615 puts("\nPOSTGRES backend interactive interface ");
1616 puts("$Revision: 1.179 $ $Date: 2000/10/07 04:00:41 $\n");
1620 * Initialize the deferred trigger manager
1622 if (DeferredTriggerInit() != 0)
1625 SetProcessingMode(NormalProcessing);
1628 * Create the memory context we will use in the main loop.
1630 * QueryContext is reset once per iteration of the main loop,
1631 * ie, upon completion of processing of each supplied query string.
1632 * It can therefore be used for any data that should live just as
1633 * long as the query string --- parse trees, for example.
1635 QueryContext = AllocSetContextCreate(TopMemoryContext,
1637 ALLOCSET_DEFAULT_MINSIZE,
1638 ALLOCSET_DEFAULT_INITSIZE,
1639 ALLOCSET_DEFAULT_MAXSIZE);
1642 * POSTGRES main processing loop begins here
1644 * If an exception is encountered, processing resumes here so we abort
1645 * the current transaction and start a new one.
1648 if (sigsetjmp(Warn_restart, 1) != 0)
1651 * Make sure we are in a valid memory context during recovery.
1653 * We use ErrorContext in hopes that it will have some free space
1654 * even if we're otherwise up against it...
1656 MemoryContextSwitchTo(ErrorContext);
1659 elog(DEBUG, "AbortCurrentTransaction");
1660 AbortCurrentTransaction();
1666 * If we recovered successfully, return to normal top-level context
1667 * and clear ErrorContext for next time.
1669 MemoryContextSwitchTo(TopMemoryContext);
1670 MemoryContextResetAndDeleteChildren(ErrorContext);
1674 Warn_restart_ready = true; /* we can now handle elog(ERROR) */
1676 PG_SETMASK(&UnBlockSig);
1679 * Non-error queries loop here.
1685 * Release storage left over from prior query cycle, and
1686 * create a new query input buffer in the cleared QueryContext.
1688 MemoryContextSwitchTo(QueryContext);
1689 MemoryContextResetAndDeleteChildren(QueryContext);
1691 parser_input = makeStringInfo();
1693 /* XXX this could be moved after ReadCommand below to get more
1694 * sensical behaviour */
1698 ProcessConfigFile(PGC_SIGHUP);
1702 * (1) tell the frontend we're ready for a new query.
1704 * Note: this includes fflush()'ing the last of the prior output.
1707 ReadyForQuery(whereToSendOutput);
1710 * (2) deal with pending asynchronous NOTIFY from other backends,
1711 * and enable async.c's signal handler to execute NOTIFY directly.
1714 QueryCancel = false; /* forget any earlier CANCEL signal */
1715 SetWaitingForLock(false);
1717 EnableNotifyInterrupt();
1720 * (3) read a command (loop blocks here)
1723 set_ps_display("idle");
1725 firstchar = ReadCommand(parser_input);
1727 QueryCancel = false; /* forget any earlier CANCEL signal */
1730 * (4) disable async.c's signal handler.
1733 DisableNotifyInterrupt();
1736 * (5) process the command.
1742 * 'F' indicates a fastpath call.
1746 /* start an xact for this function invocation */
1747 start_xact_command();
1749 if (HandleFunctionRequest() == EOF)
1751 /* lost frontend connection during F message input */
1755 /* commit the function-invocation transaction */
1756 finish_xact_command();
1760 * 'Q' indicates a user query
1764 if (strspn(parser_input->data, " \t\n") == parser_input->len)
1767 * if there is nothing in the input buffer, don't bother
1768 * trying to parse and execute anything; just send
1769 * back a quick NullCommand response.
1772 if (IsUnderPostmaster)
1773 NullCommand(Remote);
1778 * otherwise, process the input string.
1780 * Note: transaction command start/end is now done
1781 * within pg_exec_query_string(), not here.
1784 if (Show_query_stats)
1787 pg_exec_query_string(parser_input->data,
1791 if (Show_query_stats)
1793 fprintf(StatFp, "QUERY STATISTICS\n");
1800 * 'X' means that the frontend is closing down the socket.
1801 * EOF means unexpected loss of frontend connection.
1802 * Either way, perform normal shutdown.
1810 elog(ERROR, "unknown frontend message was received");
1813 #ifdef MEMORY_CONTEXT_CHECKING
1815 * Check all memory after each backend loop. This is a rather
1816 * weird place to do it, perhaps.
1818 MemoryContextCheck(TopMemoryContext);
1820 } /* end of input-reading loop */
1823 ExitAfterAbort = true; /* ensure we will exit if elog during abort */
1824 AbortOutOfAnyTransaction();
1825 if (!IsUnderPostmaster)
1830 ProcReleaseLocks(); /* Just to be sure... */
1833 return 1; /* keep compiler quiet */
1836 #ifndef HAVE_GETRUSAGE
1837 #include "rusagestub.h"
1839 #include <sys/resource.h>
1840 #endif /* HAVE_GETRUSAGE */
1842 struct rusage Save_r;
1843 struct timeval Save_t;
1850 getrusage(RUSAGE_SELF, &Save_r);
1851 gettimeofday(&Save_t, &tz);
1853 /* ResetTupleCount(); */
1859 struct timeval user,
1861 struct timeval elapse_t;
1865 getrusage(RUSAGE_SELF, &r);
1866 gettimeofday(&elapse_t, &tz);
1867 memmove((char *) &user, (char *) &r.ru_utime, sizeof(user));
1868 memmove((char *) &sys, (char *) &r.ru_stime, sizeof(sys));
1869 if (elapse_t.tv_usec < Save_t.tv_usec)
1872 elapse_t.tv_usec += 1000000;
1874 if (r.ru_utime.tv_usec < Save_r.ru_utime.tv_usec)
1876 r.ru_utime.tv_sec--;
1877 r.ru_utime.tv_usec += 1000000;
1879 if (r.ru_stime.tv_usec < Save_r.ru_stime.tv_usec)
1881 r.ru_stime.tv_sec--;
1882 r.ru_stime.tv_usec += 1000000;
1886 * Set output destination if not otherwise set
1892 * the only stats we don't show here are for memory usage -- i can't
1893 * figure out how to interpret the relevant fields in the rusage
1894 * struct, and they change names across o/s platforms, anyway. if you
1895 * can figure out what the entries mean, you can somehow extract
1896 * resident set size, shared text size, and unshared data and stack
1900 fprintf(StatFp, "! system usage stats:\n");
1902 "!\t%ld.%06ld elapsed %ld.%06ld user %ld.%06ld system sec\n",
1903 (long int) elapse_t.tv_sec - Save_t.tv_sec,
1904 (long int) elapse_t.tv_usec - Save_t.tv_usec,
1905 (long int) r.ru_utime.tv_sec - Save_r.ru_utime.tv_sec,
1906 (long int) r.ru_utime.tv_usec - Save_r.ru_utime.tv_usec,
1907 (long int) r.ru_stime.tv_sec - Save_r.ru_stime.tv_sec,
1908 (long int) r.ru_stime.tv_usec - Save_r.ru_stime.tv_usec);
1910 "!\t[%ld.%06ld user %ld.%06ld sys total]\n",
1911 (long int) user.tv_sec,
1912 (long int) user.tv_usec,
1913 (long int) sys.tv_sec,
1914 (long int) sys.tv_usec);
1915 /* BeOS has rusage but only has some fields, and not these... */
1916 #if defined(HAVE_GETRUSAGE) && !defined(__BEOS__)
1918 "!\t%ld/%ld [%ld/%ld] filesystem blocks in/out\n",
1919 r.ru_inblock - Save_r.ru_inblock,
1920 /* they only drink coffee at dec */
1921 r.ru_oublock - Save_r.ru_oublock,
1922 r.ru_inblock, r.ru_oublock);
1924 "!\t%ld/%ld [%ld/%ld] page faults/reclaims, %ld [%ld] swaps\n",
1925 r.ru_majflt - Save_r.ru_majflt,
1926 r.ru_minflt - Save_r.ru_minflt,
1927 r.ru_majflt, r.ru_minflt,
1928 r.ru_nswap - Save_r.ru_nswap,
1931 "!\t%ld [%ld] signals rcvd, %ld/%ld [%ld/%ld] messages rcvd/sent\n",
1932 r.ru_nsignals - Save_r.ru_nsignals,
1934 r.ru_msgrcv - Save_r.ru_msgrcv,
1935 r.ru_msgsnd - Save_r.ru_msgsnd,
1936 r.ru_msgrcv, r.ru_msgsnd);
1938 "!\t%ld/%ld [%ld/%ld] voluntary/involuntary context switches\n",
1939 r.ru_nvcsw - Save_r.ru_nvcsw,
1940 r.ru_nivcsw - Save_r.ru_nivcsw,
1941 r.ru_nvcsw, r.ru_nivcsw);
1942 #endif /* HAVE_GETRUSAGE */
1943 fprintf(StatFp, "! postgres usage stats:\n");
1944 PrintBufferUsage(StatFp);
1945 /* DisplayTupleCount(StatFp); */
1950 assertEnable(int val)
1952 assert_enabled = val;
1956 #ifdef ASSERT_CHECKING_TEST
1964 /* val != 0 should be trapped by previous Assert */
1965 elog(NOTICE, "Assert test successfull (val = %d)", val);
1968 elog(NOTICE, "Assert checking is disabled (val = %d)", val);