uqa-sql 0.6.1

PostgreSQL-compatible SQL compiler built on libpg_query
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
//
// Unified Query Algebra
//
// Copyright (c) 2023-2026 Cognica, Inc.
//

//! SQL operator, boolean, and null-test lowering.

use super::expression_core::{builtin_syntax_call, dispatched_call};
use super::{compile_expr, extract_strings, BinaryOp, Expr, NodeEnum, Result, SQLError, Value};
use crate::ast::{FunctionDispatch, NumericOperator, PatternOperator};

fn compile_pattern_operand(
    rhs: &pg_query::protobuf::Node,
    wrapper_name: &str,
    operator_name: &str,
    operator_location: i32,
) -> Result<Expr> {
    let Some(NodeEnum::FuncCall(function)) = rhs.node.as_ref() else {
        return compile_expr(rhs);
    };
    let function_name = extract_strings(&function.funcname)?;
    if function.location != operator_location
        || !matches!(function_name.as_slice(), [schema, local] if schema == "pg_catalog" && local == wrapper_name)
    {
        return compile_expr(rhs);
    }
    if function.agg_distinct
        || function.agg_star
        || function.agg_within_group
        || function.func_variadic
        || !function.agg_order.is_empty()
        || function.agg_filter.is_some()
        || function.over.is_some()
    {
        return Err(SQLError::Internal(format!(
            "{operator_name} wrapper contains aggregate/function modifiers"
        )));
    }
    if !matches!(function.args.len(), 1 | 2) {
        return Err(SQLError::Internal(format!(
            "{wrapper_name} expects a pattern and optional escape"
        )));
    }
    Ok(dispatched_call(
        FunctionDispatch::PatternEscape {
            similar: wrapper_name == "similar_to_escape",
        },
        function
            .args
            .iter()
            .map(compile_expr)
            .collect::<Result<Vec<_>>>()?,
    ))
}

#[expect(
    clippy::too_many_lines,
    reason = "ordered PostgreSQL lowering preserves syntax and error precedence"
)]
pub(in crate::compiler) fn compile_a_expr(a: &pg_query::protobuf::AExpr) -> Result<Expr> {
    use pg_query::protobuf::AExprKind;
    let kind = a.kind();
    match kind {
        AExprKind::AexprOp => compile_operator(a),
        AExprKind::AexprBetween
        | AExprKind::AexprNotBetween
        | AExprKind::AexprBetweenSym
        | AExprKind::AexprNotBetweenSym => compile_between(a),
        AExprKind::AexprDistinct | AExprKind::AexprNotDistinct => {
            let lhs = a
                .lexpr
                .as_ref()
                .ok_or_else(|| SQLError::Internal("IS DISTINCT FROM without lhs".into()))?;
            let rhs = a
                .rexpr
                .as_ref()
                .ok_or_else(|| SQLError::Internal("IS DISTINCT FROM without rhs".into()))?;
            let left = compile_expr(lhs)?;
            let right = compile_expr(rhs)?;
            if matches!(left, Expr::Literal(Value::Null))
                || matches!(right, Expr::Literal(Value::Null))
            {
                let argument = if matches!(right, Expr::Literal(Value::Null)) {
                    left
                } else {
                    right
                };
                return Ok(dispatched_call(
                    FunctionDispatch::ValueNullTest {
                        negated: matches!(kind, AExprKind::AexprDistinct),
                    },
                    vec![argument],
                ));
            }
            let call = dispatched_call(FunctionDispatch::IsDistinct, vec![left, right]);
            Ok(if matches!(kind, AExprKind::AexprNotDistinct) {
                dispatched_call(FunctionDispatch::DistinctNot, vec![call])
            } else {
                call
            })
        }
        AExprKind::AexprSimilar => {
            // `expr SIMILAR TO pattern` arrives with the pattern
            // wrapped in `similar_to_escape(pattern[, escape])`.
            let op_name = extract_strings(&a.name)?.join("");
            let lhs = a
                .lexpr
                .as_ref()
                .ok_or_else(|| SQLError::Internal("SIMILAR TO without lhs".into()))?;
            let rhs = a
                .rexpr
                .as_ref()
                .ok_or_else(|| SQLError::Internal("SIMILAR TO without rhs".into()))?;
            let args = vec![
                compile_expr(lhs)?,
                compile_pattern_operand(rhs, "similar_to_escape", "SIMILAR TO", a.location)?,
            ];
            let operator = match op_name.as_str() {
                "~" => PatternOperator::Regex,
                "!~" => PatternOperator::NotRegex,
                other => {
                    return Err(SQLError::Internal(format!(
                        "SIMILAR TO has unexpected operator `{other}`"
                    )))
                }
            };
            Ok(dispatched_call(
                FunctionDispatch::Pattern {
                    operator,
                    oid: None,
                },
                args,
            ))
        }
        AExprKind::AexprOpAny | AExprKind::AexprOpAll => {
            let op_name = extract_strings(&a.name)?.join("");
            let lhs = a
                .lexpr
                .as_ref()
                .ok_or_else(|| SQLError::Internal("ANY/ALL without lhs".into()))?;
            let rhs = a
                .rexpr
                .as_ref()
                .ok_or_else(|| SQLError::Internal("ANY/ALL without rhs".into()))?;
            let dispatch = if matches!(kind, AExprKind::AexprOpAny) {
                FunctionDispatch::AnyOperator
            } else {
                FunctionDispatch::AllOperator
            };
            Ok(dispatched_call(
                dispatch,
                vec![
                    compile_expr(lhs)?,
                    compile_expr(rhs)?,
                    Expr::Literal(Value::Str(op_name)),
                ],
            ))
        }
        AExprKind::AexprNullif => {
            let lhs = a
                .lexpr
                .as_ref()
                .ok_or_else(|| SQLError::Internal("NULLIF without lhs".into()))?;
            let rhs = a
                .rexpr
                .as_ref()
                .ok_or_else(|| SQLError::Internal("NULLIF without rhs".into()))?;
            return Ok(builtin_syntax_call(
                "nullif",
                vec![compile_expr(lhs)?, compile_expr(rhs)?],
            ));
        }
        AExprKind::AexprLike | AExprKind::AexprIlike => {
            let op_name = extract_strings(&a.name)?.join("");
            let operator = PatternOperator::from_symbol(&op_name)
                .filter(|operator| operator.is_like())
                .ok_or_else(|| {
                    SQLError::Internal(format!("LIKE has unexpected operator `{op_name}`"))
                })?;
            let lhs = a
                .lexpr
                .as_ref()
                .ok_or_else(|| SQLError::Internal("LIKE without lhs".into()))?;
            let rhs = a
                .rexpr
                .as_ref()
                .ok_or_else(|| SQLError::Internal("LIKE without rhs".into()))?;
            let args = vec![
                compile_expr(lhs)?,
                compile_pattern_operand(rhs, "like_escape", "LIKE", a.location)?,
            ];
            Ok(dispatched_call(
                FunctionDispatch::Pattern {
                    operator,
                    oid: None,
                },
                args,
            ))
        }
        AExprKind::AexprIn => {
            let expr = a
                .lexpr
                .as_ref()
                .ok_or_else(|| SQLError::Internal("IN without lhs".into()))?;
            let rhs = a
                .rexpr
                .as_ref()
                .ok_or_else(|| SQLError::Internal("IN without rhs".into()))?;
            let items = match rhs.node.as_ref() {
                Some(NodeEnum::List(l)) => l.items.clone(),
                _ => return Err(SQLError::Internal("IN expects list".into())),
            };
            let list: Vec<Expr> = items.iter().map(compile_expr).collect::<Result<Vec<_>>>()?;
            let operator = extract_strings(&a.name)?.join("");
            let negated = match operator.as_str() {
                "=" => false,
                "<>" => true,
                other => {
                    return Err(SQLError::Internal(format!(
                        "IN has unexpected operator `{other}`"
                    )));
                }
            };
            Ok(Expr::InList {
                expr: Box::new(compile_expr(expr)?),
                list,
                negated,
            })
        }
        other => Err(SQLError::Unsupported(format!("AExpr kind: {other:?}"))),
    }
}

// Select the output node before reading children, then lower each operand once. Recursive calls retain two operand slots instead of a separate pair for every operator spelling.
enum OperatorLowering {
    Binary(BinaryOp),
    Dispatched(FunctionDispatch),
    Call(&'static str),
}

impl OperatorLowering {
    fn select(name: &str) -> Result<Self> {
        Ok(match name {
            "=" => Self::Binary(BinaryOp::Equal),
            "<>" | "!=" => Self::Binary(BinaryOp::NotEqual),
            "<" => Self::Binary(BinaryOp::Less),
            "<=" => Self::Binary(BinaryOp::LessEqual),
            ">" => Self::Binary(BinaryOp::Greater),
            ">=" => Self::Binary(BinaryOp::GreaterEqual),
            "+" => Self::Binary(BinaryOp::Add),
            "-" => Self::Binary(BinaryOp::Subtract),
            "*" => Self::Binary(BinaryOp::Multiply),
            "/" => Self::Binary(BinaryOp::Divide),
            "||" => Self::Dispatched(FunctionDispatch::Concat { oid: None }),
            "%" => Self::Dispatched(FunctionDispatch::NumericOperator(NumericOperator::Modulo)),
            "^" => Self::Dispatched(FunctionDispatch::NumericOperator(NumericOperator::Power)),
            "~" | "~*" | "!~" | "!~*" | "~~" | "!~~" | "~~*" | "!~~*" | "^@" => {
                Self::Dispatched(FunctionDispatch::Pattern {
                    operator: PatternOperator::from_symbol(name).expect("pattern symbol"),
                    oid: None,
                })
            }
            "->" | "->>" => Self::Dispatched(FunctionDispatch::JsonExtract {
                as_text: name == "->>",
                path: false,
            }),
            "#>" | "#>>" => Self::Dispatched(FunctionDispatch::JsonExtract {
                as_text: name == "#>>",
                path: true,
            }),
            "@@" => Self::Call("fts_match"),
            "@?" => Self::Call("jsonpath_exists"),
            "&&" => Self::Call("array_overlap"),
            "-|-" => Self::Call("range_adjacent"),
            "#-" => Self::Call("json_delete_path"),
            "@>" => Self::Call("contains_op"),
            "<@" => Self::Call("contained_by_op"),
            "?" => Self::Call("json_has_key"),
            "?|" => Self::Call("json_has_any_key"),
            "?&" => Self::Call("json_has_all_keys"),
            other => return Err(SQLError::Unsupported(format!("operator `{other}`"))),
        })
    }

    fn finish(self, lhs: Expr, rhs: Expr) -> Expr {
        match self {
            Self::Binary(op) => Expr::Binary {
                op,
                lhs: Box::new(lhs),
                rhs: Box::new(rhs),
            },
            Self::Dispatched(dispatch) => dispatched_call(dispatch, vec![lhs, rhs]),
            Self::Call(name) => Expr::Func {
                order_syntax: crate::ast::FunctionOrderSyntax::Ordinary,
                binding: None,
                name: name.into(),
                args: vec![lhs, rhs],
                distinct: false,
                order_by: Vec::new(),
                filter: None,
            },
        }
    }
}

fn compile_operator(a: &pg_query::protobuf::AExpr) -> Result<Expr> {
    let names = extract_strings(&a.name)?;
    let op_name = match names.as_slice() {
        [schema, operator] if schema == "pg_catalog" => operator.clone(),
        _ => names.join("."),
    };
    if a.lexpr.is_none() {
        let rhs = a
            .rexpr
            .as_ref()
            .ok_or_else(|| SQLError::Internal("AExpr missing rhs".into()))?;
        return compile_unary_operator(&op_name, rhs);
    }
    let lhs = a
        .lexpr
        .as_ref()
        .ok_or_else(|| SQLError::Internal("AExpr missing lhs".into()))?;
    let rhs = a
        .rexpr
        .as_ref()
        .ok_or_else(|| SQLError::Internal("AExpr missing rhs".into()))?;
    let target = OperatorLowering::select(&op_name)?;
    let left = compile_expr(lhs)?;
    let right = compile_expr(rhs)?;
    Ok(target.finish(left, right))
}

fn compile_unary_operator(name: &str, rhs: &pg_query::protobuf::Node) -> Result<Expr> {
    let rhs = compile_expr(rhs)?;
    let numeric_operator = |operator, argument| {
        dispatched_call(FunctionDispatch::NumericOperator(operator), vec![argument])
    };
    match name {
        "+" => Ok(numeric_operator(NumericOperator::Plus, rhs)),
        "-" => Ok(Expr::UnaryMinus(Box::new(rhs))),
        "|/" => Ok(numeric_operator(NumericOperator::SquareRoot, rhs)),
        "||/" => Ok(numeric_operator(NumericOperator::CubeRoot, rhs)),
        "@" => Ok(numeric_operator(NumericOperator::Absolute, rhs)),
        other => Err(SQLError::Unsupported(format!("unary operator `{other}`"))),
    }
}

pub(in crate::compiler) fn compile_bool_expr(b: &pg_query::protobuf::BoolExpr) -> Result<Expr> {
    use pg_query::protobuf::BoolExprType;
    let kind = b.boolop();
    let args: Vec<Expr> = b
        .args
        .iter()
        .map(compile_expr)
        .collect::<Result<Vec<_>>>()?;
    match kind {
        BoolExprType::AndExpr if args.len() >= 2 => Ok(Expr::And(args)),
        BoolExprType::OrExpr if args.len() >= 2 => Ok(Expr::Or(args)),
        BoolExprType::AndExpr | BoolExprType::OrExpr => Err(SQLError::Internal(format!(
            "{kind:?} requires at least two operands, got {}",
            args.len()
        ))),
        BoolExprType::NotExpr => {
            let [arg] = args.as_slice() else {
                return Err(SQLError::Internal(format!(
                    "NOT requires exactly one operand, got {}",
                    args.len()
                )));
            };
            Ok(Expr::Not(Box::new(arg.clone())))
        }
        _ => Err(SQLError::Unsupported(format!("BoolExpr {kind:?}"))),
    }
}

pub(in crate::compiler) fn compile_null_test(n: &pg_query::protobuf::NullTest) -> Result<Expr> {
    use pg_query::protobuf::NullTestType;
    let arg = n
        .arg
        .as_ref()
        .ok_or_else(|| SQLError::Internal("NullTest without arg".into()))?;
    let negated = match n.nulltesttype() {
        NullTestType::IsNull => false,
        NullTestType::IsNotNull => true,
        other => {
            return Err(SQLError::Internal(format!(
                "NullTest has invalid kind {other:?}"
            )));
        }
    };
    Ok(Expr::IsNull {
        expr: Box::new(compile_expr(arg)?),
        negated,
    })
}

/// Expand before binding so each comparison owns its coercions, subqueries and runtime state, as `PostgreSQL`'s `transformAExprBetween` does.
fn compile_between(a: &pg_query::protobuf::AExpr) -> Result<Expr> {
    use pg_query::protobuf::AExprKind;
    let value = a
        .lexpr
        .as_ref()
        .ok_or_else(|| SQLError::Internal("BETWEEN without lhs".into()))?;
    let rhs = a
        .rexpr
        .as_ref()
        .ok_or_else(|| SQLError::Internal("BETWEEN without rhs".into()))?;
    let Some(NodeEnum::List(bounds)) = rhs.node.as_ref() else {
        return Err(SQLError::Internal("BETWEEN expects 2 bounds".into()));
    };
    let [low, high] = bounds.items.as_slice() else {
        return Err(SQLError::Internal("BETWEEN expects 2 bounds".into()));
    };
    let negated = matches!(
        a.kind(),
        AExprKind::AexprNotBetween | AExprKind::AexprNotBetweenSym
    );
    crate::type_resolution::between::expand(
        matches!(
            a.kind(),
            AExprKind::AexprBetweenSym | AExprKind::AexprNotBetweenSym
        ),
        negated,
        |op, upper| {
            Ok(Expr::Binary {
                op,
                lhs: Box::new(compile_expr(value)?),
                rhs: Box::new(compile_expr(if upper { high } else { low })?),
            })
        },
        |and, items| {
            if and {
                Expr::And(items)
            } else {
                Expr::Or(items)
            }
        },
    )
}