postgres.c 42.8 KB
Newer Older
1 2
/*-------------------------------------------------------------------------
 *
3
 * postgres.c
4
 *	  POSTGRES C Backend Interface
5 6 7 8 9
 *
 * Copyright (c) 1994, Regents of the University of California
 *
 *
 * IDENTIFICATION
10
 *	  $Header: /cvsroot/pgsql/src/backend/tcop/postgres.c,v 1.136 1999/10/25 03:07:48 tgl Exp $
11 12
 *
 * NOTES
13 14
 *	  this is the "main" module of the postgres backend and
 *	  hence the main module of the "traffic cop".
15 16 17
 *
 *-------------------------------------------------------------------------
 */
B
Bruce Momjian 已提交
18 19

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

#include "postgres.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 "libpq/libpq.h"
43
#include "libpq/pqformat.h"
44
#include "libpq/pqsignal.h"
B
Bruce Momjian 已提交
45
#include "miscadmin.h"
46 47
#include "nodes/print.h"
#include "optimizer/cost.h"
48
#include "optimizer/planner.h"
49
#include "parser/parser.h"
B
Bruce Momjian 已提交
50
#include "rewrite/rewriteHandler.h"
51 52
#include "tcop/fastpath.h"
#include "tcop/pquery.h"
B
Bruce Momjian 已提交
53
#include "tcop/tcopprot.h"
54
#include "tcop/utility.h"
55
#include "storage/proc.h"
M
 
Marc G. Fournier 已提交
56
#include "utils/ps_status.h"
57
#include "utils/temprel.h"
M
 
Marc G. Fournier 已提交
58 59
#include "utils/trace.h"

B
Bruce Momjian 已提交
60 61
#include "../backend/parser/parse.h"

62
#ifdef MULTIBYTE
B
Bruce Momjian 已提交
63
#include "mb/pg_wchar.h"
64 65
#endif

M
 
Marc G. Fournier 已提交
66 67 68 69 70 71 72
/*
 * Trace flags, see backend/utils/misc/trace.c
 */
#define Verbose				pg_options[TRACE_VERBOSE]
#define DebugPrintQuery		pg_options[TRACE_QUERY]
#define DebugPrintPlan		pg_options[TRACE_PLAN]
#define DebugPrintParse		pg_options[TRACE_PARSE]
J
Jan Wieck 已提交
73 74 75 76 77 78
#define DebugPrintRewrittenParsetree \
							pg_options[TRACE_REWRITTEN]
#define DebugPPrintPlan		pg_options[TRACE_PRETTY_PLAN]
#define DebugPPrintParse	pg_options[TRACE_PRETTY_PARSE]
#define DebugPPrintRewrittenParsetree \
							pg_options[TRACE_PRETTY_REWRITTEN]
M
 
Marc G. Fournier 已提交
79 80 81 82 83 84 85 86 87 88 89
#define ShowParserStats		pg_options[TRACE_PARSERSTATS]
#define ShowPlannerStats	pg_options[TRACE_PLANNERSTATS]
#define ShowExecutorStats	pg_options[TRACE_EXECUTORSTATS]
#ifdef LOCK_MGR_DEBUG
#define LockDebug			pg_options[TRACE_LOCKS]
#endif

#define DeadlockCheckTimer	pg_options[OPT_DEADLOCKTIMEOUT]
#define HostnameLookup		pg_options[OPT_HOSTLOOKUP]
#define ShowPortNumber		pg_options[OPT_SHOWPORTNUMBER]

90
/* ----------------
91
 *		global variables
92 93
 * ----------------
 */
94

95
CommandDest whereToSendOutput = Debug;
96

M
 
Marc G. Fournier 已提交
97 98
/* Define status buffer needed by PS_SET_STATUS */
PS_DEFINE_BUFFER;
99

100 101 102 103 104 105 106 107 108
extern void		BaseInit(void);
extern void		StartupXLOG(void);
extern void		ShutdownXLOG(void);

extern void		HandleDeadLock(SIGNAL_ARGS);

extern char		XLogDir[];
extern char		ControlFilePath[];

109 110
extern int	lockingOff;
extern int	NBuffers;
111

112 113 114
int			dontExecute = 0;
static int	ShowStats;
static bool IsEmptyQuery = false;
115

116
/* note: these declarations had better match tcopprot.h */
B
Bruce Momjian 已提交
117
DLLIMPORT sigjmp_buf Warn_restart;
118

119 120
bool		InError = false;
bool		ExitAfterAbort = false;
121

122
extern int	NBuffers;
123

124
static bool	EchoQuery = false;		/* default don't echo */
125
time_t		tim;
126
char		pg_pathname[MAXPGPATH];
127
FILE	   *StatFp;
128

129
/* ----------------
130 131
 *		people who want to use EOF should #define DONTUSENEWLINE in
 *		tcop/tcopdebug.h
132 133 134
 * ----------------
 */
#ifndef TCOP_DONTUSENEWLINE
135
int			UseNewLine = 1;		/* Use newlines query delimiters (the
136 137
								 * default) */

138
#else
139
int			UseNewLine = 0;		/* Use EOF as query delimiters */
140

141
#endif	 /* TCOP_DONTUSENEWLINE */
142 143 144 145

/*
** Flags for expensive function optimization -- JMH 3/9/92
*/
146
int			XfuncMode = 0;
147 148 149

/*
 * ----------------
150 151 152 153 154 155 156
 *	 Note: _exec_repeat_ defaults to 1 but may be changed
 *		   by a DEBUG command.	 If you set this to a large
 *		   number N, run a single query, and then set it
 *		   back to 1 and run N queries, you can get an idea
 *		   of how much time is being spent in the parser and
 *		   planner b/c in the first case this overhead only
 *		   happens once.  -cim 6/9/91
157 158
 * ----------------
*/
159
int			_exec_repeat_ = 1;
160 161

/* ----------------------------------------------------------------
162
 *		decls for routines only used in this file
163 164
 * ----------------------------------------------------------------
 */
165 166 167
static int InteractiveBackend(StringInfo inBuf);
static int SocketBackend(StringInfo inBuf);
static int ReadCommand(StringInfo inBuf);
168
static void pg_exec_query(char *query_string);
169 170 171


/* ----------------------------------------------------------------
172
 *		routines to obtain user input
173 174 175 176
 * ----------------------------------------------------------------
 */

/* ----------------
177 178
 *	InteractiveBackend() is called for user interactive connections
 *	the string entered by the user is placed in its parameter inBuf.
179 180
 *
 *  EOF is returned if end-of-file input is seen; time to shut down.
181 182 183
 * ----------------
 */

184
static int
185
InteractiveBackend(StringInfo inBuf)
186
{
187 188 189
	int			c;				/* character read from getc() */
	bool		end = false;	/* end-of-input flag */
	bool		backslashSeen = false;	/* have we seen a \ ? */
190 191 192 193 194

	/* ----------------
	 *	display a prompt and obtain input from the user
	 * ----------------
	 */
195
	printf("backend> ");
196
	fflush(stdout);
197

198 199 200 201
	/* Reset inBuf to empty */
	inBuf->len = 0;
	inBuf->data[0] = '\0';

202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
	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)
					{
217 218 219
						/* discard backslash from inBuf */
						inBuf->data[--inBuf->len] = '\0';
						backslashSeen = false;
220 221 222 223 224
						continue;
					}
					else
					{
						/* keep the newline character */
225
						appendStringInfoChar(inBuf, '\n');
226 227 228 229 230 231 232 233
						break;
					}
				}
				else if (c == '\\')
					backslashSeen = true;
				else
					backslashSeen = false;

234
				appendStringInfoChar(inBuf, (char) c);
235 236 237 238 239 240 241 242 243 244 245 246
			}

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

249
			if (inBuf->len == 0)
250 251 252 253 254
				end = true;
		}

		if (end)
		{
M
 
Marc G. Fournier 已提交
255
			if (Verbose)
256
				puts("EOF");
257
			return EOF;
258 259 260 261 262 263 264 265 266 267 268 269 270 271
		}

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

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

275
	return 'Q';
276 277 278
}

/* ----------------
279
 *	SocketBackend()		Is called for frontend-backend connections
280
 *
281 282
 *	If the input is a query (case 'Q') then the string entered by
 *	the user is placed in its parameter inBuf.
283
 *
284
 *	If the input is a fastpath function call (case 'F') then
285
 *	the function call is processed in HandleFunctionRequest()
286 287 288
 *	(now called from PostgresMain()).
 *
 *  EOF is returned if the connection is lost.
289 290 291
 * ----------------
 */

292
static int
293
SocketBackend(StringInfo inBuf)
294
{
295
	char		qtype;
296
	char		result = '\0';
297 298 299 300 301

	/* ----------------
	 *	get input from the frontend
	 * ----------------
	 */
302 303
	qtype = '?';
	if (pq_getbytes(&qtype, 1) == EOF)
304
		return EOF;
305

306
	switch (qtype)
307
	{
308 309 310 311 312
			/* ----------------
			 *	'Q': user entered a query
			 * ----------------
			 */
		case 'Q':
313
			if (pq_getstr(inBuf))
314
				return EOF;
315 316
			result = 'Q';
			break;
317

318 319 320 321 322
			/* ----------------
			 *	'F':  calling user/system functions
			 * ----------------
			 */
		case 'F':
323
			if (pq_getstr(inBuf))
324
				return EOF;		/* ignore "string" at start of F message */
325 326
			result = 'F';
			break;
327

328 329 330 331 332 333 334
			/* ----------------
			 *	'X':  frontend is exiting
			 * ----------------
			 */
		case 'X':
			result = 'X';
			break;
335

336 337 338 339 340 341 342 343
			/* ----------------
			 *	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:
344
			elog(FATAL, "Socket command type %c unknown", qtype);
345
			break;
346 347
	}
	return result;
348 349 350
}

/* ----------------
351 352 353
 *		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
354
 *		call.  EOF is returned if end of file.
355 356
 * ----------------
 */
357
static int
358
ReadCommand(StringInfo inBuf)
359
{
360 361 362 363 364 365 366
	MemoryContext	oldcontext;
	int				result;

	/* Make sure any expansion of inBuf happens in permanent memory context,
	 * so that we can keep using it for future command cycles.
	 */
	oldcontext = MemoryContextSwitchTo(TopMemoryContext);
367
	if (IsUnderPostmaster)
368
		result = SocketBackend(inBuf);
369
	else
370 371 372
		result = InteractiveBackend(inBuf);
	MemoryContextSwitchTo(oldcontext);
	return result;
373 374
}

375 376 377 378
List *
pg_parse_and_plan(char *query_string,	/* string to execute */
				  Oid *typev,	/* argument types */
				  int nargs,	/* number of arguments */
B
Bruce Momjian 已提交
379 380
				  List **queryListP,	/* returned pointer to the parse
										 * trees */
381 382
				  CommandDest dest,		/* where results should go */
				  bool aclOverride)
383
{
384
	List	   *querytree_list = NIL;
385
	List	   *plan_list = NIL;
386
	List	   *querytree_list_item;
387
	Query	   *querytree;
388 389 390
	Plan	   *plan;
	List	   *new_list;
	List	   *rewritten;
391

392 393
	if (DebugPrintQuery)
	{
394
		TPRINTF(TRACE_QUERY, "query: %s", query_string);
395 396
	}

397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
	/* ----------------
	 *	(1) parse the request string into a list of parse trees
	 * ----------------
	 */
	if (ShowParserStats)
		ResetUsage();

	querytree_list = parser(query_string, typev, nargs);

	if (ShowParserStats)
	{
		fprintf(stderr, "! Parser Stats:\n");
		ShowUsage();
	}

	/* ----------------
	 *	(2) rewrite the queries, as necessary
414
	 *
B
Bruce Momjian 已提交
415 416
	 *	rewritten queries are collected in new_list.  Note there may be
	 *	more or fewer than in the original list.
417 418
	 * ----------------
	 */
419
	new_list = NIL;
B
Bruce Momjian 已提交
420
	foreach(querytree_list_item, querytree_list)
421
	{
422
		querytree = (Query *) lfirst(querytree_list_item);
423

J
Jan Wieck 已提交
424
		if (DebugPrintParse || DebugPPrintParse)
425
		{
B
Bruce Momjian 已提交
426 427
			if (DebugPPrintParse)
			{
J
Jan Wieck 已提交
428 429
				TPRINTF(TRACE_PRETTY_PARSE, "parser outputs:");
				nodeDisplay(querytree);
B
Bruce Momjian 已提交
430 431 432
			}
			else
			{
J
Jan Wieck 已提交
433 434 435
				TPRINTF(TRACE_PARSE, "parser outputs:");
				printf("\n%s\n\n", nodeToString(querytree));
			}
436
		}
437 438 439

		if (querytree->commandType == CMD_UTILITY)
		{
440 441
			/* don't rewrite utilities, just dump 'em into new_list */
			new_list = lappend(new_list, querytree);
442
		}
443
		else
444
		{
445 446 447
			/* rewrite regular queries */
			rewritten = QueryRewrite(querytree);
			new_list = nconc(new_list, rewritten);
448 449 450 451 452
		}
	}

	querytree_list = new_list;

453 454 455
	/*
	 * Override ACL checking if requested
	 */
456 457
	if (aclOverride)
	{
B
Bruce Momjian 已提交
458
		foreach(querytree_list_item, querytree_list)
459 460
		{
			List	   *l;
461

462 463
			querytree = (Query *) lfirst(querytree_list_item);

464 465 466
			if (querytree->commandType == CMD_UTILITY)
				continue;

467 468
			foreach(l, querytree->rtable)
			{
469
				RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);
470 471 472 473 474 475

				rte->skipAcl = TRUE;
			}
		}
	}

J
Jan Wieck 已提交
476
	if (DebugPrintRewrittenParsetree || DebugPPrintRewrittenParsetree)
477
	{
B
Bruce Momjian 已提交
478 479
		if (DebugPPrintRewrittenParsetree)
		{
J
Jan Wieck 已提交
480
			TPRINTF(TRACE_PRETTY_REWRITTEN, "after rewriting:");
481

B
Bruce Momjian 已提交
482
			foreach(querytree_list_item, querytree_list)
J
Jan Wieck 已提交
483
			{
484 485
				querytree = (Query *) lfirst(querytree_list_item);
				nodeDisplay(querytree);
J
Jan Wieck 已提交
486 487
				printf("\n");
			}
B
Bruce Momjian 已提交
488 489 490
		}
		else
		{
J
Jan Wieck 已提交
491 492
			TPRINTF(TRACE_REWRITTEN, "after rewriting:");

B
Bruce Momjian 已提交
493
			foreach(querytree_list_item, querytree_list)
J
Jan Wieck 已提交
494
			{
495 496
				querytree = (Query *) lfirst(querytree_list_item);
				printf("\n%s\n\n", nodeToString(querytree));
J
Jan Wieck 已提交
497
			}
498 499 500
		}
	}

B
Bruce Momjian 已提交
501
	foreach(querytree_list_item, querytree_list)
502
	{
503
		querytree = (Query *) lfirst(querytree_list_item);
504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519

		/*
		 * For each query that isn't a utility invocation, generate a
		 * plan.
		 */

		if (querytree->commandType != CMD_UTILITY)
		{

			if (IsAbortedTransactionBlockState())
			{
				/* ----------------
				 *	 the EndCommand() stuff is to tell the frontend
				 *	 that the command ended. -cim 6/1/90
				 * ----------------
				 */
520
				char	   *tag = "*ABORT STATE*";
521 522 523 524 525 526

				EndCommand(tag, dest);

				elog(NOTICE, "(transaction aborted): %s",
					 "queries ignored until END");

527
				if (queryListP)
528 529
					*queryListP = NIL;
				return NIL;
530 531 532 533
			}

			if (ShowPlannerStats)
				ResetUsage();
534 535

			/* call that optimizer */
536
			plan = planner(querytree);
537

538 539 540 541 542 543
			if (ShowPlannerStats)
			{
				fprintf(stderr, "! Planner Stats:\n");
				ShowUsage();
			}
			plan_list = lappend(plan_list, plan);
M
Fixes:  
Marc G. Fournier 已提交
544
#ifdef INDEXSCAN_PATCH
545 546 547 548 549 550
			/* ----------------
			 *	Print plan if debugging.
			 *	This has been moved here to get debugging output
			 *	also for queries in functions.	DZ - 27-8-1996
			 * ----------------
			 */
J
Jan Wieck 已提交
551
			if (DebugPrintPlan || DebugPPrintPlan)
552
			{
B
Bruce Momjian 已提交
553 554
				if (DebugPPrintPlan)
				{
J
Jan Wieck 已提交
555 556
					TPRINTF(TRACE_PRETTY_PLAN, "plan:");
					nodeDisplay(plan);
B
Bruce Momjian 已提交
557 558 559
				}
				else
				{
J
Jan Wieck 已提交
560 561 562
					TPRINTF(TRACE_PLAN, "plan:");
					printf("\n%s\n\n", nodeToString(plan));
				}
563
			}
M
Fixes:  
Marc G. Fournier 已提交
564
#endif
565
		}
B
Bruce Momjian 已提交
566

567 568 569 570 571 572 573
		/*
		 * If the command is an utility append a null plan. This is needed
		 * to keep the plan_list aligned with the querytree_list or the
		 * function executor will crash.  DZ - 30-8-1996
		 */
		else
			plan_list = lappend(plan_list, NULL);
574 575
	}

576 577 578
	if (queryListP)
		*queryListP = querytree_list;

579
	return plan_list;
580 581 582
}

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

599
static void
600
pg_exec_query(char *query_string)
601
{
602 603 604 605 606 607 608
	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);
609 610 611
}

void
612
pg_exec_query_dest(char *query_string,	/* string to execute */
613
				   CommandDest dest,	/* where results should go */
614 615
				   bool aclOverride)	/* to give utility commands power
										 * of superusers */
616
{
617
	List	   *querytree_list;
618 619
	List	   *plan_list;
	Query	   *querytree;
620 621
	Plan	   *plan;
	int			j;
622 623

	/* plan the queries */
624 625
	plan_list = pg_parse_and_plan(query_string, NULL, 0,
								  &querytree_list, dest, aclOverride);
626

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

631
	/* OK, do it to it! */
632

B
Bruce Momjian 已提交
633 634 635 636
	/*
	 * NOTE: we do not use "foreach" here because we want to be sure the
	 * list pointers have been advanced before the query is executed. We
	 * need to do that because VACUUM has a nasty little habit of doing
637 638 639 640
	 * CommitTransactionCommand at startup, and that will release the
	 * memory holding our parse/plan lists :-(.  This needs a better
	 * solution --- currently, the code will crash if someone submits
	 * "vacuum; something-else" in a single query string.  But memory
B
Bruce Momjian 已提交
641 642
	 * allocation needs redesigned anyway, so this will have to do for
	 * now.
643
	 */
644

645 646 647 648
	while (querytree_list)
	{
		querytree = (Query *) lfirst(querytree_list);
		querytree_list = lnext(querytree_list);
649 650
		plan = (Plan *) lfirst(plan_list);
		plan_list = lnext(plan_list);
651

652 653 654 655 656 657 658 659 660
		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.
			 * ----------------
			 */
661
			if (DebugPrintQuery)
M
 
Marc G. Fournier 已提交
662
				TPRINTF(TRACE_QUERY, "ProcessUtility: %s", query_string);
663
			else if (Verbose)
M
 
Marc G. Fournier 已提交
664
				TPRINTF(TRACE_VERBOSE, "ProcessUtility");
665

666 667 668 669 670 671 672
			/*
			 * We have to set query SnapShot in the case of FETCH or COPY TO.
			 */
			if (nodeTag(querytree->utilityStmt) == T_FetchStmt ||
				(nodeTag(querytree->utilityStmt) == T_CopyStmt && 
				((CopyStmt *)(querytree->utilityStmt))->direction != FROM))
				SetQuerySnapshot();
673 674 675 676
			ProcessUtility(querytree->utilityStmt, dest);
		}
		else
		{
M
Fixes:  
Marc G. Fournier 已提交
677
#ifdef INDEXSCAN_PATCH
678 679

			/*
680
			 * Print moved in pg_parse_and_plan.	DZ - 27-8-1996
681
			 */
M
Fixes:  
Marc G. Fournier 已提交
682
#else
683 684 685 686
			/* ----------------
			 *	print plan if debugging
			 * ----------------
			 */
J
Jan Wieck 已提交
687
			if (DebugPrintPlan || DebugPPrintPlan)
688
			{
B
Bruce Momjian 已提交
689 690
				if (DebugPPrintPlan)
				{
J
Jan Wieck 已提交
691 692
					TPRINTF(TRACE_PRETTY_PLAN, "plan:");
					nodeDisplay(plan);
B
Bruce Momjian 已提交
693 694 695
				}
				else
				{
J
Jan Wieck 已提交
696 697 698
					TPRINTF(TRACE_PLAN, "plan:");
					printf("\n%s\n\n", nodeToString(plan));
				}
699
			}
M
Fixes:  
Marc G. Fournier 已提交
700
#endif
701

V
Vadim B. Mikheev 已提交
702 703 704
			SetQuerySnapshot();

			/*
B
Bruce Momjian 已提交
705
			 * execute the plan
706 707 708 709 710 711
			 */
			if (ShowExecutorStats)
				ResetUsage();

			for (j = 0; j < _exec_repeat_; j++)
			{
M
 
Marc G. Fournier 已提交
712 713
				if (Verbose)
					TPRINTF(TRACE_VERBOSE, "ProcessQuery");
714
				ProcessQuery(querytree, plan, dest);
715 716 717 718 719 720 721 722 723 724 725 726 727 728 729
			}

			if (ShowExecutorStats)
			{
				fprintf(stderr, "! Executor Stats:\n");
				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.
		 */

730
		CommandCounterIncrement();
731
	}
732 733 734
}

/* --------------------------------
735
 *		signal handler routines used in PostgresMain()
736
 *
B
Bruce Momjian 已提交
737
 *		handle_warn() catches SIGQUIT.	It forces control back to the main
738 739 740
 *		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 已提交
741
 *		siglongjmp() instead.
742
 *		We still provide the signal catcher so that an error quit can be
B
Bruce Momjian 已提交
743
 *		forced externally.	This should be done only with great caution,
744 745
 *		however, since an asynchronous signal could leave the system in
 *		who-knows-what inconsistent state.
746
 *
747 748 749
 *		quickdie() occurs when signalled by the postmaster.
 *		Some backend has bought the farm,
 *		so we need to stop what we're doing and exit.
750
 *
751
 *		die() performs an orderly cleanup via ExitPostgres()
752 753 754 755
 * --------------------------------
 */

void
756
handle_warn(SIGNAL_ARGS)
757
{
758
	siglongjmp(Warn_restart, 1);
759 760
}

761
void
762
quickdie(SIGNAL_ARGS)
763
{
764
	PG_SETMASK(&BlockSig);
765
	elog(NOTICE, "Message from PostgreSQL backend:"
766 767 768 769 770
		 "\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.");
771

772 773 774 775 776 777 778

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

779
	exit(1);
780 781
}

782 783 784
/*
 * Abort transaction and exit
 */
785
void
786
die(SIGNAL_ARGS)
787
{
788 789 790 791 792 793 794 795 796 797
	PG_SETMASK(&BlockSig);
	/*
	 * If ERROR/FATAL is in progress...
	 */
	if (InError)
	{
		ExitAfterAbort = true;
		return;
	}
	elog(FATAL, "The system is shutting down");
798 799 800
}

/* signal handler for floating point exception */
801
void
802
FloatExceptionHandler(SIGNAL_ARGS)
803
{
804
	elog(ERROR, "floating point exception!"
805 806
		 " The last floating point operation either exceeded legal ranges"
		 " or was a divide by zero");
807 808 809
}


M
 
Marc G. Fournier 已提交
810
/* signal handler for query cancel signal from postmaster */
811 812 813 814 815 816 817 818 819
static void
QueryCancelHandler(SIGNAL_ARGS)
{
	QueryCancel = true;
}

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

821 822
	/*
	 * QueryCancel flag will be reset in main loop, which we reach by
M
 
Marc G. Fournier 已提交
823 824
	 * longjmp from elog().
	 */
825 826 827 828
	elog(ERROR, "Query was cancelled.");
}


829 830
static void
usage(char *progname)
831
{
832
	fprintf(stderr,
833
			"Usage: %s [options] [dbname]\n", progname);
M
 
Marc G. Fournier 已提交
834
#ifdef USE_ASSERT_CHECKING
T
Tom Lane 已提交
835
	fprintf(stderr, "\t-A on\t\tenable/disable assert checking\n");
M
 
Marc G. Fournier 已提交
836
#endif
837
	fprintf(stderr, "\t-B buffers\tset number of buffers in buffer pool\n");
T
Tom Lane 已提交
838
	fprintf(stderr, "\t-C \t\tsuppress version info\n");
839 840 841
	fprintf(stderr, "\t-D dir\t\tdata directory\n");
	fprintf(stderr, "\t-E \t\techo query before execution\n");
	fprintf(stderr, "\t-F \t\tturn off fsync\n");
842
#ifdef LOCK_MGR_DEBUG
T
Tom Lane 已提交
843
	fprintf(stderr, "\t-K lev\t\tset locking debug level [0|1|2]\n");
844
#endif
845 846
	fprintf(stderr, "\t-L \t\tturn off locking\n");
	fprintf(stderr, "\t-N \t\tdon't use newline as interactive query delimiter\n");
847
	fprintf(stderr, "\t-O \t\tallow system table structure changes\n");
848
	fprintf(stderr, "\t-Q \t\tsuppress informational messages\n");
849
	fprintf(stderr, "\t-S kbytes\tset amount of memory for sorts (in kbytes)\n");
T
Tom Lane 已提交
850 851
	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 已提交
852
	fprintf(stderr, "\t-d [1-5]\tset debug level\n");
853
	fprintf(stderr, "\t-e \t\tturn on European date format\n");
T
Tom Lane 已提交
854
	fprintf(stderr, "\t-f [s|i|n|m|h]\tforbid use of some plan types\n");
855 856 857
	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");
858
	fprintf(stderr, "\t-s \t\tshow stats after each query\n");
859
	fprintf(stderr, "\t-t [pa|pl|ex]\tshow timings after each query\n");
860
	fprintf(stderr, "\t-v version\tset protocol version being used by frontend\n");
861 862 863
}

/* ----------------------------------------------------------------
864 865
 *	PostgresMain
 *		postgres main loop
866
 *		all backends, interactive or otherwise start here
867 868 869 870 871
 *
 *	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.
872 873 874
 * ----------------------------------------------------------------
 */
int
875
PostgresMain(int argc, char *argv[], int real_argc, char *real_argv[])
876
{
877
	int			flag;
878

879
	char	   *DBName = NULL;
880
	bool		secure = true;
881
	int			errs = 0;
882

883
	int			firstchar;
884
	StringInfo	parser_input;
885
	char	   *userName;
M
 
Marc G. Fournier 已提交
886 887

	/* Used if verbose is set, must be initialized */
888 889 890
	char	   *remote_info = "interactive";
	char	   *remote_host = "";
	unsigned short remote_port = 0;
891

892 893 894
	char	   *DBDate = NULL;
	extern int	optind;
	extern char *optarg;
895
	extern int  DebugLvl;
896

897
	/*
898
	 * Set default values for command-line options.
899
	 */
900
	IsUnderPostmaster = false;
901
	ShowStats = 0;
902
	ShowParserStats = ShowPlannerStats = ShowExecutorStats = 0;
M
 
Marc G. Fournier 已提交
903
	DeadlockCheckTimer = DEADLOCK_CHECK_TIMER;
904 905
	Noversion = false;
	EchoQuery = false;
906
#ifdef LOCK_MGR_DEBUG
M
 
Marc G. Fournier 已提交
907
	LockDebug = 0;
908
#endif
909
	DataDir = getenv("PGDATA");
910

911 912
	SetProcessingMode(InitProcessing);

913
	/*
914 915 916
	 * Try to get initial values for date styles and formats. Does not do
	 * a complete job, but should be good enough for backend. Cannot call
	 * parse_date() since palloc/pfree memory is not set up yet.
917 918 919 920 921 922 923 924 925 926 927 928 929 930 931
	 */
	DBDate = getenv("PGDATESTYLE");
	if (DBDate != NULL)
	{
		if (strcasecmp(DBDate, "ISO") == 0)
			DateStyle = USE_ISO_DATES;
		else if (strcasecmp(DBDate, "SQL") == 0)
			DateStyle = USE_SQL_DATES;
		else if (strcasecmp(DBDate, "POSTGRES") == 0)
			DateStyle = USE_POSTGRES_DATES;
		else if (strcasecmp(DBDate, "GERMAN") == 0)
		{
			DateStyle = USE_GERMAN_DATES;
			EuroDates = TRUE;
		}
932
		else if (strcasecmp(DBDate, "NONEURO") == 0)
933 934 935 936
			EuroDates = FALSE;
		else if (strcasecmp(DBDate, "EURO") == 0)
			EuroDates = TRUE;
	}
937

M
 
Marc G. Fournier 已提交
938 939 940
	/*
	 * Read default pg_options from file $DATADIR/pg_options.
	 */
941
	if (DataDir)
M
 
Marc G. Fournier 已提交
942
		read_pg_options(0);
943

944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961
	/* ----------------
	 *	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 */
962

M
 
Marc G. Fournier 已提交
963
	while ((flag = getopt(argc, argv,
964
						  "A:B:CD:d:EeFf:iK:LNOo:p:QS:sT:t:v:W:x:"))
965 966 967
		   != EOF)
		switch (flag)
		{
M
 
Marc G. Fournier 已提交
968 969
			case 'A':
				/* ----------------
970
				 *	enable/disable assert checking.
M
 
Marc G. Fournier 已提交
971 972 973 974 975 976 977 978
				 * ----------------
				 */
#ifdef USE_ASSERT_CHECKING
				assert_enabled = atoi(optarg);
#else
				fprintf(stderr, "Assert checking is not enabled\n");
#endif
				break;
979

980 981 982 983 984
			case 'B':
				/* ----------------
				 *	specify the size of buffer pool
				 * ----------------
				 */
985 986
				if (secure)
					NBuffers = atoi(optarg);
987
				break;
988

989 990
			case 'C':
				/* ----------------
991
				 *	don't print version string
992 993
				 * ----------------
				 */
994
				Noversion = true;
995
				break;
996

997
			case 'D':			/* PGDATA directory */
998 999 1000 1001 1002 1003 1004 1005 1006
				if (secure)
				{
					if (!DataDir)
					{
						DataDir = optarg;
						/* must be done after DataDir is defined */
						read_pg_options(0);
					}
					DataDir = optarg;
1007
				}
M
 
Marc G. Fournier 已提交
1008
				break;
1009

1010
			case 'd':			/* debug level */
1011
				DebugLvl = atoi(optarg);
M
 
Marc G. Fournier 已提交
1012
				if (DebugLvl >= 1)
1013
					Verbose = true;
M
 
Marc G. Fournier 已提交
1014
				if (DebugLvl >= 2)
1015
					DebugPrintQuery = true;
M
 
Marc G. Fournier 已提交
1016
				if (DebugLvl >= 3)
1017
					DebugPrintParse = true;
B
Bruce Momjian 已提交
1018
				if (DebugLvl >= 4)
1019
					DebugPrintPlan = true;
J
Jan Wieck 已提交
1020 1021
				if (DebugLvl >= 5)
					DebugPPrintRewrittenParsetree = true;
1022
				break;
1023 1024 1025 1026 1027 1028

			case 'E':
				/* ----------------
				 *	E - echo the query the user entered
				 * ----------------
				 */
1029
				EchoQuery = true;
1030
				break;
1031 1032 1033 1034 1035 1036

			case 'e':
				/* --------------------------
				 * Use european date formats.
				 * --------------------------
				 */
1037
				EuroDates = true;
1038
				break;
1039 1040 1041 1042 1043 1044

			case 'F':
				/* --------------------
				 *	turn off fsync
				 * --------------------
				 */
1045 1046
				if (secure)
					disableFsync = true;
1047
				break;
1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065

			case 'f':
				/* -----------------
				 *	  f - forbid generation of certain plans
				 * -----------------
				 */
				switch (optarg[0])
				{
					case 's':	/* seqscan */
						_enable_seqscan_ = false;
						break;
					case 'i':	/* indexscan */
						_enable_indexscan_ = false;
						break;
					case 'n':	/* nestloop */
						_enable_nestloop_ = false;
						break;
					case 'm':	/* mergejoin */
1066
						_enable_mergejoin_ = false;
1067 1068 1069 1070 1071 1072 1073
						break;
					case 'h':	/* hashjoin */
						_enable_hashjoin_ = false;
						break;
					default:
						errs++;
				}
1074 1075
				break;

1076 1077 1078
			case 'i':
				dontExecute = 1;
				break;
1079

1080
			case 'K':
1081
#ifdef LOCK_MGR_DEBUG
M
 
Marc G. Fournier 已提交
1082
				LockDebug = atoi(optarg);
1083
#else
1084
				fprintf(stderr, "Lock debug not compiled in\n");
1085
#endif
1086
				break;
1087

1088 1089 1090 1091 1092
			case 'L':
				/* --------------------
				 *	turn off locking
				 * --------------------
				 */
1093 1094
				if (secure)
					lockingOff = 1;
T
Tom Lane 已提交
1095 1096
				break;

1097 1098 1099 1100 1101 1102 1103
			case 'N':
				/* ----------------
				 *	N - Don't use newline as a query delimiter
				 * ----------------
				 */
				UseNewLine = 0;
				break;
1104

1105 1106 1107 1108 1109
			case 'O':
				/* --------------------
				 *	allow system table structure modifications
				 * --------------------
				 */
1110 1111
				if (secure)		/* XXX safe to allow from client??? */
					allowSystemTableMods = true;
1112 1113
				break;

T
Tom Lane 已提交
1114 1115 1116 1117 1118
			case 'o':
				/* ----------------
				 *	o - send output (stdout and stderr) to the given file
				 * ----------------
				 */
1119 1120
				if (secure)
					StrNCpy(OutputFileName, optarg, MAXPGPATH);
T
Tom Lane 已提交
1121 1122
				break;

1123
			case 'p':
1124 1125 1126 1127 1128
				/* ----------------
				 *	p - special flag passed if backend was forked
				 *		by a postmaster.
				 * ----------------
				 */
1129 1130 1131 1132
				if (secure)
				{
					IsUnderPostmaster = true;
					DBName = optarg;
B
Bruce Momjian 已提交
1133 1134
					secure = false;		/* subsequent switches are NOT
										 * secure */
1135
				}
1136
				break;
1137

1138 1139 1140 1141 1142
			case 'Q':
				/* ----------------
				 *	Q - set Quiet mode (reduce debugging output)
				 * ----------------
				 */
1143
				Verbose = false;
1144
				break;
1145

1146 1147
			case 'S':
				/* ----------------
V
Vadim B. Mikheev 已提交
1148
				 *	S - amount of sort memory to use in 1k bytes
1149 1150
				 * ----------------
				 */
1151
				{
1152 1153
					int			S;

V
Vadim B. Mikheev 已提交
1154
					S = atoi(optarg);
1155
					if (S >= 4 * BLCKSZ / 1024)
V
Vadim B. Mikheev 已提交
1156
						SortMem = S;
1157
				}
1158
				break;
1159 1160 1161 1162 1163 1164 1165 1166

			case 's':
				/* ----------------
				 *	  s - report usage statistics (timings) after each query
				 * ----------------
				 */
				ShowStats = 1;
				StatFp = stderr;
1167
				break;
1168

1169
			case 'T':
1170 1171 1172 1173 1174
				/* ----------------
				 *	T - tracing options
				 * ----------------
				 */
				parse_options(optarg, secure);
M
 
Marc G. Fournier 已提交
1175 1176
				break;

1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205
			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.
				 * ----------------
				 */
				StatFp = stderr;
				switch (optarg[0])
				{
					case 'p':
						if (optarg[1] == 'a')
							ShowParserStats = 1;
						else if (optarg[1] == 'l')
							ShowPlannerStats = 1;
						else
							errs++;
						break;
					case 'e':
						ShowExecutorStats = 1;
						break;
					default:
						errs++;
						break;
				}
1206 1207
				break;

1208
			case 'v':
1209 1210
				if (secure)
					FrontendProtocol = (ProtocolVersion) atoi(optarg);
1211 1212
				break;

M
 
Marc G. Fournier 已提交
1213 1214
			case 'W':
				/* ----------------
1215
				 *	wait N seconds to allow attach from a debugger
M
 
Marc G. Fournier 已提交
1216 1217 1218 1219 1220
				 * ----------------
				 */
				sleep(atoi(optarg));
				break;

1221
			case 'x':
B
Bruce Momjian 已提交
1222
#ifdef NOT_USED					/* planner/xfunc.h */
1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250

				/*
				 * 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++;
				}
1251
#endif
1252
				break;
1253

1254 1255 1256 1257 1258 1259
			default:
				/* ----------------
				 *	default: bad command line option
				 * ----------------
				 */
				errs++;
T
Tom Lane 已提交
1260
				break;
1261 1262
		}

1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324
	if (ShowStats &&
		(ShowParserStats || ShowPlannerStats || ShowExecutorStats))
	{
		fprintf(stderr, "-s can not be used together with -t.\n");
		proc_exit(1);
	}

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

	/*
	 * 1. Set BlockSig and UnBlockSig masks. 
	 * 2. Set up signal handlers.
	 * 3. Allow only SIGUSR1 signal (we never block it) 
	 *    during initialization.
	 *
	 * 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

	pqsignal(SIGHUP, read_pg_options);		/* update pg_options from file */
	pqsignal(SIGINT, QueryCancelHandler);	/* cancel current query */
	pqsignal(SIGQUIT, handle_warn);			/* handle error */
	pqsignal(SIGTERM, die);
	pqsignal(SIGALRM, HandleDeadLock);
	/* 
	 * 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 
	 * midst of output during who-knows-what operation...
	 */
	pqsignal(SIGPIPE, SIG_IGN);
	pqsignal(SIGUSR1, quickdie);
	pqsignal(SIGUSR2, Async_NotifyHandler);	/* flush also sinval cache */
	pqsignal(SIGFPE, FloatExceptionHandler);
	pqsignal(SIGCHLD, SIG_IGN);				/* ignored, sent by LockOwners */
	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
1325 1326 1327 1328
	 */
	SetPgUserName();
	userName = GetPgUserName();

1329
	if (IsUnderPostmaster)
1330
	{
1331 1332 1333 1334 1335 1336
		/* noninteractive case: nothing should be left after switches */
		if (errs || argc != optind || DBName == NULL)
		{
			usage(argv[0]);
			proc_exit(1);
		}
1337 1338 1339
		pq_init();				/* initialize libpq at backend startup */
		whereToSendOutput = Remote;
		BaseInit();
1340
	}
1341
	else
1342
	{
1343
		/* interactive case: database name can be last arg on command line */
1344
		whereToSendOutput = Debug;
1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357
		if (errs || argc - optind > 1)
		{
			usage(argv[0]);
			proc_exit(1);
		}
		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]);
			proc_exit(1);
		}
1358
		BaseInit();
1359 1360 1361 1362
		snprintf(XLogDir, MAXPGPATH, "%s%cpg_xlog",
				 DataDir, SEP_CHAR);
		snprintf(ControlFilePath, MAXPGPATH, "%s%cpg_control",
				 DataDir, SEP_CHAR);
1363
		StartupXLOG();
1364 1365
	}

1366 1367 1368 1369 1370 1371 1372 1373
	/*
	 * Set up additional info.
	 */

#ifdef CYR_RECODE
	SetCharSet();
#endif

1374
	/* On some systems our dynloader code needs the executable's pathname */
1375 1376 1377
	if (FindExec(pg_pathname, argv[0], "postgres") < 0)
		elog(FATAL, "%s: could not locate executable, bailing out...",
			 argv[0]);
1378

M
 
Marc G. Fournier 已提交
1379 1380 1381
	/*
	 * Find remote host name or address.
	 */
1382 1383 1384 1385 1386
	if (IsUnderPostmaster)
	{
		switch (MyProcPort->raddr.sa.sa_family)
		{
				struct hostent *host_ent;
M
 
Marc G. Fournier 已提交
1387

1388
			case AF_INET:
M
 
Marc G. Fournier 已提交
1389 1390 1391
				remote_info = remote_host = malloc(48);
				remote_port = ntohs(MyProcPort->raddr.in.sin_port);
				strcpy(remote_host, inet_ntoa(MyProcPort->raddr.in.sin_addr));
1392 1393
				if (HostnameLookup)
				{
M
 
Marc G. Fournier 已提交
1394
					host_ent = \
1395 1396
						gethostbyaddr((char *) &MyProcPort->raddr.in.sin_addr,
								   sizeof(MyProcPort->raddr.in.sin_addr),
M
 
Marc G. Fournier 已提交
1397
									  AF_INET);
1398 1399
					if (host_ent)
					{
M
 
Marc G. Fournier 已提交
1400
						strncpy(remote_host, host_ent->h_name, 48);
1401
						*(remote_host + 47) = '\0';
M
 
Marc G. Fournier 已提交
1402 1403
					}
				}
1404 1405 1406
				if (ShowPortNumber)
				{
					remote_info = malloc(strlen(remote_host) + 6);
M
 
Marc G. Fournier 已提交
1407 1408 1409
					sprintf(remote_info, "%s:%d", remote_host, remote_port);
				}
				break;
1410
			case AF_UNIX:
M
 
Marc G. Fournier 已提交
1411 1412
				remote_info = remote_host = "localhost";
				break;
1413
			default:
M
 
Marc G. Fournier 已提交
1414 1415 1416
				remote_info = remote_host = "unknown";
				break;
		}
1417 1418 1419
		/*
		 * Set process params for ps
		 */
1420
		PS_INIT_STATUS(real_argc, real_argv, argv[0],
M
 
Marc G. Fournier 已提交
1421
					   remote_info, userName, DBName);
1422
		PS_SET_STATUS("startup");
1423 1424
	}

1425

1426
	/* ----------------
M
 
Marc G. Fournier 已提交
1427
	 *	print flags
1428 1429
	 * ----------------
	 */
M
 
Marc G. Fournier 已提交
1430
	if (Verbose)
1431
	{
1432
		if (Verbose)
1433
		{
M
 
Marc G. Fournier 已提交
1434 1435
			TPRINTF(TRACE_VERBOSE, "started: host=%s user=%s database=%s",
					remote_host, userName, DBName);
1436 1437 1438
		}
		else
		{
M
 
Marc G. Fournier 已提交
1439 1440 1441 1442 1443
			TPRINTF(TRACE_VERBOSE, "debug info:");
			TPRINTF(TRACE_VERBOSE, "\tUser         = %s", userName);
			TPRINTF(TRACE_VERBOSE, "\tRemoteHost   = %s", remote_host);
			TPRINTF(TRACE_VERBOSE, "\tRemotePort   = %d", remote_port);
			TPRINTF(TRACE_VERBOSE, "\tDatabaseName = %s", DBName);
1444
			TPRINTF(TRACE_VERBOSE, "\tDebug Level  = %d", DebugLvl);
M
 
Marc G. Fournier 已提交
1445 1446 1447 1448 1449 1450 1451 1452
			TPRINTF(TRACE_VERBOSE, "\tNoversion    = %c", Noversion ? 't' : 'f');
			TPRINTF(TRACE_VERBOSE, "\ttimings      = %c", ShowStats ? 't' : 'f');
			TPRINTF(TRACE_VERBOSE, "\tdates        = %s",
					EuroDates ? "European" : "Normal");
			TPRINTF(TRACE_VERBOSE, "\tbufsize      = %d", NBuffers);
			TPRINTF(TRACE_VERBOSE, "\tsortmem      = %d", SortMem);
			TPRINTF(TRACE_VERBOSE, "\tquery echo   = %c", EchoQuery ? 't' : 'f');
		}
1453 1454
	}

1455

1456 1457
	/*
	 * general initialization
1458
	 */
1459

M
 
Marc G. Fournier 已提交
1460 1461
	if (Verbose)
		TPRINTF(TRACE_VERBOSE, "InitPostgres");
1462 1463 1464

	InitPostgres(DBName);

1465
#ifdef MULTIBYTE
1466
	/* set default client encoding */
M
 
Marc G. Fournier 已提交
1467
	if (Verbose)
1468 1469
		puts("\treset_client_encoding()..");
	reset_client_encoding();
M
 
Marc G. Fournier 已提交
1470
	if (Verbose)
1471 1472 1473
		puts("\treset_client_encoding() done.");
#endif

1474 1475
	on_shmem_exit(remove_all_temp_relations, NULL);

1476 1477
	parser_input = makeStringInfo(); /* initialize input buffer */

1478 1479
	/* 
	 * Send this backend's cancellation info to the frontend. 
1480
	 */
M
 
Marc G. Fournier 已提交
1481 1482 1483
	if (whereToSendOutput == Remote &&
		PG_PROTOCOL_MAJOR(FrontendProtocol) >= 2)
	{
1484
		StringInfoData buf;
B
Bruce Momjian 已提交
1485

1486 1487 1488 1489 1490
		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 已提交
1491 1492 1493
		/* Need not flush since ReadyForQuery will do it. */
	}

1494 1495 1496
	if (!IsUnderPostmaster)
	{
		puts("\nPOSTGRES backend interactive interface ");
1497
		puts("$Revision: 1.136 $ $Date: 1999/10/25 03:07:48 $\n");
1498 1499
	}

1500
	/*
1501 1502 1503 1504 1505
	 * Initialize the deferred trigger manager
	 */
	if (DeferredTriggerInit() != 0)
		ExitPostgres(1);

1506 1507
	/*
	 * POSTGRES main processing loop begins here
1508
	 *
1509 1510
	 * If an exception is encountered, processing resumes here
	 * so we abort the current transaction and start a new one.
1511 1512
	 */

1513 1514
	SetProcessingMode(NormalProcessing);

1515 1516 1517 1518
	if (sigsetjmp(Warn_restart, 1) != 0)
	{
		time(&tim);

M
 
Marc G. Fournier 已提交
1519 1520
		if (Verbose)
			TPRINTF(TRACE_VERBOSE, "AbortCurrentTransaction");
1521 1522

		AbortCurrentTransaction();
1523 1524 1525 1526 1527 1528
		InError = false;
		if (ExitAfterAbort)
		{
			ProcReleaseLocks();		/* Just to be sure... */
			ExitPostgres(0);
		}
1529
	}
1530

1531
	PG_SETMASK(&UnBlockSig);
1532

1533 1534
	/*
	 * Non-error queries loop here.
1535 1536 1537 1538
	 */

	for (;;)
	{
1539 1540
		PS_SET_STATUS("idle");

B
Bruce Momjian 已提交
1541
		/* ----------------
1542 1543
		 *	 (1) tell the frontend we're ready for a new query.
		 *
B
Bruce Momjian 已提交
1544
		 *	 Note: this includes fflush()'ing the last of the prior output.
B
Bruce Momjian 已提交
1545 1546
		 * ----------------
		 */
1547
		ReadyForQuery(whereToSendOutput);
B
Bruce Momjian 已提交
1548

1549
		/* ----------------
1550
		 *	 (2) deal with pending asynchronous NOTIFY from other backends,
B
Bruce Momjian 已提交
1551
		 *	 and enable async.c's signal handler to execute NOTIFY directly.
1552 1553 1554 1555 1556 1557 1558 1559
		 * ----------------
		 */
		QueryCancel = false;	/* forget any earlier CANCEL signal */

		EnableNotifyInterrupt();

		/* ----------------
		 *	 (3) read a command.
1560 1561
		 * ----------------
		 */
1562
		firstchar = ReadCommand(parser_input);
1563

1564
		QueryCancel = false;	/* forget any earlier CANCEL signal */
1565

1566
		/* ----------------
1567 1568 1569 1570 1571 1572 1573
		 *	 (4) disable async.c's signal handler.
		 * ----------------
		 */
		DisableNotifyInterrupt();

		/* ----------------
		 *	 (5) process the command.
1574 1575
		 * ----------------
		 */
1576 1577 1578
		switch (firstchar)
		{
				/* ----------------
1579 1580
				 *	'F' indicates a fastpath call.
				 *		XXX HandleFunctionRequest
1581 1582
				 * ----------------
				 */
1583
			case 'F':
1584 1585
				IsEmptyQuery = false;

1586
				/* start an xact for this function invocation */
M
 
Marc G. Fournier 已提交
1587 1588
				if (Verbose)
					TPRINTF(TRACE_VERBOSE, "StartTransactionCommand");
1589
				StartTransactionCommand();
1590

1591 1592 1593 1594 1595 1596
				if (HandleFunctionRequest() == EOF)
				{
					/* lost frontend connection during F message input */
					pq_close();
					proc_exit(0);
				}
1597
				break;
1598

1599 1600 1601 1602 1603
				/* ----------------
				 *	'Q' indicates a user query
				 * ----------------
				 */
			case 'Q':
1604
				if (strspn(parser_input->data, " \t\n") == parser_input->len)
1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623
				{
					/* ----------------
					 *	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;
					if (ShowStats)
						ResetUsage();

					/* start an xact for this query */
M
 
Marc G. Fournier 已提交
1624 1625
					if (Verbose)
						TPRINTF(TRACE_VERBOSE, "StartTransactionCommand");
1626
					StartTransactionCommand();
1627

1628
					pg_exec_query(parser_input->data);
1629

1630 1631 1632 1633 1634 1635
					/*
					 * Invoke IMMEDIATE constraint triggers
					 *
					 */
					DeferredTriggerEndQuery();

1636 1637 1638 1639 1640 1641
					if (ShowStats)
						ShowUsage();
				}
				break;

				/* ----------------
1642 1643 1644
				 *	'X' means that the frontend is closing down the socket.
				 *	EOF means unexpected loss of frontend connection.
				 *	Either way, perform normal shutdown.
1645 1646 1647
				 * ----------------
				 */
			case 'X':
1648
			case EOF:
1649 1650
				if (!IsUnderPostmaster)
					ShutdownXLOG();
1651
				pq_close();
1652
				proc_exit(0);
1653 1654 1655
				break;

			default:
M
 
Marc G. Fournier 已提交
1656
				elog(ERROR, "unknown frontend message was received");
1657 1658 1659
		}

		/* ----------------
1660
		 *	 (6) commit the current transaction
1661 1662
		 *
		 *	 Note: if we had an empty input buffer, then we didn't
1663
		 *	 call pg_exec_query, so we don't bother to commit this transaction.
1664 1665 1666 1667
		 * ----------------
		 */
		if (!IsEmptyQuery)
		{
M
 
Marc G. Fournier 已提交
1668 1669 1670
			if (Verbose)
				TPRINTF(TRACE_VERBOSE, "CommitTransactionCommand");
			PS_SET_STATUS("commit");
1671 1672 1673 1674
			CommitTransactionCommand();
		}
		else
		{
1675
			if (IsUnderPostmaster)
1676 1677 1678
				NullCommand(Remote);
		}
	}							/* infinite for-loop */
1679 1680

	proc_exit(0);				/* shouldn't get here... */
1681
	return 1;
1682 1683
}

1684
#ifndef HAVE_GETRUSAGE
B
Bruce Momjian 已提交
1685 1686
#include "rusagestub.h"
#else
1687
#include <sys/resource.h>
1688
#endif	 /* HAVE_GETRUSAGE */
1689

1690 1691
struct rusage Save_r;
struct timeval Save_t;
1692 1693

void
1694
ResetUsage(void)
1695
{
1696 1697 1698 1699 1700 1701
	struct timezone tz;

	getrusage(RUSAGE_SELF, &Save_r);
	gettimeofday(&Save_t, &tz);
	ResetBufferUsage();
/*	  ResetTupleCount(); */
1702 1703 1704
}

void
1705
ShowUsage(void)
1706
{
1707 1708 1709
	struct timeval user,
				sys;
	struct timeval elapse_t;
1710
	struct timezone tz;
1711
	struct rusage r;
1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756

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

	/*
	 * 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);
1757
#ifdef HAVE_GETRUSAGE
1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782
	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);
1783
#endif	 /* HAVE_GETRUSAGE */
1784 1785 1786
	fprintf(StatFp, "! postgres usage stats:\n");
	PrintBufferUsage(StatFp);
/*	   DisplayTupleCount(StatFp); */
1787
}
M
 
Marc G. Fournier 已提交
1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802

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

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

1803 1804
	if (assert_enabled)
	{
M
 
Marc G. Fournier 已提交
1805 1806 1807
		/* val != 0 should be trapped by previous Assert */
		elog(NOTICE, "Assert test successfull (val = %d)", val);
	}
1808 1809
	else
		elog(NOTICE, "Assert checking is disabled (val = %d)", val);
M
 
Marc G. Fournier 已提交
1810 1811 1812

	return val;
}
1813

M
 
Marc G. Fournier 已提交
1814 1815
#endif
#endif