explain.c 29.9 KB
Newer Older
1 2
/*-------------------------------------------------------------------------
 *
3
 * explain.c
4
 *	  Explain query execution plans
5
 *
P
 
PostgreSQL Daemon 已提交
6
 * Portions Copyright (c) 1996-2005, 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.143 2006/02/05 02:59:16 tgl Exp $
11
 *
12
 *-------------------------------------------------------------------------
13
 */
14
#include "postgres.h"
M
Marc G. Fournier 已提交
15

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

37

38 39 40
typedef struct ExplainState
{
	/* options */
41 42
	bool		printNodes;		/* do nodeToString() too */
	bool		printAnalyze;	/* print actual times */
43
	/* other states */
44
	List	   *rtable;			/* range table */
45
} ExplainState;
46

47
static void ExplainOneQuery(Query *query, ExplainStmt *stmt,
48
							ParamListInfo params, TupOutputState *tstate);
49
static double elapsed_time(instr_time *starttime);
50
static void explain_outNode(StringInfo str,
51
				Plan *plan, PlanState *planstate,
B
Bruce Momjian 已提交
52 53
				Plan *outer_plan,
				int indent, ExplainState *es);
54
static void show_scan_qual(List *qual, const char *qlabel,
B
Bruce Momjian 已提交
55 56
			   int scanrelid, Plan *outer_plan,
			   StringInfo str, int indent, ExplainState *es);
57
static void show_upper_qual(List *qual, const char *qlabel,
B
Bruce Momjian 已提交
58 59 60
				const char *outer_name, int outer_varno, Plan *outer_plan,
				const char *inner_name, int inner_varno, Plan *inner_plan,
				StringInfo str, int indent, ExplainState *es);
61
static void show_sort_keys(List *tlist, int nkeys, AttrNumber *keycols,
B
Bruce Momjian 已提交
62 63
			   const char *qlabel,
			   StringInfo str, int indent, ExplainState *es);
64 65 66

/*
 * ExplainQuery -
67
 *	  execute an EXPLAIN command
68 69
 */
void
70
ExplainQuery(ExplainStmt *stmt, ParamListInfo params, DestReceiver *dest)
71
{
72
	Query	   *query = stmt->query;
73
	TupOutputState *tstate;
B
Bruce Momjian 已提交
74
	List	   *rewritten;
75
	ListCell   *l;
76

77
	/*
B
Bruce Momjian 已提交
78 79
	 * Because the planner is not cool about not scribbling on its input, we
	 * make a preliminary copy of the source querytree.  This prevents
80 81
	 * problems in the case that the EXPLAIN is in a portal or plpgsql
	 * function and is executed repeatedly.  (See also the same hack in
B
Bruce Momjian 已提交
82 83
	 * DECLARE CURSOR and PREPARE.)  XXX the planner really shouldn't modify
	 * its input ... FIXME someday.
84 85 86
	 */
	query = copyObject(query);

87
	/* prepare for projection of tuples */
88
	tstate = begin_tup_output_tupdesc(dest, ExplainResultDesc(stmt));
89

90 91
	if (query->commandType == CMD_UTILITY)
	{
92
		/* Rewriter will not cope with utility statements */
93
		if (query->utilityStmt && IsA(query->utilityStmt, DeclareCursorStmt))
94
			ExplainOneQuery(query, stmt, params, tstate);
95
		else if (query->utilityStmt && IsA(query->utilityStmt, ExecuteStmt))
96
			ExplainExecuteQuery(stmt, params, tstate);
97 98
		else
			do_text_output_oneline(tstate, "Utility statements have no plan structure");
99
	}
100
	else
B
Bruce Momjian 已提交
101
	{
102 103 104 105 106 107
		/*
		 * Must acquire locks in case we didn't come fresh from the parser.
		 * XXX this also scribbles on query, another reason for copyObject
		 */
		AcquireRewriteLocks(query);

108 109 110 111 112 113
		/* Rewrite through rule system */
		rewritten = QueryRewrite(query);

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

129
	end_tup_output(tstate);
B
Bruce Momjian 已提交
130 131
}

132 133 134 135 136 137 138 139 140 141 142 143
/*
 * 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",
144
					   TEXTOID, -1, 0);
145 146 147
	return tupdesc;
}

B
Bruce Momjian 已提交
148 149 150 151 152
/*
 * ExplainOneQuery -
 *	  print out the execution plan for one query
 */
static void
153 154
ExplainOneQuery(Query *query, ExplainStmt *stmt, ParamListInfo params,
				TupOutputState *tstate)
B
Bruce Momjian 已提交
155 156
{
	Plan	   *plan;
157
	QueryDesc  *queryDesc;
158 159
	bool		isCursor = false;
	int			cursorOptions = 0;
B
Bruce Momjian 已提交
160

161 162 163
	/* planner will not cope with utility statements */
	if (query->commandType == CMD_UTILITY)
	{
164 165 166 167 168 169 170 171 172 173 174
		if (query->utilityStmt && IsA(query->utilityStmt, DeclareCursorStmt))
		{
			DeclareCursorStmt *dcstmt;
			List	   *rewritten;

			dcstmt = (DeclareCursorStmt *) query->utilityStmt;
			query = (Query *) dcstmt->query;
			isCursor = true;
			cursorOptions = dcstmt->options;
			/* Still need to rewrite cursor command */
			Assert(query->commandType == CMD_SELECT);
175 176
			/* get locks (we assume ExplainQuery already copied tree) */
			AcquireRewriteLocks(query);
177
			rewritten = QueryRewrite(query);
178
			if (list_length(rewritten) != 1)
179
				elog(ERROR, "unexpected rewrite result");
180
			query = (Query *) linitial(rewritten);
181 182 183 184 185 186
			Assert(query->commandType == CMD_SELECT);
			/* do not actually execute the underlying query! */
			stmt->analyze = false;
		}
		else if (query->utilityStmt && IsA(query->utilityStmt, NotifyStmt))
		{
187
			do_text_output_oneline(tstate, "NOTIFY");
188 189
			return;
		}
190
		else
191
		{
192
			do_text_output_oneline(tstate, "UTILITY");
193 194
			return;
		}
195 196
	}

197
	/* plan the query */
198
	plan = planner(query, isCursor, cursorOptions, NULL);
B
Bruce Momjian 已提交
199

200 201 202
	/*
	 * Update snapshot command ID to ensure this query sees results of any
	 * previously executed queries.  (It's a bit cheesy to modify
203 204 205
	 * 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.)
206 207 208
	 */
	ActiveSnapshot->curcid = GetCurrentCommandId();

209
	/* Create a QueryDesc requesting no output */
210 211
	queryDesc = CreateQueryDesc(query, plan,
								ActiveSnapshot, InvalidSnapshot,
212
								None_Receiver, params,
213 214
								stmt->analyze);

215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
	ExplainOnePlan(queryDesc, stmt, tstate);
}

/*
 * ExplainOnePlan -
 *		given a planned query, execute it if needed, and then print
 *		EXPLAIN output
 *
 * This is exported because it's called back from prepare.c in the
 * EXPLAIN EXECUTE case
 *
 * Note: the passed-in QueryDesc is freed when we're done with it
 */
void
ExplainOnePlan(QueryDesc *queryDesc, ExplainStmt *stmt,
			   TupOutputState *tstate)
{
B
Bruce Momjian 已提交
232
	instr_time	starttime;
233 234 235 236
	double		totaltime = 0;
	ExplainState *es;
	StringInfo	str;

237
	INSTR_TIME_SET_CURRENT(starttime);
238

239 240 241 242
	/* If analyzing, we need to cope with queued triggers */
	if (stmt->analyze)
		AfterTriggerBeginQuery();

243
	/* call ExecutorStart to prepare the plan for execution */
244
	ExecutorStart(queryDesc, !stmt->analyze);
245

246
	/* Execute the plan for statistics if asked for */
247
	if (stmt->analyze)
248
	{
249 250
		/* run the plan */
		ExecutorRun(queryDesc, ForwardScanDirection, 0L);
251

252 253
		/* We can't clean up 'till we're done printing the stats... */
		totaltime += elapsed_time(&starttime);
254 255
	}

256
	es = (ExplainState *) palloc0(sizeof(ExplainState));
B
Bruce Momjian 已提交
257

258 259
	es->printNodes = stmt->verbose;
	es->printAnalyze = stmt->analyze;
260
	es->rtable = queryDesc->parsetree->rtable;
261 262

	if (es->printNodes)
263
	{
264
		char	   *s;
265
		char	   *f;
266

267
		s = nodeToString(queryDesc->plantree);
268 269
		if (s)
		{
270 271 272 273
			if (Explain_pretty_print)
				f = pretty_format_node_dump(s);
			else
				f = format_node_dump(s);
274
			pfree(s);
275 276
			do_text_output_multiline(tstate, f);
			pfree(f);
B
Bruce Momjian 已提交
277
			do_text_output_oneline(tstate, ""); /* separator line */
278 279
		}
	}
280

281 282
	str = makeStringInfo();

283 284
	explain_outNode(str, queryDesc->plantree, queryDesc->planstate,
					NULL, 0, es);
285 286

	/*
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
	 * 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;
B
Bruce Momjian 已提交
302 303
		int			numrels = queryDesc->estate->es_num_result_relations;
		int			nr;
304 305 306 307

		rInfo = queryDesc->estate->es_result_relations;
		for (nr = 0; nr < numrels; rInfo++, nr++)
		{
B
Bruce Momjian 已提交
308
			int			nt;
309

310
			if (!rInfo->ri_TrigDesc || !rInfo->ri_TrigInstrument)
311 312 313
				continue;
			for (nt = 0; nt < rInfo->ri_TrigDesc->numtriggers; nt++)
			{
B
Bruce Momjian 已提交
314
				Trigger    *trig = rInfo->ri_TrigDesc->triggers + nt;
315
				Instrumentation *instr = rInfo->ri_TrigInstrument + nt;
B
Bruce Momjian 已提交
316
				char	   *conname;
317 318 319 320 321 322 323 324 325 326 327 328

				/* 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 (trig->tgisconstraint &&
B
Bruce Momjian 已提交
329
				(conname = GetConstraintNameForTrigger(trig->tgoid)) != NULL)
330 331 332 333 334 335 336 337 338 339
				{
					appendStringInfo(str, "Trigger for constraint %s",
									 conname);
					pfree(conname);
				}
				else
					appendStringInfo(str, "Trigger %s", trig->tgname);

				if (numrels > 1)
					appendStringInfo(str, " on %s",
B
Bruce Momjian 已提交
340
							RelationGetRelationName(rInfo->ri_RelationDesc));
341 342 343 344 345 346 347 348 349

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

	/*
B
Bruce Momjian 已提交
350 351
	 * Close down the query and free resources.  Include time for this in the
	 * total runtime (although it should be pretty minimal).
352
	 */
353
	INSTR_TIME_SET_CURRENT(starttime);
354

355
	ExecutorEnd(queryDesc);
356

357 358
	FreeQueryDesc(queryDesc);

359 360 361
	/* We need a CCI just in case query expanded to multiple plans */
	if (stmt->analyze)
		CommandCounterIncrement();
362 363 364

	totaltime += elapsed_time(&starttime);

365 366 367 368
	if (stmt->analyze)
		appendStringInfo(str, "Total runtime: %.3f ms\n",
						 1000.0 * totaltime);
	do_text_output_multiline(tstate, str->data);
369

370 371
	pfree(str->data);
	pfree(str);
B
Bruce Momjian 已提交
372
	pfree(es);
373 374
}

375
/* Compute elapsed time in seconds since given timestamp */
376
static double
377
elapsed_time(instr_time *starttime)
378
{
B
Bruce Momjian 已提交
379
	instr_time	endtime;
380

381
	INSTR_TIME_SET_CURRENT(endtime);
382

383
#ifndef WIN32
384 385 386 387 388 389 390
	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 已提交
391
#else							/* WIN32 */
392 393 394 395
	endtime.QuadPart -= starttime->QuadPart;
#endif

	return INSTR_TIME_GET_DOUBLE(endtime);
396
}
397 398 399

/*
 * explain_outNode -
400 401
 *	  converts a Plan node into ascii string and appends it to 'str'
 *
402 403 404 405
 * 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.
 *
406 407 408
 * 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.
409 410
 */
static void
411
explain_outNode(StringInfo str,
412
				Plan *plan, PlanState *planstate,
413
				Plan *outer_plan,
414
				int indent, ExplainState *es)
415
{
B
Bruce Momjian 已提交
416 417
	char	   *pname;
	int			i;
418 419 420

	if (plan == NULL)
	{
421
		appendStringInfoChar(str, '\n');
422 423 424 425 426
		return;
	}

	switch (nodeTag(plan))
	{
427 428 429 430 431 432
		case T_Result:
			pname = "Result";
			break;
		case T_Append:
			pname = "Append";
			break;
433 434 435 436 437 438
		case T_BitmapAnd:
			pname = "BitmapAnd";
			break;
		case T_BitmapOr:
			pname = "BitmapOr";
			break;
439
		case T_NestLoop:
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
			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;
			}
461 462
			break;
		case T_MergeJoin:
463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
			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;
			}
484 485
			break;
		case T_HashJoin:
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506
			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;
			}
507 508 509 510 511 512 513
			break;
		case T_SeqScan:
			pname = "Seq Scan";
			break;
		case T_IndexScan:
			pname = "Index Scan";
			break;
514 515 516 517 518 519
		case T_BitmapIndexScan:
			pname = "Bitmap Index Scan";
			break;
		case T_BitmapHeapScan:
			pname = "Bitmap Heap Scan";
			break;
520 521 522 523 524 525
		case T_TidScan:
			pname = "Tid Scan";
			break;
		case T_SubqueryScan:
			pname = "Subquery Scan";
			break;
526 527 528
		case T_FunctionScan:
			pname = "Function Scan";
			break;
529 530 531
		case T_Material:
			pname = "Materialize";
			break;
532 533 534 535 536 537 538
		case T_Sort:
			pname = "Sort";
			break;
		case T_Group:
			pname = "Group";
			break;
		case T_Agg:
539 540 541 542 543 544 545 546 547 548 549 550 551 552 553
			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;
			}
554 555 556 557
			break;
		case T_Unique:
			pname = "Unique";
			break;
558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577
		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;
578 579 580
		case T_Limit:
			pname = "Limit";
			break;
581 582 583 584
		case T_Hash:
			pname = "Hash";
			break;
		default:
585
			pname = "???";
586
			break;
587 588
	}

589
	appendStringInfoString(str, pname);
590 591
	switch (nodeTag(plan))
	{
592
		case T_IndexScan:
593
			if (ScanDirectionIsBackward(((IndexScan *) plan)->indexorderdir))
594
				appendStringInfoString(str, " Backward");
595
			appendStringInfo(str, " using %s",
B
Bruce Momjian 已提交
596
			  quote_identifier(get_rel_name(((IndexScan *) plan)->indexid)));
597
			/* FALL THRU */
598
		case T_SeqScan:
599
		case T_BitmapHeapScan:
600
		case T_TidScan:
601 602
			if (((Scan *) plan)->scanrelid > 0)
			{
603 604
				RangeTblEntry *rte = rt_fetch(((Scan *) plan)->scanrelid,
											  es->rtable);
B
Bruce Momjian 已提交
605
				char	   *relname;
606 607

				/* Assume it's on a real relation */
608
				Assert(rte->rtekind == RTE_RELATION);
609 610 611

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

613
				appendStringInfo(str, " on %s",
614
								 quote_identifier(relname));
615
				if (strcmp(rte->eref->aliasname, relname) != 0)
616
					appendStringInfo(str, " %s",
B
Bruce Momjian 已提交
617
									 quote_identifier(rte->eref->aliasname));
618 619
			}
			break;
620 621
		case T_BitmapIndexScan:
			appendStringInfo(str, " on %s",
622
							 quote_identifier(get_rel_name(((BitmapIndexScan *) plan)->indexid)));
623
			break;
624 625 626 627 628 629 630
		case T_SubqueryScan:
			if (((Scan *) plan)->scanrelid > 0)
			{
				RangeTblEntry *rte = rt_fetch(((Scan *) plan)->scanrelid,
											  es->rtable);

				appendStringInfo(str, " %s",
631
								 quote_identifier(rte->eref->aliasname));
632 633
			}
			break;
634 635 636 637 638
		case T_FunctionScan:
			if (((Scan *) plan)->scanrelid > 0)
			{
				RangeTblEntry *rte = rt_fetch(((Scan *) plan)->scanrelid,
											  es->rtable);
B
Bruce Momjian 已提交
639
				char	   *proname;
640 641 642 643

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

644
				/*
B
Bruce Momjian 已提交
645 646 647 648
				 * 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).
649 650 651 652 653 654 655 656 657 658 659
				 */
				if (rte->funcexpr && IsA(rte->funcexpr, FuncExpr))
				{
					FuncExpr   *funcexpr = (FuncExpr *) rte->funcexpr;
					Oid			funcid = funcexpr->funcid;

					/* We only show the func name, not schema name */
					proname = get_func_name(funcid);
				}
				else
					proname = rte->eref->aliasname;
660 661 662 663 664

				appendStringInfo(str, " on %s",
								 quote_identifier(proname));
				if (strcmp(rte->eref->aliasname, proname) != 0)
					appendStringInfo(str, " %s",
B
Bruce Momjian 已提交
665
									 quote_identifier(rte->eref->aliasname));
666 667
			}
			break;
668 669
		default:
			break;
670
	}
B
Bruce Momjian 已提交
671

672 673 674
	appendStringInfo(str, "  (cost=%.2f..%.2f rows=%.0f width=%d)",
					 plan->startup_cost, plan->total_cost,
					 plan->plan_rows, plan->plan_width);
675

676
	/*
B
Bruce Momjian 已提交
677 678
	 * We have to forcibly clean up the instrumentation state because we
	 * haven't done ExecutorEnd yet.  This is pretty grotty ...
679 680 681
	 */
	if (planstate->instrument)
		InstrEndLoop(planstate->instrument);
682

683 684 685
	if (planstate->instrument && planstate->instrument->nloops > 0)
	{
		double		nloops = planstate->instrument->nloops;
686

687
		appendStringInfo(str, " (actual time=%.3f..%.3f rows=%.0f loops=%.0f)",
B
Bruce Momjian 已提交
688 689
						 1000.0 * planstate->instrument->startup / nloops,
						 1000.0 * planstate->instrument->total / nloops,
690 691
						 planstate->instrument->ntuples / nloops,
						 planstate->instrument->nloops);
692
	}
693 694
	else if (es->printAnalyze)
		appendStringInfo(str, " (never executed)");
695
	appendStringInfoChar(str, '\n');
696

697
	/* quals, sort keys, etc */
698 699 700
	switch (nodeTag(plan))
	{
		case T_IndexScan:
701
			show_scan_qual(((IndexScan *) plan)->indexqualorig,
702
						   "Index Cond",
703
						   ((Scan *) plan)->scanrelid,
704
						   outer_plan,
705
						   str, indent, es);
706
			show_scan_qual(plan->qual,
707
						   "Filter",
708
						   ((Scan *) plan)->scanrelid,
709
						   outer_plan,
710 711
						   str, indent, es);
			break;
712
		case T_BitmapIndexScan:
713
			show_scan_qual(((BitmapIndexScan *) plan)->indexqualorig,
714 715 716 717 718 719 720
						   "Index Cond",
						   ((Scan *) plan)->scanrelid,
						   outer_plan,
						   str, indent, es);
			break;
		case T_BitmapHeapScan:
			/* XXX do we want to show this in production? */
721
			show_scan_qual(((BitmapHeapScan *) plan)->bitmapqualorig,
722 723 724 725 726
						   "Recheck Cond",
						   ((Scan *) plan)->scanrelid,
						   outer_plan,
						   str, indent, es);
			/* FALL THRU */
727
		case T_SeqScan:
728
		case T_SubqueryScan:
729
		case T_FunctionScan:
730
			show_scan_qual(plan->qual,
731
						   "Filter",
732
						   ((Scan *) plan)->scanrelid,
733
						   outer_plan,
734 735
						   str, indent, es);
			break;
736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757
		case T_TidScan:
			{
				/*
				 * The tidquals list has OR semantics, so be sure to show it
				 * as an OR condition.
				 */
				List *tidquals = ((TidScan *) plan)->tidquals;

				if (list_length(tidquals) > 1)
					tidquals = list_make1(make_orclause(tidquals));
				show_scan_qual(tidquals,
							   "TID Cond",
							   ((Scan *) plan)->scanrelid,
							   outer_plan,
							   str, indent, es);
				show_scan_qual(plan->qual,
							   "Filter",
							   ((Scan *) plan)->scanrelid,
							   outer_plan,
							   str, indent, es);
			}
			break;
758
		case T_NestLoop:
759
			show_upper_qual(((NestLoop *) plan)->join.joinqual,
760
							"Join Filter",
761 762 763
							"outer", OUTER, outerPlan(plan),
							"inner", INNER, innerPlan(plan),
							str, indent, es);
764 765
			show_upper_qual(plan->qual,
							"Filter",
766 767 768 769 770
							"outer", OUTER, outerPlan(plan),
							"inner", INNER, innerPlan(plan),
							str, indent, es);
			break;
		case T_MergeJoin:
771 772
			show_upper_qual(((MergeJoin *) plan)->mergeclauses,
							"Merge Cond",
773 774 775
							"outer", OUTER, outerPlan(plan),
							"inner", INNER, innerPlan(plan),
							str, indent, es);
776
			show_upper_qual(((MergeJoin *) plan)->join.joinqual,
777
							"Join Filter",
778 779 780
							"outer", OUTER, outerPlan(plan),
							"inner", INNER, innerPlan(plan),
							str, indent, es);
781 782
			show_upper_qual(plan->qual,
							"Filter",
783 784 785 786 787
							"outer", OUTER, outerPlan(plan),
							"inner", INNER, innerPlan(plan),
							str, indent, es);
			break;
		case T_HashJoin:
788 789
			show_upper_qual(((HashJoin *) plan)->hashclauses,
							"Hash Cond",
790 791 792
							"outer", OUTER, outerPlan(plan),
							"inner", INNER, innerPlan(plan),
							str, indent, es);
793
			show_upper_qual(((HashJoin *) plan)->join.joinqual,
794
							"Join Filter",
795 796 797
							"outer", OUTER, outerPlan(plan),
							"inner", INNER, innerPlan(plan),
							str, indent, es);
798 799
			show_upper_qual(plan->qual,
							"Filter",
800 801 802 803 804 805
							"outer", OUTER, outerPlan(plan),
							"inner", INNER, innerPlan(plan),
							str, indent, es);
			break;
		case T_Agg:
		case T_Group:
806 807
			show_upper_qual(plan->qual,
							"Filter",
808 809 810 811
							"subplan", 0, outerPlan(plan),
							"", 0, NULL,
							str, indent, es);
			break;
812
		case T_Sort:
813 814 815
			show_sort_keys(plan->targetlist,
						   ((Sort *) plan)->numCols,
						   ((Sort *) plan)->sortColIdx,
816 817 818
						   "Sort Key",
						   str, indent, es);
			break;
819 820
		case T_Result:
			show_upper_qual((List *) ((Result *) plan)->resconstantqual,
821
							"One-Time Filter",
822 823 824
							"subplan", OUTER, outerPlan(plan),
							"", 0, NULL,
							str, indent, es);
825 826
			show_upper_qual(plan->qual,
							"Filter",
827 828 829 830 831 832 833 834
							"subplan", OUTER, outerPlan(plan),
							"", 0, NULL,
							str, indent, es);
			break;
		default:
			break;
	}

V
Vadim B. Mikheev 已提交
835 836 837
	/* initPlan-s */
	if (plan->initPlan)
	{
838
		List	   *saved_rtable = es->rtable;
839
		ListCell   *lst;
840

B
Bruce Momjian 已提交
841
		for (i = 0; i < indent; i++)
V
Vadim B. Mikheev 已提交
842 843
			appendStringInfo(str, "  ");
		appendStringInfo(str, "  InitPlan\n");
844
		foreach(lst, planstate->initPlan)
V
Vadim B. Mikheev 已提交
845
		{
846
			SubPlanState *sps = (SubPlanState *) lfirst(lst);
B
Bruce Momjian 已提交
847
			SubPlan    *sp = (SubPlan *) sps->xprstate.expr;
848

849
			es->rtable = sp->rtable;
V
Vadim B. Mikheev 已提交
850 851 852
			for (i = 0; i < indent; i++)
				appendStringInfo(str, "  ");
			appendStringInfo(str, "    ->  ");
853 854
			explain_outNode(str, sp->plan,
							sps->planstate,
855
							NULL,
856
							indent + 4, es);
V
Vadim B. Mikheev 已提交
857 858 859
		}
		es->rtable = saved_rtable;
	}
860 861 862 863 864 865

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

868
		/*
B
Bruce Momjian 已提交
869 870
		 * 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
871 872
		 * BitmapIndexScan nodes may have outer references.
		 */
873 874
		explain_outNode(str, outerPlan(plan),
						outerPlanState(planstate),
875
						IsA(plan, BitmapHeapScan) ? outer_plan : NULL,
876
						indent + 3, es);
877
	}
878 879 880 881 882 883

	/* righttree */
	if (innerPlan(plan))
	{
		for (i = 0; i < indent; i++)
			appendStringInfo(str, "  ");
V
Vadim B. Mikheev 已提交
884
		appendStringInfo(str, "  ->  ");
885 886 887
		explain_outNode(str, innerPlan(plan),
						innerPlanState(planstate),
						outerPlan(plan),
888
						indent + 3, es);
V
Vadim B. Mikheev 已提交
889
	}
890

891
	if (IsA(plan, Append))
892
	{
893
		Append	   *appendplan = (Append *) plan;
894
		AppendState *appendstate = (AppendState *) planstate;
895
		ListCell   *lst;
896
		int			j;
897

898
		j = 0;
899 900
		foreach(lst, appendplan->appendplans)
		{
901
			Plan	   *subnode = (Plan *) lfirst(lst);
902 903 904

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

907 908 909 910 911 912
			/*
			 * 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
			 * looking at an appendrel indexscan with outer references
			 * from the member scans.
			 */
913 914
			explain_outNode(str, subnode,
							appendstate->appendplans[j],
915
							outer_plan,
916 917
							indent + 3, es);
			j++;
918 919
		}
	}
920

921 922
	if (IsA(plan, BitmapAnd))
	{
B
Bruce Momjian 已提交
923
		BitmapAnd  *bitmapandplan = (BitmapAnd *) plan;
924 925 926 927 928 929 930 931 932 933 934 935 936 937 938
		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 已提交
939
							outer_plan, /* pass down same outer plan */
940 941 942 943 944 945 946
							indent + 3, es);
			j++;
		}
	}

	if (IsA(plan, BitmapOr))
	{
B
Bruce Momjian 已提交
947
		BitmapOr   *bitmaporplan = (BitmapOr *) plan;
948 949 950 951 952 953 954 955 956 957 958 959 960 961 962
		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 已提交
963
							outer_plan, /* pass down same outer plan */
964 965 966 967 968
							indent + 3, es);
			j++;
		}
	}

969 970 971
	if (IsA(plan, SubqueryScan))
	{
		SubqueryScan *subqueryscan = (SubqueryScan *) plan;
972
		SubqueryScanState *subquerystate = (SubqueryScanState *) planstate;
973 974 975 976 977
		Plan	   *subnode = subqueryscan->subplan;
		RangeTblEntry *rte = rt_fetch(subqueryscan->scan.scanrelid,
									  es->rtable);
		List	   *saved_rtable = es->rtable;

978
		Assert(rte->rtekind == RTE_SUBQUERY);
979 980 981 982 983 984
		es->rtable = rte->subquery->rtable;

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

985 986 987 988
		explain_outNode(str, subnode,
						subquerystate->subplan,
						NULL,
						indent + 3, es);
989 990 991 992 993

		es->rtable = saved_rtable;
	}

	/* subPlan-s */
994
	if (planstate->subPlan)
995 996
	{
		List	   *saved_rtable = es->rtable;
997
		ListCell   *lst;
998 999 1000 1001

		for (i = 0; i < indent; i++)
			appendStringInfo(str, "  ");
		appendStringInfo(str, "  SubPlan\n");
1002
		foreach(lst, planstate->subPlan)
1003
		{
1004
			SubPlanState *sps = (SubPlanState *) lfirst(lst);
B
Bruce Momjian 已提交
1005
			SubPlan    *sp = (SubPlan *) sps->xprstate.expr;
1006 1007

			es->rtable = sp->rtable;
1008 1009 1010
			for (i = 0; i < indent; i++)
				appendStringInfo(str, "  ");
			appendStringInfo(str, "    ->  ");
1011 1012 1013
			explain_outNode(str, sp->plan,
							sps->planstate,
							NULL,
1014 1015 1016 1017
							indent + 4, es);
		}
		es->rtable = saved_rtable;
	}
1018 1019
}

1020 1021 1022 1023
/*
 * Show a qualifier expression for a scan plan node
 */
static void
1024
show_scan_qual(List *qual, const char *qlabel,
1025
			   int scanrelid, Plan *outer_plan,
1026 1027 1028
			   StringInfo str, int indent, ExplainState *es)
{
	RangeTblEntry *rte;
1029 1030
	Node	   *scancontext;
	Node	   *outercontext;
1031 1032 1033 1034 1035 1036 1037 1038 1039
	List	   *context;
	Node	   *node;
	char	   *exprstr;
	int			i;

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

1040 1041
	/* Convert AND list to explicit AND */
	node = (Node *) make_ands_explicit(qual);
1042

1043
	/* Generate deparse context */
1044
	Assert(scanrelid > 0 && scanrelid <= list_length(es->rtable));
1045
	rte = rt_fetch(scanrelid, es->rtable);
1046
	scancontext = deparse_context_for_rte(rte);
1047 1048

	/*
B
Bruce Momjian 已提交
1049 1050 1051
	 * If we have an outer plan that is referenced by the qual, add it to the
	 * deparse context.  If not, don't (so that we don't force prefixes
	 * unnecessarily).
1052 1053 1054
	 */
	if (outer_plan)
	{
B
Bruce Momjian 已提交
1055
		Relids		varnos = pull_varnos(node);
1056 1057

		if (bms_is_member(OUTER, varnos))
1058
			outercontext = deparse_context_for_subplan("outer",
B
Bruce Momjian 已提交
1059
													   outer_plan->targetlist,
1060 1061 1062
													   es->rtable);
		else
			outercontext = NULL;
1063
		bms_free(varnos);
1064
	}
1065
	else
1066 1067 1068
		outercontext = NULL;

	context = deparse_context_for_plan(scanrelid, scancontext,
1069 1070
									   OUTER, outercontext,
									   NIL);
1071 1072

	/* Deparse the expression */
1073
	exprstr = deparse_expression(node, context, (outercontext != NULL), false);
1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114

	/* 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
show_upper_qual(List *qual, const char *qlabel,
				const char *outer_name, int outer_varno, Plan *outer_plan,
				const char *inner_name, int inner_varno, Plan *inner_plan,
				StringInfo str, int indent, ExplainState *es)
{
	List	   *context;
	Node	   *outercontext;
	Node	   *innercontext;
	Node	   *node;
	char	   *exprstr;
	int			i;

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

	/* Generate deparse context */
	if (outer_plan)
		outercontext = deparse_context_for_subplan(outer_name,
												   outer_plan->targetlist,
												   es->rtable);
	else
		outercontext = NULL;
	if (inner_plan)
		innercontext = deparse_context_for_subplan(inner_name,
												   inner_plan->targetlist,
												   es->rtable);
	else
		innercontext = NULL;
	context = deparse_context_for_plan(outer_varno, outercontext,
1115 1116
									   inner_varno, innercontext,
									   NIL);
1117 1118 1119

	/* Deparse the expression */
	node = (Node *) make_ands_explicit(qual);
1120
	exprstr = deparse_expression(node, context, (inner_plan != NULL), false);
1121 1122 1123 1124 1125 1126 1127

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

1128 1129 1130 1131
/*
 * Show the sort keys for a Sort node.
 */
static void
1132 1133
show_sort_keys(List *tlist, int nkeys, AttrNumber *keycols,
			   const char *qlabel,
1134 1135 1136 1137 1138 1139
			   StringInfo str, int indent, ExplainState *es)
{
	List	   *context;
	bool		useprefix;
	int			keyno;
	char	   *exprstr;
1140
	Relids		varnos;
1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151
	int			i;

	if (nkeys <= 0)
		return;

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

	/*
	 * In this routine we expect that the plan node's tlist has not been
B
Bruce Momjian 已提交
1152 1153 1154 1155
	 * processed by set_plan_references().	Normally, any Vars will contain
	 * valid varnos referencing the actual rtable.	But we might instead be
	 * looking at a dummy tlist generated by prepunion.c; if there are Vars
	 * with zero varno, use the tlist itself to determine their names.
1156
	 */
1157 1158
	varnos = pull_varnos((Node *) tlist);
	if (bms_is_member(0, varnos))
1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174
	{
		Node	   *outercontext;

		outercontext = deparse_context_for_subplan("sort",
												   tlist,
												   es->rtable);
		context = deparse_context_for_plan(0, outercontext,
										   0, NULL,
										   NIL);
		useprefix = false;
	}
	else
	{
		context = deparse_context_for_plan(0, NULL,
										   0, NULL,
										   es->rtable);
1175
		useprefix = list_length(es->rtable) > 1;
1176
	}
1177
	bms_free(varnos);
1178

1179
	for (keyno = 0; keyno < nkeys; keyno++)
1180 1181
	{
		/* find key expression in tlist */
1182
		AttrNumber	keyresno = keycols[keyno];
1183
		TargetEntry *target = get_tle_by_resno(tlist, keyresno);
1184

1185
		if (!target)
1186
			elog(ERROR, "no tlist entry for key %d", keyresno);
1187 1188 1189 1190 1191 1192
		/* 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 已提交
1193
		appendStringInfoString(str, exprstr);
1194 1195 1196 1197
	}

	appendStringInfo(str, "\n");
}