diff --git a/pgdog/src/frontend/client/query_engine/test/unsupported_aggregation.rs b/pgdog/src/frontend/client/query_engine/test/unsupported_aggregation.rs index d8dcf4038..2a517aeff 100644 --- a/pgdog/src/frontend/client/query_engine/test/unsupported_aggregation.rs +++ b/pgdog/src/frontend/client/query_engine/test/unsupported_aggregation.rs @@ -18,6 +18,11 @@ async fn test_unsupported_aggregation_keeps_connection_usable() { "SELECT count(DISTINCT value) FROM sharded", "unsupported aggregation count: count(DISTINCT ...) is not yet supported", ), + ( + // The cast must not hide DISTINCT and let per-shard counts be summed. + "SELECT count(DISTINCT value)::int FROM sharded", + "unsupported aggregation count: count(DISTINCT ...) is not yet supported", + ), ( "SELECT count(*) FROM sharded HAVING count(*) > 0 LIMIT (SELECT 1)", "cross-shard HAVING is unsupported: \ diff --git a/pgdog/src/frontend/router/parser/aggregate.rs b/pgdog/src/frontend/router/parser/aggregate.rs index 4f58c1280..a2b9331d8 100644 --- a/pgdog/src/frontend/router/parser/aggregate.rs +++ b/pgdog/src/frontend/router/parser/aggregate.rs @@ -363,21 +363,19 @@ impl Aggregate { .iter() .enumerate() .filter_map(|(idx, node)| { - let func = Function::try_from(node.val()).ok()?; - let function = AggregateFunction::from_name(func.name, schema)?; - - // FIXME: This doesn't correctly handle distinct behind type - // casts any other nodes that Function::try_from handles - let distinct = if let Node::FuncCall(func) = node.val() { - func.agg_distinct - } else { - false - }; + // The call may sit behind a cast, e.g. `count(DISTINCT x)::int`. + let call = Function::extract_func_call(node.val())?; + let name = call + .funcname() + .iter() + .filter_map(Node::as_str) + .next_back()?; + let function = AggregateFunction::from_name(name, schema)?; Some(AggregateTarget { column: idx, function, - distinct, + distinct: call.agg_distinct, }) }) .collect(); @@ -465,6 +463,20 @@ mod test { assert!(!avg.is_distinct()); } + #[test] + fn test_parse_distinct_behind_cast() { + let aggr = parse( + "SELECT COUNT(DISTINCT price)::int, CAST(SUM(DISTINCT price) AS numeric)::text, \ + COUNT(price)::int FROM menu", + ); + let distinct = aggr + .targets() + .iter() + .map(AggregateTarget::is_distinct) + .collect::>(); + assert_eq!(distinct, vec![true, true, false]); + } + #[test] fn test_parse_bool_and_bit_aggregates() { let aggr = parse(