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 and execution clocks.
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 transaction start the statement's input functions and `now()` read, entered for the outermost statement on the executing thread; a nested statement keeps its caller's.
20    _transaction_clock: Option<uqa_sql::expr::TransactionClockScope>,
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 transaction_clock = (!nested).then(|| {
35            uqa_sql::expr::TransactionClockScope::enter(engine.transaction_timestamp_micros())
36        });
37        (
38            Self {
39                engine,
40                depth,
41                statement_clock,
42                previous_clock,
43                _transaction_clock: transaction_clock,
44            },
45            nested,
46        )
47    }
48}
49
50impl Drop for SQLExecutionScope<'_> {
51    fn drop(&mut self) {
52        if let Some(previous) = self.previous_clock {
53            self.statement_clock
54                .store(previous, std::sync::atomic::Ordering::Relaxed);
55        }
56        let previous = self
57            .depth
58            .fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
59        debug_assert!(previous != 0, "SQL execution depth underflow");
60        // 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.
61        if previous == 1 && self.engine.transaction_depth() == 0 {
62            self.engine.restore_local_runtime_parameters();
63        }
64    }
65}
66
67impl Engine {
68    /// Public typed reads own a statement boundary; internal execution adapters retain their caller's existing scope instead.
69    pub(crate) fn with_direct_read_snapshot<R>(
70        &self,
71        read: impl FnOnce(&Self) -> Result<R, SQLError>,
72    ) -> Result<R, SQLError> {
73        self.with_direct_query_snapshot(true, read, std::convert::identity)
74    }
75
76    pub(crate) fn with_catalog_read_snapshot<R>(
77        &self,
78        read: impl FnOnce(&Self) -> uqa_storage::StorageBackendResult<R>,
79    ) -> uqa_storage::StorageBackendResult<R> {
80        self.with_direct_query_snapshot(true, read, |error| {
81            uqa_storage::StorageBackendError::backend("catalog query", error)
82        })
83    }
84
85    pub(crate) fn with_direct_query_snapshot<R, E: std::fmt::Display>(
86        &self,
87        read_only: bool,
88        query: impl FnOnce(&Self) -> Result<R, E>,
89        map_transaction_error: impl Fn(SQLError) -> E,
90    ) -> Result<R, E> {
91        let _statement = self.lock_statement_gate();
92        let (_execution, nested) = SQLExecutionScope::enter(self);
93        self.with_query_transaction_snapshot(!nested, read_only, query, map_transaction_error)
94    }
95
96    /// 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.
97    pub fn sql_simple_query(
98        &self,
99        query: &str,
100        params: &[SQLParam],
101        mut consume: impl FnMut(&SQLResult) -> Result<(), SQLError>,
102    ) -> Result<(), SQLError> {
103        let _statement = self.lock_statement_gate();
104        let (_execution, nested) = SQLExecutionScope::enter(self);
105        self.synchronize_table_catalog()
106            .map_err(|error| SQLError::Internal(format!("refresh table catalog: {error}")))?;
107        self.synchronize_table_data().map_err(|error| {
108            SQLError::Internal(format!("refresh committed table data: {error}"))
109        })?;
110        self.synchronize_catalog_registries().map_err(|error| {
111            SQLError::Internal(format!("refresh durable catalog registries: {error}"))
112        })?;
113        uqa_execution::statement::batch::execute_simple_query(
114            &self.batch_execution_context(),
115            query,
116            params,
117            nested,
118            &mut consume,
119        )
120    }
121
122    /// Run a single SQL statement against the engine.
123    pub fn sql(&self, query: &str, params: &[SQLParam]) -> Result<SQLResult, SQLError> {
124        let _statement = self.lock_statement_gate();
125        let (_execution, nested) = SQLExecutionScope::enter(self);
126        self.synchronize_table_catalog()
127            .map_err(|err| SQLError::Internal(format!("refresh table catalog: {err}")))?;
128        self.synchronize_table_data()
129            .map_err(|err| SQLError::Internal(format!("refresh committed table data: {err}")))?;
130        self.synchronize_catalog_registries().map_err(|err| {
131            SQLError::Internal(format!("refresh durable catalog registries: {err}"))
132        })?;
133        if nested {
134            uqa_execution::statement::batch::execute_nested(
135                &self.batch_execution_context(),
136                query,
137                params,
138            )
139        } else {
140            uqa_execution::statement::batch::execute(&self.batch_execution_context(), query, params)
141        }
142    }
143
144    /// Execute one read query into a bounded spill and return a columnar batch
145    /// cursor. Unlike [`Engine::sql`], this path never retains the complete
146    /// result as `Vec<ResultRow>` in memory. The statement finishes and its
147    /// snapshot is committed before the cursor is returned.
148    pub fn sql_cursor(&self, query: &str, params: &[SQLParam]) -> Result<SQLCursor, SQLError> {
149        let _statement = self.lock_statement_gate();
150        let (_execution, _) = SQLExecutionScope::enter(self);
151        self.synchronize_table_catalog()
152            .map_err(|err| SQLError::Internal(format!("refresh table catalog: {err}")))?;
153        self.synchronize_table_data()
154            .map_err(|err| SQLError::Internal(format!("refresh committed table data: {err}")))?;
155        self.synchronize_catalog_registries().map_err(|err| {
156            SQLError::Internal(format!("refresh durable catalog registries: {err}"))
157        })?;
158        uqa_execution::statement::cursor::execute(&self.batch_execution_context(), query, params)
159    }
160
161    /// Consume the bounded cursor synchronously without retaining batches.
162    pub fn sql_columnar(
163        &self,
164        query: &str,
165        params: &[SQLParam],
166        mut consume: impl FnMut(ColumnarBatch) -> Result<(), SQLError>,
167    ) -> Result<SQLCursorSummary, SQLError> {
168        let mut cursor = self.sql_cursor(query, params)?;
169        let summary = cursor.summary();
170        for batch in &mut cursor {
171            consume(batch?)?;
172        }
173        Ok(summary)
174    }
175}