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;
19
20use mz_compute_types::ComputeInstanceId;
21use mz_controller_types::ClusterId;
22use mz_expr::EvalError;
23use mz_ore::cast::CastFrom;
24use mz_ore::error::ErrorExt;
25use mz_ore::stack::RecursionLimitError;
26use mz_ore::str::StrExt;
27use mz_pgwire_common::{ErrorResponse, Severity};
28use mz_repr::adt::array::InvalidArrayError;
29use mz_repr::adt::range::InvalidRangeError;
30use mz_repr::adt::timestamp::TimestampError;
31use mz_repr::explain::ExplainError;
32use mz_repr::strconv::{ParseError, ParseErrorKind};
33use mz_repr::{ColumnDiff, ColumnName, KeyDiff, NotNullViolation, RelationDescDiff, Timestamp};
34use mz_sql::plan::PlanError;
35use mz_sql::rbac;
36use mz_sql::session::vars::VarError;
37use mz_storage_types::connections::ConnectionValidationError;
38use mz_storage_types::controller::StorageError;
39use mz_storage_types::errors::{CollectionMissing, DataflowError};
40use smallvec::SmallVec;
41use timely::progress::Antichain;
42use tokio::sync::oneshot;
43use tokio_postgres::error::SqlState;
44
45use crate::coord::NetworkPolicyError;
46use crate::optimize::OptimizerError;
47use crate::peek_client::CollectionLookupError;
48
49/// Errors that can occur in the coordinator.
50#[derive(Debug)]
51pub enum AdapterError {
52    /// A `SUBSCRIBE` was requested whose `UP TO` bound precedes its `as_of` timestamp
53    AbsurdSubscribeBounds {
54        as_of: mz_repr::Timestamp,
55        up_to: mz_repr::Timestamp,
56    },
57    /// Attempted to use a potentially ambiguous column reference expression with a system table.
58    // We don't allow this until https://github.com/MaterializeInc/database-issues/issues/4824 is
59    // resolved because it prevents us from adding columns to system tables.
60    AmbiguousSystemColumnReference,
61    /// An error occurred in a catalog operation.
62    Catalog(mz_catalog::memory::error::Error),
63    /// 1. The cached plan or descriptor changed,
64    /// 2. or some dependency of a statement disappeared during sequencing.
65    /// TODO(ggevay): we should refactor 2. usages to use `ConcurrentDependencyDrop` instead
66    /// (e.g., in MV sequencing)
67    ChangedPlan(String),
68    /// The cursor already exists.
69    DuplicateCursor(String),
70    /// An error while evaluating an expression.
71    Eval(EvalError),
72    /// An error produced while executing a dataflow.
73    Dataflow(Box<DataflowError>),
74    /// An error occurred while planning the statement.
75    Explain(ExplainError),
76    /// The ID allocator exhausted all valid IDs.
77    IdExhaustionError,
78    /// Unexpected internal state was encountered.
79    Internal(String),
80    /// Attempted to read from log sources of a replica with disabled introspection.
81    IntrospectionDisabled {
82        log_names: Vec<String>,
83    },
84    /// Attempted to create an object dependent on log sources that doesn't support
85    /// log dependencies.
86    InvalidLogDependency {
87        object_type: String,
88        log_names: Vec<String>,
89    },
90    /// No such cluster replica size has been configured.
91    InvalidClusterReplicaAz {
92        az: String,
93        expected: Vec<String>,
94    },
95    /// SET TRANSACTION ISOLATION LEVEL was called in the middle of a transaction.
96    InvalidSetIsolationLevel,
97    /// SET cluster was called in the middle of a transaction.
98    InvalidSetCluster,
99    /// No such storage instance size has been configured.
100    InvalidStorageClusterSize {
101        size: String,
102        expected: Vec<String>,
103    },
104    /// Creating a source or sink without specifying its size is forbidden.
105    SourceOrSinkSizeRequired {
106        expected: Vec<String>,
107    },
108    /// The selection value for a table mutation operation refers to an invalid object.
109    InvalidTableMutationSelection {
110        /// The full name of the problematic object, such as a source or source-backed table.
111        object_name: String,
112        /// Human-readable type of the object, such as "source-backed table".
113        object_type: String,
114    },
115    /// A read-then-write statement's read set has more transitive dependencies
116    /// than validation is willing to walk.
117    ReadThenWriteDependencyLimitExceeded {
118        /// The configured maximum number of dependencies.
119        max_rw_dependencies: usize,
120    },
121    /// Expression violated a column's constraint
122    ConstraintViolation(NotNullViolation),
123    /// An error occurred while decoding COPY data.
124    CopyFormatError(String),
125    /// Transaction cluster was dropped in the middle of a transaction.
126    ConcurrentClusterDrop,
127    /// A dependency was dropped while sequencing a statement.
128    ConcurrentDependencyDrop {
129        dependency_kind: &'static str,
130        dependency_id: String,
131    },
132    /// A dependency's definition changed while a statement was being sequenced.
133    /// Raised by `PlanValidity::check` when a dependency's `create_sql` hash no
134    /// longer matches what we captured at plan time, and by
135    /// `Coordinator::stage_group_commit` when a table's `RelationDesc` no longer
136    /// matches the rows a staged write packed against it.
137    ConcurrentDependencyMutation {
138        dependency_id: String,
139    },
140    /// A frontend read-then-write exhausted its OCC retry budget.
141    ///
142    /// The statement is retryable: every attempt was refused before anything
143    /// was appended, so nothing it intended has been committed.
144    ReadThenWriteContention,
145    /// The write timestamp ran past what the write timeline may be advanced to,
146    /// so nothing was appended. See `coord::timeline::write_ts_upper_bound` for
147    /// the bound and why exceeding it is not recoverable.
148    ///
149    /// The timestamp comes from the timeline's oracle, so reaching this means the
150    /// oracle has run away from the wall clock rather than that the statement
151    /// asked for anything unusual.
152    ReadThenWriteTimestampTooFarAhead {
153        target_timestamp: mz_repr::Timestamp,
154        limit: mz_repr::Timestamp,
155    },
156    CollectionUnreadable {
157        id: String,
158    },
159    /// Target cluster has no replicas to service query.
160    NoClusterReplicasAvailable {
161        name: String,
162        is_managed: bool,
163    },
164    /// The named operation cannot be run in a transaction.
165    OperationProhibitsTransaction(String),
166    /// The named operation requires an active transaction.
167    OperationRequiresTransaction(String),
168    /// An error occurred while planning the statement.
169    PlanError(PlanError),
170    /// The named prepared statement already exists.
171    PreparedStatementExists(String),
172    /// Wrapper around parsing error
173    ParseError(mz_sql_parser::parser::ParserStatementError),
174    /// The transaction is in read-only mode.
175    ReadOnlyTransaction,
176    /// The transaction in in read-only mode and a read already occurred.
177    ReadWriteUnavailable,
178    /// The recursion limit of some operation was exceeded.
179    RecursionLimit(RecursionLimitError),
180    /// A query in a transaction referenced a relation outside the first query's
181    /// time domain.
182    RelationOutsideTimeDomain {
183        relations: Vec<String>,
184        names: Vec<String>,
185    },
186    /// A query tried to create more resources than is allowed in the system configuration.
187    ResourceExhaustion {
188        resource_type: String,
189        limit_name: String,
190        desired: String,
191        limit: String,
192        current: String,
193    },
194    /// Result size of a query is too large.
195    ResultSize(String),
196    /// A `SUBSCRIBE` (or `COPY (SUBSCRIBE ...) TO STDOUT`) buffered more bytes in
197    /// environmentd than its budget allows because the client was not reading
198    /// fast enough. The subscribe is retired rather than let one slow client
199    /// grow the shared process's memory without bound.
200    SubscribeFellBehind {
201        /// Bytes buffered when the budget was exceeded.
202        buffered_bytes: usize,
203        /// The `subscribe_max_buffered_bytes` budget that was exceeded.
204        max_buffered_bytes: usize,
205    },
206    /// A query exceeded the configured compute peek row iteration limit.
207    PeekRowIterationLimitExceeded {
208        /// The configured per-worker limit.
209        limit: usize,
210    },
211    /// The specified feature is not permitted in safe mode.
212    SafeModeViolation(String),
213    /// Waiting on a query timed out.
214    ///
215    /// Note this differs slightly from PG's implementation/semantics.
216    StatementTimeout,
217    /// The user canceled the query
218    Canceled,
219    /// An idle session in a transaction has timed out.
220    IdleInTransactionSessionTimeout,
221    /// The transaction is in single-subscribe mode.
222    SubscribeOnlyTransaction,
223    /// An error occurred in the optimizer.
224    Optimizer(OptimizerError),
225    /// A query depends on items which are not allowed to be referenced from the current cluster.
226    UnallowedOnCluster {
227        depends_on: SmallVec<[String; 2]>,
228        cluster: String,
229    },
230    /// A user tried to perform an action that they were unauthorized to do.
231    Unauthorized(rbac::UnauthorizedError),
232    /// The named cursor does not exist.
233    UnknownCursor(String),
234    /// The named role does not exist.
235    UnknownLoginRole(String),
236    UnknownPreparedStatement(String),
237    /// The named cluster replica does not exist.
238    UnknownClusterReplica {
239        cluster_name: String,
240        replica_name: String,
241    },
242    /// The named setting does not exist.
243    UnrecognizedConfigurationParam(String),
244    /// A generic error occurred.
245    //
246    // TODO(benesch): convert all those errors to structured errors.
247    Unstructured(anyhow::Error),
248    /// The named feature is not supported and will (probably) not be.
249    Unsupported(&'static str),
250    /// Some feature isn't available for a (potentially opaque) reason.
251    /// For example, in cloud Self-Managed auth features aren't available,
252    /// but we don't want to mention self managed auth.
253    UnavailableFeature {
254        feature: String,
255        docs: Option<String>,
256    },
257    /// Attempted to read from log sources without selecting a target replica.
258    UntargetedLogRead {
259        log_names: Vec<String>,
260    },
261    /// The transaction is in write-only mode.
262    WriteOnlyTransaction,
263    /// The transaction can only execute a single statement.
264    SingleStatementTransaction,
265    /// The transaction can only execute simple DDL.
266    DDLOnlyTransaction,
267    /// Final execution would change an outcome already reported to the client.
268    DDLTransactionOutcomeChanged,
269    /// A conditional cluster-config write failed its precondition: the cluster's
270    /// managed config changed between when the write was conditioned and when it
271    /// was applied. Produced by `Op::CheckClusterState`, never by SQL DDL, so it
272    /// does not reach a SQL client.
273    ClusterStateChanged {
274        cluster_id: ClusterId,
275    },
276    /// An error occurred in the storage layer
277    Storage(mz_storage_types::controller::StorageError),
278    /// An error occurred in the compute layer
279    Compute(anyhow::Error),
280    /// An error in the orchestrator layer
281    Orchestrator(anyhow::Error),
282    /// A statement tried to drop a role that had dependent objects.
283    ///
284    /// The map keys are role names and values are detailed error messages.
285    DependentObject(BTreeMap<String, Vec<String>>),
286    /// A statement tried to drop indexes while materialized views, indexes, or metric sinks
287    /// read from them.
288    ///
289    /// `blocked` is never empty. Each entry pairs a blocked index's name with its readers as
290    /// `(object type, name)` pairs.
291    IndexInUse {
292        blocked: Vec<(String, Vec<(String, String)>)>,
293    },
294    /// When performing an `ALTER` of some variety, re-planning the statement
295    /// errored.
296    InvalidAlter(&'static str, PlanError),
297    /// An error occurred while validating a connection.
298    ConnectionValidation(ConnectionValidationError),
299    /// We refuse to create the materialized view, because it would never be refreshed, so it would
300    /// never be queryable. This can happen when the only specified refreshes are further back in
301    /// the past than the initial compaction window of the materialized view.
302    MaterializedViewWouldNeverRefresh(Timestamp, Timestamp),
303    /// A CREATE MATERIALIZED VIEW statement tried to acquire a read hold at a REFRESH AT time,
304    /// but was unable to get a precise read hold.
305    InputNotReadableAtRefreshAtTime(Timestamp, Antichain<Timestamp>),
306    /// A humanized version of [`StorageError::RtrTimeout`].
307    RtrTimeout(String),
308    /// A humanized version of [`StorageError::RtrDropFailure`].
309    RtrDropFailure(String),
310    /// The collection requested to be sinked cannot be read at any timestamp
311    UnreadableSinkCollection,
312    /// User sessions have been blocked.
313    UserSessionsDisallowed,
314    /// This use session has been denied by a NetworkPolicy.
315    NetworkPolicyDenied(NetworkPolicyError),
316    /// An enforced query policy rejected the optimized execution plan.
317    QueryPolicyRejected(crate::query_policy::QueryPolicyViolation),
318    /// Something attempted a write (to catalog, storage, tables, etc.) while in
319    /// read-only mode.
320    ReadOnly,
321    AlterClusterTimeout,
322    /// Another `ALTER CLUSTER` replaced the target this statement was waiting
323    /// for before it became realized.
324    AlterClusterSuperseded,
325    /// The cluster controller could not provision a reconfiguration target
326    /// within the environment's resource limits.
327    AlterClusterResourceExhausted,
328    /// Attempt to convert a cluster to unmanaged while a graceful
329    /// reconfiguration is in progress.
330    AlterClusterUnmanagedWhileReconfiguring,
331    /// Attempt to convert a cluster to unmanaged while a hydration burst is in
332    /// flight.
333    AlterClusterUnmanagedWhileBursting,
334    /// Attempt to change a cluster's schedule while a graceful reconfiguration
335    /// is in progress.
336    AlterClusterScheduleWhileReconfiguring,
337    /// Attempt to use `WAIT` on an `ALTER` of a scheduled (non-`MANUAL`)
338    /// cluster, whose replica set the controller reshapes in the background.
339    AlterClusterWaitOnScheduledCluster,
340    AuthenticationError(AuthenticationError),
341    /// Schema of a replacement is incompatible with the target.
342    ReplacementSchemaMismatch(RelationDescDiff),
343    /// Attempt to replace a sealed materialized view.
344    ReplaceMaterializedViewSealed {
345        name: String,
346    },
347    /// Could not find a valid timestamp satisfying all constraints.
348    ImpossibleTimestampConstraints {
349        constraints: String,
350    },
351    /// OIDC group-to-role sync failed and strict mode is enabled.
352    OidcGroupSyncFailed(String),
353    /// Returned when bounded staleness was selected but the input frontiers lag
354    /// further than the bound permits, so no timestamp in the no-wait window is
355    /// at most `bound` stale.
356    BoundedStalenessExceeded {
357        bound: std::time::Duration,
358        gap_ms: u64,
359        slowest_input: Option<mz_repr::GlobalId>,
360    },
361    /// A write was attempted in a session whose isolation level is bounded
362    /// staleness. Bounded staleness is read-only.
363    BoundedStalenessReadOnly,
364    /// `real_time_recency = on` and bounded staleness were both requested in
365    /// the same session; they are mutually exclusive.
366    BoundedStalenessRealTimeRecencyConflict,
367    /// A bounded-staleness query touched a timeline whose timestamps are not
368    /// the `EpochMilliseconds` wall-clock timeline.
369    BoundedStalenessTimelineUnsupported,
370}
371
372#[derive(Debug, thiserror::Error)]
373pub enum AuthenticationError {
374    #[error("invalid credentials")]
375    InvalidCredentials,
376    #[error("role is not allowed to login")]
377    NonLogin,
378    #[error("role does not exist")]
379    RoleNotFound,
380    #[error("password is required")]
381    PasswordRequired,
382}
383
384/// Maps a parse/cast [`ParseError`] to the appropriate `DATA_EXCEPTION` (class
385/// 22) SQLSTATE. Out-of-range values map to overflow codes and malformed input
386/// maps to invalid-representation codes, in both cases distinguishing datetime
387/// types from everything else, matching PostgreSQL.
388fn parse_error_code(err: &ParseError) -> SqlState {
389    let is_datetime = matches!(
390        &*err.type_name,
391        "date" | "time" | "timestamp" | "timestamp with time zone" | "interval"
392    );
393    match (err.kind, is_datetime) {
394        (ParseErrorKind::OutOfRange, true) => SqlState::DATETIME_FIELD_OVERFLOW,
395        (ParseErrorKind::OutOfRange, false) => SqlState::NUMERIC_VALUE_OUT_OF_RANGE,
396        (ParseErrorKind::InvalidInputSyntax, true) => SqlState::INVALID_DATETIME_FORMAT,
397        (ParseErrorKind::InvalidInputSyntax, false) => SqlState::INVALID_TEXT_REPRESENTATION,
398    }
399}
400
401/// Maps an [`EvalError`] to the appropriate SQLSTATE.
402///
403/// Historically every `EvalError` fell through to `INTERNAL_ERROR` (`XX000`),
404/// but the overwhelming majority are user-facing data exceptions (class 22) or
405/// other well-defined conditions, not internal errors. This match is
406/// deliberately exhaustive — with no wildcard — so that adding a new
407/// `EvalError` variant is a compile error until it is assigned a code, and we
408/// never silently regress to `XX000`. Codes are chosen to match PostgreSQL
409/// where an equivalent error exists.
410fn eval_error_code(err: &EvalError) -> SqlState {
411    match err {
412        // Division and mathematical domain errors.
413        EvalError::DivisionByZero => SqlState::DIVISION_BY_ZERO,
414        EvalError::NegSqrt | EvalError::ComplexOutOfRange(_) => {
415            SqlState::INVALID_ARGUMENT_FOR_POWER_FUNCTION
416        }
417        EvalError::InfinityOutOfDomain(_)
418        | EvalError::NegativeOutOfDomain(_)
419        | EvalError::ZeroOutOfDomain(_)
420        | EvalError::OutOfDomain(..)
421        | EvalError::Undefined(_) => SqlState::INVALID_PARAMETER_VALUE,
422
423        // Out-of-range numeric, integer, and float values.
424        EvalError::FloatOverflow
425        | EvalError::FloatUnderflow
426        | EvalError::NumericFieldOverflow
427        | EvalError::Float32OutOfRange(_)
428        | EvalError::Float64OutOfRange(_)
429        | EvalError::Int16OutOfRange(_)
430        | EvalError::Int32OutOfRange(_)
431        | EvalError::Int64OutOfRange(_)
432        | EvalError::UInt16OutOfRange(_)
433        | EvalError::UInt32OutOfRange(_)
434        | EvalError::UInt64OutOfRange(_)
435        | EvalError::OidOutOfRange(_)
436        | EvalError::MzTimestampOutOfRange(_)
437        | EvalError::MzTimestampStepOverflow
438        | EvalError::CharOutOfRange => SqlState::NUMERIC_VALUE_OUT_OF_RANGE,
439
440        // Out-of-range datetime and interval values.
441        EvalError::DateOutOfRange
442        | EvalError::TimestampOutOfRange
443        | EvalError::TimestampCannotBeNan
444        | EvalError::DateBinOutOfRange(_)
445        | EvalError::DateDiffOverflow { .. } => SqlState::DATETIME_FIELD_OVERFLOW,
446        EvalError::IntervalOutOfRange(_) => SqlState::INTERVAL_FIELD_OVERFLOW,
447
448        // Parse/cast failures, plus other malformed textual/encoded input.
449        EvalError::Parse(e) => parse_error_code(e),
450        EvalError::ParseHex(_)
451        | EvalError::InvalidBase64Equals
452        | EvalError::InvalidBase64Symbol(_)
453        | EvalError::InvalidBase64EndSequence => SqlState::INVALID_TEXT_REPRESENTATION,
454        EvalError::InvalidByteSequence { .. } => SqlState::CHARACTER_NOT_IN_REPERTOIRE,
455        EvalError::CharacterNotValidForEncoding(_) | EvalError::CharacterTooLargeForEncoding(_) => {
456            SqlState::PROGRAM_LIMIT_EXCEEDED
457        }
458
459        // Invalid argument values.
460        EvalError::InvalidTimezone(_)
461        | EvalError::InvalidTimezoneInterval
462        | EvalError::InvalidTimezoneConversion
463        | EvalError::InvalidIanaTimezoneId(_)
464        | EvalError::InvalidLayer { .. }
465        | EvalError::InvalidEncodingName(_)
466        | EvalError::InvalidHashAlgorithm(_)
467        | EvalError::InvalidDatePart(_)
468        | EvalError::InvalidParameterValue(_)
469        | EvalError::InvalidJsonbCast { .. }
470        | EvalError::UnknownUnits(_)
471        | EvalError::UnsupportedUnits(..)
472        | EvalError::InvalidIdentifier { .. }
473        | EvalError::InvalidRoleId(_)
474        | EvalError::InvalidPrivileges(_)
475        | EvalError::NegLimit => SqlState::INVALID_PARAMETER_VALUE,
476
477        // Regular expressions.
478        EvalError::InvalidRegex(_) | EvalError::InvalidRegexFlag(_) => {
479            SqlState::INVALID_REGULAR_EXPRESSION
480        }
481
482        // LIKE escape sequences.
483        EvalError::UnterminatedLikeEscapeSequence | EvalError::LikeEscapeTooLong => {
484            SqlState::INVALID_ESCAPE_SEQUENCE
485        }
486
487        // NULL values where they are not permitted.
488        EvalError::KeyCannotBeNull
489        | EvalError::MustNotBeNull(_)
490        | EvalError::AclArrayNullElement
491        | EvalError::MzAclArrayNullElement => SqlState::NULL_VALUE_NOT_ALLOWED,
492
493        // Array subscript/dimension errors.
494        EvalError::IndexOutOfRange { .. }
495        | EvalError::ArrayFillWrongArraySubscripts
496        | EvalError::IncompatibleArrayDimensions { .. } => SqlState::ARRAY_SUBSCRIPT_ERROR,
497        EvalError::InvalidArray(e) => match e {
498            InvalidArrayError::TooManyDimensions(_) => SqlState::PROGRAM_LIMIT_EXCEEDED,
499            InvalidArrayError::WrongCardinality { .. } => SqlState::ARRAY_SUBSCRIPT_ERROR,
500        },
501
502        // Range errors.
503        EvalError::InvalidRange(e) => match e {
504            InvalidRangeError::CanonicalizationOverflow(_) => SqlState::NUMERIC_VALUE_OUT_OF_RANGE,
505            InvalidRangeError::MisorderedRangeBounds
506            | InvalidRangeError::InvalidRangeBoundFlags
507            | InvalidRangeError::NullRangeBoundFlags
508            | InvalidRangeError::DiscontiguousUnion
509            | InvalidRangeError::DiscontiguousDifference
510            | InvalidRangeError::InvalidRangeData => SqlState::DATA_EXCEPTION,
511        },
512
513        // Cardinality violations from scalar subqueries.
514        EvalError::MultipleRowsFromSubquery | EvalError::NegativeRowsFromSubquery => {
515            SqlState::CARDINALITY_VIOLATION
516        }
517
518        // Length, size, and resource limits.
519        EvalError::StringValueTooLong { .. } => SqlState::STRING_DATA_RIGHT_TRUNCATION,
520        EvalError::LikePatternTooLong
521        | EvalError::LengthTooLarge
522        | EvalError::TempStorageBudgetExceeded
523        | EvalError::NullCharacterNotPermitted
524        | EvalError::MaxArraySizeExceeded(_)
525        | EvalError::LetRecLimitExceeded(_) => SqlState::PROGRAM_LIMIT_EXCEEDED,
526
527        // Unsupported features.
528        EvalError::Unsupported { .. }
529        | EvalError::MultidimensionalArrayRemovalNotSupported
530        | EvalError::MultiDimensionalArraySearch => SqlState::FEATURE_NOT_SUPPORTED,
531
532        // User-raised errors (e.g. `error_if_null`).
533        EvalError::IfNullError(_) => SqlState::DATA_EXCEPTION,
534
535        // Genuinely internal errors.
536        EvalError::Internal(_)
537        | EvalError::InvalidCatalogJson(_)
538        | EvalError::TypeFromOid(_)
539        | EvalError::PrettyError(_)
540        | EvalError::RedactError(_) => SqlState::INTERNAL_ERROR,
541    }
542}
543
544fn dataflow_error_code(error: &DataflowError) -> SqlState {
545    match error {
546        DataflowError::EvalError(error) => eval_error_code(error),
547        DataflowError::DecodeError(_)
548        | DataflowError::SourceError(_)
549        | DataflowError::EnvelopeError(_) => SqlState::INTERNAL_ERROR,
550    }
551}
552
553impl AdapterError {
554    pub fn into_response(self, severity: Severity) -> ErrorResponse {
555        ErrorResponse {
556            severity,
557            code: self.code(),
558            message: self.to_string(),
559            detail: self.detail(),
560            hint: self.hint(),
561            position: self.position(),
562        }
563    }
564
565    pub fn position(&self) -> Option<usize> {
566        match self {
567            AdapterError::ParseError(err) => Some(err.error.pos),
568            _ => None,
569        }
570    }
571
572    /// Reports additional details about the error, if any are available.
573    pub fn detail(&self) -> Option<String> {
574        match self {
575            AdapterError::AmbiguousSystemColumnReference => {
576                Some("This is a current limitation in Materialize".into())
577            }
578            AdapterError::Catalog(c) => c.detail(),
579            AdapterError::Eval(e) => e.detail(),
580            AdapterError::Dataflow(e) => match &**e {
581                DataflowError::EvalError(e) => e.detail(),
582                _ => None,
583            },
584            AdapterError::RelationOutsideTimeDomain { relations, names } => Some(format!(
585                "The following relations in the query are outside the transaction's time domain:\n{}\n{}",
586                relations
587                    .iter()
588                    .map(|r| r.quoted().to_string())
589                    .collect::<Vec<_>>()
590                    .join("\n"),
591                match names.is_empty() {
592                    true => "No relations are available.".to_string(),
593                    false => format!(
594                        "Only the following relations are available:\n{}",
595                        names
596                            .iter()
597                            .map(|name| name.quoted().to_string())
598                            .collect::<Vec<_>>()
599                            .join("\n")
600                    ),
601                }
602            )),
603            AdapterError::SourceOrSinkSizeRequired { .. } => Some(
604                "Either specify the cluster that will maintain this object via IN CLUSTER or \
605                specify size via SIZE option."
606                    .into(),
607            ),
608            AdapterError::InvalidTableMutationSelection {
609                object_name,
610                object_type,
611            } => Some(format!(
612                "{object_type} '{}' may not be used in this operation; \
613                     every relation leaf in the selection must be a writable user table",
614                object_name.quoted()
615            )),
616            AdapterError::ReadThenWriteDependencyLimitExceeded {
617                max_rw_dependencies,
618            } => Some(format!(
619                "The read set transitively depends on more than {max_rw_dependencies} \
620                     objects. Reduce the number of dependencies, or raise the \
621                     read_then_write_max_dependencies system parameter."
622            )),
623            AdapterError::PeekRowIterationLimitExceeded { limit } => Some(format!(
624                "The query attempted to examine more than {limit} rows on a single compute \
625                 worker. This limit prevents long-running SELECT queries from delaying other \
626                 work on the cluster."
627            )),
628            AdapterError::SafeModeViolation(_) => Some(
629                "The Materialize server you are connected to is running in \
630                 safe mode, which limits the features that are available."
631                    .into(),
632            ),
633            AdapterError::IntrospectionDisabled { log_names }
634            | AdapterError::UntargetedLogRead { log_names } => Some(format!(
635                "The query references the following log sources:\n    {}",
636                log_names.join("\n    "),
637            )),
638            AdapterError::InvalidLogDependency { log_names, .. } => Some(format!(
639                "The object depends on the following log sources:\n    {}",
640                log_names.join("\n    "),
641            )),
642            AdapterError::PlanError(e) => e.detail(),
643            AdapterError::Unauthorized(unauthorized) => unauthorized.detail(),
644            AdapterError::IndexInUse { blocked } => match &blocked[..] {
645                [(index_name, _)] => Some(format!(
646                    "The dependent objects are live dataflows that read from index {}, so the \
647                     index cannot be dropped while they exist.",
648                    index_name.quoted()
649                )),
650                blocked => {
651                    let per_index = blocked
652                        .iter()
653                        .map(|(index_name, dependents)| {
654                            format!(
655                                "Index {} is read by {}.",
656                                index_name.quoted(),
657                                fmt_dependents(dependents.iter())
658                            )
659                        })
660                        .join(" ");
661                    Some(format!(
662                        "{per_index} The dependent objects are live dataflows that read from \
663                         these indexes, so the indexes cannot be dropped while they exist."
664                    ))
665                }
666            },
667            AdapterError::DependentObject(dependent_objects) => Some(
668                dependent_objects
669                    .iter()
670                    .map(|(role_name, err_msgs)| {
671                        err_msgs
672                            .iter()
673                            .map(|err_msg| format!("{role_name}: {err_msg}"))
674                            .join("\n")
675                    })
676                    .join("\n"),
677            ),
678            AdapterError::Storage(storage_error) => storage_error
679                .source()
680                .map(|source_error| source_error.to_string_with_causes()),
681            AdapterError::ReadOnlyTransaction => Some(
682                "SELECT queries cannot be combined with other query types, including SUBSCRIBE."
683                    .into(),
684            ),
685            AdapterError::InvalidAlter(_, e) => e.detail(),
686            AdapterError::Optimizer(e) => e.detail(),
687            AdapterError::ConnectionValidation(e) => e.detail(),
688            AdapterError::MaterializedViewWouldNeverRefresh(last_refresh, earliest_possible) => {
689                Some(format!(
690                    "The specified last refresh is at {}, while the earliest possible time to compute the materialized \
691                    view is {}.",
692                    last_refresh, earliest_possible,
693                ))
694            }
695            AdapterError::UnallowedOnCluster { cluster, .. } => {
696                (cluster == MZ_CATALOG_SERVER_CLUSTER.name).then(|| {
697                    format!(
698                        "The transaction is executing on the \
699                        {cluster} cluster, maybe having been routed \
700                        there by the first statement in the transaction."
701                    )
702                })
703            }
704            AdapterError::InputNotReadableAtRefreshAtTime(oracle_read_ts, least_valid_read) => {
705                Some(format!(
706                    "The requested REFRESH AT time is {}, \
707                    but not all input collections are readable earlier than [{}].",
708                    oracle_read_ts,
709                    if least_valid_read.len() == 1 {
710                        format!(
711                            "{}",
712                            least_valid_read
713                                .as_option()
714                                .expect("antichain contains exactly 1 timestamp")
715                        )
716                    } else {
717                        // This can't occur currently
718                        format!("{:?}", least_valid_read)
719                    }
720                ))
721            }
722            AdapterError::RtrTimeout(name) => Some(format!(
723                "{name} failed to ingest data up to the real-time recency point"
724            )),
725            AdapterError::RtrDropFailure(name) => Some(format!(
726                "{name} dropped before ingesting data to the real-time recency point"
727            )),
728            AdapterError::UserSessionsDisallowed => {
729                Some("Your organization has been blocked. Please contact support.".to_string())
730            }
731            AdapterError::NetworkPolicyDenied(reason) => Some(format!("{reason}.")),
732            AdapterError::QueryPolicyRejected(violation) => Some(violation.detail()),
733            AdapterError::ReplacementSchemaMismatch(diff) => {
734                let mut lines: Vec<_> = diff.column_diffs.iter().map(|(idx, diff)| {
735                    let pos = idx + 1;
736                    match diff {
737                        ColumnDiff::Missing { name } => {
738                            let name = name.as_str().quoted();
739                            format!("missing column {name} at position {pos}")
740                        }
741                        ColumnDiff::Extra { name } => {
742                            let name = name.as_str().quoted();
743                            format!("extra column {name} at position {pos}")
744                        }
745                        ColumnDiff::TypeMismatch { name, left, right } => {
746                            let name = name.as_str().quoted();
747                            format!("column {name} at position {pos}: type mismatch (target: {left:?}, replacement: {right:?})")
748                        }
749                        ColumnDiff::NullabilityMismatch { name, left, right } => {
750                            let name = name.as_str().quoted();
751                            let left = if *left { "NULL" } else { "NOT NULL" };
752                            let right = if *right { "NULL" } else { "NOT NULL" };
753                            format!("column {name} at position {pos}: nullability mismatch (target: {left}, replacement: {right})")
754                        }
755                        ColumnDiff::NameMismatch { left, right } => {
756                            let left = left.as_str().quoted();
757                            let right = right.as_str().quoted();
758                            format!("column at position {pos}: name mismatch (target: {left}, replacement: {right})")
759                        }
760                    }
761                }).collect();
762
763                if let Some(KeyDiff { left, right }) = &diff.key_diff {
764                    let format_keys = |keys: &BTreeSet<Vec<ColumnName>>| {
765                        if keys.is_empty() {
766                            "(none)".to_string()
767                        } else {
768                            keys.iter()
769                                .map(|key| {
770                                    let cols = key.iter().map(|c| c.as_str()).join(", ");
771                                    format!("{{{cols}}}")
772                                })
773                                .join(", ")
774                        }
775                    };
776                    lines.push(format!(
777                        "keys differ (target: {}, replacement: {})",
778                        format_keys(left),
779                        format_keys(right)
780                    ));
781                }
782                Some(lines.join("\n"))
783            }
784            AdapterError::ReplaceMaterializedViewSealed { .. } => Some(
785                "The materialized view's contents are final for all future times, so they can \
786                 no longer be changed. See \
787                 https://materialize.com/docs/sql/alter-materialized-view/#troubleshooting"
788                    .into(),
789            ),
790            AdapterError::ImpossibleTimestampConstraints { constraints } => {
791                Some(format!("Constraints:\n{}", constraints))
792            }
793            AdapterError::BoundedStalenessExceeded {
794                gap_ms,
795                slowest_input,
796                ..
797            } => {
798                let mut detail = format!(
799                    "Freshest available timestamp is {}ms older than the bound.",
800                    gap_ms,
801                );
802                if let Some(id) = slowest_input {
803                    detail.push_str(&format!(" Slowest input: {}.", id));
804                }
805                Some(detail)
806            }
807            AdapterError::BoundedStalenessTimelineUnsupported => Some(
808                "This query touches a timeline other than the EpochMilliseconds wall-clock \
809                 timeline."
810                    .into(),
811            ),
812            _ => None,
813        }
814    }
815
816    /// Reports a hint for the user about how the error could be fixed.
817    pub fn hint(&self) -> Option<String> {
818        match self {
819            AdapterError::AmbiguousSystemColumnReference => Some(
820                "Rewrite the view to refer to all columns by name. Expand all wildcards and \
821                convert all NATURAL JOINs to USING joins."
822                    .to_string(),
823            ),
824            AdapterError::Catalog(c) => c.hint(),
825            AdapterError::Eval(e) => e.hint(),
826            AdapterError::IndexInUse { .. } => Some(
827                "Drop the dependent objects first, then drop the index and recreate the \
828                 dependents. To replace them in production without downtime, use a blue/green \
829                 deployment."
830                    .to_string(),
831            ),
832            AdapterError::QueryPolicyRejected(violation) => Some(violation.hint().into()),
833            AdapterError::SubscribeFellBehind { .. } => Some(
834                "The client is not reading results fast enough. Use a client that reads output \
835                without buffering, or raise the subscribe_max_buffered_bytes system variable."
836                    .to_string(),
837            ),
838            AdapterError::Dataflow(e) => match &**e {
839                DataflowError::EvalError(e) => e.hint(),
840                DataflowError::SourceError(e) => e.hint.as_ref().map(|hint| hint.to_string()),
841                _ => None,
842            },
843            AdapterError::AlterClusterUnmanagedWhileReconfiguring => Some(
844                "Cancel the reconfiguration by altering the cluster back to its current \
845                configuration, or wait for it to settle, then convert."
846                    .to_string(),
847            ),
848            AdapterError::AlterClusterUnmanagedWhileBursting => Some(
849                "Remove the strategy with ALTER CLUSTER ... RESET (AUTO SCALING STRATEGY), \
850                or wait for the burst to wind down, then convert."
851                    .to_string(),
852            ),
853            AdapterError::AlterClusterScheduleWhileReconfiguring => Some(
854                "Cancel the reconfiguration by altering the cluster back to its current \
855                configuration, or wait for it to settle, then change the schedule."
856                    .to_string(),
857            ),
858            AdapterError::AlterClusterWaitOnScheduledCluster => Some(
859                "The scheduler reshapes a scheduled cluster's replicas in the background. \
860                Run the ALTER without a WAIT option, or set SCHEDULE = MANUAL first."
861                    .to_string(),
862            ),
863            AdapterError::InvalidClusterReplicaAz { expected, az: _ } => {
864                Some(if expected.is_empty() {
865                    "No availability zones configured; do not specify AVAILABILITY ZONE".into()
866                } else {
867                    format!("Valid availability zones are: {}", expected.join(", "))
868                })
869            }
870            AdapterError::InvalidStorageClusterSize { expected, .. } => {
871                Some(format!("Valid sizes are: {}", expected.join(", ")))
872            }
873            AdapterError::SourceOrSinkSizeRequired { expected } => Some(format!(
874                "Try choosing one of the smaller sizes to start. Available sizes: {}",
875                expected.join(", ")
876            )),
877            AdapterError::NoClusterReplicasAvailable { is_managed, .. } => {
878                Some(if *is_managed {
879                    "Use ALTER CLUSTER to adjust the replication factor of the cluster. \
880                    Example:`ALTER CLUSTER <cluster-name> SET (REPLICATION FACTOR 1)`".into()
881                } else {
882                    "Use CREATE CLUSTER REPLICA to attach cluster replicas to the cluster".into()
883                })
884            }
885            AdapterError::UntargetedLogRead { .. } => Some(
886                "Use `SET cluster_replica = <replica-name>` to target a specific replica in the \
887                 active cluster. Note that subsequent queries will only be answered by \
888                 the selected replica, which might reduce availability. To undo the replica \
889                 selection, use `RESET cluster_replica`."
890                    .into(),
891            ),
892            AdapterError::ResourceExhaustion { resource_type, .. } => Some(format!(
893                "Drop an existing {resource_type} or contact support to request a limit increase."
894            )),
895            AdapterError::StatementTimeout => Some(
896                "Consider increasing the maximum allowed statement duration for this session by \
897                 setting the statement_timeout session variable. For example, `SET \
898                 statement_timeout = '120s'`."
899                    .into(),
900            ),
901            AdapterError::PeekRowIterationLimitExceeded { .. } => Some(
902                "Reduce the number of rows the query must examine, for example by querying an \
903                 indexed, more selective result. Queries with `LIMIT` and no `ORDER BY` can also \
904                 stop early. To permit this query, increase \
905                 `compute_peek_row_iteration_limit`."
906                    .into(),
907            ),
908            AdapterError::PlanError(e) => e.hint(),
909            AdapterError::UnallowedOnCluster { cluster, .. } => {
910                (cluster != MZ_CATALOG_SERVER_CLUSTER.name).then(||
911                    "Use `SET CLUSTER = <cluster-name>` to change your cluster and re-run the query."
912                    .to_string()
913                )
914            }
915            AdapterError::InvalidAlter(_, e) => e.hint(),
916            AdapterError::Optimizer(e) => e.hint(),
917            AdapterError::ConnectionValidation(e) => e.hint(),
918            AdapterError::InputNotReadableAtRefreshAtTime(_, _) => Some(
919                "You can use `REFRESH AT greatest(mz_now(), <explicit timestamp>)` to refresh \
920                 either at the explicitly specified timestamp, or now if the given timestamp would \
921                 be in the past.".to_string()
922            ),
923            AdapterError::AlterClusterTimeout => Some(
924                "Consider increasing the timeout duration in the alter cluster statement.".into(),
925            ),
926            AdapterError::AlterClusterSuperseded => Some(
927                "Retry the ALTER CLUSTER statement if its target is still desired.".into(),
928            ),
929            AdapterError::AlterClusterResourceExhausted => Some(
930                "Reduce the target resource use, or inspect \
931                 mz_internal.mz_cluster_reconfigurations for the retained outcome."
932                    .into(),
933            ),
934            AdapterError::DDLTransactionOutcomeChanged => Some(
935                "Retry the transaction to execute its statements against the current catalog.".into()
936            ),
937            AdapterError::ConcurrentDependencyMutation { .. } => Some(
938                "Another session modified one of this statement's dependencies before \
939                 it could commit. Retry the statement.".into()
940            ),
941            AdapterError::ReadThenWriteContention => Some(
942                "Concurrent writes to the target table kept this statement from \
943                 committing. Retry the statement, or lower the write concurrency.".into()
944            ),
945            AdapterError::ReadThenWriteTimestampTooFarAhead { .. } => Some(
946                "The write timestamp this statement would have committed at is far ahead of \
947                 the wall clock. Committing there would keep writes and strict-serializable \
948                 reads on this timeline from proceeding until the clock caught up.".into()
949            ),
950            AdapterError::CollectionUnreadable { .. } => Some(
951                "This could be because the collection has recently been dropped.".into()
952            ),
953            AdapterError::ReplaceMaterializedViewSealed { .. } => Some(
954                "Create a new materialized view with the new definition instead.".into()
955            ),
956            _ => None,
957        }
958    }
959
960    pub fn code(&self) -> SqlState {
961        // We define this up here to make sure `AdapterError::` and `OptimizerError::` act the same way.
962        const RECURSION_LIMIT_ERROR_CODE: SqlState = SqlState::INTERNAL_ERROR;
963
964        // TODO(benesch): we should only use `SqlState::INTERNAL_ERROR` for
965        // those errors that are truly internal errors. At the moment we have
966        // a various classes of uncategorized errors that use this error code
967        // inappropriately.
968        match self {
969            // DATA_EXCEPTION to match what Postgres returns for degenerate
970            // range bounds
971            AdapterError::AbsurdSubscribeBounds { .. } => SqlState::DATA_EXCEPTION,
972            AdapterError::AmbiguousSystemColumnReference => SqlState::FEATURE_NOT_SUPPORTED,
973            AdapterError::Catalog(e) => match &e.kind {
974                mz_catalog::memory::error::ErrorKind::Sql(
975                    mz_sql::catalog::CatalogError::QueryPolicyInUse(_),
976                ) => SqlState::DEPENDENT_OBJECTS_STILL_EXIST,
977                mz_catalog::memory::error::ErrorKind::VarError(e) => match e {
978                    VarError::ConstrainedParameter { .. } => SqlState::INVALID_PARAMETER_VALUE,
979                    VarError::FixedValueParameter { .. } => SqlState::INVALID_PARAMETER_VALUE,
980                    VarError::InvalidParameterType { .. } => SqlState::INVALID_PARAMETER_VALUE,
981                    VarError::InvalidParameterValue { .. } => SqlState::INVALID_PARAMETER_VALUE,
982                    VarError::ReadOnlyParameter(_) => SqlState::CANT_CHANGE_RUNTIME_PARAM,
983                    VarError::UnknownParameter(_) => SqlState::UNDEFINED_OBJECT,
984                    VarError::RequiresUnsafeMode { .. } => SqlState::CANT_CHANGE_RUNTIME_PARAM,
985                    VarError::RequiresFeatureFlag { .. } => SqlState::CANT_CHANGE_RUNTIME_PARAM,
986                },
987                _ => SqlState::INTERNAL_ERROR,
988            },
989            AdapterError::ChangedPlan(_) => SqlState::FEATURE_NOT_SUPPORTED,
990            AdapterError::DuplicateCursor(_) => SqlState::DUPLICATE_CURSOR,
991            // Evaluation errors are almost all user-facing data exceptions, not
992            // internal errors. `eval_error_code` matches every variant
993            // exhaustively so the catch-all `INTERNAL_ERROR` no longer applies
994            // to errors that are really the user's fault. See SQL-326.
995            AdapterError::Eval(e) => eval_error_code(e),
996            AdapterError::Dataflow(e) => dataflow_error_code(e),
997            AdapterError::Explain(_) => SqlState::INTERNAL_ERROR,
998            AdapterError::IdExhaustionError => SqlState::INTERNAL_ERROR,
999            AdapterError::Internal(_) => SqlState::INTERNAL_ERROR,
1000            AdapterError::IntrospectionDisabled { .. } => SqlState::FEATURE_NOT_SUPPORTED,
1001            AdapterError::InvalidLogDependency { .. } => SqlState::FEATURE_NOT_SUPPORTED,
1002            AdapterError::InvalidClusterReplicaAz { .. } => SqlState::FEATURE_NOT_SUPPORTED,
1003            AdapterError::InvalidSetIsolationLevel => SqlState::ACTIVE_SQL_TRANSACTION,
1004            AdapterError::InvalidSetCluster => SqlState::ACTIVE_SQL_TRANSACTION,
1005            AdapterError::InvalidStorageClusterSize { .. } => SqlState::FEATURE_NOT_SUPPORTED,
1006            AdapterError::SourceOrSinkSizeRequired { .. } => SqlState::FEATURE_NOT_SUPPORTED,
1007            AdapterError::InvalidTableMutationSelection { .. } => {
1008                SqlState::INVALID_TRANSACTION_STATE
1009            }
1010            AdapterError::ReadThenWriteDependencyLimitExceeded { .. } => {
1011                SqlState::PROGRAM_LIMIT_EXCEEDED
1012            }
1013            AdapterError::ConstraintViolation(NotNullViolation(_)) => SqlState::NOT_NULL_VIOLATION,
1014            AdapterError::CopyFormatError(_) => SqlState::BAD_COPY_FILE_FORMAT,
1015            AdapterError::ConcurrentClusterDrop => SqlState::INVALID_TRANSACTION_STATE,
1016            AdapterError::ConcurrentDependencyDrop { .. } => SqlState::UNDEFINED_OBJECT,
1017            AdapterError::ConcurrentDependencyMutation { .. } => {
1018                SqlState::T_R_SERIALIZATION_FAILURE
1019            }
1020            AdapterError::ReadThenWriteContention => SqlState::T_R_SERIALIZATION_FAILURE,
1021            AdapterError::ReadThenWriteTimestampTooFarAhead { .. } => {
1022                // An invariant violation in the environment rather than a property of
1023                // the statement: the write timeline has run away from the wall clock.
1024                // Nothing the client sends can produce or avoid it.
1025                SqlState::INTERNAL_ERROR
1026            }
1027            AdapterError::CollectionUnreadable { .. } => SqlState::NO_DATA_FOUND,
1028            AdapterError::NoClusterReplicasAvailable { .. } => SqlState::FEATURE_NOT_SUPPORTED,
1029            AdapterError::OperationProhibitsTransaction(_) => SqlState::ACTIVE_SQL_TRANSACTION,
1030            AdapterError::OperationRequiresTransaction(_) => SqlState::NO_ACTIVE_SQL_TRANSACTION,
1031            AdapterError::ParseError(_) => SqlState::SYNTAX_ERROR,
1032            AdapterError::PlanError(PlanError::InvalidSchemaName) => SqlState::INVALID_SCHEMA_NAME,
1033            AdapterError::PlanError(PlanError::ColumnAlreadyExists { .. }) => {
1034                SqlState::DUPLICATE_COLUMN
1035            }
1036            AdapterError::PlanError(PlanError::UnknownParameter(_)) => {
1037                SqlState::UNDEFINED_PARAMETER
1038            }
1039            AdapterError::PlanError(PlanError::ParameterNotAllowed(_)) => {
1040                SqlState::UNDEFINED_PARAMETER
1041            }
1042            // `PlanError::Unsupported` is raised (via `bail_unsupported!`) only for
1043            // genuinely unsupported features, so it maps to PostgreSQL's
1044            // feature-not-supported code rather than internal-error. See SQL-326.
1045            AdapterError::PlanError(PlanError::Unsupported { .. }) => {
1046                SqlState::FEATURE_NOT_SUPPORTED
1047            }
1048            AdapterError::PlanError(_) => SqlState::INTERNAL_ERROR,
1049            AdapterError::PreparedStatementExists(_) => SqlState::DUPLICATE_PSTATEMENT,
1050            AdapterError::ReadOnlyTransaction => SqlState::READ_ONLY_SQL_TRANSACTION,
1051            AdapterError::ReadWriteUnavailable => SqlState::INVALID_TRANSACTION_STATE,
1052            AdapterError::SingleStatementTransaction => SqlState::INVALID_TRANSACTION_STATE,
1053            AdapterError::StatementTimeout => SqlState::QUERY_CANCELED,
1054            AdapterError::Canceled => SqlState::QUERY_CANCELED,
1055            AdapterError::IdleInTransactionSessionTimeout => {
1056                SqlState::IDLE_IN_TRANSACTION_SESSION_TIMEOUT
1057            }
1058            AdapterError::RecursionLimit(_) => RECURSION_LIMIT_ERROR_CODE,
1059            AdapterError::RelationOutsideTimeDomain { .. } => SqlState::INVALID_TRANSACTION_STATE,
1060            AdapterError::ResourceExhaustion { .. } => SqlState::INSUFFICIENT_RESOURCES,
1061            AdapterError::ResultSize(_) => SqlState::OUT_OF_MEMORY,
1062            AdapterError::SubscribeFellBehind { .. } => SqlState::OUT_OF_MEMORY,
1063            AdapterError::PeekRowIterationLimitExceeded { .. } => SqlState::PROGRAM_LIMIT_EXCEEDED,
1064            AdapterError::SafeModeViolation(_) => SqlState::INTERNAL_ERROR,
1065            AdapterError::SubscribeOnlyTransaction => SqlState::INVALID_TRANSACTION_STATE,
1066            AdapterError::Optimizer(e) => match e {
1067                OptimizerError::PlanError(PlanError::InvalidSchemaName) => {
1068                    SqlState::INVALID_SCHEMA_NAME
1069                }
1070                OptimizerError::PlanError(PlanError::ColumnAlreadyExists { .. }) => {
1071                    SqlState::DUPLICATE_COLUMN
1072                }
1073                OptimizerError::PlanError(PlanError::UnknownParameter(_)) => {
1074                    SqlState::UNDEFINED_PARAMETER
1075                }
1076                OptimizerError::PlanError(PlanError::ParameterNotAllowed(_)) => {
1077                    SqlState::UNDEFINED_PARAMETER
1078                }
1079                OptimizerError::PlanError(PlanError::Unsupported { .. }) => {
1080                    SqlState::FEATURE_NOT_SUPPORTED
1081                }
1082                OptimizerError::PlanError(_) => SqlState::INTERNAL_ERROR,
1083                OptimizerError::RecursionLimitError(_) => RECURSION_LIMIT_ERROR_CODE,
1084                OptimizerError::Internal(s) => {
1085                    AdapterError::Internal(s.clone()).code() // Delegate to outer
1086                }
1087                OptimizerError::EvalError(e) => {
1088                    AdapterError::Eval(e.clone()).code() // Delegate to outer
1089                }
1090                OptimizerError::TransformError(_) => SqlState::INTERNAL_ERROR,
1091                OptimizerError::UnmaterializableFunction(_) => SqlState::FEATURE_NOT_SUPPORTED,
1092                OptimizerError::UncallableFunction { .. } => SqlState::FEATURE_NOT_SUPPORTED,
1093                OptimizerError::UnsupportedTemporalExpression(_) => SqlState::FEATURE_NOT_SUPPORTED,
1094                OptimizerError::RestrictedFunction(_) => SqlState::INSUFFICIENT_PRIVILEGE,
1095                // This should be handled by peek optimization, so it's an internal error if it
1096                // reaches the user.
1097                OptimizerError::InternalUnsafeMfpPlan(_) => SqlState::INTERNAL_ERROR,
1098            },
1099            AdapterError::UnallowedOnCluster { .. } => {
1100                SqlState::S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED
1101            }
1102            AdapterError::Unauthorized(_) => SqlState::INSUFFICIENT_PRIVILEGE,
1103            AdapterError::UnknownCursor(_) => SqlState::INVALID_CURSOR_NAME,
1104            AdapterError::UnknownPreparedStatement(_) => SqlState::UNDEFINED_PSTATEMENT,
1105            AdapterError::UnknownLoginRole(_) => SqlState::INVALID_AUTHORIZATION_SPECIFICATION,
1106            AdapterError::UnknownClusterReplica { .. } => SqlState::UNDEFINED_OBJECT,
1107            AdapterError::UnrecognizedConfigurationParam(_) => SqlState::UNDEFINED_OBJECT,
1108            AdapterError::Unsupported(..) => SqlState::FEATURE_NOT_SUPPORTED,
1109            AdapterError::UnavailableFeature { .. } => SqlState::FEATURE_NOT_SUPPORTED,
1110            AdapterError::Unstructured(_) => SqlState::INTERNAL_ERROR,
1111            AdapterError::UntargetedLogRead { .. } => SqlState::FEATURE_NOT_SUPPORTED,
1112            AdapterError::DDLTransactionOutcomeChanged => SqlState::T_R_SERIALIZATION_FAILURE,
1113            AdapterError::ClusterStateChanged { .. } => SqlState::T_R_SERIALIZATION_FAILURE,
1114            // It's not immediately clear which error code to use here because a
1115            // "write-only transaction", "single table write transaction", or "ddl only
1116            // transaction" are not things in Postgres. This error code is the generic "bad txn
1117            // thing" code, so it's probably the best choice.
1118            AdapterError::WriteOnlyTransaction => SqlState::INVALID_TRANSACTION_STATE,
1119            AdapterError::DDLOnlyTransaction => SqlState::INVALID_TRANSACTION_STATE,
1120            AdapterError::Storage(_) | AdapterError::Compute(_) | AdapterError::Orchestrator(_) => {
1121                SqlState::INTERNAL_ERROR
1122            }
1123            AdapterError::DependentObject(_) => SqlState::DEPENDENT_OBJECTS_STILL_EXIST,
1124            AdapterError::IndexInUse { .. } => SqlState::DEPENDENT_OBJECTS_STILL_EXIST,
1125            AdapterError::InvalidAlter(_, _) => SqlState::FEATURE_NOT_SUPPORTED,
1126            AdapterError::ConnectionValidation(_) => SqlState::SYSTEM_ERROR,
1127            // `DATA_EXCEPTION`, similarly to `AbsurdSubscribeBounds`.
1128            AdapterError::MaterializedViewWouldNeverRefresh(_, _) => SqlState::DATA_EXCEPTION,
1129            AdapterError::InputNotReadableAtRefreshAtTime(_, _) => SqlState::DATA_EXCEPTION,
1130            AdapterError::RtrTimeout(_) => SqlState::QUERY_CANCELED,
1131            AdapterError::RtrDropFailure(_) => SqlState::UNDEFINED_OBJECT,
1132            AdapterError::UnreadableSinkCollection => SqlState::from_code("MZ009"),
1133            AdapterError::UserSessionsDisallowed => SqlState::from_code("MZ010"),
1134            AdapterError::NetworkPolicyDenied(_) => SqlState::from_code("MZ011"),
1135            AdapterError::QueryPolicyRejected(_) => SqlState::INSUFFICIENT_RESOURCES,
1136            // In read-only mode all transactions are implicitly read-only
1137            // transactions.
1138            AdapterError::ReadOnly => SqlState::READ_ONLY_SQL_TRANSACTION,
1139            AdapterError::AlterClusterTimeout => SqlState::QUERY_CANCELED,
1140            AdapterError::AlterClusterSuperseded => SqlState::QUERY_CANCELED,
1141            AdapterError::AlterClusterResourceExhausted => SqlState::INSUFFICIENT_RESOURCES,
1142            AdapterError::AlterClusterUnmanagedWhileReconfiguring => SqlState::OBJECT_IN_USE,
1143            AdapterError::AlterClusterUnmanagedWhileBursting => SqlState::OBJECT_IN_USE,
1144            AdapterError::AlterClusterScheduleWhileReconfiguring => SqlState::OBJECT_IN_USE,
1145            AdapterError::AlterClusterWaitOnScheduledCluster => SqlState::FEATURE_NOT_SUPPORTED,
1146            AdapterError::ReplacementSchemaMismatch(_) => SqlState::FEATURE_NOT_SUPPORTED,
1147            AdapterError::AuthenticationError(AuthenticationError::InvalidCredentials) => {
1148                SqlState::INVALID_PASSWORD
1149            }
1150            AdapterError::AuthenticationError(_) => SqlState::INVALID_AUTHORIZATION_SPECIFICATION,
1151            AdapterError::ReplaceMaterializedViewSealed { .. } => {
1152                SqlState::OBJECT_NOT_IN_PREREQUISITE_STATE
1153            }
1154            // similar to AbsurdSubscribeBounds
1155            AdapterError::ImpossibleTimestampConstraints { .. } => SqlState::DATA_EXCEPTION,
1156            AdapterError::OidcGroupSyncFailed(_) => SqlState::INTERNAL_ERROR,
1157            AdapterError::BoundedStalenessExceeded { .. } => SqlState::T_R_SERIALIZATION_FAILURE,
1158            // Matches ReadOnlyTransaction/ReadOnly: a write was rejected
1159            // because the session is effectively read-only.
1160            AdapterError::BoundedStalenessReadOnly => SqlState::READ_ONLY_SQL_TRANSACTION,
1161            AdapterError::BoundedStalenessRealTimeRecencyConflict => {
1162                SqlState::FEATURE_NOT_SUPPORTED
1163            }
1164            AdapterError::BoundedStalenessTimelineUnsupported => SqlState::FEATURE_NOT_SUPPORTED,
1165        }
1166    }
1167
1168    pub fn internal<E: std::fmt::Display>(context: &str, e: E) -> AdapterError {
1169        AdapterError::Internal(format!("{context}: {e}"))
1170    }
1171
1172    // We don't want the following error conversions to `ConcurrentDependencyDrop` to happen
1173    // automatically, because it might depend on the context whether `ConcurrentDependencyDrop`
1174    // is appropriate, so we want to make the conversion target explicit at the call site.
1175    // For example, maybe we get an `InstanceMissing` if the user specifies a non-existing cluster,
1176    // in which case `ConcurrentDependencyDrop` would not be appropriate.
1177
1178    pub fn concurrent_dependency_drop_from_collection_missing(e: CollectionMissing) -> Self {
1179        AdapterError::ConcurrentDependencyDrop {
1180            dependency_kind: "collection",
1181            dependency_id: e.0.to_string(),
1182        }
1183    }
1184
1185    /// Maps a lookup error of the session task's compute instance clients.
1186    pub fn concurrent_dependency_drop_from_collection_lookup_error(
1187        e: CollectionLookupError,
1188        compute_instance: ComputeInstanceId,
1189    ) -> Self {
1190        match e {
1191            CollectionLookupError::InstanceMissing(id) => AdapterError::ConcurrentDependencyDrop {
1192                dependency_kind: "cluster",
1193                dependency_id: id.to_string(),
1194            },
1195            CollectionLookupError::CollectionMissing(id) => {
1196                AdapterError::ConcurrentDependencyDrop {
1197                    dependency_kind: "collection",
1198                    dependency_id: id.to_string(),
1199                }
1200            }
1201            CollectionLookupError::InstanceShutDown => AdapterError::ConcurrentDependencyDrop {
1202                dependency_kind: "cluster",
1203                dependency_id: compute_instance.to_string(),
1204            },
1205        }
1206    }
1207
1208    /// Maps a collection lookup error of the compute controller.
1209    pub fn concurrent_dependency_drop_from_compute_lookup_error(
1210        e: compute_error::CollectionLookupError,
1211    ) -> Self {
1212        match e {
1213            compute_error::CollectionLookupError::InstanceMissing(id) => {
1214                AdapterError::ConcurrentDependencyDrop {
1215                    dependency_kind: "cluster",
1216                    dependency_id: id.to_string(),
1217                }
1218            }
1219            compute_error::CollectionLookupError::CollectionMissing(id) => {
1220                AdapterError::ConcurrentDependencyDrop {
1221                    dependency_kind: "collection",
1222                    dependency_id: id.to_string(),
1223                }
1224            }
1225        }
1226    }
1227
1228    pub fn concurrent_dependency_drop_from_instance_peek_error(
1229        e: mz_compute_client::controller::instance_client::PeekError,
1230        compute_instance: ComputeInstanceId,
1231    ) -> AdapterError {
1232        use mz_compute_client::controller::instance_client::PeekError::*;
1233        match e {
1234            ReplicaMissing(id) => AdapterError::ConcurrentDependencyDrop {
1235                dependency_kind: "replica",
1236                dependency_id: id.to_string(),
1237            },
1238            InstanceShutDown => AdapterError::ConcurrentDependencyDrop {
1239                dependency_kind: "cluster",
1240                dependency_id: compute_instance.to_string(),
1241            },
1242            e @ ReadHoldIdMismatch(_) => AdapterError::internal("instance peek error", e),
1243            e @ ReadHoldInsufficient(_) => AdapterError::internal("instance peek error", e),
1244        }
1245    }
1246
1247    pub fn concurrent_dependency_drop_from_collection_update_error(
1248        e: compute_error::CollectionUpdateError,
1249    ) -> Self {
1250        use compute_error::CollectionUpdateError::*;
1251        match e {
1252            InstanceMissing(id) => AdapterError::ConcurrentDependencyDrop {
1253                dependency_kind: "cluster",
1254                dependency_id: id.to_string(),
1255            },
1256            CollectionMissing(id) => AdapterError::ConcurrentDependencyDrop {
1257                dependency_kind: "collection",
1258                dependency_id: id.to_string(),
1259            },
1260        }
1261    }
1262
1263    pub fn concurrent_dependency_drop_from_peek_error(
1264        e: mz_compute_client::controller::error::PeekError,
1265    ) -> AdapterError {
1266        use mz_compute_client::controller::error::PeekError::*;
1267        match e {
1268            InstanceMissing(id) => AdapterError::ConcurrentDependencyDrop {
1269                dependency_kind: "cluster",
1270                dependency_id: id.to_string(),
1271            },
1272            CollectionMissing(id) => AdapterError::ConcurrentDependencyDrop {
1273                dependency_kind: "collection",
1274                dependency_id: id.to_string(),
1275            },
1276            ReplicaMissing(id) => AdapterError::ConcurrentDependencyDrop {
1277                dependency_kind: "replica",
1278                dependency_id: id.to_string(),
1279            },
1280            e @ (ReadHoldIdMismatch(_) | SinceViolation(_)) => {
1281                AdapterError::internal("peek error", e)
1282            }
1283        }
1284    }
1285
1286    pub fn concurrent_dependency_drop_from_dataflow_creation_error(
1287        e: compute_error::DataflowCreationError,
1288    ) -> Self {
1289        use compute_error::DataflowCreationError::*;
1290        match e {
1291            InstanceMissing(id) => AdapterError::ConcurrentDependencyDrop {
1292                dependency_kind: "cluster",
1293                dependency_id: id.to_string(),
1294            },
1295            CollectionMissing(id) => AdapterError::ConcurrentDependencyDrop {
1296                dependency_kind: "collection",
1297                dependency_id: id.to_string(),
1298            },
1299            ReplicaMissing(id) => AdapterError::ConcurrentDependencyDrop {
1300                dependency_kind: "replica",
1301                dependency_id: id.to_string(),
1302            },
1303            MissingAsOf | SinceViolation(..) | EmptyAsOfForSubscribe | EmptyAsOfForCopyTo => {
1304                AdapterError::internal("dataflow creation error", e)
1305            }
1306        }
1307    }
1308}
1309
1310impl fmt::Display for AdapterError {
1311    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1312        match self {
1313            AdapterError::AbsurdSubscribeBounds { as_of, up_to } => {
1314                write!(
1315                    f,
1316                    "subscription lower bound (`AS OF`) is greater than its upper bound (`UP TO`): \
1317                     {as_of} > {up_to}",
1318                )
1319            }
1320            AdapterError::AmbiguousSystemColumnReference => {
1321                write!(
1322                    f,
1323                    "cannot use wildcard expansions or NATURAL JOINs in a view that depends on \
1324                    system objects"
1325                )
1326            }
1327            AdapterError::ChangedPlan(e) => write!(f, "{}", e),
1328            AdapterError::Catalog(e) => e.fmt(f),
1329            AdapterError::DuplicateCursor(name) => {
1330                write!(f, "cursor {} already exists", name.quoted())
1331            }
1332            AdapterError::Eval(e) => e.fmt(f),
1333            AdapterError::Dataflow(e) => e.fmt(f),
1334            AdapterError::Explain(e) => e.fmt(f),
1335            AdapterError::IdExhaustionError => f.write_str("ID allocator exhausted all valid IDs"),
1336            AdapterError::Internal(e) => write!(f, "internal error: {}", e),
1337            AdapterError::IntrospectionDisabled { .. } => write!(
1338                f,
1339                "cannot read log sources of replica with disabled introspection"
1340            ),
1341            AdapterError::InvalidLogDependency { object_type, .. } => {
1342                write!(f, "{object_type} objects cannot depend on log sources")
1343            }
1344            AdapterError::InvalidClusterReplicaAz { az, expected: _ } => {
1345                write!(f, "unknown cluster replica availability zone {az}",)
1346            }
1347            AdapterError::InvalidSetIsolationLevel => write!(
1348                f,
1349                "SET TRANSACTION ISOLATION LEVEL must be called before any query"
1350            ),
1351            AdapterError::InvalidSetCluster => {
1352                write!(f, "SET cluster cannot be called in an active transaction")
1353            }
1354            AdapterError::InvalidStorageClusterSize { size, .. } => {
1355                write!(f, "unknown source size {size}")
1356            }
1357            AdapterError::SourceOrSinkSizeRequired { .. } => {
1358                write!(f, "must specify either cluster or size option")
1359            }
1360            AdapterError::InvalidTableMutationSelection { .. } => {
1361                write!(
1362                    f,
1363                    "invalid selection: every relation leaf must be a writable user table"
1364                )
1365            }
1366            AdapterError::ReadThenWriteDependencyLimitExceeded {
1367                max_rw_dependencies,
1368            } => {
1369                write!(
1370                    f,
1371                    "selection has too many transitive dependencies to validate (limit {max_rw_dependencies})"
1372                )
1373            }
1374            AdapterError::PeekRowIterationLimitExceeded { limit } => {
1375                write!(
1376                    f,
1377                    "query exceeded the configured row iteration limit of {limit} rows"
1378                )
1379            }
1380            AdapterError::ReplaceMaterializedViewSealed { name } => {
1381                write!(
1382                    f,
1383                    "materialized view {name} is sealed and thus cannot be replaced"
1384                )
1385            }
1386            AdapterError::ConstraintViolation(not_null_violation) => {
1387                write!(f, "{}", not_null_violation)
1388            }
1389            AdapterError::CopyFormatError(e) => write!(f, "{e}"),
1390            AdapterError::ConcurrentClusterDrop => {
1391                write!(f, "the transaction's active cluster has been dropped")
1392            }
1393            AdapterError::ConcurrentDependencyDrop {
1394                dependency_kind,
1395                dependency_id,
1396            } => {
1397                write!(f, "{dependency_kind} '{dependency_id}' was dropped")
1398            }
1399            AdapterError::ConcurrentDependencyMutation { dependency_id } => {
1400                write!(
1401                    f,
1402                    "catalog item '{dependency_id}' was concurrently modified"
1403                )
1404            }
1405            AdapterError::ReadThenWriteContention => {
1406                write!(
1407                    f,
1408                    "read-then-write exceeded maximum retry attempts under contention"
1409                )
1410            }
1411            AdapterError::ReadThenWriteTimestampTooFarAhead {
1412                target_timestamp,
1413                limit,
1414            } => {
1415                write!(
1416                    f,
1417                    "read-then-write would have to commit at {target_timestamp}, past the \
1418                     highest timestamp the write timeline may be advanced to ({limit})"
1419                )
1420            }
1421            AdapterError::CollectionUnreadable { id } => {
1422                write!(f, "collection '{id}' is not readable at any timestamp")
1423            }
1424            AdapterError::NoClusterReplicasAvailable { name, .. } => {
1425                write!(
1426                    f,
1427                    "CLUSTER {} has no replicas available to service request",
1428                    name.quoted()
1429                )
1430            }
1431            AdapterError::OperationProhibitsTransaction(op) => {
1432                write!(f, "{} cannot be run inside a transaction block", op)
1433            }
1434            AdapterError::OperationRequiresTransaction(op) => {
1435                write!(f, "{} can only be used in transaction blocks", op)
1436            }
1437            AdapterError::ParseError(e) => e.fmt(f),
1438            AdapterError::PlanError(e) => e.fmt(f),
1439            AdapterError::PreparedStatementExists(name) => {
1440                write!(f, "prepared statement {} already exists", name.quoted())
1441            }
1442            AdapterError::ReadOnlyTransaction => f.write_str("transaction in read-only mode"),
1443            AdapterError::SingleStatementTransaction => {
1444                f.write_str("this transaction can only execute a single statement")
1445            }
1446            AdapterError::ReadWriteUnavailable => {
1447                f.write_str("transaction read-write mode must be set before any query")
1448            }
1449            AdapterError::StatementTimeout => {
1450                write!(f, "canceling statement due to statement timeout")
1451            }
1452            AdapterError::Canceled => {
1453                write!(f, "canceling statement due to user request")
1454            }
1455            AdapterError::IdleInTransactionSessionTimeout => {
1456                write!(
1457                    f,
1458                    "terminating connection due to idle-in-transaction timeout"
1459                )
1460            }
1461            AdapterError::RecursionLimit(e) => e.fmt(f),
1462            AdapterError::RelationOutsideTimeDomain { .. } => {
1463                write!(
1464                    f,
1465                    "Transactions can only reference objects in the same timedomain. \
1466                     See https://materialize.com/docs/sql/begin/#same-timedomain-error",
1467                )
1468            }
1469            AdapterError::ResourceExhaustion {
1470                resource_type,
1471                limit_name,
1472                desired,
1473                limit,
1474                current,
1475            } => {
1476                write!(
1477                    f,
1478                    "creating {resource_type} would violate {limit_name} limit (desired: {desired}, limit: {limit}, current: {current})"
1479                )
1480            }
1481            AdapterError::ResultSize(e) => write!(f, "{e}"),
1482            AdapterError::SubscribeFellBehind {
1483                buffered_bytes,
1484                max_buffered_bytes,
1485            } => {
1486                use bytesize::ByteSize;
1487                let buffered = u64::cast_from(*buffered_bytes);
1488                let max = u64::cast_from(*max_buffered_bytes);
1489                write!(
1490                    f,
1491                    "SUBSCRIBE fell behind: the client did not read results fast enough, so its backlog reached {}, exceeding the {} budget",
1492                    ByteSize::b(buffered),
1493                    ByteSize::b(max),
1494                )
1495            }
1496            AdapterError::SafeModeViolation(feature) => {
1497                write!(f, "cannot create {} in safe mode", feature)
1498            }
1499            AdapterError::SubscribeOnlyTransaction => {
1500                f.write_str("SUBSCRIBE in transactions must be the only read statement")
1501            }
1502            AdapterError::Optimizer(e) => e.fmt(f),
1503            AdapterError::UnallowedOnCluster {
1504                depends_on,
1505                cluster,
1506            } => {
1507                let items = depends_on.into_iter().map(|item| item.quoted()).join(", ");
1508                write!(
1509                    f,
1510                    "querying the following items {items} is not allowed from the {} cluster",
1511                    cluster.quoted()
1512                )
1513            }
1514            AdapterError::Unauthorized(unauthorized) => {
1515                write!(f, "{unauthorized}")
1516            }
1517            AdapterError::UnknownCursor(name) => {
1518                write!(f, "cursor {} does not exist", name.quoted())
1519            }
1520            AdapterError::UnknownLoginRole(name) => {
1521                write!(f, "role {} does not exist", name.quoted())
1522            }
1523            AdapterError::Unsupported(features) => write!(f, "{} are not supported", features),
1524            AdapterError::Unstructured(e) => write!(f, "{}", e.display_with_causes()),
1525            AdapterError::WriteOnlyTransaction => f.write_str("transaction in write-only mode"),
1526            AdapterError::UnknownPreparedStatement(name) => {
1527                write!(f, "prepared statement {} does not exist", name.quoted())
1528            }
1529            AdapterError::UnknownClusterReplica {
1530                cluster_name,
1531                replica_name,
1532            } => write!(
1533                f,
1534                "cluster replica '{cluster_name}.{replica_name}' does not exist"
1535            ),
1536            AdapterError::UnrecognizedConfigurationParam(setting_name) => write!(
1537                f,
1538                "unrecognized configuration parameter {}",
1539                setting_name.quoted()
1540            ),
1541            AdapterError::UntargetedLogRead { .. } => {
1542                f.write_str("log source reads must target a replica")
1543            }
1544            AdapterError::DDLOnlyTransaction => f.write_str(
1545                "transactions which modify objects are restricted to just modifying objects",
1546            ),
1547            AdapterError::DDLTransactionOutcomeChanged => f.write_str(
1548                "a statement in this transaction would produce a different result at commit",
1549            ),
1550            AdapterError::ClusterStateChanged { cluster_id } => {
1551                write!(f, "cluster {cluster_id} was concurrently modified")
1552            }
1553            AdapterError::Storage(e) => e.fmt(f),
1554            AdapterError::Compute(e) => e.fmt(f),
1555            AdapterError::Orchestrator(e) => e.fmt(f),
1556            AdapterError::DependentObject(dependent_objects) => {
1557                let role_str = if dependent_objects.keys().count() == 1 {
1558                    "role"
1559                } else {
1560                    "roles"
1561                };
1562                write!(
1563                    f,
1564                    "{role_str} \"{}\" cannot be dropped because some objects depend on it",
1565                    dependent_objects.keys().join(", ")
1566                )
1567            }
1568            AdapterError::IndexInUse { blocked } => {
1569                // Mirrors `PlanError::DependentObjectsStillExist` so clients see one shape of
1570                // RESTRICT failure regardless of which layer detected the dependency.
1571                let dependents = fmt_dependents(blocked.iter().flat_map(|(_, deps)| deps).unique());
1572                match &blocked[..] {
1573                    [(index_name, _)] => write!(
1574                        f,
1575                        "cannot drop index {}: still depended upon by {dependents}",
1576                        index_name.quoted()
1577                    ),
1578                    blocked => write!(
1579                        f,
1580                        "cannot drop indexes {}: still depended upon by {dependents}",
1581                        blocked.iter().map(|(name, _)| name.quoted()).join(", ")
1582                    ),
1583                }
1584            }
1585            AdapterError::InvalidAlter(t, e) => {
1586                write!(f, "invalid ALTER {t}: {e}")
1587            }
1588            AdapterError::ConnectionValidation(e) => e.fmt(f),
1589            AdapterError::MaterializedViewWouldNeverRefresh(_, _) => {
1590                write!(
1591                    f,
1592                    "all the specified refreshes of the materialized view would be too far in the past, and thus they \
1593                    would never happen"
1594                )
1595            }
1596            AdapterError::InputNotReadableAtRefreshAtTime(_, _) => {
1597                write!(
1598                    f,
1599                    "REFRESH AT requested for a time where not all the inputs are readable"
1600                )
1601            }
1602            AdapterError::RtrTimeout(_) => {
1603                write!(
1604                    f,
1605                    "timed out before ingesting the source's visible frontier when real-time-recency query issued"
1606                )
1607            }
1608            AdapterError::RtrDropFailure(_) => write!(
1609                f,
1610                "real-time source dropped before ingesting the upstream system's visible frontier"
1611            ),
1612            AdapterError::UnreadableSinkCollection => {
1613                write!(f, "collection is not readable at any time")
1614            }
1615            AdapterError::UserSessionsDisallowed => write!(f, "login blocked"),
1616            AdapterError::NetworkPolicyDenied(_) => write!(f, "session denied"),
1617            AdapterError::QueryPolicyRejected(violation) => {
1618                write!(f, "query rejected: {}", violation.reason())
1619            }
1620            AdapterError::ReadOnly => write!(f, "cannot write in read-only mode"),
1621            AdapterError::AlterClusterTimeout => {
1622                write!(f, "canceling statement, provided timeout lapsed")
1623            }
1624            AdapterError::AlterClusterSuperseded => {
1625                write!(
1626                    f,
1627                    "cluster reconfiguration was superseded by another ALTER CLUSTER"
1628                )
1629            }
1630            AdapterError::AlterClusterResourceExhausted => {
1631                write!(
1632                    f,
1633                    "cluster reconfiguration could not provision its target within the available resource limits"
1634                )
1635            }
1636            AdapterError::AuthenticationError(e) => {
1637                write!(f, "authentication error {e}")
1638            }
1639            AdapterError::UnavailableFeature { feature, docs } => {
1640                write!(f, "{} is not supported in this environment.", feature)?;
1641                if let Some(docs) = docs {
1642                    write!(
1643                        f,
1644                        " For more information consult the documentation at {docs}"
1645                    )?;
1646                }
1647                Ok(())
1648            }
1649            AdapterError::AlterClusterUnmanagedWhileReconfiguring => {
1650                write!(
1651                    f,
1652                    "cannot convert cluster to unmanaged while a reconfiguration is in progress"
1653                )
1654            }
1655            AdapterError::AlterClusterUnmanagedWhileBursting => {
1656                write!(
1657                    f,
1658                    "cannot convert cluster to unmanaged while a hydration burst is in progress"
1659                )
1660            }
1661            AdapterError::AlterClusterScheduleWhileReconfiguring => {
1662                write!(
1663                    f,
1664                    "cannot change the cluster schedule while a reconfiguration is in progress"
1665                )
1666            }
1667            AdapterError::AlterClusterWaitOnScheduledCluster => {
1668                write!(
1669                    f,
1670                    "WAIT is not supported when the cluster SCHEDULE is not MANUAL"
1671                )
1672            }
1673            AdapterError::ReplacementSchemaMismatch(_) => {
1674                write!(f, "replacement schema differs from target schema")
1675            }
1676            AdapterError::ImpossibleTimestampConstraints { .. } => {
1677                write!(f, "could not find a valid timestamp for the query")
1678            }
1679            AdapterError::OidcGroupSyncFailed(msg) => {
1680                write!(f, "OIDC group-to-role sync failed: {msg}")
1681            }
1682            AdapterError::BoundedStalenessExceeded { bound, .. } => {
1683                write!(
1684                    f,
1685                    "cannot serve query under bounded staleness {}",
1686                    humantime::format_duration(*bound),
1687                )
1688            }
1689            AdapterError::BoundedStalenessReadOnly => {
1690                f.write_str("writes are not permitted under bounded staleness isolation")
1691            }
1692            AdapterError::BoundedStalenessRealTimeRecencyConflict => {
1693                f.write_str("real_time_recency cannot be combined with bounded staleness isolation")
1694            }
1695            AdapterError::BoundedStalenessTimelineUnsupported => {
1696                f.write_str("bounded staleness isolation requires the EpochMilliseconds timeline")
1697            }
1698        }
1699    }
1700}
1701
1702impl From<anyhow::Error> for AdapterError {
1703    fn from(e: anyhow::Error) -> AdapterError {
1704        match e.downcast::<PlanError>() {
1705            Ok(plan_error) => AdapterError::PlanError(plan_error),
1706            Err(e) => AdapterError::Unstructured(e),
1707        }
1708    }
1709}
1710
1711impl From<TryFromIntError> for AdapterError {
1712    fn from(e: TryFromIntError) -> AdapterError {
1713        AdapterError::Unstructured(e.into())
1714    }
1715}
1716
1717impl From<TryFromDecimalError> for AdapterError {
1718    fn from(e: TryFromDecimalError) -> AdapterError {
1719        AdapterError::Unstructured(e.into())
1720    }
1721}
1722
1723impl From<mz_catalog::memory::error::Error> for AdapterError {
1724    fn from(e: mz_catalog::memory::error::Error) -> AdapterError {
1725        AdapterError::Catalog(e)
1726    }
1727}
1728
1729impl From<mz_catalog::durable::CatalogError> for AdapterError {
1730    fn from(e: mz_catalog::durable::CatalogError) -> Self {
1731        mz_catalog::memory::error::Error::from(e).into()
1732    }
1733}
1734
1735impl From<mz_catalog::durable::DurableCatalogError> for AdapterError {
1736    fn from(e: mz_catalog::durable::DurableCatalogError) -> Self {
1737        mz_catalog::durable::CatalogError::from(e).into()
1738    }
1739}
1740
1741impl From<EvalError> for AdapterError {
1742    fn from(e: EvalError) -> AdapterError {
1743        AdapterError::Eval(e)
1744    }
1745}
1746
1747impl From<mz_compute_client::protocol::response::PeekError> for AdapterError {
1748    fn from(error: mz_compute_client::protocol::response::PeekError) -> Self {
1749        use mz_compute_client::protocol::response::PeekError;
1750
1751        match error {
1752            PeekError::Dataflow(error) => AdapterError::Dataflow(error),
1753            PeekError::Unstructured(error) => AdapterError::Unstructured(anyhow::Error::msg(error)),
1754            PeekError::RowIterationLimitExceeded { limit } => {
1755                AdapterError::PeekRowIterationLimitExceeded { limit }
1756            }
1757            error @ PeekError::ResultExceedsMaxSize { .. } => {
1758                AdapterError::ResultSize(error.to_string())
1759            }
1760        }
1761    }
1762}
1763
1764impl From<ExplainError> for AdapterError {
1765    fn from(e: ExplainError) -> AdapterError {
1766        match e {
1767            ExplainError::RecursionLimitError(e) => AdapterError::RecursionLimit(e),
1768            e => AdapterError::Explain(e),
1769        }
1770    }
1771}
1772
1773impl From<mz_sql::catalog::CatalogError> for AdapterError {
1774    fn from(e: mz_sql::catalog::CatalogError) -> AdapterError {
1775        AdapterError::Catalog(mz_catalog::memory::error::Error::from(e))
1776    }
1777}
1778
1779impl From<PlanError> for AdapterError {
1780    fn from(e: PlanError) -> AdapterError {
1781        match e {
1782            PlanError::UnknownCursor(name) => AdapterError::UnknownCursor(name),
1783            _ => AdapterError::PlanError(e),
1784        }
1785    }
1786}
1787
1788impl From<OptimizerError> for AdapterError {
1789    fn from(e: OptimizerError) -> AdapterError {
1790        use OptimizerError::*;
1791        match e {
1792            PlanError(e) => Self::PlanError(e),
1793            RecursionLimitError(e) => Self::RecursionLimit(e),
1794            EvalError(e) => Self::Eval(e),
1795            InternalUnsafeMfpPlan(e) => Self::Internal(e),
1796            Internal(e) => Self::Internal(e),
1797            RestrictedFunction(func) => {
1798                Self::Unauthorized(mz_sql::rbac::UnauthorizedError::RestrictedSystemObject {
1799                    object_name: format!("function {func}"),
1800                })
1801            }
1802            e => Self::Optimizer(e),
1803        }
1804    }
1805}
1806
1807impl From<NotNullViolation> for AdapterError {
1808    fn from(e: NotNullViolation) -> AdapterError {
1809        AdapterError::ConstraintViolation(e)
1810    }
1811}
1812
1813impl From<RecursionLimitError> for AdapterError {
1814    fn from(e: RecursionLimitError) -> AdapterError {
1815        AdapterError::RecursionLimit(e)
1816    }
1817}
1818
1819impl From<oneshot::error::RecvError> for AdapterError {
1820    fn from(e: oneshot::error::RecvError) -> AdapterError {
1821        AdapterError::Unstructured(e.into())
1822    }
1823}
1824
1825impl From<StorageError> for AdapterError {
1826    fn from(e: StorageError) -> Self {
1827        AdapterError::Storage(e)
1828    }
1829}
1830
1831impl From<compute_error::InstanceExists> for AdapterError {
1832    fn from(e: compute_error::InstanceExists) -> Self {
1833        AdapterError::Compute(e.into())
1834    }
1835}
1836
1837impl From<TimestampError> for AdapterError {
1838    fn from(e: TimestampError) -> Self {
1839        let e: EvalError = e.into();
1840        e.into()
1841    }
1842}
1843
1844impl From<mz_sql_parser::parser::ParserStatementError> for AdapterError {
1845    fn from(e: mz_sql_parser::parser::ParserStatementError) -> Self {
1846        AdapterError::ParseError(e)
1847    }
1848}
1849
1850impl From<VarError> for AdapterError {
1851    fn from(e: VarError) -> Self {
1852        let e: mz_catalog::memory::error::Error = e.into();
1853        e.into()
1854    }
1855}
1856
1857impl From<rbac::UnauthorizedError> for AdapterError {
1858    fn from(e: rbac::UnauthorizedError) -> Self {
1859        AdapterError::Unauthorized(e)
1860    }
1861}
1862
1863impl From<mz_sql_parser::ast::IdentError> for AdapterError {
1864    fn from(value: mz_sql_parser::ast::IdentError) -> Self {
1865        AdapterError::PlanError(PlanError::InvalidIdent(value))
1866    }
1867}
1868
1869impl From<mz_pgwire_common::ConnectionError> for AdapterError {
1870    fn from(value: mz_pgwire_common::ConnectionError) -> Self {
1871        match value {
1872            mz_pgwire_common::ConnectionError::TooManyConnections { current, limit } => {
1873                AdapterError::ResourceExhaustion {
1874                    resource_type: "connection".into(),
1875                    limit_name: "max_connections".into(),
1876                    desired: (current + 1).to_string(),
1877                    limit: limit.to_string(),
1878                    current: current.to_string(),
1879                }
1880            }
1881        }
1882    }
1883}
1884
1885impl From<NetworkPolicyError> for AdapterError {
1886    fn from(value: NetworkPolicyError) -> Self {
1887        AdapterError::NetworkPolicyDenied(value)
1888    }
1889}
1890
1891impl From<ConnectionValidationError> for AdapterError {
1892    fn from(e: ConnectionValidationError) -> AdapterError {
1893        AdapterError::ConnectionValidation(e)
1894    }
1895}
1896
1897impl Error for AdapterError {}
1898
1899#[cfg(test)]
1900mod tests {
1901    use super::*;
1902
1903    #[mz_ore::test]
1904    fn alter_cluster_resource_exhausted_is_specific() {
1905        let error = AdapterError::AlterClusterResourceExhausted;
1906        assert_eq!(error.code(), SqlState::INSUFFICIENT_RESOURCES);
1907        assert_eq!(
1908            error.hint().as_deref(),
1909            Some(
1910                "Reduce the target resource use, or inspect \
1911                 mz_internal.mz_cluster_reconfigurations for the retained outcome."
1912            )
1913        );
1914        assert_eq!(
1915            error.to_string(),
1916            "cluster reconfiguration could not provision its target within the available resource limits"
1917        );
1918    }
1919
1920    #[mz_ore::test]
1921    fn peek_row_iteration_limit_error_is_user_facing() {
1922        let response = AdapterError::PeekRowIterationLimitExceeded { limit: 1000 }
1923            .into_response(Severity::Error);
1924
1925        assert_eq!(response.code, SqlState::PROGRAM_LIMIT_EXCEEDED);
1926        assert_eq!(
1927            response.message,
1928            "query exceeded the configured row iteration limit of 1000 rows"
1929        );
1930        assert_eq!(
1931            response.detail.as_deref(),
1932            Some(
1933                "The query attempted to examine more than 1000 rows on a single compute worker. \
1934                 This limit prevents long-running SELECT queries from delaying other work on the \
1935                 cluster."
1936            )
1937        );
1938        assert!(
1939            response
1940                .hint
1941                .as_deref()
1942                .is_some_and(|hint| hint.contains("compute_peek_row_iteration_limit"))
1943        );
1944    }
1945
1946    #[mz_ore::test]
1947    fn structured_dataflow_error_preserves_message_and_code() {
1948        use mz_compute_client::protocol::response::PeekError;
1949
1950        let dataflow_error = DataflowError::from(EvalError::DivisionByZero);
1951        let expected_message = dataflow_error.to_string();
1952        let response =
1953            AdapterError::from(PeekError::from(dataflow_error)).into_response(Severity::Error);
1954
1955        assert_eq!(response.code, SqlState::DIVISION_BY_ZERO);
1956        assert_eq!(response.message, expected_message);
1957    }
1958}
1959
1960/// Renders `(object type, name)` pairs as `materialized view "mv", index "i"`.
1961fn fmt_dependents<'a>(dependents: impl Iterator<Item = &'a (String, String)>) -> String {
1962    dependents
1963        .map(|(dependent_type, dependent_name)| {
1964            format!("{} {}", dependent_type, dependent_name.quoted())
1965        })
1966        .join(", ")
1967}