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