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