1use super::{
10 batch::context::{BatchExecutionContext, CachedStatement},
11 plan_executor::UnifiedPlanExecutor,
12 transactions::{
13 abort_explicit_statement_error, rollback_after_statement_error, rollback_implicit_statement,
14 },
15};
16use crate::query::{cursor::SQLCursor, locking::query_has_row_locks};
17use std::sync::Arc;
18use uqa_sql::semantics::effects::{query_may_mutate_engine, query_requires_statement_transaction};
19use uqa_sql::{plan::UnifiedPlan, SQLError, SQLParam};
20
21pub fn execute<S: Clone + Send + Sync + 'static>(
22 context: &BatchExecutionContext<'_, S>,
23 sql: &str,
24 params: &[SQLParam],
25) -> Result<SQLCursor, SQLError> {
26 let _statement_deadline = crate::statement::batch::context::statement_deadline(context);
27 if let Err(error) = context.runtime.cancellation.check() {
28 return Err(abort_explicit_statement_error(
29 context.transactions,
30 error.into(),
31 ));
32 }
33 let _temporal_input = super::context::temporal_input_scope(context.statements);
34 let cached = context.cache.cached_sql_statement(sql);
35 if !context.persistent_backend && context.transactions.transaction_depth() == 0 {
36 if let Some((plan, parser)) = cached.as_ref().and_then(|cached| {
37 cached
38 .optimized_plan
39 .as_ref()
40 .map(|plan| (plan, &cached.parser))
41 }) {
42 if !context.statements.notification_subscriptions_required()
43 || matches!(plan.as_ref(), UnifiedPlan::Query(_))
44 {
45 for notice in parser.notices.iter() {
46 context.runtime.notices.push(notice.clone());
47 }
48 let executor = UnifiedPlanExecutor::new(
49 context.statements.statement_execution_context(),
50 params,
51 );
52 return execute_spilled(&executor, plan.as_ref());
53 }
54 }
55 }
56 execute_uncached_or_snapshot_scoped(context, sql, params, cached)
57}
58
59#[inline(never)]
60#[expect(
61 clippy::too_many_lines,
62 reason = "preserves cursor bounds and position"
63)]
64fn execute_uncached_or_snapshot_scoped<S: Clone + Send + Sync + 'static>(
65 context: &BatchExecutionContext<'_, S>,
66 sql: &str,
67 params: &[SQLParam],
68 cached: Option<CachedStatement>,
69) -> Result<SQLCursor, SQLError> {
70 let (statement, initial_plan, cached_optimized, parser) = if let Some(cached) = cached {
71 for notice in cached.parser.notices.iter() {
72 context.runtime.notices.push(notice.clone());
73 }
74 (
75 cached.statement.as_ref().clone(),
76 cached.logical_plan,
77 cached.optimized_plan,
78 cached.parser,
79 )
80 } else {
81 let (parsed, parser) =
82 uqa_sql::parser::with_settings(context.statements.parser_settings(), || {
83 uqa_sql::parse_statements(sql)
84 });
85 for notice in parser.notices.iter() {
86 context.runtime.notices.push(notice.clone());
87 }
88 let parsed =
89 parsed.map_err(|error| abort_explicit_statement_error(context.transactions, error))?;
90 if context.statements.notification_subscriptions_required() {
91 for statement in &parsed {
92 context.runtime.cancellation.check().map_err(|error| {
93 abort_explicit_statement_error(context.transactions, error.into())
94 })?;
95 if statement.is_notification_listener_command() {
96 return Err(abort_explicit_statement_error(
97 context.transactions,
98 SQLError::NotificationRequiresSubscription,
99 ));
100 }
101 }
102 }
103 let mut statements = parsed
104 .iter()
105 .map(uqa_sql::ParsedStatement::compile)
106 .collect::<Result<Vec<_>, _>>()
107 .map_err(|error| abort_explicit_statement_error(context.transactions, error))?;
108 if statements.len() != 1 {
109 return Err(abort_explicit_statement_error(
110 context.transactions,
111 single_query_error(statements.len()),
112 ));
113 }
114 let statement = statements.remove(0);
115 let plan = Arc::new(UnifiedPlan::lower_with(
116 statement.clone(),
117 context.aggregates,
118 ));
119 context.cache.cache_sql_statement(
120 sql.to_string(),
121 Arc::new(statement.clone()),
122 Arc::clone(&plan),
123 parser.clone(),
124 );
125 (statement, plan, None, parser)
126 };
127 if context.statements.notification_subscriptions_required()
128 && matches!(
129 statement,
130 uqa_sql::Statement::Listen { .. } | uqa_sql::Statement::Unlisten { .. }
131 )
132 {
133 return Err(abort_explicit_statement_error(
134 context.transactions,
135 SQLError::NotificationRequiresSubscription,
136 ));
137 }
138 let query = query_from_plan(initial_plan.as_ref())
139 .map_err(|error| abort_explicit_statement_error(context.transactions, error))?;
140 let has_row_locks = query_has_row_locks(query);
141 let _row_lock_statement = has_row_locks.then(|| context.row_locks.begin_row_lock_statement());
142
143 if context.transactions.transaction_depth() != 0 {
144 context.transactions.ensure_transaction_usable()?;
145 if has_row_locks {
146 context
147 .row_locks
148 .statement_row_lock_cache()
149 .map_err(|error| context.transactions.abort_after_error(error))?;
150 }
151 context
152 .transactions
153 .prepare_explicit_statement_snapshot(true)
154 .map_err(|error| context.transactions.abort_after_error(error))?;
155 let mut plan = UnifiedPlan::lower_with(statement.clone(), context.aggregates);
156 let current_query = query_from_plan(&plan)
157 .map_err(|error| context.transactions.abort_after_error(error))?;
158 context.cache.cache_sql_statement(
159 sql.to_string(),
160 Arc::new(statement.clone()),
161 Arc::new(plan.clone()),
162 parser.clone(),
163 );
164 if query_may_mutate_engine(&context.effects.query_effect_context(), current_query)
165 .map_err(|error| context.transactions.abort_after_error(error))?
166 && !has_row_locks
167 && context
168 .transactions
169 .prepare_explicit_transaction_writer()
170 .map_err(|error| context.transactions.abort_after_error(error))?
171 {
172 plan = UnifiedPlan::lower_with(statement.clone(), context.aggregates);
173 query_from_plan(&plan)
174 .map_err(|error| context.transactions.abort_after_error(error))?;
175 context.cache.cache_sql_statement(
176 sql.to_string(),
177 Arc::new(statement.clone()),
178 Arc::new(plan.clone()),
179 parser.clone(),
180 );
181 }
182 let optimized = context
183 .planning
184 .plan_for_execution(plan, params)
185 .map_err(|error| context.transactions.abort_after_error(error))?;
186 let executor =
187 UnifiedPlanExecutor::new(context.statements.statement_execution_context(), params);
188 return execute_spilled(&executor, &optimized)
189 .map_err(|error| context.transactions.abort_after_error(error));
190 }
191
192 let is_read_query = !query_may_mutate_engine(&context.effects.query_effect_context(), query)?;
193 let requires_statement_transaction = !is_read_query
194 || query_requires_statement_transaction(&context.effects.query_effect_context(), query)?;
195 let needs_transaction =
196 context.persistent_backend || requires_statement_transaction || has_row_locks;
197 if !needs_transaction {
198 let optimized = if let Some(plan) = cached_optimized {
199 plan
200 } else {
201 let (plan, reusable) = context
202 .planning
203 .plan_for_statement_cache(initial_plan.as_ref().clone(), params)?;
204 let plan = Arc::new(plan);
205 if reusable {
206 context
207 .cache
208 .cache_optimized_sql_plan(sql, Arc::clone(&plan));
209 }
210 plan
211 };
212 let executor =
213 UnifiedPlanExecutor::new(context.statements.statement_execution_context(), params);
214 return execute_spilled(&executor, optimized.as_ref());
215 }
216
217 if has_row_locks {
218 context.row_locks.statement_row_lock_cache()?;
219 }
220 context
221 .transactions
222 .begin_implicit_statement_transaction(is_read_query)?;
223 if let Err(error) = context
224 .transactions
225 .prepare_explicit_statement_snapshot(true)
226 {
227 return rollback_after_statement_error(context.transactions, error);
228 }
229 let mut plan = UnifiedPlan::lower_with(statement.clone(), context.aggregates);
230 context.cache.cache_sql_statement(
231 sql.to_string(),
232 Arc::new(statement.clone()),
233 Arc::new(plan.clone()),
234 parser.clone(),
235 );
236 let must_restart_as_writer = if is_read_query && context.persistent_backend && !has_row_locks {
237 match query_from_plan(&plan).and_then(|query| {
238 query_may_mutate_engine(&context.effects.query_effect_context(), query)
239 }) {
240 Ok(mutates) => mutates,
241 Err(error) => return rollback_after_statement_error(context.transactions, error),
242 }
243 } else {
244 false
245 };
246 if must_restart_as_writer {
247 rollback_implicit_statement(
248 context.transactions,
249 "restart cursor read transaction as writer",
250 )?;
251 context
252 .transactions
253 .begin_implicit_statement_transaction(false)?;
254 if let Err(error) = context
255 .transactions
256 .prepare_explicit_statement_snapshot(true)
257 {
258 return rollback_after_statement_error(context.transactions, error);
259 }
260 plan = UnifiedPlan::lower_with(statement.clone(), context.aggregates);
261 if let Err(error) = query_from_plan(&plan) {
262 return rollback_after_statement_error(context.transactions, error);
263 }
264 context.cache.cache_sql_statement(
265 sql.to_string(),
266 Arc::new(statement.clone()),
267 Arc::new(plan.clone()),
268 parser.clone(),
269 );
270 }
271 let mutating_query = match query_from_plan(&plan)
272 .and_then(|query| query_may_mutate_engine(&context.effects.query_effect_context(), query))
273 {
274 Ok(mutates) => mutates,
275 Err(error) => return rollback_after_statement_error(context.transactions, error),
276 };
277 if mutating_query && context.persistent_backend && !has_row_locks {
278 match context.transactions.prepare_explicit_transaction_writer() {
279 Ok(true) => {
280 plan = UnifiedPlan::lower_with(statement.clone(), context.aggregates);
281 if let Err(error) = query_from_plan(&plan) {
282 return rollback_after_statement_error(context.transactions, error);
283 }
284 context.cache.cache_sql_statement(
285 sql.to_string(),
286 Arc::new(statement.clone()),
287 Arc::new(plan.clone()),
288 parser.clone(),
289 );
290 }
291 Ok(false) => {}
292 Err(error) => return rollback_after_statement_error(context.transactions, error),
293 }
294 }
295 let optimized = match context.planning.plan_for_execution(plan, params) {
296 Ok(plan) => plan,
297 Err(error) => return rollback_after_statement_error(context.transactions, error),
298 };
299 let executor =
300 UnifiedPlanExecutor::new(context.statements.statement_execution_context(), params);
301 let cursor = match execute_spilled(&executor, &optimized) {
302 Ok(cursor) => cursor,
303 Err(error) => return rollback_after_statement_error(context.transactions, error),
304 };
305 context
306 .transactions
307 .run_transaction_statement(uqa_sql::ast::TransactionStmt::Commit)?;
308 Ok(cursor)
309}
310
311fn execute_spilled<S: Clone + Send + Sync + 'static>(
312 executor: &UnifiedPlanExecutor<'_, '_, S>,
313 plan: &UnifiedPlan,
314) -> Result<SQLCursor, SQLError> {
315 executor.execute_query_to_spill(plan)?.into_cursor()
316}
317
318fn query_from_plan(plan: &UnifiedPlan) -> Result<&uqa_sql::plan::QueryPlan, SQLError> {
319 let UnifiedPlan::Query(query) = plan else {
320 return Err(single_query_error(1));
321 };
322 Ok(query)
323}
324
325fn single_query_error(statement_count: usize) -> SQLError {
326 SQLError::Unsupported(format!(
327 "SQL cursor accepts exactly one query statement, received {statement_count}"
328 ))
329}