------------------------------------------------------------------------- * Flatten out parenthesized sublists in grouping lists, and some cases * of nested grouping sets. * * Inside a grouping set (ROLLUP, CUBE, or GROUPING SETS), we expect the * content to be nested no more than 2 deep: i.e. ROLLUP((a,b),(c,d)) is * ok, but ROLLUP((a,(b,c)),d) is flattened to ((a,b,c),d), which we then *
| 2342 | *------------------------------------------------------------------------- |
| 2343 | */ |
| 2344 | static Node * |
| 2345 | flatten_grouping_sets(Node *expr, bool toplevel, bool *hasGroupingSets) |
| 2346 | { |
| 2347 | /* just in case of pathological input */ |
| 2348 | check_stack_depth(); |
| 2349 | |
| 2350 | if (expr == (Node *) NIL) |
| 2351 | return (Node *) NIL; |
| 2352 | |
| 2353 | switch (expr->type) |
| 2354 | { |
| 2355 | case T_RowExpr: |
| 2356 | { |
| 2357 | RowExpr *r = (RowExpr *) expr; |
| 2358 | |
| 2359 | if (r->row_format == COERCE_IMPLICIT_CAST) |
| 2360 | return flatten_grouping_sets((Node *) r->args, |
| 2361 | false, NULL); |
| 2362 | } |
| 2363 | break; |
| 2364 | case T_GroupingSet: |
| 2365 | { |
| 2366 | GroupingSet *gset = (GroupingSet *) expr; |
| 2367 | ListCell *l2; |
| 2368 | List *result_set = NIL; |
| 2369 | |
| 2370 | if (hasGroupingSets) |
| 2371 | *hasGroupingSets = true; |
| 2372 | |
| 2373 | /* |
| 2374 | * at the top level, we skip over all empty grouping sets; the |
| 2375 | * caller can supply the canonical GROUP BY () if nothing is |
| 2376 | * left. |
| 2377 | */ |
| 2378 | |
| 2379 | if (toplevel && gset->kind == GROUPING_SET_EMPTY) |
| 2380 | return (Node *) NIL; |
| 2381 | |
| 2382 | foreach(l2, gset->content) |
| 2383 | { |
| 2384 | Node *n1 = lfirst(l2); |
| 2385 | Node *n2 = flatten_grouping_sets(n1, false, NULL); |
| 2386 | |
| 2387 | if (IsA(n1, GroupingSet) && |
| 2388 | ((GroupingSet *) n1)->kind == GROUPING_SET_SETS) |
| 2389 | result_set = list_concat(result_set, (List *) n2); |
| 2390 | else |
| 2391 | result_set = lappend(result_set, n2); |
| 2392 | } |
| 2393 | |
| 2394 | /* |
| 2395 | * At top level, keep the grouping set node; but if we're in a |
| 2396 | * nested grouping set, then we need to concat the flattened |
| 2397 | * result into the outer list if it's simply nested. |
| 2398 | */ |
| 2399 | |
| 2400 | if (toplevel || (gset->kind != GROUPING_SET_SETS)) |
| 2401 | { |
no test coverage detected