* parseCheckAggregates * Check for aggregates where they shouldn't be and improper grouping. * This function should be called after the target list and qualifications * are finalized. * * Misplaced aggregates are now mostly detected in transformAggregateCall, * but it seems more robust to check for aggregates in recursive queries * only after everything is finalized. In any case it's hard
| 1129 | * query for that. |
| 1130 | */ |
| 1131 | void |
| 1132 | parseCheckAggregates(ParseState *pstate, Query *qry) |
| 1133 | { |
| 1134 | List *gset_common = NIL; |
| 1135 | List *groupClauses = NIL; |
| 1136 | List *groupClauseCommonVars = NIL; |
| 1137 | bool have_non_var_grouping; |
| 1138 | List *func_grouped_rels = NIL; |
| 1139 | ListCell *l; |
| 1140 | bool hasJoinRTEs; |
| 1141 | bool hasSelfRefRTEs; |
| 1142 | Node *clause; |
| 1143 | |
| 1144 | /* This should only be called if we found aggregates or grouping */ |
| 1145 | Assert(pstate->p_hasAggs || qry->groupClause || qry->havingQual || qry->groupingSets); |
| 1146 | |
| 1147 | /* |
| 1148 | * If we have grouping sets, expand them and find the intersection of all |
| 1149 | * sets. |
| 1150 | */ |
| 1151 | if (qry->groupingSets) |
| 1152 | { |
| 1153 | /* |
| 1154 | * The limit of 4096 is arbitrary and exists simply to avoid resource |
| 1155 | * issues from pathological constructs. |
| 1156 | */ |
| 1157 | List *gsets = expand_grouping_sets(qry->groupingSets, qry->groupDistinct, 4096); |
| 1158 | |
| 1159 | if (!gsets) |
| 1160 | ereport(ERROR, |
| 1161 | (errcode(ERRCODE_STATEMENT_TOO_COMPLEX), |
| 1162 | errmsg("too many grouping sets present (maximum 4096)"), |
| 1163 | parser_errposition(pstate, |
| 1164 | qry->groupClause |
| 1165 | ? exprLocation((Node *) qry->groupClause) |
| 1166 | : exprLocation((Node *) qry->groupingSets)))); |
| 1167 | |
| 1168 | /* |
| 1169 | * The intersection will often be empty, so help things along by |
| 1170 | * seeding the intersect with the smallest set. |
| 1171 | */ |
| 1172 | gset_common = linitial(gsets); |
| 1173 | |
| 1174 | if (gset_common) |
| 1175 | { |
| 1176 | for_each_from(l, gsets, 1) |
| 1177 | { |
| 1178 | gset_common = list_intersection_int(gset_common, lfirst(l)); |
| 1179 | if (!gset_common) |
| 1180 | break; |
| 1181 | } |
| 1182 | } |
| 1183 | |
| 1184 | /* |
| 1185 | * If there was only one grouping set in the expansion, AND if the |
| 1186 | * groupClause is non-empty (meaning that the grouping set is not |
| 1187 | * empty either), then we can ditch the grouping set and pretend we |
| 1188 | * just had a normal GROUP BY. |
no test coverage detected