Skip to main content

mz_adapter/coord/
sequencer.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10// Prevents anyone from accidentally exporting a method from the `inner` module.
11#![allow(clippy::pub_use)]
12
13//! Logic for executing a planned SQL query.
14
15use std::sync::Arc;
16use std::time::Duration;
17
18use futures::future::LocalBoxFuture;
19use futures::stream::FuturesOrdered;
20use inner::return_if_err;
21use mz_compute_types::plan::scalar::LirScalarExpr;
22use mz_expr::row::RowCollection;
23use mz_expr::{MfpPlan, MirRelationExpr, ResultSpec, RowSetFinishing};
24use mz_ore::cast::CastFrom;
25use mz_ore::soft_panic_or_log;
26use mz_persist_client::stats::SnapshotPartStats;
27use mz_repr::{CatalogItemId, Diff, GlobalId, IntoRowIterator, Row, Timestamp};
28use mz_sql::catalog::{CatalogError, SessionCatalog};
29use mz_sql::names::ResolvedIds;
30use mz_sql::plan::{
31    self, AbortTransactionPlan, CommitTransactionPlan, CreateRolePlan, CreateSourcePlanBundle,
32    FetchPlan, MutationKind, Params, Plan, PlanKind, RaisePlan,
33};
34use mz_sql::rbac;
35use mz_sql::session::metadata::SessionMetadata;
36use mz_sql_parser::ast::{Raw, Statement};
37use mz_storage_client::client::TableData;
38use mz_storage_client::storage_collections::StorageCollections;
39use mz_storage_types::connections::inline::IntoInlineConnection;
40use mz_storage_types::stats::RelationPartStats;
41use mz_transform::notice::{OptimizerNoticeApi, OptimizerNoticeKind, RawOptimizerNotice};
42use timely::progress::Antichain;
43use tokio::sync::oneshot;
44use tracing::{Instrument, Level, Span, event, warn};
45
46use crate::ExecuteContext;
47use crate::catalog::Catalog;
48use crate::command::{Command, ExecuteResponse, Response};
49use crate::coord::{Coordinator, Message, TargetCluster, catalog_serving};
50use crate::error::AdapterError;
51use crate::notice::AdapterNotice;
52use crate::session::{
53    EndTransactionAction, Session, StateRevision, TransactionOps, TransactionStatus, WriteOp,
54};
55use crate::util::ClientTransmitter;
56
57// DO NOT make this visible in any way, i.e. do not add any version of
58// `pub` to this mod. The inner `sequence_X` methods are hidden in this
59// private module to prevent anyone from calling them directly. Bound-plan
60// sequencing should be done through the `sequence_plan` method.
61// This allows us to add catch-all logic that should be applied to all
62// plans in `sequence_plan` and guarantee that no caller can circumvent
63// that logic.
64//
65// The exceptions are:
66//
67// - Retained DDL commands enter through command admission and execute in the catalog.
68// - Creating a role during connection startup. In this scenario, the session has not been properly
69// initialized and we need to skip directly to creating role. We have a specific method,
70// `sequence_create_role_for_startup` for this purpose.
71// - Methods that continue the execution of some plan that was being run asynchronously, such as
72// `sequence_staged`.
73// - The frontend sequencing paths call `emit_optimizer_notices` and
74//   `explain_pushdown_future_inner`, which the coordinator uses as well.
75
76mod inner;
77
78impl Coordinator {
79    /// Selects and records the execution cluster, checking its restrictions.
80    pub(super) fn prepare_plan_execution(
81        &self,
82        ctx: &ExecuteContext,
83        plan: &Plan,
84    ) -> Result<(TargetCluster, Option<mz_controller_types::ClusterId>), AdapterError> {
85        let target_cluster = match ctx.session().transaction().cluster() {
86            // Use the current transaction's cluster.
87            Some(cluster_id) => TargetCluster::Transaction(cluster_id),
88            // If there isn't a current cluster set for a transaction, then try to auto route.
89            None => {
90                let session_catalog = self.catalog.for_session(ctx.session());
91                catalog_serving::auto_run_on_catalog_server(&session_catalog, ctx.session(), plan)
92            }
93        };
94        let (target_cluster_id, target_cluster_name) = match self
95            .catalog()
96            .resolve_target_cluster(target_cluster, ctx.session())
97        {
98            Ok(cluster) => (Some(cluster.id), Some(cluster.name.clone())),
99            Err(_) => (None, None),
100        };
101
102        if let (Some(cluster_id), Some(cluster_name), Some(statement_id)) = (
103            target_cluster_id,
104            target_cluster_name.clone(),
105            ctx.extra().contents(),
106        ) {
107            self.set_statement_execution_cluster(statement_id, cluster_id, cluster_name);
108        }
109
110        let session_catalog = self.catalog.for_session(ctx.session());
111
112        if let Some(cluster_name) = &target_cluster_name {
113            if let Err(e) =
114                catalog_serving::check_cluster_restrictions(cluster_name, &session_catalog, plan)
115            {
116                return Err(e);
117            }
118        }
119
120        Ok((target_cluster, target_cluster_id))
121    }
122
123    /// Dispatches a plan in a size-bounded, heap-allocated future.
124    pub(crate) fn sequence_plan(
125        &mut self,
126        mut ctx: ExecuteContext,
127        plan: Plan,
128        resolved_ids: ResolvedIds,
129        sql_impl_resolved_ids: ResolvedIds,
130    ) -> LocalBoxFuture<'_, ()> {
131        let future = async move {
132            let responses = ExecuteResponse::generated_from(&PlanKind::from(&plan));
133            ctx.tx_mut().set_allowed(responses);
134
135            if self.controller.read_only() && !plan.allowed_in_read_only() {
136                ctx.retire(Err(AdapterError::ReadOnly));
137                return;
138            }
139
140            let (target_cluster, target_cluster_id) =
141                return_if_err!(self.prepare_plan_execution(&ctx, &plan), ctx);
142            let session_catalog = self.catalog.for_session(ctx.session());
143
144            // The target-connection role only matters for `pg_cancel_backend`,
145            // which the frontend sequences.
146            if let Err(e) = rbac::check_plan(
147                &session_catalog,
148                None,
149                ctx.session(),
150                &plan,
151                target_cluster_id,
152                &resolved_ids,
153                &sql_impl_resolved_ids,
154            ) {
155                return ctx.retire(Err(e.into()));
156            }
157
158            match plan {
159                Plan::CreateSource(plan) => {
160                    if !matches!(
161                        plan.source.data_source,
162                        plan::DataSourceDesc::Webhook { .. }
163                    ) {
164                        let msg = "CREATE SOURCE must execute as a catalog command";
165                        soft_panic_or_log!("{msg}");
166                        ctx.retire(Err(AdapterError::Internal(msg.into())));
167                        return;
168                    }
169                    let (item_id, global_id) = return_if_err!(self.allocate_user_id().await, ctx);
170                    let result = self
171                        .sequence_create_source(
172                            &mut ctx,
173                            vec![CreateSourcePlanBundle {
174                                item_id,
175                                global_id,
176                                plan,
177                                resolved_ids,
178                                available_source_references: None,
179                            }],
180                        )
181                        .await;
182                    ctx.retire(result);
183                }
184                Plan::CreateSources(_) => {
185                    let msg = "CREATE SOURCE must execute as a catalog command";
186                    soft_panic_or_log!("{msg}");
187                    ctx.retire(Err(AdapterError::Internal(msg.into())));
188                }
189                Plan::CreateConnection(_) => {
190                    let msg = "CREATE CONNECTION must execute as a catalog command";
191                    soft_panic_or_log!("{msg}");
192                    ctx.retire(Err(AdapterError::Internal(msg.into())));
193                }
194                Plan::CreateDatabase(plan) => {
195                    let result = self.sequence_create_database(ctx.session_mut(), plan).await;
196                    ctx.retire(result);
197                }
198                Plan::CreateSchema(plan) => {
199                    let result = self.sequence_create_schema(ctx.session_mut(), plan).await;
200                    ctx.retire(result);
201                }
202                Plan::CreateRole(plan) => {
203                    let result = self
204                        .sequence_create_role(Some(ctx.session().conn_id()), plan)
205                        .await;
206                    if let Some(notice) = self.should_emit_rbac_notice(ctx.session()) {
207                        ctx.session().add_notice(notice);
208                    }
209                    ctx.retire(result);
210                }
211                Plan::CreateCluster(plan) => {
212                    let result = self.sequence_create_cluster(ctx.session(), plan).await;
213                    ctx.retire(result);
214                }
215                Plan::CreateClusterReplica(plan) => {
216                    let result = self
217                        .sequence_create_cluster_replica(ctx.session(), plan)
218                        .await;
219                    ctx.retire(result);
220                }
221                Plan::CreateTable(plan) => {
222                    if matches!(
223                        plan.table.data_source,
224                        plan::TableDataSource::DataSource {
225                            desc: plan::DataSourceDesc::IngestionExport { .. },
226                            ..
227                        }
228                    ) {
229                        let msg = "CREATE TABLE FROM SOURCE must execute as a catalog command";
230                        soft_panic_or_log!("{msg}");
231                        ctx.retire(Err(AdapterError::Internal(msg.into())));
232                        return;
233                    }
234                    let result = self
235                        .sequence_create_table(&mut ctx, plan, resolved_ids)
236                        .await;
237                    ctx.retire(result);
238                }
239                Plan::CreateSecret(plan) => {
240                    self.sequence_create_secret(ctx, plan).await;
241                }
242                Plan::CreateSink(plan) => {
243                    self.sequence_create_sink(ctx, plan, resolved_ids).await;
244                }
245                Plan::CreateView(plan) => {
246                    self.sequence_create_view(ctx, plan, resolved_ids).await;
247                }
248                Plan::CreateMaterializedView(plan) => {
249                    self.sequence_create_materialized_view(ctx, plan, resolved_ids)
250                        .await;
251                }
252                Plan::CreateIndex(plan) => {
253                    self.sequence_create_index(ctx, plan, resolved_ids).await;
254                }
255                Plan::CreateMetricSink(plan) => {
256                    self.sequence_create_metric_sink(ctx, plan, resolved_ids)
257                        .await;
258                }
259                Plan::CreateType(plan) => {
260                    let result = self
261                        .sequence_create_type(ctx.session(), plan, resolved_ids)
262                        .await;
263                    ctx.retire(result);
264                }
265                Plan::CreateNetworkPolicy(plan) => {
266                    let res = self
267                        .sequence_create_network_policy(ctx.session(), plan)
268                        .await;
269                    ctx.retire(res);
270                }
271                Plan::CreateQueryPolicy(plan) => {
272                    let res = self.sequence_create_query_policy(ctx.session(), plan).await;
273                    ctx.retire(res);
274                }
275                Plan::Comment(plan) => {
276                    let result = self.sequence_comment_on(ctx.session(), plan).await;
277                    ctx.retire(result);
278                }
279                Plan::DropObjects(plan) => {
280                    let result = self.sequence_drop_objects(&mut ctx, plan).await;
281                    ctx.retire(result);
282                }
283                Plan::DropOwned(plan) => {
284                    let result = self.sequence_drop_owned(ctx.session_mut(), plan).await;
285                    ctx.retire(result);
286                }
287                Plan::EmptyQuery => {
288                    ctx.retire(Ok(ExecuteResponse::EmptyQuery));
289                }
290                Plan::ShowAllVariables => {
291                    let result = self.sequence_show_all_variables(ctx.session());
292                    ctx.retire(result);
293                }
294                Plan::ShowVariable(plan) => {
295                    let result = self.sequence_show_variable(ctx.session(), plan);
296                    ctx.retire(result);
297                }
298                Plan::InspectShard(plan) => {
299                    // TODO: Ideally, this await would happen off the main thread.
300                    let result = self.sequence_inspect_shard(ctx.session(), plan).await;
301                    ctx.retire(result);
302                }
303                Plan::SetVariable(plan) => {
304                    let result = self.sequence_set_variable(ctx.session_mut(), plan);
305                    ctx.retire(result);
306                }
307                Plan::ResetVariable(plan) => {
308                    let result = self.sequence_reset_variable(ctx.session_mut(), plan);
309                    ctx.retire(result);
310                }
311                Plan::SetTransaction(plan) => {
312                    let result = self.sequence_set_transaction(ctx.session_mut(), plan);
313                    ctx.retire(result);
314                }
315                Plan::StartTransaction(plan) => {
316                    if matches!(
317                        ctx.session().transaction(),
318                        TransactionStatus::InTransaction(_)
319                    ) {
320                        ctx.session()
321                            .add_notice(AdapterNotice::ExistingTransactionInProgress);
322                    }
323                    let result = ctx.session_mut().start_transaction(
324                        self.now_datetime(),
325                        plan.access,
326                        plan.isolation_level,
327                    );
328                    ctx.retire(result.map(|_| ExecuteResponse::StartedTransaction))
329                }
330                Plan::CommitTransaction(CommitTransactionPlan {
331                    ref transaction_type,
332                })
333                | Plan::AbortTransaction(AbortTransactionPlan {
334                    ref transaction_type,
335                }) => {
336                    let action = match &plan {
337                        Plan::CommitTransaction(_) => EndTransactionAction::Commit,
338                        Plan::AbortTransaction(_) => EndTransactionAction::Rollback,
339                        _ => unreachable!(),
340                    };
341                    if ctx.session().transaction().is_implicit() && !transaction_type.is_implicit()
342                    {
343                        // In Postgres, if a user sends a COMMIT or ROLLBACK in an
344                        // implicit transaction, a warning is sent warning them.
345                        // (The transaction is still closed and a new implicit
346                        // transaction started, though.)
347                        ctx.session().add_notice(
348                            AdapterNotice::ExplicitTransactionControlInImplicitTransaction,
349                        );
350                    }
351                    self.sequence_end_transaction(ctx, action).await;
352                }
353                Plan::ShowCreate(plan) => {
354                    ctx.retire(Ok(Self::send_immediate_rows(plan.row)));
355                }
356                Plan::CopyFrom(plan) => {
357                    self.sequence_copy_from(ctx, plan, target_cluster).await;
358                }
359                Plan::ExplainPlan(plan) => {
360                    self.sequence_explain_plan(ctx, plan).await;
361                }
362                Plan::ExplainPushdown(plan) => {
363                    self.sequence_explain_pushdown(ctx, plan).await;
364                }
365                Plan::ExplainSinkSchema(plan) => {
366                    let result = self.sequence_explain_schema(plan);
367                    ctx.retire(result);
368                }
369                // `SessionClient::execute_attempts` unrolls SQL `EXECUTE`, and `try_peek` and
370                // `try_read_then_write` take over every statement that plans to one of the
371                // others.
372                // TODO(SQL-760): Drop the manual soft panic once internal errors soft-panic
373                // centrally.
374                plan @ (Plan::CopyTo(_)
375                | Plan::Execute(_)
376                | Plan::ExplainTimestamp(_)
377                | Plan::Insert(_)
378                | Plan::ReadThenWrite(_)
379                | Plan::Select(_)
380                | Plan::ShowColumns(_)
381                | Plan::SideEffectingFunc(_)
382                | Plan::Subscribe(_)) => {
383                    let msg = format!(
384                        "{:?} plan reached the coordinator despite frontend routing",
385                        PlanKind::from(&plan)
386                    );
387                    soft_panic_or_log!("{msg}");
388                    ctx.retire(Err(AdapterError::Internal(msg)));
389                }
390                Plan::AlterNoop(plan) => {
391                    ctx.retire(Ok(ExecuteResponse::AlteredObject(plan.object_type)));
392                }
393                Plan::AlterCluster(plan) => {
394                    self.sequence_alter_cluster_staged(ctx, plan).await;
395                }
396                Plan::AlterClusterRename(_)
397                | Plan::AlterClusterSwap(_)
398                | Plan::AlterClusterReplicaRename(_)
399                | Plan::AlterItemRename(_)
400                | Plan::AlterSchemaRename(_)
401                | Plan::AlterSchemaSwap(_) => {
402                    let msg = "rename/swap must execute as a catalog command";
403                    soft_panic_or_log!("{msg}");
404                    ctx.retire(Err(AdapterError::Internal(msg.into())));
405                }
406                Plan::AlterConnection(plan) => {
407                    self.sequence_alter_connection(ctx, plan).await;
408                }
409                Plan::AlterSetCluster(plan) => {
410                    let result = self.sequence_alter_set_cluster(ctx.session(), plan).await;
411                    ctx.retire(result);
412                }
413                Plan::AlterRetainHistory(plan) => {
414                    let result = self.sequence_alter_retain_history(&mut ctx, plan).await;
415                    ctx.retire(result);
416                }
417                Plan::AlterSourceTimestampInterval(plan) => {
418                    let result = self
419                        .sequence_alter_source_timestamp_interval(&mut ctx, plan)
420                        .await;
421                    ctx.retire(result);
422                }
423                Plan::AlterRole(plan) => {
424                    let result = self.sequence_alter_role(ctx.session_mut(), plan).await;
425                    ctx.retire(result);
426                }
427                Plan::AlterSecret(plan) => {
428                    self.sequence_alter_secret(ctx, plan).await;
429                }
430                Plan::AlterSink(plan) => {
431                    self.sequence_alter_sink_prepare(ctx, plan).await;
432                }
433                Plan::AlterSource(_) => {
434                    let msg = "ALTER SOURCE must execute as a catalog command";
435                    soft_panic_or_log!("{msg}");
436                    ctx.retire(Err(AdapterError::Internal(msg.into())));
437                }
438                Plan::AlterSystemSet(plan) => {
439                    let result = self.sequence_alter_system_set(ctx.session(), plan).await;
440                    ctx.retire(result);
441                }
442                Plan::AlterSystemReset(plan) => {
443                    let result = self.sequence_alter_system_reset(ctx.session(), plan).await;
444                    ctx.retire(result);
445                }
446                Plan::AlterSystemResetAll(plan) => {
447                    let result = self
448                        .sequence_alter_system_reset_all(ctx.session(), plan)
449                        .await;
450                    ctx.retire(result);
451                }
452                Plan::AlterTableAddColumn(plan) => {
453                    let result = self.sequence_alter_table(&mut ctx, plan).await;
454                    ctx.retire(result);
455                }
456                Plan::AlterMaterializedViewApplyReplacement(plan) => {
457                    self.sequence_alter_materialized_view_apply_replacement_prepare(ctx, plan)
458                        .await;
459                }
460                Plan::AlterNetworkPolicy(plan) => {
461                    let res = self
462                        .sequence_alter_network_policy(ctx.session(), plan)
463                        .await;
464                    ctx.retire(res);
465                }
466                Plan::AlterQueryPolicy(plan) => {
467                    let res = self.sequence_alter_query_policy(ctx.session(), plan).await;
468                    ctx.retire(res);
469                }
470                Plan::DiscardTemp => {
471                    self.drop_temp_items(ctx.session().conn_id()).await;
472                    ctx.retire(Ok(ExecuteResponse::DiscardedTemp));
473                }
474                Plan::DiscardAll => {
475                    // Clearing the transaction would silently discard writes staged by an
476                    // earlier statement of the same pipeline.
477                    let txn = ctx.session().transaction();
478                    let discardable =
479                        matches!(txn, TransactionStatus::Started(_)) && !txn.contains_ops();
480                    let ret = if discardable {
481                        let (_, retire_notify) = self.clear_transaction(ctx.session_mut()).await;
482                        ctx.delay_response_until(retire_notify);
483                        self.drop_temp_items(ctx.session().conn_id()).await;
484                        // NOTE: `reset()` resets session variables durably (see
485                        // `SessionVars::reset_all`). This must stay durable and
486                        // must not be reordered to depend on a transaction
487                        // commit: the transaction was just cleared above, so
488                        // there is no commit left to promote a staged reset.
489                        let params = ctx.session_mut().reset();
490                        Ok(ExecuteResponse::DiscardedAll { params })
491                    } else {
492                        Err(AdapterError::OperationProhibitsTransaction(
493                            "DISCARD ALL".into(),
494                        ))
495                    };
496                    ctx.retire(ret);
497                }
498                Plan::Declare(plan) => {
499                    self.declare(ctx, plan.name, plan.stmt, plan.sql, plan.params);
500                }
501                Plan::Fetch(FetchPlan {
502                    name,
503                    count,
504                    timeout,
505                }) => {
506                    let ctx_extra = std::mem::take(ctx.extra_mut());
507                    ctx.retire(Ok(ExecuteResponse::Fetch {
508                        name,
509                        count,
510                        timeout,
511                        ctx_extra,
512                    }));
513                }
514                Plan::Close(plan) => {
515                    if ctx.session_mut().remove_portal(&plan.name) {
516                        ctx.retire(Ok(ExecuteResponse::ClosedCursor));
517                    } else {
518                        ctx.retire(Err(AdapterError::UnknownCursor(plan.name)));
519                    }
520                }
521                Plan::Prepare(plan) => {
522                    if ctx
523                        .session()
524                        .get_prepared_statement_unverified(&plan.name)
525                        .is_some()
526                    {
527                        ctx.retire(Err(AdapterError::PreparedStatementExists(plan.name)));
528                    } else {
529                        let state_revision = StateRevision {
530                            catalog_revision: self.catalog().transient_revision(),
531                            session_state_revision: ctx.session().state_revision(),
532                        };
533                        ctx.session_mut().retain_description(
534                            plan.stmt.clone(),
535                            plan.desc.param_types.iter().cloned().map(Some).collect(),
536                            plan.desc.clone(),
537                        );
538                        ctx.session_mut().set_prepared_statement(
539                            plan.name,
540                            Some(plan.stmt),
541                            plan.sql,
542                            plan.desc,
543                            state_revision,
544                            self.now(),
545                        );
546                        ctx.retire(Ok(ExecuteResponse::Prepare));
547                    }
548                }
549                Plan::Deallocate(plan) => match plan.name {
550                    Some(name) => {
551                        if ctx.session_mut().remove_prepared_statement(&name) {
552                            ctx.retire(Ok(ExecuteResponse::Deallocate { all: false }));
553                        } else {
554                            ctx.retire(Err(AdapterError::UnknownPreparedStatement(name)));
555                        }
556                    }
557                    None => {
558                        ctx.session_mut().remove_all_prepared_statements();
559                        ctx.retire(Ok(ExecuteResponse::Deallocate { all: true }));
560                    }
561                },
562                Plan::Raise(RaisePlan { severity }) => {
563                    ctx.session()
564                        .add_notice(AdapterNotice::UserRequested { severity });
565                    ctx.retire(Ok(ExecuteResponse::Raised));
566                }
567                Plan::GrantPrivileges(plan) => {
568                    let result = self
569                        .sequence_grant_privileges(ctx.session_mut(), plan)
570                        .await;
571                    ctx.retire(result);
572                }
573                Plan::RevokePrivileges(plan) => {
574                    let result = self
575                        .sequence_revoke_privileges(ctx.session_mut(), plan)
576                        .await;
577                    ctx.retire(result);
578                }
579                Plan::AlterDefaultPrivileges(plan) => {
580                    let result = self
581                        .sequence_alter_default_privileges(ctx.session_mut(), plan)
582                        .await;
583                    ctx.retire(result);
584                }
585                Plan::GrantRole(plan) => {
586                    let result = self.sequence_grant_role(ctx.session_mut(), plan).await;
587                    ctx.retire(result);
588                }
589                Plan::RevokeRole(plan) => {
590                    let result = self.sequence_revoke_role(ctx.session_mut(), plan).await;
591                    ctx.retire(result);
592                }
593                Plan::AlterOwner(plan) => {
594                    let result = self.sequence_alter_owner(ctx.session_mut(), plan).await;
595                    ctx.retire(result);
596                }
597                Plan::ReassignOwned(plan) => {
598                    let result = self.sequence_reassign_owned(ctx.session_mut(), plan).await;
599                    ctx.retire(result);
600                }
601                Plan::ValidateConnection(plan) => {
602                    let connection = plan
603                        .connection
604                        .into_inline_connection(self.catalog().state());
605                    let current_storage_configuration = self.controller.storage.config().clone();
606                    mz_ore::task::spawn(|| "coord::validate_connection", async move {
607                        let res = match connection
608                            .validate(plan.id, &current_storage_configuration)
609                            .await
610                        {
611                            Ok(()) => Ok(ExecuteResponse::ValidatedConnection),
612                            Err(err) => Err(err.into()),
613                        };
614                        ctx.retire(res);
615                    });
616                }
617            }
618        }
619        .instrument(tracing::debug_span!("coord::sequencer::sequence_plan"));
620        crate::coord::box_dispatcher(future)
621    }
622
623    #[mz_ore::instrument(level = "debug")]
624    pub(crate) async fn sequence_execute_single_statement_transaction(
625        &mut self,
626        ctx: ExecuteContext,
627        stmt: Arc<Statement<Raw>>,
628        params: Params,
629    ) {
630        // Put the session into single statement implicit so anything can execute.
631        let (tx, internal_cmd_tx, mut session, extra, response_barriers) = ctx.into_parts();
632        assert!(matches!(session.transaction(), TransactionStatus::Default));
633        session.start_transaction_single_stmt(self.now_datetime());
634        let conn_id = session.conn_id().unhandled();
635
636        // Execute the saved statement in a temp transmitter so we can run COMMIT.
637        let (sub_tx, sub_rx) = oneshot::channel();
638        let sub_ct = ClientTransmitter::new(sub_tx, self.internal_cmd_tx.clone());
639        let sub_ctx = ExecuteContext::from_parts_with_response_barriers(
640            sub_ct,
641            internal_cmd_tx,
642            session,
643            extra,
644            response_barriers,
645        );
646        self.handle_execute_inner(stmt, params, sub_ctx).await;
647
648        // The response can need off-thread processing. Wait for it elsewhere so the coordinator can
649        // continue processing.
650        let internal_cmd_tx = self.internal_cmd_tx.clone();
651        mz_ore::task::spawn(
652            || format!("execute_single_statement:{conn_id}"),
653            async move {
654                let Ok(Response {
655                    result,
656                    session,
657                    otel_ctx,
658                }) = sub_rx.await
659                else {
660                    // Coordinator went away.
661                    return;
662                };
663                otel_ctx.attach_as_parent();
664                let (sub_tx, sub_rx) = oneshot::channel();
665                let _ = internal_cmd_tx.send(Message::Command(
666                    otel_ctx,
667                    Command::Commit {
668                        action: EndTransactionAction::Commit,
669                        session,
670                        tx: sub_tx,
671                    },
672                ));
673                let Ok(commit_response) = sub_rx.await else {
674                    // Coordinator went away.
675                    return;
676                };
677                assert!(matches!(
678                    commit_response.session.transaction(),
679                    TransactionStatus::Default
680                ));
681                // The fake, generated response was already sent to the user and we don't need to
682                // ever send an `Ok(result)` to the user, because they are expecting a response from
683                // a `COMMIT`. So, always send the `COMMIT`'s result if the original statement
684                // succeeded. If it failed, we can send an error and don't need to wrap it or send a
685                // later COMMIT or ROLLBACK.
686                let result = match (result, commit_response.result) {
687                    (Ok(_), commit) => commit,
688                    (Err(result), _) => Err(result),
689                };
690                // We ignore the resp.result because it's not clear what to do if it failed since we
691                // can only send a single ExecuteResponse to tx.
692                tx.send(result, commit_response.session);
693            }
694            .instrument(Span::current()),
695        );
696    }
697
698    /// Creates a role during connection startup.
699    ///
700    /// This should not be called from anywhere except connection startup.
701    #[mz_ore::instrument(level = "debug")]
702    pub(crate) async fn sequence_create_role_for_startup(
703        &mut self,
704        plan: CreateRolePlan,
705    ) -> Result<ExecuteResponse, AdapterError> {
706        // This does not set conn_id because it's not yet in active_conns. That is because we can't
707        // make a ConnMeta until we have a role id which we don't have until after the catalog txn
708        // is committed. Passing None here means the audit log won't have a user set in the event's
709        // user field. This seems fine because it is indeed the system that is creating this role,
710        // not a user request, and the user name is still recorded in the plan, so we aren't losing
711        // information.
712        self.sequence_create_role(None, plan).await
713    }
714
715    pub(crate) fn allocate_transient_id(&self) -> (CatalogItemId, GlobalId) {
716        self.transient_id_gen.allocate_id()
717    }
718
719    fn should_emit_rbac_notice(&self, session: &Session) -> Option<AdapterNotice> {
720        if !rbac::is_rbac_enabled_for_session(self.catalog.system_config(), session) {
721            Some(AdapterNotice::RbacUserDisabled)
722        } else {
723            None
724        }
725    }
726
727    /// Inserts the rows from `constants` into the table identified by `target_id`.
728    ///
729    /// # Panics
730    ///
731    /// Panics if `target_id` doesn't refer to a table.
732    /// Panics if `constants` is not an `MirRelationExpr::Constant`.
733    pub(crate) fn insert_constant(
734        catalog: &Catalog,
735        session: &mut Session,
736        target_id: CatalogItemId,
737        constants: MirRelationExpr,
738    ) -> Result<ExecuteResponse, AdapterError> {
739        // Insert can be queued, so we need to re-verify the id exists.
740        let desc = match catalog.try_get_entry(&target_id) {
741            Some(table) => {
742                // Inserts always happen at the latest version of a table.
743                table.relation_desc_latest().expect("table has desc")
744            }
745            None => {
746                return Err(AdapterError::Catalog(mz_catalog::memory::error::Error {
747                    kind: mz_catalog::memory::error::ErrorKind::Sql(CatalogError::UnknownItem(
748                        target_id.to_string(),
749                    )),
750                }));
751            }
752        };
753
754        match constants.as_const() {
755            Some((rows, ..)) => {
756                let rows = rows.clone()?;
757                for (row, _) in &rows {
758                    for (i, datum) in row.iter().enumerate() {
759                        desc.constraints_met(i, &datum)?;
760                    }
761                }
762                let diffs_plan = plan::SendDiffsPlan {
763                    id: target_id,
764                    updates: rows,
765                    kind: MutationKind::Insert,
766                    returning: Vec::new(),
767                    max_result_size: catalog.system_config().max_result_size(),
768                };
769                let result = Self::send_diffs(session, diffs_plan);
770                // Let schema-fencing tests land an ALTER after packing rows
771                // against this descriptor but before the transaction commits.
772                fail::fail_point!("insert_after_pack_before_commit");
773                result
774            }
775            None => panic!(
776                "tried using sequence_insert_constant on non-constant MirRelationExpr\n{}",
777                constants.pretty(),
778            ),
779        }
780    }
781
782    #[mz_ore::instrument(level = "debug")]
783    pub(crate) fn send_diffs(
784        session: &mut Session,
785        mut plan: plan::SendDiffsPlan,
786    ) -> Result<ExecuteResponse, AdapterError> {
787        let affected_rows = {
788            let mut affected_rows = Diff::from(0);
789            let mut all_positive_diffs = true;
790            // If all diffs are positive, the number of affected rows is just the
791            // sum of all unconsolidated diffs.
792            for (_, diff) in plan.updates.iter() {
793                if diff.is_negative() {
794                    all_positive_diffs = false;
795                    break;
796                }
797
798                affected_rows += diff;
799            }
800
801            if !all_positive_diffs {
802                // Consolidate rows. This is useful e.g. for an UPDATE where the row
803                // doesn't change, and we need to reflect that in the number of
804                // affected rows.
805                //
806                // NOTE: This differs from PostgreSQL, where `UPDATE t SET x = x`
807                // reports the number of rows matching the WHERE clause even when
808                // no value changes. Because Materialize works in differential
809                // dataflow, the +1 and -1 diffs for an unchanged row cancel out
810                // during consolidation, so it reports 0 affected rows. This is
811                // longstanding behavior and both read-then-write paths agree on
812                // it.
813                differential_dataflow::consolidation::consolidate(&mut plan.updates);
814
815                affected_rows = Diff::ZERO;
816                // With retractions, the number of affected rows is not the number
817                // of rows we see, but the sum of the absolute value of their diffs,
818                // e.g. if one row is retracted and another is added, the total
819                // number of rows affected is 2.
820                for (_, diff) in plan.updates.iter() {
821                    affected_rows += diff.abs();
822                }
823            }
824
825            usize::try_from(affected_rows.into_inner()).expect("positive Diff must fit")
826        };
827        event!(
828            Level::TRACE,
829            affected_rows,
830            id = format!("{:?}", plan.id),
831            kind = format!("{:?}", plan.kind),
832            updates = plan.updates.len(),
833            returning = plan.returning.len(),
834        );
835
836        session.add_transaction_ops(TransactionOps::Writes(vec![WriteOp {
837            id: plan.id,
838            rows: TableData::Rows(plan.updates),
839        }]))?;
840        if !plan.returning.is_empty() {
841            let finishing = RowSetFinishing {
842                order_by: Vec::new(),
843                limit: None,
844                offset: 0,
845                project: (0..plan.returning[0].0.iter().count()).collect(),
846            };
847            let max_returned_query_size = session.vars().max_query_result_size();
848            let duration_histogram = session.metrics().row_set_finishing_seconds();
849
850            return match finishing.finish(
851                RowCollection::new(plan.returning, &finishing.order_by),
852                plan.max_result_size,
853                Some(max_returned_query_size),
854                duration_histogram,
855            ) {
856                Ok((rows, _size_bytes)) => Ok(Self::send_immediate_rows(rows)),
857                Err(e) => Err(AdapterError::ResultSize(e)),
858            };
859        }
860        Ok(match plan.kind {
861            MutationKind::Delete => ExecuteResponse::Deleted(affected_rows),
862            MutationKind::Insert => ExecuteResponse::Inserted(affected_rows),
863            MutationKind::Update => ExecuteResponse::Updated(affected_rows / 2),
864        })
865    }
866}
867
868/// Forward notices that we got from the optimizer.
869pub(crate) fn emit_optimizer_notices(
870    catalog: &Catalog,
871    session: &Session,
872    notices: &[RawOptimizerNotice],
873) {
874    // `for_session` below is expensive, so return early if there's nothing to do.
875    if notices.is_empty() {
876        return;
877    }
878    let humanizer = catalog.for_session(session);
879    let system_vars = catalog.system_config();
880    for notice in notices {
881        let kind = OptimizerNoticeKind::from(notice);
882        let notice_enabled = match kind {
883            OptimizerNoticeKind::EqualsNull => system_vars.enable_notices_for_equals_null(),
884            OptimizerNoticeKind::IndexAlreadyExists => {
885                system_vars.enable_notices_for_index_already_exists()
886            }
887            OptimizerNoticeKind::IndexTooWideForLiteralConstraints => {
888                system_vars.enable_notices_for_index_too_wide_for_literal_constraints()
889            }
890            OptimizerNoticeKind::IndexKeyEmpty => system_vars.enable_notices_for_index_empty_key(),
891        };
892        if notice_enabled {
893            // We don't need to redact the notice parts because
894            // `emit_optimizer_notices` is only called by the `sequence_~`
895            // method for the statement that produces that notice.
896            session.add_notice(AdapterNotice::OptimizerNotice {
897                notice: notice.message(&humanizer, false).to_string(),
898                hint: notice.hint(&humanizer, false).to_string(),
899            });
900        }
901        session
902            .metrics()
903            .optimization_notices(&[kind.metric_label()])
904            .inc_by(1);
905    }
906}
907
908/// Returns a future that will execute EXPLAIN FILTER PUSHDOWN, i.e., compute the filter pushdown
909/// statistics for the given collections with the given MFPs.
910///
911/// The coordinator calls this for materialized views and the frontend peek sequencing for
912/// SELECTs, so it takes only what it needs instead of the `Coordinator`.
913pub(crate) async fn explain_pushdown_future_inner<
914    I: IntoIterator<Item = (GlobalId, MfpPlan<LirScalarExpr>)>,
915>(
916    session: &Session,
917    catalog: &Catalog,
918    storage_collections: &Arc<dyn StorageCollections + Send + Sync>,
919    as_of: Antichain<Timestamp>,
920    mz_now: ResultSpec<'static>,
921    imports: I,
922) -> impl Future<Output = Result<ExecuteResponse, AdapterError>> + use<I> {
923    let mut explain_timeout = *session.vars().statement_timeout();
924    // Timeout of 0 is equivalent to "off", meaning we will wait "forever."
925    if explain_timeout == Duration::ZERO {
926        explain_timeout = Duration::MAX;
927    }
928    let mut futures = FuturesOrdered::new();
929    for (id, plan) in imports {
930        let catalog_entry = catalog.get_entry_by_global_id(&id);
931        let full_name = catalog
932            .for_session(session)
933            .resolve_full_name(&catalog_entry.name);
934        let name = format!("{}", full_name);
935        let relation_desc = catalog_entry
936            .relation_desc()
937            .expect("source should have a proper desc")
938            .into_owned();
939        let stats_future = storage_collections
940            .snapshot_parts_stats(id, as_of.clone())
941            .await;
942
943        let mz_now = mz_now.clone();
944        // These futures may block if the source is not yet readable at the as-of;
945        // stash them in `futures` and only block on them in a separate task.
946        // TODO(peek-seq): This complication won't be needed once only the frontend calls this
947        // function, in which case it will be fine to block the current task.
948        futures.push_back(async move {
949            let snapshot_stats = match stats_future.await {
950                Ok(stats) => stats,
951                Err(e) => return Err(e),
952            };
953            let mut total_bytes = 0;
954            let mut total_parts = 0;
955            let mut selected_bytes = 0;
956            let mut selected_parts = 0;
957            for SnapshotPartStats {
958                encoded_size_bytes: bytes,
959                stats,
960            } in &snapshot_stats.parts
961            {
962                let bytes = u64::cast_from(*bytes);
963                total_bytes += bytes;
964                total_parts += 1u64;
965                let selected = match stats.as_ref().and_then(|x| x.try_decode().ok()) {
966                    // Also the arm for stats that do not decode, which a
967                    // newer writer's stats kind can produce. Both report the
968                    // part as selected, matching what a read of it would do.
969                    None => true,
970                    Some(stats) => {
971                        let stats = RelationPartStats::new(
972                            name.as_str(),
973                            &snapshot_stats.metrics.pushdown.part_stats,
974                            &relation_desc,
975                            &stats,
976                        );
977                        stats.may_match_mfp_plan(mz_now.clone(), &plan)
978                    }
979                };
980
981                if selected {
982                    selected_bytes += bytes;
983                    selected_parts += 1u64;
984                }
985            }
986            Ok(Row::pack_slice(&[
987                name.as_str().into(),
988                total_bytes.into(),
989                selected_bytes.into(),
990                total_parts.into(),
991                selected_parts.into(),
992            ]))
993        });
994    }
995
996    let fut = async move {
997        match tokio::time::timeout(
998            explain_timeout,
999            futures::TryStreamExt::try_collect::<Vec<_>>(futures),
1000        )
1001        .await
1002        {
1003            Ok(Ok(rows)) => Ok(ExecuteResponse::SendingRowsImmediate {
1004                rows: Box::new(rows.into_row_iter()),
1005            }),
1006            Ok(Err(err)) => Err(err.into()),
1007            Err(_) => Err(AdapterError::StatementTimeout),
1008        }
1009    };
1010    fut
1011}