Skip to main content

uqa_execution/statement/
plan_executor.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Exhaustive physical executor for the unified SQL plan.
8
9use crate::schema::ctas::CreateTableAsExecution;
10use uqa_sql::ast::{CreateForeignServer, CreateForeignTable};
11use uqa_sql::catalog::roles::RoleReference;
12use uqa_sql::plan::{
13    CommandPlan, DeletePlan, ExpressionPlan, InsertPlan, MergePlan, QueryPlan, UnifiedPlan,
14    UpdatePlan,
15};
16use uqa_sql::{SQLError, SQLParam, SQLResult};
17
18use super::context::StatementExecutionContext;
19
20mod completion;
21mod explain;
22mod prepared;
23mod types;
24use crate::schema::view_creation::{self, MaterializedViewRegistration, ViewRegistration};
25
26use crate::query::output::QueryOutput;
27use crate::query::statement::{
28    consumer::QueryOutputMode, execute_query_plan_output, execute_query_plan_with_ctes,
29};
30use crate::scalar::plan::{analyze_physical_call_arguments, eval_physical_call_arguments};
31
32/// Statement output consumed inside the transaction, retaining a bounded query spool instead of a public row vector.
33pub enum StatementOutput {
34    Query(QueryOutput),
35    Command(SQLResult),
36    Mutation(crate::mutation::output::MutationOutput),
37}
38
39/// Owns top-level plan orchestration. Relational, mutation, DDL, procedural,
40/// and prepared-plan execution all enter through this exhaustive dispatcher;
41/// leaf executors never choose a second top-level SQL path.
42pub struct UnifiedPlanExecutor<'engine, 'params, S: Clone + 'static> {
43    context: StatementExecutionContext<'engine, S>,
44    params: &'params [SQLParam],
45    nested_statement: bool,
46    privilege_subject: Option<RoleReference>,
47    source_sql: Option<String>,
48    inherited_ctes: Option<crate::query::CteScope<S>>,
49}
50
51impl<'engine, 'params, S: Clone + Send + Sync + 'static> UnifiedPlanExecutor<'engine, 'params, S> {
52    pub fn new(
53        context: StatementExecutionContext<'engine, S>,
54        params: &'params [SQLParam],
55    ) -> Self {
56        Self::with_nested_statement(context, params, false)
57    }
58
59    pub fn new_nested(
60        context: StatementExecutionContext<'engine, S>,
61        params: &'params [SQLParam],
62    ) -> Self {
63        Self::with_nested_statement(context, params, true)
64    }
65
66    pub fn with_nested_statement(
67        context: StatementExecutionContext<'engine, S>,
68        params: &'params [SQLParam],
69        nested_statement: bool,
70    ) -> Self {
71        Self {
72            context,
73            params,
74            nested_statement,
75            privilege_subject: None,
76            source_sql: None,
77            inherited_ctes: None,
78        }
79    }
80
81    /// Warn that `command`, whose effect lasts until its transaction ends, runs outside a transaction block, as `PostgreSQL`'s `WarnNoTransactionBlock` does. A statement nested in a function or in a multi-statement query has a transaction to last for and is not warned about.
82    fn warn_outside_transaction_block(&self, command: &str) {
83        if !self.nested_statement && !self.context.portals.state.in_transaction_block() {
84            self.context.runtime.notices.push(
85                uqa_sql::semantics::effects::transaction_blocks::no_transaction_block_warning(
86                    command,
87                ),
88            );
89        }
90    }
91
92    pub fn with_privilege_subject(mut self, subject: &RoleReference) -> Self {
93        self.privilege_subject = Some(subject.clone());
94        self
95    }
96
97    pub fn with_inherited_ctes(mut self, parent: Option<&crate::query::CteScope<S>>) -> Self {
98        self.inherited_ctes = parent.cloned();
99        self
100    }
101
102    pub fn with_source_sql(mut self, sql: &str) -> Self {
103        self.source_sql = Some(sql.to_string());
104        self
105    }
106
107    pub fn with_optional_source_sql(mut self, sql: Option<&str>) -> Self {
108        self.source_sql = sql.map(str::to_string);
109        self
110    }
111
112    fn execute_query(&self, query: &QueryPlan) -> Result<SQLResult, SQLError> {
113        if self.context.validation.transactions.transaction_depth() != 0 {
114            crate::query::locking::lock_query_relations(
115                self.context.queries.row_lock_context(),
116                query,
117            )?;
118        }
119        let mut ctes = self
120            .context
121            .queries
122            .statement_scope(self.privilege_subject.as_ref())?;
123        if let Some(parent) = &self.inherited_ctes {
124            ctes.inherit_cte_bindings(parent);
125        }
126        execute_query_plan_with_ctes(
127            &self.context.queries.query_context(),
128            query,
129            self.params,
130            &mut ctes,
131        )
132    }
133
134    pub fn execute_query_to_spill(&self, plan: &UnifiedPlan) -> Result<QueryOutput, SQLError> {
135        self.execute_query_output(plan, QueryOutputMode::SharedSpill)
136    }
137
138    fn execute_query_output(
139        &self,
140        plan: &UnifiedPlan,
141        output: QueryOutputMode<'_, S>,
142    ) -> Result<QueryOutput, SQLError> {
143        super::validation::validate_plan(
144            &self.context.validation,
145            self.context.runtime.cancellation,
146            plan,
147        )?;
148        let UnifiedPlan::Query(query) = plan else {
149            return Err(SQLError::Unsupported(
150                "SQL cursor accepts exactly one query statement".into(),
151            ));
152        };
153        if self.context.validation.transactions.transaction_depth() != 0 {
154            crate::query::locking::lock_query_relations(
155                self.context.queries.row_lock_context(),
156                query,
157            )?;
158        }
159        let mut ctes = self
160            .context
161            .queries
162            .statement_scope(self.privilege_subject.as_ref())?;
163        if let Some(parent) = &self.inherited_ctes {
164            ctes.inherit_cte_bindings(parent);
165        }
166        execute_query_plan_output(
167            &self.context.queries.query_context(),
168            query,
169            self.params,
170            &mut ctes,
171            output,
172        )
173    }
174
175    fn execute_insert(
176        &self,
177        plan: &InsertPlan,
178        destination: Option<crate::mutation::returning::ReturningDestination<'_>>,
179    ) -> Result<crate::mutation::output::MutationOutput, SQLError> {
180        let mut plan = plan.clone();
181        self.apply_statement_privilege_subject(
182            &mut plan.statement_privilege_subject,
183            &mut plan.target_privilege_subject,
184        );
185        crate::mutation::entry::run_insert(
186            &self.context.mutations.mutation_context(),
187            plan,
188            self.params,
189            self.inherited_ctes.as_ref(),
190            destination,
191        )
192    }
193
194    fn execute_update(
195        &self,
196        plan: &UpdatePlan,
197        destination: Option<crate::mutation::returning::ReturningDestination<'_>>,
198    ) -> Result<crate::mutation::output::MutationOutput, SQLError> {
199        let mut plan = plan.clone();
200        self.apply_statement_privilege_subject(
201            &mut plan.statement_privilege_subject,
202            &mut plan.target_privilege_subject,
203        );
204        crate::mutation::entry::run_update(
205            &self.context.mutations.mutation_context(),
206            plan,
207            self.params,
208            self.inherited_ctes.as_ref(),
209            destination,
210        )
211    }
212
213    fn execute_delete(
214        &self,
215        plan: &DeletePlan,
216        destination: Option<crate::mutation::returning::ReturningDestination<'_>>,
217    ) -> Result<crate::mutation::output::MutationOutput, SQLError> {
218        let mut plan = plan.clone();
219        self.apply_statement_privilege_subject(
220            &mut plan.statement_privilege_subject,
221            &mut plan.target_privilege_subject,
222        );
223        crate::mutation::entry::run_delete(
224            &self.context.mutations.mutation_context(),
225            plan,
226            self.params,
227            self.inherited_ctes.as_ref(),
228            destination,
229        )
230    }
231
232    fn apply_statement_privilege_subject(
233        &self,
234        statement_subject: &mut Option<RoleReference>,
235        target_subject: &mut Option<RoleReference>,
236    ) {
237        let Some(subject) = self.privilege_subject.as_ref() else {
238            return;
239        };
240        statement_subject.get_or_insert_with(|| subject.clone());
241        target_subject.get_or_insert_with(|| subject.clone());
242    }
243
244    fn execute_create_view(
245        &self,
246        name: &str,
247        column_names: &[String],
248        query: &QueryPlan,
249        or_replace: bool,
250        persistence: uqa_sql::ast::RelationPersistence,
251        options: &[(String, String)],
252    ) -> Result<SQLResult, SQLError> {
253        view_creation::register_view_plan(
254            self.context.schemas.views,
255            ViewRegistration {
256                name,
257                column_names,
258                plan: query.clone(),
259                or_replace,
260                persistence,
261                options,
262                params: self.params,
263            },
264        )?;
265        Ok(SQLResult::empty())
266    }
267
268    fn execute_show_variable(&self, name: &str) -> Result<SQLResult, SQLError> {
269        super::show::show(self.context.validation.session, name)
270    }
271
272    fn execute_create_foreign_server(
273        &self,
274        statement: &CreateForeignServer,
275    ) -> Result<SQLResult, SQLError> {
276        crate::schema::foreign_creation::entry::register_foreign_server_statement(
277            self.context.foreign,
278            statement.clone(),
279        )?;
280        Ok(SQLResult::empty())
281    }
282
283    fn execute_create_foreign_table(
284        &self,
285        statement: &CreateForeignTable,
286    ) -> Result<SQLResult, SQLError> {
287        crate::schema::foreign_creation::entry::register_foreign_table_statement(
288            self.context.foreign,
289            statement.clone(),
290        )?;
291        Ok(SQLResult::empty())
292    }
293
294    fn execute_merge(
295        &self,
296        plan: &MergePlan,
297        destination: Option<crate::mutation::returning::ReturningDestination<'_>>,
298    ) -> Result<crate::mutation::output::MutationOutput, SQLError> {
299        let mut plan = plan.clone();
300        self.apply_statement_privilege_subject(
301            &mut plan.statement_privilege_subject,
302            &mut plan.target_privilege_subject,
303        );
304        crate::mutation::entry::run_merge(
305            &self.context.mutations.mutation_context(),
306            plan,
307            self.params,
308            None,
309            destination,
310        )
311    }
312
313    fn execute_call(
314        &self,
315        name: &str,
316        arguments: &[ExpressionPlan],
317    ) -> Result<SQLResult, SQLError> {
318        uqa_sql::routines::call::validate_call_arguments(arguments)?;
319        uqa_sql::routines::call::reject_set_call_arguments(
320            self.context.routines.resolution,
321            arguments,
322            self.params,
323        )?;
324        let scope = self.context.queries.statement_scope(None)?;
325        let (call_arguments, explicit_variadic) = analyze_physical_call_arguments(arguments)?;
326        let argument_types = uqa_sql::routines::call::infer_call_argument_types(
327            arguments,
328            &call_arguments,
329            &mut |argument| {
330                crate::query::binding::bind_expression_plan_type(
331                    self.context.routines.resolution,
332                    argument,
333                    self.params,
334                    &scope,
335                )
336            },
337        )?;
338        self.context
339            .queries
340            .with_expression_context(&scope, self.params, &mut |context| {
341                let args = eval_physical_call_arguments(arguments, context)?;
342                crate::routines::invocation::run_call(
343                    &self.context.routines.inputs.invocation_context(),
344                    name,
345                    &args,
346                    &argument_types,
347                    explicit_variadic,
348                    self.nested_statement,
349                )
350            })
351    }
352
353    fn validate_command_target(&self, command: &CommandPlan) -> Result<(), SQLError> {
354        if uqa_sql::semantics::virtual_relation_mutation_candidate(command) {
355            let ctes = self.context.queries.statement_scope(None)?;
356            if let Some(error) = crate::catalog::projection::virtual_relation_mutation_error(
357                &ctes.catalog_read_view()?,
358                &ctes.relation_name_resolution()?,
359                command,
360            )? {
361                // Semantic errors precede the view's rewrite-time mutation rejection.
362                crate::query::binding::analyze_command_parameters(
363                    self.context.routines.resolution,
364                    command,
365                    self.params,
366                    &ctes,
367                )?;
368                return Err(error);
369            }
370        }
371        Ok(())
372    }
373
374    #[expect(
375        clippy::too_many_lines,
376        reason = "preserves SELECT schema and row identity"
377    )]
378    fn execute_command(&self, command: &CommandPlan) -> Result<SQLResult, SQLError> {
379        self.validate_command_target(command)?;
380        match command {
381            CommandPlan::Empty => Ok(SQLResult::empty()),
382            CommandPlan::CreateTable(statement) => {
383                crate::schema::table_creation::entry::run_create_table(
384                    self.context.schemas.creation,
385                    statement.as_ref().clone(),
386                )
387            }
388            CommandPlan::CreateTableIfNotExists(statement) => {
389                crate::schema::table_creation::entry::run_create_table_if_not_exists(
390                    self.context.schemas.creation,
391                    statement.clone(),
392                )
393            }
394            CommandPlan::CreateIndex(statement) => {
395                crate::schema::indexes::creation::run_create_index(
396                    &self.context.schemas.inputs.index_creation_context(),
397                    statement.clone(),
398                )
399            }
400            CommandPlan::RenameIndex(statement) => {
401                crate::schema::table_alteration::entry::run_rename_index(
402                    &self.context.schemas.inputs.table_alter_entry_context(),
403                    statement,
404                )
405            }
406            CommandPlan::Insert(plan) => self.execute_insert(plan, None)?.into_sql_result(),
407            CommandPlan::Update(plan) => self.execute_update(plan, None)?.into_sql_result(),
408            CommandPlan::Delete(plan) => self.execute_delete(plan, None)?.into_sql_result(),
409            CommandPlan::Drop(statement) => crate::schema::removal::entry::run_drop_statement(
410                self.context.schemas.removal,
411                statement.clone(),
412            ),
413            CommandPlan::AlterRoutineOwner(statement) => {
414                crate::routines::privileges::alter_sql_routine_owner(
415                    &self.context.routines.inputs.privilege_context(),
416                    statement,
417                )?;
418                Ok(SQLResult::empty())
419            }
420            CommandPlan::RenameRoutine(statement) => {
421                self.context
422                    .routines
423                    .transactions
424                    .with_rename(Box::new(|context| {
425                        crate::routines::rename::rename_sql_routine(context, statement)
426                    }))?;
427                Ok(SQLResult::empty())
428            }
429            CommandPlan::GrantRoutine(statement) => {
430                crate::routines::privileges::grant_sql_routine(
431                    &self.context.routines.inputs.privilege_context(),
432                    statement,
433                )?;
434                Ok(SQLResult::empty())
435            }
436            CommandPlan::GrantTable(statement) => {
437                crate::catalog::security::table_grants::grant_table_privileges(
438                    self.context.table_privileges,
439                    statement,
440                )?;
441                Ok(SQLResult::empty())
442            }
443            CommandPlan::GrantSequence(statement) => {
444                self.context
445                    .schemas
446                    .inputs
447                    .sequence_privilege_context()
448                    .grant_sequence_privileges(statement)?;
449                Ok(SQLResult::empty())
450            }
451            CommandPlan::GrantDatabase(statement) => {
452                crate::catalog::security::database_lifecycle::grant_database_privileges(
453                    &self.context.schemas.inputs.database_privilege_context(),
454                    statement,
455                )?;
456                Ok(SQLResult::empty())
457            }
458            CommandPlan::GrantSchema(statement) => {
459                crate::schema::namespaces::privileges::grant_schema_privileges(
460                    &self.context.schemas.inputs.schema_privilege_context(),
461                    statement,
462                )?;
463                Ok(SQLResult::empty())
464            }
465            CommandPlan::GrantRole(statement) => {
466                crate::catalog::security::role_lifecycle::grant_roles(
467                    &self.context.roles,
468                    statement,
469                )?;
470                Ok(SQLResult::empty())
471            }
472            CommandPlan::CreateRole(statement) => {
473                crate::catalog::security::role_lifecycle::create_role(
474                    &self.context.roles,
475                    statement,
476                )?;
477                Ok(SQLResult::empty())
478            }
479            CommandPlan::AlterRole(statement) => {
480                crate::catalog::security::role_lifecycle::alter_role(
481                    &self.context.roles,
482                    statement,
483                )?;
484                Ok(SQLResult::empty())
485            }
486            CommandPlan::RenameRole(statement) => {
487                crate::catalog::security::role_lifecycle::rename_role(
488                    &self.context.roles,
489                    statement,
490                )?;
491                Ok(SQLResult::empty())
492            }
493            CommandPlan::DropRole(statement) => {
494                crate::catalog::security::role_lifecycle::drop_roles(
495                    &self.context.roles,
496                    statement,
497                )?;
498                Ok(SQLResult::empty())
499            }
500            CommandPlan::CreateTrigger(statement) => {
501                self.context.events.register_trigger(statement.clone())?;
502                Ok(SQLResult::empty())
503            }
504            CommandPlan::DropTrigger(statement) => {
505                self.context.events.drop_trigger_sql(statement)?;
506                Ok(SQLResult::empty())
507            }
508            CommandPlan::CreateRule(statement) => {
509                self.context.events.register_rule(statement.clone())?;
510                Ok(SQLResult::empty())
511            }
512            CommandPlan::DropRule(statement) => {
513                self.context.events.drop_rule_sql(statement)?;
514                Ok(SQLResult::empty())
515            }
516            CommandPlan::AlterTable(statement) => {
517                crate::schema::table_alteration::entry::run_alter_table(
518                    &self.context.schemas.inputs.table_alter_entry_context(),
519                    (**statement).clone(),
520                )
521            }
522            CommandPlan::AlterForeignTable(statement) => {
523                crate::schema::foreign_table_alteration::alter_foreign_table(
524                    self.context.schemas.foreign_alteration,
525                    statement,
526                )?;
527                Ok(SQLResult::empty())
528            }
529            CommandPlan::AlterView(statement) => {
530                crate::schema::view_alteration::alter_view(
531                    self.context.schemas.view_alteration,
532                    statement,
533                )?;
534                Ok(SQLResult::empty())
535            }
536            CommandPlan::CreateView {
537                name,
538                column_names,
539                query,
540                or_replace,
541                persistence,
542                options,
543            } => self.execute_create_view(
544                name,
545                column_names,
546                query,
547                *or_replace,
548                *persistence,
549                options,
550            ),
551            CommandPlan::CreateMaterializedView {
552                name,
553                column_names,
554                if_not_exists,
555                with_no_data,
556                options,
557                query,
558            } => {
559                let populated_rows = view_creation::register_materialized_view_plan(
560                    self.context.schemas.views,
561                    MaterializedViewRegistration {
562                        name,
563                        column_names,
564                        plan: (**query).clone(),
565                        explained: None,
566                        if_not_exists: *if_not_exists,
567                        with_no_data: *with_no_data,
568                        options,
569                        params: self.params,
570                    },
571                )?;
572                let completion = populated_rows.map_or_else(
573                    || "CREATE MATERIALIZED VIEW".to_string(),
574                    |rows| format!("SELECT {rows}"),
575                );
576                Ok(SQLResult::from_affected(populated_rows.unwrap_or(0))
577                    .with_command_tag(completion))
578            }
579            CommandPlan::RefreshMaterializedView {
580                name,
581                concurrently,
582                with_no_data,
583            } => {
584                view_creation::refresh_materialized_view(
585                    self.context.schemas.views,
586                    name,
587                    *concurrently,
588                    *with_no_data,
589                )?;
590                Ok(SQLResult::empty())
591            }
592            CommandPlan::CreateSchema {
593                name,
594                if_not_exists,
595                authorization,
596            } => crate::schema::namespaces::create_schema(
597                &self.context.schemas.inputs.schema_creation_context(),
598                name.as_deref(),
599                *if_not_exists,
600                authorization.as_ref(),
601            ),
602            CommandPlan::AlterSchemaOwner { name, new_owner } => self
603                .context
604                .schemas
605                .owners
606                .with_owner_write(Box::new(|context| {
607                    crate::schema::namespaces::alter_schema_owner(context, name, new_owner)?;
608                    Ok(SQLResult::empty())
609                })),
610            CommandPlan::RenameSchema { name, new_name } => self
611                .context
612                .schemas
613                .renames
614                .with_rename_write(Box::new(|context| {
615                    crate::schema::namespaces::rename::rename_schema(context, name, new_name)?;
616                    Ok(SQLResult::empty())
617                })),
618            CommandPlan::Notify { channel, payload } => {
619                self.context.notifications.notify(channel, payload)?;
620                Ok(SQLResult::empty())
621            }
622            CommandPlan::Listen { channel } => {
623                super::notifications::require_sql_listener_session(
624                    self.context
625                        .notifications
626                        .notification_subscriptions_required(),
627                )?;
628                self.context.notifications.listen(channel)?;
629                Ok(SQLResult::empty())
630            }
631            CommandPlan::Unlisten { channel } => {
632                super::notifications::require_sql_listener_session(
633                    self.context
634                        .notifications
635                        .notification_subscriptions_required(),
636                )?;
637                self.context.notifications.unlisten(channel.as_deref())?;
638                Ok(SQLResult::empty())
639            }
640            CommandPlan::SetVariable {
641                name,
642                value,
643                local,
644                is_default,
645            } => {
646                if *local {
647                    self.warn_outside_transaction_block("SET LOCAL");
648                }
649                self.context.settings.set_runtime_parameter(
650                    name,
651                    (!is_default).then_some(value.as_str()),
652                    *local,
653                )?;
654                Ok(SQLResult::empty())
655            }
656            CommandPlan::ResetVariable { name } => {
657                self.context
658                    .settings
659                    .set_runtime_parameter(name, None, false)?;
660                Ok(SQLResult::empty())
661            }
662            CommandPlan::ResetAllVariables => {
663                self.context.settings.reset_all_variables();
664                Ok(SQLResult::empty())
665            }
666            CommandPlan::SetConstraints {
667                constraints,
668                deferred,
669            } => {
670                self.context.controls.set_constraints(
671                    constraints,
672                    *deferred,
673                    self.nested_statement,
674                )?;
675                Ok(SQLResult::empty())
676            }
677            CommandPlan::ShowVariable { name } => self.execute_show_variable(name),
678            CommandPlan::Discard { target } => {
679                self.context.settings.discard(*target)?;
680                Ok(SQLResult::empty())
681            }
682            CommandPlan::Load { library } => {
683                self.context.settings.load_library(library)?;
684                Ok(SQLResult::empty())
685            }
686            CommandPlan::Explain {
687                body,
688                options,
689                unbound_parameters,
690            } => self.execute_explain(body, options, unbound_parameters.as_deref()),
691            CommandPlan::Analyze { table } => {
692                let context = self.context.schemas.inputs.vacuum_execution_context();
693                let targets = if let Some(requested) = table.as_deref() {
694                    let Some((canonical, "table")) =
695                        context.catalog.resolve_relation_kind(requested)?
696                    else {
697                        return Err(SQLError::UnknownTable(requested.to_string()));
698                    };
699                    context.privileges.ensure_maintain(&canonical)?;
700                    vec![requested.to_string()]
701                } else {
702                    context.statistics.table_names("analyze")?
703                };
704                for target in targets {
705                    context
706                        .statistics
707                        .analyze_target(&target, &[], true)
708                        .map_err(|error| {
709                            uqa_sql::catalog::errors::storage_error("ANALYZE", &error)
710                        })?;
711                }
712                Ok(SQLResult::empty())
713            }
714            CommandPlan::LockTable(statement) => super::table_locks::execute(
715                self.context.schemas.inputs.table_lock_context(),
716                statement,
717                self.nested_statement,
718            ),
719            CommandPlan::Vacuum(statement) => crate::maintenance::run_vacuum(
720                &self.context.schemas.inputs.vacuum_execution_context(),
721                statement,
722            ),
723            CommandPlan::Truncate {
724                tables,
725                cascade,
726                restart_identity,
727            } => crate::schema::truncate::execute(
728                &self.context.schemas.inputs.truncate_context(),
729                tables,
730                *cascade,
731                *restart_identity,
732            ),
733            CommandPlan::Transaction(statement) => {
734                if let Some(completed) = super::transactions::complete_idle_transaction(
735                    self.context.validation.transactions,
736                    self.context.runtime.notices,
737                    statement,
738                ) {
739                    return Ok(completed);
740                }
741                if matches!(
742                    statement,
743                    uqa_sql::ast::TransactionStmt::SetCharacteristics(_)
744                ) {
745                    self.warn_outside_transaction_block("SET TRANSACTION");
746                }
747                self.context
748                    .controls
749                    .run_transaction_statement(statement.clone())?;
750                Ok(SQLResult::empty())
751            }
752            CommandPlan::DeclareCursor {
753                name,
754                binary,
755                scroll,
756                hold,
757                query,
758            } => super::portal::declaration::declare_session_portal(
759                &self
760                    .context
761                    .portals
762                    .clone()
763                    .with_source_sql(self.source_sql.as_deref()),
764                self.params,
765                name,
766                *binary,
767                *scroll,
768                *hold,
769                query,
770            ),
771            CommandPlan::FetchCursor(fetch) => {
772                self.context.portals.state.fetch_session_portal(fetch)
773            }
774            CommandPlan::CloseCursor { name } => {
775                if let Some(name) = name {
776                    self.context.portals.state.close_session_portal(name)?;
777                } else {
778                    self.context.portals.state.close_all_session_portals();
779                }
780                Ok(SQLResult::empty())
781            }
782            CommandPlan::CreateSequence(statement) => {
783                crate::schema::sequences::entry::run_create_sequence(
784                    self.context.schemas.sequence_creation,
785                    self.context.runtime.notices,
786                    statement,
787                )
788            }
789            CommandPlan::CreateDomain(_)
790            | CommandPlan::AlterDomain(_)
791            | CommandPlan::CreateEnum(_)
792            | CommandPlan::CommentType(_)
793            | CommandPlan::CreateShellType(_)
794            | CommandPlan::CreateCompositeType(_)
795            | CommandPlan::AlterEnum(_)
796            | CommandPlan::AlterTypeObject(_)
797            | CommandPlan::GrantType(_) => self.execute_type_command(command),
798            CommandPlan::AlterSequence(statement) => {
799                crate::schema::sequences::entry::run_alter_sequence(
800                    self.context.schemas.sequence_alteration,
801                    self.context.runtime.notices,
802                    statement,
803                )
804            }
805            CommandPlan::CreateTableAs {
806                name,
807                if_not_exists,
808                column_names,
809                with_no_data,
810                persistence,
811                on_commit,
812                query,
813                ..
814            } => crate::schema::ctas::entry::run_create_table_as(
815                self.context.schemas.tables_as,
816                CreateTableAsExecution {
817                    name,
818                    if_not_exists: *if_not_exists,
819                    column_names,
820                    with_no_data: *with_no_data,
821                    persistence: *persistence,
822                    on_commit: *on_commit,
823                    query,
824                    explained: None,
825                    params: self.params,
826                },
827            ),
828            CommandPlan::Prepare {
829                name,
830                parameter_types,
831                body,
832            } => self.execute_prepare(name, parameter_types, body),
833            CommandPlan::Execute { name, params } => self.execute_prepared(name, params),
834            CommandPlan::Deallocate { name } => self.execute_deallocate(name.as_deref()),
835            CommandPlan::CreateForeignWrapper(statement) => {
836                crate::schema::foreign_creation::entry::register_foreign_wrapper_statement(
837                    self.context.foreign,
838                    statement.clone(),
839                )?;
840                Ok(SQLResult::empty())
841            }
842            CommandPlan::CreateForeignServer(statement) => {
843                self.execute_create_foreign_server(statement)
844            }
845            CommandPlan::CreateForeignTable(statement) => {
846                self.execute_create_foreign_table(statement)
847            }
848            CommandPlan::CreateForeignTableDefinition(statement) => {
849                crate::schema::foreign_creation::entry::register_deferred_foreign_table(
850                    self.context.foreign,
851                    statement.clone(),
852                )
853                .map(|()| SQLResult::empty())
854            }
855            CommandPlan::Merge(plan) => self.execute_merge(plan, None)?.into_sql_result(),
856            CommandPlan::CreateFunction(definition) => {
857                crate::routines::registration::register_sql_function(
858                    &self.context.routines.inputs.registration_context(),
859                    (**definition).clone(),
860                )?;
861                Ok(SQLResult::empty())
862            }
863            CommandPlan::DropFunction(statement) => {
864                self.context
865                    .routines
866                    .transactions
867                    .with_removal(Box::new(|context| {
868                        crate::routines::removal::drop_sql_functions(context, statement)
869                    }))?;
870                Ok(SQLResult::empty())
871            }
872            CommandPlan::AlterRoutine(statement) => {
873                crate::routines::registration::alter_sql_routine(
874                    &self.context.routines.inputs.registration_context(),
875                    statement,
876                )?;
877                Ok(SQLResult::empty())
878            }
879            CommandPlan::DoBlock { language, body } => crate::routines::invocation::run_do_block(
880                &self.context.routines.inputs.anonymous_block_context(),
881                language,
882                body,
883                self.nested_statement,
884            ),
885            CommandPlan::Call { name, args } => self.execute_call(name, args),
886        }
887    }
888}