Skip to main content

mz_adapter/
error.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::collections::{BTreeMap, BTreeSet};
11use std::error::Error;
12use std::fmt;
13use std::num::TryFromIntError;
14
15use dec::TryFromDecimalError;
16use itertools::Itertools;
17use mz_catalog::builtin::MZ_CATALOG_SERVER_CLUSTER;
18use mz_compute_client::controller::error as compute_error;
19use mz_compute_client::controller::error::InstanceMissing;
20
21use mz_compute_types::ComputeInstanceId;
22use mz_expr::EvalError;
23use mz_ore::error::ErrorExt;
24use mz_ore::stack::RecursionLimitError;
25use mz_ore::str::StrExt;
26use mz_pgwire_common::{ErrorResponse, Severity};
27use mz_repr::adt::timestamp::TimestampError;
28use mz_repr::explain::ExplainError;
29use mz_repr::{ColumnDiff, ColumnName, KeyDiff, NotNullViolation, RelationDescDiff, Timestamp};
30use mz_sql::plan::PlanError;
31use mz_sql::rbac;
32use mz_sql::session::vars::VarError;
33use mz_storage_types::connections::ConnectionValidationError;
34use mz_storage_types::controller::StorageError;
35use mz_storage_types::errors::CollectionMissing;
36use smallvec::SmallVec;
37use timely::progress::Antichain;
38use tokio::sync::oneshot;
39use tokio_postgres::error::SqlState;
40
41use crate::coord::NetworkPolicyError;
42use crate::optimize::OptimizerError;
43use crate::peek_client::CollectionLookupError;
44
45/// Errors that can occur in the coordinator.
46#[derive(Debug)]
47pub enum AdapterError {
48    /// A `SUBSCRIBE` was requested whose `UP TO` bound precedes its `as_of` timestamp
49    AbsurdSubscribeBounds {
50        as_of: mz_repr::Timestamp,
51        up_to: mz_repr::Timestamp,
52    },
53    /// Attempted to use a potentially ambiguous column reference expression with a system table.
54    // We don't allow this until https://github.com/MaterializeInc/database-issues/issues/4824 is
55    // resolved because it prevents us from adding columns to system tables.
56    AmbiguousSystemColumnReference,
57    /// An error occurred in a catalog operation.
58    Catalog(mz_catalog::memory::error::Error),
59    /// 1. The cached plan or descriptor changed,
60    /// 2. or some dependency of a statement disappeared during sequencing.
61    /// TODO(ggevay): we should refactor 2. usages to use `ConcurrentDependencyDrop` instead
62    /// (e.g., in MV sequencing)
63    ChangedPlan(String),
64    /// The cursor already exists.
65    DuplicateCursor(String),
66    /// An error while evaluating an expression.
67    Eval(EvalError),
68    /// An error occurred while planning the statement.
69    Explain(ExplainError),
70    /// The ID allocator exhausted all valid IDs.
71    IdExhaustionError,
72    /// Unexpected internal state was encountered.
73    Internal(String),
74    /// Attempted to read from log sources of a replica with disabled introspection.
75    IntrospectionDisabled {
76        log_names: Vec<String>,
77    },
78    /// Attempted to create an object dependent on log sources that doesn't support
79    /// log dependencies.
80    InvalidLogDependency {
81        object_type: String,
82        log_names: Vec<String>,
83    },
84    /// No such cluster replica size has been configured.
85    InvalidClusterReplicaAz {
86        az: String,
87        expected: Vec<String>,
88    },
89    /// SET TRANSACTION ISOLATION LEVEL was called in the middle of a transaction.
90    InvalidSetIsolationLevel,
91    /// SET cluster was called in the middle of a transaction.
92    InvalidSetCluster,
93    /// No such storage instance size has been configured.
94    InvalidStorageClusterSize {
95        size: String,
96        expected: Vec<String>,
97    },
98    /// Creating a source or sink without specifying its size is forbidden.
99    SourceOrSinkSizeRequired {
100        expected: Vec<String>,
101    },
102    /// The selection value for a table mutation operation refers to an invalid object.
103    InvalidTableMutationSelection {
104        /// The full name of the problematic object (e.g. a source or source-export table).
105        object_name: String,
106        /// Human-readable type of the object (e.g. "source", "source-export table").
107        object_type: String,
108    },
109    /// Expression violated a column's constraint
110    ConstraintViolation(NotNullViolation),
111    /// An error occurred while decoding COPY data.
112    CopyFormatError(String),
113    /// Transaction cluster was dropped in the middle of a transaction.
114    ConcurrentClusterDrop,
115    /// A dependency was dropped while sequencing a statement.
116    ConcurrentDependencyDrop {
117        dependency_kind: &'static str,
118        dependency_id: String,
119    },
120    CollectionUnreadable {
121        id: String,
122    },
123    /// Target cluster has no replicas to service query.
124    NoClusterReplicasAvailable {
125        name: String,
126        is_managed: bool,
127    },
128    /// The named operation cannot be run in a transaction.
129    OperationProhibitsTransaction(String),
130    /// The named operation requires an active transaction.
131    OperationRequiresTransaction(String),
132    /// An error occurred while planning the statement.
133    PlanError(PlanError),
134    /// The named prepared statement already exists.
135    PreparedStatementExists(String),
136    /// Wrapper around parsing error
137    ParseError(mz_sql_parser::parser::ParserStatementError),
138    /// The transaction is in read-only mode.
139    ReadOnlyTransaction,
140    /// The transaction in in read-only mode and a read already occurred.
141    ReadWriteUnavailable,
142    /// The recursion limit of some operation was exceeded.
143    RecursionLimit(RecursionLimitError),
144    /// A query in a transaction referenced a relation outside the first query's
145    /// time domain.
146    RelationOutsideTimeDomain {
147        relations: Vec<String>,
148        names: Vec<String>,
149    },
150    /// A query tried to create more resources than is allowed in the system configuration.
151    ResourceExhaustion {
152        resource_type: String,
153        limit_name: String,
154        desired: String,
155        limit: String,
156        current: String,
157    },
158    /// Result size of a query is too large.
159    ResultSize(String),
160    /// The specified feature is not permitted in safe mode.
161    SafeModeViolation(String),
162    /// The current transaction had the wrong set of write locks.
163    WrongSetOfLocks,
164    /// Waiting on a query timed out.
165    ///
166    /// Note this differs slightly from PG's implementation/semantics.
167    StatementTimeout,
168    /// The user canceled the query
169    Canceled,
170    /// An idle session in a transaction has timed out.
171    IdleInTransactionSessionTimeout,
172    /// The transaction is in single-subscribe mode.
173    SubscribeOnlyTransaction,
174    /// An error occurred in the optimizer.
175    Optimizer(OptimizerError),
176    /// A query depends on items which are not allowed to be referenced from the current cluster.
177    UnallowedOnCluster {
178        depends_on: SmallVec<[String; 2]>,
179        cluster: String,
180    },
181    /// A user tried to perform an action that they were unauthorized to do.
182    Unauthorized(rbac::UnauthorizedError),
183    /// The named cursor does not exist.
184    UnknownCursor(String),
185    /// The named role does not exist.
186    UnknownLoginRole(String),
187    UnknownPreparedStatement(String),
188    /// The named cluster replica does not exist.
189    UnknownClusterReplica {
190        cluster_name: String,
191        replica_name: String,
192    },
193    /// The named setting does not exist.
194    UnrecognizedConfigurationParam(String),
195    /// A generic error occurred.
196    //
197    // TODO(benesch): convert all those errors to structured errors.
198    Unstructured(anyhow::Error),
199    /// The named feature is not supported and will (probably) not be.
200    Unsupported(&'static str),
201    /// Some feature isn't available for a (potentially opaque) reason.
202    /// For example, in cloud Self-Managed auth features aren't available,
203    /// but we don't want to mention self managed auth.
204    UnavailableFeature {
205        feature: String,
206        docs: Option<String>,
207    },
208    /// Attempted to read from log sources without selecting a target replica.
209    UntargetedLogRead {
210        log_names: Vec<String>,
211    },
212    /// The transaction is in write-only mode.
213    WriteOnlyTransaction,
214    /// The transaction can only execute a single statement.
215    SingleStatementTransaction,
216    /// The transaction can only execute simple DDL.
217    DDLOnlyTransaction,
218    /// Another session modified the Catalog while this transaction was open.
219    DDLTransactionRace,
220    /// An error occurred in the storage layer
221    Storage(mz_storage_types::controller::StorageError),
222    /// An error occurred in the compute layer
223    Compute(anyhow::Error),
224    /// An error in the orchestrator layer
225    Orchestrator(anyhow::Error),
226    /// A statement tried to drop a role that had dependent objects.
227    ///
228    /// The map keys are role names and values are detailed error messages.
229    DependentObject(BTreeMap<String, Vec<String>>),
230    /// When performing an `ALTER` of some variety, re-planning the statement
231    /// errored.
232    InvalidAlter(&'static str, PlanError),
233    /// An error occurred while validating a connection.
234    ConnectionValidation(ConnectionValidationError),
235    /// We refuse to create the materialized view, because it would never be refreshed, so it would
236    /// never be queryable. This can happen when the only specified refreshes are further back in
237    /// the past than the initial compaction window of the materialized view.
238    MaterializedViewWouldNeverRefresh(Timestamp, Timestamp),
239    /// A CREATE MATERIALIZED VIEW statement tried to acquire a read hold at a REFRESH AT time,
240    /// but was unable to get a precise read hold.
241    InputNotReadableAtRefreshAtTime(Timestamp, Antichain<Timestamp>),
242    /// A humanized version of [`StorageError::RtrTimeout`].
243    RtrTimeout(String),
244    /// A humanized version of [`StorageError::RtrDropFailure`].
245    RtrDropFailure(String),
246    /// The collection requested to be sinked cannot be read at any timestamp
247    UnreadableSinkCollection,
248    /// User sessions have been blocked.
249    UserSessionsDisallowed,
250    /// This use session has been denied by a NetworkPolicy.
251    NetworkPolicyDenied(NetworkPolicyError),
252    /// Something attempted a write (to catalog, storage, tables, etc.) while in
253    /// read-only mode.
254    ReadOnly,
255    AlterClusterTimeout,
256    AlterClusterWhilePendingReplicas,
257    AuthenticationError(AuthenticationError),
258    /// Schema of a replacement is incompatible with the target.
259    ReplacementSchemaMismatch(RelationDescDiff),
260    /// Attempt to apply a replacement to a sealed materialized view.
261    ReplaceMaterializedViewSealed {
262        name: String,
263    },
264    /// Could not find a valid timestamp satisfying all constraints.
265    ImpossibleTimestampConstraints {
266        constraints: String,
267    },
268    /// OIDC group-to-role sync failed and strict mode is enabled.
269    OidcGroupSyncFailed(String),
270}
271
272#[derive(Debug, thiserror::Error)]
273pub enum AuthenticationError {
274    #[error("invalid credentials")]
275    InvalidCredentials,
276    #[error("role is not allowed to login")]
277    NonLogin,
278    #[error("role does not exist")]
279    RoleNotFound,
280    #[error("password is required")]
281    PasswordRequired,
282}
283
284impl AdapterError {
285    pub fn into_response(self, severity: Severity) -> ErrorResponse {
286        ErrorResponse {
287            severity,
288            code: self.code(),
289            message: self.to_string(),
290            detail: self.detail(),
291            hint: self.hint(),
292            position: self.position(),
293        }
294    }
295
296    pub fn position(&self) -> Option<usize> {
297        match self {
298            AdapterError::ParseError(err) => Some(err.error.pos),
299            _ => None,
300        }
301    }
302
303    /// Reports additional details about the error, if any are available.
304    pub fn detail(&self) -> Option<String> {
305        match self {
306            AdapterError::AmbiguousSystemColumnReference => {
307                Some("This is a current limitation in Materialize".into())
308            }
309            AdapterError::Catalog(c) => c.detail(),
310            AdapterError::Eval(e) => e.detail(),
311            AdapterError::RelationOutsideTimeDomain { relations, names } => Some(format!(
312                "The following relations in the query are outside the transaction's time domain:\n{}\n{}",
313                relations
314                    .iter()
315                    .map(|r| r.quoted().to_string())
316                    .collect::<Vec<_>>()
317                    .join("\n"),
318                match names.is_empty() {
319                    true => "No relations are available.".to_string(),
320                    false => format!(
321                        "Only the following relations are available:\n{}",
322                        names
323                            .iter()
324                            .map(|name| name.quoted().to_string())
325                            .collect::<Vec<_>>()
326                            .join("\n")
327                    ),
328                }
329            )),
330            AdapterError::SourceOrSinkSizeRequired { .. } => Some(
331                "Either specify the cluster that will maintain this object via IN CLUSTER or \
332                specify size via SIZE option."
333                    .into(),
334            ),
335            AdapterError::InvalidTableMutationSelection {
336                object_name,
337                object_type,
338            } => Some(format!(
339                "{object_type} '{}' may not be used in this operation; \
340                     the selection may refer to views and materialized views, but transitive \
341                     dependencies must not include sources or source-export tables",
342                object_name.quoted()
343            )),
344            AdapterError::SafeModeViolation(_) => Some(
345                "The Materialize server you are connected to is running in \
346                 safe mode, which limits the features that are available."
347                    .into(),
348            ),
349            AdapterError::IntrospectionDisabled { log_names }
350            | AdapterError::UntargetedLogRead { log_names } => Some(format!(
351                "The query references the following log sources:\n    {}",
352                log_names.join("\n    "),
353            )),
354            AdapterError::InvalidLogDependency { log_names, .. } => Some(format!(
355                "The object depends on the following log sources:\n    {}",
356                log_names.join("\n    "),
357            )),
358            AdapterError::PlanError(e) => e.detail(),
359            AdapterError::Unauthorized(unauthorized) => unauthorized.detail(),
360            AdapterError::DependentObject(dependent_objects) => Some(
361                dependent_objects
362                    .iter()
363                    .map(|(role_name, err_msgs)| {
364                        err_msgs
365                            .iter()
366                            .map(|err_msg| format!("{role_name}: {err_msg}"))
367                            .join("\n")
368                    })
369                    .join("\n"),
370            ),
371            AdapterError::Storage(storage_error) => storage_error
372                .source()
373                .map(|source_error| source_error.to_string_with_causes()),
374            AdapterError::ReadOnlyTransaction => Some(
375                "SELECT queries cannot be combined with other query types, including SUBSCRIBE."
376                    .into(),
377            ),
378            AdapterError::InvalidAlter(_, e) => e.detail(),
379            AdapterError::Optimizer(e) => e.detail(),
380            AdapterError::ConnectionValidation(e) => e.detail(),
381            AdapterError::MaterializedViewWouldNeverRefresh(last_refresh, earliest_possible) => {
382                Some(format!(
383                    "The specified last refresh is at {}, while the earliest possible time to compute the materialized \
384                    view is {}.",
385                    last_refresh, earliest_possible,
386                ))
387            }
388            AdapterError::UnallowedOnCluster { cluster, .. } => {
389                (cluster == MZ_CATALOG_SERVER_CLUSTER.name).then(|| {
390                    format!(
391                        "The transaction is executing on the \
392                        {cluster} cluster, maybe having been routed \
393                        there by the first statement in the transaction."
394                    )
395                })
396            }
397            AdapterError::InputNotReadableAtRefreshAtTime(oracle_read_ts, least_valid_read) => {
398                Some(format!(
399                    "The requested REFRESH AT time is {}, \
400                    but not all input collections are readable earlier than [{}].",
401                    oracle_read_ts,
402                    if least_valid_read.len() == 1 {
403                        format!(
404                            "{}",
405                            least_valid_read
406                                .as_option()
407                                .expect("antichain contains exactly 1 timestamp")
408                        )
409                    } else {
410                        // This can't occur currently
411                        format!("{:?}", least_valid_read)
412                    }
413                ))
414            }
415            AdapterError::RtrTimeout(name) => Some(format!(
416                "{name} failed to ingest data up to the real-time recency point"
417            )),
418            AdapterError::RtrDropFailure(name) => Some(format!(
419                "{name} dropped before ingesting data to the real-time recency point"
420            )),
421            AdapterError::UserSessionsDisallowed => {
422                Some("Your organization has been blocked. Please contact support.".to_string())
423            }
424            AdapterError::NetworkPolicyDenied(reason) => Some(format!("{reason}.")),
425            AdapterError::ReplacementSchemaMismatch(diff) => {
426                let mut lines: Vec<_> = diff.column_diffs.iter().map(|(idx, diff)| {
427                    let pos = idx + 1;
428                    match diff {
429                        ColumnDiff::Missing { name } => {
430                            let name = name.as_str().quoted();
431                            format!("missing column {name} at position {pos}")
432                        }
433                        ColumnDiff::Extra { name } => {
434                            let name = name.as_str().quoted();
435                            format!("extra column {name} at position {pos}")
436                        }
437                        ColumnDiff::TypeMismatch { name, left, right } => {
438                            let name = name.as_str().quoted();
439                            format!("column {name} at position {pos}: type mismatch (target: {left:?}, replacement: {right:?})")
440                        }
441                        ColumnDiff::NullabilityMismatch { name, left, right } => {
442                            let name = name.as_str().quoted();
443                            let left = if *left { "NULL" } else { "NOT NULL" };
444                            let right = if *right { "NULL" } else { "NOT NULL" };
445                            format!("column {name} at position {pos}: nullability mismatch (target: {left}, replacement: {right})")
446                        }
447                        ColumnDiff::NameMismatch { left, right } => {
448                            let left = left.as_str().quoted();
449                            let right = right.as_str().quoted();
450                            format!("column at position {pos}: name mismatch (target: {left}, replacement: {right})")
451                        }
452                    }
453                }).collect();
454
455                if let Some(KeyDiff { left, right }) = &diff.key_diff {
456                    let format_keys = |keys: &BTreeSet<Vec<ColumnName>>| {
457                        if keys.is_empty() {
458                            "(none)".to_string()
459                        } else {
460                            keys.iter()
461                                .map(|key| {
462                                    let cols = key.iter().map(|c| c.as_str()).join(", ");
463                                    format!("{{{cols}}}")
464                                })
465                                .join(", ")
466                        }
467                    };
468                    lines.push(format!(
469                        "keys differ (target: {}, replacement: {})",
470                        format_keys(left),
471                        format_keys(right)
472                    ));
473                }
474                Some(lines.join("\n"))
475            }
476            AdapterError::ReplaceMaterializedViewSealed { .. } => Some(
477                "The materialized view has already computed its output until the end of time, \
478                 so replacing its definition would have no effect."
479                    .into(),
480            ),
481            AdapterError::ImpossibleTimestampConstraints { constraints } => {
482                Some(format!("Constraints:\n{}", constraints))
483            }
484            _ => None,
485        }
486    }
487
488    /// Reports a hint for the user about how the error could be fixed.
489    pub fn hint(&self) -> Option<String> {
490        match self {
491            AdapterError::AmbiguousSystemColumnReference => Some(
492                "Rewrite the view to refer to all columns by name. Expand all wildcards and \
493                convert all NATURAL JOINs to USING joins."
494                    .to_string(),
495            ),
496            AdapterError::Catalog(c) => c.hint(),
497            AdapterError::Eval(e) => e.hint(),
498            AdapterError::InvalidClusterReplicaAz { expected, az: _ } => {
499                Some(if expected.is_empty() {
500                    "No availability zones configured; do not specify AVAILABILITY ZONE".into()
501                } else {
502                    format!("Valid availability zones are: {}", expected.join(", "))
503                })
504            }
505            AdapterError::InvalidStorageClusterSize { expected, .. } => {
506                Some(format!("Valid sizes are: {}", expected.join(", ")))
507            }
508            AdapterError::SourceOrSinkSizeRequired { expected } => Some(format!(
509                "Try choosing one of the smaller sizes to start. Available sizes: {}",
510                expected.join(", ")
511            )),
512            AdapterError::NoClusterReplicasAvailable { is_managed, .. } => {
513                Some(if *is_managed {
514                    "Use ALTER CLUSTER to adjust the replication factor of the cluster. \
515                    Example:`ALTER CLUSTER <cluster-name> SET (REPLICATION FACTOR 1)`".into()
516                } else {
517                    "Use CREATE CLUSTER REPLICA to attach cluster replicas to the cluster".into()
518                })
519            }
520            AdapterError::UntargetedLogRead { .. } => Some(
521                "Use `SET cluster_replica = <replica-name>` to target a specific replica in the \
522                 active cluster. Note that subsequent queries will only be answered by \
523                 the selected replica, which might reduce availability. To undo the replica \
524                 selection, use `RESET cluster_replica`."
525                    .into(),
526            ),
527            AdapterError::ResourceExhaustion { resource_type, .. } => Some(format!(
528                "Drop an existing {resource_type} or contact support to request a limit increase."
529            )),
530            AdapterError::StatementTimeout => Some(
531                "Consider increasing the maximum allowed statement duration for this session by \
532                 setting the statement_timeout session variable. For example, `SET \
533                 statement_timeout = '120s'`."
534                    .into(),
535            ),
536            AdapterError::PlanError(e) => e.hint(),
537            AdapterError::UnallowedOnCluster { cluster, .. } => {
538                (cluster != MZ_CATALOG_SERVER_CLUSTER.name).then(||
539                    "Use `SET CLUSTER = <cluster-name>` to change your cluster and re-run the query."
540                    .to_string()
541                )
542            }
543            AdapterError::InvalidAlter(_, e) => e.hint(),
544            AdapterError::Optimizer(e) => e.hint(),
545            AdapterError::ConnectionValidation(e) => e.hint(),
546            AdapterError::InputNotReadableAtRefreshAtTime(_, _) => Some(
547                "You can use `REFRESH AT greatest(mz_now(), <explicit timestamp>)` to refresh \
548                 either at the explicitly specified timestamp, or now if the given timestamp would \
549                 be in the past.".to_string()
550            ),
551            AdapterError::AlterClusterTimeout => Some(
552                "Consider increasing the timeout duration in the alter cluster statement.".into(),
553            ),
554            AdapterError::DDLTransactionRace => Some(
555                "Currently, DDL transactions fail when any other DDL happens concurrently, \
556                 even on unrelated schemas/clusters.".into()
557            ),
558            AdapterError::CollectionUnreadable { .. } => Some(
559                "This could be because the collection has recently been dropped.".into()
560            ),
561            _ => None,
562        }
563    }
564
565    pub fn code(&self) -> SqlState {
566        // TODO(benesch): we should only use `SqlState::INTERNAL_ERROR` for
567        // those errors that are truly internal errors. At the moment we have
568        // a various classes of uncategorized errors that use this error code
569        // inappropriately.
570        match self {
571            // DATA_EXCEPTION to match what Postgres returns for degenerate
572            // range bounds
573            AdapterError::AbsurdSubscribeBounds { .. } => SqlState::DATA_EXCEPTION,
574            AdapterError::AmbiguousSystemColumnReference => SqlState::FEATURE_NOT_SUPPORTED,
575            AdapterError::Catalog(e) => match &e.kind {
576                mz_catalog::memory::error::ErrorKind::VarError(e) => match e {
577                    VarError::ConstrainedParameter { .. } => SqlState::INVALID_PARAMETER_VALUE,
578                    VarError::FixedValueParameter { .. } => SqlState::INVALID_PARAMETER_VALUE,
579                    VarError::InvalidParameterType { .. } => SqlState::INVALID_PARAMETER_VALUE,
580                    VarError::InvalidParameterValue { .. } => SqlState::INVALID_PARAMETER_VALUE,
581                    VarError::ReadOnlyParameter(_) => SqlState::CANT_CHANGE_RUNTIME_PARAM,
582                    VarError::UnknownParameter(_) => SqlState::UNDEFINED_OBJECT,
583                    VarError::RequiresUnsafeMode { .. } => SqlState::CANT_CHANGE_RUNTIME_PARAM,
584                    VarError::RequiresFeatureFlag { .. } => SqlState::CANT_CHANGE_RUNTIME_PARAM,
585                },
586                _ => SqlState::INTERNAL_ERROR,
587            },
588            AdapterError::ChangedPlan(_) => SqlState::FEATURE_NOT_SUPPORTED,
589            AdapterError::DuplicateCursor(_) => SqlState::DUPLICATE_CURSOR,
590            AdapterError::Eval(EvalError::CharacterNotValidForEncoding(_)) => {
591                SqlState::PROGRAM_LIMIT_EXCEEDED
592            }
593            AdapterError::Eval(EvalError::CharacterTooLargeForEncoding(_)) => {
594                SqlState::PROGRAM_LIMIT_EXCEEDED
595            }
596            AdapterError::Eval(EvalError::LengthTooLarge) => SqlState::PROGRAM_LIMIT_EXCEEDED,
597            AdapterError::Eval(EvalError::NullCharacterNotPermitted) => {
598                SqlState::PROGRAM_LIMIT_EXCEEDED
599            }
600            AdapterError::Eval(_) => SqlState::INTERNAL_ERROR,
601            AdapterError::Explain(_) => SqlState::INTERNAL_ERROR,
602            AdapterError::IdExhaustionError => SqlState::INTERNAL_ERROR,
603            AdapterError::Internal(_) => SqlState::INTERNAL_ERROR,
604            AdapterError::IntrospectionDisabled { .. } => SqlState::FEATURE_NOT_SUPPORTED,
605            AdapterError::InvalidLogDependency { .. } => SqlState::FEATURE_NOT_SUPPORTED,
606            AdapterError::InvalidClusterReplicaAz { .. } => SqlState::FEATURE_NOT_SUPPORTED,
607            AdapterError::InvalidSetIsolationLevel => SqlState::ACTIVE_SQL_TRANSACTION,
608            AdapterError::InvalidSetCluster => SqlState::ACTIVE_SQL_TRANSACTION,
609            AdapterError::InvalidStorageClusterSize { .. } => SqlState::FEATURE_NOT_SUPPORTED,
610            AdapterError::SourceOrSinkSizeRequired { .. } => SqlState::FEATURE_NOT_SUPPORTED,
611            AdapterError::InvalidTableMutationSelection { .. } => {
612                SqlState::INVALID_TRANSACTION_STATE
613            }
614            AdapterError::ConstraintViolation(NotNullViolation(_)) => SqlState::NOT_NULL_VIOLATION,
615            AdapterError::CopyFormatError(_) => SqlState::BAD_COPY_FILE_FORMAT,
616            AdapterError::ConcurrentClusterDrop => SqlState::INVALID_TRANSACTION_STATE,
617            AdapterError::ConcurrentDependencyDrop { .. } => SqlState::UNDEFINED_OBJECT,
618            AdapterError::CollectionUnreadable { .. } => SqlState::NO_DATA_FOUND,
619            AdapterError::NoClusterReplicasAvailable { .. } => SqlState::FEATURE_NOT_SUPPORTED,
620            AdapterError::OperationProhibitsTransaction(_) => SqlState::ACTIVE_SQL_TRANSACTION,
621            AdapterError::OperationRequiresTransaction(_) => SqlState::NO_ACTIVE_SQL_TRANSACTION,
622            AdapterError::ParseError(_) => SqlState::SYNTAX_ERROR,
623            AdapterError::PlanError(PlanError::InvalidSchemaName) => SqlState::INVALID_SCHEMA_NAME,
624            AdapterError::PlanError(PlanError::ColumnAlreadyExists { .. }) => {
625                SqlState::DUPLICATE_COLUMN
626            }
627            AdapterError::PlanError(PlanError::UnknownParameter(_)) => {
628                SqlState::UNDEFINED_PARAMETER
629            }
630            AdapterError::PlanError(PlanError::ParameterNotAllowed(_)) => {
631                SqlState::UNDEFINED_PARAMETER
632            }
633            AdapterError::PlanError(_) => SqlState::INTERNAL_ERROR,
634            AdapterError::PreparedStatementExists(_) => SqlState::DUPLICATE_PSTATEMENT,
635            AdapterError::ReadOnlyTransaction => SqlState::READ_ONLY_SQL_TRANSACTION,
636            AdapterError::ReadWriteUnavailable => SqlState::INVALID_TRANSACTION_STATE,
637            AdapterError::SingleStatementTransaction => SqlState::INVALID_TRANSACTION_STATE,
638            AdapterError::WrongSetOfLocks => SqlState::LOCK_NOT_AVAILABLE,
639            AdapterError::StatementTimeout => SqlState::QUERY_CANCELED,
640            AdapterError::Canceled => SqlState::QUERY_CANCELED,
641            AdapterError::IdleInTransactionSessionTimeout => {
642                SqlState::IDLE_IN_TRANSACTION_SESSION_TIMEOUT
643            }
644            AdapterError::RecursionLimit(_) => SqlState::INTERNAL_ERROR,
645            AdapterError::RelationOutsideTimeDomain { .. } => SqlState::INVALID_TRANSACTION_STATE,
646            AdapterError::ResourceExhaustion { .. } => SqlState::INSUFFICIENT_RESOURCES,
647            AdapterError::ResultSize(_) => SqlState::OUT_OF_MEMORY,
648            AdapterError::SafeModeViolation(_) => SqlState::INTERNAL_ERROR,
649            AdapterError::SubscribeOnlyTransaction => SqlState::INVALID_TRANSACTION_STATE,
650            AdapterError::Optimizer(e) => match e {
651                OptimizerError::PlanError(PlanError::InvalidSchemaName) => {
652                    SqlState::INVALID_SCHEMA_NAME
653                }
654                OptimizerError::PlanError(PlanError::ColumnAlreadyExists { .. }) => {
655                    SqlState::DUPLICATE_COLUMN
656                }
657                OptimizerError::PlanError(PlanError::UnknownParameter(_)) => {
658                    SqlState::UNDEFINED_PARAMETER
659                }
660                OptimizerError::PlanError(PlanError::ParameterNotAllowed(_)) => {
661                    SqlState::UNDEFINED_PARAMETER
662                }
663                OptimizerError::PlanError(_) => SqlState::INTERNAL_ERROR,
664                OptimizerError::RecursionLimitError(e) => {
665                    AdapterError::RecursionLimit(e.clone()).code() // Delegate to outer
666                }
667                OptimizerError::Internal(s) => {
668                    AdapterError::Internal(s.clone()).code() // Delegate to outer
669                }
670                OptimizerError::EvalError(e) => {
671                    AdapterError::Eval(e.clone()).code() // Delegate to outer
672                }
673                OptimizerError::TransformError(_) => SqlState::INTERNAL_ERROR,
674                OptimizerError::UnmaterializableFunction(_) => SqlState::FEATURE_NOT_SUPPORTED,
675                OptimizerError::UncallableFunction { .. } => SqlState::FEATURE_NOT_SUPPORTED,
676                OptimizerError::UnsupportedTemporalExpression(_) => SqlState::FEATURE_NOT_SUPPORTED,
677                // This should be handled by peek optimization, so it's an internal error if it
678                // reaches the user.
679                OptimizerError::InternalUnsafeMfpPlan(_) => SqlState::INTERNAL_ERROR,
680            },
681            AdapterError::UnallowedOnCluster { .. } => {
682                SqlState::S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED
683            }
684            AdapterError::Unauthorized(_) => SqlState::INSUFFICIENT_PRIVILEGE,
685            AdapterError::UnknownCursor(_) => SqlState::INVALID_CURSOR_NAME,
686            AdapterError::UnknownPreparedStatement(_) => SqlState::UNDEFINED_PSTATEMENT,
687            AdapterError::UnknownLoginRole(_) => SqlState::INVALID_AUTHORIZATION_SPECIFICATION,
688            AdapterError::UnknownClusterReplica { .. } => SqlState::UNDEFINED_OBJECT,
689            AdapterError::UnrecognizedConfigurationParam(_) => SqlState::UNDEFINED_OBJECT,
690            AdapterError::Unsupported(..) => SqlState::FEATURE_NOT_SUPPORTED,
691            AdapterError::UnavailableFeature { .. } => SqlState::FEATURE_NOT_SUPPORTED,
692            AdapterError::Unstructured(_) => SqlState::INTERNAL_ERROR,
693            AdapterError::UntargetedLogRead { .. } => SqlState::FEATURE_NOT_SUPPORTED,
694            AdapterError::DDLTransactionRace => SqlState::T_R_SERIALIZATION_FAILURE,
695            // It's not immediately clear which error code to use here because a
696            // "write-only transaction", "single table write transaction", or "ddl only
697            // transaction" are not things in Postgres. This error code is the generic "bad txn
698            // thing" code, so it's probably the best choice.
699            AdapterError::WriteOnlyTransaction => SqlState::INVALID_TRANSACTION_STATE,
700            AdapterError::DDLOnlyTransaction => SqlState::INVALID_TRANSACTION_STATE,
701            AdapterError::Storage(_) | AdapterError::Compute(_) | AdapterError::Orchestrator(_) => {
702                SqlState::INTERNAL_ERROR
703            }
704            AdapterError::DependentObject(_) => SqlState::DEPENDENT_OBJECTS_STILL_EXIST,
705            AdapterError::InvalidAlter(_, _) => SqlState::FEATURE_NOT_SUPPORTED,
706            AdapterError::ConnectionValidation(_) => SqlState::SYSTEM_ERROR,
707            // `DATA_EXCEPTION`, similarly to `AbsurdSubscribeBounds`.
708            AdapterError::MaterializedViewWouldNeverRefresh(_, _) => SqlState::DATA_EXCEPTION,
709            AdapterError::InputNotReadableAtRefreshAtTime(_, _) => SqlState::DATA_EXCEPTION,
710            AdapterError::RtrTimeout(_) => SqlState::QUERY_CANCELED,
711            AdapterError::RtrDropFailure(_) => SqlState::UNDEFINED_OBJECT,
712            AdapterError::UnreadableSinkCollection => SqlState::from_code("MZ009"),
713            AdapterError::UserSessionsDisallowed => SqlState::from_code("MZ010"),
714            AdapterError::NetworkPolicyDenied(_) => SqlState::from_code("MZ011"),
715            // In read-only mode all transactions are implicitly read-only
716            // transactions.
717            AdapterError::ReadOnly => SqlState::READ_ONLY_SQL_TRANSACTION,
718            AdapterError::AlterClusterTimeout => SqlState::QUERY_CANCELED,
719            AdapterError::AlterClusterWhilePendingReplicas => SqlState::OBJECT_IN_USE,
720            AdapterError::ReplacementSchemaMismatch(_) => SqlState::FEATURE_NOT_SUPPORTED,
721            AdapterError::AuthenticationError(AuthenticationError::InvalidCredentials) => {
722                SqlState::INVALID_PASSWORD
723            }
724            AdapterError::AuthenticationError(_) => SqlState::INVALID_AUTHORIZATION_SPECIFICATION,
725            AdapterError::ReplaceMaterializedViewSealed { .. } => {
726                SqlState::OBJECT_NOT_IN_PREREQUISITE_STATE
727            }
728            // similar to AbsurdSubscribeBounds
729            AdapterError::ImpossibleTimestampConstraints { .. } => SqlState::DATA_EXCEPTION,
730            AdapterError::OidcGroupSyncFailed(_) => SqlState::INTERNAL_ERROR,
731        }
732    }
733
734    pub fn internal<E: std::fmt::Display>(context: &str, e: E) -> AdapterError {
735        AdapterError::Internal(format!("{context}: {e}"))
736    }
737
738    // We don't want the following error conversions to `ConcurrentDependencyDrop` to happen
739    // automatically, because it might depend on the context whether `ConcurrentDependencyDrop`
740    // is appropriate, so we want to make the conversion target explicit at the call site.
741    // For example, maybe we get an `InstanceMissing` if the user specifies a non-existing cluster,
742    // in which case `ConcurrentDependencyDrop` would not be appropriate.
743
744    pub fn concurrent_dependency_drop_from_instance_missing(e: InstanceMissing) -> Self {
745        AdapterError::ConcurrentDependencyDrop {
746            dependency_kind: "cluster",
747            dependency_id: e.0.to_string(),
748        }
749    }
750
751    pub fn concurrent_dependency_drop_from_collection_missing(e: CollectionMissing) -> Self {
752        AdapterError::ConcurrentDependencyDrop {
753            dependency_kind: "collection",
754            dependency_id: e.0.to_string(),
755        }
756    }
757
758    pub fn concurrent_dependency_drop_from_collection_lookup_error(
759        e: CollectionLookupError,
760        compute_instance: ComputeInstanceId,
761    ) -> Self {
762        match e {
763            CollectionLookupError::InstanceMissing(id) => AdapterError::ConcurrentDependencyDrop {
764                dependency_kind: "cluster",
765                dependency_id: id.to_string(),
766            },
767            CollectionLookupError::CollectionMissing(id) => {
768                AdapterError::ConcurrentDependencyDrop {
769                    dependency_kind: "collection",
770                    dependency_id: id.to_string(),
771                }
772            }
773            CollectionLookupError::InstanceShutDown => AdapterError::ConcurrentDependencyDrop {
774                dependency_kind: "cluster",
775                dependency_id: compute_instance.to_string(),
776            },
777        }
778    }
779
780    pub fn concurrent_dependency_drop_from_watch_set_install_error(
781        e: compute_error::CollectionLookupError,
782    ) -> Self {
783        match e {
784            compute_error::CollectionLookupError::InstanceMissing(id) => {
785                AdapterError::ConcurrentDependencyDrop {
786                    dependency_kind: "cluster",
787                    dependency_id: id.to_string(),
788                }
789            }
790            compute_error::CollectionLookupError::CollectionMissing(id) => {
791                AdapterError::ConcurrentDependencyDrop {
792                    dependency_kind: "collection",
793                    dependency_id: id.to_string(),
794                }
795            }
796        }
797    }
798
799    pub fn concurrent_dependency_drop_from_instance_peek_error(
800        e: mz_compute_client::controller::instance_client::PeekError,
801        compute_instance: ComputeInstanceId,
802    ) -> AdapterError {
803        use mz_compute_client::controller::instance_client::PeekError::*;
804        match e {
805            ReplicaMissing(id) => AdapterError::ConcurrentDependencyDrop {
806                dependency_kind: "replica",
807                dependency_id: id.to_string(),
808            },
809            InstanceShutDown => AdapterError::ConcurrentDependencyDrop {
810                dependency_kind: "cluster",
811                dependency_id: compute_instance.to_string(),
812            },
813            e @ ReadHoldIdMismatch(_) => AdapterError::internal("instance peek error", e),
814            e @ ReadHoldInsufficient(_) => AdapterError::internal("instance peek error", e),
815        }
816    }
817
818    pub fn concurrent_dependency_drop_from_collection_update_error(
819        e: compute_error::CollectionUpdateError,
820    ) -> Self {
821        use compute_error::CollectionUpdateError::*;
822        match e {
823            InstanceMissing(id) => AdapterError::ConcurrentDependencyDrop {
824                dependency_kind: "cluster",
825                dependency_id: id.to_string(),
826            },
827            CollectionMissing(id) => AdapterError::ConcurrentDependencyDrop {
828                dependency_kind: "collection",
829                dependency_id: id.to_string(),
830            },
831        }
832    }
833
834    pub fn concurrent_dependency_drop_from_peek_error(
835        e: mz_compute_client::controller::error::PeekError,
836    ) -> AdapterError {
837        use mz_compute_client::controller::error::PeekError::*;
838        match e {
839            InstanceMissing(id) => AdapterError::ConcurrentDependencyDrop {
840                dependency_kind: "cluster",
841                dependency_id: id.to_string(),
842            },
843            CollectionMissing(id) => AdapterError::ConcurrentDependencyDrop {
844                dependency_kind: "collection",
845                dependency_id: id.to_string(),
846            },
847            ReplicaMissing(id) => AdapterError::ConcurrentDependencyDrop {
848                dependency_kind: "replica",
849                dependency_id: id.to_string(),
850            },
851            e @ (ReadHoldIdMismatch(_) | SinceViolation(_)) => {
852                AdapterError::internal("peek error", e)
853            }
854        }
855    }
856
857    pub fn concurrent_dependency_drop_from_dataflow_creation_error(
858        e: compute_error::DataflowCreationError,
859    ) -> Self {
860        use compute_error::DataflowCreationError::*;
861        match e {
862            InstanceMissing(id) => AdapterError::ConcurrentDependencyDrop {
863                dependency_kind: "cluster",
864                dependency_id: id.to_string(),
865            },
866            CollectionMissing(id) => AdapterError::ConcurrentDependencyDrop {
867                dependency_kind: "collection",
868                dependency_id: id.to_string(),
869            },
870            ReplicaMissing(id) => AdapterError::ConcurrentDependencyDrop {
871                dependency_kind: "replica",
872                dependency_id: id.to_string(),
873            },
874            MissingAsOf | SinceViolation(..) | EmptyAsOfForSubscribe | EmptyAsOfForCopyTo => {
875                AdapterError::internal("dataflow creation error", e)
876            }
877        }
878    }
879}
880
881impl fmt::Display for AdapterError {
882    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
883        match self {
884            AdapterError::AbsurdSubscribeBounds { as_of, up_to } => {
885                write!(
886                    f,
887                    "subscription lower bound (`AS OF`) is greater than its upper bound (`UP TO`): \
888                     {as_of} > {up_to}",
889                )
890            }
891            AdapterError::AmbiguousSystemColumnReference => {
892                write!(
893                    f,
894                    "cannot use wildcard expansions or NATURAL JOINs in a view that depends on \
895                    system objects"
896                )
897            }
898            AdapterError::ChangedPlan(e) => write!(f, "{}", e),
899            AdapterError::Catalog(e) => e.fmt(f),
900            AdapterError::DuplicateCursor(name) => {
901                write!(f, "cursor {} already exists", name.quoted())
902            }
903            AdapterError::Eval(e) => e.fmt(f),
904            AdapterError::Explain(e) => e.fmt(f),
905            AdapterError::IdExhaustionError => f.write_str("ID allocator exhausted all valid IDs"),
906            AdapterError::Internal(e) => write!(f, "internal error: {}", e),
907            AdapterError::IntrospectionDisabled { .. } => write!(
908                f,
909                "cannot read log sources of replica with disabled introspection"
910            ),
911            AdapterError::InvalidLogDependency { object_type, .. } => {
912                write!(f, "{object_type} objects cannot depend on log sources")
913            }
914            AdapterError::InvalidClusterReplicaAz { az, expected: _ } => {
915                write!(f, "unknown cluster replica availability zone {az}",)
916            }
917            AdapterError::InvalidSetIsolationLevel => write!(
918                f,
919                "SET TRANSACTION ISOLATION LEVEL must be called before any query"
920            ),
921            AdapterError::InvalidSetCluster => {
922                write!(f, "SET cluster cannot be called in an active transaction")
923            }
924            AdapterError::InvalidStorageClusterSize { size, .. } => {
925                write!(f, "unknown source size {size}")
926            }
927            AdapterError::SourceOrSinkSizeRequired { .. } => {
928                write!(f, "must specify either cluster or size option")
929            }
930            AdapterError::InvalidTableMutationSelection { .. } => {
931                write!(
932                    f,
933                    "invalid selection: operation may only (transitively) refer to non-source, non-system tables"
934                )
935            }
936            AdapterError::ReplaceMaterializedViewSealed { name } => {
937                write!(
938                    f,
939                    "materialized view {name} is sealed and thus cannot be replaced"
940                )
941            }
942            AdapterError::ConstraintViolation(not_null_violation) => {
943                write!(f, "{}", not_null_violation)
944            }
945            AdapterError::CopyFormatError(e) => write!(f, "{e}"),
946            AdapterError::ConcurrentClusterDrop => {
947                write!(f, "the transaction's active cluster has been dropped")
948            }
949            AdapterError::ConcurrentDependencyDrop {
950                dependency_kind,
951                dependency_id,
952            } => {
953                write!(f, "{dependency_kind} '{dependency_id}' was dropped")
954            }
955            AdapterError::CollectionUnreadable { id } => {
956                write!(f, "collection '{id}' is not readable at any timestamp")
957            }
958            AdapterError::NoClusterReplicasAvailable { name, .. } => {
959                write!(
960                    f,
961                    "CLUSTER {} has no replicas available to service request",
962                    name.quoted()
963                )
964            }
965            AdapterError::OperationProhibitsTransaction(op) => {
966                write!(f, "{} cannot be run inside a transaction block", op)
967            }
968            AdapterError::OperationRequiresTransaction(op) => {
969                write!(f, "{} can only be used in transaction blocks", op)
970            }
971            AdapterError::ParseError(e) => e.fmt(f),
972            AdapterError::PlanError(e) => e.fmt(f),
973            AdapterError::PreparedStatementExists(name) => {
974                write!(f, "prepared statement {} already exists", name.quoted())
975            }
976            AdapterError::ReadOnlyTransaction => f.write_str("transaction in read-only mode"),
977            AdapterError::SingleStatementTransaction => {
978                f.write_str("this transaction can only execute a single statement")
979            }
980            AdapterError::ReadWriteUnavailable => {
981                f.write_str("transaction read-write mode must be set before any query")
982            }
983            AdapterError::WrongSetOfLocks => {
984                write!(f, "internal error, wrong set of locks acquired")
985            }
986            AdapterError::StatementTimeout => {
987                write!(f, "canceling statement due to statement timeout")
988            }
989            AdapterError::Canceled => {
990                write!(f, "canceling statement due to user request")
991            }
992            AdapterError::IdleInTransactionSessionTimeout => {
993                write!(
994                    f,
995                    "terminating connection due to idle-in-transaction timeout"
996                )
997            }
998            AdapterError::RecursionLimit(e) => e.fmt(f),
999            AdapterError::RelationOutsideTimeDomain { .. } => {
1000                write!(
1001                    f,
1002                    "Transactions can only reference objects in the same timedomain. \
1003                     See https://materialize.com/docs/sql/begin/#same-timedomain-error",
1004                )
1005            }
1006            AdapterError::ResourceExhaustion {
1007                resource_type,
1008                limit_name,
1009                desired,
1010                limit,
1011                current,
1012            } => {
1013                write!(
1014                    f,
1015                    "creating {resource_type} would violate {limit_name} limit (desired: {desired}, limit: {limit}, current: {current})"
1016                )
1017            }
1018            AdapterError::ResultSize(e) => write!(f, "{e}"),
1019            AdapterError::SafeModeViolation(feature) => {
1020                write!(f, "cannot create {} in safe mode", feature)
1021            }
1022            AdapterError::SubscribeOnlyTransaction => {
1023                f.write_str("SUBSCRIBE in transactions must be the only read statement")
1024            }
1025            AdapterError::Optimizer(e) => e.fmt(f),
1026            AdapterError::UnallowedOnCluster {
1027                depends_on,
1028                cluster,
1029            } => {
1030                let items = depends_on.into_iter().map(|item| item.quoted()).join(", ");
1031                write!(
1032                    f,
1033                    "querying the following items {items} is not allowed from the {} cluster",
1034                    cluster.quoted()
1035                )
1036            }
1037            AdapterError::Unauthorized(unauthorized) => {
1038                write!(f, "{unauthorized}")
1039            }
1040            AdapterError::UnknownCursor(name) => {
1041                write!(f, "cursor {} does not exist", name.quoted())
1042            }
1043            AdapterError::UnknownLoginRole(name) => {
1044                write!(f, "role {} does not exist", name.quoted())
1045            }
1046            AdapterError::Unsupported(features) => write!(f, "{} are not supported", features),
1047            AdapterError::Unstructured(e) => write!(f, "{}", e.display_with_causes()),
1048            AdapterError::WriteOnlyTransaction => f.write_str("transaction in write-only mode"),
1049            AdapterError::UnknownPreparedStatement(name) => {
1050                write!(f, "prepared statement {} does not exist", name.quoted())
1051            }
1052            AdapterError::UnknownClusterReplica {
1053                cluster_name,
1054                replica_name,
1055            } => write!(
1056                f,
1057                "cluster replica '{cluster_name}.{replica_name}' does not exist"
1058            ),
1059            AdapterError::UnrecognizedConfigurationParam(setting_name) => write!(
1060                f,
1061                "unrecognized configuration parameter {}",
1062                setting_name.quoted()
1063            ),
1064            AdapterError::UntargetedLogRead { .. } => {
1065                f.write_str("log source reads must target a replica")
1066            }
1067            AdapterError::DDLOnlyTransaction => f.write_str(
1068                "transactions which modify objects are restricted to just modifying objects",
1069            ),
1070            AdapterError::DDLTransactionRace => f.write_str(
1071                "another session modified the catalog while this DDL transaction was open",
1072            ),
1073            AdapterError::Storage(e) => e.fmt(f),
1074            AdapterError::Compute(e) => e.fmt(f),
1075            AdapterError::Orchestrator(e) => e.fmt(f),
1076            AdapterError::DependentObject(dependent_objects) => {
1077                let role_str = if dependent_objects.keys().count() == 1 {
1078                    "role"
1079                } else {
1080                    "roles"
1081                };
1082                write!(
1083                    f,
1084                    "{role_str} \"{}\" cannot be dropped because some objects depend on it",
1085                    dependent_objects.keys().join(", ")
1086                )
1087            }
1088            AdapterError::InvalidAlter(t, e) => {
1089                write!(f, "invalid ALTER {t}: {e}")
1090            }
1091            AdapterError::ConnectionValidation(e) => e.fmt(f),
1092            AdapterError::MaterializedViewWouldNeverRefresh(_, _) => {
1093                write!(
1094                    f,
1095                    "all the specified refreshes of the materialized view would be too far in the past, and thus they \
1096                    would never happen"
1097                )
1098            }
1099            AdapterError::InputNotReadableAtRefreshAtTime(_, _) => {
1100                write!(
1101                    f,
1102                    "REFRESH AT requested for a time where not all the inputs are readable"
1103                )
1104            }
1105            AdapterError::RtrTimeout(_) => {
1106                write!(
1107                    f,
1108                    "timed out before ingesting the source's visible frontier when real-time-recency query issued"
1109                )
1110            }
1111            AdapterError::RtrDropFailure(_) => write!(
1112                f,
1113                "real-time source dropped before ingesting the upstream system's visible frontier"
1114            ),
1115            AdapterError::UnreadableSinkCollection => {
1116                write!(f, "collection is not readable at any time")
1117            }
1118            AdapterError::UserSessionsDisallowed => write!(f, "login blocked"),
1119            AdapterError::NetworkPolicyDenied(_) => write!(f, "session denied"),
1120            AdapterError::ReadOnly => write!(f, "cannot write in read-only mode"),
1121            AdapterError::AlterClusterTimeout => {
1122                write!(f, "canceling statement, provided timeout lapsed")
1123            }
1124            AdapterError::AuthenticationError(e) => {
1125                write!(f, "authentication error {e}")
1126            }
1127            AdapterError::UnavailableFeature { feature, docs } => {
1128                write!(f, "{} is not supported in this environment.", feature)?;
1129                if let Some(docs) = docs {
1130                    write!(
1131                        f,
1132                        " For more information consult the documentation at {docs}"
1133                    )?;
1134                }
1135                Ok(())
1136            }
1137            AdapterError::AlterClusterWhilePendingReplicas => {
1138                write!(f, "cannot alter clusters with pending updates")
1139            }
1140            AdapterError::ReplacementSchemaMismatch(_) => {
1141                write!(f, "replacement schema differs from target schema")
1142            }
1143            AdapterError::ImpossibleTimestampConstraints { .. } => {
1144                write!(f, "could not find a valid timestamp for the query")
1145            }
1146            AdapterError::OidcGroupSyncFailed(msg) => {
1147                write!(f, "OIDC group-to-role sync failed: {msg}")
1148            }
1149        }
1150    }
1151}
1152
1153impl From<anyhow::Error> for AdapterError {
1154    fn from(e: anyhow::Error) -> AdapterError {
1155        match e.downcast::<PlanError>() {
1156            Ok(plan_error) => AdapterError::PlanError(plan_error),
1157            Err(e) => AdapterError::Unstructured(e),
1158        }
1159    }
1160}
1161
1162impl From<TryFromIntError> for AdapterError {
1163    fn from(e: TryFromIntError) -> AdapterError {
1164        AdapterError::Unstructured(e.into())
1165    }
1166}
1167
1168impl From<TryFromDecimalError> for AdapterError {
1169    fn from(e: TryFromDecimalError) -> AdapterError {
1170        AdapterError::Unstructured(e.into())
1171    }
1172}
1173
1174impl From<mz_catalog::memory::error::Error> for AdapterError {
1175    fn from(e: mz_catalog::memory::error::Error) -> AdapterError {
1176        AdapterError::Catalog(e)
1177    }
1178}
1179
1180impl From<mz_catalog::durable::CatalogError> for AdapterError {
1181    fn from(e: mz_catalog::durable::CatalogError) -> Self {
1182        mz_catalog::memory::error::Error::from(e).into()
1183    }
1184}
1185
1186impl From<mz_catalog::durable::DurableCatalogError> for AdapterError {
1187    fn from(e: mz_catalog::durable::DurableCatalogError) -> Self {
1188        mz_catalog::durable::CatalogError::from(e).into()
1189    }
1190}
1191
1192impl From<EvalError> for AdapterError {
1193    fn from(e: EvalError) -> AdapterError {
1194        AdapterError::Eval(e)
1195    }
1196}
1197
1198impl From<ExplainError> for AdapterError {
1199    fn from(e: ExplainError) -> AdapterError {
1200        match e {
1201            ExplainError::RecursionLimitError(e) => AdapterError::RecursionLimit(e),
1202            e => AdapterError::Explain(e),
1203        }
1204    }
1205}
1206
1207impl From<mz_sql::catalog::CatalogError> for AdapterError {
1208    fn from(e: mz_sql::catalog::CatalogError) -> AdapterError {
1209        AdapterError::Catalog(mz_catalog::memory::error::Error::from(e))
1210    }
1211}
1212
1213impl From<PlanError> for AdapterError {
1214    fn from(e: PlanError) -> AdapterError {
1215        match e {
1216            PlanError::UnknownCursor(name) => AdapterError::UnknownCursor(name),
1217            _ => AdapterError::PlanError(e),
1218        }
1219    }
1220}
1221
1222impl From<OptimizerError> for AdapterError {
1223    fn from(e: OptimizerError) -> AdapterError {
1224        use OptimizerError::*;
1225        match e {
1226            PlanError(e) => Self::PlanError(e),
1227            RecursionLimitError(e) => Self::RecursionLimit(e),
1228            EvalError(e) => Self::Eval(e),
1229            InternalUnsafeMfpPlan(e) => Self::Internal(e),
1230            Internal(e) => Self::Internal(e),
1231            e => Self::Optimizer(e),
1232        }
1233    }
1234}
1235
1236impl From<NotNullViolation> for AdapterError {
1237    fn from(e: NotNullViolation) -> AdapterError {
1238        AdapterError::ConstraintViolation(e)
1239    }
1240}
1241
1242impl From<RecursionLimitError> for AdapterError {
1243    fn from(e: RecursionLimitError) -> AdapterError {
1244        AdapterError::RecursionLimit(e)
1245    }
1246}
1247
1248impl From<oneshot::error::RecvError> for AdapterError {
1249    fn from(e: oneshot::error::RecvError) -> AdapterError {
1250        AdapterError::Unstructured(e.into())
1251    }
1252}
1253
1254impl From<StorageError> for AdapterError {
1255    fn from(e: StorageError) -> Self {
1256        AdapterError::Storage(e)
1257    }
1258}
1259
1260impl From<compute_error::InstanceExists> for AdapterError {
1261    fn from(e: compute_error::InstanceExists) -> Self {
1262        AdapterError::Compute(e.into())
1263    }
1264}
1265
1266impl From<TimestampError> for AdapterError {
1267    fn from(e: TimestampError) -> Self {
1268        let e: EvalError = e.into();
1269        e.into()
1270    }
1271}
1272
1273impl From<mz_sql_parser::parser::ParserStatementError> for AdapterError {
1274    fn from(e: mz_sql_parser::parser::ParserStatementError) -> Self {
1275        AdapterError::ParseError(e)
1276    }
1277}
1278
1279impl From<VarError> for AdapterError {
1280    fn from(e: VarError) -> Self {
1281        let e: mz_catalog::memory::error::Error = e.into();
1282        e.into()
1283    }
1284}
1285
1286impl From<rbac::UnauthorizedError> for AdapterError {
1287    fn from(e: rbac::UnauthorizedError) -> Self {
1288        AdapterError::Unauthorized(e)
1289    }
1290}
1291
1292impl From<mz_sql_parser::ast::IdentError> for AdapterError {
1293    fn from(value: mz_sql_parser::ast::IdentError) -> Self {
1294        AdapterError::PlanError(PlanError::InvalidIdent(value))
1295    }
1296}
1297
1298impl From<mz_pgwire_common::ConnectionError> for AdapterError {
1299    fn from(value: mz_pgwire_common::ConnectionError) -> Self {
1300        match value {
1301            mz_pgwire_common::ConnectionError::TooManyConnections { current, limit } => {
1302                AdapterError::ResourceExhaustion {
1303                    resource_type: "connection".into(),
1304                    limit_name: "max_connections".into(),
1305                    desired: (current + 1).to_string(),
1306                    limit: limit.to_string(),
1307                    current: current.to_string(),
1308                }
1309            }
1310        }
1311    }
1312}
1313
1314impl From<NetworkPolicyError> for AdapterError {
1315    fn from(value: NetworkPolicyError) -> Self {
1316        AdapterError::NetworkPolicyDenied(value)
1317    }
1318}
1319
1320impl From<ConnectionValidationError> for AdapterError {
1321    fn from(e: ConnectionValidationError) -> AdapterError {
1322        AdapterError::ConnectionValidation(e)
1323    }
1324}
1325
1326impl Error for AdapterError {}