postgres.c 43.1 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.169 2000/07/12 17:38:45 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"
M
 
Marc G. Fournier 已提交
59
#include "utils/ps_status.h"
60
#include "utils/temprel.h"
61
#ifdef MULTIBYTE
B
Bruce Momjian 已提交
62
#include "mb/pg_wchar.h"
63 64
#endif

M
 
Marc G. Fournier 已提交
65

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

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

bool Log_connections = false;

79
CommandDest whereToSendOutput = Debug;
80

81

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

85
extern void HandleDeadLock(SIGNAL_ARGS);
86

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

90
static bool	dontExecute = false;
91

92
static bool IsEmptyQuery = false;
93

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

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

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

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

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

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

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

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

/*
 * 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;
141 142 143


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

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

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

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

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

174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
	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)
					{
189 190 191
						/* discard backslash from inBuf */
						inBuf->data[--inBuf->len] = '\0';
						backslashSeen = false;
192 193 194 195 196
						continue;
					}
					else
					{
						/* keep the newline character */
197
						appendStringInfoChar(inBuf, '\n');
198 199 200 201 202 203 204 205
						break;
					}
				}
				else if (c == '\\')
					backslashSeen = true;
				else
					backslashSeen = false;

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

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

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

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

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

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

243
	return 'Q';
244 245 246
}

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

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

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

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

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

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

304 305 306 307 308 309 310 311
			/* ----------------
			 *	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:
312
			elog(FATAL, "Socket command type %c unknown", qtype);
313
			break;
314 315
	}
	return result;
316 317 318
}

/* ----------------
319 320 321
 *		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
322
 *		call.  EOF is returned if end of file.
323 324
 * ----------------
 */
325
static int
326
ReadCommand(StringInfo inBuf)
327
{
328
	int			result;
329

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

337 338 339 340 341 342 343

/*
 * 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.
 */
344
List *
345 346 347
pg_parse_and_rewrite(char *query_string,	/* string to execute */
					 Oid *typev,			/* parameter types */
					 int nargs)				/* number of parameters */
348
{
349
	List	   *querytree_list;
350
	List	   *querytree_list_item;
351
	Query	   *querytree;
352
	List	   *new_list;
353

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

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

	querytree_list = parser(query_string, typev, nargs);

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

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

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

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

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

	querytree_list = new_list;

411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
#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.
	 *
	 * Currently, copyObject doesn't know about most of the utility query
	 * types, so suppress the check until that can be fixed... it should
	 * be fixed, though.
	 */
	if (querytree_list &&
		((Query *) lfirst(querytree_list))->commandType != CMD_UTILITY)
	{
		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;
	}
#endif

436
	if (Debug_print_rewritten)
437
	{
438
		if (Debug_pretty_print)
B
Bruce Momjian 已提交
439
		{
440
			elog(DEBUG, "rewritten parse tree:");
B
Bruce Momjian 已提交
441
			foreach(querytree_list_item, querytree_list)
J
Jan Wieck 已提交
442
			{
443 444
				querytree = (Query *) lfirst(querytree_list_item);
				nodeDisplay(querytree);
J
Jan Wieck 已提交
445 446
				printf("\n");
			}
B
Bruce Momjian 已提交
447 448 449
		}
		else
		{
450
			elog(DEBUG, "rewritten parse tree:");
J
Jan Wieck 已提交
451

B
Bruce Momjian 已提交
452
			foreach(querytree_list_item, querytree_list)
J
Jan Wieck 已提交
453
			{
454
				querytree = (Query *) lfirst(querytree_list_item);
455
				elog(DEBUG, "%s", nodeToString(querytree));
J
Jan Wieck 已提交
456
			}
457 458 459
		}
	}

460 461
	return querytree_list;
}
462 463


464 465 466 467 468
/* Generate a plan for a single query. */
Plan *
pg_plan_query(Query *querytree)
{
	Plan	   *plan;
469

470 471 472
	/* Utility commands have no plans. */
	if (querytree->commandType == CMD_UTILITY)
		return NULL;
473

474
	if (Show_planner_stats)
475
		ResetUsage();
476

477 478
	/* call that optimizer */
	plan = planner(querytree);
479

480
	if (Show_planner_stats)
481
	{
482
		fprintf(stderr, "PLANNER STATISTICS\n");
483 484
		ShowUsage();
	}
485

486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
#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

504 505 506 507
	/* ----------------
	 *	Print plan if debugging.
	 * ----------------
	 */
508
	if (Debug_print_plan)
509
	{
510
		if (Debug_pretty_print)
511
		{
512
			elog(DEBUG, "plan:");
513
			nodeDisplay(plan);
514 515
		}
		else
516
			elog(DEBUG, "plan: %s", nodeToString(plan));
517 518
	}

519
	return plan;
520 521
}

522

523
/* ----------------------------------------------------------------
524
 *		pg_exec_query_dest()
525 526
 *
 *		Takes a querystring, runs the parser/utilities or
527 528 529 530 531 532 533 534 535 536 537 538
 *		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!
539
 *
540 541
 * parse_context references a context suitable for holding the
 * parse/rewrite trees (typically this will be QueryContext).
542
 * This context *must* be longer-lived than the CurrentMemoryContext!
543 544 545 546 547 548 549
 * 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.
550 551 552 553 554
 *
 * ----------------------------------------------------------------
 */

void
555
pg_exec_query_dest(char *query_string,	/* string to execute */
556
				   CommandDest dest,	/* where results should go */
557
				   MemoryContext parse_context)	/* context for parsetrees */
558
{
559 560 561
	MemoryContext oldcontext;
	List	   *querytree_list,
			   *querytree_item;
562

563 564 565 566 567 568 569 570 571 572
	/*
	 * 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);

573 574 575 576
	/*
	 * Switch to appropriate context for constructing parsetrees.
	 */
	oldcontext = MemoryContextSwitchTo(parse_context);
577

B
Bruce Momjian 已提交
578
	/*
579
	 * Parse and rewrite the query or queries.
580
	 */
581
	querytree_list = pg_parse_and_rewrite(query_string, NULL, 0);
582

583 584 585 586 587 588 589 590 591 592 593
	/*
	 * 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);
594 595 596 597

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

599 600 601 602 603 604 605 606 607
		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.
			 * ----------------
			 */
608 609 610 611
			if (Debug_print_query)
				elog(DEBUG, "ProcessUtility: %s", query_string);
			else if (DebugLvl > 1)
				elog(DEBUG, "ProcessUtility");
612 613 614 615 616

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

619
			/* If aborted transaction, skip planning and execution */
620
			if (IsAbortedTransactionBlockState())
621
			{
622 623 624 625 626 627 628 629 630 631 632 633
				/* ----------------
				 *	 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);

634 635
				/*
				 * We continue in the loop, on the off chance that there
636 637 638 639
				 * is a COMMIT or ROLLBACK utility command later in the
				 * query string.
				 */
				continue;
640 641
			}

642 643 644 645 646 647 648
			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 已提交
649 650 651
			SetQuerySnapshot();

			/*
B
Bruce Momjian 已提交
652
			 * execute the plan
653
			 */
654
			if (Show_executor_stats)
655 656
				ResetUsage();

657 658 659 660 661 662 663 664 665 666 667
			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);
			}
668

669
			if (Show_executor_stats)
670
			{
671
				fprintf(stderr, "EXECUTOR STATISTICS\n");
672 673 674 675 676 677 678 679 680
				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.
		 */
681
		CommandCounterIncrement();
682 683 684 685 686 687 688 689
		/*
		 * 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);
690
	}
691 692 693
}

/* --------------------------------
694
 *		signal handler routines used in PostgresMain()
695
 *
B
Bruce Momjian 已提交
696
 *		handle_warn() catches SIGQUIT.	It forces control back to the main
697 698 699
 *		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 已提交
700
 *		siglongjmp() instead.
701
 *		We still provide the signal catcher so that an error quit can be
B
Bruce Momjian 已提交
702
 *		forced externally.	This should be done only with great caution,
703 704
 *		however, since an asynchronous signal could leave the system in
 *		who-knows-what inconsistent state.
705
 *
706 707 708
 *		quickdie() occurs when signalled by the postmaster.
 *		Some backend has bought the farm,
 *		so we need to stop what we're doing and exit.
709
 *
710
 *		die() performs an orderly cleanup via proc_exit()
711 712 713 714
 * --------------------------------
 */

void
715
handle_warn(SIGNAL_ARGS)
716
{
717
	siglongjmp(Warn_restart, 1);
718 719
}

720
static void
721
quickdie(SIGNAL_ARGS)
722
{
723
	PG_SETMASK(&BlockSig);
724
	elog(NOTICE, "Message from PostgreSQL backend:"
725 726 727 728 729
		 "\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.");
730

731 732

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

738
	exit(1);
739 740
}

741 742 743
/*
 * Abort transaction and exit
 */
744
void
745
die(SIGNAL_ARGS)
746
{
747
	PG_SETMASK(&BlockSig);
748

749 750 751 752 753 754 755 756 757
	/*
	 * If ERROR/FATAL is in progress...
	 */
	if (InError)
	{
		ExitAfterAbort = true;
		return;
	}
	elog(FATAL, "The system is shutting down");
758 759 760
}

/* signal handler for floating point exception */
761
static void
762
FloatExceptionHandler(SIGNAL_ARGS)
763
{
764
	elog(ERROR, "floating point exception!"
765 766
		 " The last floating point operation either exceeded legal ranges"
		 " or was a divide by zero");
767 768
}

M
 
Marc G. Fournier 已提交
769
/* signal handler for query cancel signal from postmaster */
770 771 772 773
static void
QueryCancelHandler(SIGNAL_ARGS)
{
	QueryCancel = true;
774
	LockWaitCancel();
775 776 777 778 779
}

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

781 782
	/*
	 * QueryCancel flag will be reset in main loop, which we reach by
M
 
Marc G. Fournier 已提交
783 784
	 * longjmp from elog().
	 */
785 786 787
	elog(ERROR, "Query was cancelled.");
}

788 789 790
static void
SigHupHandler(SIGNAL_ARGS)
{
791
	got_SIGHUP = true;
792 793
}

794

795 796
static void
usage(char *progname)
797
{
798
	fprintf(stderr,
799
			"Usage: %s [options] [dbname]\n", progname);
M
 
Marc G. Fournier 已提交
800
#ifdef USE_ASSERT_CHECKING
T
Tom Lane 已提交
801
	fprintf(stderr, "\t-A on\t\tenable/disable assert checking\n");
M
 
Marc G. Fournier 已提交
802
#endif
803
	fprintf(stderr, "\t-B buffers\tset number of buffers in buffer pool\n");
T
Tom Lane 已提交
804
	fprintf(stderr, "\t-C \t\tsuppress version info\n");
805 806
	fprintf(stderr, "\t-D dir\t\tdata directory\n");
	fprintf(stderr, "\t-E \t\techo query before execution\n");
807
	fprintf(stderr, "\t-F \t\tturn fsync off\n");
808 809
	fprintf(stderr, "\t-L \t\tturn off locking\n");
	fprintf(stderr, "\t-N \t\tdon't use newline as interactive query delimiter\n");
810
	fprintf(stderr, "\t-O \t\tallow system table structure changes\n");
811
	fprintf(stderr, "\t-Q \t\tsuppress informational messages\n");
812
	fprintf(stderr, "\t-S kbytes\tset amount of memory for sorts (in kbytes)\n");
T
Tom Lane 已提交
813 814
	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 已提交
815
	fprintf(stderr, "\t-d [1-5]\tset debug level\n");
816
	fprintf(stderr, "\t-e \t\tturn on European date format\n");
T
Tom Lane 已提交
817
	fprintf(stderr, "\t-f [s|i|n|m|h]\tforbid use of some plan types\n");
818 819 820
	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");
821
	fprintf(stderr, "\t-s \t\tshow stats after each query\n");
822
	fprintf(stderr, "\t-t [pa|pl|ex]\tshow timings after each query\n");
823
	fprintf(stderr, "\t-v version\tset protocol version being used by frontend\n");
824 825 826
}

/* ----------------------------------------------------------------
827 828
 *	PostgresMain
 *		postgres main loop
829
 *		all backends, interactive or otherwise start here
830 831 832 833 834
 *
 *	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.
835 836 837
 * ----------------------------------------------------------------
 */
int
838
PostgresMain(int argc, char *argv[], int real_argc, char *real_argv[])
839
{
840
	int			flag;
841

842
	char	   *DBName = NULL;
843
	bool		secure = true;
844
	int			errs = 0;
845

846
	int			firstchar;
847
	StringInfo	parser_input;
848
	char	   *userName;
M
 
Marc G. Fournier 已提交
849

850 851
	char	   *remote_host;
	unsigned short remote_port;
852

853 854
	extern int	optind;
	extern char *optarg;
855
	extern int	DebugLvl;
856

857 858 859 860 861 862 863 864 865 866 867
	/*
	 * Fire up essential subsystems: error and memory management
	 *
	 * If we are running under the postmaster, this is done already.
	 */
	if (!IsUnderPostmaster)
	{
		EnableExceptionHandling(true);
		MemoryContextInit();
	}

868
	/*
869
	 * Set default values for command-line options.
870
	 */
871 872
	Noversion = false;
	EchoQuery = false;
873 874 875 876 877 878 879

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

882 883
	SetProcessingMode(InitProcessing);

884 885
	/* Check for PGDATESTYLE environment variable */
	set_default_datestyle();
886

887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904
	/* ----------------
	 *	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 */
905

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

917 918 919 920 921
			case 'B':
				/* ----------------
				 *	specify the size of buffer pool
				 * ----------------
				 */
922 923
				if (secure)
					NBuffers = atoi(optarg);
924
				break;
925

926 927
			case 'C':
				/* ----------------
928
				 *	don't print version string
929 930
				 * ----------------
				 */
931
				Noversion = true;
932
				break;
933

934
			case 'D':			/* PGDATA directory */
935
				if (secure)
936 937 938 939 940
				{
					if (DataDir)
						free(DataDir);
					DataDir = strdup(optarg);
				}
M
 
Marc G. Fournier 已提交
941
				break;
942

943
			case 'd':			/* debug level */
944
				DebugLvl = atoi(optarg);
945 946
				if (DebugLvl >= 1);
					Log_connections = true;
M
 
Marc G. Fournier 已提交
947
				if (DebugLvl >= 2)
948
					Debug_print_query = true;
M
 
Marc G. Fournier 已提交
949
				if (DebugLvl >= 3)
950
					Debug_print_parse = true;
B
Bruce Momjian 已提交
951
				if (DebugLvl >= 4)
952
					Debug_print_plan = true;
J
Jan Wieck 已提交
953
				if (DebugLvl >= 5)
954
					Debug_print_rewritten = true;
955
				break;
956 957 958 959 960 961

			case 'E':
				/* ----------------
				 *	E - echo the query the user entered
				 * ----------------
				 */
962
				EchoQuery = true;
963
				break;
964 965 966 967 968 969

			case 'e':
				/* --------------------------
				 * Use european date formats.
				 * --------------------------
				 */
970
				EuroDates = true;
971
				break;
972 973 974 975

			case 'F':
				/* --------------------
				 *	turn off fsync
976 977 978 979
				 *
				 *	7.0 buffer manager can support different backends running
				 *	with different fsync settings, so this no longer needs
				 *	to be "if (secure)".
980 981
				 * --------------------
				 */
982
				enableFsync = false;
983
				break;
984 985 986 987 988 989 990 991 992

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

1015
			case 'i':
1016
				dontExecute = true;
1017
				break;
1018

1019 1020 1021 1022 1023
			case 'L':
				/* --------------------
				 *	turn off locking
				 * --------------------
				 */
1024 1025
				if (secure)
					lockingOff = 1;
T
Tom Lane 已提交
1026 1027
				break;

1028 1029 1030 1031 1032 1033 1034
			case 'N':
				/* ----------------
				 *	N - Don't use newline as a query delimiter
				 * ----------------
				 */
				UseNewLine = 0;
				break;
1035

1036 1037 1038 1039 1040
			case 'O':
				/* --------------------
				 *	allow system table structure modifications
				 * --------------------
				 */
1041 1042
				if (secure)		/* XXX safe to allow from client??? */
					allowSystemTableMods = true;
1043 1044
				break;

H
Hiroshi Inoue 已提交
1045 1046 1047 1048 1049 1050 1051 1052 1053
			case 'P':
				/* --------------------
				 *	ignore system indexes
				 * --------------------
				 */
				if (secure)		/* XXX safe to allow from client??? */
					IgnoreSystemIndexes(true);
				break;

T
Tom Lane 已提交
1054 1055 1056 1057 1058
			case 'o':
				/* ----------------
				 *	o - send output (stdout and stderr) to the given file
				 * ----------------
				 */
1059 1060
				if (secure)
					StrNCpy(OutputFileName, optarg, MAXPGPATH);
T
Tom Lane 已提交
1061 1062
				break;

1063
			case 'p':
1064 1065 1066 1067 1068
				/* ----------------
				 *	p - special flag passed if backend was forked
				 *		by a postmaster.
				 * ----------------
				 */
1069 1070
				if (secure)
				{
1071
					DBName = strdup(optarg);
B
Bruce Momjian 已提交
1072 1073
					secure = false;		/* subsequent switches are NOT
										 * secure */
1074
				}
1075
				break;
1076

1077 1078
			case 'S':
				/* ----------------
V
Vadim B. Mikheev 已提交
1079
				 *	S - amount of sort memory to use in 1k bytes
1080 1081
				 * ----------------
				 */
1082
				{
1083 1084
					int			S;

V
Vadim B. Mikheev 已提交
1085
					S = atoi(optarg);
1086
					if (S >= 4 * BLCKSZ / 1024)
V
Vadim B. Mikheev 已提交
1087
						SortMem = S;
1088
				}
1089
				break;
1090 1091 1092 1093 1094 1095

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

1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113
			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')
1114
							Show_parser_stats = 1;
1115
						else if (optarg[1] == 'l')
1116
							Show_planner_stats = 1;
1117 1118 1119 1120
						else
							errs++;
						break;
					case 'e':
1121
						Show_executor_stats = 1;
1122 1123 1124 1125 1126
						break;
					default:
						errs++;
						break;
				}
1127 1128
				break;

1129
			case 'v':
1130 1131
				if (secure)
					FrontendProtocol = (ProtocolVersion) atoi(optarg);
1132 1133
				break;

M
 
Marc G. Fournier 已提交
1134 1135
			case 'W':
				/* ----------------
1136
				 *	wait N seconds to allow attach from a debugger
M
 
Marc G. Fournier 已提交
1137 1138 1139 1140 1141
				 * ----------------
				 */
				sleep(atoi(optarg));
				break;

1142
			case 'x':
B
Bruce Momjian 已提交
1143
#ifdef NOT_USED					/* planner/xfunc.h */
1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171

				/*
				 * 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++;
				}
1172
#endif
1173
				break;
1174

1175 1176
			case '-':
			{
1177
				char *name, *value;
1178

1179 1180
				ParseLongOption(optarg, &name, &value);
				if (!value)
1181
					elog(ERROR, "--%s requires argument", optarg);
1182 1183 1184 1185 1186

				SetConfigOption(name, value, PGC_BACKEND);
				free(name);
				if (value)
					free(value);
1187 1188 1189
				break;
			}

1190 1191 1192 1193 1194 1195
			default:
				/* ----------------
				 *	default: bad command line option
				 * ----------------
				 */
				errs++;
T
Tom Lane 已提交
1196
				break;
1197 1198
		}

1199 1200
	if (Show_query_stats &&
		(Show_parser_stats || Show_planner_stats || Show_executor_stats))
1201
	{
1202 1203
		elog(NOTICE, "Query statistics are disabled because parser, planner, or executor statistics are on.");
		Show_query_stats = false;
1204 1205 1206 1207 1208 1209 1210
	}

	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 "
1211
			 "option or by setting the PGDATA environment variable.\n\n",
1212 1213 1214 1215 1216
				argv[0]);
		proc_exit(1);
	}

	/*
1217 1218 1219
	 * 1. Set BlockSig and UnBlockSig masks. 2. Set up signal handlers. 3.
	 * Allow only SIGUSR1 signal (we never block it) during
	 * initialization.
1220 1221 1222
	 *
	 * Note that postmaster already blocked ALL signals to make us happy.
	 */
1223
	pqinitmask();
1224 1225 1226 1227 1228 1229 1230

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

1231 1232
	PG_SETMASK(&BlockSig);		/* block everything except SIGUSR1 */

1233
	pqsignal(SIGHUP, SigHupHandler);	/* set flag to read config file */
1234 1235
	pqsignal(SIGINT, QueryCancelHandler);		/* cancel current query */
	pqsignal(SIGQUIT, handle_warn);		/* handle error */
1236 1237
	pqsignal(SIGTERM, die);
	pqsignal(SIGALRM, HandleDeadLock);
1238 1239 1240 1241 1242

	/*
	 * 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
1243 1244 1245 1246
	 * midst of output during who-knows-what operation...
	 */
	pqsignal(SIGPIPE, SIG_IGN);
	pqsignal(SIGUSR1, quickdie);
1247
	pqsignal(SIGUSR2, Async_NotifyHandler);		/* flush also sinval cache */
1248
	pqsignal(SIGFPE, FloatExceptionHandler);
1249
	pqsignal(SIGCHLD, SIG_IGN); /* ignored, sent by LockOwners */
1250 1251 1252 1253 1254 1255 1256
	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
1257 1258 1259 1260
	 */
	SetPgUserName();
	userName = GetPgUserName();

1261
	if (IsUnderPostmaster)
1262
	{
1263 1264 1265 1266
		/* noninteractive case: nothing should be left after switches */
		if (errs || argc != optind || DBName == NULL)
		{
			usage(argv[0]);
1267
			proc_exit(0);
1268
		}
1269 1270 1271
		pq_init();				/* initialize libpq at backend startup */
		whereToSendOutput = Remote;
		BaseInit();
1272
	}
1273
	else
1274
	{
1275
		/* interactive case: database name can be last arg on command line */
1276
		whereToSendOutput = Debug;
1277 1278 1279
		if (errs || argc - optind > 1)
		{
			usage(argv[0]);
1280
			proc_exit(0);
1281 1282 1283 1284 1285 1286 1287
		}
		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]);
1288
			proc_exit(0);
1289
		}
1290 1291 1292 1293 1294

		/*
		 * Try to create pid file.
		 */
		SetPidFname(DataDir);
1295
		if (SetPidFile(-getpid()))
1296
			proc_exit(0);
1297

1298 1299 1300 1301 1302
		/*
		 * Register clean up proc.
		 */
		on_proc_exit(UnlinkPidFile, NULL);

1303
		BaseInit();
1304 1305
		snprintf(XLogDir, MAXPGPATH, "%s/pg_xlog", DataDir);
		snprintf(ControlFilePath, MAXPGPATH, "%s/global/pg_control", DataDir);
1306
		StartupXLOG();
1307 1308
	}

1309 1310 1311 1312 1313 1314 1315 1316
	/*
	 * Set up additional info.
	 */

#ifdef CYR_RECODE
	SetCharSet();
#endif

1317
	/* On some systems our dynloader code needs the executable's pathname */
1318
	if (FindExec(pg_pathname, real_argv[0], "postgres") < 0)
1319
		elog(FATAL, "%s: could not locate executable, bailing out...",
1320
			 real_argv[0]);
1321

M
 
Marc G. Fournier 已提交
1322 1323 1324
	/*
	 * Find remote host name or address.
	 */
1325 1326
	remote_host = NULL;

1327 1328
	if (IsUnderPostmaster)
	{
1329
		if (MyProcPort->raddr.sa.sa_family == AF_INET)
1330
		{
1331 1332
			struct hostent *host_ent;
			char * host_addr;
M
 
Marc G. Fournier 已提交
1333

1334 1335 1336 1337 1338 1339 1340 1341
			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)
1342
				{
1343 1344
					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 已提交
1345
				}
1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357
			}

			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 已提交
1358
		}
1359 1360 1361
		else /* not AF_INET */
			remote_host = "[local]";

1362

1363
		/*
1364 1365 1366 1367 1368 1369
		 * 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.
1370
		 */
1371 1372
		init_ps_display(real_argc, real_argv, userName, DBName, remote_host);
		set_ps_display("startup");
1373 1374
	}

1375 1376 1377
	if (Log_connections)
		elog(DEBUG, "connection: host=%s user=%s database=%s",
			 remote_host, userName, DBName);
1378

1379 1380
	/*
	 * general initialization
1381
	 */
1382 1383
	if (DebugLvl > 1)
		elog(DEBUG, "InitPostgres");
1384 1385
	InitPostgres(DBName);

1386
#ifdef MULTIBYTE
1387
	/* set default client encoding */
1388 1389
	if (DebugLvl > 1)
		elog(DEBUG, "reset_client_encoding");
1390 1391 1392
	reset_client_encoding();
#endif

1393 1394
	on_shmem_exit(remove_all_temp_relations, NULL);

1395 1396
	/*
	 * Send this backend's cancellation info to the frontend.
1397
	 */
M
 
Marc G. Fournier 已提交
1398 1399 1400
	if (whereToSendOutput == Remote &&
		PG_PROTOCOL_MAJOR(FrontendProtocol) >= 2)
	{
1401
		StringInfoData buf;
B
Bruce Momjian 已提交
1402

1403 1404 1405 1406 1407
		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 已提交
1408 1409 1410
		/* Need not flush since ReadyForQuery will do it. */
	}

1411 1412 1413
	if (!IsUnderPostmaster)
	{
		puts("\nPOSTGRES backend interactive interface ");
1414
		puts("$Revision: 1.169 $ $Date: 2000/07/12 17:38:45 $\n");
1415 1416
	}

1417
	/*
1418 1419 1420
	 * Initialize the deferred trigger manager
	 */
	if (DeferredTriggerInit() != 0)
1421
		proc_exit(0);
1422 1423

	SetProcessingMode(NormalProcessing);
1424

1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438
	/*
	 * 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);

1439 1440
	/*
	 * POSTGRES main processing loop begins here
1441
	 *
1442 1443
	 * If an exception is encountered, processing resumes here so we abort
	 * the current transaction and start a new one.
1444 1445 1446 1447
	 */

	if (sigsetjmp(Warn_restart, 1) != 0)
	{
1448 1449 1450 1451 1452 1453 1454
		/*
		 * 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);
1455

1456 1457
		if (DebugLvl >= 1)
			elog(DEBUG, "AbortCurrentTransaction");
1458
		AbortCurrentTransaction();
1459

1460 1461
		if (ExitAfterAbort)
		{
1462
			ProcReleaseLocks(); /* Just to be sure... */
1463
			proc_exit(0);
1464
		}
1465 1466 1467 1468 1469 1470 1471
		/*
		 * If we recovered successfully, return to normal top-level context
		 * and clear ErrorContext for next time.
		 */
		MemoryContextSwitchTo(TopMemoryContext);
		MemoryContextResetAndDeleteChildren(ErrorContext);
		InError = false;
1472
	}
1473

1474 1475
	Warn_restart_ready = true;	/* we can now handle elog(ERROR) */

1476
	PG_SETMASK(&UnBlockSig);
1477

1478 1479
	/*
	 * Non-error queries loop here.
1480 1481 1482 1483
	 */

	for (;;)
	{
1484 1485 1486 1487 1488 1489 1490 1491
		/*
		 * 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();
1492

1493 1494 1495 1496 1497 1498 1499 1500
		/* 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 已提交
1501
		/* ----------------
1502 1503
		 *	 (1) tell the frontend we're ready for a new query.
		 *
B
Bruce Momjian 已提交
1504
		 *	 Note: this includes fflush()'ing the last of the prior output.
B
Bruce Momjian 已提交
1505 1506
		 * ----------------
		 */
1507
		ReadyForQuery(whereToSendOutput);
B
Bruce Momjian 已提交
1508

1509
		/* ----------------
1510
		 *	 (2) deal with pending asynchronous NOTIFY from other backends,
B
Bruce Momjian 已提交
1511
		 *	 and enable async.c's signal handler to execute NOTIFY directly.
1512 1513 1514
		 * ----------------
		 */
		QueryCancel = false;	/* forget any earlier CANCEL signal */
1515
		SetWaitingForLock(false);
1516 1517 1518 1519

		EnableNotifyInterrupt();

		/* ----------------
1520
		 *	 (3) read a command (loop blocks here)
1521 1522
		 * ----------------
		 */
1523 1524
		set_ps_display("idle");

1525
		firstchar = ReadCommand(parser_input);
1526

1527
		QueryCancel = false;	/* forget any earlier CANCEL signal */
1528

1529
		/* ----------------
1530 1531 1532 1533 1534 1535 1536
		 *	 (4) disable async.c's signal handler.
		 * ----------------
		 */
		DisableNotifyInterrupt();

		/* ----------------
		 *	 (5) process the command.
1537 1538
		 * ----------------
		 */
1539 1540 1541
		switch (firstchar)
		{
				/* ----------------
1542 1543
				 *	'F' indicates a fastpath call.
				 *		XXX HandleFunctionRequest
1544 1545
				 * ----------------
				 */
1546
			case 'F':
1547 1548
				IsEmptyQuery = false;

1549
				/* start an xact for this function invocation */
1550 1551
				if (DebugLvl >= 1)
					elog(DEBUG, "StartTransactionCommand");
1552
				StartTransactionCommand();
1553

1554 1555 1556 1557 1558 1559
				if (HandleFunctionRequest() == EOF)
				{
					/* lost frontend connection during F message input */
					pq_close();
					proc_exit(0);
				}
1560
				break;
1561

1562 1563 1564 1565 1566
				/* ----------------
				 *	'Q' indicates a user query
				 * ----------------
				 */
			case 'Q':
1567
				if (strspn(parser_input->data, " \t\n") == parser_input->len)
1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582
				{
					/* ----------------
					 *	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;
1583
					if (Show_query_stats)
1584 1585 1586
						ResetUsage();

					/* start an xact for this query */
1587 1588
					if (DebugLvl >= 1)
						elog(DEBUG, "StartTransactionCommand");
1589
					StartTransactionCommand();
1590

1591 1592 1593
					pg_exec_query_dest(parser_input->data,
									   whereToSendOutput,
									   QueryContext);
1594

1595 1596 1597 1598 1599 1600
					/*
					 * Invoke IMMEDIATE constraint triggers
					 *
					 */
					DeferredTriggerEndQuery();

1601
					if (Show_query_stats)
1602 1603
					{
						fprintf(StatFp, "QUERY STATISTICS\n");
1604
						ShowUsage();
1605
					}
1606 1607 1608 1609
				}
				break;

				/* ----------------
1610 1611 1612
				 *	'X' means that the frontend is closing down the socket.
				 *	EOF means unexpected loss of frontend connection.
				 *	Either way, perform normal shutdown.
1613 1614 1615
				 * ----------------
				 */
			case 'X':
1616
			case EOF:
1617 1618
				if (!IsUnderPostmaster)
					ShutdownXLOG();
1619
				pq_close();
1620
				proc_exit(0);
1621 1622 1623
				break;

			default:
M
 
Marc G. Fournier 已提交
1624
				elog(ERROR, "unknown frontend message was received");
1625 1626 1627
		}

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

#ifdef MEMORY_CONTEXT_CHECKING
		/*
		 * Check all memory after each backend loop
		 */
		MemoryContextCheck(TopMemoryContext);	
#endif
1659
	}							/* infinite for-loop */
1660 1661

	proc_exit(0);				/* shouldn't get here... */
1662
	return 1;
1663 1664
}

1665
#ifndef HAVE_GETRUSAGE
B
Bruce Momjian 已提交
1666 1667
#include "rusagestub.h"
#else
1668
#include <sys/resource.h>
1669
#endif	 /* HAVE_GETRUSAGE */
1670

1671 1672
struct rusage Save_r;
struct timeval Save_t;
1673 1674

void
1675
ResetUsage(void)
1676
{
1677 1678 1679 1680 1681 1682
	struct timezone tz;

	getrusage(RUSAGE_SELF, &Save_r);
	gettimeofday(&Save_t, &tz);
	ResetBufferUsage();
/*	  ResetTupleCount(); */
1683 1684 1685
}

void
1686
ShowUsage(void)
1687
{
1688 1689 1690
	struct timeval user,
				sys;
	struct timeval elapse_t;
1691
	struct timezone tz;
1692
	struct rusage r;
1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713

	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;
	}

1714 1715 1716 1717 1718 1719
	/*
	 * Set output destination if not otherwise set
	 */
	if (StatFp == NULL)
		StatFp = stderr;

1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743
	/*
	 * 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);
1744
#ifdef HAVE_GETRUSAGE
1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769
	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);
1770
#endif	 /* HAVE_GETRUSAGE */
1771 1772 1773
	fprintf(StatFp, "! postgres usage stats:\n");
	PrintBufferUsage(StatFp);
/*	   DisplayTupleCount(StatFp); */
1774
}
M
 
Marc G. Fournier 已提交
1775

1776 1777
#ifdef NOT_USED
static int
M
 
Marc G. Fournier 已提交
1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789
assertEnable(int val)
{
	assert_enabled = val;
	return val;
}

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

1790 1791
	if (assert_enabled)
	{
M
 
Marc G. Fournier 已提交
1792 1793 1794
		/* val != 0 should be trapped by previous Assert */
		elog(NOTICE, "Assert test successfull (val = %d)", val);
	}
1795 1796
	else
		elog(NOTICE, "Assert checking is disabled (val = %d)", val);
M
 
Marc G. Fournier 已提交
1797 1798 1799

	return val;
}
1800

M
 
Marc G. Fournier 已提交
1801 1802
#endif
#endif