Skip to main content

mz_adapter/
notice.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
10use std::fmt;
11use std::time::Duration;
12
13use chrono::{DateTime, Utc};
14use itertools::Itertools;
15use mz_controller::clusters::ClusterStatus;
16use mz_orchestrator::{OfflineReason, ServiceStatus};
17use mz_ore::str::{StrExt, separated};
18use mz_pgwire_common::{ErrorResponse, Severity};
19use mz_repr::adt::mz_acl_item::AclMode;
20use mz_repr::strconv;
21use mz_sql::ast::NoticeSeverity;
22use mz_sql::catalog::ErrorMessageObjectDescription;
23use mz_sql::plan::PlanNotice;
24use mz_sql::session::vars::IsolationLevel;
25use tokio_postgres::error::SqlState;
26
27use crate::TimestampExplanation;
28
29/// Notices that can occur in the adapter layer.
30///
31/// These are diagnostic warnings or informational messages that are not
32/// severe enough to warrant failing a query entirely.
33#[derive(Clone, Debug)]
34pub enum AdapterNotice {
35    DatabaseAlreadyExists {
36        name: String,
37    },
38    SchemaAlreadyExists {
39        name: String,
40    },
41    TableAlreadyExists {
42        name: String,
43    },
44    ObjectAlreadyExists {
45        name: String,
46        ty: &'static str,
47    },
48    DatabaseDoesNotExist {
49        name: String,
50    },
51    ClusterDoesNotExist {
52        name: String,
53    },
54    DefaultClusterDoesNotExist {
55        name: String,
56        kind: &'static str,
57        suggested_action: String,
58    },
59    NoResolvableSearchPathSchema {
60        search_path: Vec<String>,
61    },
62    ExistingTransactionInProgress,
63    ExplicitTransactionControlInImplicitTransaction,
64    UserRequested {
65        severity: NoticeSeverity,
66    },
67    ClusterReplicaStatusChanged {
68        cluster: String,
69        replica: String,
70        status: ClusterStatus,
71        time: DateTime<Utc>,
72    },
73    CascadeDroppedObject {
74        objects: Vec<String>,
75    },
76    DroppedActiveDatabase {
77        name: String,
78    },
79    DroppedActiveCluster {
80        name: String,
81    },
82    QueryTimestamp {
83        explanation: TimestampExplanation,
84    },
85    EqualSubscribeBounds {
86        bound: mz_repr::Timestamp,
87    },
88    QueryTrace {
89        trace_id: opentelemetry::trace::TraceId,
90    },
91    UnimplementedIsolationLevel {
92        isolation_level: String,
93    },
94    StrongSessionSerializable,
95    BadStartupSetting {
96        name: String,
97        reason: String,
98    },
99    RbacUserDisabled,
100    RoleMembershipAlreadyExists {
101        role_name: String,
102        member_name: String,
103    },
104    RoleMembershipDoesNotExists {
105        role_name: String,
106        member_name: String,
107    },
108    AutoRunOnCatalogServerCluster,
109    AlterIndexOwner {
110        name: String,
111    },
112    CannotRevoke {
113        object_description: ErrorMessageObjectDescription,
114    },
115    NonApplicablePrivilegeTypes {
116        non_applicable_privileges: AclMode,
117        object_description: ErrorMessageObjectDescription,
118    },
119    PlanNotice(PlanNotice),
120    UnknownSessionDatabase(String),
121    OptimizerNotice {
122        notice: String,
123        hint: String,
124    },
125    QueryPolicyWarning(crate::query_policy::QueryPolicyViolation),
126    WebhookSourceCreated {
127        url: url::Url,
128    },
129    DroppedInUseIndex(DroppedInUseIndex),
130    DroppedIndexReadByInFlightStatements(InFlightIndexReaders),
131    PerReplicaLogRead {
132        log_names: Vec<String>,
133    },
134    VarDefaultUpdated {
135        role: Option<String>,
136        var_name: Option<String>,
137    },
138    /// An `ALTER SYSTEM` statement named a system parameter that
139    /// `environmentd` only reads at startup, so the running process keeps the
140    /// value it sampled at boot.
141    StartupOnlyVarUpdated {
142        var_name: String,
143    },
144    Welcome(String),
145    PlanInsights(String),
146    ExecutionTime(ExecutionTime),
147    IntrospectionClusterUsage,
148    AutoRouteIntrospectionQueriesUsage,
149    /// A cluster contains sources that run on only one replica, yet the
150    /// cluster has (or is about to have) more than one replica.
151    SingleReplicaSourcesOnMultiReplicaCluster {
152        cluster: String,
153        sources: Vec<String>,
154    },
155    /// An OIDC group maps to a reserved role name (mz_/pg_ prefix).
156    OidcGroupSyncReservedRole {
157        group: String,
158    },
159    /// OIDC group sync encountered an error (fail-open mode).
160    OidcGroupSyncError {
161        message: String,
162    },
163}
164
165impl AdapterNotice {
166    pub fn into_response(self) -> ErrorResponse {
167        ErrorResponse {
168            severity: self.severity(),
169            code: self.code(),
170            message: self.to_string(),
171            detail: self.detail(),
172            hint: self.hint(),
173            position: None,
174        }
175    }
176
177    /// Returns the severity for a notice.
178    pub fn severity(&self) -> Severity {
179        match self {
180            AdapterNotice::DatabaseAlreadyExists { .. } => Severity::Notice,
181            AdapterNotice::SchemaAlreadyExists { .. } => Severity::Notice,
182            AdapterNotice::TableAlreadyExists { .. } => Severity::Notice,
183            AdapterNotice::ObjectAlreadyExists { .. } => Severity::Notice,
184            AdapterNotice::DatabaseDoesNotExist { .. } => Severity::Notice,
185            AdapterNotice::ClusterDoesNotExist { .. } => Severity::Notice,
186            AdapterNotice::DefaultClusterDoesNotExist { .. } => Severity::Notice,
187            AdapterNotice::NoResolvableSearchPathSchema { .. } => Severity::Notice,
188            AdapterNotice::ExistingTransactionInProgress => Severity::Warning,
189            AdapterNotice::ExplicitTransactionControlInImplicitTransaction => Severity::Warning,
190            AdapterNotice::UserRequested { severity } => match severity {
191                NoticeSeverity::Debug => Severity::Debug,
192                NoticeSeverity::Info => Severity::Info,
193                NoticeSeverity::Log => Severity::Log,
194                NoticeSeverity::Notice => Severity::Notice,
195                NoticeSeverity::Warning => Severity::Warning,
196            },
197            AdapterNotice::ClusterReplicaStatusChanged { .. } => Severity::Notice,
198            AdapterNotice::CascadeDroppedObject { .. } => Severity::Notice,
199            AdapterNotice::DroppedActiveDatabase { .. } => Severity::Notice,
200            AdapterNotice::DroppedActiveCluster { .. } => Severity::Notice,
201            AdapterNotice::QueryTimestamp { .. } => Severity::Notice,
202            AdapterNotice::EqualSubscribeBounds { .. } => Severity::Notice,
203            AdapterNotice::QueryTrace { .. } => Severity::Notice,
204            AdapterNotice::UnimplementedIsolationLevel { .. } => Severity::Notice,
205            AdapterNotice::StrongSessionSerializable => Severity::Notice,
206            AdapterNotice::BadStartupSetting { .. } => Severity::Notice,
207            AdapterNotice::RbacUserDisabled => Severity::Notice,
208            AdapterNotice::RoleMembershipAlreadyExists { .. } => Severity::Notice,
209            AdapterNotice::RoleMembershipDoesNotExists { .. } => Severity::Warning,
210            AdapterNotice::AutoRunOnCatalogServerCluster => Severity::Debug,
211            AdapterNotice::AlterIndexOwner { .. } => Severity::Warning,
212            AdapterNotice::CannotRevoke { .. } => Severity::Warning,
213            AdapterNotice::NonApplicablePrivilegeTypes { .. } => Severity::Notice,
214            AdapterNotice::PlanNotice(notice) => match notice {
215                PlanNotice::ObjectDoesNotExist { .. } => Severity::Notice,
216                PlanNotice::ColumnAlreadyExists { .. } => Severity::Notice,
217                PlanNotice::UpsertSinkKeyNotEnforced { .. } => Severity::Warning,
218                PlanNotice::ReplicaDiskOptionDeprecated { .. } => Severity::Notice,
219            },
220            AdapterNotice::UnknownSessionDatabase(_) => Severity::Notice,
221            AdapterNotice::OptimizerNotice { .. } => Severity::Notice,
222            AdapterNotice::QueryPolicyWarning(_) => Severity::Notice,
223            AdapterNotice::WebhookSourceCreated { .. } => Severity::Notice,
224            AdapterNotice::DroppedInUseIndex { .. } => Severity::Warning,
225            AdapterNotice::DroppedIndexReadByInFlightStatements(_) => Severity::Notice,
226            AdapterNotice::PerReplicaLogRead { .. } => Severity::Notice,
227            AdapterNotice::VarDefaultUpdated { .. } => Severity::Notice,
228            AdapterNotice::StartupOnlyVarUpdated { .. } => Severity::Warning,
229            AdapterNotice::Welcome(_) => Severity::Notice,
230            AdapterNotice::PlanInsights(_) => Severity::Notice,
231            AdapterNotice::ExecutionTime(_) => Severity::Notice,
232            AdapterNotice::IntrospectionClusterUsage => Severity::Warning,
233            AdapterNotice::AutoRouteIntrospectionQueriesUsage => Severity::Warning,
234            AdapterNotice::SingleReplicaSourcesOnMultiReplicaCluster { .. } => Severity::Warning,
235            AdapterNotice::OidcGroupSyncReservedRole { .. } => Severity::Warning,
236            AdapterNotice::OidcGroupSyncError { .. } => Severity::Warning,
237        }
238    }
239
240    /// Reports additional details about the notice, if any are available.
241    pub fn detail(&self) -> Option<String> {
242        match self {
243            AdapterNotice::PlanNotice(notice) => notice.detail(),
244            AdapterNotice::ExecutionTime(time) => Some(
245                serde_json::json!({
246                    "kind": time.kind.name(),
247                    "duration_us": u64::try_from(time.elapsed.as_micros()).unwrap_or(u64::MAX),
248                })
249                .to_string(),
250            ),
251            AdapterNotice::DroppedInUseIndex(..) => Some(
252                "The index no longer appears in the catalog, but it is still maintained, using \
253                 memory and CPU, until those objects are dropped or recreated, or replanned at \
254                 the next restart. The drop was allowed because enable_drop_in_use_index is set."
255                    .into(),
256            ),
257            AdapterNotice::SingleReplicaSourcesOnMultiReplicaCluster { .. } => Some(
258                "Adding replicas to the cluster does not make these sources more fault tolerant \
259                 and does not increase their ingestion throughput."
260                    .into(),
261            ),
262            AdapterNotice::QueryTimestamp { explanation } => Some(format!("\n{explanation}")),
263            AdapterNotice::QueryPolicyWarning(violation) => Some(format!(
264                "{} Policy mode is 'warn', so this rule does not reject the query.",
265                violation.detail(),
266            )),
267            AdapterNotice::CascadeDroppedObject { objects } => Some(
268                objects
269                    .iter()
270                    .map(|obj_info| format!("drop cascades to {}", obj_info))
271                    .join("\n"),
272            ),
273            _ => None,
274        }
275    }
276
277    /// Reports a hint for the user about how the notice could be addressed.
278    pub fn hint(&self) -> Option<String> {
279        match self {
280            AdapterNotice::DatabaseDoesNotExist { name: _ } => Some("Create the database with CREATE DATABASE or pick an extant database with SET DATABASE = name. List available databases with SHOW DATABASES.".into()),
281            AdapterNotice::ClusterDoesNotExist { name: _ } => Some("Create the cluster with CREATE CLUSTER or pick an extant cluster with SET CLUSTER = name. List available clusters with SHOW CLUSTERS.".into()),
282            AdapterNotice::DefaultClusterDoesNotExist {
283                name: _,
284                kind: _,
285                suggested_action,
286            } => Some(suggested_action.clone()),
287            AdapterNotice::NoResolvableSearchPathSchema { search_path: _ } => Some("Create a schema with CREATE SCHEMA or pick an extant schema with SET SCHEMA = name. List available schemas with SHOW SCHEMAS.".into()),
288            AdapterNotice::DroppedActiveDatabase { name: _ } => Some("Choose a new active database by executing SET DATABASE = <name>.".into()),
289            AdapterNotice::DroppedActiveCluster { name: _ } => Some("Choose a new active cluster by executing SET CLUSTER = <name>.".into()),
290            AdapterNotice::ClusterReplicaStatusChanged { status, .. } => {
291                match status {
292                    ServiceStatus::Offline(None)
293                    | ServiceStatus::Offline(Some(OfflineReason::Initializing)) => Some("The cluster replica may be restarting or going offline.".into()),
294                    ServiceStatus::Offline(Some(OfflineReason::OomKilled)) => Some("The cluster replica may have run out of memory and been killed.".into()),
295                    ServiceStatus::Online => None,
296                }
297            },
298            AdapterNotice::RbacUserDisabled => Some("To enable RBAC globally run `ALTER SYSTEM SET enable_rbac_checks TO TRUE` as a superuser. TO enable RBAC for just this session run `SET enable_session_rbac_checks TO TRUE`.".into()),
299            AdapterNotice::AlterIndexOwner {name: _} => Some("Change the ownership of the index's relation, instead.".into()),
300            AdapterNotice::UnknownSessionDatabase(_) => Some(
301                "Create the database with CREATE DATABASE \
302                 or pick an extant database with SET DATABASE = name. \
303                 List available databases with SHOW DATABASES."
304                    .into(),
305            ),
306            AdapterNotice::OptimizerNotice { notice: _, hint } => Some(hint.clone()),
307            AdapterNotice::DroppedInUseIndex(..) => Some("Drop and recreate those objects to free the index's resources.".into()),
308            AdapterNotice::QueryPolicyWarning(violation) => Some(violation.hint().into()),
309            AdapterNotice::IntrospectionClusterUsage => Some("Use the new name instead.".into()),
310            AdapterNotice::AutoRouteIntrospectionQueriesUsage => Some("Use the new name instead.".into()),
311            AdapterNotice::SingleReplicaSourcesOnMultiReplicaCluster { .. } => Some(
312                "To achieve fault tolerance for other objects in the cluster, consider moving \
313                 these sources to a separate cluster with a single replica."
314                    .into(),
315            ),
316            _ => None
317        }
318    }
319
320    /// Reports the error code.
321    pub fn code(&self) -> SqlState {
322        match self {
323            AdapterNotice::DatabaseAlreadyExists { .. } => SqlState::DUPLICATE_DATABASE,
324            AdapterNotice::SchemaAlreadyExists { .. } => SqlState::DUPLICATE_SCHEMA,
325            AdapterNotice::TableAlreadyExists { .. } => SqlState::DUPLICATE_TABLE,
326            AdapterNotice::ObjectAlreadyExists { .. } => SqlState::DUPLICATE_OBJECT,
327            AdapterNotice::DatabaseDoesNotExist { .. } => SqlState::from_code("MZ006"),
328            AdapterNotice::ClusterDoesNotExist { .. } => SqlState::from_code("MZ007"),
329            AdapterNotice::NoResolvableSearchPathSchema { .. } => SqlState::from_code("MZ008"),
330            AdapterNotice::ExistingTransactionInProgress => SqlState::ACTIVE_SQL_TRANSACTION,
331            AdapterNotice::ExplicitTransactionControlInImplicitTransaction => {
332                SqlState::NO_ACTIVE_SQL_TRANSACTION
333            }
334            AdapterNotice::UserRequested { severity } => match severity {
335                NoticeSeverity::Warning => SqlState::WARNING,
336                _ => SqlState::SUCCESSFUL_COMPLETION,
337            },
338            AdapterNotice::ClusterReplicaStatusChanged { .. } => SqlState::SUCCESSFUL_COMPLETION,
339            AdapterNotice::CascadeDroppedObject { .. } => SqlState::SUCCESSFUL_COMPLETION,
340            AdapterNotice::DroppedActiveDatabase { .. } => SqlState::from_code("MZ002"),
341            AdapterNotice::DroppedActiveCluster { .. } => SqlState::from_code("MZ003"),
342            AdapterNotice::QueryTimestamp { .. } => SqlState::SUCCESSFUL_COMPLETION,
343            AdapterNotice::EqualSubscribeBounds { .. } => SqlState::SUCCESSFUL_COMPLETION,
344            AdapterNotice::QueryTrace { .. } => SqlState::SUCCESSFUL_COMPLETION,
345            AdapterNotice::UnimplementedIsolationLevel { .. } => SqlState::SUCCESSFUL_COMPLETION,
346            AdapterNotice::StrongSessionSerializable => SqlState::SUCCESSFUL_COMPLETION,
347            AdapterNotice::BadStartupSetting { .. } => SqlState::SUCCESSFUL_COMPLETION,
348            AdapterNotice::RbacUserDisabled => SqlState::SUCCESSFUL_COMPLETION,
349            AdapterNotice::RoleMembershipAlreadyExists { .. } => SqlState::SUCCESSFUL_COMPLETION,
350            AdapterNotice::RoleMembershipDoesNotExists { .. } => SqlState::WARNING,
351            AdapterNotice::AutoRunOnCatalogServerCluster => SqlState::SUCCESSFUL_COMPLETION,
352            AdapterNotice::AlterIndexOwner { .. } => SqlState::WARNING,
353            AdapterNotice::CannotRevoke { .. } => SqlState::WARNING_PRIVILEGE_NOT_REVOKED,
354            AdapterNotice::NonApplicablePrivilegeTypes { .. } => SqlState::SUCCESSFUL_COMPLETION,
355            AdapterNotice::PlanNotice(plan) => match plan {
356                PlanNotice::ObjectDoesNotExist { .. } => SqlState::UNDEFINED_OBJECT,
357                PlanNotice::ColumnAlreadyExists { .. } => SqlState::DUPLICATE_COLUMN,
358                PlanNotice::UpsertSinkKeyNotEnforced { .. } => SqlState::WARNING,
359                PlanNotice::ReplicaDiskOptionDeprecated { .. } => {
360                    SqlState::WARNING_DEPRECATED_FEATURE
361                }
362            },
363            AdapterNotice::UnknownSessionDatabase(_) => SqlState::from_code("MZ004"),
364            AdapterNotice::DefaultClusterDoesNotExist { .. } => SqlState::from_code("MZ005"),
365            AdapterNotice::OptimizerNotice { .. } => SqlState::SUCCESSFUL_COMPLETION,
366            AdapterNotice::DroppedInUseIndex { .. } => SqlState::WARNING,
367            AdapterNotice::DroppedIndexReadByInFlightStatements(_) => {
368                SqlState::SUCCESSFUL_COMPLETION
369            }
370            AdapterNotice::QueryPolicyWarning(_) => SqlState::SUCCESSFUL_COMPLETION,
371            AdapterNotice::WebhookSourceCreated { .. } => SqlState::SUCCESSFUL_COMPLETION,
372            AdapterNotice::PerReplicaLogRead { .. } => SqlState::SUCCESSFUL_COMPLETION,
373            AdapterNotice::VarDefaultUpdated { .. } => SqlState::SUCCESSFUL_COMPLETION,
374            AdapterNotice::StartupOnlyVarUpdated { .. } => SqlState::WARNING,
375            AdapterNotice::Welcome(_) => SqlState::SUCCESSFUL_COMPLETION,
376            AdapterNotice::PlanInsights(_) => SqlState::from_code("MZ001"),
377            AdapterNotice::ExecutionTime(_) => SqlState::from_code("MZ012"),
378            AdapterNotice::IntrospectionClusterUsage => SqlState::WARNING,
379            AdapterNotice::AutoRouteIntrospectionQueriesUsage => SqlState::WARNING,
380            AdapterNotice::SingleReplicaSourcesOnMultiReplicaCluster { .. } => SqlState::WARNING,
381            AdapterNotice::OidcGroupSyncReservedRole { .. } => SqlState::WARNING,
382            AdapterNotice::OidcGroupSyncError { .. } => SqlState::WARNING,
383        }
384    }
385}
386
387impl fmt::Display for AdapterNotice {
388    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
389        match self {
390            AdapterNotice::QueryPolicyWarning(violation) => write!(
391                f,
392                "query would be rejected under query policy {} (rule {}): {}",
393                violation.policy.quoted(),
394                violation.rule.quoted(),
395                violation.reason(),
396            ),
397            AdapterNotice::DatabaseAlreadyExists { name } => {
398                write!(f, "database {} already exists, skipping", name.quoted())
399            }
400            AdapterNotice::SchemaAlreadyExists { name } => {
401                write!(f, "schema {} already exists, skipping", name.quoted())
402            }
403            AdapterNotice::TableAlreadyExists { name } => {
404                write!(f, "table {} already exists, skipping", name.quoted())
405            }
406            AdapterNotice::ObjectAlreadyExists { name, ty } => {
407                write!(f, "{} {} already exists, skipping", ty, name.quoted())
408            }
409            AdapterNotice::DatabaseDoesNotExist { name } => {
410                write!(f, "database {} does not exist", name.quoted())
411            }
412            AdapterNotice::CascadeDroppedObject { objects } => {
413                write!(f, "drop cascades to {} other objects", objects.len())
414            }
415            AdapterNotice::ClusterDoesNotExist { name } => {
416                write!(f, "cluster {} does not exist", name.quoted())
417            }
418            AdapterNotice::DefaultClusterDoesNotExist { kind, name, .. } => {
419                write!(f, "{kind} default cluster {} does not exist", name.quoted())
420            }
421            AdapterNotice::NoResolvableSearchPathSchema { search_path } => {
422                write!(
423                    f,
424                    "no schema on the search path exists: {}",
425                    search_path.join(", ")
426                )
427            }
428            AdapterNotice::ExistingTransactionInProgress => {
429                write!(f, "there is already a transaction in progress")
430            }
431            AdapterNotice::ExplicitTransactionControlInImplicitTransaction => {
432                write!(f, "there is no transaction in progress")
433            }
434            AdapterNotice::UserRequested { severity } => {
435                write!(f, "raised a test {}", severity.to_string().to_lowercase())
436            }
437            AdapterNotice::ClusterReplicaStatusChanged {
438                cluster,
439                replica,
440                status,
441                time,
442            } => {
443                let mut time_buf = String::new();
444                strconv::format_timestamptz(&mut time_buf, time);
445                write!(
446                    f,
447                    "cluster replica {}.{} changed status to {} at {}",
448                    cluster,
449                    replica,
450                    status.as_kebab_case_str().quoted(),
451                    time_buf,
452                )?;
453                Ok(())
454            }
455            AdapterNotice::DroppedActiveDatabase { name } => {
456                write!(f, "active database {} has been dropped", name.quoted())
457            }
458            AdapterNotice::DroppedActiveCluster { name } => {
459                write!(f, "active cluster {} has been dropped", name.quoted())
460            }
461            AdapterNotice::QueryTimestamp { .. } => write!(f, "EXPLAIN TIMESTAMP for query"),
462            AdapterNotice::EqualSubscribeBounds { bound } => {
463                write!(
464                    f,
465                    "subscribe as of {bound} (inclusive) up to the same bound {bound} (exclusive) is guaranteed to be empty"
466                )
467            }
468            AdapterNotice::QueryTrace { trace_id } => {
469                write!(f, "trace id: {}", trace_id)
470            }
471            AdapterNotice::UnimplementedIsolationLevel { isolation_level } => {
472                write!(
473                    f,
474                    "transaction isolation level {isolation_level} is unimplemented, the session will be upgraded to {}",
475                    IsolationLevel::Serializable
476                )
477            }
478            AdapterNotice::StrongSessionSerializable => {
479                write!(
480                    f,
481                    "The Strong Session Serializable isolation level may exhibit consistency violations when reading from catalog objects",
482                )
483            }
484            AdapterNotice::BadStartupSetting { name, reason } => {
485                write!(f, "startup setting {name} not set: {reason}")
486            }
487            AdapterNotice::RbacUserDisabled => {
488                write!(
489                    f,
490                    "RBAC is disabled so no role attributes or object ownership will be considered \
491                    when executing statements"
492                )
493            }
494            AdapterNotice::RoleMembershipAlreadyExists {
495                role_name,
496                member_name,
497            } => write!(
498                f,
499                "role \"{member_name}\" is already a member of role \"{role_name}\""
500            ),
501            AdapterNotice::RoleMembershipDoesNotExists {
502                role_name,
503                member_name,
504            } => write!(
505                f,
506                "role \"{member_name}\" is not a member of role \"{role_name}\""
507            ),
508            AdapterNotice::AutoRunOnCatalogServerCluster => write!(
509                f,
510                "query was automatically run on the \"mz_catalog_server\" cluster"
511            ),
512            AdapterNotice::AlterIndexOwner { name } => {
513                write!(f, "cannot change owner of {}", name.quoted())
514            }
515            AdapterNotice::CannotRevoke { object_description } => {
516                write!(f, "no privileges could be revoked for {object_description}")
517            }
518            AdapterNotice::NonApplicablePrivilegeTypes {
519                non_applicable_privileges,
520                object_description,
521            } => {
522                write!(
523                    f,
524                    "non-applicable privilege types {} for {}",
525                    non_applicable_privileges.to_error_string(),
526                    object_description,
527                )
528            }
529            AdapterNotice::PlanNotice(plan) => plan.fmt(f),
530            AdapterNotice::UnknownSessionDatabase(name) => {
531                write!(f, "session database {} does not exist", name.quoted())
532            }
533            AdapterNotice::OptimizerNotice { notice, hint: _ } => notice.fmt(f),
534            AdapterNotice::WebhookSourceCreated { url } => {
535                write!(f, "URL to POST data is '{url}'")
536            }
537            AdapterNotice::DroppedInUseIndex(DroppedInUseIndex {
538                index_name,
539                dependant_objects,
540            }) => {
541                write!(
542                    f,
543                    "index {} was dropped, but these objects still read from it: {}",
544                    index_name.quoted(),
545                    separated(", ", dependant_objects)
546                )
547            }
548            AdapterNotice::DroppedIndexReadByInFlightStatements(readers) => {
549                write!(
550                    f,
551                    "index {} is still read by transient dataflows for {}. Those dataflows end when their statements finish, and the index is maintained until then.",
552                    readers.index_name.quoted(),
553                    readers.describe_statements()
554                )
555            }
556            AdapterNotice::PerReplicaLogRead { log_names } => {
557                write!(
558                    f,
559                    "Queried introspection relations: {}. Unlike other objects in Materialize, results from querying these objects depend on the current values of the `cluster` and `cluster_replica` session variables.",
560                    log_names.join(", ")
561                )
562            }
563            AdapterNotice::VarDefaultUpdated { role, var_name } => {
564                let vars = match var_name {
565                    Some(name) => format!("variable {} was", name.quoted()),
566                    None => "variables were".to_string(),
567                };
568                let target = match role {
569                    Some(role_name) => role_name.quoted().to_string(),
570                    None => "the system".to_string(),
571                };
572                write!(
573                    f,
574                    "{vars} updated for {target}, this will have no effect on the current session"
575                )
576            }
577            AdapterNotice::StartupOnlyVarUpdated { var_name } => write!(
578                f,
579                "changes to {} only take effect when environmentd restarts",
580                var_name.quoted()
581            ),
582            AdapterNotice::Welcome(message) => message.fmt(f),
583            AdapterNotice::PlanInsights(message) => message.fmt(f),
584            AdapterNotice::ExecutionTime(time) => {
585                write!(
586                    f,
587                    "execution time: {:.3} ms",
588                    time.elapsed.as_secs_f64() * 1000.0
589                )?;
590                if matches!(time.kind, ExecutionTimeKind::Staged) {
591                    f.write_str(" (staged)")?;
592                }
593                Ok(())
594            }
595            AdapterNotice::IntrospectionClusterUsage => write!(
596                f,
597                "The mz_introspection cluster has been renamed to mz_catalog_server."
598            ),
599            AdapterNotice::AutoRouteIntrospectionQueriesUsage => write!(
600                f,
601                "The auto_route_introspection_queries variable has been renamed to auto_route_catalog_queries."
602            ),
603            AdapterNotice::SingleReplicaSourcesOnMultiReplicaCluster { cluster, sources } => {
604                // Keep the notice readable on clusters with many sources.
605                const MAX_LISTED_SOURCES: usize = 3;
606                write!(
607                    f,
608                    "cluster {} has more than one replica, but the following sources in it always \
609                     run on only the first replica: {}",
610                    cluster.quoted(),
611                    separated(
612                        ", ",
613                        sources.iter().take(MAX_LISTED_SOURCES).map(|n| n.quoted())
614                    ),
615                )?;
616                if sources.len() > MAX_LISTED_SOURCES {
617                    write!(f, ", and {} more", sources.len() - MAX_LISTED_SOURCES)?;
618                }
619                Ok(())
620            }
621            AdapterNotice::OidcGroupSyncReservedRole { group } => {
622                write!(
623                    f,
624                    "OIDC group \"{}\" maps to a reserved role name, skipping",
625                    group
626                )
627            }
628            AdapterNotice::OidcGroupSyncError { message } => {
629                write!(f, "OIDC group-to-role sync failed: {}", message)
630            }
631        }
632    }
633}
634
635#[derive(Clone, Debug)]
636pub struct DroppedInUseIndex {
637    pub index_name: String,
638    pub dependant_objects: Vec<String>,
639}
640
641/// One-shot dataflows that read from a dropped index, by the kind of statement that owns them.
642#[derive(Clone, Debug, Default)]
643pub struct InFlightIndexReaders {
644    pub index_name: String,
645    pub subscribes: usize,
646    pub copy_tos: usize,
647    pub selects: usize,
648    /// Dataflows the system installed itself, such as introspection subscribes.
649    pub system: usize,
650}
651
652impl InFlightIndexReaders {
653    fn describe_statements(&self) -> String {
654        fn part(count: usize, what: &str) -> Option<String> {
655            let plural = if count == 1 { "" } else { "s" };
656            (count > 0).then(|| format!("{count} in-progress {what}{plural}"))
657        }
658        [
659            part(self.subscribes, "SUBSCRIBE statement"),
660            part(self.copy_tos, "COPY TO statement"),
661            part(self.selects, "SELECT statement"),
662            part(self.system, "system dataflow"),
663        ]
664        .into_iter()
665        .flatten()
666        .join(", ")
667    }
668}
669
670impl From<PlanNotice> for AdapterNotice {
671    fn from(notice: PlanNotice) -> AdapterNotice {
672        AdapterNotice::PlanNotice(notice)
673    }
674}
675
676/// Time from bound-statement execution to its first available result.
677///
678/// Parsing, describing, and binding are excluded, except binding within SQL `EXECUTE`.
679/// Reads and writes use the same boundary. Subsequent row delivery and implicit commit
680/// are excluded. Work performed within execution, including an explicit `COMMIT`, is
681/// included.
682#[derive(Clone, Debug)]
683pub struct ExecutionTime {
684    pub(crate) kind: ExecutionTimeKind,
685    pub(crate) elapsed: Duration,
686}
687
688impl ExecutionTime {
689    /// The time of a statement that cannot return rows.
690    pub fn completed(elapsed: Duration) -> Self {
691        Self {
692            kind: ExecutionTimeKind::Completed,
693            elapsed,
694        }
695    }
696}
697
698/// Where the interval of an [`ExecutionTime`] ends.
699#[derive(Clone, Copy, Debug)]
700pub(crate) enum ExecutionTimeKind {
701    /// A statement that returns rows has its first row ready. Delivering the rows is excluded.
702    FirstRow,
703    /// A statement that could return rows finished without any.
704    EmptyResult,
705    /// A statement that cannot return rows, such as `SET`, finished executing.
706    Completed,
707    /// The transaction still holds work for a later commit, which the time excludes.
708    Staged,
709}
710
711impl ExecutionTimeKind {
712    fn name(self) -> &'static str {
713        match self {
714            Self::FirstRow => "first_row",
715            Self::EmptyResult => "empty_result",
716            Self::Completed => "completed",
717            Self::Staged => "staged",
718        }
719    }
720}