Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion crates/polyglot-sql/src/dialects/normalization/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2248,7 +2248,11 @@ pub(super) fn normalize(
// DATE_BIN -> TIME_BUCKET for DuckDB
"DATE_BIN" if matches!(target, DialectType::DuckDB) => Action::Temporal(temporal::Action::DateBinConvert),
// Multi-arg MIN(a,b,c) -> LEAST, MAX(a,b,c) -> GREATEST
"MIN" | "MAX" if f.args.len() > 1 && !matches!(target, DialectType::SQLite) => Action::Scalar(scalar::Action::MinMaxToLeastGreatest),
// ...except Presto/Trino's two-argument MIN(x, n)/MAX(x, n), the
// aggregate of the n smallest/largest values, which sqlglot keeps.
"MIN" | "MAX" if f.args.len() > 1
&& !matches!(target, DialectType::SQLite)
&& !(f.args.len() == 2 && matches!(source, DialectType::Presto | DialectType::Trino | DialectType::Athena)) => Action::Scalar(scalar::Action::MinMaxToLeastGreatest),
// ClickHouse uniq -> APPROX_COUNT_DISTINCT for other dialects
"UNIQ" if matches!(source, DialectType::ClickHouse) && !matches!(target, DialectType::ClickHouse) => Action::Aggregates(aggregates::Action::ClickHouseUniqToApproxCountDistinct),
// ClickHouse any -> ANY_VALUE for other dialects
Expand Down
39 changes: 39 additions & 0 deletions crates/polyglot-sql/tests/presto_max_min_top_n.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
//! In Presto and Trino, two-argument `max(x, n)` / `min(x, n)` is an aggregate:
//! an array of the `n` largest / smallest values of `x`. It is not the scalar
//! `GREATEST`/`LEAST` it means in other dialects, and sqlglot reprints it
//! unchanged.

use polyglot_sql::{transpile, DialectType};

fn reprint(sql: &str, dialect: DialectType) -> String {
transpile(sql, dialect, dialect)
.unwrap_or_else(|e| panic!("failed to transpile {sql:?}: {e}"))
.remove(0)
}

#[test]
fn two_argument_max_and_min_stay_aggregates() {
for dialect in [DialectType::Trino, DialectType::Presto, DialectType::Athena] {
for sql in [
"SELECT MAX(x, 3) FROM t",
"SELECT MIN(x, 3) FROM t",
"SELECT k, MAX(x, 2) AS top FROM t GROUP BY k",
] {
assert_eq!(reprint(sql, dialect), sql, "{dialect:?}");
}
}
}

#[test]
fn many_argument_max_from_other_dialects_is_still_greatest() {
assert_eq!(
transpile(
"SELECT MAX(a, b, c)",
DialectType::Generic,
DialectType::Trino
)
.unwrap()
.remove(0),
"SELECT GREATEST(a, b, c)",
);
}
Loading