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