explain.c 30.3 KB
Newer Older
1 2
/*-------------------------------------------------------------------------
 *
3
 * explain.c
4
 *	  Explain query execution plans
5
 *
6
 * Portions Copyright (c) 1996-2007, PostgreSQL Global Development Group
B
Add:  
Bruce Momjian 已提交
7
 * Portions Copyright (c) 1994-5, Regents of the University of California
8
 *
9
 * IDENTIFICATION
10
 *	  $PostgreSQL: pgsql/src/backend/commands/explain.c,v 1.165 2007/08/15 21:39:50 tgl Exp $
11
 *
12
 *-------------------------------------------------------------------------
13
 */
14
#include "postgres.h"
M
Marc G. Fournier 已提交
15

16
#include "access/xact.h"
17
#include "catalog/pg_constraint.h"
18
#include "catalog/pg_type.h"
19
#include "commands/explain.h"
20
#include "commands/prepare.h"
21
#include "commands/trigger.h"
22
#include "executor/instrument.h"
B
Bruce Momjian 已提交
23
#include "nodes/print.h"
24
#include "optimizer/clauses.h"
25
#include "optimizer/planner.h"
26
#include "optimizer/var.h"
B
Bruce Momjian 已提交
27
#include "parser/parsetree.h"
28
#include "rewrite/rewriteHandler.h"
29
#include "tcop/tcopprot.h"
30
#include "utils/builtins.h"
31
#include "utils/guc.h"
32
#include "utils/lsyscache.h"
33
#include "utils/tuplesort.h"
34

35

36 37 38 39 40 41
/* Hook for plugins to get control in ExplainOneQuery() */
ExplainOneQuery_hook_type ExplainOneQuery_hook = NULL;
/* Hook for plugins to get control in explain_get_index_name() */
explain_get_index_name_hook_type explain_get_index_name_hook = NULL;


42 43 44
typedef struct ExplainState
{
	/* options */
45 46
	bool		printNodes;		/* do nodeToString() too */
	bool		printAnalyze;	/* print actual times */
47
	/* other states */
48
	PlannedStmt *pstmt;			/* top of plan */
49
	List	   *rtable;			/* range table */
50
} ExplainState;
51

52 53
static void ExplainOneQuery(Query *query, ExplainStmt *stmt,
							const char *queryString,
54
							ParamListInfo params, TupOutputState *tstate);
55 56
static void report_triggers(ResultRelInfo *rInfo, bool show_relname,
							StringInfo buf);
57
static double elapsed_time(instr_time *starttime);
58
static void explain_outNode(StringInfo str,
59
				Plan *plan, PlanState *planstate,
B
Bruce Momjian 已提交
60 61
				Plan *outer_plan,
				int indent, ExplainState *es);
62
static void show_scan_qual(List *qual, const char *qlabel,
63
			   int scanrelid, Plan *outer_plan, Plan *inner_plan,
B
Bruce Momjian 已提交
64
			   StringInfo str, int indent, ExplainState *es);
65
static void show_upper_qual(List *qual, const char *qlabel, Plan *plan,
B
Bruce Momjian 已提交
66
				StringInfo str, int indent, ExplainState *es);
67
static void show_sort_keys(Plan *sortplan, int nkeys, AttrNumber *keycols,
B
Bruce Momjian 已提交
68 69
			   const char *qlabel,
			   StringInfo str, int indent, ExplainState *es);
70 71
static void show_sort_info(SortState *sortstate,
			   StringInfo str, int indent, ExplainState *es);
72 73
static const char *explain_get_index_name(Oid indexId);

74 75 76

/*
 * ExplainQuery -
77
 *	  execute an EXPLAIN command
78 79
 */
void
80 81
ExplainQuery(ExplainStmt *stmt, const char *queryString,
			 ParamListInfo params, DestReceiver *dest)
82
{
83 84
	Oid		   *param_types;
	int			num_params;
85
	TupOutputState *tstate;
B
Bruce Momjian 已提交
86
	List	   *rewritten;
87
	ListCell   *l;
88

89 90 91
	/* Convert parameter type data to the form parser wants */
	getParamListTypes(params, &param_types, &num_params);

92
	/*
93 94 95 96
	 * Run parse analysis and rewrite.  Note this also acquires sufficient
	 * locks on the source table(s).
	 *
	 * Because the parser and planner tend to scribble on their input, we
B
Bruce Momjian 已提交
97
	 * make a preliminary copy of the source querytree.  This prevents
98 99
	 * problems in the case that the EXPLAIN is in a portal or plpgsql
	 * function and is executed repeatedly.  (See also the same hack in
100
	 * DECLARE CURSOR and PREPARE.)  XXX FIXME someday.
101
	 */
102 103
	rewritten = pg_analyze_and_rewrite((Node *) copyObject(stmt->query),
									   queryString, param_types, num_params);
104

105
	/* prepare for projection of tuples */
106
	tstate = begin_tup_output_tupdesc(dest, ExplainResultDesc(stmt));
107

108
	if (rewritten == NIL)
109
	{
110 111
		/* In the case of an INSTEAD NOTHING, tell at least that */
		do_text_output_oneline(tstate, "Query rewrites to nothing");
112
	}
113
	else
B
Bruce Momjian 已提交
114
	{
115 116
		/* Explain every plan */
		foreach(l, rewritten)
117
		{
118 119
			ExplainOneQuery((Query *) lfirst(l), stmt,
							queryString, params, tstate);
120 121 122
			/* put a blank line between plans */
			if (lnext(l) != NULL)
				do_text_output_oneline(tstate, "");
123
		}
B
Bruce Momjian 已提交
124 125
	}

126
	end_tup_output(tstate);
B
Bruce Momjian 已提交
127 128
}

129 130 131 132 133 134 135 136 137 138 139 140
/*
 * ExplainResultDesc -
 *	  construct the result tupledesc for an EXPLAIN
 */
TupleDesc
ExplainResultDesc(ExplainStmt *stmt)
{
	TupleDesc	tupdesc;

	/* need a tuple descriptor representing a single TEXT column */
	tupdesc = CreateTemplateTupleDesc(1, false);
	TupleDescInitEntry(tupdesc, (AttrNumber) 1, "QUERY PLAN",
141
					   TEXTOID, -1, 0);
142 143 144
	return tupdesc;
}

B
Bruce Momjian 已提交
145 146
/*
 * ExplainOneQuery -
147
 *	  print out the execution plan for one Query
B
Bruce Momjian 已提交
148 149
 */
static void
150
ExplainOneQuery(Query *query, ExplainStmt *stmt, const char *queryString,
151
				ParamListInfo params, TupOutputState *tstate)
B
Bruce Momjian 已提交
152
{
153 154 155
	/* planner will not cope with utility statements */
	if (query->commandType == CMD_UTILITY)
	{
156 157 158
		ExplainOneUtility(query->utilityStmt, stmt,
						  queryString, params, tstate);
		return;
159 160
	}

161 162 163 164 165 166
	/* if an advisor plugin is present, let it manage things */
	if (ExplainOneQuery_hook)
		(*ExplainOneQuery_hook) (query, stmt, queryString, params, tstate);
	else
	{
		PlannedStmt *plan;
167

168 169
		/* plan the query */
		plan = planner(query, 0, params);
170

171 172 173
		/* run it (if needed) and produce output */
		ExplainOnePlan(plan, params, stmt, tstate);
	}
174 175
}

176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
/*
 * ExplainOneUtility -
 *	  print out the execution plan for one utility statement
 *	  (In general, utility statements don't have plans, but there are some
 *	  we treat as special cases)
 *
 * This is exported because it's called back from prepare.c in the
 * EXPLAIN EXECUTE case
 */
void
ExplainOneUtility(Node *utilityStmt, ExplainStmt *stmt,
				  const char *queryString, ParamListInfo params,
				  TupOutputState *tstate)
{
	if (utilityStmt == NULL)
		return;

193
	if (IsA(utilityStmt, ExecuteStmt))
194 195 196 197 198 199 200 201 202
		ExplainExecuteQuery((ExecuteStmt *) utilityStmt, stmt,
							queryString, params, tstate);
	else if (IsA(utilityStmt, NotifyStmt))
		do_text_output_oneline(tstate, "NOTIFY");
	else
		do_text_output_oneline(tstate,
							   "Utility statements have no plan structure");
}

203 204 205 206 207
/*
 * ExplainOnePlan -
 *		given a planned query, execute it if needed, and then print
 *		EXPLAIN output
 *
208 209 210 211 212
 * Since we ignore any DeclareCursorStmt that might be attached to the query,
 * if you say EXPLAIN ANALYZE DECLARE CURSOR then we'll actually run the
 * query.  This is different from pre-8.3 behavior but seems more useful than
 * not running the query.  No cursor will be created, however.
 *
213
 * This is exported because it's called back from prepare.c in the
214 215
 * EXPLAIN EXECUTE case, and because an index advisor plugin would need
 * to call it.
216 217
 */
void
218 219
ExplainOnePlan(PlannedStmt *plannedstmt, ParamListInfo params,
			   ExplainStmt *stmt, TupOutputState *tstate)
220
{
221
	QueryDesc  *queryDesc;
B
Bruce Momjian 已提交
222
	instr_time	starttime;
223 224
	double		totaltime = 0;
	ExplainState *es;
225
	StringInfoData buf;
226
	int			eflags;
227

228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
	/*
	 * Update snapshot command ID to ensure this query sees results of any
	 * previously executed queries.  (It's a bit cheesy to modify
	 * ActiveSnapshot without making a copy, but for the limited ways in which
	 * EXPLAIN can be invoked, I think it's OK, because the active snapshot
	 * shouldn't be shared with anything else anyway.)
	 */
	ActiveSnapshot->curcid = GetCurrentCommandId();

	/* Create a QueryDesc requesting no output */
	queryDesc = CreateQueryDesc(plannedstmt,
								ActiveSnapshot, InvalidSnapshot,
								None_Receiver, params,
								stmt->analyze);

243
	INSTR_TIME_SET_CURRENT(starttime);
244

245 246 247 248
	/* If analyzing, we need to cope with queued triggers */
	if (stmt->analyze)
		AfterTriggerBeginQuery();

249 250 251 252 253 254
	/* Select execution options */
	if (stmt->analyze)
		eflags = 0;				/* default run-to-completion flags */
	else
		eflags = EXEC_FLAG_EXPLAIN_ONLY;

255
	/* call ExecutorStart to prepare the plan for execution */
256
	ExecutorStart(queryDesc, eflags);
257

258
	/* Execute the plan for statistics if asked for */
259
	if (stmt->analyze)
260
	{
261 262
		/* run the plan */
		ExecutorRun(queryDesc, ForwardScanDirection, 0L);
263

264 265
		/* We can't clean up 'till we're done printing the stats... */
		totaltime += elapsed_time(&starttime);
266 267
	}

268
	es = (ExplainState *) palloc0(sizeof(ExplainState));
B
Bruce Momjian 已提交
269

270 271
	es->printNodes = stmt->verbose;
	es->printAnalyze = stmt->analyze;
272
	es->pstmt = queryDesc->plannedstmt;
273
	es->rtable = queryDesc->plannedstmt->rtable;
274 275

	if (es->printNodes)
276
	{
277
		char	   *s;
278
		char	   *f;
279

280
		s = nodeToString(queryDesc->plannedstmt->planTree);
281 282
		if (s)
		{
283 284 285 286
			if (Explain_pretty_print)
				f = pretty_format_node_dump(s);
			else
				f = format_node_dump(s);
287
			pfree(s);
288 289
			do_text_output_multiline(tstate, f);
			pfree(f);
B
Bruce Momjian 已提交
290
			do_text_output_oneline(tstate, ""); /* separator line */
291 292
		}
	}
293

294
	initStringInfo(&buf);
295 296
	explain_outNode(&buf,
					queryDesc->plannedstmt->planTree, queryDesc->planstate,
297
					NULL, 0, es);
298 299

	/*
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
	 * If we ran the command, run any AFTER triggers it queued.  (Note this
	 * will not include DEFERRED triggers; since those don't run until end of
	 * transaction, we can't measure them.)  Include into total runtime.
	 */
	if (stmt->analyze)
	{
		INSTR_TIME_SET_CURRENT(starttime);
		AfterTriggerEndQuery(queryDesc->estate);
		totaltime += elapsed_time(&starttime);
	}

	/* Print info about runtime of triggers */
	if (es->printAnalyze)
	{
		ResultRelInfo *rInfo;
315
		bool		show_relname;
B
Bruce Momjian 已提交
316
		int			numrels = queryDesc->estate->es_num_result_relations;
317
		List	   *targrels = queryDesc->estate->es_trig_target_relations;
B
Bruce Momjian 已提交
318
		int			nr;
319
		ListCell   *l;
320

321
		show_relname = (numrels > 1 || targrels != NIL);
322 323
		rInfo = queryDesc->estate->es_result_relations;
		for (nr = 0; nr < numrels; rInfo++, nr++)
324 325 326
			report_triggers(rInfo, show_relname, &buf);

		foreach(l, targrels)
327
		{
328 329
			rInfo = (ResultRelInfo *) lfirst(l);
			report_triggers(rInfo, show_relname, &buf);
330 331 332 333
		}
	}

	/*
B
Bruce Momjian 已提交
334 335
	 * Close down the query and free resources.  Include time for this in the
	 * total runtime (although it should be pretty minimal).
336
	 */
337
	INSTR_TIME_SET_CURRENT(starttime);
338

339
	ExecutorEnd(queryDesc);
340

341 342
	FreeQueryDesc(queryDesc);

343 344 345
	/* We need a CCI just in case query expanded to multiple plans */
	if (stmt->analyze)
		CommandCounterIncrement();
346 347 348

	totaltime += elapsed_time(&starttime);

349
	if (stmt->analyze)
350
		appendStringInfo(&buf, "Total runtime: %.3f ms\n",
351
						 1000.0 * totaltime);
352
	do_text_output_multiline(tstate, buf.data);
353

354
	pfree(buf.data);
B
Bruce Momjian 已提交
355
	pfree(es);
356 357
}

358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
/*
 * report_triggers -
 *		report execution stats for a single relation's triggers
 */
static void
report_triggers(ResultRelInfo *rInfo, bool show_relname, StringInfo buf)
{
	int			nt;

	if (!rInfo->ri_TrigDesc || !rInfo->ri_TrigInstrument)
		return;
	for (nt = 0; nt < rInfo->ri_TrigDesc->numtriggers; nt++)
	{
		Trigger    *trig = rInfo->ri_TrigDesc->triggers + nt;
		Instrumentation *instr = rInfo->ri_TrigInstrument + nt;
		char	   *conname;

		/* Must clean up instrumentation state */
		InstrEndLoop(instr);

		/*
		 * We ignore triggers that were never invoked; they likely
		 * aren't relevant to the current query type.
		 */
		if (instr->ntuples == 0)
			continue;

		if (OidIsValid(trig->tgconstraint) &&
			(conname = get_constraint_name(trig->tgconstraint)) != NULL)
		{
			appendStringInfo(buf, "Trigger for constraint %s", conname);
			pfree(conname);
		}
		else
			appendStringInfo(buf, "Trigger %s", trig->tgname);

		if (show_relname)
			appendStringInfo(buf, " on %s",
							 RelationGetRelationName(rInfo->ri_RelationDesc));

		appendStringInfo(buf, ": time=%.3f calls=%.0f\n",
						 1000.0 * instr->total, instr->ntuples);
	}
}

403
/* Compute elapsed time in seconds since given timestamp */
404
static double
405
elapsed_time(instr_time *starttime)
406
{
B
Bruce Momjian 已提交
407
	instr_time	endtime;
408

409
	INSTR_TIME_SET_CURRENT(endtime);
410

411
#ifndef WIN32
412 413 414 415 416 417 418
	endtime.tv_sec -= starttime->tv_sec;
	endtime.tv_usec -= starttime->tv_usec;
	while (endtime.tv_usec < 0)
	{
		endtime.tv_usec += 1000000;
		endtime.tv_sec--;
	}
B
Bruce Momjian 已提交
419
#else							/* WIN32 */
420 421 422 423
	endtime.QuadPart -= starttime->QuadPart;
#endif

	return INSTR_TIME_GET_DOUBLE(endtime);
424
}
425 426 427

/*
 * explain_outNode -
428 429
 *	  converts a Plan node into ascii string and appends it to 'str'
 *
430 431 432 433
 * planstate points to the executor state node corresponding to the plan node.
 * We need this to get at the instrumentation data (if any) as well as the
 * list of subplans.
 *
434 435 436
 * outer_plan, if not null, references another plan node that is the outer
 * side of a join with the current node.  This is only interesting for
 * deciphering runtime keys of an inner indexscan.
437 438
 */
static void
439
explain_outNode(StringInfo str,
440
				Plan *plan, PlanState *planstate,
441
				Plan *outer_plan,
442
				int indent, ExplainState *es)
443
{
B
Bruce Momjian 已提交
444 445
	char	   *pname;
	int			i;
446 447 448

	if (plan == NULL)
	{
449
		appendStringInfoChar(str, '\n');
450 451 452 453 454
		return;
	}

	switch (nodeTag(plan))
	{
455 456 457 458 459 460
		case T_Result:
			pname = "Result";
			break;
		case T_Append:
			pname = "Append";
			break;
461 462 463 464 465 466
		case T_BitmapAnd:
			pname = "BitmapAnd";
			break;
		case T_BitmapOr:
			pname = "BitmapOr";
			break;
467
		case T_NestLoop:
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
			switch (((NestLoop *) plan)->join.jointype)
			{
				case JOIN_INNER:
					pname = "Nested Loop";
					break;
				case JOIN_LEFT:
					pname = "Nested Loop Left Join";
					break;
				case JOIN_FULL:
					pname = "Nested Loop Full Join";
					break;
				case JOIN_RIGHT:
					pname = "Nested Loop Right Join";
					break;
				case JOIN_IN:
					pname = "Nested Loop IN Join";
					break;
				default:
					pname = "Nested Loop ??? Join";
					break;
			}
489 490
			break;
		case T_MergeJoin:
491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511
			switch (((MergeJoin *) plan)->join.jointype)
			{
				case JOIN_INNER:
					pname = "Merge Join";
					break;
				case JOIN_LEFT:
					pname = "Merge Left Join";
					break;
				case JOIN_FULL:
					pname = "Merge Full Join";
					break;
				case JOIN_RIGHT:
					pname = "Merge Right Join";
					break;
				case JOIN_IN:
					pname = "Merge IN Join";
					break;
				default:
					pname = "Merge ??? Join";
					break;
			}
512 513
			break;
		case T_HashJoin:
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
			switch (((HashJoin *) plan)->join.jointype)
			{
				case JOIN_INNER:
					pname = "Hash Join";
					break;
				case JOIN_LEFT:
					pname = "Hash Left Join";
					break;
				case JOIN_FULL:
					pname = "Hash Full Join";
					break;
				case JOIN_RIGHT:
					pname = "Hash Right Join";
					break;
				case JOIN_IN:
					pname = "Hash IN Join";
					break;
				default:
					pname = "Hash ??? Join";
					break;
			}
535 536 537 538 539 540 541
			break;
		case T_SeqScan:
			pname = "Seq Scan";
			break;
		case T_IndexScan:
			pname = "Index Scan";
			break;
542 543 544 545 546 547
		case T_BitmapIndexScan:
			pname = "Bitmap Index Scan";
			break;
		case T_BitmapHeapScan:
			pname = "Bitmap Heap Scan";
			break;
548 549 550 551 552 553
		case T_TidScan:
			pname = "Tid Scan";
			break;
		case T_SubqueryScan:
			pname = "Subquery Scan";
			break;
554 555 556
		case T_FunctionScan:
			pname = "Function Scan";
			break;
557 558 559
		case T_ValuesScan:
			pname = "Values Scan";
			break;
560 561 562
		case T_Material:
			pname = "Materialize";
			break;
563 564 565 566 567 568 569
		case T_Sort:
			pname = "Sort";
			break;
		case T_Group:
			pname = "Group";
			break;
		case T_Agg:
570 571 572 573 574 575 576 577 578 579 580 581 582 583 584
			switch (((Agg *) plan)->aggstrategy)
			{
				case AGG_PLAIN:
					pname = "Aggregate";
					break;
				case AGG_SORTED:
					pname = "GroupAggregate";
					break;
				case AGG_HASHED:
					pname = "HashAggregate";
					break;
				default:
					pname = "Aggregate ???";
					break;
			}
585 586 587 588
			break;
		case T_Unique:
			pname = "Unique";
			break;
589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608
		case T_SetOp:
			switch (((SetOp *) plan)->cmd)
			{
				case SETOPCMD_INTERSECT:
					pname = "SetOp Intersect";
					break;
				case SETOPCMD_INTERSECT_ALL:
					pname = "SetOp Intersect All";
					break;
				case SETOPCMD_EXCEPT:
					pname = "SetOp Except";
					break;
				case SETOPCMD_EXCEPT_ALL:
					pname = "SetOp Except All";
					break;
				default:
					pname = "SetOp ???";
					break;
			}
			break;
609 610 611
		case T_Limit:
			pname = "Limit";
			break;
612 613 614 615
		case T_Hash:
			pname = "Hash";
			break;
		default:
616
			pname = "???";
617
			break;
618 619
	}

620
	appendStringInfoString(str, pname);
621 622
	switch (nodeTag(plan))
	{
623
		case T_IndexScan:
624
			if (ScanDirectionIsBackward(((IndexScan *) plan)->indexorderdir))
625
				appendStringInfoString(str, " Backward");
626
			appendStringInfo(str, " using %s",
627
					explain_get_index_name(((IndexScan *) plan)->indexid));
628
			/* FALL THRU */
629
		case T_SeqScan:
630
		case T_BitmapHeapScan:
631
		case T_TidScan:
632 633
			if (((Scan *) plan)->scanrelid > 0)
			{
634 635
				RangeTblEntry *rte = rt_fetch(((Scan *) plan)->scanrelid,
											  es->rtable);
B
Bruce Momjian 已提交
636
				char	   *relname;
637 638

				/* Assume it's on a real relation */
639
				Assert(rte->rtekind == RTE_RELATION);
640 641 642

				/* We only show the rel name, not schema name */
				relname = get_rel_name(rte->relid);
643

644
				appendStringInfo(str, " on %s",
645
								 quote_identifier(relname));
646
				if (strcmp(rte->eref->aliasname, relname) != 0)
647
					appendStringInfo(str, " %s",
B
Bruce Momjian 已提交
648
									 quote_identifier(rte->eref->aliasname));
649 650
			}
			break;
651 652
		case T_BitmapIndexScan:
			appendStringInfo(str, " on %s",
653
				explain_get_index_name(((BitmapIndexScan *) plan)->indexid));
654
			break;
655 656 657 658 659 660 661
		case T_SubqueryScan:
			if (((Scan *) plan)->scanrelid > 0)
			{
				RangeTblEntry *rte = rt_fetch(((Scan *) plan)->scanrelid,
											  es->rtable);

				appendStringInfo(str, " %s",
662
								 quote_identifier(rte->eref->aliasname));
663 664
			}
			break;
665 666 667 668 669
		case T_FunctionScan:
			if (((Scan *) plan)->scanrelid > 0)
			{
				RangeTblEntry *rte = rt_fetch(((Scan *) plan)->scanrelid,
											  es->rtable);
670
				Node	   *funcexpr;
B
Bruce Momjian 已提交
671
				char	   *proname;
672 673 674 675

				/* Assert it's on a RangeFunction */
				Assert(rte->rtekind == RTE_FUNCTION);

676
				/*
B
Bruce Momjian 已提交
677 678 679 680
				 * If the expression is still a function call, we can get the
				 * real name of the function.  Otherwise, punt (this can
				 * happen if the optimizer simplified away the function call,
				 * for example).
681
				 */
682 683
				funcexpr = ((FunctionScan *) plan)->funcexpr;
				if (funcexpr && IsA(funcexpr, FuncExpr))
684
				{
685
					Oid			funcid = ((FuncExpr *) funcexpr)->funcid;
686 687 688 689 690 691

					/* We only show the func name, not schema name */
					proname = get_func_name(funcid);
				}
				else
					proname = rte->eref->aliasname;
692 693 694 695 696

				appendStringInfo(str, " on %s",
								 quote_identifier(proname));
				if (strcmp(rte->eref->aliasname, proname) != 0)
					appendStringInfo(str, " %s",
B
Bruce Momjian 已提交
697
									 quote_identifier(rte->eref->aliasname));
698 699
			}
			break;
700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715
		case T_ValuesScan:
			if (((Scan *) plan)->scanrelid > 0)
			{
				RangeTblEntry *rte = rt_fetch(((Scan *) plan)->scanrelid,
											  es->rtable);
				char	   *valsname;

				/* Assert it's on a values rte */
				Assert(rte->rtekind == RTE_VALUES);

				valsname = rte->eref->aliasname;

				appendStringInfo(str, " on %s",
								 quote_identifier(valsname));
			}
			break;
716 717
		default:
			break;
718
	}
B
Bruce Momjian 已提交
719

720 721 722
	appendStringInfo(str, "  (cost=%.2f..%.2f rows=%.0f width=%d)",
					 plan->startup_cost, plan->total_cost,
					 plan->plan_rows, plan->plan_width);
723

724
	/*
B
Bruce Momjian 已提交
725 726
	 * We have to forcibly clean up the instrumentation state because we
	 * haven't done ExecutorEnd yet.  This is pretty grotty ...
727 728 729
	 */
	if (planstate->instrument)
		InstrEndLoop(planstate->instrument);
730

731 732 733
	if (planstate->instrument && planstate->instrument->nloops > 0)
	{
		double		nloops = planstate->instrument->nloops;
734

735
		appendStringInfo(str, " (actual time=%.3f..%.3f rows=%.0f loops=%.0f)",
B
Bruce Momjian 已提交
736 737
						 1000.0 * planstate->instrument->startup / nloops,
						 1000.0 * planstate->instrument->total / nloops,
738 739
						 planstate->instrument->ntuples / nloops,
						 planstate->instrument->nloops);
740
	}
741 742
	else if (es->printAnalyze)
		appendStringInfo(str, " (never executed)");
743
	appendStringInfoChar(str, '\n');
744

745
	/* quals, sort keys, etc */
746 747 748
	switch (nodeTag(plan))
	{
		case T_IndexScan:
749
			show_scan_qual(((IndexScan *) plan)->indexqualorig,
750
						   "Index Cond",
751
						   ((Scan *) plan)->scanrelid,
752
						   outer_plan, NULL,
753
						   str, indent, es);
754
			show_scan_qual(plan->qual,
755
						   "Filter",
756
						   ((Scan *) plan)->scanrelid,
757
						   outer_plan, NULL,
758 759
						   str, indent, es);
			break;
760
		case T_BitmapIndexScan:
761
			show_scan_qual(((BitmapIndexScan *) plan)->indexqualorig,
762 763
						   "Index Cond",
						   ((Scan *) plan)->scanrelid,
764
						   outer_plan, NULL,
765 766 767 768
						   str, indent, es);
			break;
		case T_BitmapHeapScan:
			/* XXX do we want to show this in production? */
769
			show_scan_qual(((BitmapHeapScan *) plan)->bitmapqualorig,
770 771
						   "Recheck Cond",
						   ((Scan *) plan)->scanrelid,
772
						   outer_plan, NULL,
773 774
						   str, indent, es);
			/* FALL THRU */
775
		case T_SeqScan:
776
		case T_FunctionScan:
777
		case T_ValuesScan:
778 779 780 781 782 783 784
			show_scan_qual(plan->qual,
						   "Filter",
						   ((Scan *) plan)->scanrelid,
						   outer_plan, NULL,
						   str, indent, es);
			break;
		case T_SubqueryScan:
785
			show_scan_qual(plan->qual,
786
						   "Filter",
787
						   ((Scan *) plan)->scanrelid,
788
						   outer_plan,
789
						   ((SubqueryScan *) plan)->subplan,
790 791
						   str, indent, es);
			break;
792 793 794 795 796 797
		case T_TidScan:
			{
				/*
				 * The tidquals list has OR semantics, so be sure to show it
				 * as an OR condition.
				 */
B
Bruce Momjian 已提交
798
				List	   *tidquals = ((TidScan *) plan)->tidquals;
799 800 801 802 803 804

				if (list_length(tidquals) > 1)
					tidquals = list_make1(make_orclause(tidquals));
				show_scan_qual(tidquals,
							   "TID Cond",
							   ((Scan *) plan)->scanrelid,
805
							   outer_plan, NULL,
806 807 808 809
							   str, indent, es);
				show_scan_qual(plan->qual,
							   "Filter",
							   ((Scan *) plan)->scanrelid,
810
							   outer_plan, NULL,
811 812 813
							   str, indent, es);
			}
			break;
814
		case T_NestLoop:
815
			show_upper_qual(((NestLoop *) plan)->join.joinqual,
816
							"Join Filter", plan,
817
							str, indent, es);
818
			show_upper_qual(plan->qual,
819
							"Filter", plan,
820 821 822
							str, indent, es);
			break;
		case T_MergeJoin:
823
			show_upper_qual(((MergeJoin *) plan)->mergeclauses,
824
							"Merge Cond", plan,
825
							str, indent, es);
826
			show_upper_qual(((MergeJoin *) plan)->join.joinqual,
827
							"Join Filter", plan,
828
							str, indent, es);
829
			show_upper_qual(plan->qual,
830
							"Filter", plan,
831 832 833
							str, indent, es);
			break;
		case T_HashJoin:
834
			show_upper_qual(((HashJoin *) plan)->hashclauses,
835
							"Hash Cond", plan,
836
							str, indent, es);
837
			show_upper_qual(((HashJoin *) plan)->join.joinqual,
838
							"Join Filter", plan,
839
							str, indent, es);
840
			show_upper_qual(plan->qual,
841
							"Filter", plan,
842 843 844 845
							str, indent, es);
			break;
		case T_Agg:
		case T_Group:
846
			show_upper_qual(plan->qual,
847
							"Filter", plan,
848 849
							str, indent, es);
			break;
850
		case T_Sort:
851
			show_sort_keys(plan,
852 853
						   ((Sort *) plan)->numCols,
						   ((Sort *) plan)->sortColIdx,
854 855
						   "Sort Key",
						   str, indent, es);
856 857
			show_sort_info((SortState *) planstate,
						   str, indent, es);
858
			break;
859 860
		case T_Result:
			show_upper_qual((List *) ((Result *) plan)->resconstantqual,
861
							"One-Time Filter", plan,
862
							str, indent, es);
863
			show_upper_qual(plan->qual,
864
							"Filter", plan,
865 866 867 868 869 870
							str, indent, es);
			break;
		default:
			break;
	}

V
Vadim B. Mikheev 已提交
871 872 873
	/* initPlan-s */
	if (plan->initPlan)
	{
874
		ListCell   *lst;
875

B
Bruce Momjian 已提交
876
		for (i = 0; i < indent; i++)
V
Vadim B. Mikheev 已提交
877 878
			appendStringInfo(str, "  ");
		appendStringInfo(str, "  InitPlan\n");
879
		foreach(lst, planstate->initPlan)
V
Vadim B. Mikheev 已提交
880
		{
881
			SubPlanState *sps = (SubPlanState *) lfirst(lst);
B
Bruce Momjian 已提交
882
			SubPlan    *sp = (SubPlan *) sps->xprstate.expr;
883

V
Vadim B. Mikheev 已提交
884 885 886
			for (i = 0; i < indent; i++)
				appendStringInfo(str, "  ");
			appendStringInfo(str, "    ->  ");
887 888
			explain_outNode(str,
							exec_subplan_get_plan(es->pstmt, sp),
889
							sps->planstate,
890
							NULL,
891
							indent + 4, es);
V
Vadim B. Mikheev 已提交
892 893
		}
	}
894 895 896 897 898 899

	/* lefttree */
	if (outerPlan(plan))
	{
		for (i = 0; i < indent; i++)
			appendStringInfo(str, "  ");
V
Vadim B. Mikheev 已提交
900
		appendStringInfo(str, "  ->  ");
B
Bruce Momjian 已提交
901

902
		/*
B
Bruce Momjian 已提交
903 904
		 * Ordinarily we don't pass down our own outer_plan value to our child
		 * nodes, but in bitmap scan trees we must, since the bottom
905 906
		 * BitmapIndexScan nodes may have outer references.
		 */
907 908
		explain_outNode(str, outerPlan(plan),
						outerPlanState(planstate),
909
						IsA(plan, BitmapHeapScan) ? outer_plan : NULL,
910
						indent + 3, es);
911
	}
912 913 914 915 916 917

	/* righttree */
	if (innerPlan(plan))
	{
		for (i = 0; i < indent; i++)
			appendStringInfo(str, "  ");
V
Vadim B. Mikheev 已提交
918
		appendStringInfo(str, "  ->  ");
919 920 921
		explain_outNode(str, innerPlan(plan),
						innerPlanState(planstate),
						outerPlan(plan),
922
						indent + 3, es);
V
Vadim B. Mikheev 已提交
923
	}
924

925
	if (IsA(plan, Append))
926
	{
927
		Append	   *appendplan = (Append *) plan;
928
		AppendState *appendstate = (AppendState *) planstate;
929
		ListCell   *lst;
930
		int			j;
931

932
		j = 0;
933 934
		foreach(lst, appendplan->appendplans)
		{
935
			Plan	   *subnode = (Plan *) lfirst(lst);
936 937 938

			for (i = 0; i < indent; i++)
				appendStringInfo(str, "  ");
939
			appendStringInfo(str, "  ->  ");
940

941 942 943
			/*
			 * Ordinarily we don't pass down our own outer_plan value to our
			 * child nodes, but in an Append we must, since we might be
B
Bruce Momjian 已提交
944 945
			 * looking at an appendrel indexscan with outer references from
			 * the member scans.
946
			 */
947 948
			explain_outNode(str, subnode,
							appendstate->appendplans[j],
949
							outer_plan,
950 951
							indent + 3, es);
			j++;
952 953
		}
	}
954

955 956
	if (IsA(plan, BitmapAnd))
	{
B
Bruce Momjian 已提交
957
		BitmapAnd  *bitmapandplan = (BitmapAnd *) plan;
958 959 960 961 962 963 964 965 966 967 968 969 970 971 972
		BitmapAndState *bitmapandstate = (BitmapAndState *) planstate;
		ListCell   *lst;
		int			j;

		j = 0;
		foreach(lst, bitmapandplan->bitmapplans)
		{
			Plan	   *subnode = (Plan *) lfirst(lst);

			for (i = 0; i < indent; i++)
				appendStringInfo(str, "  ");
			appendStringInfo(str, "  ->  ");

			explain_outNode(str, subnode,
							bitmapandstate->bitmapplans[j],
B
Bruce Momjian 已提交
973
							outer_plan, /* pass down same outer plan */
974 975 976 977 978 979 980
							indent + 3, es);
			j++;
		}
	}

	if (IsA(plan, BitmapOr))
	{
B
Bruce Momjian 已提交
981
		BitmapOr   *bitmaporplan = (BitmapOr *) plan;
982 983 984 985 986 987 988 989 990 991 992 993 994 995 996
		BitmapOrState *bitmaporstate = (BitmapOrState *) planstate;
		ListCell   *lst;
		int			j;

		j = 0;
		foreach(lst, bitmaporplan->bitmapplans)
		{
			Plan	   *subnode = (Plan *) lfirst(lst);

			for (i = 0; i < indent; i++)
				appendStringInfo(str, "  ");
			appendStringInfo(str, "  ->  ");

			explain_outNode(str, subnode,
							bitmaporstate->bitmapplans[j],
B
Bruce Momjian 已提交
997
							outer_plan, /* pass down same outer plan */
998 999 1000 1001 1002
							indent + 3, es);
			j++;
		}
	}

1003 1004 1005
	if (IsA(plan, SubqueryScan))
	{
		SubqueryScan *subqueryscan = (SubqueryScan *) plan;
1006
		SubqueryScanState *subquerystate = (SubqueryScanState *) planstate;
1007 1008 1009 1010 1011 1012
		Plan	   *subnode = subqueryscan->subplan;

		for (i = 0; i < indent; i++)
			appendStringInfo(str, "  ");
		appendStringInfo(str, "  ->  ");

1013 1014 1015 1016
		explain_outNode(str, subnode,
						subquerystate->subplan,
						NULL,
						indent + 3, es);
1017 1018 1019
	}

	/* subPlan-s */
1020
	if (planstate->subPlan)
1021
	{
1022
		ListCell   *lst;
1023 1024 1025 1026

		for (i = 0; i < indent; i++)
			appendStringInfo(str, "  ");
		appendStringInfo(str, "  SubPlan\n");
1027
		foreach(lst, planstate->subPlan)
1028
		{
1029
			SubPlanState *sps = (SubPlanState *) lfirst(lst);
B
Bruce Momjian 已提交
1030
			SubPlan    *sp = (SubPlan *) sps->xprstate.expr;
1031

1032 1033 1034
			for (i = 0; i < indent; i++)
				appendStringInfo(str, "  ");
			appendStringInfo(str, "    ->  ");
1035 1036
			explain_outNode(str,
							exec_subplan_get_plan(es->pstmt, sp),
1037 1038
							sps->planstate,
							NULL,
1039 1040 1041
							indent + 4, es);
		}
	}
1042 1043
}

1044 1045
/*
 * Show a qualifier expression for a scan plan node
1046 1047 1048 1049
 *
 * Note: outer_plan is the referent for any OUTER vars in the scan qual;
 * this would be the outer side of a nestloop plan.  inner_plan should be
 * NULL except for a SubqueryScan plan node, where it should be the subplan.
1050 1051
 */
static void
1052
show_scan_qual(List *qual, const char *qlabel,
1053
			   int scanrelid, Plan *outer_plan, Plan *inner_plan,
1054 1055 1056
			   StringInfo str, int indent, ExplainState *es)
{
	List	   *context;
1057
	bool		useprefix;
1058 1059 1060 1061 1062 1063 1064 1065
	Node	   *node;
	char	   *exprstr;
	int			i;

	/* No work if empty qual */
	if (qual == NIL)
		return;

1066 1067
	/* Convert AND list to explicit AND */
	node = (Node *) make_ands_explicit(qual);
1068

1069 1070 1071
	/* Set up deparsing context */
	context = deparse_context_for_plan((Node *) outer_plan,
									   (Node *) inner_plan,
1072
									   es->rtable);
1073
	useprefix = (outer_plan != NULL || inner_plan != NULL);
1074 1075

	/* Deparse the expression */
1076
	exprstr = deparse_expression(node, context, useprefix, false);
1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087

	/* And add to str */
	for (i = 0; i < indent; i++)
		appendStringInfo(str, "  ");
	appendStringInfo(str, "  %s: %s\n", qlabel, exprstr);
}

/*
 * Show a qualifier expression for an upper-level plan node
 */
static void
1088
show_upper_qual(List *qual, const char *qlabel, Plan *plan,
1089 1090 1091
				StringInfo str, int indent, ExplainState *es)
{
	List	   *context;
1092
	bool		useprefix;
1093 1094 1095 1096 1097 1098 1099 1100
	Node	   *node;
	char	   *exprstr;
	int			i;

	/* No work if empty qual */
	if (qual == NIL)
		return;

1101 1102 1103
	/* Set up deparsing context */
	context = deparse_context_for_plan((Node *) outerPlan(plan),
									   (Node *) innerPlan(plan),
1104
									   es->rtable);
1105
	useprefix = list_length(es->rtable) > 1;
1106 1107 1108

	/* Deparse the expression */
	node = (Node *) make_ands_explicit(qual);
1109
	exprstr = deparse_expression(node, context, useprefix, false);
1110 1111 1112 1113 1114 1115 1116

	/* And add to str */
	for (i = 0; i < indent; i++)
		appendStringInfo(str, "  ");
	appendStringInfo(str, "  %s: %s\n", qlabel, exprstr);
}

1117 1118 1119 1120
/*
 * Show the sort keys for a Sort node.
 */
static void
1121
show_sort_keys(Plan *sortplan, int nkeys, AttrNumber *keycols,
1122
			   const char *qlabel,
1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137
			   StringInfo str, int indent, ExplainState *es)
{
	List	   *context;
	bool		useprefix;
	int			keyno;
	char	   *exprstr;
	int			i;

	if (nkeys <= 0)
		return;

	for (i = 0; i < indent; i++)
		appendStringInfo(str, "  ");
	appendStringInfo(str, "  %s: ", qlabel);

1138 1139 1140 1141 1142
	/* Set up deparsing context */
	context = deparse_context_for_plan((Node *) outerPlan(sortplan),
									   NULL,		/* Sort has no innerPlan */
									   es->rtable);
	useprefix = list_length(es->rtable) > 1;
1143

1144
	for (keyno = 0; keyno < nkeys; keyno++)
1145 1146
	{
		/* find key expression in tlist */
1147
		AttrNumber	keyresno = keycols[keyno];
1148
		TargetEntry *target = get_tle_by_resno(sortplan->targetlist, keyresno);
1149

1150
		if (!target)
1151
			elog(ERROR, "no tlist entry for key %d", keyresno);
1152 1153 1154 1155 1156 1157
		/* Deparse the expression, showing any top-level cast */
		exprstr = deparse_expression((Node *) target->expr, context,
									 useprefix, true);
		/* And add to str */
		if (keyno > 0)
			appendStringInfo(str, ", ");
N
Neil Conway 已提交
1158
		appendStringInfoString(str, exprstr);
1159 1160 1161 1162
	}

	appendStringInfo(str, "\n");
}
1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184

/*
 * If it's EXPLAIN ANALYZE, show tuplesort explain info for a sort node
 */
static void
show_sort_info(SortState *sortstate,
			   StringInfo str, int indent, ExplainState *es)
{
	Assert(IsA(sortstate, SortState));
	if (es->printAnalyze && sortstate->sort_Done &&
		sortstate->tuplesortstate != NULL)
	{
		char	   *sortinfo;
		int			i;

		sortinfo = tuplesort_explain((Tuplesortstate *) sortstate->tuplesortstate);
		for (i = 0; i < indent; i++)
			appendStringInfo(str, "  ");
		appendStringInfo(str, "  %s\n", sortinfo);
		pfree(sortinfo);
	}
}
1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210

/*
 * Fetch the name of an index in an EXPLAIN
 *
 * We allow plugins to get control here so that plans involving hypothetical
 * indexes can be explained.
 */
static const char *
explain_get_index_name(Oid indexId)
{
	const char   *result;

	if (explain_get_index_name_hook)
		result = (*explain_get_index_name_hook) (indexId);
	else
		result = NULL;
	if (result == NULL)
	{
		/* default behavior: look in the catalogs and quote it */
		result = get_rel_name(indexId);
		if (result == NULL)
			elog(ERROR, "cache lookup failed for index %u", indexId);
		result = quote_identifier(result);
	}
	return result;
}