postgres.c 40.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.158 2000/06/04 01:44:33 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

#include <unistd.h>
21
#include <signal.h>
22 23
#include <time.h>
#include <sys/time.h>
B
Bruce Momjian 已提交
24 25
#include <sys/types.h>
#include <fcntl.h>
26
#include <sys/socket.h>
B
Bruce Momjian 已提交
27 28 29

#include "postgres.h"

30
#include <errno.h>
31
#if HAVE_SYS_SELECT_H
32
#include <sys/select.h>
33
#endif	 /* aix */
M
 
Marc G. Fournier 已提交
34 35 36
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
37
#ifdef HAVE_GETOPT_H
B
Bruce Momjian 已提交
38
#include <getopt.h>
39
#endif
40 41

#include "commands/async.h"
42
#include "commands/trigger.h"
43
#include "commands/variable.h"
44
#include "libpq/libpq.h"
45
#include "libpq/pqformat.h"
46
#include "libpq/pqsignal.h"
B
Bruce Momjian 已提交
47
#include "miscadmin.h"
48 49
#include "nodes/print.h"
#include "optimizer/cost.h"
50
#include "optimizer/planner.h"
51
#include "parser/parse.h"
52
#include "parser/parser.h"
B
Bruce Momjian 已提交
53
#include "rewrite/rewriteHandler.h"
54 55
#include "tcop/fastpath.h"
#include "tcop/pquery.h"
B
Bruce Momjian 已提交
56
#include "tcop/tcopprot.h"
57
#include "tcop/utility.h"
58
#include "storage/proc.h"
M
 
Marc G. Fournier 已提交
59
#include "utils/ps_status.h"
60
#include "utils/temprel.h"
61
#include "utils/guc.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 85
extern void BaseInit(void);
extern void StartupXLOG(void);
extern void ShutdownXLOG(void);
86

87
extern void HandleDeadLock(SIGNAL_ARGS);
88

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

92 93
extern int	lockingOff;
extern int	NBuffers;
94

95 96
int			dontExecute = 0;
static bool IsEmptyQuery = false;
97

98
/* note: these declarations had better match tcopprot.h */
B
Bruce Momjian 已提交
99
DLLIMPORT sigjmp_buf Warn_restart;
100

101
bool		Warn_restart_ready = false;
102 103
bool		InError = false;
bool		ExitAfterAbort = false;
104

105
extern int	NBuffers;
106

107
static bool EchoQuery = false;	/* default don't echo */
108
char		pg_pathname[MAXPGPATH];
109
FILE	   *StatFp = NULL;
110

111
/* ----------------
112 113
 *		people who want to use EOF should #define DONTUSENEWLINE in
 *		tcop/tcopdebug.h
114 115 116
 * ----------------
 */
#ifndef TCOP_DONTUSENEWLINE
117
int			UseNewLine = 1;		/* Use newlines query delimiters (the
118 119
								 * default) */

120
#else
121
int			UseNewLine = 0;		/* Use EOF as query delimiters */
122

123
#endif	 /* TCOP_DONTUSENEWLINE */
124 125 126 127

/*
** Flags for expensive function optimization -- JMH 3/9/92
*/
128
int			XfuncMode = 0;
129 130

/* ----------------------------------------------------------------
131
 *		decls for routines only used in this file
132 133
 * ----------------------------------------------------------------
 */
134 135 136
static int	InteractiveBackend(StringInfo inBuf);
static int	SocketBackend(StringInfo inBuf);
static int	ReadCommand(StringInfo inBuf);
137
static void pg_exec_query(char *query_string);
138 139 140 141 142 143 144 145
static void SigHupHandler(SIGNAL_ARGS);

/*
 * 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;
146 147 148


/* ----------------------------------------------------------------
149
 *		routines to obtain user input
150 151 152 153
 * ----------------------------------------------------------------
 */

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

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

	/* ----------------
	 *	display a prompt and obtain input from the user
	 * ----------------
	 */
172
	printf("backend> ");
173
	fflush(stdout);
174

175 176 177 178
	/* Reset inBuf to empty */
	inBuf->len = 0;
	inBuf->data[0] = '\0';

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

211
				appendStringInfoChar(inBuf, (char) c);
212 213 214 215 216 217 218 219 220 221 222 223
			}

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

226
			if (inBuf->len == 0)
227 228 229 230
				end = true;
		}

		if (end)
231
			return EOF;
232 233 234 235 236 237 238 239 240 241 242 243 244

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

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

248
	return 'Q';
249 250 251
}

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

265
static int
266
SocketBackend(StringInfo inBuf)
267
{
268
	char		qtype;
269
	char		result = '\0';
270 271 272 273 274

	/* ----------------
	 *	get input from the frontend
	 * ----------------
	 */
275 276
	qtype = '?';
	if (pq_getbytes(&qtype, 1) == EOF)
277
		return EOF;
278

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

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

301 302 303 304 305 306 307
			/* ----------------
			 *	'X':  frontend is exiting
			 * ----------------
			 */
		case 'X':
			result = 'X';
			break;
308

309 310 311 312 313 314 315 316
			/* ----------------
			 *	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:
317
			elog(FATAL, "Socket command type %c unknown", qtype);
318
			break;
319 320
	}
	return result;
321 322 323
}

/* ----------------
324 325 326
 *		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
327
 *		call.  EOF is returned if end of file.
328 329
 * ----------------
 */
330
static int
331
ReadCommand(StringInfo inBuf)
332
{
333 334
	MemoryContext oldcontext;
	int			result;
335

336 337 338
	/*
	 * Make sure any expansion of inBuf happens in permanent memory
	 * context, so that we can keep using it for future command cycles.
339 340
	 */
	oldcontext = MemoryContextSwitchTo(TopMemoryContext);
341
	if (IsUnderPostmaster)
342
		result = SocketBackend(inBuf);
343
	else
344 345 346
		result = InteractiveBackend(inBuf);
	MemoryContextSwitchTo(oldcontext);
	return result;
347 348
}

349 350 351 352 353 354 355

/*
 * 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.
 */
356
List *
357 358 359
pg_parse_and_rewrite(char *query_string,		/* string to execute */
					 Oid *typev,/* argument types */
					 int nargs, /* number of arguments */
360
					 bool aclOverride)
361
{
362
	List	   *querytree_list;
363
	List	   *querytree_list_item;
364
	Query	   *querytree;
365
	List	   *new_list;
366

367 368
	if (Debug_print_query)
		elog(DEBUG, "query: %s", query_string);
369

370 371 372 373
	/* ----------------
	 *	(1) parse the request string into a list of parse trees
	 * ----------------
	 */
374
	if (Show_parser_stats)
375 376 377 378
		ResetUsage();

	querytree_list = parser(query_string, typev, nargs);

379
	if (Show_parser_stats)
380
	{
381
		fprintf(StatFp, "PARSER STATISTICS\n");
382 383 384 385 386
		ShowUsage();
	}

	/* ----------------
	 *	(2) rewrite the queries, as necessary
387
	 *
B
Bruce Momjian 已提交
388 389
	 *	rewritten queries are collected in new_list.  Note there may be
	 *	more or fewer than in the original list.
390 391
	 * ----------------
	 */
392
	new_list = NIL;
B
Bruce Momjian 已提交
393
	foreach(querytree_list_item, querytree_list)
394
	{
395
		querytree = (Query *) lfirst(querytree_list_item);
396

397
		if (Debug_print_parse)
398
		{
399
			if (Debug_pretty_print)
B
Bruce Momjian 已提交
400
			{
401
				elog(DEBUG, "parse tree:");
J
Jan Wieck 已提交
402
				nodeDisplay(querytree);
B
Bruce Momjian 已提交
403 404
			}
			else
405
				elog(DEBUG, "parse tree: %s", nodeToString(querytree));
406
		}
407 408 409

		if (querytree->commandType == CMD_UTILITY)
		{
410 411
			/* don't rewrite utilities, just dump 'em into new_list */
			new_list = lappend(new_list, querytree);
412
		}
413
		else
414
		{
415
			/* rewrite regular queries */
416 417
			List	   *rewritten = QueryRewrite(querytree);

418
			new_list = nconc(new_list, rewritten);
419 420 421 422 423
		}
	}

	querytree_list = new_list;

424 425 426
	/* ----------------
	 *	(3) If ACL override is requested, mark queries for no ACL check.
	 * ----------------
427
	 */
428 429
	if (aclOverride)
	{
B
Bruce Momjian 已提交
430
		foreach(querytree_list_item, querytree_list)
431 432
		{
			List	   *l;
433

434 435
			querytree = (Query *) lfirst(querytree_list_item);

436 437 438
			if (querytree->commandType == CMD_UTILITY)
				continue;

439 440
			foreach(l, querytree->rtable)
			{
441
				RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
442 443 444 445 446 447

				rte->skipAcl = TRUE;
			}
		}
	}

448
	if (Debug_print_rewritten)
449
	{
450
		if (Debug_pretty_print)
B
Bruce Momjian 已提交
451
		{
452
			elog(DEBUG, "rewritten parse tree:");
B
Bruce Momjian 已提交
453
			foreach(querytree_list_item, querytree_list)
J
Jan Wieck 已提交
454
			{
455 456
				querytree = (Query *) lfirst(querytree_list_item);
				nodeDisplay(querytree);
J
Jan Wieck 已提交
457 458
				printf("\n");
			}
B
Bruce Momjian 已提交
459 460 461
		}
		else
		{
462
			elog(DEBUG, "rewritten parse tree:");
J
Jan Wieck 已提交
463

B
Bruce Momjian 已提交
464
			foreach(querytree_list_item, querytree_list)
J
Jan Wieck 已提交
465
			{
466
				querytree = (Query *) lfirst(querytree_list_item);
467
				elog(DEBUG, "%s", nodeToString(querytree));
J
Jan Wieck 已提交
468
			}
469 470 471
		}
	}

472 473
	return querytree_list;
}
474 475


476 477 478 479 480
/* Generate a plan for a single query. */
Plan *
pg_plan_query(Query *querytree)
{
	Plan	   *plan;
481

482 483 484
	/* Utility commands have no plans. */
	if (querytree->commandType == CMD_UTILITY)
		return NULL;
485

486
	if (Show_planner_stats)
487
		ResetUsage();
488

489 490
	/* call that optimizer */
	plan = planner(querytree);
491

492
	if (Show_planner_stats)
493
	{
494
		fprintf(stderr, "PLANNER STATISTICS\n");
495 496
		ShowUsage();
	}
497

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

513
	return plan;
514 515
}

516

517
/* ----------------------------------------------------------------
518
 *		pg_exec_query()
519 520 521 522 523 524
 *
 *		Takes a querystring, runs the parser/utilities or
 *		parser/planner/executor over it as necessary
 *		Begin Transaction Should have been called before this
 *		and CommitTransaction After this is called
 *		This is strictly because we do not allow for nested xactions.
525
 *
526 527 528 529
 *		NON-OBVIOUS-RESTRICTIONS
 *		this function _MUST_ allocate a new "parsetree" each time,
 *		since it may be stored in a named portal and should not
 *		change its value.
530 531 532 533
 *
 * ----------------------------------------------------------------
 */

534
static void
535
pg_exec_query(char *query_string)
536
{
537 538 539 540 541 542 543
	pg_exec_query_dest(query_string, whereToSendOutput, FALSE);
}

void
pg_exec_query_acl_override(char *query_string)
{
	pg_exec_query_dest(query_string, whereToSendOutput, TRUE);
544 545 546
}

void
547
pg_exec_query_dest(char *query_string,	/* string to execute */
548
				   CommandDest dest,	/* where results should go */
549 550
				   bool aclOverride)	/* to give utility commands power
										 * of superusers */
551
{
552
	List	   *querytree_list;
553

554 555 556
	/* parse and rewrite the queries */
	querytree_list = pg_parse_and_rewrite(query_string, NULL, 0,
										  aclOverride);
557

B
Bruce Momjian 已提交
558 559
	/*
	 * NOTE: we do not use "foreach" here because we want to be sure the
560
	 * list pointer has been advanced before the query is executed. We
B
Bruce Momjian 已提交
561
	 * need to do that because VACUUM has a nasty little habit of doing
562
	 * CommitTransactionCommand at startup, and that will release the
563 564 565 566
	 * memory holding our parse list :-(.  This needs a better solution
	 * --- currently, the code will crash if someone submits "vacuum;
	 * something-else" in a single query string.  But memory allocation
	 * needs redesigned anyway, so this will have to do for now.
567 568 569
	 */
	while (querytree_list)
	{
570 571
		Query	   *querytree = (Query *) lfirst(querytree_list);

572
		querytree_list = lnext(querytree_list);
573 574 575 576

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

578 579 580 581 582 583 584 585 586
		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.
			 * ----------------
			 */
587 588 589 590
			if (Debug_print_query)
				elog(DEBUG, "ProcessUtility: %s", query_string);
			else if (DebugLvl > 1)
				elog(DEBUG, "ProcessUtility");
591 592 593 594 595

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

598
			/* If aborted transaction, skip planning and execution */
599
			if (IsAbortedTransactionBlockState())
600
			{
601 602 603 604 605 606 607 608 609 610 611 612
				/* ----------------
				 *	 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);

613 614
				/*
				 * We continue in the loop, on the off chance that there
615 616 617 618
				 * is a COMMIT or ROLLBACK utility command later in the
				 * query string.
				 */
				continue;
619 620
			}

621 622 623 624 625 626 627
			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 已提交
628 629 630
			SetQuerySnapshot();

			/*
B
Bruce Momjian 已提交
631
			 * execute the plan
632
			 */
633
			if (Show_executor_stats)
634 635
				ResetUsage();

636 637
			if (DebugLvl > 1)
				elog(DEBUG, "ProcessQuery");
638
			ProcessQuery(querytree, plan, dest);
639

640
			if (Show_executor_stats)
641
			{
642
				fprintf(stderr, "EXECUTOR STATISTICS\n");
643 644 645 646 647 648 649 650 651 652
				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.
		 */

653
		CommandCounterIncrement();
654
	}
655 656 657
}

/* --------------------------------
658
 *		signal handler routines used in PostgresMain()
659
 *
B
Bruce Momjian 已提交
660
 *		handle_warn() catches SIGQUIT.	It forces control back to the main
661 662 663
 *		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 已提交
664
 *		siglongjmp() instead.
665
 *		We still provide the signal catcher so that an error quit can be
B
Bruce Momjian 已提交
666
 *		forced externally.	This should be done only with great caution,
667 668
 *		however, since an asynchronous signal could leave the system in
 *		who-knows-what inconsistent state.
669
 *
670 671 672
 *		quickdie() occurs when signalled by the postmaster.
 *		Some backend has bought the farm,
 *		so we need to stop what we're doing and exit.
673
 *
674
 *		die() performs an orderly cleanup via proc_exit()
675 676 677 678
 * --------------------------------
 */

void
679
handle_warn(SIGNAL_ARGS)
680
{
681
	siglongjmp(Warn_restart, 1);
682 683
}

684
void
685
quickdie(SIGNAL_ARGS)
686
{
687
	PG_SETMASK(&BlockSig);
688
	elog(NOTICE, "Message from PostgreSQL backend:"
689 690 691 692 693
		 "\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.");
694

695 696

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

702
	exit(1);
703 704
}

705 706 707
/*
 * Abort transaction and exit
 */
708
void
709
die(SIGNAL_ARGS)
710
{
711
	PG_SETMASK(&BlockSig);
712

713 714 715 716 717 718 719 720 721
	/*
	 * If ERROR/FATAL is in progress...
	 */
	if (InError)
	{
		ExitAfterAbort = true;
		return;
	}
	elog(FATAL, "The system is shutting down");
722 723 724
}

/* signal handler for floating point exception */
725
void
726
FloatExceptionHandler(SIGNAL_ARGS)
727
{
728
	elog(ERROR, "floating point exception!"
729 730
		 " The last floating point operation either exceeded legal ranges"
		 " or was a divide by zero");
731 732
}

M
 
Marc G. Fournier 已提交
733
/* signal handler for query cancel signal from postmaster */
734 735 736 737
static void
QueryCancelHandler(SIGNAL_ARGS)
{
	QueryCancel = true;
738
	LockWaitCancel();
739 740 741 742 743
}

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

745 746
	/*
	 * QueryCancel flag will be reset in main loop, which we reach by
M
 
Marc G. Fournier 已提交
747 748
	 * longjmp from elog().
	 */
749 750 751
	elog(ERROR, "Query was cancelled.");
}

752 753 754 755 756 757
static void
SigHupHandler(SIGNAL_ARGS)
{
    got_SIGHUP = true;
}

758

759 760
static void
usage(char *progname)
761
{
762
	fprintf(stderr,
763
			"Usage: %s [options] [dbname]\n", progname);
M
 
Marc G. Fournier 已提交
764
#ifdef USE_ASSERT_CHECKING
T
Tom Lane 已提交
765
	fprintf(stderr, "\t-A on\t\tenable/disable assert checking\n");
M
 
Marc G. Fournier 已提交
766
#endif
767
	fprintf(stderr, "\t-B buffers\tset number of buffers in buffer pool\n");
T
Tom Lane 已提交
768
	fprintf(stderr, "\t-C \t\tsuppress version info\n");
769 770
	fprintf(stderr, "\t-D dir\t\tdata directory\n");
	fprintf(stderr, "\t-E \t\techo query before execution\n");
771
	fprintf(stderr, "\t-F \t\tturn fsync off\n");
772 773
	fprintf(stderr, "\t-L \t\tturn off locking\n");
	fprintf(stderr, "\t-N \t\tdon't use newline as interactive query delimiter\n");
774
	fprintf(stderr, "\t-O \t\tallow system table structure changes\n");
775
	fprintf(stderr, "\t-Q \t\tsuppress informational messages\n");
776
	fprintf(stderr, "\t-S kbytes\tset amount of memory for sorts (in kbytes)\n");
T
Tom Lane 已提交
777 778
	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 已提交
779
	fprintf(stderr, "\t-d [1-5]\tset debug level\n");
780
	fprintf(stderr, "\t-e \t\tturn on European date format\n");
T
Tom Lane 已提交
781
	fprintf(stderr, "\t-f [s|i|n|m|h]\tforbid use of some plan types\n");
782 783 784
	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");
785
	fprintf(stderr, "\t-s \t\tshow stats after each query\n");
786
	fprintf(stderr, "\t-t [pa|pl|ex]\tshow timings after each query\n");
787
	fprintf(stderr, "\t-v version\tset protocol version being used by frontend\n");
788 789 790
}

/* ----------------------------------------------------------------
791 792
 *	PostgresMain
 *		postgres main loop
793
 *		all backends, interactive or otherwise start here
794 795 796 797 798
 *
 *	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.
799 800 801
 * ----------------------------------------------------------------
 */
int
802
PostgresMain(int argc, char *argv[], int real_argc, char *real_argv[])
803
{
804
	int			flag;
805

806
	char	   *DBName = NULL;
807
	bool		secure = true;
808
	int			errs = 0;
809

810
	int			firstchar;
811
	StringInfo	parser_input;
812
	char	   *userName;
M
 
Marc G. Fournier 已提交
813

814 815
	char	   *remote_host;
	unsigned short remote_port;
816

817 818
	extern int	optind;
	extern char *optarg;
819
	extern int	DebugLvl;
820

821
	/*
822
	 * Set default values for command-line options.
823
	 */
824 825 826
	IsUnderPostmaster = false;
	Noversion = false;
	EchoQuery = false;
827
#ifdef LOCK_MGR_DEBUG
M
 
Marc G. Fournier 已提交
828
	LockDebug = 0;
829
#endif
830
	DataDir = getenv("PGDATA");
831
	StatFp = stderr;
832

833 834
	SetProcessingMode(InitProcessing);

835 836
	/* Check for PGDATESTYLE environment variable */
	set_default_datestyle();
837

838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855
	/* ----------------
	 *	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 */
856

857
	while ((flag = getopt(argc, argv,  "A:B:CD:d:Eef:FiLNOPo:p:S:st:v:W:x:-:")) != EOF)
858 859
		switch (flag)
		{
M
 
Marc G. Fournier 已提交
860 861
			case 'A':
				/* ----------------
862
				 *	enable/disable assert checking.
M
 
Marc G. Fournier 已提交
863 864 865 866 867 868 869 870
				 * ----------------
				 */
#ifdef USE_ASSERT_CHECKING
				assert_enabled = atoi(optarg);
#else
				fprintf(stderr, "Assert checking is not enabled\n");
#endif
				break;
871

872 873 874 875 876
			case 'B':
				/* ----------------
				 *	specify the size of buffer pool
				 * ----------------
				 */
877 878
				if (secure)
					NBuffers = atoi(optarg);
879
				break;
880

881 882
			case 'C':
				/* ----------------
883
				 *	don't print version string
884 885
				 * ----------------
				 */
886
				Noversion = true;
887
				break;
888

889
			case 'D':			/* PGDATA directory */
890 891
				if (secure)
					DataDir = optarg;
M
 
Marc G. Fournier 已提交
892
				break;
893

894
			case 'd':			/* debug level */
895
				DebugLvl = atoi(optarg);
896 897
				if (DebugLvl >= 1);
					Log_connections = true;
M
 
Marc G. Fournier 已提交
898
				if (DebugLvl >= 2)
899
					Debug_print_query = true;
M
 
Marc G. Fournier 已提交
900
				if (DebugLvl >= 3)
901
					Debug_print_parse = true;
B
Bruce Momjian 已提交
902
				if (DebugLvl >= 4)
903
					Debug_print_plan = true;
J
Jan Wieck 已提交
904
				if (DebugLvl >= 5)
905
					Debug_print_rewritten = true;
906
				break;
907 908 909 910 911 912

			case 'E':
				/* ----------------
				 *	E - echo the query the user entered
				 * ----------------
				 */
913
				EchoQuery = true;
914
				break;
915 916 917 918 919 920

			case 'e':
				/* --------------------------
				 * Use european date formats.
				 * --------------------------
				 */
921
				EuroDates = true;
922
				break;
923 924 925 926

			case 'F':
				/* --------------------
				 *	turn off fsync
927 928 929 930
				 *
				 *	7.0 buffer manager can support different backends running
				 *	with different fsync settings, so this no longer needs
				 *	to be "if (secure)".
931 932
				 * --------------------
				 */
933
				enableFsync = false;
934
				break;
935 936 937 938 939 940 941 942 943

			case 'f':
				/* -----------------
				 *	  f - forbid generation of certain plans
				 * -----------------
				 */
				switch (optarg[0])
				{
					case 's':	/* seqscan */
944
						enable_seqscan = false;
945 946
						break;
					case 'i':	/* indexscan */
947 948 949 950
						enable_indexscan = false;
						break;
					case 't':	/* tidscan */
						enable_tidscan = false;
951 952
						break;
					case 'n':	/* nestloop */
953
						enable_nestloop = false;
954 955
						break;
					case 'm':	/* mergejoin */
956
						enable_mergejoin = false;
957 958
						break;
					case 'h':	/* hashjoin */
959
						enable_hashjoin = false;
960 961 962 963
						break;
					default:
						errs++;
				}
964 965
				break;

966 967 968
			case 'i':
				dontExecute = 1;
				break;
969

970 971 972 973 974
			case 'L':
				/* --------------------
				 *	turn off locking
				 * --------------------
				 */
975 976
				if (secure)
					lockingOff = 1;
T
Tom Lane 已提交
977 978
				break;

979 980 981 982 983 984 985
			case 'N':
				/* ----------------
				 *	N - Don't use newline as a query delimiter
				 * ----------------
				 */
				UseNewLine = 0;
				break;
986

987 988 989 990 991
			case 'O':
				/* --------------------
				 *	allow system table structure modifications
				 * --------------------
				 */
992 993
				if (secure)		/* XXX safe to allow from client??? */
					allowSystemTableMods = true;
994 995
				break;

H
Hiroshi Inoue 已提交
996 997 998 999 1000 1001 1002 1003 1004
			case 'P':
				/* --------------------
				 *	ignore system indexes
				 * --------------------
				 */
				if (secure)		/* XXX safe to allow from client??? */
					IgnoreSystemIndexes(true);
				break;

T
Tom Lane 已提交
1005 1006 1007 1008 1009
			case 'o':
				/* ----------------
				 *	o - send output (stdout and stderr) to the given file
				 * ----------------
				 */
1010 1011
				if (secure)
					StrNCpy(OutputFileName, optarg, MAXPGPATH);
T
Tom Lane 已提交
1012 1013
				break;

1014
			case 'p':
1015 1016 1017 1018 1019
				/* ----------------
				 *	p - special flag passed if backend was forked
				 *		by a postmaster.
				 * ----------------
				 */
1020 1021 1022 1023
				if (secure)
				{
					IsUnderPostmaster = true;
					DBName = optarg;
B
Bruce Momjian 已提交
1024 1025
					secure = false;		/* subsequent switches are NOT
										 * secure */
1026
				}
1027
				break;
1028

1029 1030
			case 'S':
				/* ----------------
V
Vadim B. Mikheev 已提交
1031
				 *	S - amount of sort memory to use in 1k bytes
1032 1033
				 * ----------------
				 */
1034
				{
1035 1036
					int			S;

V
Vadim B. Mikheev 已提交
1037
					S = atoi(optarg);
1038
					if (S >= 4 * BLCKSZ / 1024)
V
Vadim B. Mikheev 已提交
1039
						SortMem = S;
1040
				}
1041
				break;
1042 1043 1044 1045 1046 1047

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

1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065
			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')
1066
							Show_parser_stats = 1;
1067
						else if (optarg[1] == 'l')
1068
							Show_planner_stats = 1;
1069 1070 1071 1072
						else
							errs++;
						break;
					case 'e':
1073
						Show_executor_stats = 1;
1074 1075 1076 1077 1078
						break;
					default:
						errs++;
						break;
				}
1079 1080
				break;

1081
			case 'v':
1082 1083
				if (secure)
					FrontendProtocol = (ProtocolVersion) atoi(optarg);
1084 1085
				break;

M
 
Marc G. Fournier 已提交
1086 1087
			case 'W':
				/* ----------------
1088
				 *	wait N seconds to allow attach from a debugger
M
 
Marc G. Fournier 已提交
1089 1090 1091 1092 1093
				 * ----------------
				 */
				sleep(atoi(optarg));
				break;

1094
			case 'x':
B
Bruce Momjian 已提交
1095
#ifdef NOT_USED					/* planner/xfunc.h */
1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123

				/*
				 * 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++;
				}
1124
#endif
1125
				break;
1126

1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143
			case '-':
			{
				/* A little 'long argument' simulation */
				/* (copy&pasted from PostmasterMain() */
				size_t equal_pos = strcspn(optarg, "=");
				char *cp;

				if (optarg[equal_pos] != '=')
					elog(ERROR, "--%s requires argument", optarg);
				optarg[equal_pos] = '\0';
				for(cp = optarg; *cp; cp++)
					if (*cp == '-')
						*cp = '_';
				SetConfigOption(optarg, optarg + equal_pos + 1, PGC_BACKEND);
				break;
			}

1144 1145 1146 1147 1148 1149
			default:
				/* ----------------
				 *	default: bad command line option
				 * ----------------
				 */
				errs++;
T
Tom Lane 已提交
1150
				break;
1151 1152
		}

1153 1154
	if (Show_query_stats &&
		(Show_parser_stats || Show_planner_stats || Show_executor_stats))
1155
	{
1156 1157
        elog(NOTICE, "Query statistics are disabled because parser, planner, or executor statistics are on.");
        Show_query_stats = false;
1158 1159 1160 1161 1162 1163 1164
	}

	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 "
1165
			 "option or by setting the PGDATA environment variable.\n\n",
1166 1167 1168 1169
				argv[0]);
		proc_exit(1);
	}

1170 1171 1172 1173 1174 1175
	/*
	 * Make a copy of DataDir because the arguments and environment
	 * might be moved around later on.
	 */
	DataDir = strdup(DataDir);

1176
	/*
1177 1178 1179
	 * 1. Set BlockSig and UnBlockSig masks. 2. Set up signal handlers. 3.
	 * Allow only SIGUSR1 signal (we never block it) during
	 * initialization.
1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194
	 *
	 * Note that postmaster already blocked ALL signals to make us happy.
	 */
	if (!IsUnderPostmaster)
	{
		PG_INITMASK();
		PG_SETMASK(&BlockSig);
	}

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

1195
	pqsignal(SIGHUP, SigHupHandler);	/* set flag to read config file */
1196 1197
	pqsignal(SIGINT, QueryCancelHandler);		/* cancel current query */
	pqsignal(SIGQUIT, handle_warn);		/* handle error */
1198 1199
	pqsignal(SIGTERM, die);
	pqsignal(SIGALRM, HandleDeadLock);
1200 1201 1202 1203 1204

	/*
	 * 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
1205 1206 1207 1208
	 * midst of output during who-knows-what operation...
	 */
	pqsignal(SIGPIPE, SIG_IGN);
	pqsignal(SIGUSR1, quickdie);
1209
	pqsignal(SIGUSR2, Async_NotifyHandler);		/* flush also sinval cache */
1210
	pqsignal(SIGFPE, FloatExceptionHandler);
1211
	pqsignal(SIGCHLD, SIG_IGN); /* ignored, sent by LockOwners */
1212 1213 1214 1215 1216 1217 1218 1219 1220
	pqsignal(SIGTTIN, SIG_DFL);
	pqsignal(SIGTTOU, SIG_DFL);
	pqsignal(SIGCONT, SIG_DFL);

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

	/*
	 * Get user name (needed now in case it is the default database name)
	 * and check command line validity
1221 1222 1223 1224
	 */
	SetPgUserName();
	userName = GetPgUserName();

1225
	if (IsUnderPostmaster)
1226
	{
1227 1228 1229 1230
		/* noninteractive case: nothing should be left after switches */
		if (errs || argc != optind || DBName == NULL)
		{
			usage(argv[0]);
1231
			proc_exit(0);
1232
		}
1233 1234 1235
		pq_init();				/* initialize libpq at backend startup */
		whereToSendOutput = Remote;
		BaseInit();
1236
	}
1237
	else
1238
	{
1239
		/* interactive case: database name can be last arg on command line */
1240
		whereToSendOutput = Debug;
1241 1242 1243
		if (errs || argc - optind > 1)
		{
			usage(argv[0]);
1244
			proc_exit(0);
1245 1246 1247 1248 1249 1250 1251
		}
		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]);
1252
			proc_exit(0);
1253
		}
1254 1255 1256 1257 1258

		/*
		 * Try to create pid file.
		 */
		SetPidFname(DataDir);
1259
		if (SetPidFile(-getpid()))
1260
			proc_exit(0);
1261

1262 1263 1264 1265 1266
		/*
		 * Register clean up proc.
		 */
		on_proc_exit(UnlinkPidFile, NULL);

1267
		BaseInit();
1268 1269 1270 1271
		snprintf(XLogDir, MAXPGPATH, "%s%cpg_xlog",
				 DataDir, SEP_CHAR);
		snprintf(ControlFilePath, MAXPGPATH, "%s%cpg_control",
				 DataDir, SEP_CHAR);
1272
		StartupXLOG();
1273 1274
	}

1275 1276 1277 1278 1279 1280 1281 1282
	/*
	 * Set up additional info.
	 */

#ifdef CYR_RECODE
	SetCharSet();
#endif

1283
	/* On some systems our dynloader code needs the executable's pathname */
1284
	if (FindExec(pg_pathname, real_argv[0], "postgres") < 0)
1285
		elog(FATAL, "%s: could not locate executable, bailing out...",
1286
			 real_argv[0]);
1287

M
 
Marc G. Fournier 已提交
1288 1289 1290
	/*
	 * Find remote host name or address.
	 */
1291 1292
	remote_host = NULL;

1293 1294
	if (IsUnderPostmaster)
	{
1295
		if (MyProcPort->raddr.sa.sa_family == AF_INET)
1296
		{
1297 1298
			struct hostent *host_ent;
			char * host_addr;
M
 
Marc G. Fournier 已提交
1299

1300 1301 1302 1303 1304 1305 1306 1307
			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)
1308
				{
1309 1310
					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 已提交
1311
				}
1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323
			}

			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 已提交
1324
		}
1325 1326 1327
		else /* not AF_INET */
			remote_host = "[local]";

1328

1329 1330 1331
		/*
		 * Set process params for ps
		 */
1332 1333
		init_ps_display(real_argc, real_argv, userName, DBName, remote_host);
		set_ps_display("startup");
1334 1335
	}

1336 1337 1338
	if (Log_connections)
		elog(DEBUG, "connection: host=%s user=%s database=%s",
			 remote_host, userName, DBName);
1339

1340 1341
	/*
	 * general initialization
1342
	 */
1343 1344
	if (DebugLvl > 1)
		elog(DEBUG, "InitPostgres");
1345 1346
	InitPostgres(DBName);

1347
#ifdef MULTIBYTE
1348
	/* set default client encoding */
1349 1350
	if (DebugLvl > 1)
		elog(DEBUG, "reset_client_encoding");
1351 1352 1353
	reset_client_encoding();
#endif

1354 1355
	on_shmem_exit(remove_all_temp_relations, NULL);

H
 
Hiroshi Inoue 已提交
1356
	{
1357 1358 1359
		MemoryContext oldcontext = MemoryContextSwitchTo(TopMemoryContext);

		parser_input = makeStringInfo();		/* initialize input buffer */
H
 
Hiroshi Inoue 已提交
1360 1361
		MemoryContextSwitchTo(oldcontext);
	}
1362

1363 1364
	/*
	 * Send this backend's cancellation info to the frontend.
1365
	 */
M
 
Marc G. Fournier 已提交
1366 1367 1368
	if (whereToSendOutput == Remote &&
		PG_PROTOCOL_MAJOR(FrontendProtocol) >= 2)
	{
1369
		StringInfoData buf;
B
Bruce Momjian 已提交
1370

1371 1372 1373 1374 1375
		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 已提交
1376 1377 1378
		/* Need not flush since ReadyForQuery will do it. */
	}

1379 1380 1381
	if (!IsUnderPostmaster)
	{
		puts("\nPOSTGRES backend interactive interface ");
1382
		puts("$Revision: 1.158 $ $Date: 2000/06/04 01:44:33 $\n");
1383 1384
	}

1385
	/*
1386 1387 1388
	 * Initialize the deferred trigger manager
	 */
	if (DeferredTriggerInit() != 0)
1389
		proc_exit(0);
1390 1391

	SetProcessingMode(NormalProcessing);
1392

1393 1394
	/*
	 * POSTGRES main processing loop begins here
1395
	 *
1396 1397
	 * If an exception is encountered, processing resumes here so we abort
	 * the current transaction and start a new one.
1398 1399 1400 1401
	 */

	if (sigsetjmp(Warn_restart, 1) != 0)
	{
1402 1403
		/* Make sure we are in a valid memory context */
		MemoryContextSwitchTo(TopMemoryContext);
1404

1405 1406
		if (DebugLvl >= 1)
			elog(DEBUG, "AbortCurrentTransaction");
1407
		AbortCurrentTransaction();
1408 1409 1410
		InError = false;
		if (ExitAfterAbort)
		{
1411
			ProcReleaseLocks(); /* Just to be sure... */
1412
			proc_exit(0);
1413
		}
1414
	}
1415

1416 1417
	Warn_restart_ready = true;	/* we can now handle elog(ERROR) */

1418
	PG_SETMASK(&UnBlockSig);
1419

1420 1421
	/*
	 * Non-error queries loop here.
1422 1423 1424 1425
	 */

	for (;;)
	{
1426
		set_ps_display("idle");
1427

1428 1429 1430 1431 1432 1433 1434 1435
		/* 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 已提交
1436
		/* ----------------
1437 1438
		 *	 (1) tell the frontend we're ready for a new query.
		 *
B
Bruce Momjian 已提交
1439
		 *	 Note: this includes fflush()'ing the last of the prior output.
B
Bruce Momjian 已提交
1440 1441
		 * ----------------
		 */
1442
		ReadyForQuery(whereToSendOutput);
B
Bruce Momjian 已提交
1443

1444
		/* ----------------
1445
		 *	 (2) deal with pending asynchronous NOTIFY from other backends,
B
Bruce Momjian 已提交
1446
		 *	 and enable async.c's signal handler to execute NOTIFY directly.
1447 1448 1449
		 * ----------------
		 */
		QueryCancel = false;	/* forget any earlier CANCEL signal */
1450
		SetWaitingForLock(false);
1451 1452 1453 1454

		EnableNotifyInterrupt();

		/* ----------------
1455
		 *	 (3) read a command (loop blocks here)
1456 1457
		 * ----------------
		 */
1458
		firstchar = ReadCommand(parser_input);
1459

1460
		QueryCancel = false;	/* forget any earlier CANCEL signal */
1461

1462
		/* ----------------
1463 1464 1465 1466 1467 1468 1469
		 *	 (4) disable async.c's signal handler.
		 * ----------------
		 */
		DisableNotifyInterrupt();

		/* ----------------
		 *	 (5) process the command.
1470 1471
		 * ----------------
		 */
1472 1473 1474
		switch (firstchar)
		{
				/* ----------------
1475 1476
				 *	'F' indicates a fastpath call.
				 *		XXX HandleFunctionRequest
1477 1478
				 * ----------------
				 */
1479
			case 'F':
1480 1481
				IsEmptyQuery = false;

1482
				/* start an xact for this function invocation */
1483 1484
				if (DebugLvl >= 1)
					elog(DEBUG, "StartTransactionCommand");
1485
				StartTransactionCommand();
1486

1487 1488 1489 1490 1491 1492
				if (HandleFunctionRequest() == EOF)
				{
					/* lost frontend connection during F message input */
					pq_close();
					proc_exit(0);
				}
1493
				break;
1494

1495 1496 1497 1498 1499
				/* ----------------
				 *	'Q' indicates a user query
				 * ----------------
				 */
			case 'Q':
1500
				if (strspn(parser_input->data, " \t\n") == parser_input->len)
1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515
				{
					/* ----------------
					 *	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;
1516
					if (Show_query_stats)
1517 1518 1519
						ResetUsage();

					/* start an xact for this query */
1520 1521
					if (DebugLvl >= 1)
						elog(DEBUG, "StartTransactionCommand");
1522
					StartTransactionCommand();
1523

1524
					pg_exec_query(parser_input->data);
1525

1526 1527 1528 1529 1530 1531
					/*
					 * Invoke IMMEDIATE constraint triggers
					 *
					 */
					DeferredTriggerEndQuery();

1532 1533 1534
					if (Show_query_stats)
                    {
                        fprintf(StatFp, "QUERY STATISTICS\n");
1535
						ShowUsage();
1536
                    }
1537 1538 1539 1540
				}
				break;

				/* ----------------
1541 1542 1543
				 *	'X' means that the frontend is closing down the socket.
				 *	EOF means unexpected loss of frontend connection.
				 *	Either way, perform normal shutdown.
1544 1545 1546
				 * ----------------
				 */
			case 'X':
1547
			case EOF:
1548 1549
				if (!IsUnderPostmaster)
					ShutdownXLOG();
1550
				pq_close();
1551
				proc_exit(0);
1552 1553 1554
				break;

			default:
M
 
Marc G. Fournier 已提交
1555
				elog(ERROR, "unknown frontend message was received");
1556 1557 1558
		}

		/* ----------------
1559
		 *	 (6) commit the current transaction
1560 1561
		 *
		 *	 Note: if we had an empty input buffer, then we didn't
1562
		 *	 call pg_exec_query, so we don't bother to commit this transaction.
1563 1564 1565 1566
		 * ----------------
		 */
		if (!IsEmptyQuery)
		{
1567 1568
			if (DebugLvl >= 1)
				elog(DEBUG, "CommitTransactionCommand");
1569
			set_ps_display("commit");
1570
			CommitTransactionCommand();
1571 1572 1573 1574 1575
#ifdef SHOW_MEMORY_STATS
			/* print global-context stats at each commit for leak tracking */
			if (ShowStats)
				GlobalMemoryStats();
#endif
1576 1577 1578
		}
		else
		{
1579
			if (IsUnderPostmaster)
1580 1581 1582
				NullCommand(Remote);
		}
	}							/* infinite for-loop */
1583 1584

	proc_exit(0);				/* shouldn't get here... */
1585
	return 1;
1586 1587
}

1588
#ifndef HAVE_GETRUSAGE
B
Bruce Momjian 已提交
1589 1590
#include "rusagestub.h"
#else
1591
#include <sys/resource.h>
1592
#endif	 /* HAVE_GETRUSAGE */
1593

1594 1595
struct rusage Save_r;
struct timeval Save_t;
1596 1597

void
1598
ResetUsage(void)
1599
{
1600 1601 1602 1603 1604 1605
	struct timezone tz;

	getrusage(RUSAGE_SELF, &Save_r);
	gettimeofday(&Save_t, &tz);
	ResetBufferUsage();
/*	  ResetTupleCount(); */
1606 1607 1608
}

void
1609
ShowUsage(void)
1610
{
1611 1612 1613
	struct timeval user,
				sys;
	struct timeval elapse_t;
1614
	struct timezone tz;
1615
	struct rusage r;
1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636

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

1637 1638 1639 1640 1641 1642
	/*
	 * Set output destination if not otherwise set
	 */
	if (StatFp == NULL)
		StatFp = stderr;

1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666
	/*
	 * 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);
1667
#ifdef HAVE_GETRUSAGE
1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692
	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);
1693
#endif	 /* HAVE_GETRUSAGE */
1694 1695 1696
	fprintf(StatFp, "! postgres usage stats:\n");
	PrintBufferUsage(StatFp);
/*	   DisplayTupleCount(StatFp); */
1697
}
M
 
Marc G. Fournier 已提交
1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712

#ifdef USE_ASSERT_CHECKING
int
assertEnable(int val)
{
	assert_enabled = val;
	return val;
}

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

1713 1714
	if (assert_enabled)
	{
M
 
Marc G. Fournier 已提交
1715 1716 1717
		/* val != 0 should be trapped by previous Assert */
		elog(NOTICE, "Assert test successfull (val = %d)", val);
	}
1718 1719
	else
		elog(NOTICE, "Assert checking is disabled (val = %d)", val);
M
 
Marc G. Fournier 已提交
1720 1721 1722

	return val;
}
1723

M
 
Marc G. Fournier 已提交
1724 1725
#endif
#endif