1use 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 _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 if previous == 1 && self.engine.transaction_depth() == 0 {
62 self.engine.restore_local_runtime_parameters();
63 }
64 }
65}
66
67impl Engine {
68 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 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 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 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 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}