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.149 2000/04/04 21:44:39 tgl Exp $
14 * this is the "main" module of the postgres backend and
15 * hence the main module of the "traffic cop".
17 *-------------------------------------------------------------------------
24 #include <sys/types.h>
26 #include <sys/socket.h>
32 #include <sys/select.h>
34 #include <netinet/in.h>
35 #include <arpa/inet.h>
41 #include "commands/async.h"
42 #include "commands/trigger.h"
43 #include "commands/variable.h"
44 #include "libpq/libpq.h"
45 #include "libpq/pqformat.h"
46 #include "libpq/pqsignal.h"
47 #include "miscadmin.h"
48 #include "nodes/print.h"
49 #include "optimizer/cost.h"
50 #include "optimizer/planner.h"
51 #include "parser/parser.h"
52 #include "rewrite/rewriteHandler.h"
53 #include "tcop/fastpath.h"
54 #include "tcop/pquery.h"
55 #include "tcop/tcopprot.h"
56 #include "tcop/utility.h"
57 #include "storage/proc.h"
58 #include "utils/ps_status.h"
59 #include "utils/temprel.h"
60 #include "utils/trace.h"
62 #include "../backend/parser/parse.h"
65 #include "mb/pg_wchar.h"
69 * Trace flags, see backend/utils/misc/trace.c
71 #define Verbose pg_options[TRACE_VERBOSE]
72 #define DebugPrintQuery pg_options[TRACE_QUERY]
73 #define DebugPrintPlan pg_options[TRACE_PLAN]
74 #define DebugPrintParse pg_options[TRACE_PARSE]
75 #define DebugPrintRewrittenParsetree \
76 pg_options[TRACE_REWRITTEN]
77 #define DebugPPrintPlan pg_options[TRACE_PRETTY_PLAN]
78 #define DebugPPrintParse pg_options[TRACE_PRETTY_PARSE]
79 #define DebugPPrintRewrittenParsetree \
80 pg_options[TRACE_PRETTY_REWRITTEN]
81 #define ShowParserStats pg_options[TRACE_PARSERSTATS]
82 #define ShowPlannerStats pg_options[TRACE_PLANNERSTATS]
83 #define ShowExecutorStats pg_options[TRACE_EXECUTORSTATS]
85 #define LockDebug pg_options[TRACE_LOCKS]
88 #define DeadlockCheckTimer pg_options[OPT_DEADLOCKTIMEOUT]
89 #define HostnameLookup pg_options[OPT_HOSTLOOKUP]
90 #define ShowPortNumber pg_options[OPT_SHOWPORTNUMBER]
97 CommandDest whereToSendOutput = Debug;
99 /* Define status buffer needed by PS_SET_STATUS */
100 #ifdef PS_DEFINE_BUFFER
104 extern void BaseInit(void);
105 extern void StartupXLOG(void);
106 extern void ShutdownXLOG(void);
108 extern void HandleDeadLock(SIGNAL_ARGS);
110 extern char XLogDir[];
111 extern char ControlFilePath[];
113 extern int lockingOff;
117 static int ShowStats;
118 static bool IsEmptyQuery = false;
120 /* note: these declarations had better match tcopprot.h */
121 DLLIMPORT sigjmp_buf Warn_restart;
123 bool Warn_restart_ready = false;
124 bool InError = false;
125 bool ExitAfterAbort = false;
129 static bool EchoQuery = false; /* default don't echo */
131 char pg_pathname[MAXPGPATH];
135 * people who want to use EOF should #define DONTUSENEWLINE in
139 #ifndef TCOP_DONTUSENEWLINE
140 int UseNewLine = 1; /* Use newlines query delimiters (the
144 int UseNewLine = 0; /* Use EOF as query delimiters */
146 #endif /* TCOP_DONTUSENEWLINE */
149 ** Flags for expensive function optimization -- JMH 3/9/92
155 * Note: _exec_repeat_ defaults to 1 but may be changed
156 * by a DEBUG command. If you set this to a large
157 * number N, run a single query, and then set it
158 * back to 1 and run N queries, you can get an idea
159 * of how much time is being spent in the parser and
160 * planner b/c in the first case this overhead only
161 * happens once. -cim 6/9/91
164 int _exec_repeat_ = 1;
166 /* ----------------------------------------------------------------
167 * decls for routines only used in this file
168 * ----------------------------------------------------------------
170 static int InteractiveBackend(StringInfo inBuf);
171 static int SocketBackend(StringInfo inBuf);
172 static int ReadCommand(StringInfo inBuf);
173 static void pg_exec_query(char *query_string);
176 /* ----------------------------------------------------------------
177 * routines to obtain user input
178 * ----------------------------------------------------------------
182 * InteractiveBackend() is called for user interactive connections
183 * the string entered by the user is placed in its parameter inBuf.
185 * EOF is returned if end-of-file input is seen; time to shut down.
190 InteractiveBackend(StringInfo inBuf)
192 int c; /* character read from getc() */
193 bool end = false; /* end-of-input flag */
194 bool backslashSeen = false; /* have we seen a \ ? */
197 * display a prompt and obtain input from the user
203 /* Reset inBuf to empty */
205 inBuf->data[0] = '\0';
212 * if we are using \n as a delimiter, then read
213 * characters until the \n.
216 while ((c = getc(stdin)) != EOF)
222 /* discard backslash from inBuf */
223 inBuf->data[--inBuf->len] = '\0';
224 backslashSeen = false;
229 /* keep the newline character */
230 appendStringInfoChar(inBuf, '\n');
235 backslashSeen = true;
237 backslashSeen = false;
239 appendStringInfoChar(inBuf, (char) c);
248 * otherwise read characters until EOF.
251 while ((c = getc(stdin)) != EOF)
252 appendStringInfoChar(inBuf, (char) c);
266 * otherwise we have a user query so process it.
273 * if the query echo flag was given, print the query..
277 printf("query: %s\n", inBuf->data);
284 * SocketBackend() Is called for frontend-backend connections
286 * If the input is a query (case 'Q') then the string entered by
287 * the user is placed in its parameter inBuf.
289 * If the input is a fastpath function call (case 'F') then
290 * the function call is processed in HandleFunctionRequest()
291 * (now called from PostgresMain()).
293 * EOF is returned if the connection is lost.
298 SocketBackend(StringInfo inBuf)
304 * get input from the frontend
308 if (pq_getbytes(&qtype, 1) == EOF)
314 * 'Q': user entered a query
318 if (pq_getstr(inBuf))
324 * 'F': calling user/system functions
328 if (pq_getstr(inBuf))
329 return EOF; /* ignore "string" at start of F message */
334 * 'X': frontend is exiting
342 * otherwise we got garbage from the frontend.
344 * XXX are we certain that we want to do an elog(FATAL) here?
349 elog(FATAL, "Socket command type %c unknown", qtype);
356 * ReadCommand reads a command from either the frontend or
357 * standard input, places it in inBuf, and returns a char
358 * representing whether the string is a 'Q'uery or a 'F'astpath
359 * call. EOF is returned if end of file.
363 ReadCommand(StringInfo inBuf)
365 MemoryContext oldcontext;
368 /* Make sure any expansion of inBuf happens in permanent memory context,
369 * so that we can keep using it for future command cycles.
371 oldcontext = MemoryContextSwitchTo(TopMemoryContext);
372 if (IsUnderPostmaster)
373 result = SocketBackend(inBuf);
375 result = InteractiveBackend(inBuf);
376 MemoryContextSwitchTo(oldcontext);
382 * Parse a query string and pass it through the rewriter.
384 * A list of Query nodes is returned, since the string might contain
385 * multiple queries and/or the rewriter might expand one query to several.
388 pg_parse_and_rewrite(char *query_string, /* string to execute */
389 Oid *typev, /* argument types */
390 int nargs, /* number of arguments */
393 List *querytree_list;
394 List *querytree_list_item;
400 TPRINTF(TRACE_QUERY, "query: %s", query_string);
404 * (1) parse the request string into a list of parse trees
410 querytree_list = parser(query_string, typev, nargs);
414 fprintf(stderr, "! Parser Stats:\n");
419 * (2) rewrite the queries, as necessary
421 * rewritten queries are collected in new_list. Note there may be
422 * more or fewer than in the original list.
426 foreach(querytree_list_item, querytree_list)
428 querytree = (Query *) lfirst(querytree_list_item);
430 if (DebugPrintParse || DebugPPrintParse)
432 if (DebugPPrintParse)
434 TPRINTF(TRACE_PRETTY_PARSE, "parser outputs:");
435 nodeDisplay(querytree);
439 TPRINTF(TRACE_PARSE, "parser outputs:");
440 printf("\n%s\n\n", nodeToString(querytree));
444 if (querytree->commandType == CMD_UTILITY)
446 /* don't rewrite utilities, just dump 'em into new_list */
447 new_list = lappend(new_list, querytree);
451 /* rewrite regular queries */
452 List *rewritten = QueryRewrite(querytree);
453 new_list = nconc(new_list, rewritten);
457 querytree_list = new_list;
460 * (3) If ACL override is requested, mark queries for no ACL check.
465 foreach(querytree_list_item, querytree_list)
469 querytree = (Query *) lfirst(querytree_list_item);
471 if (querytree->commandType == CMD_UTILITY)
474 foreach(l, querytree->rtable)
476 RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
483 if (DebugPrintRewrittenParsetree || DebugPPrintRewrittenParsetree)
485 if (DebugPPrintRewrittenParsetree)
487 TPRINTF(TRACE_PRETTY_REWRITTEN, "after rewriting:");
489 foreach(querytree_list_item, querytree_list)
491 querytree = (Query *) lfirst(querytree_list_item);
492 nodeDisplay(querytree);
498 TPRINTF(TRACE_REWRITTEN, "after rewriting:");
500 foreach(querytree_list_item, querytree_list)
502 querytree = (Query *) lfirst(querytree_list_item);
503 printf("\n%s\n\n", nodeToString(querytree));
508 return querytree_list;
512 /* Generate a plan for a single query. */
514 pg_plan_query(Query *querytree)
518 /* Utility commands have no plans. */
519 if (querytree->commandType == CMD_UTILITY)
522 if (ShowPlannerStats)
525 /* call that optimizer */
526 plan = planner(querytree);
528 if (ShowPlannerStats)
530 fprintf(stderr, "! Planner Stats:\n");
535 * Print plan if debugging.
538 if (DebugPrintPlan || DebugPPrintPlan)
542 TPRINTF(TRACE_PRETTY_PLAN, "plan:");
547 TPRINTF(TRACE_PLAN, "plan:");
548 printf("\n%s\n\n", nodeToString(plan));
556 /* ----------------------------------------------------------------
559 * Takes a querystring, runs the parser/utilities or
560 * parser/planner/executor over it as necessary
561 * Begin Transaction Should have been called before this
562 * and CommitTransaction After this is called
563 * This is strictly because we do not allow for nested xactions.
565 * NON-OBVIOUS-RESTRICTIONS
566 * this function _MUST_ allocate a new "parsetree" each time,
567 * since it may be stored in a named portal and should not
570 * ----------------------------------------------------------------
574 pg_exec_query(char *query_string)
576 pg_exec_query_dest(query_string, whereToSendOutput, FALSE);
580 pg_exec_query_acl_override(char *query_string)
582 pg_exec_query_dest(query_string, whereToSendOutput, TRUE);
586 pg_exec_query_dest(char *query_string, /* string to execute */
587 CommandDest dest, /* where results should go */
588 bool aclOverride) /* to give utility commands power
591 List *querytree_list;
593 /* parse and rewrite the queries */
594 querytree_list = pg_parse_and_rewrite(query_string, NULL, 0,
598 * NOTE: we do not use "foreach" here because we want to be sure the
599 * list pointer has been advanced before the query is executed. We
600 * need to do that because VACUUM has a nasty little habit of doing
601 * CommitTransactionCommand at startup, and that will release the
602 * memory holding our parse list :-(. This needs a better
603 * solution --- currently, the code will crash if someone submits
604 * "vacuum; something-else" in a single query string. But memory
605 * allocation needs redesigned anyway, so this will have to do for
608 while (querytree_list)
610 Query *querytree = (Query *) lfirst(querytree_list);
612 querytree_list = lnext(querytree_list);
614 /* if we got a cancel signal in parsing or prior command, quit */
618 if (querytree->commandType == CMD_UTILITY)
621 * process utility functions (create, destroy, etc..)
623 * Note: we do not check for the transaction aborted state
624 * because that is done in ProcessUtility.
628 TPRINTF(TRACE_QUERY, "ProcessUtility: %s", query_string);
630 TPRINTF(TRACE_VERBOSE, "ProcessUtility");
632 ProcessUtility(querytree->utilityStmt, dest);
639 /* If aborted transaction, quit now */
640 if (IsAbortedTransactionBlockState())
643 * the EndCommand() stuff is to tell the frontend
644 * that the command ended. -cim 6/1/90
647 char *tag = "*ABORT STATE*";
649 elog(NOTICE, "current transaction is aborted, "
650 "queries ignored until end of transaction block");
652 EndCommand(tag, dest);
657 plan = pg_plan_query(querytree);
659 /* if we got a cancel signal whilst planning, quit */
663 /* Initialize snapshot state for query */
669 if (ShowExecutorStats)
672 for (j = 0; j < _exec_repeat_; j++)
675 TPRINTF(TRACE_VERBOSE, "ProcessQuery");
676 ProcessQuery(querytree, plan, dest);
679 if (ShowExecutorStats)
681 fprintf(stderr, "! Executor Stats:\n");
687 * In a query block, we want to increment the command counter
688 * between queries so that the effects of early queries are
689 * visible to subsequent ones.
692 CommandCounterIncrement();
696 /* --------------------------------
697 * signal handler routines used in PostgresMain()
699 * handle_warn() catches SIGQUIT. It forces control back to the main
700 * loop, just as if an internal error (elog(ERROR,...)) had occurred.
701 * elog() used to actually use kill(2) to induce a SIGQUIT to get here!
702 * But that's not 100% reliable on some systems, so now it does its own
703 * siglongjmp() instead.
704 * We still provide the signal catcher so that an error quit can be
705 * forced externally. This should be done only with great caution,
706 * however, since an asynchronous signal could leave the system in
707 * who-knows-what inconsistent state.
709 * quickdie() occurs when signalled by the postmaster.
710 * Some backend has bought the farm,
711 * so we need to stop what we're doing and exit.
713 * die() performs an orderly cleanup via proc_exit()
714 * --------------------------------
718 handle_warn(SIGNAL_ARGS)
720 siglongjmp(Warn_restart, 1);
724 quickdie(SIGNAL_ARGS)
726 PG_SETMASK(&BlockSig);
727 elog(NOTICE, "Message from PostgreSQL backend:"
728 "\n\tThe Postmaster has informed me that some other backend"
729 " died abnormally and possibly corrupted shared memory."
730 "\n\tI have rolled back the current transaction and am"
731 " going to terminate your database system connection and exit."
732 "\n\tPlease reconnect to the database system and repeat your query.");
736 * DO NOT proc_exit(0) -- we're here because shared memory may be
737 * corrupted, so we don't want to flush any shared state to stable
738 * storage. Just nail the windows shut and get out of town.
745 * Abort transaction and exit
750 PG_SETMASK(&BlockSig);
752 * If ERROR/FATAL is in progress...
756 ExitAfterAbort = true;
759 elog(FATAL, "The system is shutting down");
762 /* signal handler for floating point exception */
764 FloatExceptionHandler(SIGNAL_ARGS)
766 elog(ERROR, "floating point exception!"
767 " The last floating point operation either exceeded legal ranges"
768 " or was a divide by zero");
771 /* signal handler for query cancel signal from postmaster */
773 QueryCancelHandler(SIGNAL_ARGS)
784 * QueryCancel flag will be reset in main loop, which we reach by
785 * longjmp from elog().
787 elog(ERROR, "Query was cancelled.");
792 usage(char *progname)
795 "Usage: %s [options] [dbname]\n", progname);
796 #ifdef USE_ASSERT_CHECKING
797 fprintf(stderr, "\t-A on\t\tenable/disable assert checking\n");
799 fprintf(stderr, "\t-B buffers\tset number of buffers in buffer pool\n");
800 fprintf(stderr, "\t-C \t\tsuppress version info\n");
801 fprintf(stderr, "\t-D dir\t\tdata directory\n");
802 fprintf(stderr, "\t-E \t\techo query before execution\n");
803 fprintf(stderr, "\t-F \t\tturn off fsync\n");
804 #ifdef LOCK_MGR_DEBUG
805 fprintf(stderr, "\t-K lev\t\tset locking debug level [0|1|2]\n");
807 fprintf(stderr, "\t-L \t\tturn off locking\n");
808 fprintf(stderr, "\t-N \t\tdon't use newline as interactive query delimiter\n");
809 fprintf(stderr, "\t-O \t\tallow system table structure changes\n");
810 fprintf(stderr, "\t-Q \t\tsuppress informational messages\n");
811 fprintf(stderr, "\t-S kbytes\tset amount of memory for sorts (in kbytes)\n");
812 fprintf(stderr, "\t-T options\tspecify pg_options\n");
813 fprintf(stderr, "\t-W sec\t\twait N seconds to allow attach from a debugger\n");
814 fprintf(stderr, "\t-d [1-5]\tset debug level\n");
815 fprintf(stderr, "\t-e \t\tturn on European date format\n");
816 fprintf(stderr, "\t-f [s|i|n|m|h]\tforbid use of some plan types\n");
817 fprintf(stderr, "\t-i \t\tdon't execute queries\n");
818 fprintf(stderr, "\t-o file\t\tsend stdout and stderr to given filename\n");
819 fprintf(stderr, "\t-p database\tbackend is started under a postmaster\n");
820 fprintf(stderr, "\t-s \t\tshow stats after each query\n");
821 fprintf(stderr, "\t-t [pa|pl|ex]\tshow timings after each query\n");
822 fprintf(stderr, "\t-v version\tset protocol version being used by frontend\n");
825 /* ----------------------------------------------------------------
828 * all backends, interactive or otherwise start here
830 * argc/argv are the command line arguments to be used. When being forked
831 * by the postmaster, these are not the original argv array of the process.
832 * real_argc/real_argv point to the original argv array, which is needed by
833 * PS_INIT_STATUS on some platforms.
834 * ----------------------------------------------------------------
837 PostgresMain(int argc, char *argv[], int real_argc, char *real_argv[])
846 StringInfo parser_input;
849 /* Used if verbose is set, must be initialized */
850 char *remote_info = "interactive";
851 char *remote_host = "";
852 unsigned short remote_port = 0;
859 * Set default values for command-line options.
861 IsUnderPostmaster = false;
863 ShowParserStats = ShowPlannerStats = ShowExecutorStats = 0;
864 DeadlockCheckTimer = DEADLOCK_CHECK_TIMER;
867 #ifdef LOCK_MGR_DEBUG
870 DataDir = getenv("PGDATA");
872 SetProcessingMode(InitProcessing);
874 /* Check for PGDATESTYLE environment variable */
875 set_default_datestyle();
878 * Read default pg_options from file $DATADIR/pg_options.
884 * parse command line arguments
886 * There are now two styles of command line layout for the backend:
888 * For interactive use (not started from postmaster) the format is
889 * postgres [switches] [databasename]
890 * If the databasename is omitted it is taken to be the user name.
892 * When started from the postmaster, the format is
893 * postgres [secure switches] -p databasename [insecure switches]
894 * Switches appearing after -p came from the client (via "options"
895 * field of connection request). For security reasons we restrict
896 * what these switches can do.
900 optind = 1; /* reset after postmaster's usage */
902 while ((flag = getopt(argc, argv,
903 "A:B:CD:d:EeFf:iK:LNOPo:p:QS:sT:t:v:W:x:"))
909 * enable/disable assert checking.
912 #ifdef USE_ASSERT_CHECKING
913 assert_enabled = atoi(optarg);
915 fprintf(stderr, "Assert checking is not enabled\n");
921 * specify the size of buffer pool
925 NBuffers = atoi(optarg);
930 * don't print version string
936 case 'D': /* PGDATA directory */
942 /* must be done after DataDir is defined */
949 case 'd': /* debug level */
950 DebugLvl = atoi(optarg);
954 DebugPrintQuery = true;
956 DebugPrintParse = true;
958 DebugPrintPlan = true;
960 DebugPPrintRewrittenParsetree = true;
965 * E - echo the query the user entered
972 /* --------------------------
973 * Use european date formats.
974 * --------------------------
980 /* --------------------
982 * --------------------
990 * f - forbid generation of certain plans
995 case 's': /* seqscan */
996 enable_seqscan = false;
998 case 'i': /* indexscan */
999 enable_indexscan = false;
1001 case 't': /* tidscan */
1002 enable_tidscan = false;
1004 case 'n': /* nestloop */
1005 enable_nestloop = false;
1007 case 'm': /* mergejoin */
1008 enable_mergejoin = false;
1010 case 'h': /* hashjoin */
1011 enable_hashjoin = false;
1023 #ifdef LOCK_MGR_DEBUG
1024 LockDebug = atoi(optarg);
1026 fprintf(stderr, "Lock debug not compiled in\n");
1031 /* --------------------
1033 * --------------------
1041 * N - Don't use newline as a query delimiter
1048 /* --------------------
1049 * allow system table structure modifications
1050 * --------------------
1052 if (secure) /* XXX safe to allow from client??? */
1053 allowSystemTableMods = true;
1057 /* --------------------
1058 * ignore system indexes
1059 * --------------------
1061 if (secure) /* XXX safe to allow from client??? */
1062 IgnoreSystemIndexes(true);
1067 * o - send output (stdout and stderr) to the given file
1071 StrNCpy(OutputFileName, optarg, MAXPGPATH);
1076 * p - special flag passed if backend was forked
1082 IsUnderPostmaster = true;
1084 secure = false; /* subsequent switches are NOT
1091 * Q - set Quiet mode (reduce debugging output)
1099 * S - amount of sort memory to use in 1k bytes
1106 if (S >= 4 * BLCKSZ / 1024)
1113 * s - report usage statistics (timings) after each query
1122 * T - tracing options
1125 parse_options(optarg, secure);
1130 * tell postgres to report usage statistics (timings) for
1133 * -tpa[rser] = print stats for parser time of each query
1134 * -tpl[anner] = print stats for planner time of each query
1135 * -te[xecutor] = print stats for executor time of each query
1136 * caution: -s can not be used together with -t.
1143 if (optarg[1] == 'a')
1144 ShowParserStats = 1;
1145 else if (optarg[1] == 'l')
1146 ShowPlannerStats = 1;
1151 ShowExecutorStats = 1;
1161 FrontendProtocol = (ProtocolVersion) atoi(optarg);
1166 * wait N seconds to allow attach from a debugger
1169 sleep(atoi(optarg));
1173 #ifdef NOT_USED /* planner/xfunc.h */
1176 * control joey hellerstein's expensive function
1181 fprintf(stderr, "only one -x flag is allowed\n");
1185 if (strcmp(optarg, "off") == 0)
1186 XfuncMode = XFUNC_OFF;
1187 else if (strcmp(optarg, "nor") == 0)
1188 XfuncMode = XFUNC_NOR;
1189 else if (strcmp(optarg, "nopull") == 0)
1190 XfuncMode = XFUNC_NOPULL;
1191 else if (strcmp(optarg, "nopm") == 0)
1192 XfuncMode = XFUNC_NOPM;
1193 else if (strcmp(optarg, "pullall") == 0)
1194 XfuncMode = XFUNC_PULLALL;
1195 else if (strcmp(optarg, "wait") == 0)
1196 XfuncMode = XFUNC_WAIT;
1199 fprintf(stderr, "use -x {off,nor,nopull,nopm,pullall,wait}\n");
1207 * default: bad command line option
1215 (ShowParserStats || ShowPlannerStats || ShowExecutorStats))
1217 fprintf(stderr, "-s can not be used together with -t.\n");
1223 fprintf(stderr, "%s does not know where to find the database system "
1224 "data. You must specify the directory that contains the "
1225 "database system either by specifying the -D invocation "
1226 "option or by setting the PGDATA environment variable.\n\n",
1232 * 1. Set BlockSig and UnBlockSig masks.
1233 * 2. Set up signal handlers.
1234 * 3. Allow only SIGUSR1 signal (we never block it)
1235 * during initialization.
1237 * Note that postmaster already blocked ALL signals to make us happy.
1239 if (!IsUnderPostmaster)
1242 PG_SETMASK(&BlockSig);
1245 #ifdef HAVE_SIGPROCMASK
1246 sigdelset(&BlockSig, SIGUSR1);
1248 BlockSig &= ~(sigmask(SIGUSR1));
1251 pqsignal(SIGHUP, read_pg_options); /* update pg_options from file */
1252 pqsignal(SIGINT, QueryCancelHandler); /* cancel current query */
1253 pqsignal(SIGQUIT, handle_warn); /* handle error */
1254 pqsignal(SIGTERM, die);
1255 pqsignal(SIGALRM, HandleDeadLock);
1257 * Ignore failure to write to frontend. Note: if frontend closes
1258 * connection, we will notice it and exit cleanly when control next
1259 * returns to outer loop. This seems safer than forcing exit in the
1260 * midst of output during who-knows-what operation...
1262 pqsignal(SIGPIPE, SIG_IGN);
1263 pqsignal(SIGUSR1, quickdie);
1264 pqsignal(SIGUSR2, Async_NotifyHandler); /* flush also sinval cache */
1265 pqsignal(SIGFPE, FloatExceptionHandler);
1266 pqsignal(SIGCHLD, SIG_IGN); /* ignored, sent by LockOwners */
1267 pqsignal(SIGTTIN, SIG_DFL);
1268 pqsignal(SIGTTOU, SIG_DFL);
1269 pqsignal(SIGCONT, SIG_DFL);
1271 PG_SETMASK(&BlockSig); /* block everything except SIGUSR1 */
1274 * Get user name (needed now in case it is the default database name)
1275 * and check command line validity
1278 userName = GetPgUserName();
1280 if (IsUnderPostmaster)
1282 /* noninteractive case: nothing should be left after switches */
1283 if (errs || argc != optind || DBName == NULL)
1288 pq_init(); /* initialize libpq at backend startup */
1289 whereToSendOutput = Remote;
1294 /* interactive case: database name can be last arg on command line */
1295 whereToSendOutput = Debug;
1296 if (errs || argc - optind > 1)
1301 else if (argc - optind == 1)
1302 DBName = argv[optind];
1303 else if ((DBName = userName) == NULL)
1305 fprintf(stderr, "%s: USER undefined and no database specified\n",
1311 * Try to create pid file.
1313 SetPidFname(DataDir);
1314 if (SetPidFile(-getpid())) {
1318 * Register clean up proc.
1320 on_proc_exit(UnlinkPidFile, NULL);
1323 snprintf(XLogDir, MAXPGPATH, "%s%cpg_xlog",
1325 snprintf(ControlFilePath, MAXPGPATH, "%s%cpg_control",
1331 * Set up additional info.
1338 /* On some systems our dynloader code needs the executable's pathname */
1339 if (FindExec(pg_pathname, argv[0], "postgres") < 0)
1340 elog(FATAL, "%s: could not locate executable, bailing out...",
1344 * Find remote host name or address.
1346 if (IsUnderPostmaster)
1348 switch (MyProcPort->raddr.sa.sa_family)
1350 struct hostent *host_ent;
1353 remote_info = remote_host = malloc(48);
1354 remote_port = ntohs(MyProcPort->raddr.in.sin_port);
1355 strcpy(remote_host, inet_ntoa(MyProcPort->raddr.in.sin_addr));
1359 gethostbyaddr((char *) &MyProcPort->raddr.in.sin_addr,
1360 sizeof(MyProcPort->raddr.in.sin_addr),
1364 strncpy(remote_host, host_ent->h_name, 48);
1365 *(remote_host + 47) = '\0';
1370 remote_info = malloc(strlen(remote_host) + 6);
1371 sprintf(remote_info, "%s:%d", remote_host, remote_port);
1375 remote_info = remote_host = "localhost";
1378 remote_info = remote_host = "unknown";
1382 * Set process params for ps
1384 PS_INIT_STATUS(real_argc, real_argv, argv[0],
1385 remote_info, userName, DBName);
1386 PS_SET_STATUS("startup");
1398 TPRINTF(TRACE_VERBOSE, "started: host=%s user=%s database=%s",
1399 remote_host, userName, DBName);
1403 TPRINTF(TRACE_VERBOSE, "debug info:");
1404 TPRINTF(TRACE_VERBOSE, "\tUser = %s", userName);
1405 TPRINTF(TRACE_VERBOSE, "\tRemoteHost = %s", remote_host);
1406 TPRINTF(TRACE_VERBOSE, "\tRemotePort = %d", remote_port);
1407 TPRINTF(TRACE_VERBOSE, "\tDatabaseName = %s", DBName);
1408 TPRINTF(TRACE_VERBOSE, "\tDebug Level = %d", DebugLvl);
1409 TPRINTF(TRACE_VERBOSE, "\tNoversion = %c", Noversion ? 't' : 'f');
1410 TPRINTF(TRACE_VERBOSE, "\ttimings = %c", ShowStats ? 't' : 'f');
1411 TPRINTF(TRACE_VERBOSE, "\tdates = %s",
1412 EuroDates ? "European" : "Normal");
1413 TPRINTF(TRACE_VERBOSE, "\tbufsize = %d", NBuffers);
1414 TPRINTF(TRACE_VERBOSE, "\tsortmem = %d", SortMem);
1415 TPRINTF(TRACE_VERBOSE, "\tquery echo = %c", EchoQuery ? 't' : 'f');
1421 * general initialization
1425 TPRINTF(TRACE_VERBOSE, "InitPostgres");
1427 InitPostgres(DBName);
1430 /* set default client encoding */
1432 TPRINTF(TRACE_VERBOSE, "reset_client_encoding()..");
1433 reset_client_encoding();
1435 TPRINTF(TRACE_VERBOSE, "reset_client_encoding() done.");
1438 on_shmem_exit(remove_all_temp_relations, NULL);
1441 MemoryContext oldcontext = MemoryContextSwitchTo(TopMemoryContext);
1442 parser_input = makeStringInfo(); /* initialize input buffer */
1443 MemoryContextSwitchTo(oldcontext);
1447 * Send this backend's cancellation info to the frontend.
1449 if (whereToSendOutput == Remote &&
1450 PG_PROTOCOL_MAJOR(FrontendProtocol) >= 2)
1454 pq_beginmessage(&buf);
1455 pq_sendbyte(&buf, 'K');
1456 pq_sendint(&buf, (int32) MyProcPid, sizeof(int32));
1457 pq_sendint(&buf, (int32) MyCancelKey, sizeof(int32));
1458 pq_endmessage(&buf);
1459 /* Need not flush since ReadyForQuery will do it. */
1462 if (!IsUnderPostmaster)
1464 puts("\nPOSTGRES backend interactive interface ");
1465 puts("$Revision: 1.149 $ $Date: 2000/04/04 21:44:39 $\n");
1469 * Initialize the deferred trigger manager
1471 if (DeferredTriggerInit() != 0)
1474 SetProcessingMode(NormalProcessing);
1477 * POSTGRES main processing loop begins here
1479 * If an exception is encountered, processing resumes here
1480 * so we abort the current transaction and start a new one.
1483 if (sigsetjmp(Warn_restart, 1) != 0)
1488 TPRINTF(TRACE_VERBOSE, "AbortCurrentTransaction");
1490 AbortCurrentTransaction();
1494 ProcReleaseLocks(); /* Just to be sure... */
1499 Warn_restart_ready = true; /* we can now handle elog(ERROR) */
1501 PG_SETMASK(&UnBlockSig);
1504 * Non-error queries loop here.
1509 PS_SET_STATUS("idle");
1512 * (1) tell the frontend we're ready for a new query.
1514 * Note: this includes fflush()'ing the last of the prior output.
1517 ReadyForQuery(whereToSendOutput);
1520 * (2) deal with pending asynchronous NOTIFY from other backends,
1521 * and enable async.c's signal handler to execute NOTIFY directly.
1524 QueryCancel = false; /* forget any earlier CANCEL signal */
1525 SetWaitingForLock(false);
1527 EnableNotifyInterrupt();
1530 * (3) read a command.
1533 firstchar = ReadCommand(parser_input);
1535 QueryCancel = false; /* forget any earlier CANCEL signal */
1538 * (4) disable async.c's signal handler.
1541 DisableNotifyInterrupt();
1544 * (5) process the command.
1550 * 'F' indicates a fastpath call.
1551 * XXX HandleFunctionRequest
1555 IsEmptyQuery = false;
1557 /* start an xact for this function invocation */
1559 TPRINTF(TRACE_VERBOSE, "StartTransactionCommand");
1560 StartTransactionCommand();
1562 if (HandleFunctionRequest() == EOF)
1564 /* lost frontend connection during F message input */
1571 * 'Q' indicates a user query
1575 if (strspn(parser_input->data, " \t\n") == parser_input->len)
1578 * if there is nothing in the input buffer, don't bother
1579 * trying to parse and execute anything..
1582 IsEmptyQuery = true;
1587 * otherwise, process the input string.
1590 IsEmptyQuery = false;
1594 /* start an xact for this query */
1596 TPRINTF(TRACE_VERBOSE, "StartTransactionCommand");
1597 StartTransactionCommand();
1599 pg_exec_query(parser_input->data);
1602 * Invoke IMMEDIATE constraint triggers
1605 DeferredTriggerEndQuery();
1613 * 'X' means that the frontend is closing down the socket.
1614 * EOF means unexpected loss of frontend connection.
1615 * Either way, perform normal shutdown.
1620 if (!IsUnderPostmaster)
1627 elog(ERROR, "unknown frontend message was received");
1631 * (6) commit the current transaction
1633 * Note: if we had an empty input buffer, then we didn't
1634 * call pg_exec_query, so we don't bother to commit this transaction.
1640 TPRINTF(TRACE_VERBOSE, "CommitTransactionCommand");
1641 PS_SET_STATUS("commit");
1642 CommitTransactionCommand();
1646 if (IsUnderPostmaster)
1647 NullCommand(Remote);
1649 } /* infinite for-loop */
1651 proc_exit(0); /* shouldn't get here... */
1655 #ifndef HAVE_GETRUSAGE
1656 #include "rusagestub.h"
1658 #include <sys/resource.h>
1659 #endif /* HAVE_GETRUSAGE */
1661 struct rusage Save_r;
1662 struct timeval Save_t;
1669 getrusage(RUSAGE_SELF, &Save_r);
1670 gettimeofday(&Save_t, &tz);
1672 /* ResetTupleCount(); */
1678 struct timeval user,
1680 struct timeval elapse_t;
1684 getrusage(RUSAGE_SELF, &r);
1685 gettimeofday(&elapse_t, &tz);
1686 memmove((char *) &user, (char *) &r.ru_utime, sizeof(user));
1687 memmove((char *) &sys, (char *) &r.ru_stime, sizeof(sys));
1688 if (elapse_t.tv_usec < Save_t.tv_usec)
1691 elapse_t.tv_usec += 1000000;
1693 if (r.ru_utime.tv_usec < Save_r.ru_utime.tv_usec)
1695 r.ru_utime.tv_sec--;
1696 r.ru_utime.tv_usec += 1000000;
1698 if (r.ru_stime.tv_usec < Save_r.ru_stime.tv_usec)
1700 r.ru_stime.tv_sec--;
1701 r.ru_stime.tv_usec += 1000000;
1705 * the only stats we don't show here are for memory usage -- i can't
1706 * figure out how to interpret the relevant fields in the rusage
1707 * struct, and they change names across o/s platforms, anyway. if you
1708 * can figure out what the entries mean, you can somehow extract
1709 * resident set size, shared text size, and unshared data and stack
1713 fprintf(StatFp, "! system usage stats:\n");
1715 "!\t%ld.%06ld elapsed %ld.%06ld user %ld.%06ld system sec\n",
1716 (long int) elapse_t.tv_sec - Save_t.tv_sec,
1717 (long int) elapse_t.tv_usec - Save_t.tv_usec,
1718 (long int) r.ru_utime.tv_sec - Save_r.ru_utime.tv_sec,
1719 (long int) r.ru_utime.tv_usec - Save_r.ru_utime.tv_usec,
1720 (long int) r.ru_stime.tv_sec - Save_r.ru_stime.tv_sec,
1721 (long int) r.ru_stime.tv_usec - Save_r.ru_stime.tv_usec);
1723 "!\t[%ld.%06ld user %ld.%06ld sys total]\n",
1724 (long int) user.tv_sec,
1725 (long int) user.tv_usec,
1726 (long int) sys.tv_sec,
1727 (long int) sys.tv_usec);
1728 #ifdef HAVE_GETRUSAGE
1730 "!\t%ld/%ld [%ld/%ld] filesystem blocks in/out\n",
1731 r.ru_inblock - Save_r.ru_inblock,
1732 /* they only drink coffee at dec */
1733 r.ru_oublock - Save_r.ru_oublock,
1734 r.ru_inblock, r.ru_oublock);
1736 "!\t%ld/%ld [%ld/%ld] page faults/reclaims, %ld [%ld] swaps\n",
1737 r.ru_majflt - Save_r.ru_majflt,
1738 r.ru_minflt - Save_r.ru_minflt,
1739 r.ru_majflt, r.ru_minflt,
1740 r.ru_nswap - Save_r.ru_nswap,
1743 "!\t%ld [%ld] signals rcvd, %ld/%ld [%ld/%ld] messages rcvd/sent\n",
1744 r.ru_nsignals - Save_r.ru_nsignals,
1746 r.ru_msgrcv - Save_r.ru_msgrcv,
1747 r.ru_msgsnd - Save_r.ru_msgsnd,
1748 r.ru_msgrcv, r.ru_msgsnd);
1750 "!\t%ld/%ld [%ld/%ld] voluntary/involuntary context switches\n",
1751 r.ru_nvcsw - Save_r.ru_nvcsw,
1752 r.ru_nivcsw - Save_r.ru_nivcsw,
1753 r.ru_nvcsw, r.ru_nivcsw);
1754 #endif /* HAVE_GETRUSAGE */
1755 fprintf(StatFp, "! postgres usage stats:\n");
1756 PrintBufferUsage(StatFp);
1757 /* DisplayTupleCount(StatFp); */
1760 #ifdef USE_ASSERT_CHECKING
1762 assertEnable(int val)
1764 assert_enabled = val;
1768 #ifdef ASSERT_CHECKING_TEST
1776 /* val != 0 should be trapped by previous Assert */
1777 elog(NOTICE, "Assert test successfull (val = %d)", val);
1780 elog(NOTICE, "Assert checking is disabled (val = %d)", val);