explain.c 25.3 KB
Newer Older
1 2
/*-------------------------------------------------------------------------
 *
3
 * explain.c
4
 *	  Explain query execution plans
5
 *
B
Bruce Momjian 已提交
6
 * Portions Copyright (c) 1996-2004, 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.127 2004/09/30 17:42:42 tgl Exp $
11
 *
12
 *-------------------------------------------------------------------------
13
 */
14
#include "postgres.h"
M
Marc G. Fournier 已提交
15

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

36

37 38 39
typedef struct ExplainState
{
	/* options */
40
	bool		printCost;		/* print cost */
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,
B
Bruce Momjian 已提交
48
				TupOutputState *tstate);
B
Bruce Momjian 已提交
49
static double elapsed_time(struct timeval * 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, bool is_or_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
static Node *make_ors_ands_explicit(List *orclauses);
65 66 67

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

78
	/* prepare for projection of tuples */
79
	tstate = begin_tup_output_tupdesc(dest, ExplainResultDesc(stmt));
80

81 82
	if (query->commandType == CMD_UTILITY)
	{
83
		/* Rewriter will not cope with utility statements */
84 85 86
		if (query->utilityStmt && IsA(query->utilityStmt, DeclareCursorStmt))
			ExplainOneQuery(query, stmt, tstate);
		else if (query->utilityStmt && IsA(query->utilityStmt, ExecuteStmt))
87 88 89
			ExplainExecuteQuery(stmt, tstate);
		else
			do_text_output_oneline(tstate, "Utility statements have no plan structure");
90
	}
91
	else
B
Bruce Momjian 已提交
92
	{
93 94 95 96 97 98
		/* Rewrite through rule system */
		rewritten = QueryRewrite(query);

		if (rewritten == NIL)
		{
			/* In the case of an INSTEAD NOTHING, tell at least that */
99
			do_text_output_oneline(tstate, "Query rewrites to nothing");
100 101 102 103 104 105 106 107
		}
		else
		{
			/* Explain every plan */
			foreach(l, rewritten)
			{
				ExplainOneQuery(lfirst(l), stmt, tstate);
				/* put a blank line between plans */
108
				if (lnext(l) != NULL)
109
					do_text_output_oneline(tstate, "");
110 111
			}
		}
B
Bruce Momjian 已提交
112 113
	}

114
	end_tup_output(tstate);
B
Bruce Momjian 已提交
115 116
}

117 118 119 120 121 122 123 124 125 126 127 128
/*
 * 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",
129
					   TEXTOID, -1, 0);
130 131 132
	return tupdesc;
}

B
Bruce Momjian 已提交
133 134 135 136 137
/*
 * ExplainOneQuery -
 *	  print out the execution plan for one query
 */
static void
138
ExplainOneQuery(Query *query, ExplainStmt *stmt, TupOutputState *tstate)
B
Bruce Momjian 已提交
139 140
{
	Plan	   *plan;
141
	QueryDesc  *queryDesc;
142 143
	bool		isCursor = false;
	int			cursorOptions = 0;
B
Bruce Momjian 已提交
144

145 146 147
	/* planner will not cope with utility statements */
	if (query->commandType == CMD_UTILITY)
	{
148 149 150 151 152 153 154 155 156 157 158 159
		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);
			rewritten = QueryRewrite(query);
160
			if (list_length(rewritten) != 1)
161
				elog(ERROR, "unexpected rewrite result");
162
			query = (Query *) linitial(rewritten);
163 164 165 166 167 168
			Assert(query->commandType == CMD_SELECT);
			/* do not actually execute the underlying query! */
			stmt->analyze = false;
		}
		else if (query->utilityStmt && IsA(query->utilityStmt, NotifyStmt))
		{
169
			do_text_output_oneline(tstate, "NOTIFY");
170 171
			return;
		}
172
		else
173
		{
174
			do_text_output_oneline(tstate, "UTILITY");
175 176
			return;
		}
177 178
	}

179
	/* plan the query */
180
	plan = planner(query, isCursor, cursorOptions, NULL);
B
Bruce Momjian 已提交
181

182
	/* Create a QueryDesc requesting no output */
183 184 185
	queryDesc = CreateQueryDesc(query, plan,
								ActiveSnapshot, InvalidSnapshot,
								None_Receiver, NULL,
186 187
								stmt->analyze);

188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
	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)
{
	struct timeval starttime;
	double		totaltime = 0;
	ExplainState *es;
	StringInfo	str;

	gettimeofday(&starttime, NULL);

212 213 214 215
	/* If analyzing, we need to cope with queued triggers */
	if (stmt->analyze)
		AfterTriggerBeginQuery();

216
	/* call ExecutorStart to prepare the plan for execution */
217
	ExecutorStart(queryDesc, !stmt->analyze);
218

219
	/* Execute the plan for statistics if asked for */
220
	if (stmt->analyze)
221
	{
222 223
		/* run the plan */
		ExecutorRun(queryDesc, ForwardScanDirection, 0L);
224

225 226
		/* We can't clean up 'till we're done printing the stats... */
		totaltime += elapsed_time(&starttime);
227 228
	}

229
	es = (ExplainState *) palloc0(sizeof(ExplainState));
B
Bruce Momjian 已提交
230

231
	es->printCost = true;		/* default */
232 233
	es->printNodes = stmt->verbose;
	es->printAnalyze = stmt->analyze;
234
	es->rtable = queryDesc->parsetree->rtable;
235 236

	if (es->printNodes)
237
	{
238
		char	   *s;
239
		char	   *f;
240

241
		s = nodeToString(queryDesc->plantree);
242 243
		if (s)
		{
244 245 246 247
			if (Explain_pretty_print)
				f = pretty_format_node_dump(s);
			else
				f = format_node_dump(s);
248
			pfree(s);
249 250 251
			do_text_output_multiline(tstate, f);
			pfree(f);
			if (es->printCost)
B
Bruce Momjian 已提交
252
				do_text_output_oneline(tstate, "");		/* separator line */
253 254
		}
	}
255

256 257
	str = makeStringInfo();

258 259
	if (es->printCost)
	{
260
		explain_outNode(str, queryDesc->plantree, queryDesc->planstate,
261 262 263 264
						NULL, 0, es);
	}

	/*
265 266
	 * Close down the query and free resources; also run any queued
	 * AFTER triggers.  Include time for this in the total runtime.
267 268
	 */
	gettimeofday(&starttime, NULL);
269

270
	ExecutorEnd(queryDesc);
271 272 273 274

	if (stmt->analyze)
		AfterTriggerEndQuery();

275 276
	FreeQueryDesc(queryDesc);

277 278 279
	/* We need a CCI just in case query expanded to multiple plans */
	if (stmt->analyze)
		CommandCounterIncrement();
280 281 282 283 284

	totaltime += elapsed_time(&starttime);

	if (es->printCost)
	{
285
		if (stmt->analyze)
286
			appendStringInfo(str, "Total runtime: %.3f ms\n",
287
							 1000.0 * totaltime);
288
		do_text_output_multiline(tstate, str->data);
B
Bruce Momjian 已提交
289
	}
290

291 292
	pfree(str->data);
	pfree(str);
B
Bruce Momjian 已提交
293
	pfree(es);
294 295
}

296 297
/* Compute elapsed time in seconds since given gettimeofday() timestamp */
static double
B
Bruce Momjian 已提交
298
elapsed_time(struct timeval * starttime)
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
{
	struct timeval endtime;

	gettimeofday(&endtime, NULL);

	endtime.tv_sec -= starttime->tv_sec;
	endtime.tv_usec -= starttime->tv_usec;
	while (endtime.tv_usec < 0)
	{
		endtime.tv_usec += 1000000;
		endtime.tv_sec--;
	}
	return (double) endtime.tv_sec +
		(double) endtime.tv_usec / 1000000.0;
}
314 315 316

/*
 * explain_outNode -
317 318
 *	  converts a Plan node into ascii string and appends it to 'str'
 *
319 320 321 322
 * 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.
 *
323 324 325
 * 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.
326 327
 */
static void
328
explain_outNode(StringInfo str,
329
				Plan *plan, PlanState *planstate,
330
				Plan *outer_plan,
331
				int indent, ExplainState *es)
332
{
B
Bruce Momjian 已提交
333
	ListCell   *l;
B
Bruce Momjian 已提交
334 335
	char	   *pname;
	int			i;
336 337 338

	if (plan == NULL)
	{
339
		appendStringInfoChar(str, '\n');
340 341 342 343 344
		return;
	}

	switch (nodeTag(plan))
	{
345 346 347 348 349 350 351
		case T_Result:
			pname = "Result";
			break;
		case T_Append:
			pname = "Append";
			break;
		case T_NestLoop:
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
			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;
			}
373 374
			break;
		case T_MergeJoin:
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
			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;
			}
396 397
			break;
		case T_HashJoin:
398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418
			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;
			}
419 420 421 422 423 424 425
			break;
		case T_SeqScan:
			pname = "Seq Scan";
			break;
		case T_IndexScan:
			pname = "Index Scan";
			break;
426 427 428 429 430 431
		case T_TidScan:
			pname = "Tid Scan";
			break;
		case T_SubqueryScan:
			pname = "Subquery Scan";
			break;
432 433 434
		case T_FunctionScan:
			pname = "Function Scan";
			break;
435 436 437
		case T_Material:
			pname = "Materialize";
			break;
438 439 440 441 442 443 444
		case T_Sort:
			pname = "Sort";
			break;
		case T_Group:
			pname = "Group";
			break;
		case T_Agg:
445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
			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;
			}
460 461 462 463
			break;
		case T_Unique:
			pname = "Unique";
			break;
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
		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;
484 485 486
		case T_Limit:
			pname = "Limit";
			break;
487 488 489 490
		case T_Hash:
			pname = "Hash";
			break;
		default:
491
			pname = "???";
492
			break;
493 494
	}

495
	appendStringInfoString(str, pname);
496 497
	switch (nodeTag(plan))
	{
498
		case T_IndexScan:
499
			if (ScanDirectionIsBackward(((IndexScan *) plan)->indxorderdir))
500 501
				appendStringInfoString(str, " Backward");
			appendStringInfoString(str, " using ");
V
Vadim B. Mikheev 已提交
502
			i = 0;
B
Bruce Momjian 已提交
503
			foreach(l, ((IndexScan *) plan)->indxid)
V
Vadim B. Mikheev 已提交
504
			{
505
				char	   *indname;
506

507
				indname = get_rel_name(lfirst_oid(l));
508 509
				appendStringInfo(str, "%s%s",
								 (++i > 1) ? ", " : "",
510
								 quote_identifier(indname));
V
Vadim B. Mikheev 已提交
511
			}
512
			/* FALL THRU */
513
		case T_SeqScan:
514
		case T_TidScan:
515 516
			if (((Scan *) plan)->scanrelid > 0)
			{
517 518
				RangeTblEntry *rte = rt_fetch(((Scan *) plan)->scanrelid,
											  es->rtable);
B
Bruce Momjian 已提交
519
				char	   *relname;
520 521

				/* Assume it's on a real relation */
522
				Assert(rte->rtekind == RTE_RELATION);
523 524 525

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

527
				appendStringInfo(str, " on %s",
528
								 quote_identifier(relname));
529
				if (strcmp(rte->eref->aliasname, relname) != 0)
530
					appendStringInfo(str, " %s",
B
Bruce Momjian 已提交
531
								 quote_identifier(rte->eref->aliasname));
532 533 534 535 536 537 538 539 540
			}
			break;
		case T_SubqueryScan:
			if (((Scan *) plan)->scanrelid > 0)
			{
				RangeTblEntry *rte = rt_fetch(((Scan *) plan)->scanrelid,
											  es->rtable);

				appendStringInfo(str, " %s",
541
								 quote_identifier(rte->eref->aliasname));
542 543
			}
			break;
544 545 546 547 548
		case T_FunctionScan:
			if (((Scan *) plan)->scanrelid > 0)
			{
				RangeTblEntry *rte = rt_fetch(((Scan *) plan)->scanrelid,
											  es->rtable);
B
Bruce Momjian 已提交
549
				char	   *proname;
550 551 552 553

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

554 555 556
				/*
				 * If the expression is still a function call, we can get
				 * the real name of the function.  Otherwise, punt (this
B
Bruce Momjian 已提交
557 558
				 * can happen if the optimizer simplified away the
				 * function call, for example).
559 560 561 562 563 564 565 566 567 568 569
				 */
				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;
570 571 572 573 574

				appendStringInfo(str, " on %s",
								 quote_identifier(proname));
				if (strcmp(rte->eref->aliasname, proname) != 0)
					appendStringInfo(str, " %s",
B
Bruce Momjian 已提交
575
								 quote_identifier(rte->eref->aliasname));
576 577
			}
			break;
578 579
		default:
			break;
580 581 582
	}
	if (es->printCost)
	{
583 584 585
		appendStringInfo(str, "  (cost=%.2f..%.2f rows=%.0f width=%d)",
						 plan->startup_cost, plan->total_cost,
						 plan->plan_rows, plan->plan_width);
586

587 588 589 590 591 592 593
		/*
		 * We have to forcibly clean up the instrumentation state because
		 * we haven't done ExecutorEnd yet.  This is pretty grotty ...
		 */
		InstrEndLoop(planstate->instrument);

		if (planstate->instrument && planstate->instrument->nloops > 0)
594
		{
595
			double		nloops = planstate->instrument->nloops;
596

597
			appendStringInfo(str, " (actual time=%.3f..%.3f rows=%.0f loops=%.0f)",
B
Bruce Momjian 已提交
598 599
						1000.0 * planstate->instrument->startup / nloops,
						  1000.0 * planstate->instrument->total / nloops,
600 601
							 planstate->instrument->ntuples / nloops,
							 planstate->instrument->nloops);
602
		}
603
		else if (es->printAnalyze)
604
			appendStringInfo(str, " (never executed)");
605
	}
606
	appendStringInfoChar(str, '\n');
607

608
	/* quals, sort keys, etc */
609 610 611 612
	switch (nodeTag(plan))
	{
		case T_IndexScan:
			show_scan_qual(((IndexScan *) plan)->indxqualorig, true,
613
						   "Index Cond",
614
						   ((Scan *) plan)->scanrelid,
615
						   outer_plan,
616
						   str, indent, es);
617 618
			show_scan_qual(plan->qual, false,
						   "Filter",
619
						   ((Scan *) plan)->scanrelid,
620
						   outer_plan,
621 622 623 624
						   str, indent, es);
			break;
		case T_SeqScan:
		case T_TidScan:
625
		case T_SubqueryScan:
626
		case T_FunctionScan:
627 628
			show_scan_qual(plan->qual, false,
						   "Filter",
629
						   ((Scan *) plan)->scanrelid,
630
						   outer_plan,
631 632 633
						   str, indent, es);
			break;
		case T_NestLoop:
634
			show_upper_qual(((NestLoop *) plan)->join.joinqual,
635
							"Join Filter",
636 637 638
							"outer", OUTER, outerPlan(plan),
							"inner", INNER, innerPlan(plan),
							str, indent, es);
639 640
			show_upper_qual(plan->qual,
							"Filter",
641 642 643 644 645
							"outer", OUTER, outerPlan(plan),
							"inner", INNER, innerPlan(plan),
							str, indent, es);
			break;
		case T_MergeJoin:
646 647
			show_upper_qual(((MergeJoin *) plan)->mergeclauses,
							"Merge Cond",
648 649 650
							"outer", OUTER, outerPlan(plan),
							"inner", INNER, innerPlan(plan),
							str, indent, es);
651
			show_upper_qual(((MergeJoin *) plan)->join.joinqual,
652
							"Join Filter",
653 654 655
							"outer", OUTER, outerPlan(plan),
							"inner", INNER, innerPlan(plan),
							str, indent, es);
656 657
			show_upper_qual(plan->qual,
							"Filter",
658 659 660 661 662
							"outer", OUTER, outerPlan(plan),
							"inner", INNER, innerPlan(plan),
							str, indent, es);
			break;
		case T_HashJoin:
663 664
			show_upper_qual(((HashJoin *) plan)->hashclauses,
							"Hash Cond",
665 666 667
							"outer", OUTER, outerPlan(plan),
							"inner", INNER, innerPlan(plan),
							str, indent, es);
668
			show_upper_qual(((HashJoin *) plan)->join.joinqual,
669
							"Join Filter",
670 671 672
							"outer", OUTER, outerPlan(plan),
							"inner", INNER, innerPlan(plan),
							str, indent, es);
673 674
			show_upper_qual(plan->qual,
							"Filter",
675 676 677 678 679 680
							"outer", OUTER, outerPlan(plan),
							"inner", INNER, innerPlan(plan),
							str, indent, es);
			break;
		case T_Agg:
		case T_Group:
681 682
			show_upper_qual(plan->qual,
							"Filter",
683 684 685 686
							"subplan", 0, outerPlan(plan),
							"", 0, NULL,
							str, indent, es);
			break;
687
		case T_Sort:
688 689 690
			show_sort_keys(plan->targetlist,
						   ((Sort *) plan)->numCols,
						   ((Sort *) plan)->sortColIdx,
691 692 693
						   "Sort Key",
						   str, indent, es);
			break;
694 695
		case T_Result:
			show_upper_qual((List *) ((Result *) plan)->resconstantqual,
696
							"One-Time Filter",
697 698 699
							"subplan", OUTER, outerPlan(plan),
							"", 0, NULL,
							str, indent, es);
700 701
			show_upper_qual(plan->qual,
							"Filter",
702 703 704 705 706 707 708 709
							"subplan", OUTER, outerPlan(plan),
							"", 0, NULL,
							str, indent, es);
			break;
		default:
			break;
	}

V
Vadim B. Mikheev 已提交
710 711 712
	/* initPlan-s */
	if (plan->initPlan)
	{
713
		List	   *saved_rtable = es->rtable;
714
		ListCell   *lst;
715

B
Bruce Momjian 已提交
716
		for (i = 0; i < indent; i++)
V
Vadim B. Mikheev 已提交
717 718
			appendStringInfo(str, "  ");
		appendStringInfo(str, "  InitPlan\n");
719
		foreach(lst, planstate->initPlan)
V
Vadim B. Mikheev 已提交
720
		{
721
			SubPlanState *sps = (SubPlanState *) lfirst(lst);
B
Bruce Momjian 已提交
722
			SubPlan    *sp = (SubPlan *) sps->xprstate.expr;
723

724
			es->rtable = sp->rtable;
V
Vadim B. Mikheev 已提交
725 726 727
			for (i = 0; i < indent; i++)
				appendStringInfo(str, "  ");
			appendStringInfo(str, "    ->  ");
728 729
			explain_outNode(str, sp->plan,
							sps->planstate,
730
							NULL,
731
							indent + 4, es);
V
Vadim B. Mikheev 已提交
732 733 734
		}
		es->rtable = saved_rtable;
	}
735 736 737 738 739 740

	/* lefttree */
	if (outerPlan(plan))
	{
		for (i = 0; i < indent; i++)
			appendStringInfo(str, "  ");
V
Vadim B. Mikheev 已提交
741
		appendStringInfo(str, "  ->  ");
742 743 744 745
		explain_outNode(str, outerPlan(plan),
						outerPlanState(planstate),
						NULL,
						indent + 3, es);
746
	}
747 748 749 750 751 752

	/* righttree */
	if (innerPlan(plan))
	{
		for (i = 0; i < indent; i++)
			appendStringInfo(str, "  ");
V
Vadim B. Mikheev 已提交
753
		appendStringInfo(str, "  ->  ");
754 755 756
		explain_outNode(str, innerPlan(plan),
						innerPlanState(planstate),
						outerPlan(plan),
757
						indent + 3, es);
V
Vadim B. Mikheev 已提交
758
	}
759

760
	if (IsA(plan, Append))
761
	{
762
		Append	   *appendplan = (Append *) plan;
763
		AppendState *appendstate = (AppendState *) planstate;
764
		ListCell   *lst;
765
		int			j;
766

767
		j = 0;
768 769
		foreach(lst, appendplan->appendplans)
		{
770
			Plan	   *subnode = (Plan *) lfirst(lst);
771 772 773

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

776 777 778 779 780
			explain_outNode(str, subnode,
							appendstate->appendplans[j],
							NULL,
							indent + 3, es);
			j++;
781 782
		}
	}
783 784 785 786

	if (IsA(plan, SubqueryScan))
	{
		SubqueryScan *subqueryscan = (SubqueryScan *) plan;
787
		SubqueryScanState *subquerystate = (SubqueryScanState *) planstate;
788 789 790 791 792
		Plan	   *subnode = subqueryscan->subplan;
		RangeTblEntry *rte = rt_fetch(subqueryscan->scan.scanrelid,
									  es->rtable);
		List	   *saved_rtable = es->rtable;

793
		Assert(rte->rtekind == RTE_SUBQUERY);
794 795 796 797 798 799
		es->rtable = rte->subquery->rtable;

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

800 801 802 803
		explain_outNode(str, subnode,
						subquerystate->subplan,
						NULL,
						indent + 3, es);
804 805 806 807 808

		es->rtable = saved_rtable;
	}

	/* subPlan-s */
809
	if (planstate->subPlan)
810 811
	{
		List	   *saved_rtable = es->rtable;
812
		ListCell   *lst;
813 814 815 816

		for (i = 0; i < indent; i++)
			appendStringInfo(str, "  ");
		appendStringInfo(str, "  SubPlan\n");
817
		foreach(lst, planstate->subPlan)
818
		{
819
			SubPlanState *sps = (SubPlanState *) lfirst(lst);
B
Bruce Momjian 已提交
820
			SubPlan    *sp = (SubPlan *) sps->xprstate.expr;
821 822

			es->rtable = sp->rtable;
823 824 825
			for (i = 0; i < indent; i++)
				appendStringInfo(str, "  ");
			appendStringInfo(str, "    ->  ");
826 827 828
			explain_outNode(str, sp->plan,
							sps->planstate,
							NULL,
829 830 831 832
							indent + 4, es);
		}
		es->rtable = saved_rtable;
	}
833 834
}

835 836 837 838 839
/*
 * Show a qualifier expression for a scan plan node
 */
static void
show_scan_qual(List *qual, bool is_or_qual, const char *qlabel,
840
			   int scanrelid, Plan *outer_plan,
841 842 843
			   StringInfo str, int indent, ExplainState *es)
{
	RangeTblEntry *rte;
844 845
	Node	   *scancontext;
	Node	   *outercontext;
846 847 848 849 850 851 852 853
	List	   *context;
	Node	   *node;
	char	   *exprstr;
	int			i;

	/* No work if empty qual */
	if (qual == NIL)
		return;
854 855
	if (is_or_qual && list_length(qual) == 1 && linitial(qual) == NIL)
		return;
856

857 858 859 860 861 862
	/* Fix qual --- indexqual requires different processing */
	if (is_or_qual)
		node = make_ors_ands_explicit(qual);
	else
		node = (Node *) make_ands_explicit(qual);

863
	/* Generate deparse context */
864
	Assert(scanrelid > 0 && scanrelid <= list_length(es->rtable));
865
	rte = rt_fetch(scanrelid, es->rtable);
866
	scancontext = deparse_context_for_rte(rte);
867 868 869

	/*
	 * If we have an outer plan that is referenced by the qual, add it to
B
Bruce Momjian 已提交
870 871
	 * the deparse context.  If not, don't (so that we don't force
	 * prefixes unnecessarily).
872 873 874
	 */
	if (outer_plan)
	{
B
Bruce Momjian 已提交
875
		Relids		varnos = pull_varnos(node);
876 877

		if (bms_is_member(OUTER, varnos))
878
			outercontext = deparse_context_for_subplan("outer",
B
Bruce Momjian 已提交
879
												  outer_plan->targetlist,
880 881 882
													   es->rtable);
		else
			outercontext = NULL;
883
		bms_free(varnos);
884
	}
885
	else
886 887 888
		outercontext = NULL;

	context = deparse_context_for_plan(scanrelid, scancontext,
889 890
									   OUTER, outercontext,
									   NIL);
891 892

	/* Deparse the expression */
893
	exprstr = deparse_expression(node, context, (outercontext != NULL), false);
894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934

	/* 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,
935 936
									   inner_varno, innercontext,
									   NIL);
937 938 939

	/* Deparse the expression */
	node = (Node *) make_ands_explicit(qual);
940
	exprstr = deparse_expression(node, context, (inner_plan != NULL), false);
941 942 943 944 945 946 947

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

948 949 950 951
/*
 * Show the sort keys for a Sort node.
 */
static void
952 953
show_sort_keys(List *tlist, int nkeys, AttrNumber *keycols,
			   const char *qlabel,
954 955 956 957 958 959
			   StringInfo str, int indent, ExplainState *es)
{
	List	   *context;
	bool		useprefix;
	int			keyno;
	char	   *exprstr;
960
	Relids		varnos;
961 962 963 964 965 966 967 968 969 970 971
	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 已提交
972 973 974 975 976
	 * 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.
977
	 */
978 979
	varnos = pull_varnos((Node *) tlist);
	if (bms_is_member(0, varnos))
980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995
	{
		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);
996
		useprefix = list_length(es->rtable) > 1;
997
	}
998
	bms_free(varnos);
999

1000
	for (keyno = 0; keyno < nkeys; keyno++)
1001 1002
	{
		/* find key expression in tlist */
1003
		AttrNumber	keyresno = keycols[keyno];
1004
		TargetEntry *target = get_tle_by_resno(tlist, keyresno);
1005

1006
		if (!target)
1007
			elog(ERROR, "no tlist entry for key %d", keyresno);
1008 1009 1010 1011 1012 1013
		/* 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 已提交
1014
		appendStringInfoString(str, exprstr);
1015 1016 1017 1018 1019
	}

	appendStringInfo(str, "\n");
}

1020
/*
B
Bruce Momjian 已提交
1021
 * Indexscan qual lists have an implicit OR-of-ANDs structure.	Make it
1022 1023 1024 1025 1026 1027 1028
 * explicit so deparsing works properly.
 */
static Node *
make_ors_ands_explicit(List *orclauses)
{
	if (orclauses == NIL)
		return NULL;			/* probably can't happen */
1029 1030
	else if (list_length(orclauses) == 1)
		return (Node *) make_ands_explicit(linitial(orclauses));
1031 1032
	else
	{
1033 1034
		List	   *args = NIL;
		ListCell   *orptr;
1035 1036

		foreach(orptr, orclauses)
1037
			args = lappend(args, make_ands_explicit(lfirst(orptr)));
1038

1039
		return (Node *) make_orclause(args);
1040 1041
	}
}