Skip to main content

uqa_execution/statement/
prepared.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Prepared registration ordered around retained session registry publication.
8
9pub mod invalidation;
10
11use std::sync::Arc;
12use uqa_core::memory::{OwnedProductionControl, Produced, ProductionControl};
13use uqa_sql::{
14    plan::{AggregateClassifier, MutableExecutablePlan, UnifiedPlan},
15    prepared::{definition::PreparedDefinitionContext, entry::PreparedStatementPlan},
16    ColumnType, SQLError, Statement,
17};
18
19pub trait PreparedDefinitionWrite {
20    fn insert(
21        &mut self,
22        name: Produced<String>,
23        definition: PreparedStatementPlan,
24        control: &ProductionControl<'_>,
25    ) -> Result<(), SQLError>;
26}
27
28pub trait PreparedDefinitionRegistry {
29    fn write_definitions(
30        &self,
31        control: &ProductionControl<'_>,
32    ) -> Result<Box<dyn PreparedDefinitionWrite + '_>, SQLError>;
33    fn production_resources(&self) -> Result<OwnedProductionControl, SQLError> {
34        Ok(ProductionControl::uncontrolled().capture())
35    }
36}
37
38#[derive(Clone, Copy)]
39pub struct PreparedRegistrationContext<'a> {
40    pub analysis: PreparedDefinitionContext<'a>,
41    pub aggregates: &'a dyn AggregateClassifier,
42    pub registry: &'a dyn PreparedDefinitionRegistry,
43    /// The session's active transaction clock, including direct host registration; `None` keeps the caller's clock.
44    pub transaction_timestamp_micros: Option<i64>,
45    pub date_order: Option<uqa_core::TemporalDateOrder>,
46    pub interval_style: Option<uqa_core::TemporalIntervalStyle>,
47    /// The session's cancellation, which the definition's analysis observes.
48    pub cancellation: &'a uqa_core::CancellationToken,
49    pub clock: fn() -> i64,
50}
51
52pub fn register_statement(
53    context: &PreparedRegistrationContext<'_>,
54    name: String,
55    statement: Statement,
56) -> Result<(), SQLError> {
57    let owner = context.registry.production_resources()?;
58    let control = owner.control();
59    let plan = UnifiedPlan::lower_borrowed_for_rewrite(&statement, context.aggregates, &control)?;
60    register_definition(context, name, plan, &[], None, false, &control)
61}
62
63pub fn register_plan(
64    context: &PreparedRegistrationContext<'_>,
65    name: String,
66    logical_plan: UnifiedPlan,
67    declared: &[ColumnType],
68    source_sql: Option<&str>,
69) -> Result<(), SQLError> {
70    let owner = context.registry.production_resources()?;
71    let control = owner.control();
72    register_definition(
73        context,
74        name,
75        logical_plan.copy_for_rewrite(&control)?,
76        declared,
77        source_sql,
78        source_sql.is_some(),
79        &control,
80    )
81}
82
83/// Parse a prepared message before selecting its analysis snapshot. Empty input remains an explicit native definition.
84pub fn parse_host_sql(
85    sql: &str,
86    settings: uqa_sql::parser::ParserSettings,
87    notices: &crate::query::NoticeQueue,
88    cancellation: &uqa_core::CancellationToken,
89) -> Result<Arc<Statement>, SQLError> {
90    cancellation.check()?;
91    let (statements, parser) =
92        uqa_sql::parser::with_settings(settings, || uqa_sql::parse_statements(sql));
93    for notice in parser.notices.iter() {
94        notices.push(notice.clone());
95    }
96    let mut statements = statements?;
97    if statements.len() > 1 {
98        return Err(SQLError::Routine {
99            sqlstate: "42601".into(),
100            message: "cannot insert multiple commands into a prepared statement".into(),
101        });
102    }
103    let statement = statements
104        .pop()
105        .map(|statement| statement.compile())
106        .transpose()?
107        .unwrap_or(Statement::Empty);
108    Ok(Arc::new(statement))
109}
110
111/// Analyze the parsed host definition in its admitted session boundary. Retain source text without marking it as SQL PREPARE.
112pub fn register_host_statement(
113    context: &PreparedRegistrationContext<'_>,
114    name: String,
115    statement: &Statement,
116    sql: &str,
117    declared: &[ColumnType],
118) -> Result<(), SQLError> {
119    let owner = context.registry.production_resources()?;
120    let control = owner.control();
121    let plan = UnifiedPlan::lower_borrowed_for_rewrite(statement, context.aggregates, &control)?;
122    register_definition(context, name, plan, declared, Some(sql), false, &control)
123}
124
125fn register_definition(
126    context: &PreparedRegistrationContext<'_>,
127    name: String,
128    logical_plan: MutableExecutablePlan,
129    declared: &[ColumnType],
130    source_sql: Option<&str>,
131    from_sql: bool,
132    control: &ProductionControl<'_>,
133) -> Result<(), SQLError> {
134    let _statement_thread = super::thread_context::StatementThreadContext {
135        retained_rows: crate::query::sources::retained_source::RetainedRowContext::current(),
136        io: uqa_core::io_usage::IOContext::current(),
137        regex_cache: uqa_sql::expr::current_regex_cache(),
138        temporal_input: uqa_sql::expr::TemporalInputContext {
139            transaction_clock_micros: context
140                .transaction_timestamp_micros
141                .or_else(uqa_sql::expr::transaction_clock_micros),
142            interval_style: context
143                .interval_style
144                .unwrap_or_else(uqa_sql::expr::temporal_interval_style),
145            date_order: context
146                .date_order
147                .unwrap_or_else(uqa_sql::expr::temporal_date_order),
148        },
149        cancellation: Some(context.cancellation.clone()),
150    }
151    .enter();
152    let source_plan = logical_plan.finish(control)?.into_shared(control)?;
153    let definition = uqa_sql::prepared::definition::analyze_definition_owned(
154        &context.analysis,
155        source_plan.copy_for_rewrite(control)?,
156        declared,
157        control,
158    )?
159    .into_shared_with_control(control)?;
160    let name = control.copy_text(&name)?;
161    let source_sql = source_sql
162        .map(|sql| {
163            uqa_sql::prepared::ownership::SharedPreparedInput::from_produced(
164                control.copy_text(sql)?,
165                control,
166            )
167        })
168        .transpose()?;
169    context.registry.write_definitions(control)?.insert(
170        name,
171        PreparedStatementPlan {
172            definition_identity: std::sync::Arc::new(()),
173            composite_inputs: definition.composite_inputs,
174            source_plan,
175            logical_plan: definition.logical_plan,
176            needs_analysis: false,
177            effective_search_path: definition.effective_search_path,
178            dependencies: definition.dependencies,
179            dependency_snapshot: definition.dependency_snapshot,
180            plan: None,
181            parameter_types: definition.parameter_types,
182            result_schema: definition.result_schema,
183            source_sql,
184            prepared_at_micros: (context.clock)(),
185            from_sql,
186            generic_plans: 0,
187            custom_plans: 0,
188            generic_cost: None,
189            total_custom_cost: 0.0,
190        },
191        control,
192    )
193}
194
195#[cfg(test)]
196mod tests;