1use super::{
10 plan_executor::{StatementOutput, UnifiedPlanExecutor},
11 transactions::{
12 abort_explicit_statement_error, rollback_after_statement_error, rollback_implicit_statement,
13 },
14};
15use crate::query::locking::query_has_row_locks;
16use context::{BatchExecutionContext, CachedStatement};
17use std::sync::Arc;
18use uqa_sql::{
19 plan::UnifiedPlan,
20 semantics::effects::{
21 is_transaction_control, query_may_mutate_engine, query_requires_statement_transaction,
22 transaction_blocks::{no_active_transaction_error, transaction_requires_explicit_block},
23 },
24 SQLError, SQLParam, SQLResult,
25};
26
27mod analysis;
28pub mod context;
29
30#[cfg(test)]
31mod tests;
32
33pub fn execute<S: Clone + Send + Sync + 'static>(
34 context: &BatchExecutionContext<'_, S>,
35 sql: &str,
36 params: &[SQLParam],
37) -> Result<SQLResult, SQLError> {
38 execute_with_context(context, sql, params, false, &mut None)
39}
40
41pub fn execute_nested<S: Clone + Send + Sync + 'static>(
42 context: &BatchExecutionContext<'_, S>,
43 sql: &str,
44 params: &[SQLParam],
45) -> Result<SQLResult, SQLError> {
46 execute_with_context(context, sql, params, true, &mut None)
47}
48
49enum ResultConsumer<'a> {
50 Completed(&'a mut dyn FnMut(&SQLResult) -> Result<(), SQLError>),
51 WithinStatement(&'a mut dyn FnMut(StatementOutput) -> Result<(), SQLError>),
52}
53
54pub fn execute_with_output<S: Clone + Send + Sync + 'static>(
57 context: &BatchExecutionContext<'_, S>,
58 sql: &str,
59 params: &[SQLParam],
60 consume: &mut dyn FnMut(StatementOutput) -> Result<(), SQLError>,
61) -> Result<(), SQLError> {
62 execute_with_context(
63 context,
64 sql,
65 params,
66 false,
67 &mut Some(ResultConsumer::WithinStatement(consume)),
68 )
69 .map(|_| ())
70}
71
72fn execute_plan<S: Clone + Send + Sync + 'static>(
73 executor: &mut UnifiedPlanExecutor<'_, '_, S>,
74 plan: &UnifiedPlan,
75 consumer: &mut Option<ResultConsumer<'_>>,
76) -> Result<SQLResult, SQLError> {
77 if let Some(ResultConsumer::WithinStatement(consume)) = consumer {
78 consume(executor.execute_for_output(plan)?)?;
79 Ok(SQLResult::empty())
81 } else {
82 executor.execute(plan)
83 }
84}
85
86enum StatementInput<'sql> {
87 Cached(Arc<uqa_sql::Statement>),
88 Parsed(uqa_sql::ParsedStatement<'sql>),
89}
90
91impl StatementInput<'_> {
92 fn is_notification_listener_command(&self) -> bool {
93 match self {
94 Self::Cached(statement) => matches!(
95 statement.as_ref(),
96 uqa_sql::Statement::Listen { .. } | uqa_sql::Statement::Unlisten { .. }
97 ),
98 Self::Parsed(statement) => statement.is_notification_listener_command(),
99 }
100 }
101}
102
103pub fn execute_simple_query<S: Clone + Send + Sync + 'static>(
104 context: &BatchExecutionContext<'_, S>,
105 sql: &str,
106 params: &[SQLParam],
107 nested_statement: bool,
108 consume: &mut dyn FnMut(&SQLResult) -> Result<(), SQLError>,
109) -> Result<(), SQLError> {
110 let mut consumer = Some(ResultConsumer::Completed(consume));
111 let result = execute_with_context(context, sql, params, nested_statement, &mut consumer)?;
112 consume_result(context, &result, &mut consumer)
113}
114
115fn consume_result<S: Clone + Send + Sync + 'static>(
116 context: &BatchExecutionContext<'_, S>,
117 result: &SQLResult,
118 consumer: &mut Option<ResultConsumer<'_>>,
119) -> Result<(), SQLError> {
120 if let Some(ResultConsumer::Completed(consume)) = consumer {
121 let _statement_thread = super::context::statement_thread_scope(
122 context.statements,
123 context.runtime.cancellation,
124 );
125 consume(result)
126 .map_err(|error| abort_explicit_statement_error(context.transactions, error))?;
127 }
128 Ok(())
129}
130
131fn execute_with_context<S: Clone + Send + Sync + 'static>(
132 context: &BatchExecutionContext<'_, S>,
133 sql: &str,
134 params: &[SQLParam],
135 nested_statement: bool,
136 consumer: &mut Option<ResultConsumer<'_>>,
137) -> Result<SQLResult, SQLError> {
138 if let Err(error) = context.runtime.cancellation.check() {
143 return Err(abort_explicit_statement_error(
144 context.transactions,
145 error.into(),
146 ));
147 }
148 let _statement_thread =
149 super::context::statement_thread_scope(context.statements, context.runtime.cancellation);
150 let display = context
152 .statements
153 .diagnostic_search_path()
154 .map(|path| uqa_sql::ast::TypeDisplayScope::enter(&path));
155 let cached = context.cache.cached_sql_statement(sql);
156 if !context.persistent_backend && context.transactions.transaction_depth() == 0 {
157 if let Some((plan, parser)) = cached.as_ref().and_then(|cached| {
158 cached
159 .optimized_plan
160 .as_ref()
161 .map(|plan| (plan, &cached.parser))
162 }) {
163 let _statement_deadline = (!nested_statement)
164 .then(|| context::statement_deadline(context))
165 .flatten();
166 let can_execute_without_transaction = match plan.as_ref() {
167 uqa_sql::plan::UnifiedPlan::Query(query) => !query_requires_statement_transaction(
168 &context.effects.query_effect_context(),
169 query,
170 )?,
171 uqa_sql::plan::UnifiedPlan::Command(_) => false,
172 };
173 if can_execute_without_transaction {
174 for notice in parser.notices.iter() {
175 context.runtime.notices.push(notice.clone());
176 }
177 let mut executor = UnifiedPlanExecutor::with_nested_statement(
178 context.statements.statement_execution_context(),
179 params,
180 nested_statement,
181 )
182 .with_source_sql(sql);
183 return execute_plan(&mut executor, plan.as_ref(), consumer);
184 }
185 }
186 }
187 execute_uncached_or_snapshot_scoped(
188 context,
189 sql,
190 params,
191 nested_statement,
192 consumer,
193 display.as_ref(),
194 cached,
195 )
196}
197
198#[inline(never)]
199#[expect(
200 clippy::too_many_lines,
201 reason = "preserves statement transaction order"
202)]
203fn execute_uncached_or_snapshot_scoped<S: Clone + Send + Sync + 'static>(
204 context: &BatchExecutionContext<'_, S>,
205 sql: &str,
206 params: &[SQLParam],
207 nested_statement: bool,
208 consumer: &mut Option<ResultConsumer<'_>>,
209 display: Option<&uqa_sql::ast::TypeDisplayScope>,
210 cached_statement: Option<CachedStatement>,
211) -> Result<SQLResult, SQLError> {
212 let (statements, mut cached_entry, parser) = match cached_statement {
218 Some(cached) => {
219 let parser = cached.parser.clone();
220 for notice in parser.notices.iter() {
221 context.runtime.notices.push(notice.clone());
222 }
223 (
224 vec![StatementInput::Cached(cached.statement.clone())],
225 Some(cached),
226 parser,
227 )
228 }
229 None => {
230 let (statements, parser) =
231 uqa_sql::parser::with_settings(context.statements.parser_settings(), || {
232 uqa_sql::parse_statements(sql)
233 });
234 for notice in parser.notices.iter() {
235 context.runtime.notices.push(notice.clone());
236 }
237 let statements = statements
238 .map_err(|error| abort_explicit_statement_error(context.transactions, error))?;
239 (
240 statements.into_iter().map(StatementInput::Parsed).collect(),
241 None,
242 parser,
243 )
244 }
245 };
246 if context.statements.notification_subscriptions_required() {
247 for statement in &statements {
248 context.runtime.cancellation.check().map_err(|error| {
249 abort_explicit_statement_error(context.transactions, error.into())
250 })?;
251 if statement.is_notification_listener_command() {
252 return Err(abort_explicit_statement_error(
253 context.transactions,
254 SQLError::NotificationRequiresSubscription,
255 ));
256 }
257 }
258 }
259 if statements.is_empty() {
260 return Ok(SQLResult::empty());
261 }
262 let is_single_statement = statements.len() == 1;
263 let final_statement_index = statements.len() - 1;
264 let simple_query_batch = !is_single_statement;
265 let mut implicit_segment_open = false;
266 let execution = (|| -> Result<SQLResult, SQLError> {
267 let mut last = SQLResult::empty();
268 for (statement_index, statement) in statements.into_iter().enumerate() {
269 let _statement_deadline = (!nested_statement)
270 .then(|| context::statement_deadline(context))
271 .flatten();
272 if let Err(error) = context.runtime.cancellation.check() {
273 return Err(abort_explicit_statement_error(
274 context.transactions,
275 error.into(),
276 ));
277 }
278 let _statement_thread = super::context::statement_thread_scope(
280 context.statements,
281 context.runtime.cancellation,
282 );
283 if let (Some(display), Some(path)) = (
285 display.filter(|_| statement_index > 0),
286 context.statements.diagnostic_search_path(),
287 ) {
288 display.refresh(&path);
289 }
290 let (parsed_statement, batch_statement) = match statement {
291 StatementInput::Cached(statement) => (Some(statement), None),
292 StatementInput::Parsed(statement) => {
293 let statement = statement.compile().map_err(|error| {
294 abort_explicit_statement_error(context.transactions, error)
295 })?;
296 if is_single_statement {
297 (Some(Arc::new(statement)), None)
298 } else {
299 (None, Some(statement))
300 }
301 }
302 };
303 let statement = parsed_statement
304 .as_deref()
305 .or(batch_statement.as_ref())
306 .expect("compiled statement");
307 let shared_statement =
308 || Arc::clone(parsed_statement.as_ref().expect("single statement cache"));
309 let transaction = match statement {
310 uqa_sql::ast::Statement::Transaction(transaction) => Some(transaction.clone()),
311 _ => None,
312 };
313 if simple_query_batch
314 && transaction
315 .as_ref()
316 .is_some_and(transaction_requires_explicit_block)
317 && (implicit_segment_open || context.transactions.transaction_depth() == 0)
318 {
319 return Err(no_active_transaction_error(
320 transaction.as_ref().expect("checked transaction command"),
321 ));
322 }
323 if simple_query_batch
324 && implicit_segment_open
325 && transaction.as_ref().is_some_and(|transaction| {
326 matches!(
327 transaction,
328 uqa_sql::ast::TransactionStmt::Begin
329 | uqa_sql::ast::TransactionStmt::BeginWithCharacteristics(_)
330 )
331 })
332 {
333 context.transactions.promote_simple_query_transaction()?;
337 if let Some(uqa_sql::ast::TransactionStmt::BeginWithCharacteristics(options)) =
338 transaction
339 {
340 context.transactions.run_transaction_statement(
341 uqa_sql::ast::TransactionStmt::SetCharacteristics(options),
342 )?;
343 }
344 implicit_segment_open = false;
345 last = SQLResult::empty();
346 last.command_tag = Some("BEGIN".into());
347 if statement_index != final_statement_index {
348 consume_result(context, &last, consumer)?;
349 }
350 continue;
351 }
352 if simple_query_batch
353 && transaction.is_none()
354 && context.transactions.transaction_depth() == 0
355 && !implicit_segment_open
356 {
357 context.transactions.begin_simple_query_transaction()?;
358 implicit_segment_open = true;
359 }
360 let (initial_plan, cached_optimized_plan) = if is_single_statement {
361 if let Some(cached) = cached_entry.take() {
362 (cached.logical_plan, cached.optimized_plan)
363 } else {
364 let plan = Arc::new(UnifiedPlan::lower_with(
365 statement.clone(),
366 context.aggregates,
367 ));
368 context.cache.cache_sql_statement(
369 sql.to_string(),
370 shared_statement(),
371 Arc::clone(&plan),
372 parser.clone(),
373 );
374 (plan, None)
375 }
376 } else {
377 (
378 Arc::new(UnifiedPlan::lower_with(
379 statement.clone(),
380 context.aggregates,
381 )),
382 None,
383 )
384 };
385 if is_transaction_control(initial_plan.as_ref()) {
386 if context.transactions.transaction_depth() == 0
388 && transaction.as_ref().is_some_and(|transaction| {
389 matches!(
390 transaction,
391 uqa_sql::ast::TransactionStmt::Commit
392 | uqa_sql::ast::TransactionStmt::Rollback
393 )
394 })
395 {
396 context.runtime.notices.push(
397 uqa_sql::semantics::effects::transaction_blocks::no_transaction_in_progress_warning(),
398 );
399 last = SQLResult::empty();
400 last.command_tag = Some(
401 uqa_sql::result::completion::transaction_completion(
402 transaction.as_ref().expect("checked transaction command"),
403 false,
404 )
405 .into(),
406 );
407 if statement_index != final_statement_index {
408 consume_result(context, &last, consumer)?;
409 }
410 continue;
411 }
412 if simple_query_batch
413 && implicit_segment_open
414 && transaction.as_ref().is_some_and(|transaction| {
415 matches!(
416 transaction,
417 uqa_sql::ast::TransactionStmt::Commit
418 | uqa_sql::ast::TransactionStmt::Rollback
419 )
420 })
421 {
422 context.runtime.notices.push(
423 uqa_sql::semantics::effects::transaction_blocks::no_transaction_in_progress_warning(),
424 );
425 }
426 let mut executor = UnifiedPlanExecutor::with_nested_statement(
427 context.statements.statement_execution_context(),
428 params,
429 nested_statement || simple_query_batch,
430 )
431 .with_source_sql(sql);
432 last = execute_plan(&mut executor, initial_plan.as_ref(), consumer)?;
433 if simple_query_batch
434 && transaction.as_ref().is_some_and(|transaction| {
435 matches!(
436 transaction,
437 uqa_sql::ast::TransactionStmt::Commit
438 | uqa_sql::ast::TransactionStmt::Rollback
439 )
440 })
441 {
442 implicit_segment_open = false;
443 }
444 if statement_index != final_statement_index {
445 consume_result(context, &last, consumer)?;
446 }
447 continue;
448 }
449 let (has_row_locks, needs_row_lock_statement) = match initial_plan.as_ref() {
450 uqa_sql::plan::UnifiedPlan::Query(query) => {
451 let has_row_locks = query_has_row_locks(query);
452 (has_row_locks, has_row_locks)
453 }
454 uqa_sql::plan::UnifiedPlan::Command(_) => (false, true),
455 };
456 let _row_lock_statement =
457 needs_row_lock_statement.then(|| context.row_locks.begin_row_lock_statement());
458
459 if context.transactions.transaction_depth() != 0 {
460 context.transactions.ensure_transaction_usable()?;
461 if has_row_locks {
462 context
463 .row_locks
464 .statement_row_lock_cache()
465 .map_err(|error| context.transactions.abort_after_error(error))?;
466 }
467 context
468 .transactions
469 .prepare_explicit_statement_snapshot(
470 uqa_sql::semantics::effects::read_only::plan_sets_transaction_snapshot(
471 initial_plan.as_ref(),
472 ),
473 )
474 .map_err(|error| context.transactions.abort_after_error(error))?;
475 let mut plan = UnifiedPlan::lower_with(statement.clone(), context.aggregates);
478 if is_single_statement {
479 context.cache.cache_sql_statement(
480 sql.to_string(),
481 shared_statement(),
482 Arc::new(plan.clone()),
483 parser.clone(),
484 );
485 }
486 let mutating_query = match &plan {
487 uqa_sql::plan::UnifiedPlan::Query(query) => {
488 query_may_mutate_engine(&context.effects.query_effect_context(), query)
489 }
490 uqa_sql::plan::UnifiedPlan::Command(_) => Ok(false),
491 }
492 .map_err(|error| context.transactions.abort_after_error(error))?;
493 if mutating_query
494 && !has_row_locks
495 && context
496 .transactions
497 .prepare_explicit_transaction_writer()
498 .map_err(|error| context.transactions.abort_after_error(error))?
499 {
500 plan = UnifiedPlan::lower_with(statement.clone(), context.aggregates);
501 if is_single_statement {
502 context.cache.cache_sql_statement(
503 sql.to_string(),
504 shared_statement(),
505 Arc::new(plan.clone()),
506 parser.clone(),
507 );
508 }
509 }
510 let optimized = match analysis::plan(
511 context,
512 sql,
513 plan,
514 params,
515 is_single_statement && !nested_statement,
516 ) {
517 Ok(plan) => plan,
518 Err(error) => {
519 return Err(context.transactions.abort_after_error(error));
520 }
521 };
522 let mut executor = UnifiedPlanExecutor::with_nested_statement(
523 context.statements.statement_execution_context(),
524 params,
525 nested_statement || simple_query_batch,
526 )
527 .with_source_sql(sql);
528 match execute_plan(&mut executor, &optimized, consumer) {
529 Ok(result) => last = result,
530 Err(error) => return Err(context.transactions.abort_after_error(error)),
531 }
532 if statement_index != final_statement_index {
533 consume_result(context, &last, consumer)?;
534 }
535 continue;
536 }
537
538 let (is_read_query, requires_statement_transaction) = match initial_plan.as_ref() {
546 uqa_sql::plan::UnifiedPlan::Query(query) => {
547 let mutates =
548 query_may_mutate_engine(&context.effects.query_effect_context(), query)?;
549 (
550 !mutates,
551 mutates
552 || query_requires_statement_transaction(
553 &context.effects.query_effect_context(),
554 query,
555 )?,
556 )
557 }
558 uqa_sql::plan::UnifiedPlan::Command(_) => (false, true),
559 };
560 let runs_outside_transaction = matches!(
561 initial_plan.as_ref(),
562 uqa_sql::plan::UnifiedPlan::Command(command)
563 if matches!(
564 command.as_ref(),
565 uqa_sql::plan::CommandPlan::Discard { .. }
566 | uqa_sql::plan::CommandPlan::Vacuum(_)
567 )
568 );
569 let needs_implicit_transaction = !runs_outside_transaction
570 && (context.persistent_backend || requires_statement_transaction || has_row_locks);
571 if needs_implicit_transaction {
572 if has_row_locks {
573 context.row_locks.statement_row_lock_cache()?;
574 }
575 context
576 .transactions
577 .begin_implicit_statement_transaction(is_read_query)?;
578 if let Err(error) = context.transactions.prepare_explicit_statement_snapshot(
579 uqa_sql::semantics::effects::read_only::plan_sets_transaction_snapshot(
580 initial_plan.as_ref(),
581 ),
582 ) {
583 return rollback_after_statement_error(context.transactions, error);
584 }
585 let mut plan = UnifiedPlan::lower_with(statement.clone(), context.aggregates);
591 if is_single_statement {
592 context.cache.cache_sql_statement(
593 sql.to_string(),
594 shared_statement(),
595 Arc::new(plan.clone()),
596 parser.clone(),
597 );
598 }
599 let must_restart_as_writer =
600 if is_read_query && context.persistent_backend && !has_row_locks {
601 match &plan {
602 uqa_sql::plan::UnifiedPlan::Query(query) => {
603 match query_may_mutate_engine(
604 &context.effects.query_effect_context(),
605 query,
606 ) {
607 Ok(mutates) => mutates,
608 Err(error) => {
609 return rollback_after_statement_error(
610 context.transactions,
611 error,
612 )
613 }
614 }
615 }
616 uqa_sql::plan::UnifiedPlan::Command(_) => false,
617 }
618 } else {
619 false
620 };
621 if must_restart_as_writer {
622 rollback_implicit_statement(
623 context.transactions,
624 "restart read transaction as writer",
625 )?;
626 context
627 .transactions
628 .begin_implicit_statement_transaction(false)?;
629 if let Err(error) = context.transactions.prepare_explicit_statement_snapshot(
630 uqa_sql::semantics::effects::read_only::plan_sets_transaction_snapshot(
631 initial_plan.as_ref(),
632 ),
633 ) {
634 return rollback_after_statement_error(context.transactions, error);
635 }
636 plan = UnifiedPlan::lower_with(statement.clone(), context.aggregates);
637 if is_single_statement {
638 context.cache.cache_sql_statement(
639 sql.to_string(),
640 shared_statement(),
641 Arc::new(plan.clone()),
642 parser.clone(),
643 );
644 }
645 }
646 let mutating_query = match &plan {
647 uqa_sql::plan::UnifiedPlan::Query(query) => {
648 query_may_mutate_engine(&context.effects.query_effect_context(), query)
649 }
650 uqa_sql::plan::UnifiedPlan::Command(_) => Ok(false),
651 };
652 let mutating_query = match mutating_query {
653 Ok(mutates) => mutates,
654 Err(error) => {
655 return rollback_after_statement_error(context.transactions, error)
656 }
657 };
658 if mutating_query && context.persistent_backend && !has_row_locks {
659 match context.transactions.prepare_explicit_transaction_writer() {
660 Ok(true) => {
661 plan = UnifiedPlan::lower_with(statement.clone(), context.aggregates);
662 if is_single_statement {
663 context.cache.cache_sql_statement(
664 sql.to_string(),
665 shared_statement(),
666 Arc::new(plan.clone()),
667 parser.clone(),
668 );
669 }
670 }
671 Ok(false) => {}
672 Err(error) => {
673 return rollback_after_statement_error(context.transactions, error)
674 }
675 }
676 }
677 let optimized = match analysis::plan(
678 context,
679 sql,
680 plan,
681 params,
682 is_single_statement && !nested_statement,
683 ) {
684 Ok(plan) => plan,
685 Err(error) => {
686 return rollback_after_statement_error(context.transactions, error)
687 }
688 };
689 let mut executor = UnifiedPlanExecutor::with_nested_statement(
690 context.statements.statement_execution_context(),
691 params,
692 nested_statement || simple_query_batch,
693 )
694 .with_source_sql(sql);
695 match execute_plan(&mut executor, &optimized, consumer) {
696 Ok(result) => {
697 context
700 .transactions
701 .run_transaction_statement(uqa_sql::ast::TransactionStmt::Commit)?;
702 last = result;
703 }
704 Err(statement_error) => {
705 return rollback_after_statement_error(
706 context.transactions,
707 statement_error,
708 )
709 }
710 }
711 } else {
712 let optimized = if let Some(plan) = cached_optimized_plan {
716 plan
717 } else {
718 let (plan, reusable) = context
719 .planning
720 .plan_for_statement_cache(initial_plan.as_ref().clone(), params)?;
721 let plan = Arc::new(plan);
722 if is_single_statement && reusable {
723 context
724 .cache
725 .cache_optimized_sql_plan(sql, Arc::clone(&plan));
726 }
727 plan
728 };
729 let mut executor = UnifiedPlanExecutor::with_nested_statement(
730 context.statements.statement_execution_context(),
731 params,
732 nested_statement || simple_query_batch,
733 )
734 .with_source_sql(sql);
735 last = execute_plan(&mut executor, optimized.as_ref(), consumer)?;
736 }
737 if statement_index != final_statement_index {
738 consume_result(context, &last, consumer)?;
739 }
740 }
741 Ok(last)
742 })();
743 if !simple_query_batch {
744 return execution;
745 }
746 let _statement_thread =
747 super::context::statement_thread_scope(context.statements, context.runtime.cancellation);
748 match execution {
749 Ok(result) if implicit_segment_open => {
750 context
751 .transactions
752 .run_transaction_statement(uqa_sql::ast::TransactionStmt::Commit)?;
753 Ok(result)
754 }
755 Ok(result) => Ok(result),
756 Err(error) if implicit_segment_open && context.transactions.transaction_depth() != 0 => {
757 rollback_after_statement_error(context.transactions, error)
758 }
759 Err(error) => Err(error),
760 }
761}