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