Skip to main content

uqa_execution/statement/
batch.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! SQL batch scheduling over live cache, transaction and statement inputs.
8
9use 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
41/// Execute native syntax through the same snapshot, deadline and transaction scheduler as SQL text, without reading or publishing text-cache entries.
42pub fn execute_prepared_statement<S: Clone + Send + Sync + 'static>(
43    context: &BatchExecutionContext<'_, S>,
44    statement: Arc<uqa_sql::Statement>,
45    name: &str,
46    sql: Option<&str>,
47    params: &[SQLParam],
48    nested_statement: bool,
49) -> Result<SQLResult, SQLError> {
50    context
51        .runtime
52        .cancellation
53        .check()
54        .map_err(|error| abort_explicit_statement_error(context.transactions, error.into()))?;
55    let _statement_thread =
56        super::context::statement_thread_scope(context.statements, context.runtime.cancellation);
57    let display = context
58        .statements
59        .diagnostic_search_path()
60        .map(|path| uqa_sql::ast::TypeDisplayScope::enter(&path));
61    let logical_plan = Arc::new(UnifiedPlan::lower_with(
62        statement.as_ref().clone(),
63        context.aggregates,
64    ));
65    execute_uncached_or_snapshot_scoped(
66        context,
67        StatementSource {
68            sql,
69            prepared: Some(name),
70        },
71        params,
72        nested_statement,
73        &mut None,
74        display.as_ref(),
75        Some(CachedStatement {
76            statement,
77            logical_plan,
78            optimized_plan: None,
79            parser: uqa_sql::parser::ParserMetadata::default(),
80        }),
81    )
82}
83
84pub fn execute_nested<S: Clone + Send + Sync + 'static>(
85    context: &BatchExecutionContext<'_, S>,
86    sql: &str,
87    params: &[SQLParam],
88) -> Result<SQLResult, SQLError> {
89    execute_with_context(context, sql, params, true, &mut None)
90}
91
92enum ResultConsumer<'a> {
93    Completed(&'a mut dyn FnMut(&SQLResult) -> Result<(), SQLError>),
94    WithinStatement(&'a mut dyn FnMut(StatementOutput) -> Result<(), SQLError>),
95}
96
97/// Consume results before the implicit statement or batch commits. Consumer errors
98/// follow the same rollback/abort path as errors raised by statement execution.
99pub fn execute_with_output<S: Clone + Send + Sync + 'static>(
100    context: &BatchExecutionContext<'_, S>,
101    sql: &str,
102    params: &[SQLParam],
103    consume: &mut dyn FnMut(StatementOutput) -> Result<(), SQLError>,
104) -> Result<(), SQLError> {
105    execute_with_context(
106        context,
107        sql,
108        params,
109        false,
110        &mut Some(ResultConsumer::WithinStatement(consume)),
111    )
112    .map(|_| ())
113}
114
115fn execute_plan<S: Clone + Send + Sync + 'static>(
116    executor: &mut UnifiedPlanExecutor<'_, '_, S>,
117    plan: &UnifiedPlan,
118    consumer: &mut Option<ResultConsumer<'_>>,
119    prepared: Option<&str>,
120) -> Result<SQLResult, SQLError> {
121    if let Some(name) = prepared {
122        return executor.execute_host_prepared(name);
123    }
124    if let Some(ResultConsumer::WithinStatement(consume)) = consumer {
125        consume(executor.execute_for_output(plan)?)?;
126        // This entry point hands off the result and returns no public row vector.
127        Ok(SQLResult::empty())
128    } else {
129        executor.execute(plan)
130    }
131}
132
133enum StatementInput<'sql> {
134    Cached(Arc<uqa_sql::Statement>),
135    Parsed(uqa_sql::ParsedStatement<'sql>),
136}
137
138impl StatementInput<'_> {
139    fn is_notification_listener_command(&self) -> bool {
140        match self {
141            Self::Cached(statement) => matches!(
142                statement.as_ref(),
143                uqa_sql::Statement::Listen { .. } | uqa_sql::Statement::Unlisten { .. }
144            ),
145            Self::Parsed(statement) => statement.is_notification_listener_command(),
146        }
147    }
148}
149
150pub fn execute_simple_query<S: Clone + Send + Sync + 'static>(
151    context: &BatchExecutionContext<'_, S>,
152    sql: &str,
153    params: &[SQLParam],
154    nested_statement: bool,
155    consume: &mut dyn FnMut(&SQLResult) -> Result<(), SQLError>,
156) -> Result<(), SQLError> {
157    let mut consumer = Some(ResultConsumer::Completed(consume));
158    let result = execute_with_context(context, sql, params, nested_statement, &mut consumer)?;
159    consume_result(context, &result, &mut consumer)
160}
161
162fn consume_result<S: Clone + Send + Sync + 'static>(
163    context: &BatchExecutionContext<'_, S>,
164    result: &SQLResult,
165    consumer: &mut Option<ResultConsumer<'_>>,
166) -> Result<(), SQLError> {
167    if let Some(ResultConsumer::Completed(consume)) = consumer {
168        let _statement_thread = super::context::statement_thread_scope(
169            context.statements,
170            context.runtime.cancellation,
171        );
172        consume(result)
173            .map_err(|error| abort_explicit_statement_error(context.transactions, error))?;
174    }
175    Ok(())
176}
177
178fn execute_with_context<S: Clone + Send + Sync + 'static>(
179    context: &BatchExecutionContext<'_, S>,
180    sql: &str,
181    params: &[SQLParam],
182    nested_statement: bool,
183    consumer: &mut Option<ResultConsumer<'_>>,
184) -> Result<SQLResult, SQLError> {
185    // Reject cancelled tokens up-front so a stale cancel signal does
186    // not leak into a fresh batch. Callers that want the
187    // cancellation flag preserved across statements should use
188    // their session cancellation-reset API explicitly between calls.
189    if let Err(error) = context.runtime.cancellation.check() {
190        return Err(abort_explicit_statement_error(
191            context.transactions,
192            error.into(),
193        ));
194    }
195    let _statement_thread =
196        super::context::statement_thread_scope(context.statements, context.runtime.cancellation);
197    // Diagnostics spell user-defined types as the statement's search path finds them.
198    let display = context
199        .statements
200        .diagnostic_search_path()
201        .map(|path| uqa_sql::ast::TypeDisplayScope::enter(&path));
202    let cached = context.cache.cached_sql_statement(sql);
203    if !context.persistent_backend && context.transactions.transaction_depth() == 0 {
204        if let Some((plan, parser)) = cached.as_ref().and_then(|cached| {
205            cached
206                .optimized_plan_for(params)
207                .map(|plan| (plan, &cached.parser))
208        }) {
209            let _statement_deadline = (!nested_statement)
210                .then(|| context::statement_deadline(context))
211                .flatten();
212            let can_execute_without_transaction = match plan.as_ref() {
213                uqa_sql::plan::UnifiedPlan::Query(query) => !query_requires_statement_transaction(
214                    &context.effects.query_effect_context(),
215                    query,
216                )?,
217                uqa_sql::plan::UnifiedPlan::Command(_) => false,
218            };
219            if can_execute_without_transaction {
220                for notice in parser.notices.iter() {
221                    context.runtime.notices.push(notice.clone());
222                }
223                let mut executor = UnifiedPlanExecutor::with_nested_statement(
224                    context.statements.statement_execution_context(),
225                    params,
226                    nested_statement,
227                )
228                .with_source_sql(sql);
229                return execute_plan(&mut executor, plan.as_ref(), consumer, None);
230            }
231        }
232    }
233    execute_uncached_or_snapshot_scoped(
234        context,
235        StatementSource {
236            sql: Some(sql),
237            prepared: None,
238        },
239        params,
240        nested_statement,
241        consumer,
242        display.as_ref(),
243        cached,
244    )
245}
246
247#[derive(Clone, Copy)]
248struct StatementSource<'a> {
249    sql: Option<&'a str>,
250    prepared: Option<&'a str>,
251}
252
253#[inline(never)]
254#[expect(
255    clippy::too_many_lines,
256    reason = "preserves statement transaction order"
257)]
258fn execute_uncached_or_snapshot_scoped<S: Clone + Send + Sync + 'static>(
259    context: &BatchExecutionContext<'_, S>,
260    source: StatementSource<'_>,
261    params: &[SQLParam],
262    nested_statement: bool,
263    consumer: &mut Option<ResultConsumer<'_>>,
264    display: Option<&uqa_sql::ast::TypeDisplayScope>,
265    cached_statement: Option<CachedStatement>,
266) -> Result<SQLResult, SQLError> {
267    let source_sql = source.sql;
268    let sql = source_sql.unwrap_or_default();
269    // Parse an uncached batch completely before executing its first statement.
270    // This preserves syntax atomicity. Exact single-statement cache hits reuse
271    // the parsed AST and logical plan; batches still lower each statement only
272    // when its turn arrives so earlier DDL, SET, ANALYZE, and function commands
273    // can affect the following statement's semantics.
274    let (mut statements, mut cached_entry, parser) = match cached_statement {
275        Some(cached) => {
276            let parser = cached.parser.clone();
277            for notice in parser.notices.iter() {
278                context.runtime.notices.push(notice.clone());
279            }
280            (
281                vec![StatementInput::Cached(cached.statement.clone())],
282                Some(cached),
283                parser,
284            )
285        }
286        None => {
287            let (statements, parser) =
288                uqa_sql::parser::with_settings(context.statements.parser_settings(), || {
289                    uqa_sql::parse_statements(sql)
290                });
291            for notice in parser.notices.iter() {
292                context.runtime.notices.push(notice.clone());
293            }
294            let statements = statements
295                .map_err(|error| abort_explicit_statement_error(context.transactions, error))?;
296            (
297                statements.into_iter().map(StatementInput::Parsed).collect(),
298                None,
299                parser,
300            )
301        }
302    };
303    if context.statements.notification_subscriptions_required() {
304        for statement in &statements {
305            context.runtime.cancellation.check().map_err(|error| {
306                abort_explicit_statement_error(context.transactions, error.into())
307            })?;
308            if statement.is_notification_listener_command() {
309                return Err(abort_explicit_statement_error(
310                    context.transactions,
311                    SQLError::NotificationRequiresSubscription,
312                ));
313            }
314        }
315    }
316    let empty_request = statements.is_empty();
317    if empty_request {
318        if params.is_empty() {
319            return Ok(SQLResult::empty());
320        }
321        // An empty request still binds supplied inputs in the native operation scope.
322        statements.push(StatementInput::Cached(Arc::new(uqa_sql::Statement::Empty)));
323    }
324    let is_single_statement = statements.len() == 1;
325    let cache_single_statement =
326        is_single_statement && !empty_request && source_sql.is_some() && source.prepared.is_none();
327    let final_statement_index = statements.len() - 1;
328    let simple_query_batch = !is_single_statement;
329    let mut implicit_segment_open = false;
330    let execution = (|| -> Result<SQLResult, SQLError> {
331        let mut last = SQLResult::empty();
332        for (statement_index, statement) in statements.into_iter().enumerate() {
333            let _statement_deadline = (!nested_statement)
334                .then(|| context::statement_deadline(context))
335                .flatten();
336            if let Err(error) = context.runtime.cancellation.check() {
337                return Err(abort_explicit_statement_error(
338                    context.transactions,
339                    error.into(),
340                ));
341            }
342            // An earlier command can have completed or chained the transaction while the message clock stays fixed.
343            let _statement_thread = super::context::statement_thread_scope(
344                context.statements,
345                context.runtime.cancellation,
346            );
347            // An earlier statement of the message may have changed the search path.
348            if let (Some(display), Some(path)) = (
349                display.filter(|_| statement_index > 0),
350                context.statements.diagnostic_search_path(),
351            ) {
352                display.refresh(&path);
353            }
354            let (parsed_statement, batch_statement) = match statement {
355                StatementInput::Cached(statement) => (Some(statement), None),
356                StatementInput::Parsed(statement) => {
357                    let statement = statement.compile().map_err(|error| {
358                        abort_explicit_statement_error(context.transactions, error)
359                    })?;
360                    if is_single_statement {
361                        (Some(Arc::new(statement)), None)
362                    } else {
363                        (None, Some(statement))
364                    }
365                }
366            };
367            let statement = parsed_statement
368                .as_deref()
369                .or(batch_statement.as_ref())
370                .expect("compiled statement");
371            let shared_statement =
372                || Arc::clone(parsed_statement.as_ref().expect("single statement cache"));
373            let transaction = match statement {
374                uqa_sql::ast::Statement::Transaction(transaction) => Some(transaction.clone()),
375                _ => None,
376            };
377            if simple_query_batch
378                && transaction
379                    .as_ref()
380                    .is_some_and(transaction_requires_explicit_block)
381                && (implicit_segment_open || context.transactions.transaction_depth() == 0)
382            {
383                return Err(no_active_transaction_error(
384                    transaction.as_ref().expect("checked transaction command"),
385                ));
386            }
387            if simple_query_batch
388                && implicit_segment_open
389                && transaction.as_ref().is_some_and(|transaction| {
390                    matches!(
391                        transaction,
392                        uqa_sql::ast::TransactionStmt::Begin
393                            | uqa_sql::ast::TransactionStmt::BeginWithCharacteristics(_)
394                    )
395                })
396            {
397                // PostgreSQL promotes the simple-query message's implicit
398                // transaction to an explicit block. The preceding statements
399                // stay uncommitted; a later COMMIT or ROLLBACK controls them.
400                context.transactions.promote_simple_query_transaction()?;
401                if let Some(uqa_sql::ast::TransactionStmt::BeginWithCharacteristics(options)) =
402                    transaction
403                {
404                    context.transactions.run_transaction_statement(
405                        uqa_sql::ast::TransactionStmt::SetCharacteristics(options),
406                    )?;
407                }
408                implicit_segment_open = false;
409                last = SQLResult::empty();
410                last.command_tag = Some("BEGIN".into());
411                if statement_index != final_statement_index {
412                    consume_result(context, &last, consumer)?;
413                }
414                continue;
415            }
416            if simple_query_batch
417                && transaction.is_none()
418                && context.transactions.transaction_depth() == 0
419                && !implicit_segment_open
420            {
421                context.transactions.begin_simple_query_transaction()?;
422                implicit_segment_open = true;
423            }
424            let (initial_plan, cached_optimized_plan) = if is_single_statement {
425                if let Some(cached) = cached_entry.take() {
426                    let optimized = cached.optimized_plan_for(params).cloned();
427                    (cached.logical_plan, optimized)
428                } else {
429                    let plan = Arc::new(UnifiedPlan::lower_with(
430                        statement.clone(),
431                        context.aggregates,
432                    ));
433                    if cache_single_statement {
434                        context.cache.cache_sql_statement(
435                            sql.to_string(),
436                            shared_statement(),
437                            Arc::clone(&plan),
438                            parser.clone(),
439                        );
440                    }
441                    (plan, None)
442                }
443            } else {
444                (
445                    Arc::new(UnifiedPlan::lower_with(
446                        statement.clone(),
447                        context.aggregates,
448                    )),
449                    None,
450                )
451            };
452            if is_transaction_control(initial_plan.as_ref()) {
453                let mut execute = || {
454                    let analyzed = if source.prepared.is_none() && !params.is_empty() {
455                        Some(
456                            context
457                                .planning
458                                .plan_for_execution(initial_plan.as_ref().clone(), params)?,
459                        )
460                    } else {
461                        None
462                    };
463                    // Completion follows host input binding. Prepared commands bind through their retained definition's request owner.
464                    if source.prepared.is_none() {
465                        if let Some(completed) = transaction.as_ref().and_then(|statement| {
466                            super::transactions::complete_idle_transaction(
467                                context.transactions,
468                                context.runtime.notices,
469                                statement,
470                            )
471                        }) {
472                            return Ok(completed);
473                        }
474                    }
475                    if simple_query_batch
476                        && implicit_segment_open
477                        && transaction.as_ref().is_some_and(|transaction| {
478                            matches!(
479                                transaction,
480                                uqa_sql::ast::TransactionStmt::Commit
481                                    | uqa_sql::ast::TransactionStmt::Rollback
482                            )
483                        })
484                    {
485                        context.runtime.notices.push(
486                            uqa_sql::semantics::effects::transaction_blocks::no_transaction_in_progress_warning(),
487                        );
488                    }
489                    let mut executor = UnifiedPlanExecutor::with_nested_statement(
490                        context.statements.statement_execution_context(),
491                        params,
492                        nested_statement || simple_query_batch,
493                    )
494                    .with_optional_source_sql(source_sql);
495                    execute_plan(
496                        &mut executor,
497                        analyzed.as_ref().unwrap_or(initial_plan.as_ref()),
498                        consumer,
499                        source.prepared,
500                    )
501                };
502                last = if source.prepared.is_none()
503                    && !params.is_empty()
504                    && context.transactions.transaction_depth() != 0
505                {
506                    context::with_active_transaction(context.transactions, execute)?
507                } else {
508                    execute()?
509                };
510                if simple_query_batch
511                    && transaction.as_ref().is_some_and(|transaction| {
512                        matches!(
513                            transaction,
514                            uqa_sql::ast::TransactionStmt::Commit
515                                | uqa_sql::ast::TransactionStmt::Rollback
516                        )
517                    })
518                {
519                    implicit_segment_open = false;
520                }
521                if statement_index != final_statement_index {
522                    consume_result(context, &last, consumer)?;
523                }
524                continue;
525            }
526            let empty_statement = matches!(
527                initial_plan.as_ref(),
528                UnifiedPlan::Command(command) if matches!(command.as_ref(), uqa_sql::plan::CommandPlan::Empty)
529            );
530            let (has_row_locks, needs_row_lock_statement) = match initial_plan.as_ref() {
531                uqa_sql::plan::UnifiedPlan::Query(query) => {
532                    let has_row_locks = query_has_row_locks(query);
533                    (has_row_locks, has_row_locks)
534                }
535                uqa_sql::plan::UnifiedPlan::Command(_) => (false, !empty_statement),
536            };
537            let _row_lock_statement =
538                needs_row_lock_statement.then(|| context.row_locks.begin_row_lock_statement());
539
540            if context.transactions.transaction_depth() != 0 {
541                last = context::with_active_transaction(context.transactions, || {
542                    if has_row_locks {
543                        context.row_locks.statement_row_lock_cache()?;
544                    }
545                    if !empty_statement {
546                        context.transactions.prepare_explicit_statement_snapshot(
547                            uqa_sql::semantics::effects::read_only::plan_sets_transaction_snapshot(
548                                initial_plan.as_ref(),
549                            ),
550                        )?;
551                    }
552                    // Earlier BEGIN or catalog changes precede this statement's admitted snapshot.
553                    let mut plan = UnifiedPlan::lower_with(statement.clone(), context.aggregates);
554                    if cache_single_statement {
555                        context.cache.cache_sql_statement(
556                            sql.to_string(),
557                            shared_statement(),
558                            Arc::new(plan.clone()),
559                            parser.clone(),
560                        );
561                    }
562                    let mutating_query = match &plan {
563                        uqa_sql::plan::UnifiedPlan::Query(query) => {
564                            query_may_mutate_engine(&context.effects.query_effect_context(), query)
565                        }
566                        uqa_sql::plan::UnifiedPlan::Command(_) => Ok(false),
567                    }?;
568                    if mutating_query
569                        && !has_row_locks
570                        && context.transactions.prepare_explicit_transaction_writer()?
571                    {
572                        plan = UnifiedPlan::lower_with(statement.clone(), context.aggregates);
573                        if cache_single_statement {
574                            context.cache.cache_sql_statement(
575                                sql.to_string(),
576                                shared_statement(),
577                                Arc::new(plan.clone()),
578                                parser.clone(),
579                            );
580                        }
581                    }
582                    let optimized = analysis::plan(
583                        context,
584                        sql,
585                        plan,
586                        params,
587                        cache_single_statement && !nested_statement,
588                        source.prepared.is_some(),
589                    )?;
590                    let mut executor = UnifiedPlanExecutor::with_nested_statement(
591                        context.statements.statement_execution_context(),
592                        params,
593                        nested_statement || simple_query_batch,
594                    )
595                    .with_optional_source_sql(source_sql);
596                    execute_plan(&mut executor, &optimized, consumer, source.prepared)
597                })?;
598                if statement_index != final_statement_index {
599                    consume_result(context, &last, consumer)?;
600                }
601                continue;
602            }
603
604            // Every persistent SQL statement owns one storage transaction when
605            // the caller has not opened an explicit transaction. This is the
606            // actual autocommit boundary: catalog, document, FTS, btree, vector,
607            // graph, and registry writes either commit together or are all rolled
608            // back. Memory commands use the same boundary so a fallible multi-row
609            // mutation restores its pre-statement snapshot; read-only memory
610            // queries avoid copying the whole database.
611            let (is_read_query, requires_statement_transaction) = match initial_plan.as_ref() {
612                uqa_sql::plan::UnifiedPlan::Query(query) => {
613                    let mutates =
614                        query_may_mutate_engine(&context.effects.query_effect_context(), query)?;
615                    (
616                        !mutates,
617                        mutates
618                            || query_requires_statement_transaction(
619                                &context.effects.query_effect_context(),
620                                query,
621                            )?,
622                    )
623                }
624                uqa_sql::plan::UnifiedPlan::Command(_) => (false, true),
625            };
626            let runs_outside_transaction = matches!(
627                initial_plan.as_ref(),
628                uqa_sql::plan::UnifiedPlan::Command(command)
629                    if matches!(
630                        command.as_ref(),
631                        uqa_sql::plan::CommandPlan::Empty
632                            | uqa_sql::plan::CommandPlan::Discard { .. }
633                            | uqa_sql::plan::CommandPlan::Vacuum(_)
634                    )
635            );
636            let needs_implicit_transaction = !runs_outside_transaction
637                && (context.persistent_backend || requires_statement_transaction || has_row_locks);
638            if needs_implicit_transaction {
639                if has_row_locks {
640                    context.row_locks.statement_row_lock_cache()?;
641                }
642                context
643                    .transactions
644                    .begin_implicit_statement_transaction(is_read_query)?;
645                if let Err(error) = context.transactions.prepare_explicit_statement_snapshot(
646                    uqa_sql::semantics::effects::read_only::plan_sets_transaction_snapshot(
647                        initial_plan.as_ref(),
648                    ),
649                ) {
650                    return rollback_after_statement_error(context.transactions, error);
651                }
652                // Catalog/table refresh intentionally invalidates cached logical
653                // plans even when the in-process generation did not move: a
654                // sibling SQLite writer can release its lock immediately before
655                // publishing that generation. Re-lower the parsed statement while
656                // the database snapshot is pinned, then optimize that exact plan.
657                let mut plan = UnifiedPlan::lower_with(statement.clone(), context.aggregates);
658                if cache_single_statement {
659                    context.cache.cache_sql_statement(
660                        sql.to_string(),
661                        shared_statement(),
662                        Arc::new(plan.clone()),
663                        parser.clone(),
664                    );
665                }
666                let must_restart_as_writer =
667                    if is_read_query && context.persistent_backend && !has_row_locks {
668                        match &plan {
669                            uqa_sql::plan::UnifiedPlan::Query(query) => {
670                                match query_may_mutate_engine(
671                                    &context.effects.query_effect_context(),
672                                    query,
673                                ) {
674                                    Ok(mutates) => mutates,
675                                    Err(error) => {
676                                        return rollback_after_statement_error(
677                                            context.transactions,
678                                            error,
679                                        )
680                                    }
681                                }
682                            }
683                            uqa_sql::plan::UnifiedPlan::Command(_) => false,
684                        }
685                    } else {
686                        false
687                    };
688                if must_restart_as_writer {
689                    rollback_implicit_statement(
690                        context.transactions,
691                        "restart read transaction as writer",
692                    )?;
693                    context
694                        .transactions
695                        .begin_implicit_statement_transaction(false)?;
696                    if let Err(error) = context.transactions.prepare_explicit_statement_snapshot(
697                        uqa_sql::semantics::effects::read_only::plan_sets_transaction_snapshot(
698                            initial_plan.as_ref(),
699                        ),
700                    ) {
701                        return rollback_after_statement_error(context.transactions, error);
702                    }
703                    plan = UnifiedPlan::lower_with(statement.clone(), context.aggregates);
704                    if cache_single_statement {
705                        context.cache.cache_sql_statement(
706                            sql.to_string(),
707                            shared_statement(),
708                            Arc::new(plan.clone()),
709                            parser.clone(),
710                        );
711                    }
712                }
713                let mutating_query = match &plan {
714                    uqa_sql::plan::UnifiedPlan::Query(query) => {
715                        query_may_mutate_engine(&context.effects.query_effect_context(), query)
716                    }
717                    uqa_sql::plan::UnifiedPlan::Command(_) => Ok(false),
718                };
719                let mutating_query = match mutating_query {
720                    Ok(mutates) => mutates,
721                    Err(error) => {
722                        return rollback_after_statement_error(context.transactions, error)
723                    }
724                };
725                if mutating_query && context.persistent_backend && !has_row_locks {
726                    match context.transactions.prepare_explicit_transaction_writer() {
727                        Ok(true) => {
728                            plan = UnifiedPlan::lower_with(statement.clone(), context.aggregates);
729                            if cache_single_statement {
730                                context.cache.cache_sql_statement(
731                                    sql.to_string(),
732                                    shared_statement(),
733                                    Arc::new(plan.clone()),
734                                    parser.clone(),
735                                );
736                            }
737                        }
738                        Ok(false) => {}
739                        Err(error) => {
740                            return rollback_after_statement_error(context.transactions, error)
741                        }
742                    }
743                }
744                let optimized = match analysis::plan(
745                    context,
746                    sql,
747                    plan,
748                    params,
749                    cache_single_statement && !nested_statement,
750                    source.prepared.is_some(),
751                ) {
752                    Ok(plan) => plan,
753                    Err(error) => {
754                        return rollback_after_statement_error(context.transactions, error)
755                    }
756                };
757                let mut executor = UnifiedPlanExecutor::with_nested_statement(
758                    context.statements.statement_execution_context(),
759                    params,
760                    nested_statement || simple_query_batch,
761                )
762                .with_optional_source_sql(source_sql);
763                match execute_plan(&mut executor, &optimized, consumer, source.prepared) {
764                    Ok(result) => {
765                        // Commit failure cleanup is owned by the transaction
766                        // layer, including cache restoration and stack reset.
767                        context
768                            .transactions
769                            .run_transaction_statement(uqa_sql::ast::TransactionStmt::Commit)?;
770                        last = result;
771                    }
772                    Err(statement_error) => {
773                        return rollback_after_statement_error(
774                            context.transactions,
775                            statement_error,
776                        )
777                    }
778                }
779            } else {
780                // In-memory read-only queries run without a transaction snapshot.
781                // Catalog generations protect identity, while SQL analysis decides
782                // whether input constants also require a fresh message boundary.
783                let optimized = if source.prepared.is_some() {
784                    initial_plan.clone()
785                } else if let Some(plan) = cached_optimized_plan {
786                    plan
787                } else {
788                    let (plan, reusable) = context
789                        .planning
790                        .plan_for_statement_cache(initial_plan.as_ref().clone(), params)?;
791                    let plan = Arc::new(plan);
792                    if cache_single_statement && reusable {
793                        context
794                            .cache
795                            .cache_optimized_sql_plan(sql, Arc::clone(&plan));
796                    }
797                    plan
798                };
799                let mut executor = UnifiedPlanExecutor::with_nested_statement(
800                    context.statements.statement_execution_context(),
801                    params,
802                    nested_statement || simple_query_batch,
803                )
804                .with_optional_source_sql(source_sql);
805                last = execute_plan(&mut executor, optimized.as_ref(), consumer, source.prepared)?;
806            }
807            if statement_index != final_statement_index {
808                consume_result(context, &last, consumer)?;
809            }
810        }
811        Ok(last)
812    })();
813    if !simple_query_batch {
814        return execution;
815    }
816    let _statement_thread =
817        super::context::statement_thread_scope(context.statements, context.runtime.cancellation);
818    match execution {
819        Ok(result) if implicit_segment_open => {
820            context
821                .transactions
822                .run_transaction_statement(uqa_sql::ast::TransactionStmt::Commit)?;
823            Ok(result)
824        }
825        Ok(result) => Ok(result),
826        Err(error) if implicit_segment_open && context.transactions.transaction_depth() != 0 => {
827            rollback_after_statement_error(context.transactions, error)
828        }
829        Err(error) => Err(error),
830    }
831}