postgres.c 62.8 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.326 2003/04/29 22:13:11 tgl 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
#include "parser/analyze.h"
47
#include "parser/parser.h"
B
Bruce Momjian 已提交
48
#include "rewrite/rewriteHandler.h"
49
#include "storage/freespace.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
extern int	optind;
extern char *optarg;

66

67
/* ----------------
68
 *		global variables
69 70
 * ----------------
 */
71
const char *debug_query_string; /* for pgmonitor and
B
Bruce Momjian 已提交
72
								 * log_min_error_statement */
73

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

B
Bruce Momjian 已提交
77
static bool dontExecute = false;
78

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

82
bool		Warn_restart_ready = false;
83
bool		InError = false;
84

85 86
extern bool	autocommit;

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 void start_xact_command(void);
122
static void finish_xact_command(bool forceCommit);
123 124
static void SigHupHandler(SIGNAL_ARGS);
static void FloatExceptionHandler(SIGNAL_ARGS);
125
static const char *CreateCommandTag(Node *parsetree);
126 127 128


/* ----------------------------------------------------------------
129
 *		routines to obtain user input
130 131 132 133
 * ----------------------------------------------------------------
 */

/* ----------------
134
 *	InteractiveBackend() is called for user interactive connections
135 136 137
 *
 *	the string entered by the user is placed in its parameter inBuf,
 *	and we act like a Q message was received.
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
	/* Reset inBuf to empty */
	inBuf->len = 0;
	inBuf->data[0] = '\0';
159
	inBuf->cursor = 0;
160

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

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

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

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

		if (end)
211
			return EOF;
212

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

219 220 221
	/* Add '\0' to make it look the same as message case. */
	appendStringInfoChar(inBuf, (char) '\0');

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

229
	return 'Q';
230 231 232
}

/* ----------------
233
 *	SocketBackend()		Is called for frontend-backend connections
234
 *
235
 *	Returns the message type code, and loads message body data into inBuf.
236
 *
237
 *	EOF is returned if the connection is lost.
238 239
 * ----------------
 */
240
static int
241
SocketBackend(StringInfo inBuf)
242
{
243
	int			qtype;
244

245
	/*
246
	 * Get message type code from the frontend.
247
	 */
248
	qtype = pq_getbyte();
249

250 251 252 253 254 255 256 257 258 259 260
	if (qtype == EOF)			/* frontend disconnected */
	{
		elog(COMMERROR, "unexpected EOF on client connection");
		return qtype;
	}

	/*
	 * Validate message type code before trying to read body; if we have
	 * lost sync, better to say "command unknown" than to run out of memory
	 * because we used garbage as a length word.
	 */
261
	switch (qtype)
262
	{
263 264 265 266 267 268 269 270 271 272
		case 'Q':				/* simple query */
			if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
			{
				/* old style without length word; convert */
				if (pq_getstring(inBuf))
				{
					elog(COMMERROR, "unexpected EOF on client connection");
					return EOF;
				}
			}
273 274
			break;

275
		case 'F':				/* fastpath function call */
276
			break;
277

278
		case 'X':				/* terminate */
279
			break;
280

281 282 283 284
		case 'd':				/* copy data */
		case 'c':				/* copy done */
		case 'f':				/* copy fail */
			/* Accept but ignore these messages, per protocol spec */
285
			break;
286

287
		default:
288
			/*
289 290 291
			 * Otherwise we got garbage from the frontend.  We treat this
			 * as fatal because we have probably lost message boundary sync,
			 * and there's no good way to recover.
292
			 */
293
			elog(FATAL, "Socket command type %c unknown", qtype);
294
			break;
295
	}
296

297 298 299 300 301 302 303 304 305 306 307
	/*
	 * In protocol version 3, all frontend messages have a length word
	 * next after the type code; we can read the message contents
	 * independently of the type.
	 */
	if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3)
	{
		if (pq_getmessage(inBuf, 0))
			return EOF;			/* suitable message already logged */
	}

308
	return qtype;
309 310 311
}

/* ----------------
312 313 314
 *		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
315
 *		call.  EOF is returned if end of file.
316 317
 * ----------------
 */
318
static int
319
ReadCommand(StringInfo inBuf)
320
{
321
	int			result;
322

323
	if (IsUnderPostmaster)
324
		result = SocketBackend(inBuf);
325
	else
326 327
		result = InteractiveBackend(inBuf);
	return result;
328 329
}

330 331 332 333 334 335

/*
 * 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.
336 337 338
 *
 * NOTE: this routine is no longer used for processing interactive queries,
 * but it is still needed for parsing of SQL function bodies.
339
 */
340
List *
341
pg_parse_and_rewrite(const char *query_string, /* string to execute */
342 343
					 Oid *paramTypes,	/* parameter types */
					 int numParams) /* number of parameters */
344
{
345
	List	   *raw_parsetree_list;
346
	List	   *querytree_list;
347 348
	List	   *list_item;

349 350
	/*
	 * (1) parse the request string into a list of raw parse trees.
351
	 */
352
	raw_parsetree_list = pg_parse_query(query_string);
353

354 355
	/*
	 * (2) Do parse analysis and rule rewrite.
356 357 358 359
	 */
	querytree_list = NIL;
	foreach(list_item, raw_parsetree_list)
	{
B
Bruce Momjian 已提交
360
		Node	   *parsetree = (Node *) lfirst(list_item);
361 362

		querytree_list = nconc(querytree_list,
363 364 365
							   pg_analyze_and_rewrite(parsetree,
													  paramTypes,
													  numParams));
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
	}

	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.
 */
384
List *
385
pg_parse_query(const char *query_string)
386 387
{
	List	   *raw_parsetree_list;
388

B
Rename:  
Bruce Momjian 已提交
389
	if (log_statement)
390
		elog(LOG, "query: %s", query_string);
391

B
Rename:  
Bruce Momjian 已提交
392
	if (log_parser_stats)
393 394
		ResetUsage();

395
	raw_parsetree_list = raw_parser(query_string);
396

B
Rename:  
Bruce Momjian 已提交
397
	if (log_parser_stats)
398
		ShowUsage("PARSER STATISTICS");
399 400 401 402 403

	return raw_parsetree_list;
}

/*
404 405
 * Given a raw parsetree (gram.y output), and optionally information about
 * types of parameter symbols ($n), perform parse analysis and rule rewriting.
406 407 408 409 410 411
 *
 * 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.
 */
412
List *
413
pg_analyze_and_rewrite(Node *parsetree, Oid *paramTypes, int numParams)
414 415 416 417 418 419
{
	List	   *querytree_list;
	List	   *list_item;
	Query	   *querytree;
	List	   *new_list;

420 421
	/*
	 * (1) Perform parse analysis.
422
	 */
B
Rename:  
Bruce Momjian 已提交
423
	if (log_parser_stats)
424 425
		ResetUsage();

426
	querytree_list = parse_analyze(parsetree, paramTypes, numParams);
427

B
Rename:  
Bruce Momjian 已提交
428
	if (log_parser_stats)
429
	{
430
		ShowUsage("PARSE ANALYSIS STATISTICS");
431
		ResetUsage();
432 433
	}

434 435
	/*
	 * (2) Rewrite the queries, as necessary
436
	 *
437 438
	 * rewritten queries are collected in new_list.  Note there may be more
	 * or fewer than in the original list.
439
	 */
440
	new_list = NIL;
441
	foreach(list_item, querytree_list)
442
	{
443
		querytree = (Query *) lfirst(list_item);
444

445
		if (Debug_print_parse)
446 447
			elog_node_display(LOG, "parse tree", querytree,
							  Debug_pretty_print);
448 449 450

		if (querytree->commandType == CMD_UTILITY)
		{
451 452
			/* don't rewrite utilities, just dump 'em into new_list */
			new_list = lappend(new_list, querytree);
453
		}
454
		else
455
		{
456
			/* rewrite regular queries */
457 458
			List	   *rewritten = QueryRewrite(querytree);

459
			new_list = nconc(new_list, rewritten);
460 461 462 463 464
		}
	}

	querytree_list = new_list;

B
Rename:  
Bruce Momjian 已提交
465
	if (log_parser_stats)
466
		ShowUsage("REWRITER STATISTICS");
467

468
#ifdef COPY_PARSE_PLAN_TREES
B
Bruce Momjian 已提交
469 470 471 472 473

	/*
	 * Optional debugging check: pass querytree output through
	 * copyObject()
	 */
474 475
	new_list = (List *) copyObject(querytree_list);
	/* This checks both copyObject() and the equal() routines... */
B
Bruce Momjian 已提交
476
	if (!equal(new_list, querytree_list))
B
Bruce Momjian 已提交
477
		elog(WARNING, "pg_analyze_and_rewrite: copyObject failed on parse tree");
478 479
	else
		querytree_list = new_list;
480 481
#endif

482
	if (Debug_print_rewritten)
483 484
		elog_node_display(LOG, "rewritten parse tree", querytree_list,
						  Debug_pretty_print);
485

486 487
	return querytree_list;
}
488 489


490 491 492 493 494
/* Generate a plan for a single query. */
Plan *
pg_plan_query(Query *querytree)
{
	Plan	   *plan;
495

496 497 498
	/* Utility commands have no plans. */
	if (querytree->commandType == CMD_UTILITY)
		return NULL;
499

B
Rename:  
Bruce Momjian 已提交
500
	if (log_planner_stats)
501
		ResetUsage();
502

503
	/* call the optimizer */
504
	plan = planner(querytree, false, 0);
505

B
Rename:  
Bruce Momjian 已提交
506
	if (log_planner_stats)
507
		ShowUsage("PLANNER STATISTICS");
508

509 510 511
#ifdef COPY_PARSE_PLAN_TREES
	/* Optional debugging check: pass plan output through copyObject() */
	{
B
Bruce Momjian 已提交
512
		Plan	   *new_plan = (Plan *) copyObject(plan);
513

B
Bruce Momjian 已提交
514 515
		/*
		 * equal() currently does not have routines to compare Plan nodes,
516 517 518 519
		 * 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 已提交
520
		if (!equal(new_plan, plan))
B
Bruce Momjian 已提交
521
			elog(WARNING, "pg_plan_query: copyObject failed on plan tree");
522 523 524 525 526 527
		else
#endif
			plan = new_plan;
	}
#endif

528 529
	/*
	 * Print plan if debugging.
530
	 */
531
	if (Debug_print_plan)
532
		elog_node_display(LOG, "plan", plan, Debug_pretty_print);
533

534
	return plan;
535 536
}

537

538
/* ----------------------------------------------------------------
539
 *		pg_exec_query_string()
540 541
 *
 *		Takes a querystring, runs the parser/utilities or
542 543 544 545
 *		parser/planner/executor over it as necessary.
 *
 * Assumptions:
 *
546
 * At call, we are not inside a transaction command.
547
 *
548
 * The CurrentMemoryContext after starting a transaction command must be
549
 * appropriate for execution of individual queries (typically this will be
B
Bruce Momjian 已提交
550
 * TransactionCommandContext).	Note that this routine resets that context
551 552
 * after each individual query, so don't store anything there that
 * must outlive the call!
553
 *
554 555
 * parse_context references a context suitable for holding the
 * parse/rewrite trees (typically this will be QueryContext).
556
 * This context *must* be longer-lived than the transaction context!
557 558 559 560 561 562 563
 * 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.
564 565 566
 *
 * ----------------------------------------------------------------
 */
567
static void
568
pg_exec_query_string(const char *query_string,	/* string to execute */
B
Bruce Momjian 已提交
569 570 571
					 CommandDest dest,	/* where results should go */
					 MemoryContext parse_context)		/* context for
														 * parsetrees */
572
{
573
	bool		xact_started;
574
	MemoryContext oldcontext;
575 576
	List	   *parsetree_list,
			   *parsetree_item;
B
Bruce Momjian 已提交
577 578
	struct timeval start_t,
				stop_t;
B
Rename:  
Bruce Momjian 已提交
579
	bool		save_log_duration = log_duration;
580

581
	debug_query_string = query_string;
582

583
	/*
B
Rename:  
Bruce Momjian 已提交
584
	 * We use save_log_duration so "SET log_duration = true" doesn't
B
Bruce Momjian 已提交
585
	 * report incorrect time because gettimeofday() wasn't called.
586
	 */
B
Rename:  
Bruce Momjian 已提交
587
	if (save_log_duration)
588
		gettimeofday(&start_t, NULL);
589

590
	/*
B
Bruce Momjian 已提交
591 592 593 594 595
	 * 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.)
596 597 598 599 600
	 */
	start_xact_command();
	xact_started = true;

	/*
B
Bruce Momjian 已提交
601 602 603 604 605
	 * 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.)
606 607 608
	 */
	Assert(parse_context != CurrentMemoryContext);

609 610 611 612
	/*
	 * Switch to appropriate context for constructing parsetrees.
	 */
	oldcontext = MemoryContextSwitchTo(parse_context);
613

B
Bruce Momjian 已提交
614
	/*
B
Bruce Momjian 已提交
615 616
	 * Do basic parsing of the query or queries (this should be safe even
	 * if we are in aborted transaction state!)
617
	 */
618
	parsetree_list = pg_parse_query(query_string);
619

620
	/*
621
	 * Switch back to execution context to enter the loop.
622 623 624 625
	 */
	MemoryContextSwitchTo(oldcontext);

	/*
626
	 * Run through the parsetree(s) and process each one.
627
	 */
628
	foreach(parsetree_item, parsetree_list)
629
	{
B
Bruce Momjian 已提交
630
		Node	   *parsetree = (Node *) lfirst(parsetree_item);
631 632
		const char *commandTag;
		char		completionTag[COMPLETION_TAG_BUFSIZE];
633 634
		CmdType		origCmdType;
		bool		foundOriginalQuery = false;
B
Bruce Momjian 已提交
635 636
		List	   *querytree_list,
				   *querytree_item;
637

638
		/*
B
Bruce Momjian 已提交
639 640 641
		 * 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
642 643 644 645
		 * start-of-SQL-command processing needed by the destination.
		 */
		commandTag = CreateCommandTag(parsetree);

646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665
		switch (nodeTag(parsetree))
		{
			case T_InsertStmt:
				origCmdType = CMD_INSERT;
				break;
			case T_DeleteStmt:
				origCmdType = CMD_DELETE;
				break;
			case T_UpdateStmt:
				origCmdType = CMD_UPDATE;
				break;
			case T_SelectStmt:
				origCmdType = CMD_SELECT;
				break;
			default:
				/* Otherwise, never match commandType */
				origCmdType = CMD_UNKNOWN;
				break;
		}

666 667 668 669
		set_ps_display(commandTag);

		BeginCommand(commandTag, dest);

670 671 672 673
		/*
		 * 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 已提交
674 675 676
		 * 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...)
677 678
		 */
		if (IsAbortedTransactionBlockState())
679
		{
B
Bruce Momjian 已提交
680
			bool		allowit = false;
681

682
			if (IsA(parsetree, TransactionStmt))
683 684 685
			{
				TransactionStmt *stmt = (TransactionStmt *) parsetree;

686 687
				if (stmt->kind == TRANS_STMT_COMMIT ||
					stmt->kind == TRANS_STMT_ROLLBACK)
688
					allowit = true;
689
			}
690

B
Bruce Momjian 已提交
691
			if (!allowit)
692
				elog(ERROR, "current transaction is aborted, "
693
					 "queries ignored until end of transaction block");
694
		}
695

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

703
		/* If we got a cancel signal in parsing or prior command, quit */
704
		CHECK_FOR_INTERRUPTS();
705 706 707

		/*
		 * OK to analyze and rewrite this query.
708
		 *
B
Bruce Momjian 已提交
709 710
		 * Switch to appropriate context for constructing querytrees (again,
		 * these must outlive the execution context).
711 712
		 */
		oldcontext = MemoryContextSwitchTo(parse_context);
713

714
		querytree_list = pg_analyze_and_rewrite(parsetree, NULL, 0);
V
Vadim B. Mikheev 已提交
715

716 717 718 719 720 721 722 723 724 725 726 727
		/*
		 * 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);
728
			bool		endTransactionBlock = false;
729
			bool		canSetTag;
730

731
			/* Make sure we are in a transaction command */
B
Bruce Momjian 已提交
732
			if (!xact_started)
733
			{
734 735 736 737
				start_xact_command();
				xact_started = true;
			}

B
Bruce Momjian 已提交
738 739 740 741
			/*
			 * If we got a cancel signal in analysis or prior command,
			 * quit
			 */
742
			CHECK_FOR_INTERRUPTS();
743

744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761
			/*
			 * This query can set the completion tag if it is the original
			 * query, or if it is an INSTEAD query of the same kind as the
			 * original and we haven't yet seen the original query.
			 */
			if (querytree->querySource == QSRC_ORIGINAL)
			{
				canSetTag = true;
				foundOriginalQuery = true;
			}
			else if (!foundOriginalQuery &&
					 querytree->commandType == origCmdType &&
					 (querytree->querySource == QSRC_INSTEAD_RULE ||
					  querytree->querySource == QSRC_QUAL_INSTEAD_RULE))
				canSetTag = true;
			else
				canSetTag = false;

762 763
			if (querytree->commandType == CMD_UTILITY)
			{
764 765
				/*
				 * process utility functions (create, destroy, etc..)
766
				 */
767 768
				Node   *utilityStmt = querytree->utilityStmt;

769
				elog(DEBUG2, "ProcessUtility");
770

771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794
				/*
				 * Set snapshot if utility stmt needs one.  Most reliable
				 * way to do this seems to be to enumerate those that do not
				 * need one; this is a short list.  Transaction control,
				 * LOCK, and SET must *not* set a snapshot since they need
				 * to be executable at the start of a serializable transaction
				 * without freezing a snapshot.  By extension we allow SHOW
				 * not to set a snapshot.  The other stmts listed are just
				 * efficiency hacks.  Beware of listing anything that can
				 * modify the database --- if, say, it has to update a
				 * functional index, then it had better have a snapshot.
				 */
				if (! (IsA(utilityStmt, TransactionStmt) ||
					   IsA(utilityStmt, LockStmt) ||
					   IsA(utilityStmt, VariableSetStmt) ||
					   IsA(utilityStmt, VariableShowStmt) ||
					   IsA(utilityStmt, VariableResetStmt) ||
					   IsA(utilityStmt, ConstraintsSetStmt) ||
					   /* efficiency hacks from here down */
					   IsA(utilityStmt, FetchStmt) ||
					   IsA(utilityStmt, ListenStmt) ||
					   IsA(utilityStmt, NotifyStmt) ||
					   IsA(utilityStmt, UnlistenStmt) ||
					   IsA(utilityStmt, CheckPointStmt)))
795 796
					SetQuerySnapshot();

797 798 799 800 801 802 803
				/* end transaction block if transaction or variable stmt */
				if (IsA(utilityStmt, TransactionStmt) ||
					IsA(utilityStmt, VariableSetStmt) ||
					IsA(utilityStmt, VariableShowStmt) ||
					IsA(utilityStmt, VariableResetStmt))
					endTransactionBlock = true;

804
				if (canSetTag)
805 806
				{
					/* utility statement can override default tag string */
807
					ProcessUtility(utilityStmt, dest, completionTag);
808 809 810 811 812 813
					if (completionTag[0])
						commandTag = completionTag;
				}
				else
				{
					/* utility added by rewrite cannot override tag */
814
					ProcessUtility(utilityStmt, dest, NULL);
815
				}
816 817 818
			}
			else
			{
819 820
				/*
				 * process a plannable query.
821 822 823
				 */
				Plan	   *plan;

824 825 826 827 828 829 830 831 832
				/*
				 * Initialize snapshot state for query.  This has to
				 * be done before running the planner, because it might
				 * try to evaluate immutable or stable functions, which
				 * in turn might run queries.
				 */
				SetQuerySnapshot();

				/* Make the plan */
833 834 835
				plan = pg_plan_query(querytree);

				/* if we got a cancel signal whilst planning, quit */
836
				CHECK_FOR_INTERRUPTS();
837 838 839 840

				/*
				 * execute the plan
				 */
B
Rename:  
Bruce Momjian 已提交
841
				if (log_executor_stats)
842 843 844 845 846 847 848 849 850
					ResetUsage();

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

853
					if (canSetTag)
854
					{
855
						/* statement can override default tag string */
856 857 858 859 860 861 862 863
						ProcessQuery(querytree, plan, dest, completionTag);
						commandTag = completionTag;
					}
					else
					{
						/* stmt added by rewrite cannot override tag */
						ProcessQuery(querytree, plan, dest, NULL);
					}
864 865
				}

B
Rename:  
Bruce Momjian 已提交
866
				if (log_executor_stats)
867
					ShowUsage("EXECUTOR STATISTICS");
868
			}
869

870 871 872
			/*
			 * In a query block, we want to increment the command counter
			 * between queries so that the effects of early queries are
B
Bruce Momjian 已提交
873 874
			 * visible to subsequent ones.	In particular we'd better do
			 * so before checking constraints.
875
			 */
876
			if (!endTransactionBlock)
877 878 879
				CommandCounterIncrement();

			/*
B
Bruce Momjian 已提交
880 881
			 * Clear the execution context to recover temporary memory
			 * used by the query.  NOTE: if query string contains
882
			 * BEGIN/COMMIT transaction commands, execution context may
B
Bruce Momjian 已提交
883 884
			 * now be different from what we were originally passed; so be
			 * careful to clear current context not "oldcontext".
885 886 887 888 889 890
			 */
			Assert(parse_context != CurrentMemoryContext);

			MemoryContextResetAndDeleteChildren(CurrentMemoryContext);

			/*
891 892 893
			 * If this was a transaction control statement or a variable
			 * set/show/reset statement, commit it and arrange to start a
			 * new xact command for the next command (if any).
894
			 */
895
			if (endTransactionBlock)
896
			{
897
				finish_xact_command(true);
898
				xact_started = false;
899
			}
B
Bruce Momjian 已提交
900 901
		}						/* end loop over queries generated from a
								 * parsetree */
902

903 904
		/*
		 * If this is the last parsetree of the query string, close down
B
Bruce Momjian 已提交
905 906 907 908 909
		 * 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
910 911 912
		 * historical Postgres behavior, we do not force a transaction
		 * boundary between queries appearing in a single query string.
		 */
913
		if ((lnext(parsetree_item) == NIL || !autocommit) && xact_started)
914
		{
915
			finish_xact_command(false);
916 917 918
			xact_started = false;
		}

919
		/*
B
Bruce Momjian 已提交
920
		 * It is possible that the original query was removed due to a DO
921 922 923
		 * INSTEAD rewrite rule.  If so, and if we found no INSTEAD query
		 * matching the command type, we will still have the default
		 * completion tag.  This is fine for most purposes, but it
B
Bruce Momjian 已提交
924 925
		 * may confuse clients if it's INSERT/UPDATE/DELETE. Clients
		 * expect those tags to have counts after them (cf. ProcessQuery).
926
		 */
927 928 929 930 931 932 933 934 935
		if (!foundOriginalQuery)
		{
			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";
		}
936 937 938

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

947 948 949 950
	/* No parsetree - return empty result */
	if (!parsetree_list)
		NullCommand(dest);

951
	/*
B
Bruce Momjian 已提交
952 953
	 * Close down transaction statement, if one is open. (Note that this
	 * will only happen if the querystring was empty.)
954 955
	 */
	if (xact_started)
956
		finish_xact_command(false);
957

B
Rename:  
Bruce Momjian 已提交
958
	if (save_log_duration)
959
	{
960
		gettimeofday(&stop_t, NULL);
961 962 963 964 965 966
		if (stop_t.tv_usec < start_t.tv_usec)
		{
			stop_t.tv_sec--;
			stop_t.tv_usec += 1000000;
		}
		elog(LOG, "duration: %ld.%06ld sec",
967 968
			 (long) (stop_t.tv_sec - start_t.tv_sec),
			 (long) (stop_t.tv_usec - start_t.tv_usec));
969
	}
970 971

	debug_query_string = NULL;
972 973
}

974 975 976 977 978 979
/*
 * Convenience routines for starting/committing a single command.
 */
static void
start_xact_command(void)
{
980
	elog(DEBUG1, "StartTransactionCommand");
981
	StartTransactionCommand(false);
982 983 984 985

	/* Set statement timeout running, if any */
	if (StatementTimeout > 0)
		enable_sig_alarm(StatementTimeout, true);
986 987 988
}

static void
989
finish_xact_command(bool forceCommit)
990
{
991 992 993
	/* Invoke IMMEDIATE constraint triggers */
	DeferredTriggerEndQuery();

994 995 996
	/* Cancel any active statement timeout before committing */
	disable_sig_alarm(true);

997
	/* Now commit the command */
998
	elog(DEBUG1, "CommitTransactionCommand");
999

1000
	CommitTransactionCommand(forceCommit);
1001

1002
#ifdef SHOW_MEMORY_STATS
1003
	/* Print mem stats at each commit for leak tracking */
1004 1005 1006 1007 1008 1009
	if (ShowStats)
		MemoryContextStats(TopMemoryContext);
#endif
}


1010
/* --------------------------------
1011
 *		signal handler routines used in PostgresMain()
1012 1013 1014
 * --------------------------------
 */

1015
/*
T
Tom Lane 已提交
1016
 * quickdie() occurs when signalled SIGQUIT by the postmaster.
1017 1018 1019 1020
 *
 * Some backend has bought the farm,
 * so we need to stop what we're doing and exit.
 */
T
Tom Lane 已提交
1021
void
1022
quickdie(SIGNAL_ARGS)
1023
{
1024
	PG_SETMASK(&BlockSig);
B
Bruce Momjian 已提交
1025
	elog(WARNING, "Message from PostgreSQL backend:"
1026
		 "\n\tThe Postmaster has informed me that some other backend"
1027
		 "\n\tdied abnormally and possibly corrupted shared memory."
1028
		 "\n\tI have rolled back the current transaction and am"
1029
	   "\n\tgoing to terminate your database system connection and exit."
1030
	"\n\tPlease reconnect to the database system and repeat your query.");
1031

1032
	/*
1033 1034 1035 1036
	 * 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 已提交
1037 1038 1039 1040
	 * 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.
1041 1042
	 */

1043
	exit(1);
1044 1045
}

1046
/*
1047 1048
 * Shutdown signal from postmaster: abort transaction and exit
 * at soonest convenient time
1049
 */
1050
void
1051
die(SIGNAL_ARGS)
1052
{
1053 1054 1055
	int			save_errno = errno;

	/* Don't joggle the elbow of proc_exit */
B
Bruce Momjian 已提交
1056
	if (!proc_exit_inprogress)
1057
	{
1058
		InterruptPending = true;
1059
		ProcDiePending = true;
B
Bruce Momjian 已提交
1060

1061
		/*
B
Bruce Momjian 已提交
1062 1063
		 * If it's safe to interrupt, and we're waiting for input or a
		 * lock, service the interrupt immediately
1064
		 */
1065 1066
		if (ImmediateInterruptOK && InterruptHoldoffCount == 0 &&
			CritSectionCount == 0)
1067
		{
1068 1069 1070
			/* bump holdoff count to make ProcessInterrupts() a no-op */
			/* until we are done getting ready for it */
			InterruptHoldoffCount++;
1071
			DisableNotifyInterrupt();
1072
			/* Make sure CheckDeadLock won't run while shutting down... */
1073
			LockWaitCancel();
1074
			InterruptHoldoffCount--;
1075 1076
			ProcessInterrupts();
		}
1077
	}
1078 1079

	errno = save_errno;
1080 1081
}

1082
/*
1083
 * Timeout or shutdown signal from postmaster during client authentication.
1084
 * Simply exit(0).
1085 1086 1087
 *
 * XXX: possible future improvement: try to send a message indicating
 * why we are disconnecting.  Problem is to be sure we don't block while
1088
 * doing so, nor mess up the authentication message exchange.
1089 1090 1091 1092 1093 1094 1095
 */
void
authdie(SIGNAL_ARGS)
{
	exit(0);
}

1096
/*
1097 1098
 * Query-cancel signal from postmaster: abort current transaction
 * at soonest convenient time
1099
 */
1100
static void
1101
StatementCancelHandler(SIGNAL_ARGS)
1102
{
1103 1104
	int			save_errno = errno;

B
Bruce Momjian 已提交
1105 1106 1107 1108
	/*
	 * Don't joggle the elbow of proc_exit, nor an already-in-progress
	 * abort
	 */
1109
	if (!proc_exit_inprogress && !InError)
1110
	{
1111 1112
		InterruptPending = true;
		QueryCancelPending = true;
B
Bruce Momjian 已提交
1113

1114
		/*
1115
		 * If it's safe to interrupt, and we're waiting for a lock,
B
Bruce Momjian 已提交
1116 1117
		 * service the interrupt immediately.  No point in interrupting if
		 * we're waiting for input, however.
1118
		 */
1119
		if (ImmediateInterruptOK && InterruptHoldoffCount == 0 &&
1120
			CritSectionCount == 0)
1121
		{
1122 1123 1124 1125 1126 1127
			/* bump holdoff count to make ProcessInterrupts() a no-op */
			/* until we are done getting ready for it */
			InterruptHoldoffCount++;
			if (LockWaitCancel())
			{
				DisableNotifyInterrupt();
T
Tom Lane 已提交
1128
				InterruptHoldoffCount--;
1129 1130 1131 1132
				ProcessInterrupts();
			}
			else
				InterruptHoldoffCount--;
1133
		}
1134 1135
	}

1136
	errno = save_errno;
1137 1138
}

1139 1140 1141 1142 1143 1144 1145 1146 1147
/* 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");
}

1148
/* SIGHUP: set flag to re-read config file at next convenient time */
1149
static void
1150
SigHupHandler(SIGNAL_ARGS)
1151
{
1152
	got_SIGHUP = true;
1153 1154
}

1155

1156 1157 1158 1159 1160 1161 1162 1163 1164 1165
/*
 * 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)
{
1166 1167
	/* OK to accept interrupt now? */
	if (InterruptHoldoffCount != 0 || CritSectionCount != 0)
1168 1169 1170 1171 1172
		return;
	InterruptPending = false;
	if (ProcDiePending)
	{
		ProcDiePending = false;
B
Bruce Momjian 已提交
1173 1174
		QueryCancelPending = false;		/* ProcDie trumps QueryCancel */
		ImmediateInterruptOK = false;	/* not idle anymore */
1175
		DisableNotifyInterrupt();
B
Bruce Momjian 已提交
1176
		elog(FATAL, "This connection has been terminated by the administrator.");
1177 1178 1179 1180
	}
	if (QueryCancelPending)
	{
		QueryCancelPending = false;
B
Bruce Momjian 已提交
1181
		ImmediateInterruptOK = false;	/* not idle anymore */
1182
		DisableNotifyInterrupt();
1183
		elog(ERROR, "Query was canceled.");
1184 1185 1186 1187
	}
	/* If we get here, do nothing (probably, QueryCancelPending was reset) */
}

1188

1189 1190
static void
usage(char *progname)
1191
{
1192 1193
	printf("%s is the PostgreSQL stand-alone backend.  It is not\nintended to be used by normal users.\n\n", progname);

1194
	printf("Usage:\n  %s [OPTION]... [DBNAME]\n\n", progname);
1195
	printf("Options:\n");
M
 
Marc G. Fournier 已提交
1196
#ifdef USE_ASSERT_CHECKING
1197
	printf("  -A 1|0          enable/disable run-time assert checking\n");
M
 
Marc G. Fournier 已提交
1198
#endif
1199 1200
	printf("  -B NBUFFERS     number of shared buffers (default %d)\n", DEF_NBUFFERS);
	printf("  -c NAME=VALUE   set run-time parameter\n");
1201
	printf("  -d 0-5          debugging level (0 is off)\n");
1202 1203 1204 1205 1206 1207
	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 已提交
1208
	printf("  -P              disable system indexes\n");
1209 1210
	printf("  -s              show statistics after each query\n");
	printf("  -S SORT-MEM     set amount of memory for sorts (in kbytes)\n");
1211 1212 1213 1214
	printf("  --help          show this help, then exit\n");
	printf("  --version       output version information, then exit\n");
	printf("\nDeveloper options:\n");
	printf("  -f s|i|n|m|h    forbid use of some plan types\n");
1215 1216
	printf("  -i              do not execute queries\n");
	printf("  -O              allow system table structure changes\n");
1217
	printf("  -t pa|pl|ex     show timings after each query\n");
1218 1219
	printf("  -W NUM          wait NUM seconds to allow attach from a debugger\n");
	printf("\nReport bugs to <pgsql-bugs@postgresql.org>.\n");
1220 1221
}

1222 1223


1224
/* ----------------------------------------------------------------
1225
 * PostgresMain
B
Bruce Momjian 已提交
1226
 *	   postgres main loop -- all backends, interactive or otherwise start here
1227
 *
1228 1229 1230 1231
 * 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.
1232 1233 1234
 * ----------------------------------------------------------------
 */
int
1235
PostgresMain(int argc, char *argv[], const char *username)
1236
{
1237
	int			flag;
B
Bruce Momjian 已提交
1238
	const char *DBName = NULL;
1239
	char	   *potential_DataDir = NULL;
1240
	bool		secure;
1241
	int			errs = 0;
1242
	int			debug_flag = 0;
1243
	GucContext	ctx;
1244
	GucSource	gucsource;
1245
	char	   *tmp;
1246
	int			firstchar;
1247
	StringInfo	input_message;
1248
	bool		send_rfq;
1249

1250
	/*
B
Bruce Momjian 已提交
1251 1252
	 * Catch standard options before doing much else.  This even works on
	 * systems without getopt_long.
1253 1254 1255
	 */
	if (!IsUnderPostmaster && argc > 1)
	{
B
Bruce Momjian 已提交
1256
		if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
1257 1258 1259 1260
		{
			usage(argv[0]);
			exit(0);
		}
B
Bruce Momjian 已提交
1261
		if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
1262 1263 1264 1265
		{
			puts("postgres (PostgreSQL) " PG_VERSION);
			exit(0);
		}
B
Bruce Momjian 已提交
1266
	}
1267

1268 1269 1270 1271 1272 1273 1274
	/*
	 * initialize globals (already done if under postmaster, but not if
	 * standalone; cheap enough to do over)
	 */

	MyProcPid = getpid();

1275 1276 1277 1278 1279
	/*
	 * Fire up essential subsystems: error and memory management
	 *
	 * If we are running under the postmaster, this is done already.
	 */
1280
	if (!IsUnderPostmaster)
1281 1282
		MemoryContextInit();

1283 1284
	set_ps_display("startup");

1285 1286
	SetProcessingMode(InitProcessing);

1287
	/*
1288
	 * Set default values for command-line options.
1289
	 */
1290 1291
	Noversion = false;
	EchoQuery = false;
1292 1293 1294

	if (!IsUnderPostmaster)
	{
1295
		InitializeGUCOptions();
1296
		potential_DataDir = getenv("PGDATA");
1297
	}
1298

1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315
	/* ----------------
	 *	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.
	 * ----------------
	 */

1316 1317 1318
	/* all options are allowed until '-p' */
	secure = true;
	ctx = PGC_POSTMASTER;
1319
	gucsource = PGC_S_ARGV;		/* initial switches came from command line */
1320

1321
	while ((flag = getopt(argc, argv, "A:B:c:CD:d:Eef:FiNOPo:p:S:st:v:W:x:-:")) != -1)
1322 1323
		switch (flag)
		{
M
 
Marc G. Fournier 已提交
1324 1325
			case 'A':
#ifdef USE_ASSERT_CHECKING
1326
				SetConfigOption("debug_assertions", optarg, ctx, gucsource);
M
 
Marc G. Fournier 已提交
1327
#else
B
Bruce Momjian 已提交
1328
				elog(WARNING, "Assert checking is not compiled in");
M
 
Marc G. Fournier 已提交
1329 1330
#endif
				break;
1331

1332
			case 'B':
1333 1334 1335

				/*
				 * specify the size of buffer pool
1336
				 */
1337
				SetConfigOption("shared_buffers", optarg, ctx, gucsource);
1338
				break;
1339

1340
			case 'C':
1341 1342 1343

				/*
				 * don't print version string
1344
				 */
1345
				Noversion = true;
1346
				break;
1347

1348
			case 'D':			/* PGDATA directory */
1349
				if (secure)
1350
					potential_DataDir = optarg;
M
 
Marc G. Fournier 已提交
1351
				break;
1352

1353
			case 'd':			/* debug level */
1354
				{
1355
					debug_flag = atoi(optarg);
1356 1357 1358
					/* Set server debugging level. */
					if (atoi(optarg) != 0)
					{
B
Bruce Momjian 已提交
1359
						char	   *debugstr = palloc(strlen("debug") + strlen(optarg) + 1);
1360 1361

						sprintf(debugstr, "debug%s", optarg);
1362
						SetConfigOption("log_min_messages", debugstr, ctx, gucsource);
1363
						pfree(debugstr);
B
Bruce Momjian 已提交
1364

1365 1366 1367
					}
					else
						/*
1368
						 * -d0 allows user to prevent postmaster debug
1369 1370
						 * from propagating to backend.  It would be nice
						 * to set it to the postgresql.conf value here.
1371
						 */
1372
						SetConfigOption("log_min_messages", "notice",
1373
										ctx, gucsource);
1374
				}
1375
				break;
1376 1377

			case 'E':
1378 1379 1380

				/*
				 * E - echo the query the user entered
1381
				 */
1382
				EchoQuery = true;
1383
				break;
1384 1385

			case 'e':
1386 1387

				/*
1388 1389
				 * Use european date formats.
				 */
1390
				SetConfigOption("datestyle", "euro", ctx, gucsource);
1391
				break;
1392 1393

			case 'F':
1394 1395 1396

				/*
				 * turn off fsync
1397
				 */
1398
				SetConfigOption("fsync", "false", ctx, gucsource);
1399
				break;
1400 1401

			case 'f':
1402 1403 1404

				/*
				 * f - forbid generation of certain plans
1405
				 */
1406
				tmp = NULL;
1407 1408 1409
				switch (optarg[0])
				{
					case 's':	/* seqscan */
1410
						tmp = "enable_seqscan";
1411 1412
						break;
					case 'i':	/* indexscan */
1413
						tmp = "enable_indexscan";
1414 1415
						break;
					case 't':	/* tidscan */
1416
						tmp = "enable_tidscan";
1417 1418
						break;
					case 'n':	/* nestloop */
1419
						tmp = "enable_nestloop";
1420 1421
						break;
					case 'm':	/* mergejoin */
1422
						tmp = "enable_mergejoin";
1423 1424
						break;
					case 'h':	/* hashjoin */
1425
						tmp = "enable_hashjoin";
1426 1427 1428 1429
						break;
					default:
						errs++;
				}
1430
				if (tmp)
1431
					SetConfigOption(tmp, "false", ctx, gucsource);
1432 1433
				break;

1434
			case 'i':
1435
				dontExecute = true;
1436
				break;
1437

1438
			case 'N':
1439 1440 1441

				/*
				 * N - Don't use newline as a query delimiter
1442 1443 1444
				 */
				UseNewLine = 0;
				break;
1445

1446
			case 'O':
1447 1448 1449

				/*
				 * allow system table structure modifications
1450
				 */
1451 1452
				if (secure)		/* XXX safe to allow from client??? */
					allowSystemTableMods = true;
1453 1454
				break;

H
Hiroshi Inoue 已提交
1455
			case 'P':
1456 1457 1458

				/*
				 * ignore system indexes
H
Hiroshi Inoue 已提交
1459 1460 1461 1462 1463
				 */
				if (secure)		/* XXX safe to allow from client??? */
					IgnoreSystemIndexes(true);
				break;

T
Tom Lane 已提交
1464
			case 'o':
1465 1466 1467

				/*
				 * o - send output (stdout and stderr) to the given file
T
Tom Lane 已提交
1468
				 */
1469 1470
				if (secure)
					StrNCpy(OutputFileName, optarg, MAXPGPATH);
T
Tom Lane 已提交
1471 1472
				break;

1473
			case 'p':
1474 1475 1476 1477

				/*
				 * p - special flag passed if backend was forked by a
				 * postmaster.
1478
				 */
1479 1480
				if (secure)
				{
1481
					DBName = strdup(optarg);
B
Bruce Momjian 已提交
1482 1483
					secure = false;		/* subsequent switches are NOT
										 * secure */
1484
					ctx = PGC_BACKEND;
1485
					gucsource = PGC_S_CLIENT;
1486
				}
1487
				break;
1488

1489
			case 'S':
1490 1491 1492

				/*
				 * S - amount of sort memory to use in 1k bytes
1493
				 */
1494
				SetConfigOption("sort_mem", optarg, ctx, gucsource);
1495
				break;
1496 1497

			case 's':
1498 1499 1500

				/*
				 * s - report usage statistics (timings) after each query
1501
				 */
1502
				SetConfigOption("show_statement_stats", "true", ctx, gucsource);
M
 
Marc G. Fournier 已提交
1503 1504
				break;

1505
			case 't':
1506
				/* ---------------
1507 1508 1509 1510 1511 1512 1513 1514 1515
				 *	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.
				 * ----------------
				 */
1516
				tmp = NULL;
1517 1518 1519 1520
				switch (optarg[0])
				{
					case 'p':
						if (optarg[1] == 'a')
B
Rename:  
Bruce Momjian 已提交
1521
							tmp = "log_parser_stats";
1522
						else if (optarg[1] == 'l')
B
Rename:  
Bruce Momjian 已提交
1523
							tmp = "log_planner_stats";
1524 1525 1526 1527
						else
							errs++;
						break;
					case 'e':
1528
						tmp = "show_executor_stats";
1529 1530 1531 1532 1533
						break;
					default:
						errs++;
						break;
				}
1534
				if (tmp)
1535
					SetConfigOption(tmp, "true", ctx, gucsource);
1536 1537
				break;

1538
			case 'v':
1539 1540
				if (secure)
					FrontendProtocol = (ProtocolVersion) atoi(optarg);
1541 1542
				break;

M
 
Marc G. Fournier 已提交
1543
			case 'W':
1544 1545 1546

				/*
				 * wait N seconds to allow attach from a debugger
M
 
Marc G. Fournier 已提交
1547 1548 1549 1550
				 */
				sleep(atoi(optarg));
				break;

1551
			case 'x':
B
Bruce Momjian 已提交
1552
#ifdef NOT_USED					/* planner/xfunc.h */
1553 1554 1555 1556 1557 1558 1559

				/*
				 * control joey hellerstein's expensive function
				 * optimization
				 */
				if (XfuncMode != 0)
				{
B
Bruce Momjian 已提交
1560
					elog(WARNING, "only one -x flag is allowed");
1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577
					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 已提交
1578
					elog(WARNING, "use -x {off,nor,nopull,nopm,pullall,wait}");
1579 1580
					errs++;
				}
1581
#endif
1582
				break;
1583

1584
			case 'c':
1585
			case '-':
1586
				{
B
Bruce Momjian 已提交
1587 1588
					char	   *name,
							   *value;
1589

B
Bruce Momjian 已提交
1590 1591 1592 1593 1594 1595 1596 1597 1598
					ParseLongOption(optarg, &name, &value);
					if (!value)
					{
						if (flag == '-')
							elog(ERROR, "--%s requires argument", optarg);
						else
							elog(ERROR, "-c %s requires argument", optarg);
					}

1599
					SetConfigOption(name, value, ctx, gucsource);
B
Bruce Momjian 已提交
1600 1601 1602 1603 1604
					free(name);
					if (value)
						free(value);
					break;
				}
1605

1606 1607
			default:
				errs++;
T
Tom Lane 已提交
1608
				break;
1609 1610
		}

1611 1612
	/*
	 * -d is not the same as setting
1613
	 * log_min_messages because it enables other
1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626
	 * output options.
	 */
	if (debug_flag >= 1)
		SetConfigOption("log_connections", "true", ctx, gucsource);
	if (debug_flag >= 2)
		SetConfigOption("log_statement", "true", ctx, gucsource);
	if (debug_flag >= 3)
		SetConfigOption("debug_print_parse", "true", ctx, gucsource);
	if (debug_flag >= 4)
		SetConfigOption("debug_print_plan", "true", ctx, gucsource);
	if (debug_flag >= 5)
		SetConfigOption("debug_print_rewritten", "true", ctx, gucsource);

1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646
	/*
	 * Process any additional GUC variable settings passed in startup packet.
	 */
	if (MyProcPort != NULL)
	{
		List   *gucopts = MyProcPort->guc_options;

		while (gucopts)
		{
			char	   *name,
					   *value;

			name = lfirst(gucopts);
			gucopts = lnext(gucopts);
			value = lfirst(gucopts);
			gucopts = lnext(gucopts);
			SetConfigOption(name, value, PGC_BACKEND, PGC_S_CLIENT);
		}
	}

1647 1648 1649
	/*
	 * Post-processing for command line options.
	 */
B
Rename:  
Bruce Momjian 已提交
1650 1651
	if (log_statement_stats &&
		(log_parser_stats || log_planner_stats || log_executor_stats))
1652
	{
B
Bruce Momjian 已提交
1653
		elog(WARNING, "Query statistics are disabled because parser, planner, or executor statistics are on.");
1654
		SetConfigOption("show_statement_stats", "false", ctx, gucsource);
1655 1656
	}

1657
	if (!IsUnderPostmaster)
1658
	{
1659 1660 1661
		if (!potential_DataDir)
		{
			fprintf(stderr, "%s does not know where to find the database system "
1662 1663 1664
			   "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",
1665 1666 1667 1668
					argv[0]);
			proc_exit(1);
		}
		SetDataDir(potential_DataDir);
1669
	}
1670
	Assert(DataDir);
1671 1672

	/*
1673
	 * Set up signal handlers and masks.
1674
	 *
1675
	 * Note that postmaster blocked all signals before forking child process,
B
Bruce Momjian 已提交
1676 1677
	 * so there is no race condition whereby we might receive a signal
	 * before we have set up the handler.
T
Tom Lane 已提交
1678 1679
	 *
	 * Also note: it's best not to use any signals that are SIG_IGNored in
B
Bruce Momjian 已提交
1680
	 * the postmaster.	If such a signal arrives before we are able to
1681
	 * change the handler to non-SIG_IGN, it'll get dropped.  Instead,
B
Bruce Momjian 已提交
1682 1683
	 * make a dummy handler in the postmaster to reserve the signal. (Of
	 * course, this isn't an issue for signals that are locally generated,
1684
	 * such as SIGALRM and SIGPIPE.)
1685
	 */
1686

1687
	pqsignal(SIGHUP, SigHupHandler);	/* set flag to read config file */
B
Bruce Momjian 已提交
1688
	pqsignal(SIGINT, StatementCancelHandler);	/* cancel current query */
1689
	pqsignal(SIGTERM, die);		/* cancel current query and exit */
1690
	pqsignal(SIGQUIT, quickdie);	/* hard crash time */
1691
	pqsignal(SIGALRM, handle_sig_alarm);	/* timeout conditions */
1692 1693 1694 1695 1696

	/*
	 * 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
1697 1698 1699
	 * midst of output during who-knows-what operation...
	 */
	pqsignal(SIGPIPE, SIG_IGN);
B
Bruce Momjian 已提交
1700
	pqsignal(SIGUSR1, SIG_IGN); /* this signal available for use */
1701

1702
	pqsignal(SIGUSR2, Async_NotifyHandler);		/* flush also sinval cache */
1703
	pqsignal(SIGFPE, FloatExceptionHandler);
1704 1705

	/*
B
Bruce Momjian 已提交
1706 1707
	 * Reset some signals that are accepted by postmaster but not by
	 * backend
1708
	 */
1709 1710
	pqsignal(SIGCHLD, SIG_DFL); /* system() requires this on some
								 * platforms */
1711

1712 1713
	pqinitmask();

T
Tom Lane 已提交
1714
	/* We allow SIGQUIT (quickdie) at all times */
1715
#ifdef HAVE_SIGPROCMASK
T
Tom Lane 已提交
1716
	sigdelset(&BlockSig, SIGQUIT);
1717
#else
T
Tom Lane 已提交
1718
	BlockSig &= ~(sigmask(SIGQUIT));
1719 1720
#endif

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

1723

1724
	if (IsUnderPostmaster)
1725
	{
1726 1727 1728
		/* noninteractive case: nothing should be left after switches */
		if (errs || argc != optind || DBName == NULL)
		{
B
Bruce Momjian 已提交
1729
			elog(WARNING, "%s: invalid command line arguments\nTry -? for help.",
1730
				 argv[0]);
B
Bruce Momjian 已提交
1731 1732
			proc_exit(0);		/* not 1, that causes system-wide
								 * restart... */
1733
		}
1734
		BaseInit();
1735
	}
1736
	else
1737
	{
1738 1739 1740
		/* interactive case: database name can be last arg on command line */
		if (errs || argc - optind > 1)
		{
B
Bruce Momjian 已提交
1741
			elog(WARNING, "%s: invalid command line arguments\nTry -? for help.",
1742
				 argv[0]);
1743
			proc_exit(1);
1744 1745 1746
		}
		else if (argc - optind == 1)
			DBName = argv[optind];
1747
		else if ((DBName = username) == NULL)
1748
		{
B
Bruce Momjian 已提交
1749
			elog(WARNING, "%s: user name undefined and no database specified",
1750
				 argv[0]);
1751
			proc_exit(1);
1752
		}
1753

1754 1755 1756 1757 1758 1759 1760 1761
		/*
		 * 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]);

1762
		/*
1763 1764
		 * Validate we have been given a reasonable-looking DataDir (if
		 * under postmaster, assume postmaster did this already).
1765 1766 1767
		 */
		ValidatePgVersion(DataDir);

1768
		/*
1769
		 * Create lockfile for data directory.
1770
		 */
B
Bruce Momjian 已提交
1771
		if (!CreateDataDirLockFile(DataDir, false))
1772
			proc_exit(1);
1773

1774
		XLOGPathInit();
1775
		BaseInit();
1776 1777 1778 1779 1780

		/*
		 * Start up xlog for standalone backend, and register to have it
		 * closed down at exit.
		 */
1781
		StartupXLOG();
1782
		on_shmem_exit(ShutdownXLOG, 0);
1783 1784 1785 1786 1787 1788 1789

		/*
		 * Read any existing FSM cache file, and register to write one out
		 * at exit.
		 */
		LoadFreeSpaceMap();
		on_shmem_exit(DumpFreeSpaceMap, 0);
1790 1791
	}

1792 1793 1794 1795 1796 1797 1798 1799
	/*
	 * Set up additional info.
	 */

#ifdef CYR_RECODE
	SetCharSet();
#endif

1800
	/*
1801 1802 1803 1804 1805
	 * 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.
1806
	 */
1807
	elog(DEBUG2, "InitPostgres");
1808
	InitPostgres(DBName, username);
1809

1810
	SetProcessingMode(NormalProcessing);
1811

1812 1813
	/*
	 * Send this backend's cancellation info to the frontend.
1814
	 */
M
 
Marc G. Fournier 已提交
1815 1816 1817
	if (whereToSendOutput == Remote &&
		PG_PROTOCOL_MAJOR(FrontendProtocol) >= 2)
	{
1818
		StringInfoData buf;
B
Bruce Momjian 已提交
1819

1820
		pq_beginmessage(&buf, 'K');
1821 1822 1823
		pq_sendint(&buf, (int32) MyProcPid, sizeof(int32));
		pq_sendint(&buf, (int32) MyCancelKey, sizeof(int32));
		pq_endmessage(&buf);
M
 
Marc G. Fournier 已提交
1824 1825 1826
		/* Need not flush since ReadyForQuery will do it. */
	}

1827 1828 1829
	if (!IsUnderPostmaster)
	{
		puts("\nPOSTGRES backend interactive interface ");
1830
		puts("$Revision: 1.326 $ $Date: 2003/04/29 22:13:11 $\n");
1831 1832
	}

1833 1834 1835
	/*
	 * Create the memory context we will use in the main loop.
	 *
B
Bruce Momjian 已提交
1836 1837 1838 1839
	 * 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.
1840 1841 1842 1843 1844 1845 1846
	 */
	QueryContext = AllocSetContextCreate(TopMemoryContext,
										 "QueryContext",
										 ALLOCSET_DEFAULT_MINSIZE,
										 ALLOCSET_DEFAULT_INITSIZE,
										 ALLOCSET_DEFAULT_MAXSIZE);

1847 1848 1849 1850 1851 1852 1853
	/* ----------
	 * Tell the statistics collector that we're alive and
	 * to which database we belong.
	 * ----------
	 */
	pgstat_bestart();

1854 1855
	/*
	 * POSTGRES main processing loop begins here
1856
	 *
1857 1858
	 * If an exception is encountered, processing resumes here so we abort
	 * the current transaction and start a new one.
1859 1860 1861 1862
	 */

	if (sigsetjmp(Warn_restart, 1) != 0)
	{
1863
		/*
1864
		 * NOTE: if you are tempted to add more code in this if-block,
B
Bruce Momjian 已提交
1865 1866
		 * consider the probability that it should be in
		 * AbortTransaction() instead.
1867
		 *
1868 1869
		 * Make sure we're not interrupted while cleaning up.  Also forget
		 * any pending QueryCancel request, since we're aborting anyway.
1870 1871
		 * Force InterruptHoldoffCount to a known state in case we elog'd
		 * from inside a holdoff section.
1872 1873 1874
		 */
		ImmediateInterruptOK = false;
		QueryCancelPending = false;
1875 1876
		InterruptHoldoffCount = 1;
		CritSectionCount = 0;	/* should be unnecessary, but... */
1877 1878
		disable_sig_alarm(true);
		QueryCancelPending = false;	/* again in case timeout occurred */
1879
		DisableNotifyInterrupt();
1880
		debug_query_string = NULL;
1881 1882

		/*
1883 1884 1885 1886 1887 1888
		 * 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);
1889

1890
		/* Do the recovery */
1891
		elog(DEBUG1, "AbortCurrentTransaction");
1892
		AbortCurrentTransaction();
1893 1894

		/*
1895 1896
		 * Now return to normal top-level context and clear ErrorContext
		 * for next time.
1897 1898 1899
		 */
		MemoryContextSwitchTo(TopMemoryContext);
		MemoryContextResetAndDeleteChildren(ErrorContext);
1900 1901 1902 1903 1904

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

		/*
1908
		 * Exit interrupt holdoff section we implicitly established above.
1909
		 */
1910
		RESUME_INTERRUPTS();
1911
	}
1912

1913 1914
	Warn_restart_ready = true;	/* we can now handle elog(ERROR) */

1915
	PG_SETMASK(&UnBlockSig);
1916

1917 1918
	send_rfq = true;			/* initially, or after error */

1919 1920
	/*
	 * Non-error queries loop here.
1921 1922 1923 1924
	 */

	for (;;)
	{
1925
		/*
B
Bruce Momjian 已提交
1926 1927
		 * Release storage left over from prior query cycle, and create a
		 * new query input buffer in the cleared QueryContext.
1928 1929 1930 1931
		 */
		MemoryContextSwitchTo(QueryContext);
		MemoryContextResetAndDeleteChildren(QueryContext);

1932
		input_message = makeStringInfo();
1933

1934 1935
		/*
		 * (1) tell the frontend we're ready for a new query.
1936
		 *
1937
		 * Note: this includes fflush()'ing the last of the prior output.
B
Bruce Momjian 已提交
1938
		 */
1939 1940 1941 1942 1943
		if (send_rfq)
		{
			ReadyForQuery(whereToSendOutput);
			send_rfq = false;
		}
B
Bruce Momjian 已提交
1944

1945 1946 1947 1948 1949 1950 1951
		/* ----------
		 * Tell the statistics collector what we've collected
		 * so far.
		 * ----------
		 */
		pgstat_report_tabstat();

1952
		if (IsTransactionBlock())
1953
		{
1954
			set_ps_display("idle in transaction");
1955 1956
			pgstat_report_activity("<IDLE> in transaction");
		}
1957
		else
1958
		{
1959
			set_ps_display("idle");
1960 1961
			pgstat_report_activity("<IDLE>");
		}
1962

1963 1964 1965 1966
		/*
		 * (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.
1967
		 */
B
Bruce Momjian 已提交
1968 1969
		QueryCancelPending = false;		/* forget any earlier CANCEL
										 * signal */
1970 1971 1972

		EnableNotifyInterrupt();

1973 1974 1975 1976 1977 1978
		/* 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();

1979 1980
		/*
		 * (3) read a command (loop blocks here)
1981
		 */
1982
		firstchar = ReadCommand(input_message);
1983

1984 1985
		/*
		 * (4) disable async signal conditions again.
1986
		 */
1987
		ImmediateInterruptOK = false;
B
Bruce Momjian 已提交
1988
		QueryCancelPending = false;		/* forget any CANCEL signal */
1989

1990 1991
		DisableNotifyInterrupt();

1992 1993 1994
		/*
		 * (5) check for any other interesting events that happened while
		 * we slept.
1995 1996 1997 1998 1999 2000 2001
		 */
		if (got_SIGHUP)
		{
			got_SIGHUP = false;
			ProcessConfigFile(PGC_SIGHUP);
		}

2002 2003
		/*
		 * (6) process the command.
2004
		 */
2005 2006
		switch (firstchar)
		{
2007
			case 'Q':			/* simple query */
2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018
				{
					/*
					 * Process the query string.
					 *
					 * Note: transaction command start/end is now done within
					 * pg_exec_query_string(), not here.
					 */
					const char *query_string = pq_getmsgstring(input_message);

					if (log_statement_stats)
						ResetUsage();
2019

2020
					pgstat_report_activity(query_string);
2021

2022 2023 2024
					pg_exec_query_string(query_string,
										 whereToSendOutput,
										 QueryContext);
2025

2026 2027
					if (log_statement_stats)
						ShowUsage("QUERY STATISTICS");
2028

2029 2030
					send_rfq = true;
				}
2031 2032 2033 2034
				break;

			case 'F':			/* fastpath function call */
				/* Tell the collector what we're doing */
2035 2036
				pgstat_report_activity("<FASTPATH> function call");

2037
				/* start an xact for this function invocation */
2038
				start_xact_command();
2039

2040
				if (HandleFunctionRequest(input_message) == EOF)
2041 2042
				{
					/* lost frontend connection during F message input */
B
Bruce Momjian 已提交
2043

2044
					/*
B
Bruce Momjian 已提交
2045 2046
					 * Reset whereToSendOutput to prevent elog from
					 * attempting to send any more messages to client.
2047 2048 2049 2050
					 */
					if (whereToSendOutput == Remote)
						whereToSendOutput = None;

2051
					proc_exit(0);
2052
				}
2053 2054

				/* commit the function-invocation transaction */
2055
				finish_xact_command(false);
2056

2057
				send_rfq = true;
2058 2059
				break;

2060
				/*
B
Bruce Momjian 已提交
2061 2062 2063
				 * 'X' means that the frontend is closing down the socket.
				 * EOF means unexpected loss of frontend connection.
				 * Either way, perform normal shutdown.
2064 2065
				 */
			case 'X':
2066
			case EOF:
B
Bruce Momjian 已提交
2067

2068 2069 2070 2071 2072 2073
				/*
				 * Reset whereToSendOutput to prevent elog from attempting
				 * to send any more messages to client.
				 */
				if (whereToSendOutput == Remote)
					whereToSendOutput = None;
B
Bruce Momjian 已提交
2074

2075 2076
				/*
				 * NOTE: if you are tempted to add more code here, DON'T!
B
Bruce Momjian 已提交
2077 2078
				 * Whatever you had in mind to do should be set up as an
				 * on_proc_exit or on_shmem_exit callback, instead.
2079 2080 2081 2082
				 * Otherwise it will fail to be called during other
				 * backend-shutdown scenarios.
				 */
				proc_exit(0);
2083

2084 2085 2086 2087 2088 2089 2090 2091 2092 2093
			case 'd':				/* copy data */
			case 'c':				/* copy done */
			case 'f':				/* copy fail */
				/*
				 * Accept but ignore these messages, per protocol spec;
				 * we probably got here because a COPY failed, and the
				 * frontend is still sending data.
				 */
				break;

2094
			default:
2095
				elog(FATAL, "Socket command type %c unknown", firstchar);
2096 2097
		}

2098
#ifdef MEMORY_CONTEXT_CHECKING
B
Bruce Momjian 已提交
2099

2100
		/*
2101 2102
		 * Check all memory after each backend loop.  This is a rather
		 * weird place to do it, perhaps.
2103
		 */
B
Bruce Momjian 已提交
2104
		MemoryContextCheck(TopMemoryContext);
2105
#endif
2106
	}							/* end of input-reading loop */
2107

2108 2109
	/* can't get here because the above loop never exits */
	Assert(false);
2110

2111
	return 1;					/* keep compiler quiet */
2112 2113
}

2114
#ifndef HAVE_GETRUSAGE
B
Bruce Momjian 已提交
2115 2116
#include "rusagestub.h"
#else
2117
#include <sys/resource.h>
2118
#endif   /* HAVE_GETRUSAGE */
2119

2120 2121
struct rusage Save_r;
struct timeval Save_t;
2122 2123

void
2124
ResetUsage(void)
2125
{
2126
	getrusage(RUSAGE_SELF, &Save_r);
2127
	gettimeofday(&Save_t, NULL);
2128
	ResetBufferUsage();
2129
	/* ResetTupleCount(); */
2130 2131 2132
}

void
2133
ShowUsage(const char *title)
2134
{
2135
	StringInfoData str;
2136 2137 2138 2139
	struct timeval user,
				sys;
	struct timeval elapse_t;
	struct rusage r;
B
Bruce Momjian 已提交
2140
	char	   *bufusage;
2141 2142

	getrusage(RUSAGE_SELF, &r);
2143
	gettimeofday(&elapse_t, NULL);
2144 2145
	memcpy((char *) &user, (char *) &r.ru_utime, sizeof(user));
	memcpy((char *) &sys, (char *) &r.ru_stime, sizeof(sys));
2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169
	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.
	 */
2170
	initStringInfo(&str);
2171

2172 2173
	appendStringInfo(&str, "! system usage stats:\n");
	appendStringInfo(&str,
2174
			"!\t%ld.%06ld elapsed %ld.%06ld user %ld.%06ld system sec\n",
2175 2176 2177 2178 2179 2180
					 (long) (elapse_t.tv_sec - Save_t.tv_sec),
					 (long) (elapse_t.tv_usec - Save_t.tv_usec),
					 (long) (r.ru_utime.tv_sec - Save_r.ru_utime.tv_sec),
					 (long) (r.ru_utime.tv_usec - Save_r.ru_utime.tv_usec),
					 (long) (r.ru_stime.tv_sec - Save_r.ru_stime.tv_sec),
					 (long) (r.ru_stime.tv_usec - Save_r.ru_stime.tv_usec));
2181
	appendStringInfo(&str,
B
Bruce Momjian 已提交
2182
					 "!\t[%ld.%06ld user %ld.%06ld sys total]\n",
2183 2184 2185 2186
					 (long) user.tv_sec,
					 (long) user.tv_usec,
					 (long) sys.tv_sec,
					 (long) sys.tv_usec);
2187
/* BeOS has rusage but only has some fields, and not these... */
2188
#if defined(HAVE_GETRUSAGE)
2189
	appendStringInfo(&str,
B
Bruce Momjian 已提交
2190 2191
					 "!\t%ld/%ld [%ld/%ld] filesystem blocks in/out\n",
					 r.ru_inblock - Save_r.ru_inblock,
2192
	/* they only drink coffee at dec */
B
Bruce Momjian 已提交
2193 2194
					 r.ru_oublock - Save_r.ru_oublock,
					 r.ru_inblock, r.ru_oublock);
2195
	appendStringInfo(&str,
2196
		  "!\t%ld/%ld [%ld/%ld] page faults/reclaims, %ld [%ld] swaps\n",
B
Bruce Momjian 已提交
2197 2198 2199 2200 2201
					 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);
2202
	appendStringInfo(&str,
2203
	 "!\t%ld [%ld] signals rcvd, %ld/%ld [%ld/%ld] messages rcvd/sent\n",
B
Bruce Momjian 已提交
2204 2205 2206 2207 2208
					 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);
2209
	appendStringInfo(&str,
2210
		 "!\t%ld/%ld [%ld/%ld] voluntary/involuntary context switches\n",
B
Bruce Momjian 已提交
2211 2212 2213
					 r.ru_nvcsw - Save_r.ru_nvcsw,
					 r.ru_nivcsw - Save_r.ru_nivcsw,
					 r.ru_nvcsw, r.ru_nivcsw);
2214
#endif   /* HAVE_GETRUSAGE */
2215 2216

	bufusage = ShowBufferUsage();
2217
	appendStringInfo(&str, "! buffer usage stats:\n%s", bufusage);
2218 2219 2220
	pfree(bufusage);

	/* remove trailing newline */
B
Bruce Momjian 已提交
2221
	if (str.data[str.len - 1] == '\n')
2222 2223
		str.data[--str.len] = '\0';

2224
	elog(LOG, "%s\n%s", title, str.data);
2225 2226

	pfree(str.data);
2227
}
M
 
Marc G. Fournier 已提交
2228

2229 2230 2231 2232 2233 2234 2235 2236 2237 2238
/* ----------------------------------------------------------------
 *		CreateCommandTag
 *
 *		utility to get a string representation of the
 *		command operation.
 * ----------------------------------------------------------------
 */
static const char *
CreateCommandTag(Node *parsetree)
{
B
Bruce Momjian 已提交
2239
	const char *tag;
2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262

	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;

2263
				switch (stmt->kind)
2264
				{
2265
					case TRANS_STMT_BEGIN:
2266 2267 2268
						tag = "BEGIN";
						break;

2269
					case TRANS_STMT_START:
2270 2271 2272
						tag = "START TRANSACTION";
						break;

2273
					case TRANS_STMT_COMMIT:
2274 2275 2276
						tag = "COMMIT";
						break;

2277
					case TRANS_STMT_ROLLBACK:
2278 2279 2280 2281 2282 2283 2284 2285 2286 2287
						tag = "ROLLBACK";
						break;

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

2288 2289 2290 2291
		case T_DeclareCursorStmt:
			tag = "DECLARE CURSOR";
			break;

2292
		case T_ClosePortalStmt:
2293
			tag = "CLOSE CURSOR";
2294 2295 2296 2297 2298
			break;

		case T_FetchStmt:
			{
				FetchStmt  *stmt = (FetchStmt *) parsetree;
B
Bruce Momjian 已提交
2299

2300 2301 2302 2303
				tag = (stmt->ismove) ? "MOVE" : "FETCH";
			}
			break;

2304
		case T_CreateDomainStmt:
2305
			tag = "CREATE DOMAIN";
B
Bruce Momjian 已提交
2306 2307
			break;

2308
		case T_CreateSchemaStmt:
2309
			tag = "CREATE SCHEMA";
2310 2311
			break;

2312
		case T_CreateStmt:
2313
			tag = "CREATE TABLE";
2314 2315 2316
			break;

		case T_DropStmt:
2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336
			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;
2337
				case DROP_CONVERSION:
2338 2339 2340 2341
					tag = "DROP CONVERSION";
					break;
				case DROP_SCHEMA:
					tag = "DROP SCHEMA";
2342
					break;
2343 2344 2345
				default:
					tag = "???";
			}
2346 2347 2348
			break;

		case T_TruncateStmt:
2349
			tag = "TRUNCATE TABLE";
2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360
			break;

		case T_CommentStmt:
			tag = "COMMENT";
			break;

		case T_CopyStmt:
			tag = "COPY";
			break;

		case T_RenameStmt:
B
Bruce Momjian 已提交
2361
			if (((RenameStmt *) parsetree)->renameType == RENAME_TRIGGER)
2362 2363 2364
				tag = "ALTER TRIGGER";
			else
				tag = "ALTER TABLE";
2365 2366 2367
			break;

		case T_AlterTableStmt:
2368
			tag = "ALTER TABLE";
2369 2370
			break;

B
Bruce Momjian 已提交
2371 2372 2373 2374
		case T_AlterDomainStmt:
			tag = "ALTER DOMAIN";
			break;

2375 2376 2377
		case T_GrantStmt:
			{
				GrantStmt  *stmt = (GrantStmt *) parsetree;
B
Bruce Momjian 已提交
2378

2379 2380 2381 2382 2383
				tag = (stmt->is_grant) ? "GRANT" : "REVOKE";
			}
			break;

		case T_DefineStmt:
2384
			switch (((DefineStmt *) parsetree)->kind)
2385
			{
2386
				case DEFINE_STMT_AGGREGATE:
2387 2388
					tag = "CREATE AGGREGATE";
					break;
2389
				case DEFINE_STMT_OPERATOR:
2390 2391
					tag = "CREATE OPERATOR";
					break;
2392
				case DEFINE_STMT_TYPE:
2393 2394 2395 2396 2397
					tag = "CREATE TYPE";
					break;
				default:
					tag = "???";
			}
2398 2399
			break;

B
Bruce Momjian 已提交
2400 2401 2402 2403
		case T_CompositeTypeStmt:
			tag = "CREATE TYPE";
			break;

2404 2405
		case T_ViewStmt:
			tag = "CREATE VIEW";
2406 2407
			break;

2408 2409
		case T_CreateFunctionStmt:
			tag = "CREATE FUNCTION";
2410 2411
			break;

2412 2413
		case T_IndexStmt:
			tag = "CREATE INDEX";
2414 2415
			break;

2416 2417
		case T_RuleStmt:
			tag = "CREATE RULE";
2418 2419 2420
			break;

		case T_CreateSeqStmt:
2421
			tag = "CREATE SEQUENCE";
2422 2423
			break;

B
Bruce Momjian 已提交
2424 2425 2426 2427
		case T_AlterSeqStmt:
			tag = "ALTER SEQUENCE";
			break;

2428
		case T_RemoveAggrStmt:
2429
			tag = "DROP AGGREGATE";
2430 2431 2432
			break;

		case T_RemoveFuncStmt:
2433
			tag = "DROP FUNCTION";
2434 2435 2436
			break;

		case T_RemoveOperStmt:
2437
			tag = "DROP OPERATOR";
2438 2439 2440 2441 2442 2443
			break;

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

2444 2445 2446 2447
		case T_AlterDatabaseSetStmt:
			tag = "ALTER DATABASE";
			break;

2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483
		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:
2484
			tag = "SET";
2485 2486 2487
			break;

		case T_VariableShowStmt:
2488
			tag = "SHOW";
2489 2490 2491
			break;

		case T_VariableResetStmt:
2492
			tag = "RESET";
2493 2494 2495
			break;

		case T_CreateTrigStmt:
2496
			tag = "CREATE TRIGGER";
2497 2498
			break;

2499
		case T_DropPropertyStmt:
2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510
			switch (((DropPropertyStmt *) parsetree)->removeType)
			{
				case DROP_TRIGGER:
					tag = "DROP TRIGGER";
					break;
				case DROP_RULE:
					tag = "DROP RULE";
					break;
				default:
					tag = "???";
			}
2511 2512 2513
			break;

		case T_CreatePLangStmt:
2514
			tag = "CREATE LANGUAGE";
2515 2516 2517
			break;

		case T_DropPLangStmt:
2518
			tag = "DROP LANGUAGE";
2519 2520 2521 2522 2523 2524 2525 2526 2527 2528
			break;

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

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

2529 2530 2531 2532
		case T_AlterUserSetStmt:
			tag = "ALTER USER";
			break;

2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564
		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;

2565 2566 2567 2568
		case T_CreateConversionStmt:
			tag = "CREATE CONVERSION";
			break;

2569 2570 2571 2572 2573 2574 2575 2576
		case T_CreateCastStmt:
			tag = "CREATE CAST";
			break;

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

2577 2578 2579 2580 2581 2582 2583 2584
		case T_CreateOpClassStmt:
			tag = "CREATE OPERATOR CLASS";
			break;

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

2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596
		case T_PrepareStmt:
			tag = "PREPARE";
			break;

		case T_ExecuteStmt:
			tag = "EXECUTE";
			break;

		case T_DeallocateStmt:
			tag = "DEALLOCATE";
			break;

2597
		default:
2598
			elog(LOG, "CreateCommandTag: unknown parse node type %d",
2599 2600 2601 2602 2603 2604 2605
				 nodeTag(parsetree));
			tag = "???";
			break;
	}

	return tag;
}