uqa-sql 0.2.0

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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
//
// Unified Query Algebra
//
// Copyright (c) 2023-2026 Cognica, Inc.
//

//! `PL/pgSQL` function bodies: typed AST, parser, and the variable
//! binding rewriter.
//!
//! Bodies are parsed with `libpg_query`'s `PL/pgSQL` parser
//! (`pg_query::parse_plpgsql`), which returns the same JSON dump
//! `PostgreSQL` itself produces. This module lowers that JSON into a
//! typed AST whose embedded SQL fragments are pre-compiled into
//! [`Expr`] / [`Statement`] values, ready for execution against the
//! engine.
//!
//! Variable references inside embedded SQL are plain column
//! references after compilation. At execution time the interpreter
//! rewrites them into literals through [`VariableResolver`] /
//! [`bind_expr`] / [`bind_statement`] before handing the statement to
//! the engine. This matches `plpgsql.variable_conflict =
//! use_variable` resolution: a name that is both a `PL/pgSQL`
//! variable and a column of a queried table resolves to the variable
//! (stock `PostgreSQL` raises an ambiguity error instead).

use serde_json::Value as JSONValue;
use uqa_core::Value;

use crate::ast::{
    CreateFunction, CursorDirection, Expr, FromClause, FunctionBody, FunctionParamMode,
    FunctionReturns, MergeWhen, Projection, RoutineColumnTypeReference, SelectStmt, Statement, CTE,
};
use crate::error::{Result, SQLError};

// ---------------------------------------------------------------------
// Typed AST
// ---------------------------------------------------------------------

/// A parsed `PL/pgSQL` function body: the flat datum table plus the
/// outermost block.
#[derive(Debug, Clone)]
pub struct PLpgSQLFunction {
    pub datums: Vec<PLpgSQLDatum>,
    pub action: PLpgSQLBlock,
    /// Datum holding the implicit `NEW` record for a trigger function.
    pub new_datum: Option<usize>,
    /// Datum holding the implicit `OLD` record for a trigger function.
    pub old_datum: Option<usize>,
    /// Index of the implicit `FOUND` variable in [`Self::datums`].
    pub found_datum: Option<usize>,
}

impl PLpgSQLFunction {
    /// Datum indices synthesized for loop-local variables. The interpreter
    /// binds these names only while their loop runs so an outer variable with
    /// the same name stays visible elsewhere.
    pub fn loop_local_variable_datums(&self) -> std::collections::BTreeSet<usize> {
        let mut out = std::collections::BTreeSet::new();
        collect_loop_local_vars_block(&self.action, &mut out);
        out
    }

    /// Datum indices used as bound-cursor arguments. They are visible only
    /// while the cursor query is bound, not throughout the routine body.
    pub fn cursor_argument_datums(&self) -> std::collections::BTreeSet<usize> {
        let mut out = std::collections::BTreeSet::new();
        for datum in &self.datums {
            let PLpgSQLDatum::Var(var) = datum else {
                continue;
            };
            let Some(argument_row) = var.cursor.as_ref().and_then(|cursor| cursor.argument_row)
            else {
                continue;
            };
            if let Some(PLpgSQLDatum::Row { fields }) = self.datums.get(argument_row) {
                out.extend(fields.iter().map(|field| field.varno));
            }
        }
        out
    }
}

fn collect_loop_local_vars_block(
    block: &PLpgSQLBlock,
    out: &mut std::collections::BTreeSet<usize>,
) {
    collect_loop_local_vars_stmts(&block.body, out);
    for arm in &block.exceptions {
        collect_loop_local_vars_stmts(&arm.body, out);
    }
}

fn collect_loop_local_vars_stmts(
    stmts: &[PLpgSQLStmt],
    out: &mut std::collections::BTreeSet<usize>,
) {
    for stmt in stmts {
        match stmt {
            PLpgSQLStmt::Block(block) => collect_loop_local_vars_block(block, out),
            PLpgSQLStmt::If {
                then_body,
                elsifs,
                else_body,
                ..
            } => {
                collect_loop_local_vars_stmts(then_body, out);
                for (_, body) in elsifs {
                    collect_loop_local_vars_stmts(body, out);
                }
                if let Some(body) = else_body {
                    collect_loop_local_vars_stmts(body, out);
                }
            }
            PLpgSQLStmt::Case {
                arms, else_body, ..
            } => {
                for (_, body) in arms {
                    collect_loop_local_vars_stmts(body, out);
                }
                if let Some(body) = else_body {
                    collect_loop_local_vars_stmts(body, out);
                }
            }
            PLpgSQLStmt::Loop { body, .. } | PLpgSQLStmt::While { body, .. } => {
                collect_loop_local_vars_stmts(body, out);
            }
            PLpgSQLStmt::ForI { var, body, .. } => {
                out.insert(*var);
                collect_loop_local_vars_stmts(body, out);
            }
            PLpgSQLStmt::ForCursor { target, body, .. } => {
                out.insert(*target);
                collect_loop_local_vars_stmts(body, out);
            }
            PLpgSQLStmt::ForQuery { body, .. }
            | PLpgSQLStmt::ForDynamic { body, .. }
            | PLpgSQLStmt::ForeachArray { body, .. } => {
                collect_loop_local_vars_stmts(body, out);
            }
            _ => {}
        }
    }
}

/// One entry in the function's flat datum table. `varno` / `dno`
/// references inside statements index into this table.
#[derive(Debug, Clone)]
pub enum PLpgSQLDatum {
    Var(Box<PLpgSQLVar>),
    /// `RECORD` variable (also `FOR rec IN ...` loop targets).
    Rec {
        name: String,
    },
    /// `rec.field` assignment target.
    RecField {
        field: String,
        parent: usize,
    },
    /// Multi-variable target list (`SELECT ... INTO a, b`).
    Row {
        fields: Vec<PLpgSQLRowField>,
    },
}

impl PLpgSQLDatum {
    pub fn name(&self) -> Option<&str> {
        match self {
            PLpgSQLDatum::Var(v) => Some(&v.name),
            PLpgSQLDatum::Rec { name } => Some(name),
            PLpgSQLDatum::RecField { .. } | PLpgSQLDatum::Row { .. } => None,
        }
    }
}

/// Scalar `PL/pgSQL` variable (declared variable, parameter, loop
/// counter, or an internal compiler temporary).
#[derive(Debug, Clone)]
pub struct PLpgSQLVar {
    pub name: String,
    /// Normalized type name (`integer`, `text`, ...). The engine resolves
    /// catalog-backed references such as `%TYPE` before execution.
    pub type_name: String,
    /// Exact relation-column identity emitted by the PL/pgSQL parser for a table-backed `%TYPE` declaration.
    pub type_reference: Option<RoutineColumnTypeReference>,
    pub default: Option<Expr>,
    pub constant: bool,
    pub not_null: bool,
    /// Definition of a bound cursor declared with `CURSOR (...) FOR query`.
    pub cursor: Option<PLpgSQLCursor>,
    /// Source line of the declaration; used to disambiguate loop
    /// variables that shadow outer names.
    pub lineno: Option<i64>,
}

#[derive(Debug, Clone)]
pub struct PLpgSQLCursor {
    pub query: Statement,
    pub argument_row: Option<usize>,
    /// Explicit declaration scroll mode. `None` leaves scrollability query-dependent.
    pub scroll: Option<bool>,
}

#[derive(Debug, Clone)]
pub struct PLpgSQLCursorArgument {
    pub name: Option<String>,
    pub expr: Expr,
}

/// Query source selected by one `OPEN` statement.
#[derive(Debug, Clone)]
pub enum PLpgSQLCursorOpen {
    Bound {
        arguments: Vec<PLpgSQLCursorArgument>,
    },
    Static {
        query: Box<Statement>,
        scroll: Option<bool>,
    },
    Dynamic {
        query: Expr,
        params: Vec<Expr>,
        scroll: Option<bool>,
    },
}

/// Constant or run-time expression controlling cursor movement.
#[derive(Debug, Clone)]
pub enum PLpgSQLCursorCount {
    Constant(i64),
    Expression(Expr),
}

/// `name -> datum` slot of a row target.
#[derive(Debug, Clone)]
pub struct PLpgSQLRowField {
    pub name: String,
    pub varno: usize,
}

/// `[DECLARE ...] BEGIN ... [EXCEPTION ...] END` block.
#[derive(Debug, Clone)]
pub struct PLpgSQLBlock {
    pub label: Option<String>,
    pub body: Vec<PLpgSQLStmt>,
    pub exceptions: Vec<PLpgSQLExceptionArm>,
}

/// One `WHEN cond [OR cond ...] THEN stmts` arm of an exception
/// section.
#[derive(Debug, Clone)]
pub struct PLpgSQLExceptionArm {
    /// Lower-cased condition names (`others`, `division_by_zero`,
    /// ...). Explicit `SQLSTATE 'xxxxx'` conditions arrive as the
    /// five-character code.
    pub conditions: Vec<String>,
    pub body: Vec<PLpgSQLStmt>,
}

/// `RAISE` severity.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RaiseLevel {
    Debug,
    Log,
    Info,
    Notice,
    Warning,
    Error,
}

impl RaiseLevel {
    pub fn as_str(self) -> &'static str {
        match self {
            RaiseLevel::Debug => "DEBUG",
            RaiseLevel::Log => "LOG",
            RaiseLevel::Info => "INFO",
            RaiseLevel::Notice => "NOTICE",
            RaiseLevel::Warning => "WARNING",
            RaiseLevel::Error => "ERROR",
        }
    }
}

/// Assignment / `INTO` target.
#[derive(Debug, Clone)]
pub enum IntoTarget {
    /// A `RECORD` variable receives the whole row.
    Rec(usize),
    /// Positional list of scalar targets.
    Row(Vec<PLpgSQLRowField>),
}

/// Executable `PL/pgSQL` statement.
#[derive(Debug, Clone)]
pub enum PLpgSQLStmt {
    Block(PLpgSQLBlock),
    /// `target := expr` (also `=`). `target` indexes the datum table.
    Assign {
        target: usize,
        expr: Expr,
    },
    If {
        cond: Expr,
        then_body: Vec<PLpgSQLStmt>,
        elsifs: Vec<(Expr, Vec<PLpgSQLStmt>)>,
        else_body: Option<Vec<PLpgSQLStmt>>,
    },
    /// CASE statement. Simple form carries `t_expr` + the temporary
    /// datum the compiler references from each rewritten WHEN.
    Case {
        t_expr: Option<Expr>,
        t_varno: Option<usize>,
        arms: Vec<(Expr, Vec<PLpgSQLStmt>)>,
        else_body: Option<Vec<PLpgSQLStmt>>,
    },
    Loop {
        label: Option<String>,
        body: Vec<PLpgSQLStmt>,
    },
    While {
        label: Option<String>,
        cond: Expr,
        body: Vec<PLpgSQLStmt>,
    },
    /// `FOR i IN [REVERSE] lower..upper [BY step] LOOP`.
    ForI {
        label: Option<String>,
        var: usize,
        lower: Expr,
        upper: Expr,
        step: Option<Expr>,
        reverse: bool,
        body: Vec<PLpgSQLStmt>,
    },
    /// `FOR target IN <query> LOOP`.
    ForQuery {
        label: Option<String>,
        target: IntoTarget,
        query: Statement,
        body: Vec<PLpgSQLStmt>,
    },
    /// `FOR target IN EXECUTE query [USING params] LOOP`.
    ForDynamic {
        label: Option<String>,
        target: IntoTarget,
        query: Expr,
        params: Vec<Expr>,
        body: Vec<PLpgSQLStmt>,
    },
    /// `FOR recordvar IN bound_cursor [(arguments)] LOOP`.
    ForCursor {
        label: Option<String>,
        target: usize,
        cursor: usize,
        arguments: Vec<PLpgSQLCursorArgument>,
        body: Vec<PLpgSQLStmt>,
    },
    /// `FOREACH target [SLICE n] IN ARRAY expression LOOP`.
    ForeachArray {
        label: Option<String>,
        target: usize,
        slice: usize,
        expr: Expr,
        body: Vec<PLpgSQLStmt>,
    },
    /// `EXIT` (`is_exit`) or `CONTINUE`, optionally labelled and
    /// conditional (`WHEN cond`).
    Exit {
        is_exit: bool,
        label: Option<String>,
        cond: Option<Expr>,
    },
    Return {
        value: Option<PLpgSQLReturnValue>,
    },
    /// `RETURN NEXT [expr]` - bare form emits the current OUT /
    /// TABLE column values.
    ReturnNext {
        value: Option<PLpgSQLReturnValue>,
    },
    ReturnQuery {
        query: Statement,
    },
    ReturnQueryExecute {
        query: Expr,
        params: Vec<Expr>,
    },
    Raise {
        level: RaiseLevel,
        condition: Option<String>,
        message: Option<String>,
        params: Vec<Expr>,
    },
    /// `ASSERT condition [, message]`.
    Assert {
        condition: Expr,
        message: Option<Expr>,
    },
    /// Embedded SQL statement, optionally `INTO [STRICT] target`.
    ExecSQL {
        stmt: Statement,
        into: Option<IntoTarget>,
        strict: bool,
    },
    /// `EXECUTE <string> [INTO [STRICT] target] [USING params]`.
    DynExecute {
        query: Expr,
        params: Vec<Expr>,
        into: Option<IntoTarget>,
        strict: bool,
    },
    Perform {
        query: Statement,
    },
    OpenCursor {
        cursor: usize,
        open: PLpgSQLCursorOpen,
    },
    FetchCursor {
        cursor: usize,
        target: IntoTarget,
        direction: CursorDirection,
        count: PLpgSQLCursorCount,
    },
    MoveCursor {
        cursor: usize,
        direction: CursorDirection,
        count: PLpgSQLCursorCount,
    },
    CloseCursor {
        cursor: usize,
    },
    /// Procedural `COMMIT [AND [NO] CHAIN]`.
    Commit {
        chain: bool,
    },
    /// Procedural `ROLLBACK [AND [NO] CHAIN]`.
    Rollback {
        chain: bool,
    },
    /// `GET DIAGNOSTICS var = KIND [, ...]` as `(kind, target datum)`.
    GetDiagnostics {
        items: Vec<(String, usize)>,
    },
}

/// Value source for `RETURN` and `RETURN NEXT`. `PostgreSQL` 18 stores a simple
/// datum reference in `retvarno`, distinct from a general SQL expression.
#[derive(Debug, Clone)]
pub enum PLpgSQLReturnValue {
    Expr(Expr),
    Datum(usize),
}

// ---------------------------------------------------------------------
// Parsing: definition -> canonical text -> libpg_query JSON -> AST
// ---------------------------------------------------------------------

/// Parse the `PL/pgSQL` body of a stored definition. The definition
/// is re-serialized into a canonical `CREATE FUNCTION` statement so
/// restore-from-catalog and fresh DDL take the same path.
mod binding;
mod conditions;
mod json_validation;
mod lowering_expression;
mod lowering_statement;
mod parsing;

use json_validation::{
    ensure_single_tag, expect_tag, json_bool_or_false, json_i64_or_zero, json_kind,
    json_optional_i64, json_optional_str, json_optional_usize, json_usize_or_zero,
    normalize_plpgsql_type, optional_array, require, require_i64, require_nonempty_str,
    validate_assignable_datum, validate_record_datum, validate_scalar_datum,
};
use lowering_expression::{lower_expr, lower_expr_list, lower_full_statement};
use lowering_statement::{lower_block, lower_cursor_scroll_options};
use parsing::{lower_row_fields, normalize_condition};

pub use binding::{bind_expr, bind_select, bind_statement, ResolvedVariable, VariableResolver};
pub use conditions::{condition_sqlstate, condition_sqlstates};
pub use lowering_expression::compile_expression_text;
pub use parsing::{parse_do_block, parse_function};

#[cfg(test)]
mod tests;