uqa-execution 0.6.2

Volcano physical operators with row-batch pipelines
Documentation
//
// Unified Query Algebra
//
// Copyright (c) 2023-2026 Cognica, Inc.
//

//! PL/pgSQL statement dispatch.

use super::{Flow, Interpreter, LoopSignal, PLpgSQLStmt, SQLError};

mod queries;

impl Interpreter<'_> {
    // Source locations carry diagnostics through a small entry frame.
    pub(super) fn exec_stmt(&mut self, stmt: &PLpgSQLStmt) -> Result<Flow, SQLError> {
        self.services.runtime.cancellation_token().check()?;
        match stmt {
            PLpgSQLStmt::Located { line, statement } => {
                let result = self.exec_stmt(statement);
                match result {
                    Err(error) if !self.error_context_attached => {
                        self.error_context_attached = true;
                        Err(error.with_context(self.statement_error_context(*line, statement)))
                    }
                    Ok(flow) => {
                        self.error_context_attached = false;
                        Ok(flow)
                    }
                    error => error,
                }
            }
            _ => self.exec_statement_body(stmt),
        }
    }

    #[expect(clippy::too_many_lines, reason = "preserves PL/pgSQL transition order")]
    fn exec_statement_body(&mut self, stmt: &PLpgSQLStmt) -> Result<Flow, SQLError> {
        match stmt {
            PLpgSQLStmt::Located { .. } => {
                unreachable!("statement entry handles source locations")
            }
            PLpgSQLStmt::Block(block) => self.exec_block(block),
            PLpgSQLStmt::Assign { target, expr } => self.exec_assignment(*target, expr),
            PLpgSQLStmt::If {
                cond,
                then_body,
                elsifs,
                else_body,
            } => self.exec_if(cond, then_body, elsifs, else_body.as_deref()),
            PLpgSQLStmt::Case {
                t_expr,
                t_varno,
                arms,
                else_body,
            } => self.exec_case(t_expr.as_ref(), *t_varno, arms, else_body.as_deref()),
            PLpgSQLStmt::Loop { .. }
            | PLpgSQLStmt::While { .. }
            | PLpgSQLStmt::ForI { .. }
            | PLpgSQLStmt::ForCursor { .. }
            | PLpgSQLStmt::Exit { .. } => self.exec_loop_statement(stmt),
            PLpgSQLStmt::ForQuery {
                label,
                target,
                query,
                source_sql,
                body,
            } => self.exec_query_for(label.as_deref(), target, query, source_sql, body),
            PLpgSQLStmt::ForDynamic {
                label,
                target,
                query,
                params,
                body,
            } => self.exec_dynamic_for(label.as_deref(), target, query, params, body),
            PLpgSQLStmt::ForeachArray {
                label,
                target,
                slice,
                expr,
                body,
            } => self.exec_foreach_array(label.as_deref(), *target, *slice, expr, body),
            PLpgSQLStmt::Return { value } => self.exec_return(value.as_ref()),
            PLpgSQLStmt::ReturnNext { value } => self.exec_return_next(value.as_ref()),
            PLpgSQLStmt::ReturnQuery { query } => self.exec_return_query(query),
            PLpgSQLStmt::ReturnQueryExecute { query, params } => {
                self.exec_return_query_execute(query, params)
            }
            PLpgSQLStmt::Raise {
                level,
                condition,
                message,
                params,
                options,
            } => self.exec_raise(
                *level,
                condition.as_deref(),
                message.as_deref(),
                params,
                options,
            ),
            PLpgSQLStmt::Assert { condition, message } => {
                self.exec_assert(condition, message.as_ref())
            }
            PLpgSQLStmt::ExecSQL { stmt, into, strict } => {
                self.exec_sql_statement(stmt, into.as_ref(), *strict)
            }
            PLpgSQLStmt::DynExecute {
                query,
                params,
                into,
                strict,
            } => self.exec_dynamic_into(query, params, into.as_ref(), *strict),
            PLpgSQLStmt::Perform { query } => self.exec_perform(query),
            PLpgSQLStmt::OpenCursor { cursor, open } => {
                self.exec_open_cursor(*cursor, open).map(|()| Flow::Normal)
            }
            PLpgSQLStmt::FetchCursor {
                cursor,
                target,
                direction,
                count,
            } => self
                .exec_fetch_cursor(*cursor, target, *direction, count)
                .map(|()| Flow::Normal),
            PLpgSQLStmt::MoveCursor {
                cursor,
                direction,
                count,
            } => self
                .exec_move_cursor(*cursor, *direction, count)
                .map(|()| Flow::Normal),
            PLpgSQLStmt::CloseCursor { cursor } => {
                self.exec_close_cursor(*cursor).map(|()| Flow::Normal)
            }
            PLpgSQLStmt::Commit { chain } => self.exec_procedural_transaction(true, *chain),
            PLpgSQLStmt::Rollback { chain } => self.exec_procedural_transaction(false, *chain),
            PLpgSQLStmt::GetDiagnostics { items } => self.exec_get_diagnostics(items),
        }
    }

    // Loop-local bindings and control-flow scratch are not retained by RETURN
    // expression frames that can recursively invoke another routine.
    fn exec_loop_statement(&mut self, stmt: &PLpgSQLStmt) -> Result<Flow, SQLError> {
        match stmt {
            PLpgSQLStmt::Loop { label, body } => loop {
                match self.exec_loop_body(label.as_deref(), body)? {
                    LoopSignal::Continue => {}
                    LoopSignal::Break => return Ok(Flow::Normal),
                    LoopSignal::Propagate(flow) => return Ok(flow),
                }
            },
            PLpgSQLStmt::While { label, cond, body } => loop {
                if !self.eval_boolean(cond)?.unwrap_or(false) {
                    return Ok(Flow::Normal);
                }
                match self.exec_loop_body(label.as_deref(), body)? {
                    LoopSignal::Continue => {}
                    LoopSignal::Break => return Ok(Flow::Normal),
                    LoopSignal::Propagate(flow) => return Ok(flow),
                }
            },
            PLpgSQLStmt::ForI {
                label,
                var,
                lower,
                upper,
                step,
                reverse,
                body,
            } => {
                let name = self.datum_name(*var)?;
                self.push_binding(&name, *var);
                let result = self.exec_fori(
                    label.as_deref(),
                    *var,
                    lower,
                    upper,
                    step.as_ref(),
                    *reverse,
                    body,
                );
                self.pop_binding(&name);
                result
            }
            PLpgSQLStmt::ForCursor {
                label,
                target,
                cursor,
                arguments,
                body,
            } => {
                let name = self.datum_name(*target)?;
                self.push_binding(&name, *target);
                let result =
                    self.exec_cursor_for(label.as_deref(), *target, *cursor, arguments, body);
                self.pop_binding(&name);
                result
            }
            PLpgSQLStmt::Exit {
                is_exit,
                label,
                cond,
            } => {
                if let Some(cond) = cond {
                    if !self.eval_boolean(cond)?.unwrap_or(false) {
                        return Ok(Flow::Normal);
                    }
                }
                if *is_exit {
                    Ok(Flow::Exit(label.clone()))
                } else {
                    Ok(Flow::Continue(label.clone()))
                }
            }
            _ => unreachable!("loop statement dispatch"),
        }
    }

    fn exec_assignment(
        &mut self,
        target: usize,
        expr: &super::PLpgSQLExpression,
    ) -> Result<Flow, SQLError> {
        let record_schema = self.record_expression_schema(expr)?;
        let (value, source) = self.eval_expr_with_type(expr)?;
        self.assign_datum_typed(target, value, source.as_ref(), record_schema)?;
        Ok(Flow::Normal)
    }

    fn exec_if(
        &mut self,
        cond: &super::PLpgSQLExpression,
        then_body: &[PLpgSQLStmt],
        elsifs: &[(super::PLpgSQLExpression, Vec<PLpgSQLStmt>)],
        else_body: Option<&[PLpgSQLStmt]>,
    ) -> Result<Flow, SQLError> {
        if self.eval_boolean(cond)?.unwrap_or(false) {
            return self.exec_stmts(then_body);
        }
        for (elsif_cond, body) in elsifs {
            if self.eval_boolean(elsif_cond)?.unwrap_or(false) {
                return self.exec_stmts(body);
            }
        }
        match else_body {
            Some(body) => self.exec_stmts(body),
            None => Ok(Flow::Normal),
        }
    }

    fn exec_case(
        &mut self,
        t_expr: Option<&super::PLpgSQLExpression>,
        t_varno: Option<usize>,
        arms: &[(super::PLpgSQLExpression, Vec<PLpgSQLStmt>)],
        else_body: Option<&[PLpgSQLStmt]>,
    ) -> Result<Flow, SQLError> {
        if let (Some(t_expr), Some(varno)) = (t_expr, t_varno) {
            let value = self.eval_expr(t_expr)?;
            self.values[varno] = value;
        }
        for (cond, body) in arms {
            if self.eval_boolean(cond)?.unwrap_or(false) {
                return self.exec_stmts(body);
            }
        }
        match else_body {
            Some(body) => self.exec_stmts(body),
            None => Err(SQLError::Routine {
                sqlstate: "20000".into(),
                message: "case not found".into(),
            }),
        }
    }
}