Skip to main content

mz_adapter/catalog/
command.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//! Catalog commands that can be rechecked when committing a DDL transaction.
11//!
12//! Statements run against the transaction's working catalog, but the catalog
13//! can change before commit. Commands retain the original request and any
14//! output we might have sent to the client (aka. the "promise"), so commit can
15//! "assert" on that output when re-checking catalog commands against the
16//! current catalog.
17//!
18//! Pending external work abandons the candidate. A continuation rebuilds the
19//! prefix before consuming its indexed response, so successful preparation and
20//! preparation errors are accepted only when their inputs still match.
21//!
22//! External mutations are not catalog operations. CREATE CONNECTION retains its allocated
23//! ID, generated keys, and successful secret-write completion across retries. ROTATE KEYS
24//! uses a pinned publication command instead of retrying its external mutation. Catalog
25//! rollback cannot undo either secret writes or changes in external services.
26
27pub(crate) mod connection;
28pub(crate) mod source;
29pub(crate) mod source_statement;
30
31use std::sync::Arc;
32
33use mz_sql::ast::{Raw, Statement};
34use mz_sql::catalog::ObjectType;
35use mz_sql::plan::{Params, Plan, PlanNotice};
36use mz_sql::session::metadata::SessionMetadata;
37use tokio::sync::mpsc;
38
39use crate::catalog::command::source_statement::{
40    SourceCommand, SourceCompilation, SourceResolution,
41};
42use crate::catalog::{CatalogState, CommandExecutionError, CommandResponse, CommandWork, Op};
43use crate::session::SessionMeta;
44use crate::{AdapterError, AdapterNotice};
45
46#[derive(Clone, Debug)]
47pub enum CatalogCommand {
48    Rename(Arc<RenameCommand>),
49    CatalogResult(Arc<CatalogResultCommand>),
50    Description(Arc<DescriptionCommand>),
51    AlterConnection(Arc<connection::ConnectionStatement>),
52    CreateConnection(Arc<connection::ConnectionStatement>),
53    Source(Arc<source_statement::SourceCommand>),
54}
55
56impl CatalogCommand {
57    /// Resolves a command against the candidate catalog, or requests external work.
58    ///
59    /// The response must belong to this command's index in the replayed batch.
60    pub(super) fn compile(
61        &mut self,
62        state: &CatalogState,
63        index: usize,
64        response: Option<CommandResponse>,
65    ) -> Result<CommandExecution<'_>, CommandExecutionError> {
66        match self {
67            Self::Rename(command) => Ok(CommandExecution::raw(command.execute(state)?)),
68            Self::Description(command) => {
69                command.execute(state)?;
70                Ok(CommandExecution::raw(Vec::new()))
71            }
72            Self::CatalogResult(command) => {
73                command.execute(state)?;
74                Ok(CommandExecution::raw(Vec::new()))
75            }
76            Self::CreateConnection(command) => {
77                use connection::CreateConnectionResolution;
78                let command = Arc::make_mut(command);
79                let (preparation, secret) = match response {
80                    Some(CommandResponse::Connection(response)) => (Some(response), None),
81                    Some(CommandResponse::ConnectionSecret(response)) => (None, Some(response)),
82                    Some(CommandResponse::Source(_)) => {
83                        unreachable!("response belongs to its command")
84                    }
85                    None => (None, None),
86                };
87                let compiled = match command.resolve_create(state, preparation, secret)? {
88                    CreateConnectionResolution::Ensure(request) => {
89                        return Err(CommandExecutionError::Pending {
90                            index,
91                            work: CommandWork::ConnectionSecret(request),
92                        });
93                    }
94                    CreateConnectionResolution::Prepare(request) => {
95                        return Err(CommandExecutionError::Pending {
96                            index,
97                            work: CommandWork::Connection(request),
98                        });
99                    }
100                    CreateConnectionResolution::Ready(compiled) => compiled,
101                };
102                let (id, global_id) = command.create_id();
103                let name = compiled.plan.name;
104                let ops = vec![Op::CreateItem {
105                    id,
106                    name: name.clone(),
107                    item: mz_catalog::memory::objects::CatalogItem::Connection(
108                        mz_catalog::memory::objects::Connection {
109                            create_sql: compiled.plan.connection.create_sql,
110                            global_id,
111                            details: compiled.plan.connection.details,
112                            resolved_ids: compiled.resolved_ids,
113                        },
114                    ),
115                    owner_id: command.owner_id(),
116                }];
117                // Resource checks precede IF NOT EXISTS collision handling.
118                state.validate_resource_limits(&ops, command.connection_id())?;
119                command.applied(compiled.notices);
120                command.set_skipped_name(None);
121                let outcome = if compiled.plan.if_not_exists {
122                    Some(ExecutionOutcome::CreateConnection {
123                        command,
124                        id,
125                        name: name.item,
126                    })
127                } else {
128                    None
129                };
130                Ok(CommandExecution { ops, outcome })
131            }
132            Self::AlterConnection(command) => {
133                use connection::ConnectionResolution;
134                let command = Arc::make_mut(command);
135                let response = match response {
136                    Some(CommandResponse::Connection(response)) => Some(response),
137                    Some(CommandResponse::Source(_) | CommandResponse::ConnectionSecret(_)) => {
138                        unreachable!("response belongs to its command")
139                    }
140                    None => None,
141                };
142                let compiled = match command.resolve_alter(state, response)? {
143                    ConnectionResolution::Prepare(request) => {
144                        return Err(CommandExecutionError::Pending {
145                            index,
146                            work: CommandWork::Connection(request),
147                        });
148                    }
149                    ConnectionResolution::Ready(compiled) => compiled,
150                };
151                let ops = match compiled.connection {
152                    Some((id, connection, _)) => {
153                        use mz_storage_types::AlterCompatible;
154                        let entry = state.get_entry(&id);
155                        let current = entry.connection().map_err(AdapterError::from)?;
156                        current
157                            .details
158                            .to_connection()
159                            .alter_compatible(
160                                current.global_id,
161                                &connection.details.to_connection(),
162                            )
163                            .map_err(mz_storage_types::controller::StorageError::from)
164                            .map_err(AdapterError::from)?;
165                        vec![Op::UpdateItem {
166                            id,
167                            name: entry.name().clone(),
168                            to_item: mz_catalog::memory::objects::CatalogItem::Connection(
169                                connection,
170                            ),
171                        }]
172                    }
173                    None => Vec::new(),
174                };
175                command.applied(compiled.notices);
176                Ok(CommandExecution::raw(ops))
177            }
178            Self::Source(command) => {
179                let command = Arc::make_mut(command);
180                let resolution = match response {
181                    Some(CommandResponse::Source(response)) => {
182                        command.statement.finish(state, response)?
183                    }
184                    Some(CommandResponse::Connection(_) | CommandResponse::ConnectionSecret(_)) => {
185                        unreachable!("response belongs to its command")
186                    }
187                    None => command.statement.resolve(state)?,
188                };
189                match resolution {
190                    SourceResolution::Prepare(request) => Err(CommandExecutionError::Pending {
191                        index,
192                        work: CommandWork::Prepare(request),
193                    }),
194                    SourceResolution::Allocate(keys) => Err(CommandExecutionError::Pending {
195                        index,
196                        work: CommandWork::Allocate(keys),
197                    }),
198                    SourceResolution::Ready(mut compiled) => Ok(CommandExecution {
199                        ops: std::mem::take(&mut compiled.ops),
200                        outcome: Some(ExecutionOutcome::Source(command, compiled)),
201                    }),
202                }
203            }
204        }
205    }
206
207    /// The planning notices recorded during preparation.
208    pub(crate) fn notices(&self) -> &[PlanNotice] {
209        match self {
210            Self::Rename(command) => command.notices(),
211            Self::CatalogResult(command) => &command.notices,
212            Self::Description(_) => &[],
213            Self::AlterConnection(command) | Self::CreateConnection(command) => command.notices(),
214            Self::Source(command) => command.notices(),
215        }
216    }
217}
218
219/// Catalog writes and the outcome validation required before publishing them.
220///
221/// Run any collision probe in an isolated transaction before taking the writes.
222/// For executions that are not skipped, apply the writes in order and call
223/// `finish` before executing the next command.
224pub(super) struct CommandExecution<'a> {
225    ops: Vec<Op>,
226    outcome: Option<ExecutionOutcome<'a>>,
227}
228
229enum ExecutionOutcome<'a> {
230    Source(&'a mut SourceCommand, Box<SourceCompilation>),
231    CreateConnection {
232        command: &'a mut connection::ConnectionStatement,
233        id: mz_repr::CatalogItemId,
234        name: String,
235    },
236}
237
238impl CommandExecution<'_> {
239    pub(super) fn raw(ops: Vec<Op>) -> Self {
240        Self { ops, outcome: None }
241    }
242
243    pub(super) fn collision_probe_ops(&self) -> Option<&[Op]> {
244        match &self.outcome {
245            Some(ExecutionOutcome::Source(command, compiled)) => command
246                .needs_collision_probe(compiled)
247                .then_some(self.ops.as_slice()),
248            Some(ExecutionOutcome::CreateConnection { .. }) => Some(self.ops.as_slice()),
249            None => None,
250        }
251    }
252
253    /// Validates a requested collision probe, consuming skipped executions.
254    pub(super) fn finish_probe(
255        mut self,
256        result: Result<(), AdapterError>,
257    ) -> Result<Option<Self>, AdapterError> {
258        let skipped = match self.outcome.as_mut().expect("collision probe requested") {
259            ExecutionOutcome::Source(command, compiled) => {
260                let (_, outcome) = compiled.classify_result(result)?;
261                command.check_outcome(outcome)?;
262                command.skipped_name().is_some()
263            }
264            ExecutionOutcome::CreateConnection { command, id, name } => match result {
265                Ok(()) => false,
266                Err(AdapterError::Catalog(mz_catalog::memory::error::Error {
267                    kind:
268                        mz_catalog::memory::error::ErrorKind::Sql(
269                            mz_sql::catalog::CatalogError::ItemAlreadyExists(attempted_id, _),
270                        ),
271                })) if attempted_id == *id => {
272                    command.set_skipped_name(Some(name.clone()));
273                    true
274                }
275                Err(error) => return Err(error),
276            },
277        };
278        if skipped { Ok(None) } else { Ok(Some(self)) }
279    }
280
281    pub(super) fn take_ops(&mut self) -> Vec<Op> {
282        std::mem::take(&mut self.ops)
283    }
284
285    /// Checks the observed outcome and propagates the result unless that outcome changed.
286    pub(super) fn finish<T>(self, result: Result<T, AdapterError>) -> Result<T, AdapterError> {
287        if let Some(ExecutionOutcome::Source(command, compiled)) = self.outcome {
288            match &result {
289                Ok(_) => command.check_outcome(compiled.created())?,
290                Err(error) => {
291                    if let Some(outcome) = compiled.skipped(error) {
292                        command.check_outcome(outcome)?;
293                    }
294                }
295            }
296        }
297        result
298    }
299}
300
301/// A rename or swap command.
302#[derive(Debug)]
303pub struct RenameCommand {
304    statement: Arc<Statement<Raw>>,
305    params: Params,
306    session: SessionMeta,
307    outcome: RenameOutcome,
308}
309
310#[derive(Debug, PartialEq)]
311struct RenameOutcome {
312    object_type: ObjectType,
313    changed: bool,
314    notices: Vec<PlanNotice>,
315}
316
317impl RenameCommand {
318    /// Prepares a rename or swap and records the outcome that replay must
319    /// preserve.
320    ///
321    /// Returns the initial plan for statement execution. The statement must
322    /// plan to a supported rename, swap, or ALTER no-op.
323    ///
324    /// # Panics
325    ///
326    /// Panics if the statement plans successfully to anything other than a
327    /// supported rename, swap, or ALTER no-op.
328    pub(crate) fn prepare(
329        state: &CatalogState,
330        statement: Arc<Statement<Raw>>,
331        params: Params,
332        session: SessionMeta,
333    ) -> Result<(Self, Plan), AdapterError> {
334        let (plan, notices) = plan_command(state, &statement, &params, &session)?;
335        let (ops, object_type) = rename_ops(&plan);
336        Ok((
337            Self {
338                statement,
339                params,
340                session,
341                outcome: RenameOutcome {
342                    object_type,
343                    changed: !ops.is_empty(),
344                    notices,
345                },
346            },
347            plan,
348        ))
349    }
350
351    /// The planning notices recorded during preparation.
352    pub(crate) fn notices(&self) -> &[PlanNotice] {
353        &self.outcome.notices
354    }
355
356    /// The object type used in the statement's completion response.
357    pub(crate) fn object_type(&self) -> ObjectType {
358        self.outcome.object_type
359    }
360
361    /// Returns writes for `state` after rechecking planning and authorization.
362    ///
363    /// Rejects changes to the object type, whether the command is a no-op, or
364    /// the planning notices. The caller must apply the returned writes.
365    pub(super) fn execute(&self, state: &CatalogState) -> Result<Vec<Op>, AdapterError> {
366        let (plan, notices) = plan_command(state, &self.statement, &self.params, &self.session)?;
367        let (ops, object_type) = rename_ops(&plan);
368        let outcome = RenameOutcome {
369            object_type,
370            changed: !ops.is_empty(),
371            notices,
372        };
373        if outcome != self.outcome {
374            return Err(AdapterError::DDLTransactionOutcomeChanged);
375        }
376        Ok(ops)
377    }
378}
379
380/// A catalog query whose result and notices must remain unchanged at DDL
381/// commit.
382///
383/// In a way, this puts an "assert" into the list of commands for the DDL
384/// transaction, that enforces that the output stays what we have already
385/// reported, when committing.
386#[derive(Debug)]
387pub struct CatalogResultCommand {
388    statement: Arc<Statement<Raw>>,
389    params: Params,
390    session: SessionMeta,
391    row: mz_repr::Row,
392    notices: Vec<PlanNotice>,
393}
394
395impl CatalogResultCommand {
396    /// Whether this statement supports retaining its catalog result for replay.
397    pub(crate) fn supports_statement(statement: &Statement<Raw>) -> bool {
398        use mz_sql::ast::ShowStatement;
399        let Statement::Show(show) = statement else {
400            return false;
401        };
402        match show {
403            ShowStatement::ShowCreateView(_)
404            | ShowStatement::ShowCreateMaterializedView(_)
405            | ShowStatement::ShowCreateSource(_)
406            | ShowStatement::ShowCreateTable(_)
407            | ShowStatement::ShowCreateSink(_)
408            | ShowStatement::ShowCreateMetricSink(_)
409            | ShowStatement::ShowCreateIndex(_)
410            | ShowStatement::ShowCreateConnection(_)
411            | ShowStatement::ShowCreateCluster(_)
412            | ShowStatement::ShowCreateType(_) => true,
413            ShowStatement::ShowObjects(_)
414            | ShowStatement::ShowColumns(_)
415            | ShowStatement::ShowVariable(_)
416            | ShowStatement::InspectShard(_) => false,
417        }
418    }
419
420    /// Prepares a catalog query and records the row and notices replay must
421    /// preserve.
422    ///
423    /// Returns the initial plan for statement execution. Fails if the plan does
424    /// not provide a supported catalog result.
425    pub(crate) fn prepare(
426        state: &CatalogState,
427        statement: Arc<Statement<Raw>>,
428        params: Params,
429        session: SessionMeta,
430    ) -> Result<(Self, Plan), AdapterError> {
431        let (plan, notices) = plan_command(state, &statement, &params, &session)?;
432        let row = Self::result(&plan)?;
433        let command = Self {
434            statement,
435            params,
436            session,
437            row,
438            notices,
439        };
440        Ok((command, plan))
441    }
442
443    /// Rechecks planning and authorization and requires the recorded row and
444    /// notices.
445    pub(in crate::catalog) fn execute(&self, state: &CatalogState) -> Result<(), AdapterError> {
446        let (plan, notices) = plan_command(state, &self.statement, &self.params, &self.session)?;
447        if Self::result(&plan)? == self.row && notices == self.notices {
448            Ok(())
449        } else {
450            Err(AdapterError::DDLTransactionOutcomeChanged)
451        }
452    }
453
454    /// Returns the row to send to the client, or an error for an unsupported
455    /// plan.
456    pub(crate) fn result(plan: &Plan) -> Result<mz_repr::Row, AdapterError> {
457        match plan {
458            Plan::ShowCreate(show) => Ok(show.row.clone()),
459            _ => Err(AdapterError::Unsupported(
460                "non-deterministic catalog result",
461            )),
462        }
463    }
464}
465
466/// A statement description that must remain unchanged at DDL commit.
467///
468/// In a way, this puts an "assert" into the list of commands for the DDL
469/// transaction, that enforces that the output stays what we have already
470/// reported, when committing.
471#[derive(Debug)]
472pub struct DescriptionCommand {
473    statement: Statement<Raw>,
474    param_types: Vec<Option<mz_repr::SqlScalarType>>,
475    session: SessionMeta,
476    expected: mz_sql::plan::StatementDesc,
477}
478
479impl DescriptionCommand {
480    /// Records a statement description for validation at DDL commit.
481    ///
482    /// `expected` must be the description obtained for this statement with the
483    /// supplied parameter types and session metadata. This does not validate
484    /// it.
485    pub(crate) fn new(
486        statement: Statement<Raw>,
487        param_types: Vec<Option<mz_repr::SqlScalarType>>,
488        session: SessionMeta,
489        expected: mz_sql::plan::StatementDesc,
490    ) -> Self {
491        Self {
492            statement,
493            param_types,
494            session,
495            expected,
496        }
497    }
498
499    /// Requires the statement to retain its recorded description in `state`.
500    pub(in crate::catalog) fn execute(&self, state: &CatalogState) -> Result<(), AdapterError> {
501        let (tx, _rx) = mpsc::unbounded_channel();
502        let catalog = state.for_session_metadata(&self.session, tx);
503        let (statement, resolved_ids) = mz_sql::names::resolve(&catalog, self.statement.clone())?;
504        let current = mz_sql::plan::describe(
505            self.session.pcx(),
506            &catalog,
507            statement,
508            &self.param_types,
509            &resolved_ids,
510        )?;
511        if current == self.expected {
512            Ok(())
513        } else {
514            Err(AdapterError::DDLTransactionOutcomeChanged)
515        }
516    }
517}
518
519fn plan_command(
520    state: &CatalogState,
521    statement: &Statement<Raw>,
522    params: &Params,
523    session: &SessionMeta,
524) -> Result<(Plan, Vec<PlanNotice>), AdapterError> {
525    let (tx, mut rx) = mpsc::unbounded_channel();
526    let catalog = state.for_session_metadata(session, tx);
527    let (statement, resolved_ids) = mz_sql::names::resolve(&catalog, statement.clone())?;
528    let (plan, sql_impl_ids) = mz_sql::plan::plan(
529        Some(session.pcx()),
530        &catalog,
531        statement,
532        params,
533        &resolved_ids,
534    )?;
535    mz_sql::rbac::check_plan(
536        &catalog,
537        None,
538        session,
539        &plan,
540        None,
541        &resolved_ids,
542        &sql_impl_ids,
543    )?;
544    let mut notices = Vec::new();
545    while let Ok(notice) = rx.try_recv() {
546        match notice {
547            AdapterNotice::PlanNotice(notice) => notices.push(notice),
548            _ => unreachable!("planning only emits plan notices"),
549        }
550    }
551    Ok((plan, notices))
552}
553
554/// Returns the rename/swap ops for the given `Plan`, along with the object
555/// type.
556///
557/// # Panics
558///
559/// Panics if `plan` is not a supported rename, swap, or ALTER no-op.
560fn rename_ops(plan: &Plan) -> (Vec<Op>, ObjectType) {
561    match plan {
562        Plan::AlterNoop(plan) => (vec![], plan.object_type),
563        Plan::AlterItemRename(plan) => (
564            vec![Op::RenameItem {
565                id: plan.id,
566                current_full_name: plan.current_full_name.clone(),
567                to_name: plan.to_name.clone(),
568            }],
569            plan.object_type,
570        ),
571        Plan::AlterSchemaRename(plan) => (
572            vec![Op::RenameSchema {
573                database_spec: plan.cur_schema_spec.0,
574                schema_spec: plan.cur_schema_spec.1,
575                new_name: plan.new_schema_name.clone(),
576                check_reserved_names: true,
577            }],
578            ObjectType::Schema,
579        ),
580        Plan::AlterSchemaSwap(plan) => (
581            vec![
582                Op::RenameSchema {
583                    database_spec: plan.schema_a_spec.0,
584                    schema_spec: plan.schema_a_spec.1,
585                    new_name: plan.name_temp.clone(),
586                    check_reserved_names: false,
587                },
588                Op::RenameSchema {
589                    database_spec: plan.schema_b_spec.0,
590                    schema_spec: plan.schema_b_spec.1,
591                    new_name: plan.schema_a_name.clone(),
592                    check_reserved_names: false,
593                },
594                Op::RenameSchema {
595                    database_spec: plan.schema_a_spec.0,
596                    schema_spec: plan.schema_a_spec.1,
597                    new_name: plan.schema_b_name.clone(),
598                    check_reserved_names: false,
599                },
600            ],
601            ObjectType::Schema,
602        ),
603        Plan::AlterClusterRename(plan) => (
604            vec![Op::RenameCluster {
605                id: plan.id,
606                name: plan.name.clone(),
607                to_name: plan.to_name.clone(),
608                check_reserved_names: true,
609            }],
610            ObjectType::Cluster,
611        ),
612        Plan::AlterClusterSwap(plan) => (
613            vec![
614                Op::RenameCluster {
615                    id: plan.id_a,
616                    name: plan.name_a.clone(),
617                    to_name: plan.name_temp.clone(),
618                    check_reserved_names: false,
619                },
620                Op::RenameCluster {
621                    id: plan.id_b,
622                    name: plan.name_b.clone(),
623                    to_name: plan.name_a.clone(),
624                    check_reserved_names: false,
625                },
626                Op::RenameCluster {
627                    id: plan.id_a,
628                    name: plan.name_temp.clone(),
629                    to_name: plan.name_b.clone(),
630                    check_reserved_names: false,
631                },
632            ],
633            ObjectType::Cluster,
634        ),
635        Plan::AlterClusterReplicaRename(plan) => (
636            vec![Op::RenameClusterReplica {
637                cluster_id: plan.cluster_id,
638                replica_id: plan.replica_id,
639                name: plan.name.clone(),
640                to_name: plan.to_name.clone(),
641            }],
642            ObjectType::ClusterReplica,
643        ),
644        _ => unreachable!("rename/swap planning must produce a rename or no-op plan"),
645    }
646}
647
648pub(crate) fn plan_subsource(
649    catalog: &crate::catalog::ConnCatalog<'_>,
650    pcx: &mz_sql::plan::PlanContext,
651    params: &Params,
652    statement: mz_sql::ast::CreateSubsourceStatement<mz_sql::names::Aug>,
653    item_id: mz_repr::CatalogItemId,
654    global_id: mz_repr::GlobalId,
655) -> Result<mz_sql::plan::CreateSourcePlanBundle, AdapterError> {
656    let resolved_ids = mz_sql::names::visit_dependencies(catalog, &statement);
657    let (plan, _sql_impl_ids) = mz_sql::plan::plan(
658        Some(pcx),
659        catalog,
660        Statement::CreateSubsource(statement),
661        params,
662        &resolved_ids,
663    )?;
664    let Plan::CreateSource(plan) = plan else {
665        unreachable!("subsource planning produces a source plan");
666    };
667    Ok(mz_sql::plan::CreateSourcePlanBundle {
668        item_id,
669        global_id,
670        plan,
671        resolved_ids,
672        available_source_references: None,
673    })
674}