postgres.c 42.9 KB
Newer Older
1 2
/*-------------------------------------------------------------------------
 *
3
 * postgres.c
4
 *	  POSTGRES C Backend Interface
5
 *
B
Add:  
Bruce Momjian 已提交
6 7
 * Portions Copyright (c) 1996-2000, PostgreSQL, Inc
 * Portions Copyright (c) 1994, Regents of the University of California
8 9 10
 *
 *
 * IDENTIFICATION
11
 *	  $Header: /cvsroot/pgsql/src/backend/tcop/postgres.c,v 1.172 2000/08/27 19:00:31 petere Exp $
12 13
 *
 * NOTES
14 15
 *	  this is the "main" module of the postgres backend and
 *	  hence the main module of the "traffic cop".
16 17 18
 *
 *-------------------------------------------------------------------------
 */
B
Bruce Momjian 已提交
19

20 21
#include "postgres.h"

B
Bruce Momjian 已提交
22
#include <unistd.h>
23
#include <signal.h>
24 25
#include <time.h>
#include <sys/time.h>
B
Bruce Momjian 已提交
26 27
#include <sys/types.h>
#include <fcntl.h>
28
#include <sys/socket.h>
29
#include <errno.h>
30
#if HAVE_SYS_SELECT_H
31
#include <sys/select.h>
32
#endif	 /* aix */
M
 
Marc G. Fournier 已提交
33 34 35
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
36
#ifdef HAVE_GETOPT_H
B
Bruce Momjian 已提交
37
#include <getopt.h>
38
#endif
39 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"
B
Bruce Momjian 已提交
46
#include "miscadmin.h"
47 48
#include "nodes/print.h"
#include "optimizer/cost.h"
49
#include "optimizer/planner.h"
50
#include "parser/parser.h"
B
Bruce Momjian 已提交
51
#include "rewrite/rewriteHandler.h"
52 53
#include "tcop/fastpath.h"
#include "tcop/pquery.h"
B
Bruce Momjian 已提交
54
#include "tcop/tcopprot.h"
55
#include "tcop/utility.h"
56
#include "storage/proc.h"
57 58
#include "utils/exc.h"
#include "utils/guc.h"
59
#include "utils/memutils.h"
M
 
Marc G. Fournier 已提交
60
#include "utils/ps_status.h"
61
#include "utils/temprel.h"
62
#ifdef MULTIBYTE
B
Bruce Momjian 已提交
63
#include "mb/pg_wchar.h"
64 65
#endif

M
 
Marc G. Fournier 已提交
66

67
/* ----------------
68
 *		global variables
69 70
 * ----------------
 */
71

72 73 74 75 76 77 78 79
/*
 * XXX For ps display. That stuff needs to be cleaned up.
 */
bool HostnameLookup;
bool ShowPortNumber;

bool Log_connections = false;

80
CommandDest whereToSendOutput = Debug;
81

82

83 84
extern void StartupXLOG(void);
extern void ShutdownXLOG(void);
85

86
extern void HandleDeadLock(int signum);
87

88 89
extern char XLogDir[];
extern char ControlFilePath[];
90

91
static bool	dontExecute = false;
92

93
static bool IsEmptyQuery = false;
94

95
/* note: these declarations had better match tcopprot.h */
B
Bruce Momjian 已提交
96
DLLIMPORT sigjmp_buf Warn_restart;
97

98
bool		Warn_restart_ready = false;
99 100
bool		InError = false;
bool		ExitAfterAbort = false;
101

102
static bool EchoQuery = false;	/* default don't echo */
103
char		pg_pathname[MAXPGPATH];
104
FILE	   *StatFp = NULL;
105

106
/* ----------------
107 108
 *		people who want to use EOF should #define DONTUSENEWLINE in
 *		tcop/tcopdebug.h
109 110 111
 * ----------------
 */
#ifndef TCOP_DONTUSENEWLINE
112
int			UseNewLine = 1;		/* Use newlines query delimiters (the
113 114
								 * default) */

115
#else
116
int			UseNewLine = 0;		/* Use EOF as query delimiters */
117

118
#endif	 /* TCOP_DONTUSENEWLINE */
119 120 121 122

/*
** Flags for expensive function optimization -- JMH 3/9/92
*/
123
int			XfuncMode = 0;
124 125

/* ----------------------------------------------------------------
126
 *		decls for routines only used in this file
127 128
 * ----------------------------------------------------------------
 */
129 130 131
static int	InteractiveBackend(StringInfo inBuf);
static int	SocketBackend(StringInfo inBuf);
static int	ReadCommand(StringInfo inBuf);
132 133 134
static void SigHupHandler(int signum);
static void FloatExceptionHandler(int signum);
static void quickdie(int signum);
135 136 137 138 139 140 141

/*
 * Flag to mark SIGHUP. Whenever the main loop comes around it
 * will reread the configuration file. (Better than doing the
 * reading in the signal handler, ey?)
 */
static volatile bool got_SIGHUP = false;
142 143 144


/* ----------------------------------------------------------------
145
 *		routines to obtain user input
146 147 148 149
 * ----------------------------------------------------------------
 */

/* ----------------
150 151
 *	InteractiveBackend() is called for user interactive connections
 *	the string entered by the user is placed in its parameter inBuf.
152
 *
153
 *	EOF is returned if end-of-file input is seen; time to shut down.
154 155 156
 * ----------------
 */

157
static int
158
InteractiveBackend(StringInfo inBuf)
159
{
160 161 162
	int			c;				/* character read from getc() */
	bool		end = false;	/* end-of-input flag */
	bool		backslashSeen = false;	/* have we seen a \ ? */
163 164 165 166 167

	/* ----------------
	 *	display a prompt and obtain input from the user
	 * ----------------
	 */
168
	printf("backend> ");
169
	fflush(stdout);
170

171 172 173 174
	/* Reset inBuf to empty */
	inBuf->len = 0;
	inBuf->data[0] = '\0';

175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
	for (;;)
	{
		if (UseNewLine)
		{
			/* ----------------
			 *	if we are using \n as a delimiter, then read
			 *	characters until the \n.
			 * ----------------
			 */
			while ((c = getc(stdin)) != EOF)
			{
				if (c == '\n')
				{
					if (backslashSeen)
					{
190 191 192
						/* discard backslash from inBuf */
						inBuf->data[--inBuf->len] = '\0';
						backslashSeen = false;
193 194 195 196 197
						continue;
					}
					else
					{
						/* keep the newline character */
198
						appendStringInfoChar(inBuf, '\n');
199 200 201 202 203 204 205 206
						break;
					}
				}
				else if (c == '\\')
					backslashSeen = true;
				else
					backslashSeen = false;

207
				appendStringInfoChar(inBuf, (char) c);
208 209 210 211 212 213 214 215 216 217 218 219
			}

			if (c == EOF)
				end = true;
		}
		else
		{
			/* ----------------
			 *	otherwise read characters until EOF.
			 * ----------------
			 */
			while ((c = getc(stdin)) != EOF)
220
				appendStringInfoChar(inBuf, (char) c);
221

222
			if (inBuf->len == 0)
223 224 225 226
				end = true;
		}

		if (end)
227
			return EOF;
228 229 230 231 232 233 234 235 236 237 238 239 240

		/* ----------------
		 *	otherwise we have a user query so process it.
		 * ----------------
		 */
		break;
	}

	/* ----------------
	 *	if the query echo flag was given, print the query..
	 * ----------------
	 */
	if (EchoQuery)
241
		printf("query: %s\n", inBuf->data);
242
	fflush(stdout);
243

244
	return 'Q';
245 246 247
}

/* ----------------
248
 *	SocketBackend()		Is called for frontend-backend connections
249
 *
250 251
 *	If the input is a query (case 'Q') then the string entered by
 *	the user is placed in its parameter inBuf.
252
 *
253
 *	If the input is a fastpath function call (case 'F') then
254
 *	the function call is processed in HandleFunctionRequest()
255 256
 *	(now called from PostgresMain()).
 *
257
 *	EOF is returned if the connection is lost.
258 259 260
 * ----------------
 */

261
static int
262
SocketBackend(StringInfo inBuf)
263
{
264
	char		qtype;
265
	char		result = '\0';
266 267 268 269 270

	/* ----------------
	 *	get input from the frontend
	 * ----------------
	 */
271 272
	qtype = '?';
	if (pq_getbytes(&qtype, 1) == EOF)
273
		return EOF;
274

275
	switch (qtype)
276
	{
277 278 279 280 281
			/* ----------------
			 *	'Q': user entered a query
			 * ----------------
			 */
		case 'Q':
282
			if (pq_getstr(inBuf))
283
				return EOF;
284 285
			result = 'Q';
			break;
286

287 288 289 290 291
			/* ----------------
			 *	'F':  calling user/system functions
			 * ----------------
			 */
		case 'F':
292
			if (pq_getstr(inBuf))
293
				return EOF;		/* ignore "string" at start of F message */
294 295
			result = 'F';
			break;
296

297 298 299 300 301 302 303
			/* ----------------
			 *	'X':  frontend is exiting
			 * ----------------
			 */
		case 'X':
			result = 'X';
			break;
304

305 306 307 308 309 310 311 312
			/* ----------------
			 *	otherwise we got garbage from the frontend.
			 *
			 *	XXX are we certain that we want to do an elog(FATAL) here?
			 *		-cim 1/24/90
			 * ----------------
			 */
		default:
313
			elog(FATAL, "Socket command type %c unknown", qtype);
314
			break;
315 316
	}
	return result;
317 318 319
}

/* ----------------
320 321 322
 *		ReadCommand reads a command from either the frontend or
 *		standard input, places it in inBuf, and returns a char
 *		representing whether the string is a 'Q'uery or a 'F'astpath
323
 *		call.  EOF is returned if end of file.
324 325
 * ----------------
 */
326
static int
327
ReadCommand(StringInfo inBuf)
328
{
329
	int			result;
330

331
	if (IsUnderPostmaster)
332
		result = SocketBackend(inBuf);
333
	else
334 335
		result = InteractiveBackend(inBuf);
	return result;
336 337
}

338 339 340 341 342 343 344

/*
 * Parse a query string and pass it through the rewriter.
 *
 * A list of Query nodes is returned, since the string might contain
 * multiple queries and/or the rewriter might expand one query to several.
 */
345
List *
346 347 348
pg_parse_and_rewrite(char *query_string,	/* string to execute */
					 Oid *typev,			/* parameter types */
					 int nargs)				/* number of parameters */
349
{
350
	List	   *querytree_list;
351
	List	   *querytree_list_item;
352
	Query	   *querytree;
353
	List	   *new_list;
354

355 356
	if (Debug_print_query)
		elog(DEBUG, "query: %s", query_string);
357

358 359 360 361
	/* ----------------
	 *	(1) parse the request string into a list of parse trees
	 * ----------------
	 */
362
	if (Show_parser_stats)
363 364 365 366
		ResetUsage();

	querytree_list = parser(query_string, typev, nargs);

367
	if (Show_parser_stats)
368
	{
369
		fprintf(StatFp, "PARSER STATISTICS\n");
370 371 372 373 374
		ShowUsage();
	}

	/* ----------------
	 *	(2) rewrite the queries, as necessary
375
	 *
B
Bruce Momjian 已提交
376 377
	 *	rewritten queries are collected in new_list.  Note there may be
	 *	more or fewer than in the original list.
378 379
	 * ----------------
	 */
380
	new_list = NIL;
B
Bruce Momjian 已提交
381
	foreach(querytree_list_item, querytree_list)
382
	{
383
		querytree = (Query *) lfirst(querytree_list_item);
384

385
		if (Debug_print_parse)
386
		{
387
			if (Debug_pretty_print)
B
Bruce Momjian 已提交
388
			{
389
				elog(DEBUG, "parse tree:");
J
Jan Wieck 已提交
390
				nodeDisplay(querytree);
B
Bruce Momjian 已提交
391 392
			}
			else
393
				elog(DEBUG, "parse tree: %s", nodeToString(querytree));
394
		}
395 396 397

		if (querytree->commandType == CMD_UTILITY)
		{
398 399
			/* don't rewrite utilities, just dump 'em into new_list */
			new_list = lappend(new_list, querytree);
400
		}
401
		else
402
		{
403
			/* rewrite regular queries */
404 405
			List	   *rewritten = QueryRewrite(querytree);

406
			new_list = nconc(new_list, rewritten);
407 408 409 410 411
		}
	}

	querytree_list = new_list;

412 413 414 415 416 417 418 419 420
#ifdef COPY_PARSE_PLAN_TREES
	/* Optional debugging check: pass parsetree output through copyObject() */
	/*
	 * Note: we run this test after rewrite, not before, because copyObject()
	 * does not handle most kinds of nodes that are used only in raw parse
	 * trees.  The present (bizarre) implementation of UNION/INTERSECT/EXCEPT
	 * doesn't run analysis of the second and later subqueries until rewrite,
	 * so we'd get false failures on these queries if we did it beforehand.
	 */
421 422 423 424 425 426
	new_list = (List *) copyObject(querytree_list);
	/* This checks both copyObject() and the equal() routines... */
	if (! equal(new_list, querytree_list))
		elog(NOTICE, "pg_parse_and_rewrite: copyObject failed on parse tree");
	else
		querytree_list = new_list;
427 428
#endif

429
	if (Debug_print_rewritten)
430
	{
431
		if (Debug_pretty_print)
B
Bruce Momjian 已提交
432
		{
433
			elog(DEBUG, "rewritten parse tree:");
B
Bruce Momjian 已提交
434
			foreach(querytree_list_item, querytree_list)
J
Jan Wieck 已提交
435
			{
436 437
				querytree = (Query *) lfirst(querytree_list_item);
				nodeDisplay(querytree);
J
Jan Wieck 已提交
438 439
				printf("\n");
			}
B
Bruce Momjian 已提交
440 441 442
		}
		else
		{
443
			elog(DEBUG, "rewritten parse tree:");
J
Jan Wieck 已提交
444

B
Bruce Momjian 已提交
445
			foreach(querytree_list_item, querytree_list)
J
Jan Wieck 已提交
446
			{
447
				querytree = (Query *) lfirst(querytree_list_item);
448
				elog(DEBUG, "%s", nodeToString(querytree));
J
Jan Wieck 已提交
449
			}
450 451 452
		}
	}

453 454
	return querytree_list;
}
455 456


457 458 459 460 461
/* Generate a plan for a single query. */
Plan *
pg_plan_query(Query *querytree)
{
	Plan	   *plan;
462

463 464 465
	/* Utility commands have no plans. */
	if (querytree->commandType == CMD_UTILITY)
		return NULL;
466

467
	if (Show_planner_stats)
468
		ResetUsage();
469

470 471
	/* call that optimizer */
	plan = planner(querytree);
472

473
	if (Show_planner_stats)
474
	{
475
		fprintf(stderr, "PLANNER STATISTICS\n");
476 477
		ShowUsage();
	}
478

479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
#ifdef COPY_PARSE_PLAN_TREES
	/* Optional debugging check: pass plan output through copyObject() */
	{
		Plan   *new_plan = (Plan *) copyObject(plan);

		/* equal() currently does not have routines to compare Plan nodes,
		 * so don't try to test equality here.  Perhaps fix someday?
		 */
#ifdef NOT_USED
		/* This checks both copyObject() and the equal() routines... */
		if (! equal(new_plan, plan))
			elog(NOTICE, "pg_plan_query: copyObject failed on plan tree");
		else
#endif
			plan = new_plan;
	}
#endif

497 498 499 500
	/* ----------------
	 *	Print plan if debugging.
	 * ----------------
	 */
501
	if (Debug_print_plan)
502
	{
503
		if (Debug_pretty_print)
504
		{
505
			elog(DEBUG, "plan:");
506
			nodeDisplay(plan);
507 508
		}
		else
509
			elog(DEBUG, "plan: %s", nodeToString(plan));
510 511
	}

512
	return plan;
513 514
}

515

516
/* ----------------------------------------------------------------
517
 *		pg_exec_query_dest()
518 519
 *
 *		Takes a querystring, runs the parser/utilities or
520 521 522 523 524 525 526 527 528 529 530 531
 *		parser/planner/executor over it as necessary.
 *
 * Assumptions:
 *
 * Caller is responsible for calling StartTransactionCommand() beforehand
 * and CommitTransactionCommand() afterwards (if successful).
 *
 * The CurrentMemoryContext at entry references a context that is
 * appropriate for execution of individual queries (typically this will be
 * TransactionCommandContext).  Note that this routine resets that context
 * after each individual query, so don't store anything there that
 * must outlive the call!
532
 *
533 534
 * parse_context references a context suitable for holding the
 * parse/rewrite trees (typically this will be QueryContext).
535
 * This context *must* be longer-lived than the CurrentMemoryContext!
536 537 538 539 540 541 542
 * In fact, if the query string might contain BEGIN/COMMIT commands,
 * parse_context had better outlive TopTransactionContext!
 *
 * We could have hard-wired knowledge about QueryContext and
 * TransactionCommandContext into this routine, but it seems better
 * not to, in case callers from outside this module need to use some
 * other contexts.
543 544 545 546 547
 *
 * ----------------------------------------------------------------
 */

void
548
pg_exec_query_dest(char *query_string,	/* string to execute */
549
				   CommandDest dest,	/* where results should go */
550
				   MemoryContext parse_context)	/* context for parsetrees */
551
{
552 553 554
	MemoryContext oldcontext;
	List	   *querytree_list,
			   *querytree_item;
555

556 557 558 559 560 561 562 563 564 565
	/*
	 * If you called this routine with parse_context = CurrentMemoryContext,
	 * you blew it.  They *must* be different, else the context reset
	 * at the bottom of the loop will destroy the querytree list.
	 * (We really ought to check that parse_context isn't a child of
	 * CurrentMemoryContext either, but that would take more cycles than
	 * it's likely to be worth.)
	 */
	Assert(parse_context != CurrentMemoryContext);

566 567 568 569
	/*
	 * Switch to appropriate context for constructing parsetrees.
	 */
	oldcontext = MemoryContextSwitchTo(parse_context);
570

B
Bruce Momjian 已提交
571
	/*
572
	 * Parse and rewrite the query or queries.
573
	 */
574
	querytree_list = pg_parse_and_rewrite(query_string, NULL, 0);
575

576 577 578 579 580 581 582 583 584 585 586
	/*
	 * Switch back to execution context for planning and execution.
	 */
	MemoryContextSwitchTo(oldcontext);

	/*
	 * Run through the query or queries and execute each one.
	 */
	foreach(querytree_item, querytree_list)
	{
		Query	   *querytree = (Query *) lfirst(querytree_item);
587 588 589 590

		/* if we got a cancel signal in parsing or prior command, quit */
		if (QueryCancel)
			CancelQuery();
591

592 593 594 595 596 597 598 599 600
		if (querytree->commandType == CMD_UTILITY)
		{
			/* ----------------
			 *	 process utility functions (create, destroy, etc..)
			 *
			 *	 Note: we do not check for the transaction aborted state
			 *	 because that is done in ProcessUtility.
			 * ----------------
			 */
601 602 603 604
			if (Debug_print_query)
				elog(DEBUG, "ProcessUtility: %s", query_string);
			else if (DebugLvl > 1)
				elog(DEBUG, "ProcessUtility");
605 606 607 608 609

			ProcessUtility(querytree->utilityStmt, dest);
		}
		else
		{
610
			Plan	   *plan;
611

612
			/* If aborted transaction, skip planning and execution */
613
			if (IsAbortedTransactionBlockState())
614
			{
615 616 617 618 619 620 621 622 623 624 625 626
				/* ----------------
				 *	 the EndCommand() stuff is to tell the frontend
				 *	 that the command ended. -cim 6/1/90
				 * ----------------
				 */
				char	   *tag = "*ABORT STATE*";

				elog(NOTICE, "current transaction is aborted, "
					 "queries ignored until end of transaction block");

				EndCommand(tag, dest);

627 628
				/*
				 * We continue in the loop, on the off chance that there
629 630 631 632
				 * is a COMMIT or ROLLBACK utility command later in the
				 * query string.
				 */
				continue;
633 634
			}

635 636 637 638 639 640 641
			plan = pg_plan_query(querytree);

			/* if we got a cancel signal whilst planning, quit */
			if (QueryCancel)
				CancelQuery();

			/* Initialize snapshot state for query */
V
Vadim B. Mikheev 已提交
642 643 644
			SetQuerySnapshot();

			/*
B
Bruce Momjian 已提交
645
			 * execute the plan
646
			 */
647
			if (Show_executor_stats)
648 649
				ResetUsage();

650 651 652 653 654 655 656 657 658 659 660
			if (dontExecute)
			{
				/* don't execute it, just show the query plan */
				print_plan(plan, querytree);
			}
			else
			{
				if (DebugLvl > 1)
					elog(DEBUG, "ProcessQuery");
				ProcessQuery(querytree, plan, dest);
			}
661

662
			if (Show_executor_stats)
663
			{
664
				fprintf(stderr, "EXECUTOR STATISTICS\n");
665 666 667 668 669 670 671 672 673
				ShowUsage();
			}
		}

		/*
		 * In a query block, we want to increment the command counter
		 * between queries so that the effects of early queries are
		 * visible to subsequent ones.
		 */
674
		CommandCounterIncrement();
675 676 677 678 679 680 681 682
		/*
		 * Also, clear the execution context to recover temporary
		 * memory used by the query.  NOTE: if query string contains
		 * BEGIN/COMMIT transaction commands, execution context may
		 * now be different from what we were originally passed;
		 * so be careful to clear current context not "oldcontext".
		 */
		MemoryContextResetAndDeleteChildren(CurrentMemoryContext);
683
	}
684 685 686
}

/* --------------------------------
687
 *		signal handler routines used in PostgresMain()
688
 *
B
Bruce Momjian 已提交
689
 *		handle_warn() catches SIGQUIT.	It forces control back to the main
690 691 692
 *		loop, just as if an internal error (elog(ERROR,...)) had occurred.
 *		elog() used to actually use kill(2) to induce a SIGQUIT to get here!
 *		But that's not 100% reliable on some systems, so now it does its own
B
Bruce Momjian 已提交
693
 *		siglongjmp() instead.
694
 *		We still provide the signal catcher so that an error quit can be
B
Bruce Momjian 已提交
695
 *		forced externally.	This should be done only with great caution,
696 697
 *		however, since an asynchronous signal could leave the system in
 *		who-knows-what inconsistent state.
698
 *
699 700 701
 *		quickdie() occurs when signalled by the postmaster.
 *		Some backend has bought the farm,
 *		so we need to stop what we're doing and exit.
702
 *
703
 *		die() performs an orderly cleanup via proc_exit()
704 705 706 707
 * --------------------------------
 */

void
708
handle_warn(int signum)
709
{
710
	siglongjmp(Warn_restart, 1);
711 712
}

713
static void
714
quickdie(int signum)
715
{
716
	PG_SETMASK(&BlockSig);
717
	elog(NOTICE, "Message from PostgreSQL backend:"
718 719 720 721 722
		 "\n\tThe Postmaster has informed me that some other backend"
		 " died abnormally and possibly corrupted shared memory."
		 "\n\tI have rolled back the current transaction and am"
		 " going to terminate your database system connection and exit."
	"\n\tPlease reconnect to the database system and repeat your query.");
723

724 725

	/*
726
	 * DO NOT proc_exit(0) -- we're here because shared memory may be
727 728 729 730
	 * corrupted, so we don't want to flush any shared state to stable
	 * storage.  Just nail the windows shut and get out of town.
	 */

731
	exit(1);
732 733
}

734 735 736
/*
 * Abort transaction and exit
 */
737
void
738
die(int signum)
739
{
740
	PG_SETMASK(&BlockSig);
741

742 743 744 745 746 747 748 749 750
	/*
	 * If ERROR/FATAL is in progress...
	 */
	if (InError)
	{
		ExitAfterAbort = true;
		return;
	}
	elog(FATAL, "The system is shutting down");
751 752 753
}

/* signal handler for floating point exception */
754
static void
755
FloatExceptionHandler(int signum)
756
{
757
	elog(ERROR, "floating point exception!"
758 759
		 " The last floating point operation either exceeded legal ranges"
		 " or was a divide by zero");
760 761
}

M
 
Marc G. Fournier 已提交
762
/* signal handler for query cancel signal from postmaster */
763
static void
764
QueryCancelHandler(int signum)
765 766
{
	QueryCancel = true;
767
	LockWaitCancel();
768 769 770 771 772
}

void
CancelQuery(void)
{
B
Bruce Momjian 已提交
773

774 775
	/*
	 * QueryCancel flag will be reset in main loop, which we reach by
M
 
Marc G. Fournier 已提交
776 777
	 * longjmp from elog().
	 */
778 779 780
	elog(ERROR, "Query was cancelled.");
}

781
static void
782
SigHupHandler(int signum)
783
{
784
	got_SIGHUP = true;
785 786
}

787

788 789
static void
usage(char *progname)
790
{
791
	fprintf(stderr,
792
			"Usage: %s [options] [dbname]\n", progname);
M
 
Marc G. Fournier 已提交
793
#ifdef USE_ASSERT_CHECKING
T
Tom Lane 已提交
794
	fprintf(stderr, "\t-A on\t\tenable/disable assert checking\n");
M
 
Marc G. Fournier 已提交
795
#endif
796
	fprintf(stderr, "\t-B buffers\tset number of buffers in buffer pool\n");
T
Tom Lane 已提交
797
	fprintf(stderr, "\t-C \t\tsuppress version info\n");
798 799
	fprintf(stderr, "\t-D dir\t\tdata directory\n");
	fprintf(stderr, "\t-E \t\techo query before execution\n");
800
	fprintf(stderr, "\t-F \t\tturn fsync off\n");
801 802
	fprintf(stderr, "\t-L \t\tturn off locking\n");
	fprintf(stderr, "\t-N \t\tdon't use newline as interactive query delimiter\n");
803
	fprintf(stderr, "\t-O \t\tallow system table structure changes\n");
804
	fprintf(stderr, "\t-Q \t\tsuppress informational messages\n");
805
	fprintf(stderr, "\t-S kbytes\tset amount of memory for sorts (in kbytes)\n");
T
Tom Lane 已提交
806 807
	fprintf(stderr, "\t-T options\tspecify pg_options\n");
	fprintf(stderr, "\t-W sec\t\twait N seconds to allow attach from a debugger\n");
B
Bruce Momjian 已提交
808
	fprintf(stderr, "\t-d [1-5]\tset debug level\n");
809
	fprintf(stderr, "\t-e \t\tturn on European date format\n");
T
Tom Lane 已提交
810
	fprintf(stderr, "\t-f [s|i|n|m|h]\tforbid use of some plan types\n");
811 812 813
	fprintf(stderr, "\t-i \t\tdon't execute queries\n");
	fprintf(stderr, "\t-o file\t\tsend stdout and stderr to given filename\n");
	fprintf(stderr, "\t-p database\tbackend is started under a postmaster\n");
814
	fprintf(stderr, "\t-s \t\tshow stats after each query\n");
815
	fprintf(stderr, "\t-t [pa|pl|ex]\tshow timings after each query\n");
816
	fprintf(stderr, "\t-v version\tset protocol version being used by frontend\n");
817 818 819
}

/* ----------------------------------------------------------------
820 821
 *	PostgresMain
 *		postgres main loop
822
 *		all backends, interactive or otherwise start here
823 824 825 826 827
 *
 *	argc/argv are the command line arguments to be used.  When being forked
 *	by the postmaster, these are not the original argv array of the process.
 *	real_argc/real_argv point to the original argv array, which is needed by
 *	PS_INIT_STATUS on some platforms.
828 829 830
 * ----------------------------------------------------------------
 */
int
831
PostgresMain(int argc, char *argv[], int real_argc, char *real_argv[])
832
{
833
	int			flag;
834

835
	char	   *DBName = NULL;
836
	bool		secure = true;
837
	int			errs = 0;
838

839
	int			firstchar;
840
	StringInfo	parser_input;
841
	char	   *userName;
M
 
Marc G. Fournier 已提交
842

843 844
	char	   *remote_host;
	unsigned short remote_port;
845

846 847
	extern int	optind;
	extern char *optarg;
848
	extern int	DebugLvl;
849

850 851 852 853 854 855 856 857 858 859 860
	/*
	 * Fire up essential subsystems: error and memory management
	 *
	 * If we are running under the postmaster, this is done already.
	 */
	if (!IsUnderPostmaster)
	{
		EnableExceptionHandling(true);
		MemoryContextInit();
	}

861
	/*
862
	 * Set default values for command-line options.
863
	 */
864 865
	Noversion = false;
	EchoQuery = false;
866 867 868 869 870 871 872

	if (!IsUnderPostmaster)
	{
		ResetAllOptions();
		if (getenv("PGDATA"))
			DataDir = strdup(getenv("PGDATA"));
	}
873
	StatFp = stderr;
874

875 876
	SetProcessingMode(InitProcessing);

877 878
	/* Check for PGDATESTYLE environment variable */
	set_default_datestyle();
879

880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897
	/* ----------------
	 *	parse command line arguments
	 *
	 *	There are now two styles of command line layout for the backend:
	 *
	 *	For interactive use (not started from postmaster) the format is
	 *		postgres [switches] [databasename]
	 *	If the databasename is omitted it is taken to be the user name.
	 *
	 *	When started from the postmaster, the format is
	 *		postgres [secure switches] -p databasename [insecure switches]
	 *	Switches appearing after -p came from the client (via "options"
	 *	field of connection request).  For security reasons we restrict
	 *	what these switches can do.
	 * ----------------
	 */

	optind = 1;					/* reset after postmaster's usage */
898

899
	while ((flag = getopt(argc, argv,  "A:B:CD:d:Eef:FiLNOPo:p:S:st:v:W:x:-:")) != EOF)
900 901
		switch (flag)
		{
M
 
Marc G. Fournier 已提交
902 903 904 905
			case 'A':
#ifdef USE_ASSERT_CHECKING
				assert_enabled = atoi(optarg);
#else
906
				fprintf(stderr, "Assert checking is not compiled in\n");
M
 
Marc G. Fournier 已提交
907 908
#endif
				break;
909

910 911 912 913 914
			case 'B':
				/* ----------------
				 *	specify the size of buffer pool
				 * ----------------
				 */
915 916
				if (secure)
					NBuffers = atoi(optarg);
917
				break;
918

919 920
			case 'C':
				/* ----------------
921
				 *	don't print version string
922 923
				 * ----------------
				 */
924
				Noversion = true;
925
				break;
926

927
			case 'D':			/* PGDATA directory */
928
				if (secure)
929 930 931 932 933
				{
					if (DataDir)
						free(DataDir);
					DataDir = strdup(optarg);
				}
M
 
Marc G. Fournier 已提交
934
				break;
935

936
			case 'd':			/* debug level */
937
				DebugLvl = atoi(optarg);
938 939
				if (DebugLvl >= 1);
					Log_connections = true;
M
 
Marc G. Fournier 已提交
940
				if (DebugLvl >= 2)
941
					Debug_print_query = true;
M
 
Marc G. Fournier 已提交
942
				if (DebugLvl >= 3)
943
					Debug_print_parse = true;
B
Bruce Momjian 已提交
944
				if (DebugLvl >= 4)
945
					Debug_print_plan = true;
J
Jan Wieck 已提交
946
				if (DebugLvl >= 5)
947
					Debug_print_rewritten = true;
948
				break;
949 950 951 952 953 954

			case 'E':
				/* ----------------
				 *	E - echo the query the user entered
				 * ----------------
				 */
955
				EchoQuery = true;
956
				break;
957 958 959 960 961 962

			case 'e':
				/* --------------------------
				 * Use european date formats.
				 * --------------------------
				 */
963
				EuroDates = true;
964
				break;
965 966 967 968

			case 'F':
				/* --------------------
				 *	turn off fsync
969 970 971 972
				 *
				 *	7.0 buffer manager can support different backends running
				 *	with different fsync settings, so this no longer needs
				 *	to be "if (secure)".
973 974
				 * --------------------
				 */
975
				enableFsync = false;
976
				break;
977 978 979 980 981 982 983 984 985

			case 'f':
				/* -----------------
				 *	  f - forbid generation of certain plans
				 * -----------------
				 */
				switch (optarg[0])
				{
					case 's':	/* seqscan */
986
						enable_seqscan = false;
987 988
						break;
					case 'i':	/* indexscan */
989 990 991 992
						enable_indexscan = false;
						break;
					case 't':	/* tidscan */
						enable_tidscan = false;
993 994
						break;
					case 'n':	/* nestloop */
995
						enable_nestloop = false;
996 997
						break;
					case 'm':	/* mergejoin */
998
						enable_mergejoin = false;
999 1000
						break;
					case 'h':	/* hashjoin */
1001
						enable_hashjoin = false;
1002 1003 1004 1005
						break;
					default:
						errs++;
				}
1006 1007
				break;

1008
			case 'i':
1009
				dontExecute = true;
1010
				break;
1011

1012 1013 1014 1015 1016
			case 'L':
				/* --------------------
				 *	turn off locking
				 * --------------------
				 */
1017 1018
				if (secure)
					lockingOff = 1;
T
Tom Lane 已提交
1019 1020
				break;

1021 1022 1023 1024 1025 1026 1027
			case 'N':
				/* ----------------
				 *	N - Don't use newline as a query delimiter
				 * ----------------
				 */
				UseNewLine = 0;
				break;
1028

1029 1030 1031 1032 1033
			case 'O':
				/* --------------------
				 *	allow system table structure modifications
				 * --------------------
				 */
1034 1035
				if (secure)		/* XXX safe to allow from client??? */
					allowSystemTableMods = true;
1036 1037
				break;

H
Hiroshi Inoue 已提交
1038 1039 1040 1041 1042 1043 1044 1045 1046
			case 'P':
				/* --------------------
				 *	ignore system indexes
				 * --------------------
				 */
				if (secure)		/* XXX safe to allow from client??? */
					IgnoreSystemIndexes(true);
				break;

T
Tom Lane 已提交
1047 1048 1049 1050 1051
			case 'o':
				/* ----------------
				 *	o - send output (stdout and stderr) to the given file
				 * ----------------
				 */
1052 1053
				if (secure)
					StrNCpy(OutputFileName, optarg, MAXPGPATH);
T
Tom Lane 已提交
1054 1055
				break;

1056
			case 'p':
1057 1058 1059 1060 1061
				/* ----------------
				 *	p - special flag passed if backend was forked
				 *		by a postmaster.
				 * ----------------
				 */
1062 1063
				if (secure)
				{
1064
					DBName = strdup(optarg);
B
Bruce Momjian 已提交
1065 1066
					secure = false;		/* subsequent switches are NOT
										 * secure */
1067
				}
1068
				break;
1069

1070 1071
			case 'S':
				/* ----------------
V
Vadim B. Mikheev 已提交
1072
				 *	S - amount of sort memory to use in 1k bytes
1073 1074
				 * ----------------
				 */
1075
				{
1076 1077
					int			S;

V
Vadim B. Mikheev 已提交
1078
					S = atoi(optarg);
1079
					if (S >= 4 * BLCKSZ / 1024)
V
Vadim B. Mikheev 已提交
1080
						SortMem = S;
1081
				}
1082
				break;
1083 1084 1085 1086 1087 1088

			case 's':
				/* ----------------
				 *	  s - report usage statistics (timings) after each query
				 * ----------------
				 */
1089
				Show_query_stats = 1;
M
 
Marc G. Fournier 已提交
1090 1091
				break;

1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106
			case 't':
				/* ----------------
				 *	tell postgres to report usage statistics (timings) for
				 *	each query
				 *
				 *	-tpa[rser] = print stats for parser time of each query
				 *	-tpl[anner] = print stats for planner time of each query
				 *	-te[xecutor] = print stats for executor time of each query
				 *	caution: -s can not be used together with -t.
				 * ----------------
				 */
				switch (optarg[0])
				{
					case 'p':
						if (optarg[1] == 'a')
1107
							Show_parser_stats = 1;
1108
						else if (optarg[1] == 'l')
1109
							Show_planner_stats = 1;
1110 1111 1112 1113
						else
							errs++;
						break;
					case 'e':
1114
						Show_executor_stats = 1;
1115 1116 1117 1118 1119
						break;
					default:
						errs++;
						break;
				}
1120 1121
				break;

1122
			case 'v':
1123 1124
				if (secure)
					FrontendProtocol = (ProtocolVersion) atoi(optarg);
1125 1126
				break;

M
 
Marc G. Fournier 已提交
1127 1128
			case 'W':
				/* ----------------
1129
				 *	wait N seconds to allow attach from a debugger
M
 
Marc G. Fournier 已提交
1130 1131 1132 1133 1134
				 * ----------------
				 */
				sleep(atoi(optarg));
				break;

1135
			case 'x':
B
Bruce Momjian 已提交
1136
#ifdef NOT_USED					/* planner/xfunc.h */
1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164

				/*
				 * control joey hellerstein's expensive function
				 * optimization
				 */
				if (XfuncMode != 0)
				{
					fprintf(stderr, "only one -x flag is allowed\n");
					errs++;
					break;
				}
				if (strcmp(optarg, "off") == 0)
					XfuncMode = XFUNC_OFF;
				else if (strcmp(optarg, "nor") == 0)
					XfuncMode = XFUNC_NOR;
				else if (strcmp(optarg, "nopull") == 0)
					XfuncMode = XFUNC_NOPULL;
				else if (strcmp(optarg, "nopm") == 0)
					XfuncMode = XFUNC_NOPM;
				else if (strcmp(optarg, "pullall") == 0)
					XfuncMode = XFUNC_PULLALL;
				else if (strcmp(optarg, "wait") == 0)
					XfuncMode = XFUNC_WAIT;
				else
				{
					fprintf(stderr, "use -x {off,nor,nopull,nopm,pullall,wait}\n");
					errs++;
				}
1165
#endif
1166
				break;
1167

1168 1169
			case '-':
			{
1170
				char *name, *value;
1171

1172 1173
				ParseLongOption(optarg, &name, &value);
				if (!value)
1174
					elog(ERROR, "--%s requires argument", optarg);
1175 1176 1177 1178 1179

				SetConfigOption(name, value, PGC_BACKEND);
				free(name);
				if (value)
					free(value);
1180 1181 1182
				break;
			}

1183 1184 1185 1186 1187 1188
			default:
				/* ----------------
				 *	default: bad command line option
				 * ----------------
				 */
				errs++;
T
Tom Lane 已提交
1189
				break;
1190 1191
		}

1192 1193
	if (Show_query_stats &&
		(Show_parser_stats || Show_planner_stats || Show_executor_stats))
1194
	{
1195 1196
		elog(NOTICE, "Query statistics are disabled because parser, planner, or executor statistics are on.");
		Show_query_stats = false;
1197 1198 1199 1200 1201 1202 1203
	}

	if (!DataDir)
	{
		fprintf(stderr, "%s does not know where to find the database system "
				"data.  You must specify the directory that contains the "
				"database system either by specifying the -D invocation "
1204
			 "option or by setting the PGDATA environment variable.\n\n",
1205 1206 1207 1208 1209
				argv[0]);
		proc_exit(1);
	}

	/*
1210 1211 1212
	 * 1. Set BlockSig and UnBlockSig masks. 2. Set up signal handlers. 3.
	 * Allow only SIGUSR1 signal (we never block it) during
	 * initialization.
1213 1214 1215
	 *
	 * Note that postmaster already blocked ALL signals to make us happy.
	 */
1216
	pqinitmask();
1217 1218 1219 1220 1221 1222 1223

#ifdef HAVE_SIGPROCMASK
	sigdelset(&BlockSig, SIGUSR1);
#else
	BlockSig &= ~(sigmask(SIGUSR1));
#endif

1224 1225
	PG_SETMASK(&BlockSig);		/* block everything except SIGUSR1 */

1226
	pqsignal(SIGHUP, SigHupHandler);	/* set flag to read config file */
1227 1228
	pqsignal(SIGINT, QueryCancelHandler);		/* cancel current query */
	pqsignal(SIGQUIT, handle_warn);		/* handle error */
1229 1230
	pqsignal(SIGTERM, die);
	pqsignal(SIGALRM, HandleDeadLock);
1231 1232 1233 1234 1235

	/*
	 * Ignore failure to write to frontend. Note: if frontend closes
	 * connection, we will notice it and exit cleanly when control next
	 * returns to outer loop.  This seems safer than forcing exit in the
1236 1237 1238 1239
	 * midst of output during who-knows-what operation...
	 */
	pqsignal(SIGPIPE, SIG_IGN);
	pqsignal(SIGUSR1, quickdie);
1240
	pqsignal(SIGUSR2, Async_NotifyHandler);		/* flush also sinval cache */
1241
	pqsignal(SIGFPE, FloatExceptionHandler);
1242
	pqsignal(SIGCHLD, SIG_IGN); /* ignored, sent by LockOwners */
1243 1244 1245 1246 1247 1248 1249
	pqsignal(SIGTTIN, SIG_DFL);
	pqsignal(SIGTTOU, SIG_DFL);
	pqsignal(SIGCONT, SIG_DFL);

	/*
	 * Get user name (needed now in case it is the default database name)
	 * and check command line validity
1250 1251 1252 1253
	 */
	SetPgUserName();
	userName = GetPgUserName();

1254
	if (IsUnderPostmaster)
1255
	{
1256 1257 1258 1259
		/* noninteractive case: nothing should be left after switches */
		if (errs || argc != optind || DBName == NULL)
		{
			usage(argv[0]);
1260
			proc_exit(0);
1261
		}
1262 1263 1264
		pq_init();				/* initialize libpq at backend startup */
		whereToSendOutput = Remote;
		BaseInit();
1265
	}
1266
	else
1267
	{
1268
		/* interactive case: database name can be last arg on command line */
1269
		whereToSendOutput = Debug;
1270 1271 1272
		if (errs || argc - optind > 1)
		{
			usage(argv[0]);
1273
			proc_exit(0);
1274 1275 1276 1277 1278 1279 1280
		}
		else if (argc - optind == 1)
			DBName = argv[optind];
		else if ((DBName = userName) == NULL)
		{
			fprintf(stderr, "%s: USER undefined and no database specified\n",
					argv[0]);
1281
			proc_exit(0);
1282
		}
1283 1284 1285 1286 1287

		/*
		 * Try to create pid file.
		 */
		SetPidFname(DataDir);
1288
		if (SetPidFile(-getpid()))
1289
			proc_exit(0);
1290

1291 1292 1293 1294 1295
		/*
		 * Register clean up proc.
		 */
		on_proc_exit(UnlinkPidFile, NULL);

1296
		BaseInit();
1297 1298
		snprintf(XLogDir, MAXPGPATH, "%s/pg_xlog", DataDir);
		snprintf(ControlFilePath, MAXPGPATH, "%s/global/pg_control", DataDir);
1299
		StartupXLOG();
1300 1301
	}

1302 1303 1304 1305 1306 1307 1308 1309
	/*
	 * Set up additional info.
	 */

#ifdef CYR_RECODE
	SetCharSet();
#endif

1310
	/* On some systems our dynloader code needs the executable's pathname */
1311
	if (FindExec(pg_pathname, real_argv[0], "postgres") < 0)
1312
		elog(FATAL, "%s: could not locate executable, bailing out...",
1313
			 real_argv[0]);
1314

M
 
Marc G. Fournier 已提交
1315 1316 1317
	/*
	 * Find remote host name or address.
	 */
1318 1319
	remote_host = NULL;

1320 1321
	if (IsUnderPostmaster)
	{
1322
		if (MyProcPort->raddr.sa.sa_family == AF_INET)
1323
		{
1324 1325
			struct hostent *host_ent;
			char * host_addr;
M
 
Marc G. Fournier 已提交
1326

1327 1328 1329 1330 1331 1332 1333 1334
			remote_port = ntohs(MyProcPort->raddr.in.sin_port);
			host_addr = inet_ntoa(MyProcPort->raddr.in.sin_addr);

			if (HostnameLookup)
			{
				host_ent = gethostbyaddr((char *) &MyProcPort->raddr.in.sin_addr, sizeof(MyProcPort->raddr.in.sin_addr), AF_INET);

				if (host_ent)
1335
				{
1336 1337
					remote_host = palloc(strlen(host_addr) + strlen(host_ent->h_name) + 3);
					sprintf(remote_host, "%s[%s]", host_ent->h_name, host_addr);
M
 
Marc G. Fournier 已提交
1338
				}
1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350
			}

			if (remote_host == NULL)
				remote_host = pstrdup(host_addr);

			if (ShowPortNumber)
			{
				char * str = palloc(strlen(remote_host) + 7);
				sprintf(str, "%s:%hu", remote_host, remote_port);
				pfree(remote_host);
				remote_host = str;
			}
M
 
Marc G. Fournier 已提交
1351
		}
1352 1353 1354
		else /* not AF_INET */
			remote_host = "[local]";

1355

1356
		/*
1357 1358 1359 1360 1361 1362
		 * Set process parameters for ps
		 *
		 * WARNING: On some platforms the environment will be moved
		 * around to make room for the ps display string. So any
		 * references to optarg or getenv() from above will be invalid
		 * after this call. Better use strdup or something similar.
1363
		 */
1364 1365
		init_ps_display(real_argc, real_argv, userName, DBName, remote_host);
		set_ps_display("startup");
1366 1367
	}

1368 1369 1370
	if (Log_connections)
		elog(DEBUG, "connection: host=%s user=%s database=%s",
			 remote_host, userName, DBName);
1371

1372 1373
	/*
	 * general initialization
1374
	 */
1375 1376
	if (DebugLvl > 1)
		elog(DEBUG, "InitPostgres");
1377 1378
	InitPostgres(DBName);

1379
#ifdef MULTIBYTE
1380
	/* set default client encoding */
1381 1382
	if (DebugLvl > 1)
		elog(DEBUG, "reset_client_encoding");
1383 1384 1385
	reset_client_encoding();
#endif

1386 1387
	on_shmem_exit(remove_all_temp_relations, NULL);

1388 1389
	/*
	 * Send this backend's cancellation info to the frontend.
1390
	 */
M
 
Marc G. Fournier 已提交
1391 1392 1393
	if (whereToSendOutput == Remote &&
		PG_PROTOCOL_MAJOR(FrontendProtocol) >= 2)
	{
1394
		StringInfoData buf;
B
Bruce Momjian 已提交
1395

1396 1397 1398 1399 1400
		pq_beginmessage(&buf);
		pq_sendbyte(&buf, 'K');
		pq_sendint(&buf, (int32) MyProcPid, sizeof(int32));
		pq_sendint(&buf, (int32) MyCancelKey, sizeof(int32));
		pq_endmessage(&buf);
M
 
Marc G. Fournier 已提交
1401 1402 1403
		/* Need not flush since ReadyForQuery will do it. */
	}

1404 1405 1406
	if (!IsUnderPostmaster)
	{
		puts("\nPOSTGRES backend interactive interface ");
1407
		puts("$Revision: 1.172 $ $Date: 2000/08/27 19:00:31 $\n");
1408 1409
	}

1410
	/*
1411 1412 1413
	 * Initialize the deferred trigger manager
	 */
	if (DeferredTriggerInit() != 0)
1414
		proc_exit(0);
1415 1416

	SetProcessingMode(NormalProcessing);
1417

1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431
	/*
	 * Create the memory context we will use in the main loop.
	 *
	 * QueryContext is reset once per iteration of the main loop,
	 * ie, upon completion of processing of each supplied query string.
	 * It can therefore be used for any data that should live just as
	 * long as the query string --- parse trees, for example.
	 */
	QueryContext = AllocSetContextCreate(TopMemoryContext,
										 "QueryContext",
										 ALLOCSET_DEFAULT_MINSIZE,
										 ALLOCSET_DEFAULT_INITSIZE,
										 ALLOCSET_DEFAULT_MAXSIZE);

1432 1433
	/*
	 * POSTGRES main processing loop begins here
1434
	 *
1435 1436
	 * If an exception is encountered, processing resumes here so we abort
	 * the current transaction and start a new one.
1437 1438 1439 1440
	 */

	if (sigsetjmp(Warn_restart, 1) != 0)
	{
1441 1442 1443 1444 1445 1446 1447
		/*
		 * Make sure we are in a valid memory context during recovery.
		 *
		 * We use ErrorContext in hopes that it will have some free space
		 * even if we're otherwise up against it...
		 */
		MemoryContextSwitchTo(ErrorContext);
1448

1449 1450
		if (DebugLvl >= 1)
			elog(DEBUG, "AbortCurrentTransaction");
1451
		AbortCurrentTransaction();
1452

1453 1454
		if (ExitAfterAbort)
		{
1455
			ProcReleaseLocks(); /* Just to be sure... */
1456
			proc_exit(0);
1457
		}
1458 1459 1460 1461 1462 1463 1464
		/*
		 * If we recovered successfully, return to normal top-level context
		 * and clear ErrorContext for next time.
		 */
		MemoryContextSwitchTo(TopMemoryContext);
		MemoryContextResetAndDeleteChildren(ErrorContext);
		InError = false;
1465
	}
1466

1467 1468
	Warn_restart_ready = true;	/* we can now handle elog(ERROR) */

1469
	PG_SETMASK(&UnBlockSig);
1470

1471 1472
	/*
	 * Non-error queries loop here.
1473 1474 1475 1476
	 */

	for (;;)
	{
1477 1478 1479 1480 1481 1482 1483 1484
		/*
		 * Release storage left over from prior query cycle, and
		 * create a new query input buffer in the cleared QueryContext.
		 */
		MemoryContextSwitchTo(QueryContext);
		MemoryContextResetAndDeleteChildren(QueryContext);

		parser_input = makeStringInfo();
1485

1486 1487 1488 1489 1490 1491 1492 1493
		/* XXX this could be moved after ReadCommand below to get more
		 * sensical behaviour */
		if (got_SIGHUP)
		{
			got_SIGHUP = false;
			ProcessConfigFile(PGC_SIGHUP);
		}

B
Bruce Momjian 已提交
1494
		/* ----------------
1495 1496
		 *	 (1) tell the frontend we're ready for a new query.
		 *
B
Bruce Momjian 已提交
1497
		 *	 Note: this includes fflush()'ing the last of the prior output.
B
Bruce Momjian 已提交
1498 1499
		 * ----------------
		 */
1500
		ReadyForQuery(whereToSendOutput);
B
Bruce Momjian 已提交
1501

1502
		/* ----------------
1503
		 *	 (2) deal with pending asynchronous NOTIFY from other backends,
B
Bruce Momjian 已提交
1504
		 *	 and enable async.c's signal handler to execute NOTIFY directly.
1505 1506 1507
		 * ----------------
		 */
		QueryCancel = false;	/* forget any earlier CANCEL signal */
1508
		SetWaitingForLock(false);
1509 1510 1511 1512

		EnableNotifyInterrupt();

		/* ----------------
1513
		 *	 (3) read a command (loop blocks here)
1514 1515
		 * ----------------
		 */
1516 1517
		set_ps_display("idle");

1518
		firstchar = ReadCommand(parser_input);
1519

1520
		QueryCancel = false;	/* forget any earlier CANCEL signal */
1521

1522
		/* ----------------
1523 1524 1525 1526 1527 1528 1529
		 *	 (4) disable async.c's signal handler.
		 * ----------------
		 */
		DisableNotifyInterrupt();

		/* ----------------
		 *	 (5) process the command.
1530 1531
		 * ----------------
		 */
1532 1533 1534
		switch (firstchar)
		{
				/* ----------------
1535 1536
				 *	'F' indicates a fastpath call.
				 *		XXX HandleFunctionRequest
1537 1538
				 * ----------------
				 */
1539
			case 'F':
1540 1541
				IsEmptyQuery = false;

1542
				/* start an xact for this function invocation */
1543 1544
				if (DebugLvl >= 1)
					elog(DEBUG, "StartTransactionCommand");
1545
				StartTransactionCommand();
1546

1547 1548 1549 1550 1551 1552
				if (HandleFunctionRequest() == EOF)
				{
					/* lost frontend connection during F message input */
					pq_close();
					proc_exit(0);
				}
1553
				break;
1554

1555 1556 1557 1558 1559
				/* ----------------
				 *	'Q' indicates a user query
				 * ----------------
				 */
			case 'Q':
1560
				if (strspn(parser_input->data, " \t\n") == parser_input->len)
1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575
				{
					/* ----------------
					 *	if there is nothing in the input buffer, don't bother
					 *	trying to parse and execute anything..
					 * ----------------
					 */
					IsEmptyQuery = true;
				}
				else
				{
					/* ----------------
					 *	otherwise, process the input string.
					 * ----------------
					 */
					IsEmptyQuery = false;
1576
					if (Show_query_stats)
1577 1578 1579
						ResetUsage();

					/* start an xact for this query */
1580 1581
					if (DebugLvl >= 1)
						elog(DEBUG, "StartTransactionCommand");
1582
					StartTransactionCommand();
1583

1584 1585 1586
					pg_exec_query_dest(parser_input->data,
									   whereToSendOutput,
									   QueryContext);
1587

1588 1589 1590 1591 1592 1593
					/*
					 * Invoke IMMEDIATE constraint triggers
					 *
					 */
					DeferredTriggerEndQuery();

1594
					if (Show_query_stats)
1595 1596
					{
						fprintf(StatFp, "QUERY STATISTICS\n");
1597
						ShowUsage();
1598
					}
1599 1600 1601 1602
				}
				break;

				/* ----------------
1603 1604 1605
				 *	'X' means that the frontend is closing down the socket.
				 *	EOF means unexpected loss of frontend connection.
				 *	Either way, perform normal shutdown.
1606 1607 1608
				 * ----------------
				 */
			case 'X':
1609
			case EOF:
1610 1611
				if (!IsUnderPostmaster)
					ShutdownXLOG();
1612
				pq_close();
1613
				proc_exit(0);
1614 1615 1616
				break;

			default:
M
 
Marc G. Fournier 已提交
1617
				elog(ERROR, "unknown frontend message was received");
1618 1619 1620
		}

		/* ----------------
1621
		 *	 (6) commit the current transaction
1622 1623
		 *
		 *	 Note: if we had an empty input buffer, then we didn't
1624 1625
		 *	 call pg_exec_query_dest, so we don't bother to commit
		 *	 this transaction.
1626 1627 1628 1629
		 * ----------------
		 */
		if (!IsEmptyQuery)
		{
1630 1631
			if (DebugLvl >= 1)
				elog(DEBUG, "CommitTransactionCommand");
1632
			set_ps_display("commit");
1633
			CommitTransactionCommand();
1634 1635 1636
#ifdef SHOW_MEMORY_STATS
			/* print global-context stats at each commit for leak tracking */
			if (ShowStats)
1637
				MemoryContextStats(TopMemoryContext);
1638
#endif
1639 1640 1641
		}
		else
		{
1642
			if (IsUnderPostmaster)
1643 1644
				NullCommand(Remote);
		}
1645 1646 1647 1648 1649 1650 1651

#ifdef MEMORY_CONTEXT_CHECKING
		/*
		 * Check all memory after each backend loop
		 */
		MemoryContextCheck(TopMemoryContext);	
#endif
1652
	}							/* infinite for-loop */
1653 1654

	proc_exit(0);				/* shouldn't get here... */
1655
	return 1;
1656 1657
}

1658
#ifndef HAVE_GETRUSAGE
B
Bruce Momjian 已提交
1659 1660
#include "rusagestub.h"
#else
1661
#include <sys/resource.h>
1662
#endif	 /* HAVE_GETRUSAGE */
1663

1664 1665
struct rusage Save_r;
struct timeval Save_t;
1666 1667

void
1668
ResetUsage(void)
1669
{
1670 1671 1672 1673 1674 1675
	struct timezone tz;

	getrusage(RUSAGE_SELF, &Save_r);
	gettimeofday(&Save_t, &tz);
	ResetBufferUsage();
/*	  ResetTupleCount(); */
1676 1677 1678
}

void
1679
ShowUsage(void)
1680
{
1681 1682 1683
	struct timeval user,
				sys;
	struct timeval elapse_t;
1684
	struct timezone tz;
1685
	struct rusage r;
1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706

	getrusage(RUSAGE_SELF, &r);
	gettimeofday(&elapse_t, &tz);
	memmove((char *) &user, (char *) &r.ru_utime, sizeof(user));
	memmove((char *) &sys, (char *) &r.ru_stime, sizeof(sys));
	if (elapse_t.tv_usec < Save_t.tv_usec)
	{
		elapse_t.tv_sec--;
		elapse_t.tv_usec += 1000000;
	}
	if (r.ru_utime.tv_usec < Save_r.ru_utime.tv_usec)
	{
		r.ru_utime.tv_sec--;
		r.ru_utime.tv_usec += 1000000;
	}
	if (r.ru_stime.tv_usec < Save_r.ru_stime.tv_usec)
	{
		r.ru_stime.tv_sec--;
		r.ru_stime.tv_usec += 1000000;
	}

1707 1708 1709 1710 1711 1712
	/*
	 * Set output destination if not otherwise set
	 */
	if (StatFp == NULL)
		StatFp = stderr;

1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736
	/*
	 * the only stats we don't show here are for memory usage -- i can't
	 * figure out how to interpret the relevant fields in the rusage
	 * struct, and they change names across o/s platforms, anyway. if you
	 * can figure out what the entries mean, you can somehow extract
	 * resident set size, shared text size, and unshared data and stack
	 * sizes.
	 */

	fprintf(StatFp, "! system usage stats:\n");
	fprintf(StatFp,
			"!\t%ld.%06ld elapsed %ld.%06ld user %ld.%06ld system sec\n",
			(long int) elapse_t.tv_sec - Save_t.tv_sec,
			(long int) elapse_t.tv_usec - Save_t.tv_usec,
			(long int) r.ru_utime.tv_sec - Save_r.ru_utime.tv_sec,
			(long int) r.ru_utime.tv_usec - Save_r.ru_utime.tv_usec,
			(long int) r.ru_stime.tv_sec - Save_r.ru_stime.tv_sec,
			(long int) r.ru_stime.tv_usec - Save_r.ru_stime.tv_usec);
	fprintf(StatFp,
			"!\t[%ld.%06ld user %ld.%06ld sys total]\n",
			(long int) user.tv_sec,
			(long int) user.tv_usec,
			(long int) sys.tv_sec,
			(long int) sys.tv_usec);
1737
#ifdef HAVE_GETRUSAGE
1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762
	fprintf(StatFp,
			"!\t%ld/%ld [%ld/%ld] filesystem blocks in/out\n",
			r.ru_inblock - Save_r.ru_inblock,
	/* they only drink coffee at dec */
			r.ru_oublock - Save_r.ru_oublock,
			r.ru_inblock, r.ru_oublock);
	fprintf(StatFp,
		  "!\t%ld/%ld [%ld/%ld] page faults/reclaims, %ld [%ld] swaps\n",
			r.ru_majflt - Save_r.ru_majflt,
			r.ru_minflt - Save_r.ru_minflt,
			r.ru_majflt, r.ru_minflt,
			r.ru_nswap - Save_r.ru_nswap,
			r.ru_nswap);
	fprintf(StatFp,
	 "!\t%ld [%ld] signals rcvd, %ld/%ld [%ld/%ld] messages rcvd/sent\n",
			r.ru_nsignals - Save_r.ru_nsignals,
			r.ru_nsignals,
			r.ru_msgrcv - Save_r.ru_msgrcv,
			r.ru_msgsnd - Save_r.ru_msgsnd,
			r.ru_msgrcv, r.ru_msgsnd);
	fprintf(StatFp,
		 "!\t%ld/%ld [%ld/%ld] voluntary/involuntary context switches\n",
			r.ru_nvcsw - Save_r.ru_nvcsw,
			r.ru_nivcsw - Save_r.ru_nivcsw,
			r.ru_nvcsw, r.ru_nivcsw);
1763
#endif	 /* HAVE_GETRUSAGE */
1764 1765 1766
	fprintf(StatFp, "! postgres usage stats:\n");
	PrintBufferUsage(StatFp);
/*	   DisplayTupleCount(StatFp); */
1767
}
M
 
Marc G. Fournier 已提交
1768

1769 1770
#ifdef NOT_USED
static int
M
 
Marc G. Fournier 已提交
1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782
assertEnable(int val)
{
	assert_enabled = val;
	return val;
}

#ifdef ASSERT_CHECKING_TEST
int
assertTest(int val)
{
	Assert(val == 0);

1783 1784
	if (assert_enabled)
	{
M
 
Marc G. Fournier 已提交
1785 1786 1787
		/* val != 0 should be trapped by previous Assert */
		elog(NOTICE, "Assert test successfull (val = %d)", val);
	}
1788 1789
	else
		elog(NOTICE, "Assert checking is disabled (val = %d)", val);
M
 
Marc G. Fournier 已提交
1790 1791 1792

	return val;
}
1793

M
 
Marc G. Fournier 已提交
1794 1795
#endif
#endif