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