uqa-sql 0.1.6

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
//
// Unified Query Algebra
//
// Copyright (c) 2023-2026 Cognica, Inc.
//

//! Core expression dispatch, indirection, sublinks, and CASE lowering.

use super::{
    compile_a_expr, compile_bool_expr, compile_column_ref, compile_const, compile_func_call,
    compile_null_test, compile_select, compile_type_cast, extract_strings, Expr, Node, NodeEnum,
    Result, SQLError, Value,
};

pub(in crate::compiler) fn compile_expr(node: &Node) -> Result<Expr> {
    let Some(inner) = node.node.as_ref() else {
        return Err(SQLError::Internal("missing expr node".into()));
    };
    match inner {
        NodeEnum::SetToDefault(_) => Ok(Expr::Default),
        NodeEnum::AConst(c) => compile_const(c),
        NodeEnum::ColumnRef(c) => compile_column_ref(c),
        NodeEnum::ParamRef(p) => {
            let index = usize::try_from(p.number).map_err(|_| {
                SQLError::Internal(format!(
                    "parameter index must be positive, got {}",
                    p.number
                ))
            })?;
            if index == 0 {
                return Err(SQLError::Internal(
                    "parameter index must be greater than zero".into(),
                ));
            }
            Ok(Expr::Param(index))
        }
        NodeEnum::FuncCall(f) => compile_func_call(f),
        NodeEnum::NamedArgExpr(arg) => {
            if arg.name.is_empty() {
                return Err(SQLError::Internal(
                    "NamedArgExpr without an argument name".into(),
                ));
            }
            let Some(value_node) = arg.arg.as_ref() else {
                return Err(SQLError::Internal("NamedArgExpr without value".into()));
            };
            Ok(Expr::Func {
                binding: None,
                name: "__named_arg".into(),
                args: vec![
                    Expr::Literal(Value::Str(arg.name.clone())),
                    compile_expr(value_node)?,
                ],
                distinct: false,
                order_by: Vec::new(),
                filter: None,
            })
        }
        NodeEnum::AArrayExpr(a) => {
            let elements: Vec<Expr> = a
                .elements
                .iter()
                .map(compile_expr)
                .collect::<Result<Vec<_>>>()?;
            Ok(Expr::Array(elements))
        }
        NodeEnum::TypeCast(tc) => compile_type_cast(tc),
        NodeEnum::AExpr(a) => compile_a_expr(a),
        NodeEnum::SqlvalueFunction(svf) => compile_sql_value_function(svf),
        NodeEnum::MergeSupportFunc(_) => Ok(Expr::Func {
            binding: None,
            name: "merge_action".into(),
            args: Vec::new(),
            distinct: false,
            order_by: Vec::new(),
            filter: None,
        }),
        NodeEnum::BoolExpr(b) => compile_bool_expr(b),
        NodeEnum::NullTest(n) => compile_null_test(n),
        NodeEnum::CaseExpr(c) => compile_case_expr(c),
        NodeEnum::CoalesceExpr(ce) => {
            if ce.args.is_empty() {
                return Err(SQLError::Internal("COALESCE without arguments".into()));
            }
            let args: Vec<Expr> = ce
                .args
                .iter()
                .map(compile_expr)
                .collect::<Result<Vec<_>>>()?;
            Ok(Expr::Func {
                binding: None,
                name: "coalesce".into(),
                args,
                distinct: false,
                order_by: Vec::new(),
                filter: None,
            })
        }
        NodeEnum::MinMaxExpr(me) => {
            use pg_query::protobuf::MinMaxOp;
            let name = match me.op() {
                MinMaxOp::IsGreatest => "greatest",
                MinMaxOp::IsLeast => "least",
                _ => {
                    return Err(SQLError::Unsupported(format!(
                        "MinMaxExpr op {:?}",
                        me.op()
                    )));
                }
            };
            let args: Vec<Expr> = me
                .args
                .iter()
                .map(compile_expr)
                .collect::<Result<Vec<_>>>()?;
            if args.is_empty() {
                return Err(SQLError::Internal(format!(
                    "{} without arguments",
                    name.to_ascii_uppercase()
                )));
            }
            Ok(Expr::Func {
                binding: None,
                name: name.into(),
                args,
                distinct: false,
                order_by: Vec::new(),
                filter: None,
            })
        }
        NodeEnum::SubLink(sl) => compile_sublink(sl),
        NodeEnum::RowExpr(row) => {
            let elements: Vec<Expr> = row
                .args
                .iter()
                .map(compile_expr)
                .collect::<Result<Vec<_>>>()?;
            Ok(Expr::Row(elements))
        }
        NodeEnum::AIndirection(ind) => compile_indirection(ind),
        other => Err(SQLError::Unsupported(format!("expression form: {other:?}"))),
    }
}

/// `expr[i]`, `expr[lo:hi]`, and chains thereof. The complete array-indirection group is lowered as one operation because `PostgreSQL` resolves all dimensions together and treats every dimension as a slice when any dimension contains a colon.
pub(in crate::compiler) fn compile_indirection(
    ind: &pg_query::protobuf::AIndirection,
) -> Result<Expr> {
    let base = ind
        .arg
        .as_deref()
        .ok_or_else(|| SQLError::Internal("AIndirection without base".into()))?;
    let mut current = compile_expr(base)?;
    if ind.indirection.is_empty() {
        return Err(SQLError::Internal(
            "AIndirection without indirection steps".into(),
        ));
    }
    let mut position = 0;
    while position < ind.indirection.len() {
        let step = &ind.indirection[position];
        let inner = step
            .node
            .as_ref()
            .ok_or_else(|| SQLError::Internal("indirection contains an empty step".into()))?;
        match inner {
            NodeEnum::AIndices(_) => {
                let start = position;
                while position < ind.indirection.len()
                    && matches!(
                        ind.indirection[position].node.as_ref(),
                        Some(NodeEnum::AIndices(_))
                    )
                {
                    position += 1;
                }
                let indices = &ind.indirection[start..position];
                let has_slice = indices.iter().any(|step| {
                    matches!(
                        step.node.as_ref(),
                        Some(NodeEnum::AIndices(index)) if index.is_slice
                    )
                });
                let mut args = vec![current];
                for step in indices {
                    let Some(NodeEnum::AIndices(index)) = step.node.as_ref() else {
                        return Err(SQLError::Internal("invalid array indirection group".into()));
                    };
                    if has_slice {
                        let lower = if index.is_slice {
                            index
                                .lidx
                                .as_deref()
                                .map(compile_expr)
                                .transpose()?
                                .unwrap_or(Expr::Literal(Value::Null))
                        } else {
                            Expr::Literal(Value::Int(1))
                        };
                        let upper = index
                            .uidx
                            .as_deref()
                            .map(compile_expr)
                            .transpose()?
                            .unwrap_or(Expr::Literal(Value::Null));
                        args.push(lower);
                        args.push(upper);
                    } else {
                        args.push(
                            index
                                .uidx
                                .as_deref()
                                .map(compile_expr)
                                .transpose()?
                                .ok_or_else(|| {
                                    SQLError::Internal("subscript without index".into())
                                })?,
                        );
                    }
                }
                current = Expr::Func {
                    binding: None,
                    name: if has_slice {
                        "__array_slices".into()
                    } else {
                        "__array_subscripts".into()
                    },
                    args,
                    distinct: false,
                    order_by: Vec::new(),
                    filter: None,
                };
                continue;
            }
            NodeEnum::String(field) => {
                if field.sval.is_empty() {
                    return Err(SQLError::Internal(
                        "indirection contains an empty field name".into(),
                    ));
                }
                // `(composite).field` access on map values.
                current = Expr::Func {
                    binding: None,
                    name: "__subscript".into(),
                    args: vec![current, Expr::Literal(Value::Str(field.sval.clone()))],
                    distinct: false,
                    order_by: Vec::new(),
                    filter: None,
                };
            }
            other => {
                return Err(SQLError::Unsupported(format!(
                    "indirection step: {other:?}"
                )));
            }
        }
        position += 1;
    }
    Ok(current)
}

pub(in crate::compiler) fn compile_sql_value_function(
    svf: &pg_query::protobuf::SqlValueFunction,
) -> Result<Expr> {
    use pg_query::protobuf::SqlValueFunctionOp;
    let name = match svf.op() {
        SqlValueFunctionOp::SvfopCurrentDate => "current_date",
        SqlValueFunctionOp::SvfopCurrentTimestamp
        | SqlValueFunctionOp::SvfopCurrentTimestampN
        | SqlValueFunctionOp::SvfopLocaltimestamp
        | SqlValueFunctionOp::SvfopLocaltimestampN
        | SqlValueFunctionOp::SvfopCurrentTime
        | SqlValueFunctionOp::SvfopCurrentTimeN
        | SqlValueFunctionOp::SvfopLocaltime
        | SqlValueFunctionOp::SvfopLocaltimeN => "current_timestamp",
        SqlValueFunctionOp::SvfopCurrentSchema => "current_schema",
        SqlValueFunctionOp::SvfopCurrentCatalog => "current_database",
        SqlValueFunctionOp::SvfopCurrentUser
        | SqlValueFunctionOp::SvfopCurrentRole
        | SqlValueFunctionOp::SvfopSessionUser
        | SqlValueFunctionOp::SvfopUser => "current_user",
        other => {
            return Err(SQLError::Unsupported(format!(
                "SQL value function {other:?}"
            )));
        }
    };
    Ok(Expr::Func {
        binding: None,
        name: name.into(),
        args: Vec::new(),
        distinct: false,
        order_by: Vec::new(),
        filter: None,
    })
}

pub(in crate::compiler) fn compile_sublink(sl: &pg_query::protobuf::SubLink) -> Result<Expr> {
    use pg_query::protobuf::SubLinkType;
    let body_node = sl
        .subselect
        .as_deref()
        .ok_or_else(|| SQLError::Internal("SubLink without subselect".into()))?;
    let inner_select = match body_node.node.as_ref() {
        Some(NodeEnum::SelectStmt(s)) => compile_select(s)?,
        _ => {
            return Err(SQLError::Unsupported("SubLink body must be SELECT".into()));
        }
    };
    let body = Box::new(inner_select);
    let operator = if sl.oper_name.is_empty() {
        None
    } else {
        Some(extract_strings(&sl.oper_name)?.join(""))
    };
    match sl.sub_link_type() {
        SubLinkType::ExprSublink => {
            if sl.testexpr.is_some() || operator.is_some() {
                return Err(SQLError::Internal(
                    "scalar SubLink unexpectedly has a test expression or operator".into(),
                ));
            }
            Ok(Expr::ScalarSubquery(body))
        }
        SubLinkType::ExistsSublink => {
            if sl.testexpr.is_some() || operator.is_some() {
                return Err(SQLError::Internal(
                    "EXISTS SubLink unexpectedly has a test expression or operator".into(),
                ));
            }
            Ok(Expr::Exists {
                body,
                negated: false,
            })
        }
        SubLinkType::AnySublink => {
            if !matches!(operator.as_deref(), None | Some("=")) {
                return Err(SQLError::Unsupported(format!(
                    "ANY subquery operator `{}` is not represented by InSubquery",
                    operator.as_deref().unwrap_or("")
                )));
            }
            let testexpr = sl
                .testexpr
                .as_deref()
                .ok_or_else(|| SQLError::Internal("ANY SubLink without testexpr".into()))?;
            Ok(Expr::InSubquery {
                expr: Box::new(compile_expr(testexpr)?),
                body,
                negated: false,
            })
        }
        SubLinkType::AllSublink => {
            if operator.as_deref() != Some("<>") {
                return Err(SQLError::Unsupported(format!(
                    "ALL subquery operator `{}` is not represented by InSubquery",
                    operator.as_deref().unwrap_or("")
                )));
            }
            // `lhs <> ALL (subquery)` is SQL's `lhs NOT IN (subquery)`.
            let testexpr = sl
                .testexpr
                .as_deref()
                .ok_or_else(|| SQLError::Internal("ALL SubLink without testexpr".into()))?;
            Ok(Expr::InSubquery {
                expr: Box::new(compile_expr(testexpr)?),
                body,
                negated: true,
            })
        }
        other => Err(SQLError::Unsupported(format!("SubLink type {other:?}"))),
    }
}

pub(in crate::compiler) fn compile_case_expr(c: &pg_query::protobuf::CaseExpr) -> Result<Expr> {
    let base = c
        .arg
        .as_ref()
        .map(|n| compile_expr(n))
        .transpose()?
        .map(Box::new);
    let mut when: Vec<(Expr, Expr)> = Vec::with_capacity(c.args.len());
    if c.args.is_empty() {
        return Err(SQLError::Internal(
            "CASE expression without WHEN arms".into(),
        ));
    }
    for arm in &c.args {
        let inner = arm
            .node
            .as_ref()
            .ok_or_else(|| SQLError::Internal("CASE arm without body".into()))?;
        let NodeEnum::CaseWhen(cw) = inner else {
            return Err(SQLError::Internal(format!(
                "CASE arm expected CaseWhen, got {inner:?}"
            )));
        };
        let cond = cw
            .expr
            .as_ref()
            .ok_or_else(|| SQLError::Internal("CASE WHEN without cond".into()))?;
        let result = cw
            .result
            .as_ref()
            .ok_or_else(|| SQLError::Internal("CASE WHEN without THEN".into()))?;
        when.push((compile_expr(cond)?, compile_expr(result)?));
    }
    let else_branch = c
        .defresult
        .as_ref()
        .map(|n| compile_expr(n))
        .transpose()?
        .map(Box::new);
    Ok(Expr::Case {
        base,
        when,
        else_branch,
    })
}