* DISTINCT/DISTINCT ON/ORDER BY optimization. * Remove DISTINCT clause if possibile, ex: * select DISTINCT count(a) from t; to * select count(a) from t; * There is one row returned at most, DISTINCT and/or ON is pointless then. * The same with ORDER BY clause; */
| 549 | * The same with ORDER BY clause; |
| 550 | */ |
| 551 | Query *remove_distinct_sort_clause(Query *parse) |
| 552 | { |
| 553 | if (parse->hasAggs && |
| 554 | parse->groupClause == NIL && |
| 555 | !contain_mutable_functions((Node *) parse) && |
| 556 | !tlist_has_srf(parse)) |
| 557 | { |
| 558 | List *useless_tlist = NIL; |
| 559 | List *tles; |
| 560 | List *sortops; |
| 561 | List *eqops; |
| 562 | ListCell *lc; |
| 563 | |
| 564 | if (parse->distinctClause != NIL) |
| 565 | { |
| 566 | get_sortgroupclauses_tles(parse->distinctClause, parse->targetList, |
| 567 | &tles, &sortops, &eqops); |
| 568 | foreach(lc, tles) |
| 569 | { |
| 570 | TargetEntry *tle = lfirst(lc); |
| 571 | if (tle->resjunk) |
| 572 | useless_tlist = lappend(useless_tlist, tle); |
| 573 | } |
| 574 | parse->distinctClause = NIL; |
| 575 | if (parse->hasDistinctOn) |
| 576 | parse->hasDistinctOn = false; |
| 577 | } |
| 578 | |
| 579 | if (parse->sortClause != NIL) |
| 580 | { |
| 581 | |
| 582 | get_sortgroupclauses_tles(parse->sortClause, parse->targetList, |
| 583 | &tles, &sortops, &eqops); |
| 584 | foreach(lc, tles) |
| 585 | { |
| 586 | TargetEntry *tle = lfirst(lc); |
| 587 | /* |
| 588 | * For SELECT DISTINCT, ORDER BY expressions must appear in select list, |
| 589 | * Some tles may be already in the list. |
| 590 | */ |
| 591 | if (tle->resjunk) |
| 592 | useless_tlist = list_append_unique(useless_tlist, tle); |
| 593 | } |
| 594 | parse->sortClause = NIL; |
| 595 | } |
| 596 | |
| 597 | /* |
| 598 | * There is no groupClause, sortClause and distinctClause now . |
| 599 | * The junk TargetEntrys with ressortgroupref index are safe to be removed. |
| 600 | */ |
| 601 | if (useless_tlist != NIL) |
| 602 | parse->targetList = list_difference(parse->targetList, useless_tlist); |
| 603 | } |
| 604 | |
| 605 | return parse; |
| 606 | } |
no test coverage detected