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