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