Skip to main content

uqa_engine/
queries.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Engine query entry points, statement gates, execution clocks and the statement thread context.
8
9use uqa_execution::ColumnarBatch;
10
11use crate::{Engine, SQLCursor, SQLCursorSummary};
12use uqa_sql::{SQLError, SQLParam, SQLResult};
13
14pub(crate) struct SQLExecutionScope<'a> {
15    engine: &'a Engine,
16    depth: &'a std::sync::atomic::AtomicUsize,
17    statement_clock: &'a std::sync::atomic::AtomicI64,
18    previous_clock: Option<i64>,
19    /// The statement thread context, whose transaction start the statement's input functions and `now()` read and whose cancellation its evaluation observes, entered for the outermost statement on the executing thread; a nested statement keeps its caller's.
20    _statement_thread: Option<uqa_execution::statement::thread_scope::StatementThreadScope>,
21}
22
23impl<'a> SQLExecutionScope<'a> {
24    pub(crate) fn enter(engine: &'a Engine) -> (Self, bool) {
25        let depth = &engine.runtime.sql_execution_depth;
26        let statement_clock = &engine.session.statement_started_at_micros;
27        let nested = depth.fetch_add(1, std::sync::atomic::Ordering::Relaxed) != 0;
28        let previous_clock = (!nested).then(|| {
29            statement_clock.swap(
30                uqa_sql::expr::clock_timestamp_micros(),
31                std::sync::atomic::Ordering::Relaxed,
32            )
33        });
34        let statement_thread = (!nested).then(|| engine.statement_thread_context().enter());
35        (
36            Self {
37                engine,
38                depth,
39                statement_clock,
40                previous_clock,
41                _statement_thread: statement_thread,
42            },
43            nested,
44        )
45    }
46}
47
48impl Drop for SQLExecutionScope<'_> {
49    fn drop(&mut self) {
50        if let Some(previous) = self.previous_clock {
51            self.statement_clock
52                .store(previous, std::sync::atomic::Ordering::Relaxed);
53        }
54        let previous = self
55            .depth
56            .fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
57        debug_assert!(previous != 0, "SQL execution depth underflow");
58        // A statement outside a transaction block runs in a transaction of its own, so the LOCAL assignments it made (`set_config(..., true)`) end with it.
59        if previous == 1 && self.engine.transaction_depth() == 0 {
60            self.engine.restore_local_runtime_parameters();
61        }
62    }
63}
64
65impl Engine {
66    /// Bind retained regex state after provider initialization, which can install the native session allowance during initial catalog restoration.
67    pub(crate) fn session_regex_cache(&self) -> std::sync::Arc<uqa_sql::expr::RegexCache> {
68        let budget = self
69            .storage
70            .backend
71            .as_ref()
72            .and_then(|backend| backend.retention_control())
73            .map_or_else(
74                || self.session.query_retention.clone(),
75                |control| control.memory().clone(),
76            );
77        let mut retained = self.session.regex_cache.lock();
78        if let Some(cache) = retained
79            .as_ref()
80            .filter(|cache| cache.shares_allowance(&budget))
81        {
82            return cache.clone();
83        }
84        let cache = std::sync::Arc::new(uqa_sql::expr::RegexCache::new(budget));
85        *retained = Some(cache.clone());
86        cache
87    }
88
89    /// The thread context this session's statements evaluate under: its transaction clock, live date order and interval style, cancellation token and retained regex cache. Direct APIs that evaluate SQL expressions outside a statement enter the same context.
90    pub(crate) fn statement_thread_context(
91        &self,
92    ) -> uqa_execution::statement::thread_context::StatementThreadContext {
93        uqa_execution::statement::thread_context::StatementThreadContext {
94            retained_rows:
95                uqa_execution::query::sources::retained_source::RetainedRowContext::current(),
96            io: self.runtime.diagnostics.io_context(),
97            regex_cache: Some(self.session_regex_cache()),
98            temporal_input: uqa_sql::expr::TemporalInputContext {
99                transaction_clock_micros: self.session_transaction_clock_micros(),
100                interval_style: self.session.interval_style(),
101                date_order: uqa_sql::semantics::parameters::datestyle::date_order(
102                    &self.session.setting("DateStyle"),
103                ),
104            },
105            cancellation: Some(self.runtime.cancellation.clone()),
106        }
107    }
108
109    /// Public typed reads own a statement boundary; internal execution adapters retain their caller's existing scope instead.
110    pub(crate) fn with_direct_read_snapshot<R>(
111        &self,
112        read: impl FnOnce(&Self) -> Result<R, SQLError>,
113    ) -> Result<R, SQLError> {
114        self.with_direct_query_snapshot(true, read, std::convert::identity)
115    }
116
117    pub(crate) fn with_catalog_read_snapshot<R>(
118        &self,
119        read: impl FnOnce(&Self) -> uqa_storage::StorageBackendResult<R>,
120    ) -> uqa_storage::StorageBackendResult<R> {
121        self.with_direct_query_snapshot(true, read, |error| {
122            uqa_storage::StorageBackendError::backend("catalog query", error)
123        })
124    }
125
126    pub(crate) fn with_direct_query_snapshot<R, E: crate::transactions::TransactionError>(
127        &self,
128        read_only: bool,
129        query: impl FnOnce(&Self) -> Result<R, E>,
130        map_transaction_error: impl Fn(SQLError) -> E,
131    ) -> Result<R, E> {
132        let _statement = self.lock_statement_gate();
133        let (_execution, nested) = SQLExecutionScope::enter(self);
134        self.with_query_transaction_snapshot(!nested, read_only, query, map_transaction_error)
135    }
136
137    pub(crate) fn with_prepared_registration<R>(
138        &self,
139        parse: impl FnOnce(&Self) -> Result<std::sync::Arc<uqa_sql::Statement>, SQLError>,
140        register: impl FnOnce(&Self, std::sync::Arc<uqa_sql::Statement>) -> Result<R, SQLError>,
141    ) -> Result<R, SQLError> {
142        let _statement = self.lock_statement_gate();
143        let (_execution, nested) = SQLExecutionScope::enter(self);
144        self.run_prepared_operation(
145            || {
146                self.runtime.cancellation.check()?;
147                let statement = parse(self)?;
148                Ok((
149                    crate::transactions::prepared::PreparedOperation::Parse {
150                        statement: std::sync::Arc::clone(&statement),
151                        outermost: !nested,
152                    },
153                    statement,
154                ))
155            },
156            |statement| register(self, statement),
157        )
158    }
159
160    /// Execute a simple-query message, delivering each statement's result in order. The whole message is parsed before execution, and implicit transaction segments retain the same boundaries as [`Engine::sql`]. The final result is delivered only after its implicit transaction has committed. Earlier results may have been delivered when a later statement fails; such failure still rolls back its implicit segment. An empty message delivers one result with no command completion.
161    pub fn sql_simple_query(
162        &self,
163        query: &str,
164        params: &[SQLParam],
165        mut consume: impl FnMut(&SQLResult) -> Result<(), SQLError>,
166    ) -> Result<(), SQLError> {
167        let _statement = self.lock_statement_gate();
168        let (_execution, nested) = SQLExecutionScope::enter(self);
169        uqa_execution::statement::batch::execute_simple_query(
170            &self.batch_execution_context(),
171            query,
172            params,
173            nested,
174            &mut consume,
175        )
176    }
177
178    /// Execute a complete SQL message and return its final result. Multiple statements retain their native implicit transaction segments and explicit transaction boundaries; an empty message returns an empty result without a command tag.
179    pub fn sql(&self, query: &str, params: &[SQLParam]) -> Result<SQLResult, SQLError> {
180        let _statement = self.lock_statement_gate();
181        let (_execution, nested) = SQLExecutionScope::enter(self);
182        if nested {
183            uqa_execution::statement::batch::execute_nested(
184                &self.batch_execution_context(),
185                query,
186                params,
187            )
188        } else {
189            uqa_execution::statement::batch::execute(&self.batch_execution_context(), query, params)
190        }
191    }
192
193    pub(crate) fn execute_compiled_prepared(
194        &self,
195        name: &str,
196        statement: std::sync::Arc<uqa_sql::Statement>,
197        sql: Option<&str>,
198        params: &[SQLParam],
199    ) -> Result<SQLResult, SQLError> {
200        let _statement = self.lock_statement_gate();
201        let (_execution, nested) = SQLExecutionScope::enter(self);
202        uqa_execution::statement::batch::execute_prepared_statement(
203            &self.batch_execution_context(),
204            statement,
205            name,
206            sql,
207            params,
208            nested,
209        )
210    }
211
212    /// Execute one read query into a bounded spill and return a columnar batch
213    /// cursor. Unlike [`Engine::sql`], this path never retains the complete
214    /// result as `Vec<ResultRow>` in memory. The statement finishes and its
215    /// snapshot is committed before the cursor is returned.
216    pub fn sql_cursor(&self, query: &str, params: &[SQLParam]) -> Result<SQLCursor, SQLError> {
217        let _statement = self.lock_statement_gate();
218        let (_execution, nested) = SQLExecutionScope::enter(self);
219        if nested {
220            uqa_execution::statement::cursor::execute_nested(
221                &self.batch_execution_context(),
222                query,
223                params,
224            )
225        } else {
226            uqa_execution::statement::cursor::execute(
227                &self.batch_execution_context(),
228                query,
229                params,
230            )
231        }
232    }
233
234    /// Consume the bounded cursor synchronously without retaining batches.
235    pub fn sql_columnar(
236        &self,
237        query: &str,
238        params: &[SQLParam],
239        mut consume: impl FnMut(ColumnarBatch) -> Result<(), SQLError>,
240    ) -> Result<SQLCursorSummary, SQLError> {
241        let mut cursor = self.sql_cursor(query, params)?;
242        let summary = cursor.summary();
243        for batch in &mut cursor {
244            consume(batch?)?;
245        }
246        Ok(summary)
247    }
248}