Skip to main content

uqa_execution/routines/sql_body/
inputs.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! First-use SQL analysis and executable variants, retained by their routine owner.
8
9use parking_lot::Mutex;
10use std::{collections::BTreeMap, sync::Arc};
11use uqa_sql::{
12    prepared::{
13        definition::{analysis_is_current, PreparedDefinition, PreparedDefinitionContext},
14        entry::PreparedStatementPlan,
15    },
16    routines::SQLUserFunction,
17    ColumnType, SQLError,
18};
19
20#[derive(Clone, Copy)]
21pub struct SQLBodyIdentity {
22    object: [u8; 16],
23    version: u64,
24}
25
26impl SQLBodyIdentity {
27    pub fn new(function: &SQLUserFunction) -> Result<Self, SQLError> {
28        Ok(Self {
29            object: function
30                .def
31                .object_id
32                .ok_or_else(|| SQLError::Internal("SQL body has no routine identity".into()))?,
33            version: function.definition_version()?,
34        })
35    }
36}
37
38struct StatementInputs {
39    position: usize,
40    parameter_types: Vec<ColumnType>,
41    statement: Arc<SQLRoutineStatement>,
42}
43
44struct RoutineInputs {
45    version: u64,
46    statements: Vec<StatementInputs>,
47}
48
49/// Session-local analysis by routine revision, statement position and concrete input types.
50#[derive(Default)]
51pub struct SQLRoutineInputs {
52    routines: Mutex<BTreeMap<[u8; 16], RoutineInputs>>,
53}
54
55pub struct SQLRoutineInputContext<'a> {
56    pub cache: &'a SQLRoutineInputs,
57    pub analysis: PreparedDefinitionContext<'a>,
58}
59
60/// One successful input analysis owns its custom/generic history. Replacement
61/// analysis starts a new owner, so an older activation cannot republish its plan.
62pub struct SQLRoutineStatement {
63    pub definition: PreparedDefinition,
64    variants: super::super::plans::RoutinePlanVariants,
65}
66
67impl SQLRoutineStatement {
68    fn new(definition: PreparedDefinition) -> Self {
69        let variants = super::super::plans::RoutinePlanVariants::new(&definition);
70        Self {
71            definition,
72            variants,
73        }
74    }
75
76    pub(super) fn select(
77        &self,
78        select: impl FnOnce(
79            &PreparedStatementPlan,
80        )
81            -> Result<uqa_sql::prepared::planning::PreparedPlanSelection, SQLError>,
82    ) -> Result<uqa_sql::plan::UnifiedPlan, SQLError> {
83        self.variants.select(select)
84    }
85}
86
87impl SQLRoutineInputs {
88    pub(crate) fn invalidate_execution_plans(&self) {
89        for routine in self.routines.lock().values() {
90            for statement in &routine.statements {
91                statement.statement.variants.invalidate();
92            }
93        }
94    }
95
96    pub(crate) fn invalidate(
97        &self,
98        affects: impl Fn(&uqa_sql::prepared::dependencies::PreparedAnalysisDependencies) -> bool,
99    ) {
100        let mut routines = self.routines.lock();
101        for routine in routines.values_mut() {
102            routine
103                .statements
104                .retain(|statement| !affects(&statement.statement.definition.dependencies));
105        }
106        routines.retain(|_, routine| !routine.statements.is_empty());
107    }
108
109    /// Publish only successful analysis and result validation, before execution.
110    /// Neither catalog callbacks nor recursive preparation run under the cache lock.
111    pub fn statement(
112        &self,
113        identity: SQLBodyIdentity,
114        position: usize,
115        parameter_types: &[ColumnType],
116        context: &PreparedDefinitionContext<'_>,
117        prepare: impl FnOnce() -> Result<PreparedDefinition, SQLError>,
118    ) -> Result<Arc<SQLRoutineStatement>, SQLError> {
119        let retained = self
120            .routines
121            .lock()
122            .get(&identity.object)
123            .filter(|routine| routine.version == identity.version)
124            .and_then(|routine| {
125                routine.statements.iter().find(|statement| {
126                    statement.position == position && statement.parameter_types == parameter_types
127                })
128            })
129            .map(|statement| Arc::clone(&statement.statement));
130        if let Some(statement) = retained {
131            let definition = &statement.definition;
132            if analysis_is_current(
133                context,
134                definition.effective_search_path.as_ref(),
135                &definition.dependencies,
136                definition.dependency_snapshot.as_ref(),
137            )? {
138                return Ok(statement);
139            }
140        }
141        let statement = Arc::new(SQLRoutineStatement::new(prepare()?));
142        let mut routines = self.routines.lock();
143        let routine = routines
144            .entry(identity.object)
145            .or_insert_with(|| RoutineInputs {
146                version: identity.version,
147                statements: Vec::new(),
148            });
149        if routine.version != identity.version {
150            routine.version = identity.version;
151            routine.statements.clear();
152        }
153        routine.statements.retain(|statement| {
154            statement.position != position || statement.parameter_types != parameter_types
155        });
156        routine.statements.push(StatementInputs {
157            position,
158            parameter_types: parameter_types.to_vec(),
159            statement: Arc::clone(&statement),
160        });
161        Ok(statement)
162    }
163}
164
165#[cfg(test)]
166mod tests;