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::sync::Arc;
11use uqa_core::memory::{MemoryReservation, OwnedMap, Produced, ProductionControl, ProductionVec};
12use uqa_sql::{
13    prepared::{
14        definition::{
15            analysis_is_current_with_control, PreparedDefinition, PreparedDefinitionContext,
16        },
17        entry::PreparedStatementPlan,
18    },
19    routines::SQLUserFunction,
20    ColumnType, SQLError,
21};
22
23#[derive(Clone, Copy)]
24pub struct SQLBodyIdentity {
25    object: [u8; 16],
26    version: u64,
27}
28
29impl SQLBodyIdentity {
30    pub fn new(function: &SQLUserFunction) -> Result<Self, SQLError> {
31        Ok(Self {
32            object: function
33                .def
34                .object_id
35                .ok_or_else(|| SQLError::Internal("SQL body has no routine identity".into()))?,
36            version: function.definition_version()?,
37        })
38    }
39}
40
41struct StatementInputs {
42    position: usize,
43    parameter_types: Produced<Vec<ColumnType>>,
44    statement: Arc<SQLRoutineStatement>,
45}
46
47struct RoutineInputs {
48    version: u64,
49    statements: OwnedMap<usize, StatementInputs>,
50}
51
52/// Session-local analysis by routine revision, statement position and concrete input types.
53#[derive(Default)]
54pub struct SQLRoutineInputs {
55    routines: Mutex<OwnedMap<[u8; 16], RoutineInputs>>,
56}
57
58pub struct SQLRoutineInputContext<'a> {
59    pub cache: &'a SQLRoutineInputs,
60    pub analysis: PreparedDefinitionContext<'a>,
61}
62
63/// One successful input analysis owns its custom/generic history. Replacement
64/// analysis starts a new owner, so an older activation cannot republish its plan.
65pub struct SQLRoutineStatement {
66    pub definition: PreparedDefinition<uqa_sql::plan::SharedExecutablePlan>,
67    variants: super::super::plans::RoutinePlanVariants,
68    _memory: Option<MemoryReservation>,
69}
70
71impl SQLRoutineStatement {
72    fn new(
73        definition: PreparedDefinition<uqa_sql::plan::SharedExecutablePlan>,
74        control: &ProductionControl<'_>,
75    ) -> Result<Arc<Self>, SQLError> {
76        let memory = control.reserve(size_of::<Self>())?;
77        let variants = super::super::plans::RoutinePlanVariants::new(&definition);
78        Ok(Arc::new(Self {
79            definition,
80            variants,
81            _memory: memory,
82        }))
83    }
84
85    pub(super) fn select(
86        &self,
87        select: impl FnOnce(
88            &PreparedStatementPlan,
89        )
90            -> Result<uqa_sql::prepared::planning::PreparedPlanSelection, SQLError>,
91    ) -> Result<uqa_sql::plan::SharedExecutablePlan, SQLError> {
92        self.variants.select(select)
93    }
94}
95
96impl SQLRoutineInputs {
97    pub(crate) fn invalidate_execution_plans(&self) {
98        for routine in self.routines.lock().values() {
99            for statement in routine.statements.values() {
100                statement.statement.variants.invalidate();
101            }
102        }
103    }
104
105    pub(crate) fn invalidate(
106        &self,
107        affects: impl Fn(&uqa_sql::prepared::dependencies::PreparedAnalysisDependencies) -> bool,
108    ) {
109        let mut routines = self.routines.lock();
110        routines.retain(|_, routine| {
111            routine
112                .statements
113                .retain(|_, statement| !affects(&statement.statement.definition.dependencies));
114            !routine.statements.is_empty()
115        });
116    }
117
118    /// Publish only successful analysis and result validation, before execution.
119    /// Neither catalog callbacks nor recursive preparation run under the cache lock.
120    pub fn statement(
121        &self,
122        identity: SQLBodyIdentity,
123        position: usize,
124        parameter_types: &[ColumnType],
125        context: &PreparedDefinitionContext<'_>,
126        prepare: impl FnOnce() -> Result<PreparedDefinition, SQLError>,
127    ) -> Result<Arc<SQLRoutineStatement>, SQLError> {
128        self.statement_with_control(
129            identity,
130            position,
131            parameter_types,
132            context,
133            &ProductionControl::uncontrolled(),
134            || prepare().map(PreparedDefinition::into_shared),
135        )
136    }
137
138    pub fn statement_with_control(
139        &self,
140        identity: SQLBodyIdentity,
141        position: usize,
142        parameter_types: &[ColumnType],
143        context: &PreparedDefinitionContext<'_>,
144        control: &ProductionControl<'_>,
145        prepare: impl FnOnce() -> Result<
146            PreparedDefinition<uqa_sql::plan::SharedExecutablePlan>,
147            SQLError,
148        >,
149    ) -> Result<Arc<SQLRoutineStatement>, SQLError> {
150        control.check()?;
151        let retained = self
152            .routines
153            .lock()
154            .get(&identity.object)
155            .filter(|routine| routine.version == identity.version)
156            .and_then(|routine| {
157                routine.statements.values().find(|statement| {
158                    statement.position == position
159                        && statement.parameter_types.as_slice() == parameter_types
160                })
161            })
162            .map(|statement| Arc::clone(&statement.statement));
163        if let Some(statement) = retained {
164            let definition = &statement.definition;
165            if analysis_is_current_with_control(
166                context,
167                definition.effective_search_path.as_ref(),
168                &definition.dependencies,
169                definition.dependency_snapshot.as_ref(),
170                control,
171            )? {
172                return Ok(statement);
173            }
174        }
175        let statement = SQLRoutineStatement::new(prepare()?, control)?;
176        let mut types = ProductionVec::new(*control);
177        types.reserve(parameter_types.len())?;
178        for ty in parameter_types {
179            types.push_produced(ty.clone_with_control(control)?)?;
180        }
181        let input = StatementInputs {
182            position,
183            parameter_types: types.finish()?,
184            statement: Arc::clone(&statement),
185        };
186        let mut routines = self.routines.lock();
187        if let Some(routine) = routines
188            .get_mut(&identity.object)
189            .filter(|routine| routine.version == identity.version)
190        {
191            let slot = routine
192                .statements
193                .iter()
194                .find(|(_, input)| {
195                    input.position == position
196                        && input.parameter_types.as_slice() == parameter_types
197                })
198                .map(|(slot, _)| *slot);
199            let slot = match slot {
200                Some(slot) => slot,
201                None => routine
202                    .statements
203                    .keys()
204                    .copied()
205                    .max()
206                    .map_or(Ok(0), |last| {
207                        last.checked_add(1).ok_or_else(|| {
208                            SQLError::Internal("SQL routine statement cache is full".into())
209                        })
210                    })?,
211            };
212            insert(&mut routine.statements, slot, input, control)?;
213        } else {
214            let mut selected = OwnedMap::new();
215            insert(&mut selected, 0, input, control)?;
216            insert(
217                &mut routines,
218                identity.object,
219                RoutineInputs {
220                    version: identity.version,
221                    statements: selected,
222                },
223                control,
224            )?;
225        }
226        Ok(statement)
227    }
228}
229
230fn insert<K: Ord, V>(
231    map: &mut OwnedMap<K, V>,
232    key: K,
233    value: V,
234    control: &ProductionControl<'_>,
235) -> Result<(), SQLError> {
236    control.check()?;
237    match control.budget() {
238        Some(budget) => {
239            map.insert_budgeted(key, value, budget)?;
240        }
241        None => {
242            map.insert(key, value);
243        }
244    }
245    Ok(())
246}
247
248#[cfg(test)]
249mod tests;