postgres.c 58.0 KB
Newer Older
1 2
/*-------------------------------------------------------------------------
 *
3
 * postgres.c
4
 *	  POSTGRES C Backend Interface
5
 *
B
Bruce Momjian 已提交
6
 * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group
B
Add:  
Bruce Momjian 已提交
7
 * Portions Copyright (c) 1994, Regents of the University of California
8 9 10
 *
 *
 * IDENTIFICATION
11
 *	  $Header: /cvsroot/pgsql/src/backend/tcop/postgres.c,v 1.289 2002/09/02 02:47:04 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 21
#include "postgres.h"

B
Bruce Momjian 已提交
22
#include <unistd.h>
23
#include <signal.h>
24 25
#include <time.h>
#include <sys/time.h>
B
Bruce Momjian 已提交
26
#include <fcntl.h>
27
#include <sys/socket.h>
28
#include <errno.h>
29
#if HAVE_SYS_SELECT_H
30
#include <sys/select.h>
31
#endif
32
#ifdef HAVE_GETOPT_H
B
Bruce Momjian 已提交
33
#include <getopt.h>
34
#endif
35

36
#include "access/xlog.h"
37
#include "commands/async.h"
38
#include "commands/trigger.h"
39
#include "libpq/libpq.h"
40
#include "libpq/pqformat.h"
41
#include "libpq/pqsignal.h"
B
Bruce Momjian 已提交
42
#include "miscadmin.h"
43 44
#include "nodes/print.h"
#include "optimizer/cost.h"
45
#include "optimizer/planner.h"
46 47
#include "parser/analyze.h"
#include "parser/parse.h"
48
#include "parser/parser.h"
B
Bruce Momjian 已提交
49
#include "rewrite/rewriteHandler.h"
50 51
#include "storage/ipc.h"
#include "storage/proc.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 "utils/guc.h"
57
#include "utils/memutils.h"
M
 
Marc G. Fournier 已提交
58
#include "utils/ps_status.h"
B
Bruce Momjian 已提交
59
#include "mb/pg_wchar.h"
60

61
#include "pgstat.h"
M
 
Marc G. Fournier 已提交
62

63

64
/* ----------------
65
 *		global variables
66 67
 * ----------------
 */
68

B
Bruce Momjian 已提交
69
extern int	optind;
70 71
extern char *optarg;

72
char	   *debug_query_string; /* used by pgmonitor */
73

74
/* Note: whereToSendOutput is initialized for the bootstrap/standalone case */
75
CommandDest whereToSendOutput = Debug;
76

77 78
extern int StatementTimeout;

B
Bruce Momjian 已提交
79
static bool dontExecute = false;
80

81
/* note: these declarations had better match tcopprot.h */
82
sigjmp_buf	Warn_restart;
83

84
bool		Warn_restart_ready = false;
85
bool		InError = false;
86

87
static bool EchoQuery = false;	/* default don't echo */
88

89 90 91 92 93 94 95
/*
 * Flag to mark SIGHUP. Whenever the main loop comes around it
 * will reread the configuration file. (Better than doing the
 * reading in the signal handler, ey?)
 */
static volatile bool got_SIGHUP = false;

96
/* ----------------
97 98
 *		people who want to use EOF should #define DONTUSENEWLINE in
 *		tcop/tcopdebug.h
99 100 101
 * ----------------
 */
#ifndef TCOP_DONTUSENEWLINE
102
int			UseNewLine = 1;		/* Use newlines query delimiters (the
103 104
								 * default) */

105
#else
106
int			UseNewLine = 0;		/* Use EOF as query delimiters */
107
#endif   /* TCOP_DONTUSENEWLINE */
108 109 110 111

/*
** Flags for expensive function optimization -- JMH 3/9/92
*/
112
int			XfuncMode = 0;
113 114

/* ----------------------------------------------------------------
115
 *		decls for routines only used in this file
116 117
 * ----------------------------------------------------------------
 */
118 119 120
static int	InteractiveBackend(StringInfo inBuf);
static int	SocketBackend(StringInfo inBuf);
static int	ReadCommand(StringInfo inBuf);
121
static List *pg_parse_query(StringInfo query_string, Oid *typev, int nargs);
122 123 124
static List *pg_analyze_and_rewrite(Node *parsetree);
static void start_xact_command(void);
static void finish_xact_command(void);
125 126
static void SigHupHandler(SIGNAL_ARGS);
static void FloatExceptionHandler(SIGNAL_ARGS);
127
static const char *CreateCommandTag(Node *parsetree);
128 129 130


/* ----------------------------------------------------------------
131
 *		routines to obtain user input
132 133 134 135
 * ----------------------------------------------------------------
 */

/* ----------------
136 137
 *	InteractiveBackend() is called for user interactive connections
 *	the string entered by the user is placed in its parameter inBuf.
138
 *
139
 *	EOF is returned if end-of-file input is seen; time to shut down.
140 141 142
 * ----------------
 */

143
static int
144
InteractiveBackend(StringInfo inBuf)
145
{
146 147 148
	int			c;				/* character read from getc() */
	bool		end = false;	/* end-of-input flag */
	bool		backslashSeen = false;	/* have we seen a \ ? */
149

150 151
	/*
	 * display a prompt and obtain input from the user
152
	 */
153
	printf("backend> ");
154
	fflush(stdout);
155

156 157 158 159
	/* Reset inBuf to empty */
	inBuf->len = 0;
	inBuf->data[0] = '\0';

160 161 162 163
	for (;;)
	{
		if (UseNewLine)
		{
164 165 166
			/*
			 * if we are using \n as a delimiter, then read characters
			 * until the \n.
167 168 169 170 171 172 173
			 */
			while ((c = getc(stdin)) != EOF)
			{
				if (c == '\n')
				{
					if (backslashSeen)
					{
174 175 176
						/* discard backslash from inBuf */
						inBuf->data[--inBuf->len] = '\0';
						backslashSeen = false;
177 178 179 180 181
						continue;
					}
					else
					{
						/* keep the newline character */
182
						appendStringInfoChar(inBuf, '\n');
183 184 185 186 187 188 189 190
						break;
					}
				}
				else if (c == '\\')
					backslashSeen = true;
				else
					backslashSeen = false;

191
				appendStringInfoChar(inBuf, (char) c);
192 193 194 195 196 197 198
			}

			if (c == EOF)
				end = true;
		}
		else
		{
199 200
			/*
			 * otherwise read characters until EOF.
201 202
			 */
			while ((c = getc(stdin)) != EOF)
203
				appendStringInfoChar(inBuf, (char) c);
204

205
			if (inBuf->len == 0)
206 207 208 209
				end = true;
		}

		if (end)
210
			return EOF;
211

212 213
		/*
		 * otherwise we have a user query so process it.
214 215 216 217
		 */
		break;
	}

218 219
	/*
	 * if the query echo flag was given, print the query..
220 221
	 */
	if (EchoQuery)
222
		printf("statement: %s\n", inBuf->data);
223
	fflush(stdout);
224

225
	return 'Q';
226 227 228
}

/* ----------------
229
 *	SocketBackend()		Is called for frontend-backend connections
230
 *
231 232
 *	If the input is a query (case 'Q') then the string entered by
 *	the user is placed in its parameter inBuf.
233
 *
234
 *	If the input is a fastpath function call (case 'F') then
235
 *	the function call is processed in HandleFunctionRequest()
236 237
 *	(now called from PostgresMain()).
 *
238
 *	EOF is returned if the connection is lost.
239 240 241
 * ----------------
 */

242
static int
243
SocketBackend(StringInfo inBuf)
244
{
245
	int			qtype;
246

247 248
	/*
	 * get input from the frontend
249
	 */
250
	qtype = pq_getbyte();
251

252
	switch (qtype)
253
	{
254 255 256 257
		case EOF:
			/* frontend disconnected */
			break;

258 259
			/*
			 * 'Q': user entered a query
260 261
			 */
		case 'Q':
262
			if (pq_getstr(inBuf))
263
				return EOF;
264
			break;
265

266 267
			/*
			 * 'F':  calling user/system functions
268 269
			 */
		case 'F':
270
			if (pq_getstr(inBuf))
271
				return EOF;		/* ignore "string" at start of F message */
272
			break;
273

274 275
			/*
			 * 'X':  frontend is exiting
276 277 278
			 */
		case 'X':
			break;
279

280 281
			/*
			 * otherwise we got garbage from the frontend.
282
			 *
283 284
			 * XXX are we certain that we want to do an elog(FATAL) here?
			 * -cim 1/24/90
285 286
			 */
		default:
287
			elog(FATAL, "Socket command type %c unknown", qtype);
288
			break;
289
	}
290 291

	return qtype;
292 293 294
}

/* ----------------
295 296 297
 *		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
298
 *		call.  EOF is returned if end of file.
299 300
 * ----------------
 */
301
static int
302
ReadCommand(StringInfo inBuf)
303
{
304
	int			result;
305

306
	if (IsUnderPostmaster)
307
		result = SocketBackend(inBuf);
308
	else
309 310
		result = InteractiveBackend(inBuf);
	return result;
311 312
}

313 314 315 316 317 318

/*
 * Parse a query string and pass it through the rewriter.
 *
 * A list of Query nodes is returned, since the string might contain
 * multiple queries and/or the rewriter might expand one query to several.
319 320 321
 *
 * NOTE: this routine is no longer used for processing interactive queries,
 * but it is still needed for parsing of SQL function bodies.
322
 */
323
List *
B
Bruce Momjian 已提交
324
pg_parse_and_rewrite(char *query_string,		/* string to execute */
325
					 Oid *typev,	/* parameter types */
B
Bruce Momjian 已提交
326
					 int nargs) /* number of parameters */
327
{
328
	List	   *raw_parsetree_list;
329
	List	   *querytree_list;
330
	List	   *list_item;
331 332 333 334
	StringInfoData stri;

	initStringInfo(&stri);
	appendStringInfo(&stri, "%s", query_string);
335

336 337
	/*
	 * (1) parse the request string into a list of raw parse trees.
338
	 */
339
	raw_parsetree_list = pg_parse_query(&stri, typev, nargs);
340

341 342
	/*
	 * (2) Do parse analysis and rule rewrite.
343 344 345 346
	 */
	querytree_list = NIL;
	foreach(list_item, raw_parsetree_list)
	{
B
Bruce Momjian 已提交
347
		Node	   *parsetree = (Node *) lfirst(list_item);
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369

		querytree_list = nconc(querytree_list,
							   pg_analyze_and_rewrite(parsetree));
	}

	return querytree_list;
}

/*
 * Do raw parsing (only).
 *
 * A list of parsetrees is returned, since there might be multiple
 * commands in the given string.
 *
 * NOTE: for interactive queries, it is important to keep this routine
 * separate from the analysis & rewrite stages.  Analysis and rewriting
 * cannot be done in an aborted transaction, since they require access to
 * database tables.  So, we rely on the raw parser to determine whether
 * we've seen a COMMIT or ABORT command; when we are in abort state, other
 * commands are not processed any further than the raw parse stage.
 */
static List *
370
pg_parse_query(StringInfo query_string, Oid *typev, int nargs)
371 372
{
	List	   *raw_parsetree_list;
373

374
	if (Log_statement)
375
		elog(LOG, "query: %s", query_string->data);
376

377 378 379 380 381 382
	if (Show_parser_stats)
		ResetUsage();

	raw_parsetree_list = parser(query_string, typev, nargs);

	if (Show_parser_stats)
383
		ShowUsage("PARSER STATISTICS");
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404

	return raw_parsetree_list;
}

/*
 * Given a raw parsetree (gram.y output), perform parse analysis and
 * rule rewriting.
 *
 * A list of Query nodes is returned, since either the analyzer or the
 * rewriter might expand one query to several.
 *
 * NOTE: for reasons mentioned above, this must be separate from raw parsing.
 */
static List *
pg_analyze_and_rewrite(Node *parsetree)
{
	List	   *querytree_list;
	List	   *list_item;
	Query	   *querytree;
	List	   *new_list;

405 406
	/*
	 * (1) Perform parse analysis.
407
	 */
408
	if (Show_parser_stats)
409 410
		ResetUsage();

411
	querytree_list = parse_analyze(parsetree, NULL);
412

413
	if (Show_parser_stats)
414
	{
415
		ShowUsage("PARSE ANALYSIS STATISTICS");
416
		ResetUsage();
417 418
	}

419 420
	/*
	 * (2) Rewrite the queries, as necessary
421
	 *
422 423
	 * rewritten queries are collected in new_list.  Note there may be more
	 * or fewer than in the original list.
424
	 */
425
	new_list = NIL;
426
	foreach(list_item, querytree_list)
427
	{
428
		querytree = (Query *) lfirst(list_item);
429

430
		if (Debug_print_parse)
431 432
			elog_node_display(LOG, "parse tree", querytree,
							  Debug_pretty_print);
433 434 435

		if (querytree->commandType == CMD_UTILITY)
		{
436 437
			/* don't rewrite utilities, just dump 'em into new_list */
			new_list = lappend(new_list, querytree);
438
		}
439
		else
440
		{
441
			/* rewrite regular queries */
442 443
			List	   *rewritten = QueryRewrite(querytree);

444
			new_list = nconc(new_list, rewritten);
445 446 447 448 449
		}
	}

	querytree_list = new_list;

450
	if (Show_parser_stats)
451
		ShowUsage("REWRITER STATISTICS");
452

453
#ifdef COPY_PARSE_PLAN_TREES
B
Bruce Momjian 已提交
454 455 456 457 458

	/*
	 * Optional debugging check: pass querytree output through
	 * copyObject()
	 */
459 460
	new_list = (List *) copyObject(querytree_list);
	/* This checks both copyObject() and the equal() routines... */
B
Bruce Momjian 已提交
461
	if (!equal(new_list, querytree_list))
B
Bruce Momjian 已提交
462
		elog(WARNING, "pg_analyze_and_rewrite: copyObject failed on parse tree");
463 464
	else
		querytree_list = new_list;
465 466
#endif

467
	if (Debug_print_rewritten)
468 469
		elog_node_display(LOG, "rewritten parse tree", querytree_list,
						  Debug_pretty_print);
470

471 472
	return querytree_list;
}
473 474


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

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

485
	if (Show_planner_stats)
486
		ResetUsage();
487

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

491
	if (Show_planner_stats)
492
		ShowUsage("PLANNER STATISTICS");
493

494 495 496
#ifdef COPY_PARSE_PLAN_TREES
	/* Optional debugging check: pass plan output through copyObject() */
	{
B
Bruce Momjian 已提交
497
		Plan	   *new_plan = (Plan *) copyObject(plan);
498

B
Bruce Momjian 已提交
499 500
		/*
		 * equal() currently does not have routines to compare Plan nodes,
501 502 503 504
		 * so don't try to test equality here.  Perhaps fix someday?
		 */
#ifdef NOT_USED
		/* This checks both copyObject() and the equal() routines... */
B
Bruce Momjian 已提交
505
		if (!equal(new_plan, plan))
B
Bruce Momjian 已提交
506
			elog(WARNING, "pg_plan_query: copyObject failed on plan tree");
507 508 509 510 511 512
		else
#endif
			plan = new_plan;
	}
#endif

513 514
	/*
	 * Print plan if debugging.
515
	 */
516
	if (Debug_print_plan)
517
		elog_node_display(LOG, "plan", plan, Debug_pretty_print);
518

519
	return plan;
520 521
}

522

523
/* ----------------------------------------------------------------
524
 *		pg_exec_query_string()
525 526
 *
 *		Takes a querystring, runs the parser/utilities or
527 528 529 530
 *		parser/planner/executor over it as necessary.
 *
 * Assumptions:
 *
531
 * At call, we are not inside a transaction command.
532
 *
533
 * The CurrentMemoryContext after starting a transaction command must be
534
 * appropriate for execution of individual queries (typically this will be
B
Bruce Momjian 已提交
535
 * TransactionCommandContext).	Note that this routine resets that context
536 537
 * after each individual query, so don't store anything there that
 * must outlive the call!
538
 *
539 540
 * parse_context references a context suitable for holding the
 * parse/rewrite trees (typically this will be QueryContext).
541
 * This context *must* be longer-lived than the transaction context!
542 543 544 545 546 547 548
 * In fact, if the query string might contain BEGIN/COMMIT commands,
 * parse_context had better outlive TopTransactionContext!
 *
 * We could have hard-wired knowledge about QueryContext and
 * TransactionCommandContext into this routine, but it seems better
 * not to, in case callers from outside this module need to use some
 * other contexts.
549 550 551 552 553
 *
 * ----------------------------------------------------------------
 */

void
554
pg_exec_query_string(StringInfo query_string,		/* string to execute */
B
Bruce Momjian 已提交
555 556 557
					 CommandDest dest,	/* where results should go */
					 MemoryContext parse_context)		/* context for
														 * parsetrees */
558
{
559
	bool		xact_started;
560
	MemoryContext oldcontext;
561 562
	List	   *parsetree_list,
			   *parsetree_item;
563 564 565 566
	struct timezone tz;
	struct timeval start_t, stop_t;
	bool		save_Log_duration = Log_duration;
	
567
	debug_query_string = query_string->data;	/* used by pgmonitor */
568

569 570 571 572 573 574 575
	/*
	 *	We use save_Log_duration so setting Log_duration to true doesn't
	 * 	report incorrect time because gettimeofday() wasn't called.
	 */
	if (save_Log_duration)
		gettimeofday(&start_t, &tz);

576
	/*
B
Bruce Momjian 已提交
577 578 579 580 581
	 * Start up a transaction command.	All queries generated by the
	 * query_string will be in this same command block, *unless* we find a
	 * BEGIN/COMMIT/ABORT statement; we have to force a new xact command
	 * after one of those, else bad things will happen in xact.c. (Note
	 * that this will possibly change current memory context.)
582 583 584 585
	 */
	start_xact_command();
	xact_started = true;

586 587 588
	if (StatementTimeout)
		enable_sig_alarm(StatementTimeout, true);

589
	/*
B
Bruce Momjian 已提交
590 591 592 593 594
	 * parse_context *must* be different from the execution memory
	 * context, else the context reset at the bottom of the loop will
	 * destroy the parsetree list.	(We really ought to check that
	 * parse_context isn't a child of CurrentMemoryContext either, but
	 * that would take more cycles than it's likely to be worth.)
595 596 597
	 */
	Assert(parse_context != CurrentMemoryContext);

598 599 600 601
	/*
	 * Switch to appropriate context for constructing parsetrees.
	 */
	oldcontext = MemoryContextSwitchTo(parse_context);
602

B
Bruce Momjian 已提交
603
	/*
B
Bruce Momjian 已提交
604 605
	 * Do basic parsing of the query or queries (this should be safe even
	 * if we are in aborted transaction state!)
606
	 */
607
	parsetree_list = pg_parse_query(query_string, NULL, 0);
608

609
	/*
610
	 * Switch back to execution context to enter the loop.
611 612 613 614
	 */
	MemoryContextSwitchTo(oldcontext);

	/*
615
	 * Run through the parsetree(s) and process each one.
616
	 */
617
	foreach(parsetree_item, parsetree_list)
618
	{
B
Bruce Momjian 已提交
619 620
		Node	   *parsetree = (Node *) lfirst(parsetree_item);
		bool		isTransactionStmt;
621 622
		const char *commandTag;
		char		completionTag[COMPLETION_TAG_BUFSIZE];
B
Bruce Momjian 已提交
623 624
		List	   *querytree_list,
				   *querytree_item;
625

626 627
		/* Transaction control statements need some special handling */
		isTransactionStmt = IsA(parsetree, TransactionStmt);
628

629 630 631 632 633 634 635 636 637 638 639 640
		/*
		 * First we set the command-completion tag to the main query
		 * (as opposed to each of the others that may be generated by
		 * analyze and rewrite).  Also set ps_status and do any special
		 * start-of-SQL-command processing needed by the destination.
		 */
		commandTag = CreateCommandTag(parsetree);

		set_ps_display(commandTag);

		BeginCommand(commandTag, dest);

641 642 643 644
		/*
		 * If we are in an aborted transaction, ignore all commands except
		 * COMMIT/ABORT.  It is important that this test occur before we
		 * try to do parse analysis, rewrite, or planning, since all those
B
Bruce Momjian 已提交
645 646 647
		 * phases try to do database accesses, which may fail in abort
		 * state. (It might be safe to allow some additional utility
		 * commands in this state, but not many...)
648 649
		 */
		if (IsAbortedTransactionBlockState())
650
		{
B
Bruce Momjian 已提交
651
			bool		allowit = false;
652

653 654 655 656
			if (isTransactionStmt)
			{
				TransactionStmt *stmt = (TransactionStmt *) parsetree;

657 658
				if (stmt->command == COMMIT || stmt->command == ROLLBACK)
					allowit = true;
659
			}
660

B
Bruce Momjian 已提交
661
			if (!allowit)
662
				elog(ERROR, "current transaction is aborted, "
663
					 "queries ignored until end of transaction block");
664
		}
665

666
		/* Make sure we are in a transaction command */
B
Bruce Momjian 已提交
667
		if (!xact_started)
668 669 670 671
		{
			start_xact_command();
			xact_started = true;
		}
672

673
		/* If we got a cancel signal in parsing or prior command, quit */
674
		CHECK_FOR_INTERRUPTS();
675 676 677

		/*
		 * OK to analyze and rewrite this query.
678
		 *
B
Bruce Momjian 已提交
679 680
		 * Switch to appropriate context for constructing querytrees (again,
		 * these must outlive the execution context).
681 682
		 */
		oldcontext = MemoryContextSwitchTo(parse_context);
683

684
		querytree_list = pg_analyze_and_rewrite(parsetree);
V
Vadim B. Mikheev 已提交
685

686 687 688 689 690 691 692 693 694 695 696 697
		/*
		 * Switch back to execution context for planning and execution.
		 */
		MemoryContextSwitchTo(oldcontext);

		/*
		 * Inner loop handles the individual queries generated from a
		 * single parsetree by analysis and rewrite.
		 */
		foreach(querytree_item, querytree_list)
		{
			Query	   *querytree = (Query *) lfirst(querytree_item);
698

699
			/* Make sure we are in a transaction command */
B
Bruce Momjian 已提交
700
			if (!xact_started)
701
			{
702 703 704 705
				start_xact_command();
				xact_started = true;
			}

B
Bruce Momjian 已提交
706 707 708 709
			/*
			 * If we got a cancel signal in analysis or prior command,
			 * quit
			 */
710
			CHECK_FOR_INTERRUPTS();
711 712 713

			if (querytree->commandType == CMD_UTILITY)
			{
714 715
				/*
				 * process utility functions (create, destroy, etc..)
716
				 */
717
				elog(DEBUG2, "ProcessUtility");
718

719 720 721 722 723 724 725 726 727 728 729 730 731
				if (querytree->originalQuery)
				{
					/* utility statement can override default tag string */
					ProcessUtility(querytree->utilityStmt, dest,
								   completionTag);
					if (completionTag[0])
						commandTag = completionTag;
				}
				else
				{
					/* utility added by rewrite cannot override tag */
					ProcessUtility(querytree->utilityStmt, dest, NULL);
				}
732 733 734
			}
			else
			{
735 736
				/*
				 * process a plannable query.
737 738 739 740 741 742
				 */
				Plan	   *plan;

				plan = pg_plan_query(querytree);

				/* if we got a cancel signal whilst planning, quit */
743
				CHECK_FOR_INTERRUPTS();
744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760

				/* Initialize snapshot state for query */
				SetQuerySnapshot();

				/*
				 * execute the plan
				 */
				if (Show_executor_stats)
					ResetUsage();

				if (dontExecute)
				{
					/* don't execute it, just show the query plan */
					print_plan(plan, querytree);
				}
				else
				{
761
					elog(DEBUG2, "ProcessQuery");
762

H
Hiroshi Inoue 已提交
763
					if (querytree->originalQuery || length(querytree_list) == 1)
764 765 766 767 768 769 770 771 772 773
					{
						/* original stmt can override default tag string */
						ProcessQuery(querytree, plan, dest, completionTag);
						commandTag = completionTag;
					}
					else
					{
						/* stmt added by rewrite cannot override tag */
						ProcessQuery(querytree, plan, dest, NULL);
					}
774 775 776
				}

				if (Show_executor_stats)
777
					ShowUsage("EXECUTOR STATISTICS");
778
			}
779

780 781 782
			/*
			 * In a query block, we want to increment the command counter
			 * between queries so that the effects of early queries are
B
Bruce Momjian 已提交
783 784
			 * visible to subsequent ones.	In particular we'd better do
			 * so before checking constraints.
785 786 787 788 789
			 */
			if (!isTransactionStmt)
				CommandCounterIncrement();

			/*
B
Bruce Momjian 已提交
790 791
			 * Clear the execution context to recover temporary memory
			 * used by the query.  NOTE: if query string contains
792
			 * BEGIN/COMMIT transaction commands, execution context may
B
Bruce Momjian 已提交
793 794
			 * now be different from what we were originally passed; so be
			 * careful to clear current context not "oldcontext".
795 796 797 798 799 800
			 */
			Assert(parse_context != CurrentMemoryContext);

			MemoryContextResetAndDeleteChildren(CurrentMemoryContext);

			/*
B
Bruce Momjian 已提交
801 802 803
			 * If this was a transaction control statement, commit it and
			 * arrange to start a new xact command for the next command
			 * (if any).
804 805
			 */
			if (isTransactionStmt)
806
			{
807 808
				finish_xact_command();
				xact_started = false;
809
			}
810
		} /* end loop over queries generated from a parsetree */
811

812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827
		/*
		 * If this is the last parsetree of the query string, close down
		 * transaction statement before reporting command-complete.  This is
		 * so that any end-of-transaction errors are reported before the
		 * command-complete message is issued, to avoid confusing clients
		 * who will expect either a command-complete message or an error,
		 * not one and then the other.  But for compatibility with
		 * historical Postgres behavior, we do not force a transaction
		 * boundary between queries appearing in a single query string.
		 */
		if (lnext(parsetree_item) == NIL && xact_started)
		{
			finish_xact_command();
			xact_started = false;
		}

828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846
		/*
		 * It is possible that the original query was removed due to
		 * a DO INSTEAD rewrite rule.  In that case we will still have
		 * the default completion tag, which is fine for most purposes,
		 * but it may confuse clients if it's INSERT/UPDATE/DELETE.
		 * Clients expect those tags to have counts after them (cf.
		 * ProcessQuery).
		 */
		if (strcmp(commandTag, "INSERT") == 0)
			commandTag = "INSERT 0 0";
		else if (strcmp(commandTag, "UPDATE") == 0)
			commandTag = "UPDATE 0";
		else if (strcmp(commandTag, "DELETE") == 0)
			commandTag = "DELETE 0";

		/*
		 * Tell client that we're done with this query.  Note we emit
		 * exactly one EndCommand report for each raw parsetree, thus
		 * one for each SQL command the client sent, regardless of
847 848
		 * rewriting.  (But a command aborted by error will not send
		 * an EndCommand report at all.)
849 850
		 */
		EndCommand(commandTag, dest);
B
Bruce Momjian 已提交
851
	}							/* end loop over parsetrees */
852

853 854
	disable_sig_alarm(true);

855 856
	/*
	 * Close down transaction statement, if one is open.
857
	 * (Note that this will only happen if the querystring was empty.)
858 859 860
	 */
	if (xact_started)
		finish_xact_command();
861

862 863 864 865 866 867 868 869 870 871 872 873 874
	if (save_Log_duration)
	{
		gettimeofday(&stop_t, &tz);
		if (stop_t.tv_usec < start_t.tv_usec)
		{
			stop_t.tv_sec--;
			stop_t.tv_usec += 1000000;
		}
		elog(LOG, "duration: %ld.%06ld sec",
			(long int) stop_t.tv_sec - start_t.tv_sec,
			(long int) stop_t.tv_usec - start_t.tv_usec);
	}
		
875
	debug_query_string = NULL;	/* used by pgmonitor */
876 877
}

878 879 880 881 882 883
/*
 * Convenience routines for starting/committing a single command.
 */
static void
start_xact_command(void)
{
884
	elog(DEBUG1, "StartTransactionCommand");
885
	StartTransactionCommand(false);
886 887 888 889 890
}

static void
finish_xact_command(void)
{
891 892 893 894
	/* Invoke IMMEDIATE constraint triggers */
	DeferredTriggerEndQuery();

	/* Now commit the command */
895
	elog(DEBUG1, "CommitTransactionCommand");
896

897
	CommitTransactionCommand(false);
898

899
#ifdef SHOW_MEMORY_STATS
900
	/* Print mem stats at each commit for leak tracking */
901 902 903 904 905 906
	if (ShowStats)
		MemoryContextStats(TopMemoryContext);
#endif
}


907
/* --------------------------------
908
 *		signal handler routines used in PostgresMain()
909 910 911
 * --------------------------------
 */

912
/*
T
Tom Lane 已提交
913
 * quickdie() occurs when signalled SIGQUIT by the postmaster.
914 915 916 917
 *
 * Some backend has bought the farm,
 * so we need to stop what we're doing and exit.
 */
T
Tom Lane 已提交
918
void
919
quickdie(SIGNAL_ARGS)
920
{
921
	PG_SETMASK(&BlockSig);
B
Bruce Momjian 已提交
922
	elog(WARNING, "Message from PostgreSQL backend:"
923
		 "\n\tThe Postmaster has informed me that some other backend"
924
		 "\n\tdied abnormally and possibly corrupted shared memory."
925
		 "\n\tI have rolled back the current transaction and am"
926
	   "\n\tgoing to terminate your database system connection and exit."
927
	"\n\tPlease reconnect to the database system and repeat your query.");
928

929
	/*
930 931 932 933
	 * DO NOT proc_exit() -- we're here because shared memory may be
	 * corrupted, so we don't want to try to clean up our transaction.
	 * Just nail the windows shut and get out of town.
	 *
B
Bruce Momjian 已提交
934 935 936 937
	 * Note we do exit(1) not exit(0).	This is to force the postmaster into
	 * a system reset cycle if some idiot DBA sends a manual SIGQUIT to a
	 * random backend.	This is necessary precisely because we don't clean
	 * up our shared memory state.
938 939
	 */

940
	exit(1);
941 942
}

943
/*
944 945
 * Shutdown signal from postmaster: abort transaction and exit
 * at soonest convenient time
946
 */
947
void
948
die(SIGNAL_ARGS)
949
{
950 951 952
	int			save_errno = errno;

	/* Don't joggle the elbow of proc_exit */
B
Bruce Momjian 已提交
953
	if (!proc_exit_inprogress)
954
	{
955
		InterruptPending = true;
956
		ProcDiePending = true;
B
Bruce Momjian 已提交
957

958
		/*
B
Bruce Momjian 已提交
959 960
		 * If it's safe to interrupt, and we're waiting for input or a
		 * lock, service the interrupt immediately
961
		 */
962 963
		if (ImmediateInterruptOK && InterruptHoldoffCount == 0 &&
			CritSectionCount == 0)
964
		{
965 966 967
			/* bump holdoff count to make ProcessInterrupts() a no-op */
			/* until we are done getting ready for it */
			InterruptHoldoffCount++;
968
			DisableNotifyInterrupt();
969 970
			/* Make sure HandleDeadLock won't run while shutting down... */
			LockWaitCancel();
971
			InterruptHoldoffCount--;
972 973
			ProcessInterrupts();
		}
974
	}
975 976

	errno = save_errno;
977 978
}

979
/*
980
 * Timeout or shutdown signal from postmaster during client authentication.
981
 * Simply exit(0).
982 983 984
 *
 * XXX: possible future improvement: try to send a message indicating
 * why we are disconnecting.  Problem is to be sure we don't block while
985
 * doing so, nor mess up the authentication message exchange.
986 987 988 989 990 991 992
 */
void
authdie(SIGNAL_ARGS)
{
	exit(0);
}

993
/*
994 995
 * Query-cancel signal from postmaster: abort current transaction
 * at soonest convenient time
996
 */
997
static void
998
StatementCancelHandler(SIGNAL_ARGS)
999
{
1000 1001
	int			save_errno = errno;

B
Bruce Momjian 已提交
1002 1003 1004 1005
	/*
	 * Don't joggle the elbow of proc_exit, nor an already-in-progress
	 * abort
	 */
1006
	if (!proc_exit_inprogress && !InError)
1007
	{
1008 1009
		InterruptPending = true;
		QueryCancelPending = true;
B
Bruce Momjian 已提交
1010

1011
		/*
1012
		 * If it's safe to interrupt, and we're waiting for a lock,
B
Bruce Momjian 已提交
1013 1014
		 * service the interrupt immediately.  No point in interrupting if
		 * we're waiting for input, however.
1015
		 */
1016
		if (ImmediateInterruptOK && InterruptHoldoffCount == 0 &&
1017
			CritSectionCount == 0)
1018
		{
1019 1020 1021 1022 1023 1024
			/* bump holdoff count to make ProcessInterrupts() a no-op */
			/* until we are done getting ready for it */
			InterruptHoldoffCount++;
			if (LockWaitCancel())
			{
				DisableNotifyInterrupt();
T
Tom Lane 已提交
1025
				InterruptHoldoffCount--;
1026 1027 1028 1029
				ProcessInterrupts();
			}
			else
				InterruptHoldoffCount--;
1030
		}
1031 1032
	}

1033
	errno = save_errno;
1034 1035
}

1036 1037 1038 1039 1040 1041 1042 1043 1044
/* signal handler for floating point exception */
static void
FloatExceptionHandler(SIGNAL_ARGS)
{
	elog(ERROR, "floating point exception!"
		 " The last floating point operation either exceeded legal ranges"
		 " or was a divide by zero");
}

1045
/* SIGHUP: set flag to re-read config file at next convenient time */
1046
static void
1047
SigHupHandler(SIGNAL_ARGS)
1048
{
1049
	got_SIGHUP = true;
1050 1051
}

1052

1053 1054 1055 1056 1057 1058 1059 1060 1061 1062
/*
 * ProcessInterrupts: out-of-line portion of CHECK_FOR_INTERRUPTS() macro
 *
 * If an interrupt condition is pending, and it's safe to service it,
 * then clear the flag and accept the interrupt.  Called only when
 * InterruptPending is true.
 */
void
ProcessInterrupts(void)
{
1063 1064
	/* OK to accept interrupt now? */
	if (InterruptHoldoffCount != 0 || CritSectionCount != 0)
1065 1066 1067 1068 1069
		return;
	InterruptPending = false;
	if (ProcDiePending)
	{
		ProcDiePending = false;
B
Bruce Momjian 已提交
1070 1071
		QueryCancelPending = false;		/* ProcDie trumps QueryCancel */
		ImmediateInterruptOK = false;	/* not idle anymore */
B
Bruce Momjian 已提交
1072
		elog(FATAL, "This connection has been terminated by the administrator.");
1073 1074 1075 1076
	}
	if (QueryCancelPending)
	{
		QueryCancelPending = false;
B
Bruce Momjian 已提交
1077
		ImmediateInterruptOK = false;	/* not idle anymore */
1078 1079 1080 1081 1082
		elog(ERROR, "Query was cancelled.");
	}
	/* If we get here, do nothing (probably, QueryCancelPending was reset) */
}

1083

1084 1085
static void
usage(char *progname)
1086
{
1087 1088 1089 1090
	printf("%s is the PostgreSQL stand-alone backend.  It is not\nintended to be used by normal users.\n\n", progname);

	printf("Usage:\n  %s [options...] [dbname]\n\n", progname);
	printf("Options:\n");
M
 
Marc G. Fournier 已提交
1091
#ifdef USE_ASSERT_CHECKING
1092
	printf("  -A 1|0          enable/disable run-time assert checking\n");
M
 
Marc G. Fournier 已提交
1093
#endif
1094 1095
	printf("  -B NBUFFERS     number of shared buffers (default %d)\n", DEF_NBUFFERS);
	printf("  -c NAME=VALUE   set run-time parameter\n");
1096
	printf("  -d 1-5,0        debugging level (0 is off)\n");
1097 1098 1099 1100 1101 1102
	printf("  -D DATADIR      database directory\n");
	printf("  -e              use European date format\n");
	printf("  -E              echo query before execution\n");
	printf("  -F              turn fsync off\n");
	printf("  -N              do not use newline as interactive query delimiter\n");
	printf("  -o FILENAME     send stdout and stderr to given file\n");
B
Bruce Momjian 已提交
1103
	printf("  -P              disable system indexes\n");
1104 1105 1106 1107 1108 1109 1110 1111 1112
	printf("  -s              show statistics after each query\n");
	printf("  -S SORT-MEM     set amount of memory for sorts (in kbytes)\n");
	printf("Developer options:\n");
	printf("  -f [s|i|n|m|h]  forbid use of some plan types\n");
	printf("  -i              do not execute queries\n");
	printf("  -O              allow system table structure changes\n");
	printf("  -t [pa|pl|ex]   show timings after each query\n");
	printf("  -W NUM          wait NUM seconds to allow attach from a debugger\n");
	printf("\nReport bugs to <pgsql-bugs@postgresql.org>.\n");
1113 1114
}

1115 1116


1117
/* ----------------------------------------------------------------
1118
 * PostgresMain
B
Bruce Momjian 已提交
1119
 *	   postgres main loop -- all backends, interactive or otherwise start here
1120
 *
1121 1122 1123 1124
 * 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.)
 * username is the (possibly authenticated) PostgreSQL user name to be used
 * for the session.
1125 1126 1127
 * ----------------------------------------------------------------
 */
int
1128
PostgresMain(int argc, char *argv[], const char *username)
1129
{
1130
	int			flag;
1131

B
Bruce Momjian 已提交
1132
	const char *DBName = NULL;
1133
	bool		secure;
1134
	int			errs = 0;
1135
	GucContext	ctx;
1136
	GucSource	gucsource;
1137
	char	   *tmp;
1138

1139
	int			firstchar;
1140
	StringInfo	parser_input;
M
 
Marc G. Fournier 已提交
1141

B
Bruce Momjian 已提交
1142
	char	   *potential_DataDir = NULL;
1143

1144
	/*
B
Bruce Momjian 已提交
1145 1146
	 * Catch standard options before doing much else.  This even works on
	 * systems without getopt_long.
1147 1148 1149
	 */
	if (!IsUnderPostmaster && argc > 1)
	{
B
Bruce Momjian 已提交
1150
		if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
1151 1152 1153 1154
		{
			usage(argv[0]);
			exit(0);
		}
B
Bruce Momjian 已提交
1155
		if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
1156 1157 1158 1159
		{
			puts("postgres (PostgreSQL) " PG_VERSION);
			exit(0);
		}
B
Bruce Momjian 已提交
1160
	}
1161

1162 1163 1164 1165 1166
	/*
	 * Fire up essential subsystems: error and memory management
	 *
	 * If we are running under the postmaster, this is done already.
	 */
1167
	if (!IsUnderPostmaster)
1168 1169 1170 1171
	{
		MemoryContextInit();
	}

1172 1173
	set_ps_display("startup");

1174 1175
	SetProcessingMode(InitProcessing);

1176
	/*
1177
	 * Set default values for command-line options.
1178
	 */
1179 1180
	Noversion = false;
	EchoQuery = false;
1181 1182 1183

	if (!IsUnderPostmaster)
	{
1184
		InitializeGUCOptions();
1185
		potential_DataDir = getenv("PGDATA");
1186
	}
1187

1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204
	/* ----------------
	 *	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.
	 * ----------------
	 */

1205 1206 1207
	/* all options are allowed until '-p' */
	secure = true;
	ctx = PGC_POSTMASTER;
1208
	gucsource = PGC_S_ARGV;		/* initial switches came from command line */
1209

1210
	while ((flag = getopt(argc, argv, "A:B:c:CD:d:Eef:FiNOPo:p:S:st:v:W:x:-:")) != -1)
1211 1212
		switch (flag)
		{
M
 
Marc G. Fournier 已提交
1213 1214
			case 'A':
#ifdef USE_ASSERT_CHECKING
1215
				SetConfigOption("debug_assertions", optarg, ctx, gucsource);
M
 
Marc G. Fournier 已提交
1216
#else
B
Bruce Momjian 已提交
1217
				elog(WARNING, "Assert checking is not compiled in");
M
 
Marc G. Fournier 已提交
1218 1219
#endif
				break;
1220

1221
			case 'B':
1222 1223 1224

				/*
				 * specify the size of buffer pool
1225
				 */
1226
				SetConfigOption("shared_buffers", optarg, ctx, gucsource);
1227
				break;
1228

1229
			case 'C':
1230 1231 1232

				/*
				 * don't print version string
1233
				 */
1234
				Noversion = true;
1235
				break;
1236

1237
			case 'D':			/* PGDATA directory */
1238
				if (secure)
1239
					potential_DataDir = optarg;
M
 
Marc G. Fournier 已提交
1240
				break;
1241

1242
			case 'd':			/* debug level */
1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258
				{
					/* Set server debugging level. */
					if (atoi(optarg) != 0)
					{
						char *debugstr = palloc(strlen("debug") + strlen(optarg) + 1);

						sprintf(debugstr, "debug%s", optarg);
						SetConfigOption("server_min_messages", debugstr, ctx, gucsource);
						pfree(debugstr);
						/*
						 * -d is not the same as setting client_min_messages
						 * because it enables other output options.
						 */
						if (atoi(optarg) >= 1)
							SetConfigOption("log_connections", "true", ctx, gucsource);
						if (atoi(optarg) >= 2)
1259
							SetConfigOption("log_statement", "true", ctx, gucsource);
1260 1261 1262 1263 1264 1265 1266 1267 1268 1269
						if (atoi(optarg) >= 3)
							SetConfigOption("debug_print_parse", "true", ctx, gucsource);
						if (atoi(optarg) >= 4)
							SetConfigOption("debug_print_plan", "true", ctx, gucsource);
						if (atoi(optarg) >= 5)
							SetConfigOption("debug_print_rewritten", "true", ctx, gucsource);
					}
					else
						/*
						 *	-d 0 allows user to prevent postmaster debug from
1270
						 *	propagating to backend.
1271
						 */
1272 1273
						SetConfigOption("server_min_messages", "notice",
										ctx, gucsource);
1274
				}
1275
				break;
1276 1277

			case 'E':
1278 1279 1280

				/*
				 * E - echo the query the user entered
1281
				 */
1282
				EchoQuery = true;
1283
				break;
1284 1285

			case 'e':
1286 1287

				/*
1288 1289
				 * Use european date formats.
				 */
1290
				SetConfigOption("datestyle", "euro", ctx, gucsource);
1291
				break;
1292 1293

			case 'F':
1294 1295 1296

				/*
				 * turn off fsync
1297
				 */
1298
				SetConfigOption("fsync", "false", ctx, gucsource);
1299
				break;
1300 1301

			case 'f':
1302 1303 1304

				/*
				 * f - forbid generation of certain plans
1305
				 */
1306
				tmp = NULL;
1307 1308 1309
				switch (optarg[0])
				{
					case 's':	/* seqscan */
1310
						tmp = "enable_seqscan";
1311 1312
						break;
					case 'i':	/* indexscan */
1313
						tmp = "enable_indexscan";
1314 1315
						break;
					case 't':	/* tidscan */
1316
						tmp = "enable_tidscan";
1317 1318
						break;
					case 'n':	/* nestloop */
1319
						tmp = "enable_nestloop";
1320 1321
						break;
					case 'm':	/* mergejoin */
1322
						tmp = "enable_mergejoin";
1323 1324
						break;
					case 'h':	/* hashjoin */
1325
						tmp = "enable_hashjoin";
1326 1327 1328 1329
						break;
					default:
						errs++;
				}
1330
				if (tmp)
1331
					SetConfigOption(tmp, "false", ctx, gucsource);
1332 1333
				break;

1334
			case 'i':
1335
				dontExecute = true;
1336
				break;
1337

1338
			case 'N':
1339 1340 1341

				/*
				 * N - Don't use newline as a query delimiter
1342 1343 1344
				 */
				UseNewLine = 0;
				break;
1345

1346
			case 'O':
1347 1348 1349

				/*
				 * allow system table structure modifications
1350
				 */
1351 1352
				if (secure)		/* XXX safe to allow from client??? */
					allowSystemTableMods = true;
1353 1354
				break;

H
Hiroshi Inoue 已提交
1355
			case 'P':
1356 1357 1358

				/*
				 * ignore system indexes
H
Hiroshi Inoue 已提交
1359 1360 1361 1362 1363
				 */
				if (secure)		/* XXX safe to allow from client??? */
					IgnoreSystemIndexes(true);
				break;

T
Tom Lane 已提交
1364
			case 'o':
1365 1366 1367

				/*
				 * o - send output (stdout and stderr) to the given file
T
Tom Lane 已提交
1368
				 */
1369 1370
				if (secure)
					StrNCpy(OutputFileName, optarg, MAXPGPATH);
T
Tom Lane 已提交
1371 1372
				break;

1373
			case 'p':
1374 1375 1376 1377

				/*
				 * p - special flag passed if backend was forked by a
				 * postmaster.
1378
				 */
1379 1380
				if (secure)
				{
1381
					DBName = strdup(optarg);
B
Bruce Momjian 已提交
1382 1383
					secure = false;		/* subsequent switches are NOT
										 * secure */
1384
					ctx = PGC_BACKEND;
1385
					gucsource = PGC_S_CLIENT;
1386
				}
1387
				break;
1388

1389
			case 'S':
1390 1391 1392

				/*
				 * S - amount of sort memory to use in 1k bytes
1393
				 */
1394
				SetConfigOption("sort_mem", optarg, ctx, gucsource);
1395
				break;
1396 1397

			case 's':
1398 1399 1400

				/*
				 * s - report usage statistics (timings) after each query
1401
				 */
1402
				SetConfigOption("show_statement_stats", "true", ctx, gucsource);
M
 
Marc G. Fournier 已提交
1403 1404
				break;

1405
			case 't':
1406
				/* ---------------
1407 1408 1409 1410 1411 1412 1413 1414 1415
				 *	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.
				 * ----------------
				 */
1416
				tmp = NULL;
1417 1418 1419 1420
				switch (optarg[0])
				{
					case 'p':
						if (optarg[1] == 'a')
1421
							tmp = "show_parser_stats";
1422
						else if (optarg[1] == 'l')
1423
							tmp = "show_planner_stats";
1424 1425 1426 1427
						else
							errs++;
						break;
					case 'e':
1428
						tmp = "show_executor_stats";
1429 1430 1431 1432 1433
						break;
					default:
						errs++;
						break;
				}
1434
				if (tmp)
1435
					SetConfigOption(tmp, "true", ctx, gucsource);
1436 1437
				break;

1438
			case 'v':
1439 1440
				if (secure)
					FrontendProtocol = (ProtocolVersion) atoi(optarg);
1441 1442
				break;

M
 
Marc G. Fournier 已提交
1443
			case 'W':
1444 1445 1446

				/*
				 * wait N seconds to allow attach from a debugger
M
 
Marc G. Fournier 已提交
1447 1448 1449 1450
				 */
				sleep(atoi(optarg));
				break;

1451
			case 'x':
B
Bruce Momjian 已提交
1452
#ifdef NOT_USED					/* planner/xfunc.h */
1453 1454 1455 1456 1457 1458 1459

				/*
				 * control joey hellerstein's expensive function
				 * optimization
				 */
				if (XfuncMode != 0)
				{
B
Bruce Momjian 已提交
1460
					elog(WARNING, "only one -x flag is allowed");
1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477
					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
				{
B
Bruce Momjian 已提交
1478
					elog(WARNING, "use -x {off,nor,nopull,nopm,pullall,wait}");
1479 1480
					errs++;
				}
1481
#endif
1482
				break;
1483

1484
			case 'c':
1485
			case '-':
1486
				{
B
Bruce Momjian 已提交
1487 1488
					char	   *name,
							   *value;
1489

B
Bruce Momjian 已提交
1490 1491 1492 1493 1494 1495 1496 1497 1498
					ParseLongOption(optarg, &name, &value);
					if (!value)
					{
						if (flag == '-')
							elog(ERROR, "--%s requires argument", optarg);
						else
							elog(ERROR, "-c %s requires argument", optarg);
					}

1499
					SetConfigOption(name, value, ctx, gucsource);
B
Bruce Momjian 已提交
1500 1501 1502 1503 1504
					free(name);
					if (value)
						free(value);
					break;
				}
1505

1506 1507
			default:
				errs++;
T
Tom Lane 已提交
1508
				break;
1509 1510
		}

1511 1512 1513
	/*
	 * Post-processing for command line options.
	 */
1514
	if (Show_statement_stats &&
1515
		(Show_parser_stats || Show_planner_stats || Show_executor_stats))
1516
	{
B
Bruce Momjian 已提交
1517
		elog(WARNING, "Query statistics are disabled because parser, planner, or executor statistics are on.");
1518
		SetConfigOption("show_statement_stats", "false", ctx, gucsource);
1519 1520
	}

1521
	if (!IsUnderPostmaster)
1522
	{
1523 1524 1525
		if (!potential_DataDir)
		{
			fprintf(stderr, "%s does not know where to find the database system "
1526 1527 1528
			   "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",
1529 1530 1531 1532
					argv[0]);
			proc_exit(1);
		}
		SetDataDir(potential_DataDir);
1533
	}
1534
	Assert(DataDir);
1535 1536

	/*
1537
	 * Set up signal handlers and masks.
1538
	 *
1539
	 * Note that postmaster blocked all signals before forking child process,
B
Bruce Momjian 已提交
1540 1541
	 * so there is no race condition whereby we might receive a signal
	 * before we have set up the handler.
T
Tom Lane 已提交
1542 1543
	 *
	 * Also note: it's best not to use any signals that are SIG_IGNored in
B
Bruce Momjian 已提交
1544
	 * the postmaster.	If such a signal arrives before we are able to
1545 1546 1547 1548
	 * change the handler to non-SIG_IGN, it'll get dropped.  Instead,
	 * make a dummy handler in the postmaster to reserve the signal.
	 * (Of course, this isn't an issue for signals that are locally generated,
	 * such as SIGALRM and SIGPIPE.)
1549
	 */
1550

1551
	pqsignal(SIGHUP, SigHupHandler);	/* set flag to read config file */
1552
	pqsignal(SIGINT, StatementCancelHandler);		/* cancel current query */
1553
	pqsignal(SIGTERM, die);		/* cancel current query and exit */
1554
	pqsignal(SIGQUIT, quickdie);	/* hard crash time */
1555
	pqsignal(SIGALRM, handle_sig_alarm);	/* check for deadlock after
B
Bruce Momjian 已提交
1556
										 * timeout */
1557 1558 1559 1560 1561

	/*
	 * 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
1562 1563 1564
	 * midst of output during who-knows-what operation...
	 */
	pqsignal(SIGPIPE, SIG_IGN);
B
Bruce Momjian 已提交
1565
	pqsignal(SIGUSR1, SIG_IGN); /* this signal available for use */
1566

1567
	pqsignal(SIGUSR2, Async_NotifyHandler);		/* flush also sinval cache */
1568
	pqsignal(SIGFPE, FloatExceptionHandler);
1569 1570

	/*
B
Bruce Momjian 已提交
1571 1572
	 * Reset some signals that are accepted by postmaster but not by
	 * backend
1573
	 */
1574 1575
	pqsignal(SIGCHLD, SIG_DFL); /* system() requires this on some
								 * platforms */
1576

1577 1578
	pqinitmask();

T
Tom Lane 已提交
1579
	/* We allow SIGQUIT (quickdie) at all times */
1580
#ifdef HAVE_SIGPROCMASK
T
Tom Lane 已提交
1581
	sigdelset(&BlockSig, SIGQUIT);
1582
#else
T
Tom Lane 已提交
1583
	BlockSig &= ~(sigmask(SIGQUIT));
1584 1585
#endif

T
Tom Lane 已提交
1586
	PG_SETMASK(&BlockSig);		/* block everything except SIGQUIT */
1587

1588

1589
	if (IsUnderPostmaster)
1590
	{
1591 1592 1593
		/* noninteractive case: nothing should be left after switches */
		if (errs || argc != optind || DBName == NULL)
		{
B
Bruce Momjian 已提交
1594
			elog(WARNING, "%s: invalid command line arguments\nTry -? for help.",
1595
				 argv[0]);
B
Bruce Momjian 已提交
1596 1597
			proc_exit(0);		/* not 1, that causes system-wide
								 * restart... */
1598
		}
1599
		BaseInit();
1600
	}
1601
	else
1602
	{
1603 1604 1605
		/* interactive case: database name can be last arg on command line */
		if (errs || argc - optind > 1)
		{
B
Bruce Momjian 已提交
1606
			elog(WARNING, "%s: invalid command line arguments\nTry -? for help.",
1607
				 argv[0]);
1608
			proc_exit(1);
1609 1610 1611
		}
		else if (argc - optind == 1)
			DBName = argv[optind];
1612
		else if ((DBName = username) == NULL)
1613
		{
B
Bruce Momjian 已提交
1614
			elog(WARNING, "%s: user name undefined and no database specified",
1615
				 argv[0]);
1616
			proc_exit(1);
1617
		}
1618

1619 1620 1621 1622 1623 1624 1625 1626
		/*
		 * On some systems our dynloader code needs the executable's
		 * pathname.  (If under postmaster, this was done already.)
		 */
		if (FindExec(pg_pathname, argv[0], "postgres") < 0)
			elog(FATAL, "%s: could not locate executable, bailing out...",
				 argv[0]);

1627
		/*
1628 1629
		 * Validate we have been given a reasonable-looking DataDir (if
		 * under postmaster, assume postmaster did this already).
1630 1631 1632
		 */
		ValidatePgVersion(DataDir);

1633
		/*
1634
		 * Create lockfile for data directory.
1635
		 */
B
Bruce Momjian 已提交
1636
		if (!CreateDataDirLockFile(DataDir, false))
1637
			proc_exit(1);
1638

1639
		XLOGPathInit();
1640
		BaseInit();
1641 1642 1643 1644 1645

		/*
		 * Start up xlog for standalone backend, and register to have it
		 * closed down at exit.
		 */
1646
		StartupXLOG();
1647
		on_shmem_exit(ShutdownXLOG, 0);
1648 1649
	}

1650 1651 1652 1653 1654 1655 1656 1657
	/*
	 * Set up additional info.
	 */

#ifdef CYR_RECODE
	SetCharSet();
#endif

1658
	/*
1659 1660 1661 1662 1663
	 * General initialization.
	 *
	 * NOTE: if you are tempted to add code in this vicinity, consider
	 * putting it inside InitPostgres() instead.  In particular, anything
	 * that involves database access should be there, not here.
1664
	 */
1665
	elog(DEBUG2, "InitPostgres");
1666
	InitPostgres(DBName, username);
1667

1668
	SetProcessingMode(NormalProcessing);
1669

1670 1671
	/*
	 * Send this backend's cancellation info to the frontend.
1672
	 */
M
 
Marc G. Fournier 已提交
1673 1674 1675
	if (whereToSendOutput == Remote &&
		PG_PROTOCOL_MAJOR(FrontendProtocol) >= 2)
	{
1676
		StringInfoData buf;
B
Bruce Momjian 已提交
1677

1678 1679 1680 1681 1682
		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 已提交
1683 1684 1685
		/* Need not flush since ReadyForQuery will do it. */
	}

1686 1687 1688
	if (!IsUnderPostmaster)
	{
		puts("\nPOSTGRES backend interactive interface ");
1689
		puts("$Revision: 1.289 $ $Date: 2002/09/02 02:47:04 $\n");
1690 1691
	}

1692 1693 1694
	/*
	 * Create the memory context we will use in the main loop.
	 *
B
Bruce Momjian 已提交
1695 1696 1697 1698
	 * QueryContext is reset once per iteration of the main loop, ie, upon
	 * completion of processing of each supplied query string. It can
	 * therefore be used for any data that should live just as long as the
	 * query string --- parse trees, for example.
1699 1700 1701 1702 1703 1704 1705
	 */
	QueryContext = AllocSetContextCreate(TopMemoryContext,
										 "QueryContext",
										 ALLOCSET_DEFAULT_MINSIZE,
										 ALLOCSET_DEFAULT_INITSIZE,
										 ALLOCSET_DEFAULT_MAXSIZE);

1706 1707 1708 1709 1710 1711 1712
	/* ----------
	 * Tell the statistics collector that we're alive and
	 * to which database we belong.
	 * ----------
	 */
	pgstat_bestart();

1713 1714
	/*
	 * POSTGRES main processing loop begins here
1715
	 *
1716 1717
	 * If an exception is encountered, processing resumes here so we abort
	 * the current transaction and start a new one.
1718 1719 1720 1721
	 */

	if (sigsetjmp(Warn_restart, 1) != 0)
	{
1722
		/*
1723
		 * NOTE: if you are tempted to add more code in this if-block,
B
Bruce Momjian 已提交
1724 1725
		 * consider the probability that it should be in
		 * AbortTransaction() instead.
1726
		 *
1727 1728
		 * Make sure we're not interrupted while cleaning up.  Also forget
		 * any pending QueryCancel request, since we're aborting anyway.
1729 1730
		 * Force InterruptHoldoffCount to a known state in case we elog'd
		 * from inside a holdoff section.
1731 1732 1733
		 */
		ImmediateInterruptOK = false;
		QueryCancelPending = false;
1734 1735
		InterruptHoldoffCount = 1;
		CritSectionCount = 0;	/* should be unnecessary, but... */
1736
		debug_query_string = NULL;		/* used by pgmonitor */
1737 1738

		/*
1739 1740 1741 1742 1743 1744
		 * Make sure we are in a valid memory context during recovery.
		 *
		 * We use ErrorContext in hopes that it will have some free space
		 * even if we're otherwise up against it...
		 */
		MemoryContextSwitchTo(ErrorContext);
1745

1746
		/* Do the recovery */
1747
		elog(DEBUG1, "AbortCurrentTransaction");
1748
		AbortCurrentTransaction();
1749 1750

		/*
1751 1752
		 * Now return to normal top-level context and clear ErrorContext
		 * for next time.
1753 1754 1755
		 */
		MemoryContextSwitchTo(TopMemoryContext);
		MemoryContextResetAndDeleteChildren(ErrorContext);
1756 1757 1758 1759 1760

		/*
		 * Clear flag to indicate that we got out of error recovery mode
		 * successfully.  (Flag was set in elog.c before longjmp().)
		 */
1761
		InError = false;
1762 1763

		/*
1764
		 * Exit interrupt holdoff section we implicitly established above.
1765
		 */
1766
		RESUME_INTERRUPTS();
1767
	}
1768

1769 1770
	Warn_restart_ready = true;	/* we can now handle elog(ERROR) */

1771
	PG_SETMASK(&UnBlockSig);
1772

1773 1774
	/*
	 * Non-error queries loop here.
1775 1776 1777 1778
	 */

	for (;;)
	{
1779
		/*
B
Bruce Momjian 已提交
1780 1781
		 * Release storage left over from prior query cycle, and create a
		 * new query input buffer in the cleared QueryContext.
1782 1783 1784 1785 1786
		 */
		MemoryContextSwitchTo(QueryContext);
		MemoryContextResetAndDeleteChildren(QueryContext);

		parser_input = makeStringInfo();
1787

1788 1789
		/*
		 * (1) tell the frontend we're ready for a new query.
1790
		 *
1791
		 * Note: this includes fflush()'ing the last of the prior output.
B
Bruce Momjian 已提交
1792
		 */
1793
		ReadyForQuery(whereToSendOutput);
B
Bruce Momjian 已提交
1794

1795 1796 1797 1798 1799 1800 1801
		/* ----------
		 * Tell the statistics collector what we've collected
		 * so far.
		 * ----------
		 */
		pgstat_report_tabstat();

1802
		if (IsTransactionBlock())
1803
		{
1804
			set_ps_display("idle in transaction");
1805 1806
			pgstat_report_activity("<IDLE> in transaction");
		}
1807
		else
1808
		{
1809
			set_ps_display("idle");
1810 1811
			pgstat_report_activity("<IDLE>");
		}
1812

1813 1814 1815 1816
		/*
		 * (2) deal with pending asynchronous NOTIFY from other backends,
		 * and enable async.c's signal handler to execute NOTIFY directly.
		 * Then set up other stuff needed before blocking for input.
1817
		 */
B
Bruce Momjian 已提交
1818 1819
		QueryCancelPending = false;		/* forget any earlier CANCEL
										 * signal */
1820

1821 1822 1823
		/* Stop any statement timer */
		disable_sig_alarm(true);

1824 1825
		EnableNotifyInterrupt();

1826 1827 1828 1829 1830 1831
		/* Allow "die" interrupt to be processed while waiting */
		ImmediateInterruptOK = true;
		/* and don't forget to detect one that already arrived */
		QueryCancelPending = false;
		CHECK_FOR_INTERRUPTS();

1832 1833
		/*
		 * (3) read a command (loop blocks here)
1834
		 */
1835
		firstchar = ReadCommand(parser_input);
1836

1837 1838
		/*
		 * (4) disable async signal conditions again.
1839
		 */
1840
		ImmediateInterruptOK = false;
B
Bruce Momjian 已提交
1841
		QueryCancelPending = false;		/* forget any CANCEL signal */
1842

1843 1844
		DisableNotifyInterrupt();

1845 1846 1847
		/*
		 * (5) check for any other interesting events that happened while
		 * we slept.
1848 1849 1850 1851 1852 1853 1854
		 */
		if (got_SIGHUP)
		{
			got_SIGHUP = false;
			ProcessConfigFile(PGC_SIGHUP);
		}

1855 1856
		/*
		 * (6) process the command.
1857
		 */
1858 1859
		switch (firstchar)
		{
1860 1861
				/*
				 * 'F' indicates a fastpath call.
1862
				 */
1863
			case 'F':
1864 1865 1866 1867 1868 1869
				/* ----------
				 * Tell the collector what we're doing
				 * ----------
				 */
				pgstat_report_activity("<FASTPATH> function call");

1870
				/* start an xact for this function invocation */
1871
				start_xact_command();
1872

1873 1874 1875
				if (HandleFunctionRequest() == EOF)
				{
					/* lost frontend connection during F message input */
1876 1877 1878 1879 1880 1881 1882
					/*
					 * Reset whereToSendOutput to prevent elog from attempting
					 * to send any more messages to client.
					 */
					if (whereToSendOutput == Remote)
						whereToSendOutput = None;

1883
					proc_exit(0);
1884
				}
1885 1886 1887

				/* commit the function-invocation transaction */
				finish_xact_command();
1888
				break;
1889

1890 1891
				/*
				 * 'Q' indicates a user query
1892 1893
				 */
			case 'Q':
1894
				if (strspn(parser_input->data, " \t\r\n") == parser_input->len)
1895
				{
1896 1897 1898 1899
					/*
					 * if there is nothing in the input buffer, don't
					 * bother trying to parse and execute anything; just
					 * send back a quick NullCommand response.
1900
					 */
1901 1902
					if (IsUnderPostmaster)
						NullCommand(Remote);
1903 1904 1905
				}
				else
				{
1906 1907
					/*
					 * otherwise, process the input string.
1908
					 *
1909 1910
					 * Note: transaction command start/end is now done within
					 * pg_exec_query_string(), not here.
1911
					 */
1912
					if (Show_statement_stats)
1913 1914
						ResetUsage();

1915 1916
					pgstat_report_activity(parser_input->data);

1917
					pg_exec_query_string(parser_input,
1918 1919
										 whereToSendOutput,
										 QueryContext);
1920

1921
					if (Show_statement_stats)
1922
						ShowUsage("QUERY STATISTICS");
1923 1924 1925
				}
				break;

1926
				/*
1927 1928 1929
				 *	'X' means that the frontend is closing down the socket.
				 *	EOF means unexpected loss of frontend connection.
				 *	Either way, perform normal shutdown.
1930 1931
				 */
			case 'X':
1932
			case EOF:
1933 1934 1935 1936 1937 1938
				/*
				 * Reset whereToSendOutput to prevent elog from attempting
				 * to send any more messages to client.
				 */
				if (whereToSendOutput == Remote)
					whereToSendOutput = None;
B
Bruce Momjian 已提交
1939

1940 1941
				/*
				 * NOTE: if you are tempted to add more code here, DON'T!
B
Bruce Momjian 已提交
1942 1943
				 * Whatever you had in mind to do should be set up as an
				 * on_proc_exit or on_shmem_exit callback, instead.
1944 1945 1946 1947
				 * Otherwise it will fail to be called during other
				 * backend-shutdown scenarios.
				 */
				proc_exit(0);
1948 1949

			default:
M
 
Marc G. Fournier 已提交
1950
				elog(ERROR, "unknown frontend message was received");
1951 1952
		}

1953
#ifdef MEMORY_CONTEXT_CHECKING
B
Bruce Momjian 已提交
1954

1955
		/*
1956 1957
		 * Check all memory after each backend loop.  This is a rather
		 * weird place to do it, perhaps.
1958
		 */
B
Bruce Momjian 已提交
1959
		MemoryContextCheck(TopMemoryContext);
1960
#endif
1961
	}							/* end of input-reading loop */
1962

1963 1964
	/* can't get here because the above loop never exits */
	Assert(false);
1965

1966
	return 1;					/* keep compiler quiet */
1967 1968
}

1969
#ifndef HAVE_GETRUSAGE
B
Bruce Momjian 已提交
1970 1971
#include "rusagestub.h"
#else
1972
#include <sys/resource.h>
1973
#endif   /* HAVE_GETRUSAGE */
1974

1975 1976
struct rusage Save_r;
struct timeval Save_t;
1977 1978

void
1979
ResetUsage(void)
1980
{
1981 1982 1983 1984 1985 1986
	struct timezone tz;

	getrusage(RUSAGE_SELF, &Save_r);
	gettimeofday(&Save_t, &tz);
	ResetBufferUsage();
/*	  ResetTupleCount(); */
1987 1988 1989
}

void
1990
ShowUsage(const char *title)
1991
{
1992
	StringInfoData str;
1993 1994 1995
	struct timeval user,
				sys;
	struct timeval elapse_t;
1996
	struct timezone tz;
1997
	struct rusage r;
1998
	char *bufusage;
1999 2000 2001

	getrusage(RUSAGE_SELF, &r);
	gettimeofday(&elapse_t, &tz);
2002 2003
	memcpy((char *) &user, (char *) &r.ru_utime, sizeof(user));
	memcpy((char *) &sys, (char *) &r.ru_stime, sizeof(sys));
2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027
	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.
	 */
2028
	initStringInfo(&str);
2029

2030 2031
	appendStringInfo(&str, "! system usage stats:\n");
	appendStringInfo(&str,
2032 2033 2034 2035 2036 2037 2038
			"!\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);
2039
	appendStringInfo(&str,
2040 2041 2042 2043 2044
			"!\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);
2045
/* BeOS has rusage but only has some fields, and not these... */
2046
#if defined(HAVE_GETRUSAGE)
2047
	appendStringInfo(&str,
2048 2049 2050 2051 2052
			"!\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);
2053
	appendStringInfo(&str,
2054 2055 2056 2057 2058 2059
		  "!\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);
2060
	appendStringInfo(&str,
2061 2062 2063 2064 2065 2066
	 "!\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);
2067
	appendStringInfo(&str,
2068 2069 2070 2071
		 "!\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);
2072
#endif   /* HAVE_GETRUSAGE */
2073 2074 2075 2076 2077 2078 2079 2080 2081

	bufusage = ShowBufferUsage();
	appendStringInfo(&str, "! postgres usage stats:\n%s", bufusage);
	pfree(bufusage);

	/* remove trailing newline */
	if (str.data[str.len-1] == '\n')
		str.data[--str.len] = '\0';

2082
	elog(LOG, "%s\n%s", title, str.data);
2083 2084

	pfree(str.data);
2085
}
M
 
Marc G. Fournier 已提交
2086

2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126
/* ----------------------------------------------------------------
 *		CreateCommandTag
 *
 *		utility to get a string representation of the
 *		command operation.
 * ----------------------------------------------------------------
 */
static const char *
CreateCommandTag(Node *parsetree)
{
	const char   *tag;

	switch (nodeTag(parsetree))
	{
		case T_InsertStmt:
			tag = "INSERT";
			break;

		case T_DeleteStmt:
			tag = "DELETE";
			break;

		case T_UpdateStmt:
			tag = "UPDATE";
			break;

		case T_SelectStmt:
			tag = "SELECT";
			break;

		case T_TransactionStmt:
			{
				TransactionStmt *stmt = (TransactionStmt *) parsetree;

				switch (stmt->command)
				{
					case BEGIN_TRANS:
						tag = "BEGIN";
						break;

2127 2128 2129 2130
					case START:
						tag = "START TRANSACTION";
						break;

2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146
					case COMMIT:
						tag = "COMMIT";
						break;

					case ROLLBACK:
						tag = "ROLLBACK";
						break;

					default:
						tag = "???";
						break;
				}
			}
			break;

		case T_ClosePortalStmt:
2147
			tag = "CLOSE CURSOR";
2148 2149 2150 2151 2152 2153 2154 2155 2156
			break;

		case T_FetchStmt:
			{
				FetchStmt  *stmt = (FetchStmt *) parsetree;
				tag = (stmt->ismove) ? "MOVE" : "FETCH";
			}
			break;

2157
		case T_CreateDomainStmt:
2158
			tag = "CREATE DOMAIN";
B
Bruce Momjian 已提交
2159 2160
			break;

2161
		case T_CreateSchemaStmt:
2162
			tag = "CREATE SCHEMA";
2163 2164
			break;

2165
		case T_CreateStmt:
2166
			tag = "CREATE TABLE";
2167 2168 2169
			break;

		case T_DropStmt:
2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189
			switch (((DropStmt *) parsetree)->removeType)
			{
				case DROP_TABLE:
					tag = "DROP TABLE";
					break;
				case DROP_SEQUENCE:
					tag = "DROP SEQUENCE";
					break;
				case DROP_VIEW:
					tag = "DROP VIEW";
					break;
				case DROP_INDEX:
					tag = "DROP INDEX";
					break;
				case DROP_TYPE:
					tag = "DROP TYPE";
					break;
				case DROP_DOMAIN:
					tag = "DROP DOMAIN";
					break;
2190
				case DROP_CONVERSION:
2191 2192 2193 2194
					tag = "DROP CONVERSION";
					break;
				case DROP_SCHEMA:
					tag = "DROP SCHEMA";
2195
					break;
2196 2197 2198
				default:
					tag = "???";
			}
2199 2200 2201
			break;

		case T_TruncateStmt:
2202
			tag = "TRUNCATE TABLE";
2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213
			break;

		case T_CommentStmt:
			tag = "COMMENT";
			break;

		case T_CopyStmt:
			tag = "COPY";
			break;

		case T_RenameStmt:
2214 2215 2216 2217
			if (((RenameStmt *)parsetree)->renameType == RENAME_TRIGGER)
				tag = "ALTER TRIGGER";
			else
				tag = "ALTER TABLE";
2218 2219 2220
			break;

		case T_AlterTableStmt:
2221
			tag = "ALTER TABLE";
2222 2223 2224 2225 2226 2227 2228 2229 2230 2231
			break;

		case T_GrantStmt:
			{
				GrantStmt  *stmt = (GrantStmt *) parsetree;
				tag = (stmt->is_grant) ? "GRANT" : "REVOKE";
			}
			break;

		case T_DefineStmt:
2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245
			switch (((DefineStmt *) parsetree)->defType)
			{
				case AGGREGATE:
					tag = "CREATE AGGREGATE";
					break;
				case OPERATOR:
					tag = "CREATE OPERATOR";
					break;
				case TYPE_P:
					tag = "CREATE TYPE";
					break;
				default:
					tag = "???";
			}
2246 2247
			break;

B
Bruce Momjian 已提交
2248 2249 2250 2251
		case T_CompositeTypeStmt:
			tag = "CREATE TYPE";
			break;

2252 2253
		case T_ViewStmt:
			tag = "CREATE VIEW";
2254 2255
			break;

2256 2257
		case T_CreateFunctionStmt:
			tag = "CREATE FUNCTION";
2258 2259
			break;

2260 2261
		case T_IndexStmt:
			tag = "CREATE INDEX";
2262 2263
			break;

2264 2265
		case T_RuleStmt:
			tag = "CREATE RULE";
2266 2267 2268
			break;

		case T_CreateSeqStmt:
2269
			tag = "CREATE SEQUENCE";
2270 2271 2272
			break;

		case T_RemoveAggrStmt:
2273
			tag = "DROP AGGREGATE";
2274 2275 2276
			break;

		case T_RemoveFuncStmt:
2277
			tag = "DROP FUNCTION";
2278 2279 2280
			break;

		case T_RemoveOperStmt:
2281
			tag = "DROP OPERATOR";
2282 2283 2284 2285 2286 2287
			break;

		case T_CreatedbStmt:
			tag = "CREATE DATABASE";
			break;

2288 2289 2290 2291
		case T_AlterDatabaseSetStmt:
			tag = "ALTER DATABASE";
			break;

2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327
		case T_DropdbStmt:
			tag = "DROP DATABASE";
			break;

		case T_NotifyStmt:
			tag = "NOTIFY";
			break;

		case T_ListenStmt:
			tag = "LISTEN";
			break;

		case T_UnlistenStmt:
			tag = "UNLISTEN";
			break;

		case T_LoadStmt:
			tag = "LOAD";
			break;

		case T_ClusterStmt:
			tag = "CLUSTER";
			break;

		case T_VacuumStmt:
			if (((VacuumStmt *) parsetree)->vacuum)
				tag = "VACUUM";
			else
				tag = "ANALYZE";
			break;

		case T_ExplainStmt:
			tag = "EXPLAIN";
			break;

		case T_VariableSetStmt:
2328
			tag = "SET";
2329 2330 2331
			break;

		case T_VariableShowStmt:
2332
			tag = "SHOW";
2333 2334 2335
			break;

		case T_VariableResetStmt:
2336
			tag = "RESET";
2337 2338 2339
			break;

		case T_CreateTrigStmt:
2340
			tag = "CREATE TRIGGER";
2341 2342
			break;

2343
		case T_DropPropertyStmt:
2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354
			switch (((DropPropertyStmt *) parsetree)->removeType)
			{
				case DROP_TRIGGER:
					tag = "DROP TRIGGER";
					break;
				case DROP_RULE:
					tag = "DROP RULE";
					break;
				default:
					tag = "???";
			}
2355 2356 2357
			break;

		case T_CreatePLangStmt:
2358
			tag = "CREATE LANGUAGE";
2359 2360 2361
			break;

		case T_DropPLangStmt:
2362
			tag = "DROP LANGUAGE";
2363 2364 2365 2366 2367 2368 2369 2370 2371 2372
			break;

		case T_CreateUserStmt:
			tag = "CREATE USER";
			break;

		case T_AlterUserStmt:
			tag = "ALTER USER";
			break;

2373 2374 2375 2376
		case T_AlterUserSetStmt:
			tag = "ALTER USER";
			break;

2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408
		case T_DropUserStmt:
			tag = "DROP USER";
			break;

		case T_LockStmt:
			tag = "LOCK TABLE";
			break;

		case T_ConstraintsSetStmt:
			tag = "SET CONSTRAINTS";
			break;

		case T_CreateGroupStmt:
			tag = "CREATE GROUP";
			break;

		case T_AlterGroupStmt:
			tag = "ALTER GROUP";
			break;

		case T_DropGroupStmt:
			tag = "DROP GROUP";
			break;

		case T_CheckPointStmt:
			tag = "CHECKPOINT";
			break;

		case T_ReindexStmt:
			tag = "REINDEX";
			break;

2409 2410 2411 2412
		case T_CreateConversionStmt:
			tag = "CREATE CONVERSION";
			break;

2413 2414 2415 2416 2417 2418 2419 2420
		case T_CreateCastStmt:
			tag = "CREATE CAST";
			break;

		case T_DropCastStmt:
			tag = "DROP CAST";
			break;

2421 2422 2423 2424 2425 2426 2427 2428
		case T_CreateOpClassStmt:
			tag = "CREATE OPERATOR CLASS";
			break;

		case T_RemoveOpClassStmt:
			tag = "DROP OPERATOR CLASS";
			break;

2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440
		case T_PrepareStmt:
			tag = "PREPARE";
			break;

		case T_ExecuteStmt:
			tag = "EXECUTE";
			break;

		case T_DeallocateStmt:
			tag = "DEALLOCATE";
			break;

2441
		default:
2442
			elog(LOG, "CreateCommandTag: unknown parse node type %d",
2443 2444 2445 2446 2447 2448 2449
				 nodeTag(parsetree));
			tag = "???";
			break;
	}

	return tag;
}