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
14struct 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    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    /// The thread context this session's statements evaluate under: its transaction clock, live date order and interval style, and its cancellation token. Direct APIs that evaluate SQL expressions outside a statement enter the same context.
67    pub(crate) fn statement_thread_context(
68        &self,
69    ) -> uqa_execution::statement::thread_context::StatementThreadContext {
70        uqa_execution::statement::thread_context::StatementThreadContext {
71            temporal_input: uqa_sql::expr::TemporalInputContext {
72                transaction_clock_micros: self.session_transaction_clock_micros(),
73                interval_style: self.session.interval_style(),
74                date_order: uqa_sql::semantics::parameters::datestyle::date_order(
75                    &self.session.setting("DateStyle"),
76                ),
77            },
78            cancellation: Some(self.runtime.cancellation.clone()),
79        }
80    }
81
82    /// Public typed reads own a statement boundary; internal execution adapters retain their caller's existing scope instead.
83    pub(crate) fn with_direct_read_snapshot<R>(
84        &self,
85        read: impl FnOnce(&Self) -> Result<R, SQLError>,
86    ) -> Result<R, SQLError> {
87        self.with_direct_query_snapshot(true, read, std::convert::identity)
88    }
89
90    pub(crate) fn with_catalog_read_snapshot<R>(
91        &self,
92        read: impl FnOnce(&Self) -> uqa_storage::StorageBackendResult<R>,
93    ) -> uqa_storage::StorageBackendResult<R> {
94        self.with_direct_query_snapshot(true, read, |error| {
95            uqa_storage::StorageBackendError::backend("catalog query", error)
96        })
97    }
98
99    pub(crate) fn with_direct_query_snapshot<R, E: std::fmt::Display>(
100        &self,
101        read_only: bool,
102        query: impl FnOnce(&Self) -> Result<R, E>,
103        map_transaction_error: impl Fn(SQLError) -> E,
104    ) -> Result<R, E> {
105        let _statement = self.lock_statement_gate();
106        let (_execution, nested) = SQLExecutionScope::enter(self);
107        self.with_query_transaction_snapshot(!nested, read_only, query, map_transaction_error)
108    }
109
110    /// 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.
111    pub fn sql_simple_query(
112        &self,
113        query: &str,
114        params: &[SQLParam],
115        mut consume: impl FnMut(&SQLResult) -> Result<(), SQLError>,
116    ) -> Result<(), SQLError> {
117        let _statement = self.lock_statement_gate();
118        let (_execution, nested) = SQLExecutionScope::enter(self);
119        self.synchronize_table_catalog()
120            .map_err(|error| SQLError::Internal(format!("refresh table catalog: {error}")))?;
121        self.synchronize_table_data().map_err(|error| {
122            SQLError::Internal(format!("refresh committed table data: {error}"))
123        })?;
124        self.synchronize_catalog_registries().map_err(|error| {
125            SQLError::Internal(format!("refresh durable catalog registries: {error}"))
126        })?;
127        uqa_execution::statement::batch::execute_simple_query(
128            &self.batch_execution_context(),
129            query,
130            params,
131            nested,
132            &mut consume,
133        )
134    }
135
136    /// Run a single SQL statement against the engine.
137    pub fn sql(&self, query: &str, params: &[SQLParam]) -> Result<SQLResult, SQLError> {
138        let _statement = self.lock_statement_gate();
139        let (_execution, nested) = SQLExecutionScope::enter(self);
140        self.synchronize_table_catalog()
141            .map_err(|err| SQLError::Internal(format!("refresh table catalog: {err}")))?;
142        self.synchronize_table_data()
143            .map_err(|err| SQLError::Internal(format!("refresh committed table data: {err}")))?;
144        self.synchronize_catalog_registries().map_err(|err| {
145            SQLError::Internal(format!("refresh durable catalog registries: {err}"))
146        })?;
147        if nested {
148            uqa_execution::statement::batch::execute_nested(
149                &self.batch_execution_context(),
150                query,
151                params,
152            )
153        } else {
154            uqa_execution::statement::batch::execute(&self.batch_execution_context(), query, params)
155        }
156    }
157
158    /// Execute one read query into a bounded spill and return a columnar batch
159    /// cursor. Unlike [`Engine::sql`], this path never retains the complete
160    /// result as `Vec<ResultRow>` in memory. The statement finishes and its
161    /// snapshot is committed before the cursor is returned.
162    pub fn sql_cursor(&self, query: &str, params: &[SQLParam]) -> Result<SQLCursor, SQLError> {
163        let _statement = self.lock_statement_gate();
164        let (_execution, _) = SQLExecutionScope::enter(self);
165        self.synchronize_table_catalog()
166            .map_err(|err| SQLError::Internal(format!("refresh table catalog: {err}")))?;
167        self.synchronize_table_data()
168            .map_err(|err| SQLError::Internal(format!("refresh committed table data: {err}")))?;
169        self.synchronize_catalog_registries().map_err(|err| {
170            SQLError::Internal(format!("refresh durable catalog registries: {err}"))
171        })?;
172        uqa_execution::statement::cursor::execute(&self.batch_execution_context(), query, params)
173    }
174
175    /// Consume the bounded cursor synchronously without retaining batches.
176    pub fn sql_columnar(
177        &self,
178        query: &str,
179        params: &[SQLParam],
180        mut consume: impl FnMut(ColumnarBatch) -> Result<(), SQLError>,
181    ) -> Result<SQLCursorSummary, SQLError> {
182        let mut cursor = self.sql_cursor(query, params)?;
183        let summary = cursor.summary();
184        for batch in &mut cursor {
185            consume(batch?)?;
186        }
187        Ok(summary)
188    }
189}