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