Skip to main content

mz_sql/plan/
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::BTreeSet;
11use std::error::Error;
12use std::num::{ParseIntError, TryFromIntError};
13use std::sync::Arc;
14use std::time::Duration;
15use std::{fmt, io};
16
17use itertools::Itertools;
18use mz_expr::EvalError;
19use mz_mysql_util::MySqlError;
20use mz_ore::error::ErrorExt;
21use mz_ore::stack::RecursionLimitError;
22use mz_ore::str::{StrExt, separated};
23use mz_postgres_util::PostgresError;
24use mz_repr::adt::char::InvalidCharLengthError;
25use mz_repr::adt::mz_acl_item::AclMode;
26use mz_repr::adt::numeric::InvalidNumericMaxScaleError;
27use mz_repr::adt::timestamp::InvalidTimestampPrecisionError;
28use mz_repr::adt::varchar::InvalidVarCharMaxLengthError;
29use mz_repr::{CatalogItemId, ColumnName, strconv};
30use mz_sql_parser::ast::display::AstDisplay;
31use mz_sql_parser::ast::{IdentError, UnresolvedItemName};
32use mz_sql_parser::parser::{ParserError, ParserStatementError};
33use mz_sql_server_util::SqlServerError;
34use mz_storage_types::sources::ExternalReferenceResolutionError;
35
36use crate::catalog::{
37    CatalogError, CatalogItemType, ErrorMessageObjectDescription, SystemObjectType,
38};
39use crate::names::{PartialItemName, ResolvedItemName};
40use crate::plan::ObjectType;
41use crate::plan::plan_utils::JoinSide;
42use crate::plan::scope::ScopeItem;
43use crate::plan::typeconv::CastContext;
44use crate::pure::error::{
45    CsrPurificationError, GluePurificationError, IcebergSinkPurificationError,
46    KafkaSinkPurificationError, KafkaSourcePurificationError, LoadGeneratorSourcePurificationError,
47    MySqlSourcePurificationError, PgSourcePurificationError, SqlServerSourcePurificationError,
48};
49use crate::session::vars::VarError;
50
51#[derive(Debug)]
52pub enum PlanError {
53    /// This feature is not yet supported, but may be supported at some point in the future.
54    Unsupported {
55        feature: String,
56        discussion_no: Option<usize>,
57    },
58    /// This feature is not supported, and will likely never be supported.
59    NeverSupported {
60        feature: String,
61        documentation_link: Option<String>,
62        details: Option<String>,
63    },
64    UnknownColumn {
65        table: Option<PartialItemName>,
66        column: ColumnName,
67        similar: Box<[ColumnName]>,
68    },
69    UngroupedColumn {
70        table: Option<PartialItemName>,
71        column: ColumnName,
72    },
73    ItemWithoutColumns {
74        name: String,
75        item_type: CatalogItemType,
76    },
77    WrongJoinTypeForLateralColumn {
78        table: Option<PartialItemName>,
79        column: ColumnName,
80    },
81    AmbiguousColumn(ColumnName),
82    TooManyColumns {
83        max_num_columns: usize,
84        req_num_columns: usize,
85    },
86    ColumnAlreadyExists {
87        column_name: ColumnName,
88        object_name: String,
89    },
90    AmbiguousTable(PartialItemName),
91    UnknownColumnInUsingClause {
92        column: ColumnName,
93        join_side: JoinSide,
94    },
95    AmbiguousColumnInUsingClause {
96        column: ColumnName,
97        join_side: JoinSide,
98    },
99    MisqualifiedName(String),
100    OverqualifiedDatabaseName(String),
101    OverqualifiedSchemaName(String),
102    UnderqualifiedColumnName(String),
103    SubqueriesDisallowed {
104        context: String,
105    },
106    UnknownParameter(usize),
107    ParameterNotAllowed(String),
108    WrongParameterType(usize, String, String),
109    RecursionLimit(RecursionLimitError),
110    StrconvParse(strconv::ParseError),
111    Catalog(CatalogError),
112    UpsertSinkWithoutKey,
113    UpsertSinkWithInvalidKey {
114        name: String,
115        desired_key: Vec<String>,
116        valid_keys: Vec<Vec<String>>,
117    },
118    IcebergSinkUnsupportedKeyType {
119        column: String,
120        column_type: String,
121    },
122    InvalidWmrRecursionLimit(String),
123    InvalidNumericMaxScale(InvalidNumericMaxScaleError),
124    InvalidCharLength(InvalidCharLengthError),
125    InvalidId(CatalogItemId),
126    InvalidIdent(IdentError),
127    InvalidObject(Box<ResolvedItemName>),
128    InvalidObjectType {
129        expected_type: SystemObjectType,
130        actual_type: SystemObjectType,
131        object_name: String,
132    },
133    InvalidPrivilegeTypes {
134        invalid_privileges: AclMode,
135        object_description: ErrorMessageObjectDescription,
136    },
137    InvalidVarCharMaxLength(InvalidVarCharMaxLengthError),
138    InvalidTimestampPrecision(InvalidTimestampPrecisionError),
139    InvalidSecret(Box<ResolvedItemName>),
140    InvalidTemporarySchema,
141    InvalidCast {
142        name: String,
143        ccx: CastContext,
144        from: String,
145        to: String,
146    },
147    /// Range type with an element type that is not supported (e.g. float, uint).
148    UnsupportedRangeElementType {
149        element_type_name: String,
150    },
151    InvalidTable {
152        name: String,
153    },
154    InvalidVersion {
155        name: String,
156        version: String,
157    },
158    InvalidSinkFrom {
159        name: String,
160        item_type: String,
161    },
162    InvalidDependency {
163        name: String,
164        item_type: String,
165    },
166    MangedReplicaName(String),
167    ParserStatement(ParserStatementError),
168    Parser(ParserError),
169    DropViewOnMaterializedView(String),
170    DependentObjectsStillExist {
171        object_type: String,
172        object_name: String,
173        // (dependent type, name)
174        dependents: Vec<(String, String)>,
175    },
176    AlterViewOnMaterializedView(String),
177    ShowCreateViewOnMaterializedView(String),
178    ExplainViewOnMaterializedView(String),
179    UnacceptableTimelineName(String),
180    FetchingCsrSchemaFailed {
181        schema_lookup: String,
182        cause: Arc<dyn Error + Send + Sync>,
183    },
184    PostgresConnectionErr {
185        cause: Arc<mz_postgres_util::PostgresError>,
186    },
187    MySqlConnectionErr {
188        cause: Arc<MySqlError>,
189    },
190    SqlServerConnectionErr {
191        cause: Arc<SqlServerError>,
192    },
193    SubsourceNameConflict {
194        name: UnresolvedItemName,
195        upstream_references: Vec<UnresolvedItemName>,
196    },
197    SubsourceDuplicateReference {
198        name: UnresolvedItemName,
199        target_names: Vec<UnresolvedItemName>,
200    },
201    NoTablesFoundForSchemas(Vec<String>),
202    InvalidProtobufSchema {
203        cause: protobuf_native::OperationFailedError,
204    },
205    InvalidOptionValue {
206        // Expected to be generated from the `to_ast_string` value on the option
207        // name.
208        option_name: String,
209        err: Box<PlanError>,
210    },
211    UnexpectedDuplicateReference {
212        name: UnresolvedItemName,
213    },
214    /// Declaration of a recursive type did not match the inferred type.
215    RecursiveTypeMismatch(String, Vec<String>, Vec<String>),
216    UnknownFunction {
217        name: String,
218        arg_types: Vec<String>,
219    },
220    IndistinctFunction {
221        name: String,
222        arg_types: Vec<String>,
223    },
224    UnknownOperator {
225        name: String,
226        arg_types: Vec<String>,
227    },
228    IndistinctOperator {
229        name: String,
230        arg_types: Vec<String>,
231    },
232    InvalidPrivatelinkAvailabilityZone {
233        name: String,
234        supported_azs: BTreeSet<String>,
235    },
236    DuplicatePrivatelinkAvailabilityZone {
237        duplicate_azs: BTreeSet<String>,
238    },
239    InvalidSchemaName,
240    ItemAlreadyExists {
241        name: String,
242        item_type: CatalogItemType,
243    },
244    ManagedCluster {
245        cluster_name: String,
246    },
247    InvalidKeysInSubscribeEnvelopeUpsert,
248    InvalidKeysInSubscribeEnvelopeDebezium,
249    DuplicateKeyColumnInSubscribeEnvelope {
250        column_name: String,
251    },
252    InvalidPartitionByEnvelopeDebezium {
253        column_name: String,
254    },
255    InvalidOrderByInSubscribeWithinTimestampOrderBy,
256    FromValueRequiresParen,
257    VarError(VarError),
258    UnsolvablePolymorphicFunctionInput,
259    ShowCommandInView,
260    WebhookValidationDoesNotUseColumns,
261    WebhookValidationNonDeterministic,
262    InternalFunctionCall,
263    CommentTooLong {
264        length: usize,
265        max_size: usize,
266    },
267    InvalidTimestampInterval {
268        min: Duration,
269        max: Duration,
270        requested: Duration,
271    },
272    InvalidGroupSizeHints,
273    PgSourcePurification(PgSourcePurificationError),
274    KafkaSourcePurification(KafkaSourcePurificationError),
275    KafkaSinkPurification(KafkaSinkPurificationError),
276    IcebergSinkPurification(IcebergSinkPurificationError),
277    LoadGeneratorSourcePurification(LoadGeneratorSourcePurificationError),
278    CsrPurification(CsrPurificationError),
279    GluePurification(GluePurificationError),
280    MySqlSourcePurification(MySqlSourcePurificationError),
281    SqlServerSourcePurificationError(SqlServerSourcePurificationError),
282    UseTablesForSources(String),
283    MissingName(CatalogItemType),
284    InvalidRefreshAt,
285    InvalidRefreshEveryAlignedTo,
286    MismatchedObjectType {
287        name: PartialItemName,
288        is_type: ObjectType,
289        expected_type: ObjectType,
290    },
291    /// MZ failed to generate cast for the data type.
292    TableContainsUningestableTypes {
293        name: String,
294        type_: String,
295        column: String,
296    },
297    RetainHistoryLow {
298        limit: Duration,
299    },
300    RetainHistoryRequired,
301    UntilReadyTimeoutRequired,
302    SubsourceResolutionError(ExternalReferenceResolutionError),
303    Replan(String),
304    Internal(String),
305    NetworkPolicyLockoutError,
306    NetworkPolicyInUse,
307    /// Expected a constant expression that evaluates without an error to a non-null value.
308    ConstantExpressionSimplificationFailed(String),
309    InvalidOffset(String),
310    /// The named cursor does not exist.
311    UnknownCursor(String),
312    CopyFromTargetTableDropped {
313        target_name: String,
314    },
315    /// AS OF or UP TO should be an expression that is castable and simplifiable to a non-null mz_timestamp value.
316    InvalidAsOfUpTo,
317    InvalidReplacement {
318        item_type: CatalogItemType,
319        item_name: PartialItemName,
320        replacement_type: CatalogItemType,
321        replacement_name: PartialItemName,
322    },
323    // TODO(benesch): eventually all errors should be structured.
324    Unstructured(String),
325}
326
327impl PlanError {
328    pub(crate) fn ungrouped_column(item: &ScopeItem) -> PlanError {
329        PlanError::UngroupedColumn {
330            table: item.table_name.clone(),
331            column: item.column_name.clone(),
332        }
333    }
334
335    pub fn detail(&self) -> Option<String> {
336        match self {
337            Self::NeverSupported { details, .. } => details.clone(),
338            Self::FetchingCsrSchemaFailed { cause, .. } => Some(cause.to_string_with_causes()),
339            Self::PostgresConnectionErr { cause } => Some(cause.to_string_with_causes()),
340            Self::InvalidProtobufSchema { cause } => Some(cause.to_string_with_causes()),
341            Self::InvalidOptionValue { err, .. } => err.detail(),
342            Self::UpsertSinkWithInvalidKey {
343                name,
344                desired_key,
345                valid_keys,
346            } => {
347                let valid_keys = if valid_keys.is_empty() {
348                    "There are no known valid unique keys for the underlying relation.".into()
349                } else {
350                    format!(
351                        "The following keys are known to be unique for the underlying relation:\n{}",
352                        valid_keys
353                            .iter()
354                            .map(|k|
355                                format!("  ({})", k.iter().map(|c| c.as_str().quoted()).join(", "))
356                            )
357                            .join("\n"),
358                    )
359                };
360                Some(format!(
361                    "Materialize could not prove that the specified upsert envelope key ({}) \
362                    was a unique key of the underlying relation {}. {valid_keys}",
363                    separated(", ", desired_key.iter().map(|c| c.as_str().quoted())),
364                    name.quoted()
365                ))
366            }
367            Self::VarError(e) => e.detail(),
368            Self::InternalFunctionCall => Some("This function is for the internal use of the database system and cannot be called directly.".into()),
369            Self::PgSourcePurification(e) => e.detail(),
370            Self::MySqlSourcePurification(e) => e.detail(),
371            Self::SqlServerSourcePurificationError(e) => e.detail(),
372            Self::KafkaSourcePurification(e) => e.detail(),
373            Self::LoadGeneratorSourcePurification(e) => e.detail(),
374            Self::CsrPurification(e) => e.detail(),
375            Self::GluePurification(e) => e.detail(),
376            Self::KafkaSinkPurification(e) => e.detail(),
377            Self::IcebergSinkPurification(e) => e.detail(),
378            Self::SubsourceNameConflict {
379                name: _,
380                upstream_references,
381            } => Some(format!(
382                "referenced tables with duplicate name: {}",
383                itertools::join(upstream_references, ", ")
384            )),
385            Self::SubsourceDuplicateReference {
386                name: _,
387                target_names,
388            } => Some(format!(
389                "subsources referencing table: {}",
390                itertools::join(target_names, ", ")
391            )),
392            Self::InvalidPartitionByEnvelopeDebezium { .. } => Some(
393                "When using ENVELOPE DEBEZIUM, only columns in the key can be referenced in the PARTITION BY expression.".to_string()
394            ),
395            Self::NoTablesFoundForSchemas(schemas) => Some(format!(
396                "missing schemas: {}",
397                separated(", ", schemas.iter().map(|c| c.quoted()))
398            )),
399            _ => None,
400        }
401    }
402
403    pub fn hint(&self) -> Option<String> {
404        match self {
405            Self::DropViewOnMaterializedView(_) => {
406                Some("Use DROP MATERIALIZED VIEW to remove a materialized view.".into())
407            }
408            Self::DependentObjectsStillExist {..} => Some("Use DROP ... CASCADE to drop the dependent objects too.".into()),
409            Self::AlterViewOnMaterializedView(_) => {
410                Some("Use ALTER MATERIALIZED VIEW to rename a materialized view.".into())
411            }
412            Self::ShowCreateViewOnMaterializedView(_) => {
413                Some("Use SHOW CREATE MATERIALIZED VIEW to show a materialized view.".into())
414            }
415            Self::ExplainViewOnMaterializedView(_) => {
416                Some("Use EXPLAIN [...] MATERIALIZED VIEW to explain a materialized view.".into())
417            }
418            Self::UnacceptableTimelineName(_) => {
419                Some("The prefix \"mz_\" is reserved for system timelines.".into())
420            }
421            Self::PostgresConnectionErr { cause } => {
422                if let Some(cause) = cause.source() {
423                    if let Some(cause) = cause.downcast_ref::<io::Error>() {
424                        if cause.kind() == io::ErrorKind::TimedOut {
425                            return Some(
426                                "Do you have a firewall or security group that is \
427                                preventing Materialize from connecting to your PostgreSQL server?"
428                                    .into(),
429                            );
430                        }
431                    }
432                }
433                None
434            }
435            Self::InvalidOptionValue { err, .. } => err.hint(),
436            Self::UnknownFunction { ..} => Some("No function matches the given name and argument types.  You might need to add explicit type casts.".into()),
437            Self::IndistinctFunction {..} => {
438                Some("Could not choose a best candidate function.  You might need to add explicit type casts.".into())
439            }
440            Self::UnknownOperator {..} => {
441                Some("No operator matches the given name and argument types.  You might need to add explicit type casts.".into())
442            }
443            Self::IndistinctOperator {..} => {
444                Some("Could not choose a best candidate operator.  You might need to add explicit type casts.".into())
445            },
446            Self::InvalidPrivatelinkAvailabilityZone { supported_azs, ..} => {
447                let supported_azs_str = supported_azs.iter().join("\n  ");
448                Some(format!("Did you supply an availability zone name instead of an ID? Known availability zone IDs:\n  {}", supported_azs_str))
449            }
450            Self::DuplicatePrivatelinkAvailabilityZone { duplicate_azs, ..} => {
451                let duplicate_azs  = duplicate_azs.iter().join("\n  ");
452                Some(format!("Duplicated availability zones:\n  {}", duplicate_azs))
453            }
454            Self::InvalidKeysInSubscribeEnvelopeUpsert => {
455                Some("All keys must be columns on the underlying relation.".into())
456            }
457            Self::InvalidKeysInSubscribeEnvelopeDebezium => {
458                Some("All keys must be columns on the underlying relation.".into())
459            }
460            Self::DuplicateKeyColumnInSubscribeEnvelope { .. } => {
461                Some("Each KEY column must be listed at most once.".into())
462            }
463            Self::InvalidOrderByInSubscribeWithinTimestampOrderBy => {
464                Some("All order bys must be output columns.".into())
465            }
466            Self::UpsertSinkWithInvalidKey { .. } | Self::UpsertSinkWithoutKey => {
467                Some("See: https://materialize.com/s/sink-key-selection".into())
468            }
469            Self::IcebergSinkUnsupportedKeyType { .. } => {
470                Some("Iceberg equality delete keys must be primitive, non-floating-point columns.".into())
471            }
472            Self::Catalog(e) => e.hint(),
473            Self::VarError(e) => e.hint(),
474            Self::PgSourcePurification(e) => e.hint(),
475            Self::MySqlSourcePurification(e) => e.hint(),
476            Self::SqlServerSourcePurificationError(e) => e.hint(),
477            Self::KafkaSourcePurification(e) => e.hint(),
478            Self::LoadGeneratorSourcePurification(e) => e.hint(),
479            Self::CsrPurification(e) => e.hint(),
480            Self::GluePurification(e) => e.hint(),
481            Self::KafkaSinkPurification(e) => e.hint(),
482            Self::UnknownColumn { table, similar, .. } => {
483                let suffix = "Make sure to surround case sensitive names in double quotes.";
484                match &similar[..] {
485                    [] => None,
486                    [column] => Some(format!("The similarly named column {} does exist. {suffix}", ColumnDisplay { table, column })),
487                    names => {
488                        let similar = names.into_iter().map(|column| ColumnDisplay { table, column }).join(", ");
489                        Some(format!("There are similarly named columns that do exist: {similar}. {suffix}"))
490                    }
491                }
492            }
493            Self::RecursiveTypeMismatch(..) => {
494                Some("You will need to rewrite or cast the query's expressions.".into())
495            },
496            Self::InvalidRefreshAt
497            | Self::InvalidRefreshEveryAlignedTo => {
498                Some("Calling `mz_now()` is allowed.".into())
499            },
500            Self::TableContainsUningestableTypes { column,.. } => {
501                Some(format!("Remove the table or use TEXT COLUMNS ({column}, ..) to ingest this column as text"))
502            }
503            Self::RetainHistoryLow { .. } | Self::RetainHistoryRequired => {
504                Some("Use ALTER ... RESET (RETAIN HISTORY) to set the retain history to its default and lowest value.".into())
505            }
506            Self::NetworkPolicyInUse => {
507                Some("Use ALTER SYSTEM SET 'network_policy' to change the default network policy.".into())
508            }
509            Self::WrongParameterType(_, _, _) => {
510                Some("EXECUTE automatically inserts only such casts that are allowed in an assignment cast context.  Try adding an explicit cast.".into())
511            }
512            Self::InvalidSchemaName => {
513                Some("Use SET schema = name to select a schema.  Use SHOW SCHEMAS to list available schemas.  Use SHOW search_path to show the schema names that we looked for, but none of them existed.".into())
514            }
515            _ => None,
516        }
517    }
518}
519
520impl fmt::Display for PlanError {
521    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
522        match self {
523            Self::Unsupported { feature, discussion_no } => {
524                write!(f, "{} not yet supported", feature)?;
525                if let Some(discussion_no) = discussion_no {
526                    write!(f, ", see https://github.com/MaterializeInc/materialize/discussions/{} for more details", discussion_no)?;
527                }
528                Ok(())
529            }
530            Self::NeverSupported { feature, documentation_link: documentation_path,.. } => {
531                write!(f, "{feature} is not supported",)?;
532                if let Some(documentation_path) = documentation_path {
533                    write!(f, ", for more information consult the documentation at https://materialize.com/docs/{documentation_path}")?;
534                }
535                Ok(())
536            }
537            Self::UnknownColumn { table, column, similar: _ } => write!(
538                f,
539                "column {} does not exist",
540                ColumnDisplay { table, column }
541            ),
542            Self::UngroupedColumn { table, column } => write!(
543                f,
544                "column {} must appear in the GROUP BY clause or be used in an aggregate function",
545                ColumnDisplay { table, column },
546            ),
547            Self::ItemWithoutColumns { name, item_type } => {
548                let name = name.quoted();
549                write!(f, "{item_type} {name} does not have columns")
550            }
551            Self::WrongJoinTypeForLateralColumn { table, column } => write!(
552                f,
553                "column {} cannot be referenced from this part of the query: \
554                the combining JOIN type must be INNER or LEFT for a LATERAL reference",
555                ColumnDisplay { table, column },
556            ),
557            Self::AmbiguousColumn(column) => write!(
558                f,
559                "column reference {} is ambiguous",
560                column.quoted()
561            ),
562            Self::TooManyColumns { max_num_columns, req_num_columns } => write!(
563                f,
564                "attempt to create relation with too many columns, {} max: {}",
565                req_num_columns, max_num_columns
566            ),
567            Self::ColumnAlreadyExists { column_name, object_name } => write!(
568                f,
569                "column {} of relation {} already exists",
570                column_name.quoted(), object_name.quoted(),
571            ),
572            Self::AmbiguousTable(table) => write!(
573                f,
574                "table reference {} is ambiguous",
575                table.item.as_str().quoted()
576            ),
577            Self::UnknownColumnInUsingClause { column, join_side } => write!(
578                f,
579                "column {} specified in USING clause does not exist in {} table",
580                column.quoted(),
581                join_side,
582            ),
583            Self::AmbiguousColumnInUsingClause { column, join_side } => write!(
584                f,
585                "common column name {} appears more than once in {} table",
586                column.quoted(),
587                join_side,
588            ),
589            Self::MisqualifiedName(name) => write!(
590                f,
591                "qualified name did not have between 1 and 3 components: {}",
592                name
593            ),
594            Self::OverqualifiedDatabaseName(name) => write!(
595                f,
596                "database name '{}' does not have exactly one component",
597                name
598            ),
599            Self::OverqualifiedSchemaName(name) => write!(
600                f,
601                "schema name '{}' cannot have more than two components",
602                name
603            ),
604            Self::UnderqualifiedColumnName(name) => write!(
605                f,
606                "column name '{}' must have at least a table qualification",
607                name
608            ),
609            Self::UnacceptableTimelineName(name) => {
610                write!(f, "unacceptable timeline name {}", name.quoted(),)
611            }
612            Self::SubqueriesDisallowed { context } => {
613                write!(f, "{} does not allow subqueries", context)
614            }
615            Self::UnknownParameter(n) => write!(f, "there is no parameter ${}", n),
616            Self::ParameterNotAllowed(object_type) => write!(f, "{} cannot have parameters", object_type),
617            Self::WrongParameterType(i, expected_ty, actual_ty) => write!(f, "unable to cast given parameter ${}: expected {}, got {}", i, expected_ty, actual_ty),
618            Self::RecursionLimit(e) => write!(f, "{}", e),
619            Self::StrconvParse(e) => write!(f, "{}", e),
620            Self::Catalog(e) => write!(f, "{}", e),
621            Self::UpsertSinkWithoutKey => write!(f, "upsert sinks must specify a key"),
622            Self::UpsertSinkWithInvalidKey { .. } => {
623                write!(f, "upsert key could not be validated as unique")
624            }
625            Self::IcebergSinkUnsupportedKeyType { column, column_type } => {
626                write!(f, "column {column} has type {column_type} which cannot be used as an Iceberg equality delete key")
627            }
628            Self::InvalidWmrRecursionLimit(msg) => write!(f, "Invalid WITH MUTUALLY RECURSIVE recursion limit. {}", msg),
629            Self::InvalidNumericMaxScale(e) => e.fmt(f),
630            Self::InvalidCharLength(e) => e.fmt(f),
631            Self::InvalidVarCharMaxLength(e) => e.fmt(f),
632            Self::InvalidTimestampPrecision(e) => e.fmt(f),
633            Self::Parser(e) => e.fmt(f),
634            Self::ParserStatement(e) => e.fmt(f),
635            Self::Unstructured(e) => write!(f, "{}", e),
636            Self::InvalidId(id) => write!(f, "invalid id {}", id),
637            Self::InvalidIdent(err) => write!(f, "invalid identifier, {err}"),
638            Self::InvalidObject(i) => write!(f, "{} is not a database object", i.full_name_str()),
639            Self::InvalidObjectType{expected_type, actual_type, object_name} => write!(f, "{actual_type} {object_name} is not a {expected_type}"),
640            Self::InvalidPrivilegeTypes{ invalid_privileges, object_description, } => {
641                write!(f, "invalid privilege types {} for {}", invalid_privileges.to_error_string(), object_description)
642            },
643            Self::InvalidSecret(i) => write!(f, "{} is not a secret", i.full_name_str()),
644            Self::InvalidTemporarySchema => {
645                write!(f, "cannot create temporary item in non-temporary schema")
646            }
647            Self::InvalidCast { name, ccx, from, to } =>{
648                write!(
649                    f,
650                    "{name} does not support {ccx}casting from {from} to {to}",
651                    ccx = if matches!(ccx, CastContext::Implicit) {
652                        "implicitly "
653                    } else {
654                        ""
655                    },
656                )
657            }
658            Self::UnsupportedRangeElementType { element_type_name } => {
659                write!(f, "range type over {} is not supported", element_type_name)
660            }
661            Self::InvalidTable { name } => {
662                write!(f, "invalid table definition for {}", name.quoted())
663            },
664            Self::InvalidVersion { name, version } => {
665                write!(f, "invalid version {} for {}", version.quoted(), name.quoted())
666            },
667            Self::InvalidSinkFrom { name, item_type } => {
668                write!(f, "{item_type} {name} cannot be exported as a sink")
669            },
670            Self::InvalidDependency { name, item_type } => {
671                write!(f, "{item_type} {name} cannot be depended upon")
672            },
673            Self::DropViewOnMaterializedView(name)
674            | Self::AlterViewOnMaterializedView(name)
675            | Self::ShowCreateViewOnMaterializedView(name)
676            | Self::ExplainViewOnMaterializedView(name) => write!(f, "{name} is not a view"),
677            Self::FetchingCsrSchemaFailed { schema_lookup, .. } => {
678                write!(f, "failed to fetch schema {schema_lookup} from schema registry")
679            }
680            Self::PostgresConnectionErr { .. } => {
681                write!(f, "failed to connect to PostgreSQL database")
682            }
683            Self::MySqlConnectionErr { cause } => {
684                write!(f, "failed to connect to MySQL database: {}", cause)
685            }
686            Self::SqlServerConnectionErr { cause } => {
687                write!(f, "failed to connect to SQL Server database: {}", cause)
688            }
689            Self::SubsourceNameConflict {
690                name , upstream_references: _,
691            } => {
692                write!(f, "multiple subsources would be named {}", name)
693            },
694            Self::SubsourceDuplicateReference {
695                name,
696                target_names: _,
697            } => {
698                write!(f, "multiple subsources refer to table {}", name)
699            },
700            Self::NoTablesFoundForSchemas(schemas) => {
701                write!(f, "no tables found in referenced schemas: {}",
702                    separated(", ", schemas.iter().map(|c| c.quoted()))
703                )
704            },
705            Self::InvalidProtobufSchema { .. } => {
706                write!(f, "invalid protobuf schema")
707            }
708            Self::DependentObjectsStillExist {object_type, object_name, dependents} => {
709                let reason = match &dependents[..] {
710                    [] => " because other objects depend on it".to_string(),
711                    dependents => {
712                        let dependents = dependents.iter().map(|(dependent_type, dependent_name)| format!("{} {}", dependent_type, dependent_name.quoted())).join(", ");
713                        format!(": still depended upon by {dependents}")
714                    },
715                };
716                let object_name = object_name.quoted();
717                write!(f, "cannot drop {object_type} {object_name}{reason}")
718            }
719            Self::InvalidOptionValue { option_name, err } => write!(f, "invalid {} option value: {}", option_name, err),
720            Self::UnexpectedDuplicateReference { name } => write!(f, "unexpected multiple references to {}", name.to_ast_string_simple()),
721            Self::RecursiveTypeMismatch(name, declared, inferred) => {
722                let declared = separated(", ", declared);
723                let inferred = separated(", ", inferred);
724                let name = name.quoted();
725                write!(f, "WITH MUTUALLY RECURSIVE query {name} declared types ({declared}), but query returns types ({inferred})")
726            },
727            Self::UnknownFunction {name, arg_types, ..} => {
728                write!(f, "function {}({}) does not exist", name, arg_types.join(", "))
729            },
730            Self::IndistinctFunction {name, arg_types, ..} => {
731                write!(f, "function {}({}) is not unique", name, arg_types.join(", "))
732            },
733            Self::UnknownOperator {name, arg_types, ..} => {
734                write!(f, "operator does not exist: {}", match arg_types.as_slice(){
735                    [typ] => format!("{} {}", name, typ),
736                    [ltyp, rtyp] => {
737                        format!("{} {} {}", ltyp, name, rtyp)
738                    }
739                    _ => unreachable!("non-unary non-binary operator"),
740                })
741            },
742            Self::IndistinctOperator {name, arg_types, ..} => {
743                write!(f, "operator is not unique: {}", match arg_types.as_slice(){
744                    [typ] => format!("{} {}", name, typ),
745                    [ltyp, rtyp] => {
746                        format!("{} {} {}", ltyp, name, rtyp)
747                    }
748                    _ => unreachable!("non-unary non-binary operator"),
749                })
750            },
751            Self::InvalidPrivatelinkAvailabilityZone { name, ..} => write!(f, "invalid AWS PrivateLink availability zone {}", name.quoted()),
752            Self::DuplicatePrivatelinkAvailabilityZone {..} =>   write!(f, "connection cannot contain duplicate availability zones"),
753            Self::InvalidSchemaName => write!(f, "no valid schema selected"),
754            Self::ItemAlreadyExists { name, item_type } => write!(f, "{item_type} {} already exists", name.quoted()),
755            Self::ManagedCluster {cluster_name} => write!(f, "cannot modify managed cluster {cluster_name}"),
756            Self::InvalidKeysInSubscribeEnvelopeUpsert => {
757                write!(f, "invalid keys in SUBSCRIBE ENVELOPE UPSERT (KEY (..))")
758            }
759            Self::InvalidKeysInSubscribeEnvelopeDebezium => {
760                write!(f, "invalid keys in SUBSCRIBE ENVELOPE DEBEZIUM (KEY (..))")
761            }
762            Self::DuplicateKeyColumnInSubscribeEnvelope { column_name } => {
763                write!(
764                    f,
765                    "column {} appears more than once in SUBSCRIBE ENVELOPE KEY clause",
766                    column_name.quoted(),
767                )
768            }
769            Self::InvalidPartitionByEnvelopeDebezium { column_name } => {
770                write!(
771                    f,
772                    "PARTITION BY expression cannot refer to non-key column {}",
773                    column_name.quoted(),
774                )
775            }
776            Self::InvalidOrderByInSubscribeWithinTimestampOrderBy => {
777                write!(f, "invalid ORDER BY in SUBSCRIBE WITHIN TIMESTAMP ORDER BY")
778            }
779            Self::FromValueRequiresParen => f.write_str(
780                "VALUES expression in FROM clause must be surrounded by parentheses"
781            ),
782            Self::VarError(e) => e.fmt(f),
783            Self::UnsolvablePolymorphicFunctionInput => f.write_str(
784                "could not determine polymorphic type because input has type unknown"
785            ),
786            Self::ShowCommandInView => f.write_str("SHOW commands are not allowed in views"),
787            Self::WebhookValidationDoesNotUseColumns => f.write_str(
788                "expression provided in CHECK does not reference any columns"
789            ),
790            Self::WebhookValidationNonDeterministic => f.write_str(
791                "expression provided in CHECK is not deterministic"
792            ),
793            Self::InternalFunctionCall => f.write_str("cannot call function with arguments of type internal"),
794            Self::CommentTooLong { length, max_size } => {
795                write!(f, "provided comment was {length} bytes long, max size is {max_size} bytes")
796            }
797            Self::InvalidTimestampInterval { min, max, requested } => {
798                write!(f, "invalid timestamp interval of {}ms, must be in the range [{}ms, {}ms]", requested.as_millis(), min.as_millis(), max.as_millis())
799            }
800            Self::InvalidGroupSizeHints => f.write_str("EXPECTED GROUP SIZE cannot be provided \
801                simultaneously with any of AGGREGATE INPUT GROUP SIZE, DISTINCT ON INPUT GROUP SIZE, \
802                or LIMIT INPUT GROUP SIZE"),
803            Self::PgSourcePurification(e) => write!(f, "POSTGRES source validation: {}", e),
804            Self::KafkaSourcePurification(e) => write!(f, "KAFKA source validation: {}", e),
805            Self::LoadGeneratorSourcePurification(e) => write!(f, "LOAD GENERATOR source validation: {}", e),
806            Self::KafkaSinkPurification(e) => write!(f, "KAFKA sink validation: {}", e),
807            Self::IcebergSinkPurification(e) => write!(f, "ICEBERG sink validation: {}", e),
808            Self::CsrPurification(e) => write!(f, "CONFLUENT SCHEMA REGISTRY validation: {}", e),
809            Self::GluePurification(e) => write!(f, "AWS GLUE SCHEMA REGISTRY validation: {}", e),
810            Self::MySqlSourcePurification(e) => write!(f, "MYSQL source validation: {}", e),
811            Self::SqlServerSourcePurificationError(e) => write!(f, "SQL SERVER source validation: {}", e),
812            Self::UseTablesForSources(command) => write!(f, "{command} not supported; use CREATE TABLE .. FROM SOURCE instead"),
813            Self::MangedReplicaName(name) => {
814                write!(f, "{name} is reserved for replicas of managed clusters")
815            }
816            Self::MissingName(item_type) => {
817                write!(f, "unspecified name for {item_type}")
818            }
819            Self::InvalidRefreshAt => {
820                write!(f, "REFRESH AT argument must be an expression that can be simplified \
821                           and/or cast to a constant whose type is mz_timestamp")
822            }
823            Self::InvalidRefreshEveryAlignedTo => {
824                write!(f, "REFRESH EVERY ... ALIGNED TO argument must be an expression that can be simplified \
825                           and/or cast to a constant whose type is mz_timestamp")
826            }
827            Self::MismatchedObjectType {
828                name,
829                is_type,
830                expected_type,
831            } => {
832                write!(
833                    f,
834                    "{name} is {} {} not {} {}",
835                    if *is_type == ObjectType::Index {
836                        "an"
837                    } else {
838                        "a"
839                    },
840                    is_type.to_string().to_lowercase(),
841                    if *expected_type == ObjectType::Index {
842                        "an"
843                    } else {
844                        "a"
845                    },
846                    expected_type.to_string().to_lowercase()
847                )
848            }
849            Self::TableContainsUningestableTypes { name, type_, column } => {
850                write!(f, "table {name} contains column {column} of type {type_} which Materialize cannot currently ingest")
851            },
852            Self::RetainHistoryLow { limit } => {
853                write!(f, "RETAIN HISTORY cannot be set lower than {}ms", limit.as_millis())
854            },
855            Self::RetainHistoryRequired => {
856                write!(f, "RETAIN HISTORY cannot be disabled or set to 0")
857            },
858            Self::SubsourceResolutionError(e) => write!(f, "{}", e),
859            Self::Replan(msg) => write!(f, "internal error while replanning, please contact support: {msg}"),
860            Self::Internal(msg) => write!(f, "internal error: {msg}"),
861            Self::NetworkPolicyLockoutError => write!(f, "policy would block current session IP"),
862            Self::NetworkPolicyInUse => write!(f, "network policy is currently in use"),
863            Self::UntilReadyTimeoutRequired => {
864                write!(f, "TIMEOUT=<duration> option is required for ALTER CLUSTER ... WITH (WAIT UNTIL READY ( ... ))")
865            },
866            Self::ConstantExpressionSimplificationFailed(e) => write!(f, "{}", e),
867            Self::InvalidOffset(e) => write!(f, "Invalid OFFSET clause: {}", e),
868            Self::UnknownCursor(name) => {
869                write!(f, "cursor {} does not exist", name.quoted())
870            }
871            Self::CopyFromTargetTableDropped { target_name: name } => {
872                write!(f, "COPY FROM's target table {} was dropped", name.quoted())
873            }
874            Self::InvalidAsOfUpTo => write!(
875                f,
876                "AS OF or UP TO should be castable to a (non-null) mz_timestamp value",
877            ),
878            Self::InvalidReplacement {
879                item_type, item_name, replacement_type, replacement_name,
880            } => {
881                write!(
882                    f,
883                    "cannot replace {item_type} {item_name} \
884                     with {replacement_type} {replacement_name}",
885                )
886            }
887        }
888    }
889}
890
891impl Error for PlanError {}
892
893impl From<CatalogError> for PlanError {
894    fn from(e: CatalogError) -> PlanError {
895        PlanError::Catalog(e)
896    }
897}
898
899impl From<strconv::ParseError> for PlanError {
900    fn from(e: strconv::ParseError) -> PlanError {
901        PlanError::StrconvParse(e)
902    }
903}
904
905impl From<RecursionLimitError> for PlanError {
906    fn from(e: RecursionLimitError) -> PlanError {
907        PlanError::RecursionLimit(e)
908    }
909}
910
911impl From<InvalidNumericMaxScaleError> for PlanError {
912    fn from(e: InvalidNumericMaxScaleError) -> PlanError {
913        PlanError::InvalidNumericMaxScale(e)
914    }
915}
916
917impl From<InvalidCharLengthError> for PlanError {
918    fn from(e: InvalidCharLengthError) -> PlanError {
919        PlanError::InvalidCharLength(e)
920    }
921}
922
923impl From<InvalidVarCharMaxLengthError> for PlanError {
924    fn from(e: InvalidVarCharMaxLengthError) -> PlanError {
925        PlanError::InvalidVarCharMaxLength(e)
926    }
927}
928
929impl From<InvalidTimestampPrecisionError> for PlanError {
930    fn from(e: InvalidTimestampPrecisionError) -> PlanError {
931        PlanError::InvalidTimestampPrecision(e)
932    }
933}
934
935impl From<anyhow::Error> for PlanError {
936    fn from(e: anyhow::Error) -> PlanError {
937        // WIP: Do we maybe want to keep the alternate selector for these?
938        sql_err!("{}", e.display_with_causes())
939    }
940}
941
942impl From<TryFromIntError> for PlanError {
943    fn from(e: TryFromIntError) -> PlanError {
944        sql_err!("{}", e.display_with_causes())
945    }
946}
947
948impl From<ParseIntError> for PlanError {
949    fn from(e: ParseIntError) -> PlanError {
950        sql_err!("{}", e.display_with_causes())
951    }
952}
953
954impl From<EvalError> for PlanError {
955    fn from(e: EvalError) -> PlanError {
956        sql_err!("{}", e.display_with_causes())
957    }
958}
959
960impl From<ParserError> for PlanError {
961    fn from(e: ParserError) -> PlanError {
962        PlanError::Parser(e)
963    }
964}
965
966impl From<ParserStatementError> for PlanError {
967    fn from(e: ParserStatementError) -> PlanError {
968        PlanError::ParserStatement(e)
969    }
970}
971
972impl From<PostgresError> for PlanError {
973    fn from(e: PostgresError) -> PlanError {
974        PlanError::PostgresConnectionErr { cause: Arc::new(e) }
975    }
976}
977
978impl From<MySqlError> for PlanError {
979    fn from(e: MySqlError) -> PlanError {
980        PlanError::MySqlConnectionErr { cause: Arc::new(e) }
981    }
982}
983
984impl From<SqlServerError> for PlanError {
985    fn from(e: SqlServerError) -> PlanError {
986        PlanError::SqlServerConnectionErr { cause: Arc::new(e) }
987    }
988}
989
990impl From<VarError> for PlanError {
991    fn from(e: VarError) -> Self {
992        PlanError::VarError(e)
993    }
994}
995
996impl From<PgSourcePurificationError> for PlanError {
997    fn from(e: PgSourcePurificationError) -> Self {
998        PlanError::PgSourcePurification(e)
999    }
1000}
1001
1002impl From<KafkaSourcePurificationError> for PlanError {
1003    fn from(e: KafkaSourcePurificationError) -> Self {
1004        PlanError::KafkaSourcePurification(e)
1005    }
1006}
1007
1008impl From<KafkaSinkPurificationError> for PlanError {
1009    fn from(e: KafkaSinkPurificationError) -> Self {
1010        PlanError::KafkaSinkPurification(e)
1011    }
1012}
1013
1014impl From<IcebergSinkPurificationError> for PlanError {
1015    fn from(e: IcebergSinkPurificationError) -> Self {
1016        PlanError::IcebergSinkPurification(e)
1017    }
1018}
1019
1020impl From<GluePurificationError> for PlanError {
1021    fn from(e: GluePurificationError) -> Self {
1022        PlanError::GluePurification(e)
1023    }
1024}
1025
1026impl From<CsrPurificationError> for PlanError {
1027    fn from(e: CsrPurificationError) -> Self {
1028        PlanError::CsrPurification(e)
1029    }
1030}
1031
1032impl From<LoadGeneratorSourcePurificationError> for PlanError {
1033    fn from(e: LoadGeneratorSourcePurificationError) -> Self {
1034        PlanError::LoadGeneratorSourcePurification(e)
1035    }
1036}
1037
1038impl From<MySqlSourcePurificationError> for PlanError {
1039    fn from(e: MySqlSourcePurificationError) -> Self {
1040        PlanError::MySqlSourcePurification(e)
1041    }
1042}
1043
1044impl From<SqlServerSourcePurificationError> for PlanError {
1045    fn from(e: SqlServerSourcePurificationError) -> Self {
1046        PlanError::SqlServerSourcePurificationError(e)
1047    }
1048}
1049
1050impl From<IdentError> for PlanError {
1051    fn from(e: IdentError) -> Self {
1052        PlanError::InvalidIdent(e)
1053    }
1054}
1055
1056impl From<ExternalReferenceResolutionError> for PlanError {
1057    fn from(e: ExternalReferenceResolutionError) -> Self {
1058        PlanError::SubsourceResolutionError(e)
1059    }
1060}
1061
1062struct ColumnDisplay<'a> {
1063    table: &'a Option<PartialItemName>,
1064    column: &'a ColumnName,
1065}
1066
1067impl<'a> fmt::Display for ColumnDisplay<'a> {
1068    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1069        if let Some(table) = &self.table {
1070            format!("{}.{}", table.item, self.column).quoted().fmt(f)
1071        } else {
1072            self.column.quoted().fmt(f)
1073        }
1074    }
1075}