Skip to main content

no_mistakes_postgres_sql/
order.rs

1#[derive(Debug, Clone, PartialEq, Eq)]
2pub struct CanonicalOrderKey {
3    pub expression: String,
4    pub ascending: bool,
5    pub nulls_first: bool,
6}
7
8/// PostgreSQL `USING` operators leave sort direction unspecified.
9pub fn order_by_ascending(options: &sqlparser::ast::OrderByOptions) -> Option<bool> {
10    match options.sort.as_ref() {
11        Some(sqlparser::ast::OrderBySort::Asc) => Some(true),
12        Some(sqlparser::ast::OrderBySort::Desc) => Some(false),
13        Some(sqlparser::ast::OrderBySort::Using(_)) | None => None,
14    }
15}
16
17/// Canonical `ORDER BY` keys. `USING` operators make the whole list unanalyzable.
18pub fn canonical_order_keys(order: &sqlparser::ast::OrderBy) -> Option<Vec<CanonicalOrderKey>> {
19    let sqlparser::ast::OrderByKind::Expressions(expressions) = &order.kind else {
20        return None;
21    };
22    if expressions.iter().any(|expression| {
23        matches!(
24            expression.options.sort,
25            Some(sqlparser::ast::OrderBySort::Using(_))
26        )
27    }) {
28        return None;
29    }
30    Some(
31        expressions
32            .iter()
33            .map(|expression| {
34                let ascending = order_by_ascending(&expression.options).unwrap_or(true);
35                CanonicalOrderKey {
36                    expression: expression.expr.to_string(),
37                    ascending,
38                    nulls_first: expression.options.nulls_first.unwrap_or(!ascending),
39                }
40            })
41            .collect(),
42    )
43}