postgres.c 43.2 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.140 2000/01/22 23:50:18 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
bool		Warn_restart_ready = false;
120 121
bool		InError = false;
bool		ExitAfterAbort = false;
122

123
extern int	NBuffers;
124

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

276
	return 'Q';
277 278 279
}

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

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

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

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

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

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

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

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

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

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

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

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

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

	querytree_list = new_list;

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

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

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

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

				rte->skipAcl = TRUE;
			}
		}
	}

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

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

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

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

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

				EndCommand(tag, dest);

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

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

			if (ShowPlannerStats)
				ResetUsage();
535 536

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

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

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

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

580
	return plan_list;
581 582 583
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

731
		CommandCounterIncrement();
732
	}
733 734 735
}

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

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

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

773 774

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

780
	exit(1);
781 782
}

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

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


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

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

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


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

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

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

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

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

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

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

912 913
	SetProcessingMode(InitProcessing);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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 1206 1207 1208 1209
			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;
				}
1210 1211
				break;

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

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

1225
			case 'x':
B
Bruce Momjian 已提交
1226
#ifdef NOT_USED					/* planner/xfunc.h */
1227 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

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

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

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

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

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

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

#ifdef CYR_RECODE
	SetCharSet();
#endif

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

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

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

1442

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

1472

1473 1474
	/*
	 * general initialization
1475
	 */
1476

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

	InitPostgres(DBName);

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

1491 1492
	on_shmem_exit(remove_all_temp_relations, NULL);

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

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

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

1515 1516 1517
	if (!IsUnderPostmaster)
	{
		puts("\nPOSTGRES backend interactive interface ");
1518
		puts("$Revision: 1.140 $ $Date: 2000/01/22 23:50:18 $\n");
1519 1520
	}

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

	SetProcessingMode(NormalProcessing);
1528

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

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

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

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

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

1554
	PG_SETMASK(&UnBlockSig);
1555

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

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

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

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

		EnableNotifyInterrupt();

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

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

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

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

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

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

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

1651
					pg_exec_query(parser_input->data);
1652

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

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

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

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

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

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

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

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

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

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

void
1728
ShowUsage(void)
1729
{
1730 1731 1732
	struct timeval user,
				sys;
	struct timeval elapse_t;
1733
	struct timezone tz;
1734
	struct rusage r;
1735 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

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

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

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

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

	return val;
}
1836

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