postgres.c 43.3 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
B
Add:  
Bruce Momjian 已提交
11
 *	  $Header: /cvsroot/pgsql/src/backend/tcop/postgres.c,v 1.141 2000/01/26 05:57:07 momjian 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 "libpq/libpq.h"
44
#include "libpq/pqformat.h"
45
#include "libpq/pqsignal.h"
B
Bruce Momjian 已提交
46
#include "miscadmin.h"
47 48
#include "nodes/print.h"
#include "optimizer/cost.h"
49
#include "optimizer/planner.h"
50
#include "parser/parser.h"
B
Bruce Momjian 已提交
51
#include "rewrite/rewriteHandler.h"
52 53
#include "tcop/fastpath.h"
#include "tcop/pquery.h"
B
Bruce Momjian 已提交
54
#include "tcop/tcopprot.h"
55
#include "tcop/utility.h"
56
#include "storage/proc.h"
M
 
Marc G. Fournier 已提交
57
#include "utils/ps_status.h"
58
#include "utils/temprel.h"
M
 
Marc G. Fournier 已提交
59 60
#include "utils/trace.h"

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

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

M
 
Marc G. Fournier 已提交
67 68 69 70 71 72 73
/*
 * 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 已提交
74 75 76 77 78 79
#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 已提交
80 81 82 83 84 85 86 87 88 89 90
#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]

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

96
CommandDest whereToSendOutput = Debug;
97

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

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

extern void		HandleDeadLock(SIGNAL_ARGS);

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

110 111
extern int	lockingOff;
extern int	NBuffers;
112

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

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

120
bool		Warn_restart_ready = false;
121 122
bool		InError = false;
bool		ExitAfterAbort = false;
123

124
extern int	NBuffers;
125

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

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

140
#else
141
int			UseNewLine = 0;		/* Use EOF as query delimiters */
142

143
#endif	 /* TCOP_DONTUSENEWLINE */
144 145 146 147

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

/*
 * ----------------
152 153 154 155 156 157 158
 *	 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
159 160
 * ----------------
*/
161
int			_exec_repeat_ = 1;
162 163

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


/* ----------------------------------------------------------------
174
 *		routines to obtain user input
175 176 177 178
 * ----------------------------------------------------------------
 */

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

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

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

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

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

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

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

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

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

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

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

277
	return 'Q';
278 279 280
}

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

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

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

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

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

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

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

/* ----------------
353 354 355
 *		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
356
 *		call.  EOF is returned if end of file.
357 358
 * ----------------
 */
359
static int
360
ReadCommand(StringInfo inBuf)
361
{
362 363 364 365 366 367 368
	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);
369
	if (IsUnderPostmaster)
370
		result = SocketBackend(inBuf);
371
	else
372 373 374
		result = InteractiveBackend(inBuf);
	MemoryContextSwitchTo(oldcontext);
	return result;
375 376
}

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

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

399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
	/* ----------------
	 *	(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
416
	 *
B
Bruce Momjian 已提交
417 418
	 *	rewritten queries are collected in new_list.  Note there may be
	 *	more or fewer than in the original list.
419 420
	 * ----------------
	 */
421
	new_list = NIL;
B
Bruce Momjian 已提交
422
	foreach(querytree_list_item, querytree_list)
423
	{
424
		querytree = (Query *) lfirst(querytree_list_item);
425

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

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

	querytree_list = new_list;

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

464 465
			querytree = (Query *) lfirst(querytree_list_item);

466 467 468
			if (querytree->commandType == CMD_UTILITY)
				continue;

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

				rte->skipAcl = TRUE;
			}
		}
	}

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

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

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

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

		/*
		 * 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
				 * ----------------
				 */
522
				char	   *tag = "*ABORT STATE*";
523 524 525 526 527 528

				EndCommand(tag, dest);

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

529
				if (queryListP)
530 531
					*queryListP = NIL;
				return NIL;
532 533 534 535
			}

			if (ShowPlannerStats)
				ResetUsage();
536 537

			/* call that optimizer */
538
			plan = planner(querytree);
539

540 541 542 543 544 545
			if (ShowPlannerStats)
			{
				fprintf(stderr, "! Planner Stats:\n");
				ShowUsage();
			}
			plan_list = lappend(plan_list, plan);
M
Fixes:  
Marc G. Fournier 已提交
546
#ifdef INDEXSCAN_PATCH
547 548 549 550 551 552
			/* ----------------
			 *	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 已提交
553
			if (DebugPrintPlan || DebugPPrintPlan)
554
			{
B
Bruce Momjian 已提交
555 556
				if (DebugPPrintPlan)
				{
J
Jan Wieck 已提交
557 558
					TPRINTF(TRACE_PRETTY_PLAN, "plan:");
					nodeDisplay(plan);
B
Bruce Momjian 已提交
559 560 561
				}
				else
				{
J
Jan Wieck 已提交
562 563 564
					TPRINTF(TRACE_PLAN, "plan:");
					printf("\n%s\n\n", nodeToString(plan));
				}
565
			}
M
Fixes:  
Marc G. Fournier 已提交
566
#endif
567
		}
B
Bruce Momjian 已提交
568

569 570 571 572 573 574 575
		/*
		 * 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);
576 577
	}

578 579 580
	if (queryListP)
		*queryListP = querytree_list;

581
	return plan_list;
582 583 584
}

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

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

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

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

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

633
	/* OK, do it to it! */
634

B
Bruce Momjian 已提交
635 636 637 638
	/*
	 * 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
639 640 641 642
	 * 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 已提交
643 644
	 * allocation needs redesigned anyway, so this will have to do for
	 * now.
645
	 */
646

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

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

668 669 670 671 672 673 674
			/*
			 * 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();
675 676 677 678
			ProcessUtility(querytree->utilityStmt, dest);
		}
		else
		{
M
Fixes:  
Marc G. Fournier 已提交
679
#ifdef INDEXSCAN_PATCH
680 681

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

V
Vadim B. Mikheev 已提交
704 705 706
			SetQuerySnapshot();

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

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

			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.
		 */

732
		CommandCounterIncrement();
733
	}
734 735 736
}

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

void
758
handle_warn(SIGNAL_ARGS)
759
{
760
	siglongjmp(Warn_restart, 1);
761 762
}

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

774 775

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

781
	exit(1);
782 783
}

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

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


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

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

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


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

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

881
	char	   *DBName = NULL;
882
	bool		secure = true;
883
	int			errs = 0;
884

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

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

894 895 896
	char	   *DBDate = NULL;
	extern int	optind;
	extern char *optarg;
897
	extern int  DebugLvl;
898

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

913 914
	SetProcessingMode(InitProcessing);

915
	/*
916 917 918
	 * 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.
919 920 921 922 923 924 925 926 927 928 929 930 931 932 933
	 */
	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;
		}
934
		else if (strcasecmp(DBDate, "NONEURO") == 0)
935 936 937 938
			EuroDates = FALSE;
		else if (strcasecmp(DBDate, "EURO") == 0)
			EuroDates = TRUE;
	}
939

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

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

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

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

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

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

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

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

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

			case 'F':
				/* --------------------
				 *	turn off fsync
				 * --------------------
				 */
1047 1048
				if (secure)
					disableFsync = true;
1049
				break;
1050 1051 1052 1053 1054 1055 1056 1057 1058

			case 'f':
				/* -----------------
				 *	  f - forbid generation of certain plans
				 * -----------------
				 */
				switch (optarg[0])
				{
					case 's':	/* seqscan */
1059
						enable_seqscan = false;
1060 1061
						break;
					case 'i':	/* indexscan */
1062 1063 1064 1065
						enable_indexscan = false;
						break;
					case 't':	/* tidscan */
						enable_tidscan = false;
1066 1067
						break;
					case 'n':	/* nestloop */
1068
						enable_nestloop = false;
1069 1070
						break;
					case 'm':	/* mergejoin */
1071
						enable_mergejoin = false;
1072 1073
						break;
					case 'h':	/* hashjoin */
1074
						enable_hashjoin = false;
1075 1076 1077 1078
						break;
					default:
						errs++;
				}
1079 1080
				break;

1081 1082 1083
			case 'i':
				dontExecute = 1;
				break;
1084

1085
			case 'K':
1086
#ifdef LOCK_MGR_DEBUG
M
 
Marc G. Fournier 已提交
1087
				LockDebug = atoi(optarg);
1088
#else
1089
				fprintf(stderr, "Lock debug not compiled in\n");
1090
#endif
1091
				break;
1092

1093 1094 1095 1096 1097
			case 'L':
				/* --------------------
				 *	turn off locking
				 * --------------------
				 */
1098 1099
				if (secure)
					lockingOff = 1;
T
Tom Lane 已提交
1100 1101
				break;

1102 1103 1104 1105 1106 1107 1108
			case 'N':
				/* ----------------
				 *	N - Don't use newline as a query delimiter
				 * ----------------
				 */
				UseNewLine = 0;
				break;
1109

1110 1111 1112 1113 1114
			case 'O':
				/* --------------------
				 *	allow system table structure modifications
				 * --------------------
				 */
1115 1116
				if (secure)		/* XXX safe to allow from client??? */
					allowSystemTableMods = true;
1117 1118
				break;

T
Tom Lane 已提交
1119 1120 1121 1122 1123
			case 'o':
				/* ----------------
				 *	o - send output (stdout and stderr) to the given file
				 * ----------------
				 */
1124 1125
				if (secure)
					StrNCpy(OutputFileName, optarg, MAXPGPATH);
T
Tom Lane 已提交
1126 1127
				break;

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

1143 1144 1145 1146 1147
			case 'Q':
				/* ----------------
				 *	Q - set Quiet mode (reduce debugging output)
				 * ----------------
				 */
1148
				Verbose = false;
1149
				break;
1150

1151 1152
			case 'S':
				/* ----------------
V
Vadim B. Mikheev 已提交
1153
				 *	S - amount of sort memory to use in 1k bytes
1154 1155
				 * ----------------
				 */
1156
				{
1157 1158
					int			S;

V
Vadim B. Mikheev 已提交
1159
					S = atoi(optarg);
1160
					if (S >= 4 * BLCKSZ / 1024)
V
Vadim B. Mikheev 已提交
1161
						SortMem = S;
1162
				}
1163
				break;
1164 1165 1166 1167 1168 1169 1170 1171

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

1174
			case 'T':
1175 1176 1177 1178 1179
				/* ----------------
				 *	T - tracing options
				 * ----------------
				 */
				parse_options(optarg, secure);
M
 
Marc G. Fournier 已提交
1180 1181
				break;

1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210
			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;
				}
1211 1212
				break;

1213
			case 'v':
1214 1215
				if (secure)
					FrontendProtocol = (ProtocolVersion) atoi(optarg);
1216 1217
				break;

M
 
Marc G. Fournier 已提交
1218 1219
			case 'W':
				/* ----------------
1220
				 *	wait N seconds to allow attach from a debugger
M
 
Marc G. Fournier 已提交
1221 1222 1223 1224 1225
				 * ----------------
				 */
				sleep(atoi(optarg));
				break;

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

				/*
				 * 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++;
				}
1256
#endif
1257
				break;
1258

1259 1260 1261 1262 1263 1264
			default:
				/* ----------------
				 *	default: bad command line option
				 * ----------------
				 */
				errs++;
T
Tom Lane 已提交
1265
				break;
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 1325 1326 1327 1328 1329
	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
1330 1331 1332 1333
	 */
	SetPgUserName();
	userName = GetPgUserName();

1334
	if (IsUnderPostmaster)
1335
	{
1336 1337 1338 1339 1340 1341
		/* noninteractive case: nothing should be left after switches */
		if (errs || argc != optind || DBName == NULL)
		{
			usage(argv[0]);
			proc_exit(1);
		}
1342 1343 1344
		pq_init();				/* initialize libpq at backend startup */
		whereToSendOutput = Remote;
		BaseInit();
1345
	}
1346
	else
1347
	{
1348
		/* interactive case: database name can be last arg on command line */
1349
		whereToSendOutput = Debug;
1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362
		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);
		}
1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375

		/*
		 * Try to create pid file.
		 */
		SetPidFname(DataDir);
		if (SetPidFile(-getpid())) {
			proc_exit(0);
		}
		/*
		 * Register clean up proc.
		 */
		on_proc_exit(UnlinkPidFile, NULL);

1376
		BaseInit();
1377 1378 1379 1380
		snprintf(XLogDir, MAXPGPATH, "%s%cpg_xlog",
				 DataDir, SEP_CHAR);
		snprintf(ControlFilePath, MAXPGPATH, "%s%cpg_control",
				 DataDir, SEP_CHAR);
1381
		StartupXLOG();
1382 1383
	}

1384 1385 1386 1387 1388 1389 1390 1391
	/*
	 * Set up additional info.
	 */

#ifdef CYR_RECODE
	SetCharSet();
#endif

1392
	/* On some systems our dynloader code needs the executable's pathname */
1393 1394 1395
	if (FindExec(pg_pathname, argv[0], "postgres") < 0)
		elog(FATAL, "%s: could not locate executable, bailing out...",
			 argv[0]);
1396

M
 
Marc G. Fournier 已提交
1397 1398 1399
	/*
	 * Find remote host name or address.
	 */
1400 1401 1402 1403 1404
	if (IsUnderPostmaster)
	{
		switch (MyProcPort->raddr.sa.sa_family)
		{
				struct hostent *host_ent;
M
 
Marc G. Fournier 已提交
1405

1406
			case AF_INET:
M
 
Marc G. Fournier 已提交
1407 1408 1409
				remote_info = remote_host = malloc(48);
				remote_port = ntohs(MyProcPort->raddr.in.sin_port);
				strcpy(remote_host, inet_ntoa(MyProcPort->raddr.in.sin_addr));
1410 1411
				if (HostnameLookup)
				{
M
 
Marc G. Fournier 已提交
1412
					host_ent = \
1413 1414
						gethostbyaddr((char *) &MyProcPort->raddr.in.sin_addr,
								   sizeof(MyProcPort->raddr.in.sin_addr),
M
 
Marc G. Fournier 已提交
1415
									  AF_INET);
1416 1417
					if (host_ent)
					{
M
 
Marc G. Fournier 已提交
1418
						strncpy(remote_host, host_ent->h_name, 48);
1419
						*(remote_host + 47) = '\0';
M
 
Marc G. Fournier 已提交
1420 1421
					}
				}
1422 1423 1424
				if (ShowPortNumber)
				{
					remote_info = malloc(strlen(remote_host) + 6);
M
 
Marc G. Fournier 已提交
1425 1426 1427
					sprintf(remote_info, "%s:%d", remote_host, remote_port);
				}
				break;
1428
			case AF_UNIX:
M
 
Marc G. Fournier 已提交
1429 1430
				remote_info = remote_host = "localhost";
				break;
1431
			default:
M
 
Marc G. Fournier 已提交
1432 1433 1434
				remote_info = remote_host = "unknown";
				break;
		}
1435 1436 1437
		/*
		 * Set process params for ps
		 */
1438
		PS_INIT_STATUS(real_argc, real_argv, argv[0],
M
 
Marc G. Fournier 已提交
1439
					   remote_info, userName, DBName);
1440
		PS_SET_STATUS("startup");
1441 1442
	}

1443

1444
	/* ----------------
M
 
Marc G. Fournier 已提交
1445
	 *	print flags
1446 1447
	 * ----------------
	 */
M
 
Marc G. Fournier 已提交
1448
	if (Verbose)
1449
	{
1450
		if (Verbose)
1451
		{
M
 
Marc G. Fournier 已提交
1452 1453
			TPRINTF(TRACE_VERBOSE, "started: host=%s user=%s database=%s",
					remote_host, userName, DBName);
1454 1455 1456
		}
		else
		{
M
 
Marc G. Fournier 已提交
1457 1458 1459 1460 1461
			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);
1462
			TPRINTF(TRACE_VERBOSE, "\tDebug Level  = %d", DebugLvl);
M
 
Marc G. Fournier 已提交
1463 1464 1465 1466 1467 1468 1469 1470
			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');
		}
1471 1472
	}

1473

1474 1475
	/*
	 * general initialization
1476
	 */
1477

M
 
Marc G. Fournier 已提交
1478 1479
	if (Verbose)
		TPRINTF(TRACE_VERBOSE, "InitPostgres");
1480 1481 1482

	InitPostgres(DBName);

1483
#ifdef MULTIBYTE
1484
	/* set default client encoding */
M
 
Marc G. Fournier 已提交
1485
	if (Verbose)
1486 1487
		puts("\treset_client_encoding()..");
	reset_client_encoding();
M
 
Marc G. Fournier 已提交
1488
	if (Verbose)
1489 1490 1491
		puts("\treset_client_encoding() done.");
#endif

1492 1493
	on_shmem_exit(remove_all_temp_relations, NULL);

H
 
Hiroshi Inoue 已提交
1494 1495 1496 1497 1498
	{
		MemoryContext	oldcontext = MemoryContextSwitchTo(TopMemoryContext);
		parser_input = makeStringInfo(); /* initialize input buffer */
		MemoryContextSwitchTo(oldcontext);
	}
1499

1500 1501
	/* 
	 * Send this backend's cancellation info to the frontend. 
1502
	 */
M
 
Marc G. Fournier 已提交
1503 1504 1505
	if (whereToSendOutput == Remote &&
		PG_PROTOCOL_MAJOR(FrontendProtocol) >= 2)
	{
1506
		StringInfoData buf;
B
Bruce Momjian 已提交
1507

1508 1509 1510 1511 1512
		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 已提交
1513 1514 1515
		/* Need not flush since ReadyForQuery will do it. */
	}

1516 1517 1518
	if (!IsUnderPostmaster)
	{
		puts("\nPOSTGRES backend interactive interface ");
B
Add:  
Bruce Momjian 已提交
1519
		puts("$Revision: 1.141 $ $Date: 2000/01/26 05:57:07 $\n");
1520 1521
	}

1522
	/*
1523 1524 1525
	 * Initialize the deferred trigger manager
	 */
	if (DeferredTriggerInit() != 0)
1526 1527 1528
		proc_exit(1);

	SetProcessingMode(NormalProcessing);
1529

1530 1531
	/*
	 * POSTGRES main processing loop begins here
1532
	 *
1533 1534
	 * If an exception is encountered, processing resumes here
	 * so we abort the current transaction and start a new one.
1535 1536 1537 1538 1539 1540
	 */

	if (sigsetjmp(Warn_restart, 1) != 0)
	{
		time(&tim);

M
 
Marc G. Fournier 已提交
1541 1542
		if (Verbose)
			TPRINTF(TRACE_VERBOSE, "AbortCurrentTransaction");
1543 1544

		AbortCurrentTransaction();
1545 1546 1547 1548
		InError = false;
		if (ExitAfterAbort)
		{
			ProcReleaseLocks();		/* Just to be sure... */
1549
			proc_exit(0);
1550
		}
1551
	}
1552

1553 1554
	Warn_restart_ready = true;	/* we can now handle elog(ERROR) */

1555
	PG_SETMASK(&UnBlockSig);
1556

1557 1558
	/*
	 * Non-error queries loop here.
1559 1560 1561 1562
	 */

	for (;;)
	{
1563 1564
		PS_SET_STATUS("idle");

B
Bruce Momjian 已提交
1565
		/* ----------------
1566 1567
		 *	 (1) tell the frontend we're ready for a new query.
		 *
B
Bruce Momjian 已提交
1568
		 *	 Note: this includes fflush()'ing the last of the prior output.
B
Bruce Momjian 已提交
1569 1570
		 * ----------------
		 */
1571
		ReadyForQuery(whereToSendOutput);
B
Bruce Momjian 已提交
1572

1573
		/* ----------------
1574
		 *	 (2) deal with pending asynchronous NOTIFY from other backends,
B
Bruce Momjian 已提交
1575
		 *	 and enable async.c's signal handler to execute NOTIFY directly.
1576 1577 1578 1579 1580 1581 1582 1583
		 * ----------------
		 */
		QueryCancel = false;	/* forget any earlier CANCEL signal */

		EnableNotifyInterrupt();

		/* ----------------
		 *	 (3) read a command.
1584 1585
		 * ----------------
		 */
1586
		firstchar = ReadCommand(parser_input);
1587

1588
		QueryCancel = false;	/* forget any earlier CANCEL signal */
1589

1590
		/* ----------------
1591 1592 1593 1594 1595 1596 1597
		 *	 (4) disable async.c's signal handler.
		 * ----------------
		 */
		DisableNotifyInterrupt();

		/* ----------------
		 *	 (5) process the command.
1598 1599
		 * ----------------
		 */
1600 1601 1602
		switch (firstchar)
		{
				/* ----------------
1603 1604
				 *	'F' indicates a fastpath call.
				 *		XXX HandleFunctionRequest
1605 1606
				 * ----------------
				 */
1607
			case 'F':
1608 1609
				IsEmptyQuery = false;

1610
				/* start an xact for this function invocation */
M
 
Marc G. Fournier 已提交
1611 1612
				if (Verbose)
					TPRINTF(TRACE_VERBOSE, "StartTransactionCommand");
1613
				StartTransactionCommand();
1614

1615 1616 1617 1618 1619 1620
				if (HandleFunctionRequest() == EOF)
				{
					/* lost frontend connection during F message input */
					pq_close();
					proc_exit(0);
				}
1621
				break;
1622

1623 1624 1625 1626 1627
				/* ----------------
				 *	'Q' indicates a user query
				 * ----------------
				 */
			case 'Q':
1628
				if (strspn(parser_input->data, " \t\n") == parser_input->len)
1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647
				{
					/* ----------------
					 *	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 已提交
1648 1649
					if (Verbose)
						TPRINTF(TRACE_VERBOSE, "StartTransactionCommand");
1650
					StartTransactionCommand();
1651

1652
					pg_exec_query(parser_input->data);
1653

1654 1655 1656 1657 1658 1659
					/*
					 * Invoke IMMEDIATE constraint triggers
					 *
					 */
					DeferredTriggerEndQuery();

1660 1661 1662 1663 1664 1665
					if (ShowStats)
						ShowUsage();
				}
				break;

				/* ----------------
1666 1667 1668
				 *	'X' means that the frontend is closing down the socket.
				 *	EOF means unexpected loss of frontend connection.
				 *	Either way, perform normal shutdown.
1669 1670 1671
				 * ----------------
				 */
			case 'X':
1672
			case EOF:
1673 1674
				if (!IsUnderPostmaster)
					ShutdownXLOG();
1675
				pq_close();
1676
				proc_exit(0);
1677 1678 1679
				break;

			default:
M
 
Marc G. Fournier 已提交
1680
				elog(ERROR, "unknown frontend message was received");
1681 1682 1683
		}

		/* ----------------
1684
		 *	 (6) commit the current transaction
1685 1686
		 *
		 *	 Note: if we had an empty input buffer, then we didn't
1687
		 *	 call pg_exec_query, so we don't bother to commit this transaction.
1688 1689 1690 1691
		 * ----------------
		 */
		if (!IsEmptyQuery)
		{
M
 
Marc G. Fournier 已提交
1692 1693 1694
			if (Verbose)
				TPRINTF(TRACE_VERBOSE, "CommitTransactionCommand");
			PS_SET_STATUS("commit");
1695 1696 1697 1698
			CommitTransactionCommand();
		}
		else
		{
1699
			if (IsUnderPostmaster)
1700 1701 1702
				NullCommand(Remote);
		}
	}							/* infinite for-loop */
1703 1704

	proc_exit(0);				/* shouldn't get here... */
1705
	return 1;
1706 1707
}

1708
#ifndef HAVE_GETRUSAGE
B
Bruce Momjian 已提交
1709 1710
#include "rusagestub.h"
#else
1711
#include <sys/resource.h>
1712
#endif	 /* HAVE_GETRUSAGE */
1713

1714 1715
struct rusage Save_r;
struct timeval Save_t;
1716 1717

void
1718
ResetUsage(void)
1719
{
1720 1721 1722 1723 1724 1725
	struct timezone tz;

	getrusage(RUSAGE_SELF, &Save_r);
	gettimeofday(&Save_t, &tz);
	ResetBufferUsage();
/*	  ResetTupleCount(); */
1726 1727 1728
}

void
1729
ShowUsage(void)
1730
{
1731 1732 1733
	struct timeval user,
				sys;
	struct timeval elapse_t;
1734
	struct timezone tz;
1735
	struct rusage r;
1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780

	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);
1781
#ifdef HAVE_GETRUSAGE
1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806
	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);
1807
#endif	 /* HAVE_GETRUSAGE */
1808 1809 1810
	fprintf(StatFp, "! postgres usage stats:\n");
	PrintBufferUsage(StatFp);
/*	   DisplayTupleCount(StatFp); */
1811
}
M
 
Marc G. Fournier 已提交
1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826

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

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

1827 1828
	if (assert_enabled)
	{
M
 
Marc G. Fournier 已提交
1829 1830 1831
		/* val != 0 should be trapped by previous Assert */
		elog(NOTICE, "Assert test successfull (val = %d)", val);
	}
1832 1833
	else
		elog(NOTICE, "Assert checking is disabled (val = %d)", val);
M
 
Marc G. Fournier 已提交
1834 1835 1836

	return val;
}
1837

M
 
Marc G. Fournier 已提交
1838 1839
#endif
#endif