Skip to main content

uqa_execution/query/block/foreign/
predicates.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! SQL predicates eligible for foreign-handler pushdown.
8
9use crate::{eval_scalar, ScalarEvalContext};
10use uqa_core::Value;
11use uqa_sql::{ast::BinaryOp, SQLParam, ScalarExpr};
12
13pub fn fdw_predicates_from_where(
14    expr: Option<&ScalarExpr>,
15    params: &[SQLParam],
16) -> Vec<uqa_fdw::FDWPredicate> {
17    let Some(expr) = expr else {
18        return Vec::new();
19    };
20    let mut out = Vec::new();
21    collect_fdw_predicates(expr, params, &mut out);
22    out
23}
24
25pub fn collect_fdw_predicates(
26    expr: &ScalarExpr,
27    params: &[SQLParam],
28    out: &mut Vec<uqa_fdw::FDWPredicate>,
29) {
30    match expr {
31        ScalarExpr::And(parts) => {
32            for part in parts {
33                collect_fdw_predicates(part, params, out);
34            }
35        }
36        _ => {
37            if let Some(predicate) = fdw_predicate(expr, params) {
38                out.push(predicate);
39            }
40        }
41    }
42}
43
44pub fn fdw_predicate(expr: &ScalarExpr, params: &[SQLParam]) -> Option<uqa_fdw::FDWPredicate> {
45    match expr {
46        ScalarExpr::Binary { op, lhs, rhs } => {
47            if let Some(column) = fdw_column_name(lhs) {
48                let value = fdw_const_value(rhs, params)?;
49                return Some(uqa_fdw::FDWPredicate {
50                    column,
51                    operator: fdw_binary_op(*op)?,
52                    value,
53                });
54            }
55            if let Some(column) = fdw_column_name(rhs) {
56                let value = fdw_const_value(lhs, params)?;
57                return Some(uqa_fdw::FDWPredicate {
58                    column,
59                    operator: fdw_reversed_binary_op(*op)?,
60                    value,
61                });
62            }
63            None
64        }
65        ScalarExpr::InList {
66            expr,
67            list,
68            negated,
69        } if !negated => {
70            let column = fdw_column_name(expr)?;
71            let values = list
72                .iter()
73                .map(|item| fdw_const_value(item, params))
74                .collect::<Option<Vec<_>>>()?;
75            Some(uqa_fdw::FDWPredicate {
76                column,
77                operator: uqa_fdw::PredicateOp::In,
78                value: Value::List(values),
79            })
80        }
81        ScalarExpr::IsNull { expr, negated } => Some(uqa_fdw::FDWPredicate {
82            column: fdw_column_name(expr)?,
83            operator: if *negated {
84                uqa_fdw::PredicateOp::NotEq
85            } else {
86                uqa_fdw::PredicateOp::Eq
87            },
88            value: Value::Null,
89        }),
90        ScalarExpr::Func { binding, args, .. } => {
91            fdw_like_predicate(binding.as_ref(), args, false, params)
92        }
93        ScalarExpr::Not(inner) => match inner.as_ref() {
94            ScalarExpr::Func { binding, args, .. } => {
95                fdw_like_predicate(binding.as_ref(), args, true, params)
96            }
97            _ => None,
98        },
99        _ => None,
100    }
101}
102
103/// A LIKE or NOT LIKE call with a determinate input collation. LIKE compares characters exactly under every built-in collation, so a handler keeps the rows the canonical operator keeps. ILIKE stays in the canonical evaluator: it lowercases through the provider of its input collation, while a handler folds case by its own rules, and a row a handler rejects is never evaluated again. The canonical operator likewise reports an indeterminate collation for each row it evaluates.
104pub fn fdw_like_predicate(
105    binding: Option<&uqa_sql::ast::FunctionBinding>,
106    args: &[ScalarExpr],
107    negated: bool,
108    params: &[SQLParam],
109) -> Option<uqa_fdw::FDWPredicate> {
110    if args.len() != 2 {
111        return None;
112    }
113    let uqa_sql::ast::FunctionDispatch::Pattern { operator, .. } = binding?.dispatch? else {
114        return None;
115    };
116    if !operator.is_like()
117        || operator.case_insensitive()
118        || uqa_sql::ast::FunctionBinding::selected_input_collation(binding) == 0
119    {
120        return None;
121    }
122    let operator = if operator.negated() == negated {
123        uqa_fdw::PredicateOp::Like
124    } else {
125        uqa_fdw::PredicateOp::NotLike
126    };
127    let value = fdw_const_value(&args[1], params)?;
128    let Value::Str(pattern) = &value else {
129        return None;
130    };
131    // Foreign SQL dialects do not agree on the implicit LIKE escape.
132    // Keep backslash-bearing patterns in the canonical PostgreSQL evaluator.
133    if pattern.contains('\\') {
134        return None;
135    }
136    Some(uqa_fdw::FDWPredicate {
137        column: fdw_column_name(&args[0])?,
138        operator,
139        value,
140    })
141}
142
143pub fn fdw_column_name(expr: &ScalarExpr) -> Option<String> {
144    match expr {
145        ScalarExpr::Column(name) => Some(name.to_string()),
146        ScalarExpr::QualifiedColumn { column, .. } => Some(column.to_string()),
147        _ => None,
148    }
149}
150
151pub fn fdw_const_value(expr: &ScalarExpr, params: &[SQLParam]) -> Option<Value> {
152    let ctx = ScalarEvalContext::new(None, params);
153    eval_scalar(expr, &ctx).ok()
154}
155
156pub fn fdw_binary_op(op: BinaryOp) -> Option<uqa_fdw::PredicateOp> {
157    Some(match op {
158        BinaryOp::Equal => uqa_fdw::PredicateOp::Eq,
159        BinaryOp::NotEqual => uqa_fdw::PredicateOp::NotEq,
160        BinaryOp::Less => uqa_fdw::PredicateOp::Lt,
161        BinaryOp::LessEqual => uqa_fdw::PredicateOp::LtEq,
162        BinaryOp::Greater => uqa_fdw::PredicateOp::Gt,
163        BinaryOp::GreaterEqual => uqa_fdw::PredicateOp::GtEq,
164        BinaryOp::Add | BinaryOp::Subtract | BinaryOp::Multiply | BinaryOp::Divide => return None,
165    })
166}
167
168pub fn fdw_reversed_binary_op(op: BinaryOp) -> Option<uqa_fdw::PredicateOp> {
169    Some(match op {
170        BinaryOp::Equal => uqa_fdw::PredicateOp::Eq,
171        BinaryOp::NotEqual => uqa_fdw::PredicateOp::NotEq,
172        BinaryOp::Less => uqa_fdw::PredicateOp::Gt,
173        BinaryOp::LessEqual => uqa_fdw::PredicateOp::GtEq,
174        BinaryOp::Greater => uqa_fdw::PredicateOp::Lt,
175        BinaryOp::GreaterEqual => uqa_fdw::PredicateOp::LtEq,
176        BinaryOp::Add | BinaryOp::Subtract | BinaryOp::Multiply | BinaryOp::Divide => return None,
177    })
178}
179
180#[cfg(test)]
181mod tests;