* rewriteQueryForIMMV -- rewrite view definition query for IMMV * * count(*) is added for counting distinct tuples in views. * Also, additional hidden columns are added for aggregate values. */
| 601 | * Also, additional hidden columns are added for aggregate values. |
| 602 | */ |
| 603 | Query * |
| 604 | rewriteQueryForIMMV(Query *query, List *colNames) |
| 605 | { |
| 606 | Query *rewritten; |
| 607 | |
| 608 | Node *node; |
| 609 | ParseState *pstate = make_parsestate(NULL); |
| 610 | FuncCall *fn; |
| 611 | |
| 612 | rewritten = copyObject(query); |
| 613 | pstate->p_expr_kind = EXPR_KIND_SELECT_TARGET; |
| 614 | |
| 615 | /* group keys must be in targetlist */ |
| 616 | if (rewritten->groupClause) |
| 617 | { |
| 618 | ListCell *lc; |
| 619 | foreach(lc, rewritten->groupClause) |
| 620 | { |
| 621 | SortGroupClause *scl = (SortGroupClause *) lfirst(lc); |
| 622 | TargetEntry *tle = get_sortgroupclause_tle(scl, rewritten->targetList); |
| 623 | |
| 624 | if (tle->resjunk) |
| 625 | ereport(ERROR, |
| 626 | (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), |
| 627 | errmsg("GROUP BY expression not appearing in select list is not supported on incrementally maintainable materialized view"))); |
| 628 | } |
| 629 | } |
| 630 | /* Convert DISTINCT to GROUP BY. count(*) will be added afterward. */ |
| 631 | else if (!rewritten->hasAggs && rewritten->distinctClause) |
| 632 | rewritten->groupClause = transformDistinctClause(NULL, &rewritten->targetList, rewritten->sortClause, false); |
| 633 | |
| 634 | /* Add additional columns for aggregate values */ |
| 635 | if (rewritten->hasAggs) |
| 636 | { |
| 637 | ListCell *lc; |
| 638 | List *aggs = NIL; |
| 639 | AttrNumber next_resno = list_length(rewritten->targetList) + 1; |
| 640 | |
| 641 | foreach(lc, rewritten->targetList) |
| 642 | { |
| 643 | TargetEntry *tle = (TargetEntry *) lfirst(lc); |
| 644 | char *resname = (colNames == NIL || foreach_current_index(lc) >= list_length(colNames) ? |
| 645 | tle->resname : strVal(list_nth(colNames, tle->resno - 1))); |
| 646 | |
| 647 | if (IsA(tle->expr, Aggref)) |
| 648 | makeIvmAggColumn(pstate, (Aggref *) tle->expr, resname, &next_resno, &aggs); |
| 649 | } |
| 650 | rewritten->targetList = list_concat(rewritten->targetList, aggs); |
| 651 | } |
| 652 | |
| 653 | /* Add count(*) for counting distinct tuples in views */ |
| 654 | if (rewritten->distinctClause || rewritten->hasAggs) |
| 655 | { |
| 656 | TargetEntry *tle; |
| 657 | |
| 658 | fn = makeFuncCall(SystemFuncName("count"), NIL, COERCE_EXPLICIT_CALL, -1); |
| 659 | fn->agg_star = true; |
| 660 |
no test coverage detected