1use std::collections::BTreeMap;
11use std::error::Error;
12use std::fmt;
13use std::num::TryFromIntError;
14
15use dec::TryFromDecimalError;
16use itertools::Itertools;
17use mz_catalog::builtin::MZ_CATALOG_SERVER_CLUSTER;
18use mz_compute_client::controller::error as compute_error;
19use mz_expr::EvalError;
20use mz_ore::error::ErrorExt;
21use mz_ore::stack::RecursionLimitError;
22use mz_ore::str::StrExt;
23use mz_pgwire_common::{ErrorResponse, Severity};
24use mz_repr::adt::timestamp::TimestampError;
25use mz_repr::explain::ExplainError;
26use mz_repr::{NotNullViolation, Timestamp};
27use mz_sql::plan::PlanError;
28use mz_sql::rbac;
29use mz_sql::session::vars::VarError;
30use mz_storage_types::connections::ConnectionValidationError;
31use mz_storage_types::controller::StorageError;
32use smallvec::SmallVec;
33use timely::progress::Antichain;
34use tokio::sync::oneshot;
35use tokio_postgres::error::SqlState;
36
37use crate::coord::NetworkPolicyError;
38use crate::optimize::OptimizerError;
39
40#[derive(Debug)]
42pub enum AdapterError {
43 AbsurdSubscribeBounds {
45 as_of: mz_repr::Timestamp,
46 up_to: mz_repr::Timestamp,
47 },
48 AmbiguousSystemColumnReference,
52 Catalog(mz_catalog::memory::error::Error),
54 ChangedPlan(String),
56 DuplicateCursor(String),
58 Eval(EvalError),
60 Explain(ExplainError),
62 IdExhaustionError,
64 Internal(String),
66 IntrospectionDisabled {
68 log_names: Vec<String>,
69 },
70 InvalidLogDependency {
73 object_type: String,
74 log_names: Vec<String>,
75 },
76 InvalidClusterReplicaAz {
78 az: String,
79 expected: Vec<String>,
80 },
81 InvalidSetIsolationLevel,
83 InvalidSetCluster,
85 InvalidStorageClusterSize {
87 size: String,
88 expected: Vec<String>,
89 },
90 SourceOrSinkSizeRequired {
92 expected: Vec<String>,
93 },
94 InvalidTableMutationSelection,
96 ConstraintViolation(NotNullViolation),
98 ConcurrentClusterDrop,
100 NoClusterReplicasAvailable {
102 name: String,
103 is_managed: bool,
104 },
105 OperationProhibitsTransaction(String),
107 OperationRequiresTransaction(String),
109 PlanError(PlanError),
111 PreparedStatementExists(String),
113 ParseError(mz_sql_parser::parser::ParserStatementError),
115 ReadOnlyTransaction,
117 ReadWriteUnavailable,
119 RecursionLimit(RecursionLimitError),
121 RelationOutsideTimeDomain {
124 relations: Vec<String>,
125 names: Vec<String>,
126 },
127 ResourceExhaustion {
129 resource_type: String,
130 limit_name: String,
131 desired: String,
132 limit: String,
133 current: String,
134 },
135 ResultSize(String),
137 SafeModeViolation(String),
139 WrongSetOfLocks,
141 StatementTimeout,
145 Canceled,
147 IdleInTransactionSessionTimeout,
149 SubscribeOnlyTransaction,
151 Optimizer(OptimizerError),
153 UnallowedOnCluster {
155 depends_on: SmallVec<[String; 2]>,
156 cluster: String,
157 },
158 Unauthorized(rbac::UnauthorizedError),
160 UnknownCursor(String),
162 UnknownLoginRole(String),
164 UnknownPreparedStatement(String),
165 UnknownClusterReplica {
167 cluster_name: String,
168 replica_name: String,
169 },
170 UnrecognizedConfigurationParam(String),
172 Unstructured(anyhow::Error),
176 Unsupported(&'static str),
178 UnavailableFeature {
182 feature: String,
183 docs: Option<String>,
184 },
185 UntargetedLogRead {
187 log_names: Vec<String>,
188 },
189 WriteOnlyTransaction,
191 SingleStatementTransaction,
193 DDLOnlyTransaction,
195 DDLTransactionRace,
197 TransactionDryRun {
200 new_ops: Vec<crate::catalog::Op>,
202 new_state: crate::catalog::CatalogState,
204 },
205 Storage(mz_storage_types::controller::StorageError<mz_repr::Timestamp>),
207 Compute(anyhow::Error),
209 Orchestrator(anyhow::Error),
211 DependentObject(BTreeMap<String, Vec<String>>),
215 InvalidAlter(&'static str, PlanError),
218 ConnectionValidation(ConnectionValidationError),
220 MaterializedViewWouldNeverRefresh(Timestamp, Timestamp),
224 InputNotReadableAtRefreshAtTime(Timestamp, Antichain<Timestamp>),
227 RtrTimeout(String),
229 RtrDropFailure(String),
231 UnreadableSinkCollection,
233 UserSessionsDisallowed,
235 NetworkPolicyDenied(NetworkPolicyError),
237 ReadOnly,
240 AlterClusterTimeout,
241 AuthenticationError,
248}
249
250impl AdapterError {
251 pub fn into_response(self, severity: Severity) -> ErrorResponse {
252 ErrorResponse {
253 severity,
254 code: self.code(),
255 message: self.to_string(),
256 detail: self.detail(),
257 hint: self.hint(),
258 position: self.position(),
259 }
260 }
261
262 pub fn position(&self) -> Option<usize> {
263 match self {
264 AdapterError::ParseError(err) => Some(err.error.pos),
265 _ => None,
266 }
267 }
268
269 pub fn detail(&self) -> Option<String> {
271 match self {
272 AdapterError::AmbiguousSystemColumnReference => {
273 Some("This is a current limitation in Materialize".into())
274 },
275 AdapterError::Catalog(c) => c.detail(),
276 AdapterError::Eval(e) => e.detail(),
277 AdapterError::RelationOutsideTimeDomain { relations, names } => Some(format!(
278 "The following relations in the query are outside the transaction's time domain:\n{}\n{}",
279 relations
280 .iter()
281 .map(|r| r.quoted().to_string())
282 .collect::<Vec<_>>()
283 .join("\n"),
284 match names.is_empty() {
285 true => "No relations are available.".to_string(),
286 false => format!(
287 "Only the following relations are available:\n{}",
288 names
289 .iter()
290 .map(|name| name.quoted().to_string())
291 .collect::<Vec<_>>()
292 .join("\n")
293 ),
294 }
295 )),
296 AdapterError::SourceOrSinkSizeRequired { .. } => Some(
297 "Either specify the cluster that will maintain this object via IN CLUSTER or \
298 specify size via SIZE option."
299 .into(),
300 ),
301 AdapterError::SafeModeViolation(_) => Some(
302 "The Materialize server you are connected to is running in \
303 safe mode, which limits the features that are available."
304 .into(),
305 ),
306 AdapterError::IntrospectionDisabled { log_names }
307 | AdapterError::UntargetedLogRead { log_names } => Some(format!(
308 "The query references the following log sources:\n {}",
309 log_names.join("\n "),
310 )),
311 AdapterError::InvalidLogDependency { log_names, .. } => Some(format!(
312 "The object depends on the following log sources:\n {}",
313 log_names.join("\n "),
314 )),
315 AdapterError::PlanError(e) => e.detail(),
316 AdapterError::Unauthorized(unauthorized) => unauthorized.detail(),
317 AdapterError::DependentObject(dependent_objects) => {
318 Some(dependent_objects
319 .iter()
320 .map(|(role_name, err_msgs)| err_msgs
321 .iter()
322 .map(|err_msg| format!("{role_name}: {err_msg}"))
323 .join("\n"))
324 .join("\n"))
325 },
326 AdapterError::Storage(storage_error) => {
327 storage_error.source().map(|source_error| source_error.to_string_with_causes())
328 }
329 AdapterError::ReadOnlyTransaction => Some("SELECT queries cannot be combined with other query types, including SUBSCRIBE.".into()),
330 AdapterError::InvalidAlter(_, e) => e.detail(),
331 AdapterError::Optimizer(e) => e.detail(),
332 AdapterError::ConnectionValidation(e) => e.detail(),
333 AdapterError::MaterializedViewWouldNeverRefresh(last_refresh, earliest_possible) => {
334 Some(format!(
335 "The specified last refresh is at {}, while the earliest possible time to compute the materialized \
336 view is {}.",
337 last_refresh,
338 earliest_possible,
339 ))
340 }
341 AdapterError::UnallowedOnCluster { cluster, .. } => (cluster == MZ_CATALOG_SERVER_CLUSTER.name).then(||
342 format!("The transaction is executing on the {cluster} cluster, maybe having been routed there by the first statement in the transaction.")
343 ),
344 AdapterError::InputNotReadableAtRefreshAtTime(oracle_read_ts, least_valid_read) => {
345 Some(format!(
346 "The requested REFRESH AT time is {}, \
347 but not all input collections are readable earlier than [{}].",
348 oracle_read_ts,
349 if least_valid_read.len() == 1 {
350 format!("{}", least_valid_read.as_option().expect("antichain contains exactly 1 timestamp"))
351 } else {
352 format!("{:?}", least_valid_read)
354 }
355 ))
356 }
357 AdapterError::RtrTimeout(name) => Some(format!("{name} failed to ingest data up to the real-time recency point")),
358 AdapterError::RtrDropFailure(name) => Some(format!("{name} dropped before ingesting data to the real-time recency point")),
359 AdapterError::UserSessionsDisallowed => Some("Your organization has been blocked. Please contact support.".to_string()),
360 AdapterError::NetworkPolicyDenied(reason)=> Some(format!("{reason}.")),
361 _ => None,
362 }
363 }
364
365 pub fn hint(&self) -> Option<String> {
367 match self {
368 AdapterError::AmbiguousSystemColumnReference => Some(
369 "Rewrite the view to refer to all columns by name. Expand all wildcards and \
370 convert all NATURAL JOINs to USING joins."
371 .to_string(),
372 ),
373 AdapterError::Catalog(c) => c.hint(),
374 AdapterError::Eval(e) => e.hint(),
375 AdapterError::InvalidClusterReplicaAz { expected, az: _ } => {
376 Some(if expected.is_empty() {
377 "No availability zones configured; do not specify AVAILABILITY ZONE".into()
378 } else {
379 format!("Valid availability zones are: {}", expected.join(", "))
380 })
381 }
382 AdapterError::InvalidStorageClusterSize { expected, .. } => {
383 Some(format!("Valid sizes are: {}", expected.join(", ")))
384 }
385 AdapterError::SourceOrSinkSizeRequired { expected } => Some(format!(
386 "Try choosing one of the smaller sizes to start. Available sizes: {}",
387 expected.join(", ")
388 )),
389 AdapterError::NoClusterReplicasAvailable { is_managed, .. } => {
390 Some(if *is_managed {
391 "Use ALTER CLUSTER to adjust the replication factor of the cluster. \
392 Example:`ALTER CLUSTER <cluster-name> SET (REPLICATION FACTOR 1)`".into()
393 } else {
394 "Use CREATE CLUSTER REPLICA to attach cluster replicas to the cluster".into()
395 })
396 }
397 AdapterError::UntargetedLogRead { .. } => Some(
398 "Use `SET cluster_replica = <replica-name>` to target a specific replica in the \
399 active cluster. Note that subsequent queries will only be answered by \
400 the selected replica, which might reduce availability. To undo the replica \
401 selection, use `RESET cluster_replica`."
402 .into(),
403 ),
404 AdapterError::ResourceExhaustion { resource_type, .. } => Some(format!(
405 "Drop an existing {resource_type} or contact support to request a limit increase."
406 )),
407 AdapterError::StatementTimeout => Some(
408 "Consider increasing the maximum allowed statement duration for this session by \
409 setting the statement_timeout session variable. For example, `SET \
410 statement_timeout = '120s'`."
411 .into(),
412 ),
413 AdapterError::PlanError(e) => e.hint(),
414 AdapterError::UnallowedOnCluster { cluster, .. } => {
415 (cluster != MZ_CATALOG_SERVER_CLUSTER.name).then(||
416 "Use `SET CLUSTER = <cluster-name>` to change your cluster and re-run the query."
417 .to_string()
418 )
419 }
420 AdapterError::InvalidAlter(_, e) => e.hint(),
421 AdapterError::Optimizer(e) => e.hint(),
422 AdapterError::ConnectionValidation(e) => e.hint(),
423 AdapterError::InputNotReadableAtRefreshAtTime(_, _) => Some(
424 "You can use `REFRESH AT greatest(mz_now(), <explicit timestamp>)` to refresh \
425 either at the explicitly specified timestamp, or now if the given timestamp would \
426 be in the past.".to_string()
427 ),
428 AdapterError::AlterClusterTimeout => Some(
429 "Consider increasing the timeout duration in the alter cluster statement.".into(),
430 ),
431 _ => None,
432 }
433 }
434
435 pub fn code(&self) -> SqlState {
436 match self {
441 AdapterError::AbsurdSubscribeBounds { .. } => SqlState::DATA_EXCEPTION,
444 AdapterError::AmbiguousSystemColumnReference => SqlState::FEATURE_NOT_SUPPORTED,
445 AdapterError::Catalog(e) => match &e.kind {
446 mz_catalog::memory::error::ErrorKind::VarError(e) => match e {
447 VarError::ConstrainedParameter { .. } => SqlState::INVALID_PARAMETER_VALUE,
448 VarError::FixedValueParameter { .. } => SqlState::INVALID_PARAMETER_VALUE,
449 VarError::InvalidParameterType { .. } => SqlState::INVALID_PARAMETER_VALUE,
450 VarError::InvalidParameterValue { .. } => SqlState::INVALID_PARAMETER_VALUE,
451 VarError::ReadOnlyParameter(_) => SqlState::CANT_CHANGE_RUNTIME_PARAM,
452 VarError::UnknownParameter(_) => SqlState::UNDEFINED_OBJECT,
453 VarError::RequiresUnsafeMode { .. } => SqlState::CANT_CHANGE_RUNTIME_PARAM,
454 VarError::RequiresFeatureFlag { .. } => SqlState::CANT_CHANGE_RUNTIME_PARAM,
455 },
456 _ => SqlState::INTERNAL_ERROR,
457 },
458 AdapterError::ChangedPlan(_) => SqlState::FEATURE_NOT_SUPPORTED,
459 AdapterError::DuplicateCursor(_) => SqlState::DUPLICATE_CURSOR,
460 AdapterError::Eval(EvalError::CharacterNotValidForEncoding(_)) => {
461 SqlState::PROGRAM_LIMIT_EXCEEDED
462 }
463 AdapterError::Eval(EvalError::CharacterTooLargeForEncoding(_)) => {
464 SqlState::PROGRAM_LIMIT_EXCEEDED
465 }
466 AdapterError::Eval(EvalError::LengthTooLarge) => SqlState::PROGRAM_LIMIT_EXCEEDED,
467 AdapterError::Eval(EvalError::NullCharacterNotPermitted) => {
468 SqlState::PROGRAM_LIMIT_EXCEEDED
469 }
470 AdapterError::Eval(_) => SqlState::INTERNAL_ERROR,
471 AdapterError::Explain(_) => SqlState::INTERNAL_ERROR,
472 AdapterError::IdExhaustionError => SqlState::INTERNAL_ERROR,
473 AdapterError::Internal(_) => SqlState::INTERNAL_ERROR,
474 AdapterError::IntrospectionDisabled { .. } => SqlState::FEATURE_NOT_SUPPORTED,
475 AdapterError::InvalidLogDependency { .. } => SqlState::FEATURE_NOT_SUPPORTED,
476 AdapterError::InvalidClusterReplicaAz { .. } => SqlState::FEATURE_NOT_SUPPORTED,
477 AdapterError::InvalidSetIsolationLevel => SqlState::ACTIVE_SQL_TRANSACTION,
478 AdapterError::InvalidSetCluster => SqlState::ACTIVE_SQL_TRANSACTION,
479 AdapterError::InvalidStorageClusterSize { .. } => SqlState::FEATURE_NOT_SUPPORTED,
480 AdapterError::SourceOrSinkSizeRequired { .. } => SqlState::FEATURE_NOT_SUPPORTED,
481 AdapterError::InvalidTableMutationSelection => SqlState::INVALID_TRANSACTION_STATE,
482 AdapterError::ConstraintViolation(NotNullViolation(_)) => SqlState::NOT_NULL_VIOLATION,
483 AdapterError::ConcurrentClusterDrop => SqlState::INVALID_TRANSACTION_STATE,
484 AdapterError::NoClusterReplicasAvailable { .. } => SqlState::FEATURE_NOT_SUPPORTED,
485 AdapterError::OperationProhibitsTransaction(_) => SqlState::ACTIVE_SQL_TRANSACTION,
486 AdapterError::OperationRequiresTransaction(_) => SqlState::NO_ACTIVE_SQL_TRANSACTION,
487 AdapterError::ParseError(_) => SqlState::SYNTAX_ERROR,
488 AdapterError::PlanError(PlanError::InvalidSchemaName) => SqlState::INVALID_SCHEMA_NAME,
489 AdapterError::PlanError(PlanError::ColumnAlreadyExists { .. }) => {
490 SqlState::DUPLICATE_COLUMN
491 }
492 AdapterError::PlanError(_) => SqlState::INTERNAL_ERROR,
493 AdapterError::PreparedStatementExists(_) => SqlState::DUPLICATE_PSTATEMENT,
494 AdapterError::ReadOnlyTransaction => SqlState::READ_ONLY_SQL_TRANSACTION,
495 AdapterError::ReadWriteUnavailable => SqlState::INVALID_TRANSACTION_STATE,
496 AdapterError::SingleStatementTransaction => SqlState::INVALID_TRANSACTION_STATE,
497 AdapterError::WrongSetOfLocks => SqlState::LOCK_NOT_AVAILABLE,
498 AdapterError::StatementTimeout => SqlState::QUERY_CANCELED,
499 AdapterError::Canceled => SqlState::QUERY_CANCELED,
500 AdapterError::IdleInTransactionSessionTimeout => {
501 SqlState::IDLE_IN_TRANSACTION_SESSION_TIMEOUT
502 }
503 AdapterError::RecursionLimit(_) => SqlState::INTERNAL_ERROR,
504 AdapterError::RelationOutsideTimeDomain { .. } => SqlState::INVALID_TRANSACTION_STATE,
505 AdapterError::ResourceExhaustion { .. } => SqlState::INSUFFICIENT_RESOURCES,
506 AdapterError::ResultSize(_) => SqlState::OUT_OF_MEMORY,
507 AdapterError::SafeModeViolation(_) => SqlState::INTERNAL_ERROR,
508 AdapterError::SubscribeOnlyTransaction => SqlState::INVALID_TRANSACTION_STATE,
509 AdapterError::Optimizer(e) => match e {
510 OptimizerError::PlanError(e) => {
511 AdapterError::PlanError(e.clone()).code() }
513 OptimizerError::RecursionLimitError(e) => {
514 AdapterError::RecursionLimit(e.clone()).code() }
516 OptimizerError::Internal(s) => {
517 AdapterError::Internal(s.clone()).code() }
519 OptimizerError::EvalError(e) => {
520 AdapterError::Eval(e.clone()).code() }
522 OptimizerError::TransformError(_) => SqlState::INTERNAL_ERROR,
523 OptimizerError::UnmaterializableFunction(_) => SqlState::FEATURE_NOT_SUPPORTED,
524 OptimizerError::UncallableFunction { .. } => SqlState::FEATURE_NOT_SUPPORTED,
525 OptimizerError::UnsafeMfpPlan => SqlState::INTERNAL_ERROR,
528 },
529 AdapterError::UnallowedOnCluster { .. } => {
530 SqlState::S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED
531 }
532 AdapterError::Unauthorized(_) => SqlState::INSUFFICIENT_PRIVILEGE,
533 AdapterError::UnknownCursor(_) => SqlState::INVALID_CURSOR_NAME,
534 AdapterError::UnknownPreparedStatement(_) => SqlState::UNDEFINED_PSTATEMENT,
535 AdapterError::UnknownLoginRole(_) => SqlState::INVALID_AUTHORIZATION_SPECIFICATION,
536 AdapterError::UnknownClusterReplica { .. } => SqlState::UNDEFINED_OBJECT,
537 AdapterError::UnrecognizedConfigurationParam(_) => SqlState::UNDEFINED_OBJECT,
538 AdapterError::Unsupported(..) => SqlState::FEATURE_NOT_SUPPORTED,
539 AdapterError::UnavailableFeature { .. } => SqlState::FEATURE_NOT_SUPPORTED,
540 AdapterError::Unstructured(_) => SqlState::INTERNAL_ERROR,
541 AdapterError::UntargetedLogRead { .. } => SqlState::FEATURE_NOT_SUPPORTED,
542 AdapterError::DDLTransactionRace => SqlState::T_R_SERIALIZATION_FAILURE,
543 AdapterError::TransactionDryRun { .. } => SqlState::T_R_SERIALIZATION_FAILURE,
544 AdapterError::WriteOnlyTransaction => SqlState::INVALID_TRANSACTION_STATE,
549 AdapterError::DDLOnlyTransaction => SqlState::INVALID_TRANSACTION_STATE,
550 AdapterError::Storage(_) | AdapterError::Compute(_) | AdapterError::Orchestrator(_) => {
551 SqlState::INTERNAL_ERROR
552 }
553 AdapterError::DependentObject(_) => SqlState::DEPENDENT_OBJECTS_STILL_EXIST,
554 AdapterError::InvalidAlter(_, _) => SqlState::FEATURE_NOT_SUPPORTED,
555 AdapterError::ConnectionValidation(_) => SqlState::SYSTEM_ERROR,
556 AdapterError::MaterializedViewWouldNeverRefresh(_, _) => SqlState::DATA_EXCEPTION,
558 AdapterError::InputNotReadableAtRefreshAtTime(_, _) => SqlState::DATA_EXCEPTION,
559 AdapterError::RtrTimeout(_) => SqlState::QUERY_CANCELED,
560 AdapterError::RtrDropFailure(_) => SqlState::UNDEFINED_OBJECT,
561 AdapterError::UnreadableSinkCollection => SqlState::from_code("MZ009"),
562 AdapterError::UserSessionsDisallowed => SqlState::from_code("MZ010"),
563 AdapterError::NetworkPolicyDenied(_) => SqlState::from_code("MZ011"),
564 AdapterError::ReadOnly => SqlState::READ_ONLY_SQL_TRANSACTION,
567 AdapterError::AlterClusterTimeout => SqlState::QUERY_CANCELED,
568 AdapterError::AuthenticationError => SqlState::INVALID_AUTHORIZATION_SPECIFICATION,
569 }
570 }
571
572 pub fn internal<E: std::fmt::Display>(context: &str, e: E) -> AdapterError {
573 AdapterError::Internal(format!("{context}: {e}"))
574 }
575}
576
577impl fmt::Display for AdapterError {
578 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
579 match self {
580 AdapterError::AbsurdSubscribeBounds { as_of, up_to } => {
581 assert!(up_to < as_of);
582 write!(
583 f,
584 r#"subscription lower ("as of") bound is beyond its upper ("up to") bound: {} < {}"#,
585 up_to, as_of
586 )
587 }
588 AdapterError::AmbiguousSystemColumnReference => {
589 write!(
590 f,
591 "cannot use wildcard expansions or NATURAL JOINs in a view that depends on \
592 system objects"
593 )
594 }
595 AdapterError::ChangedPlan(e) => write!(f, "{}", e),
596 AdapterError::Catalog(e) => e.fmt(f),
597 AdapterError::DuplicateCursor(name) => {
598 write!(f, "cursor {} already exists", name.quoted())
599 }
600 AdapterError::Eval(e) => e.fmt(f),
601 AdapterError::Explain(e) => e.fmt(f),
602 AdapterError::IdExhaustionError => f.write_str("ID allocator exhausted all valid IDs"),
603 AdapterError::Internal(e) => write!(f, "internal error: {}", e),
604 AdapterError::IntrospectionDisabled { .. } => write!(
605 f,
606 "cannot read log sources of replica with disabled introspection"
607 ),
608 AdapterError::InvalidLogDependency { object_type, .. } => {
609 write!(f, "{object_type} objects cannot depend on log sources")
610 }
611 AdapterError::InvalidClusterReplicaAz { az, expected: _ } => {
612 write!(f, "unknown cluster replica availability zone {az}",)
613 }
614 AdapterError::InvalidSetIsolationLevel => write!(
615 f,
616 "SET TRANSACTION ISOLATION LEVEL must be called before any query"
617 ),
618 AdapterError::InvalidSetCluster => {
619 write!(f, "SET cluster cannot be called in an active transaction")
620 }
621 AdapterError::InvalidStorageClusterSize { size, .. } => {
622 write!(f, "unknown source size {size}")
623 }
624 AdapterError::SourceOrSinkSizeRequired { .. } => {
625 write!(f, "must specify either cluster or size option")
626 }
627 AdapterError::InvalidTableMutationSelection => {
628 f.write_str("invalid selection: operation may only refer to user-defined tables")
629 }
630 AdapterError::ConstraintViolation(not_null_violation) => {
631 write!(f, "{}", not_null_violation)
632 }
633 AdapterError::ConcurrentClusterDrop => {
634 write!(f, "the transaction's active cluster has been dropped")
635 }
636 AdapterError::NoClusterReplicasAvailable { name, .. } => {
637 write!(
638 f,
639 "CLUSTER {} has no replicas available to service request",
640 name.quoted()
641 )
642 }
643 AdapterError::OperationProhibitsTransaction(op) => {
644 write!(f, "{} cannot be run inside a transaction block", op)
645 }
646 AdapterError::OperationRequiresTransaction(op) => {
647 write!(f, "{} can only be used in transaction blocks", op)
648 }
649 AdapterError::ParseError(e) => e.fmt(f),
650 AdapterError::PlanError(e) => e.fmt(f),
651 AdapterError::PreparedStatementExists(name) => {
652 write!(f, "prepared statement {} already exists", name.quoted())
653 }
654 AdapterError::ReadOnlyTransaction => f.write_str("transaction in read-only mode"),
655 AdapterError::SingleStatementTransaction => {
656 f.write_str("this transaction can only execute a single statement")
657 }
658 AdapterError::ReadWriteUnavailable => {
659 f.write_str("transaction read-write mode must be set before any query")
660 }
661 AdapterError::WrongSetOfLocks => {
662 write!(f, "internal error, wrong set of locks acquired")
663 }
664 AdapterError::StatementTimeout => {
665 write!(f, "canceling statement due to statement timeout")
666 }
667 AdapterError::Canceled => {
668 write!(f, "canceling statement due to user request")
669 }
670 AdapterError::IdleInTransactionSessionTimeout => {
671 write!(
672 f,
673 "terminating connection due to idle-in-transaction timeout"
674 )
675 }
676 AdapterError::RecursionLimit(e) => e.fmt(f),
677 AdapterError::RelationOutsideTimeDomain { .. } => {
678 write!(
679 f,
680 "Transactions can only reference objects in the same timedomain. \
681 See https://materialize.com/docs/sql/begin/#same-timedomain-error",
682 )
683 }
684 AdapterError::ResourceExhaustion {
685 resource_type,
686 limit_name,
687 desired,
688 limit,
689 current,
690 } => {
691 write!(
692 f,
693 "creating {resource_type} would violate {limit_name} limit (desired: {desired}, limit: {limit}, current: {current})"
694 )
695 }
696 AdapterError::ResultSize(e) => write!(f, "{e}"),
697 AdapterError::SafeModeViolation(feature) => {
698 write!(f, "cannot create {} in safe mode", feature)
699 }
700 AdapterError::SubscribeOnlyTransaction => {
701 f.write_str("SUBSCRIBE in transactions must be the only read statement")
702 }
703 AdapterError::Optimizer(e) => e.fmt(f),
704 AdapterError::UnallowedOnCluster {
705 depends_on,
706 cluster,
707 } => {
708 let items = depends_on.into_iter().map(|item| item.quoted()).join(", ");
709 write!(
710 f,
711 "querying the following items {items} is not allowed from the {} cluster",
712 cluster.quoted()
713 )
714 }
715 AdapterError::Unauthorized(unauthorized) => {
716 write!(f, "{unauthorized}")
717 }
718 AdapterError::UnknownCursor(name) => {
719 write!(f, "cursor {} does not exist", name.quoted())
720 }
721 AdapterError::UnknownLoginRole(name) => {
722 write!(f, "role {} does not exist", name.quoted())
723 }
724 AdapterError::Unsupported(features) => write!(f, "{} are not supported", features),
725 AdapterError::Unstructured(e) => write!(f, "{}", e.display_with_causes()),
726 AdapterError::WriteOnlyTransaction => f.write_str("transaction in write-only mode"),
727 AdapterError::UnknownPreparedStatement(name) => {
728 write!(f, "prepared statement {} does not exist", name.quoted())
729 }
730 AdapterError::UnknownClusterReplica {
731 cluster_name,
732 replica_name,
733 } => write!(
734 f,
735 "cluster replica '{cluster_name}.{replica_name}' does not exist"
736 ),
737 AdapterError::UnrecognizedConfigurationParam(setting_name) => write!(
738 f,
739 "unrecognized configuration parameter {}",
740 setting_name.quoted()
741 ),
742 AdapterError::UntargetedLogRead { .. } => {
743 f.write_str("log source reads must target a replica")
744 }
745 AdapterError::DDLOnlyTransaction => f.write_str(
746 "transactions which modify objects are restricted to just modifying objects",
747 ),
748 AdapterError::DDLTransactionRace => {
749 f.write_str("object state changed while transaction was in progress")
750 }
751 AdapterError::TransactionDryRun { .. } => f.write_str("transaction dry run"),
752 AdapterError::Storage(e) => e.fmt(f),
753 AdapterError::Compute(e) => e.fmt(f),
754 AdapterError::Orchestrator(e) => e.fmt(f),
755 AdapterError::DependentObject(dependent_objects) => {
756 let role_str = if dependent_objects.keys().count() == 1 {
757 "role"
758 } else {
759 "roles"
760 };
761 write!(
762 f,
763 "{role_str} \"{}\" cannot be dropped because some objects depend on it",
764 dependent_objects.keys().join(", ")
765 )
766 }
767 AdapterError::InvalidAlter(t, e) => {
768 write!(f, "invalid ALTER {t}: {e}")
769 }
770 AdapterError::ConnectionValidation(e) => e.fmt(f),
771 AdapterError::MaterializedViewWouldNeverRefresh(_, _) => {
772 write!(
773 f,
774 "all the specified refreshes of the materialized view would be too far in the past, and thus they \
775 would never happen"
776 )
777 }
778 AdapterError::InputNotReadableAtRefreshAtTime(_, _) => {
779 write!(
780 f,
781 "REFRESH AT requested for a time where not all the inputs are readable"
782 )
783 }
784 AdapterError::RtrTimeout(_) => {
785 write!(
786 f,
787 "timed out before ingesting the source's visible frontier when real-time-recency query issued"
788 )
789 }
790 AdapterError::RtrDropFailure(_) => write!(
791 f,
792 "real-time source dropped before ingesting the upstream system's visible frontier"
793 ),
794 AdapterError::UnreadableSinkCollection => {
795 write!(f, "collection is not readable at any time")
796 }
797 AdapterError::UserSessionsDisallowed => write!(f, "login blocked"),
798 AdapterError::NetworkPolicyDenied(_) => write!(f, "session denied"),
799 AdapterError::ReadOnly => write!(f, "cannot write in read-only mode"),
800 AdapterError::AlterClusterTimeout => {
801 write!(f, "canceling statement, provided timeout lapsed")
802 }
803 AdapterError::AuthenticationError => {
804 write!(f, "authentication error")
805 }
806 AdapterError::UnavailableFeature { feature, docs } => {
807 write!(f, "{} is not supported in this environment.", feature)?;
808 if let Some(docs) = docs {
809 write!(
810 f,
811 " For more information consult the documentation at {docs}"
812 )?;
813 }
814 Ok(())
815 }
816 }
817 }
818}
819
820impl From<anyhow::Error> for AdapterError {
821 fn from(e: anyhow::Error) -> AdapterError {
822 match e.downcast_ref::<PlanError>() {
823 Some(plan_error) => AdapterError::PlanError(plan_error.clone()),
824 None => AdapterError::Unstructured(e),
825 }
826 }
827}
828
829impl From<TryFromIntError> for AdapterError {
830 fn from(e: TryFromIntError) -> AdapterError {
831 AdapterError::Unstructured(e.into())
832 }
833}
834
835impl From<TryFromDecimalError> for AdapterError {
836 fn from(e: TryFromDecimalError) -> AdapterError {
837 AdapterError::Unstructured(e.into())
838 }
839}
840
841impl From<mz_catalog::memory::error::Error> for AdapterError {
842 fn from(e: mz_catalog::memory::error::Error) -> AdapterError {
843 AdapterError::Catalog(e)
844 }
845}
846
847impl From<mz_catalog::durable::CatalogError> for AdapterError {
848 fn from(e: mz_catalog::durable::CatalogError) -> Self {
849 mz_catalog::memory::error::Error::from(e).into()
850 }
851}
852
853impl From<mz_catalog::durable::DurableCatalogError> for AdapterError {
854 fn from(e: mz_catalog::durable::DurableCatalogError) -> Self {
855 mz_catalog::durable::CatalogError::from(e).into()
856 }
857}
858
859impl From<EvalError> for AdapterError {
860 fn from(e: EvalError) -> AdapterError {
861 AdapterError::Eval(e)
862 }
863}
864
865impl From<ExplainError> for AdapterError {
866 fn from(e: ExplainError) -> AdapterError {
867 match e {
868 ExplainError::RecursionLimitError(e) => AdapterError::RecursionLimit(e),
869 e => AdapterError::Explain(e),
870 }
871 }
872}
873
874impl From<mz_sql::catalog::CatalogError> for AdapterError {
875 fn from(e: mz_sql::catalog::CatalogError) -> AdapterError {
876 AdapterError::Catalog(mz_catalog::memory::error::Error::from(e))
877 }
878}
879
880impl From<PlanError> for AdapterError {
881 fn from(e: PlanError) -> AdapterError {
882 AdapterError::PlanError(e)
883 }
884}
885
886impl From<OptimizerError> for AdapterError {
887 fn from(e: OptimizerError) -> AdapterError {
888 use OptimizerError::*;
889 match e {
890 PlanError(e) => Self::PlanError(e),
891 RecursionLimitError(e) => Self::RecursionLimit(e),
892 EvalError(e) => Self::Eval(e),
893 Internal(e) => Self::Internal(e),
894 e => Self::Optimizer(e),
895 }
896 }
897}
898
899impl From<NotNullViolation> for AdapterError {
900 fn from(e: NotNullViolation) -> AdapterError {
901 AdapterError::ConstraintViolation(e)
902 }
903}
904
905impl From<RecursionLimitError> for AdapterError {
906 fn from(e: RecursionLimitError) -> AdapterError {
907 AdapterError::RecursionLimit(e)
908 }
909}
910
911impl From<oneshot::error::RecvError> for AdapterError {
912 fn from(e: oneshot::error::RecvError) -> AdapterError {
913 AdapterError::Unstructured(e.into())
914 }
915}
916
917impl From<StorageError<mz_repr::Timestamp>> for AdapterError {
918 fn from(e: StorageError<mz_repr::Timestamp>) -> Self {
919 AdapterError::Storage(e)
920 }
921}
922
923impl From<compute_error::InstanceExists> for AdapterError {
924 fn from(e: compute_error::InstanceExists) -> Self {
925 AdapterError::Compute(e.into())
926 }
927}
928
929impl From<TimestampError> for AdapterError {
930 fn from(e: TimestampError) -> Self {
931 let e: EvalError = e.into();
932 e.into()
933 }
934}
935
936impl From<mz_sql_parser::parser::ParserStatementError> for AdapterError {
937 fn from(e: mz_sql_parser::parser::ParserStatementError) -> Self {
938 AdapterError::ParseError(e)
939 }
940}
941
942impl From<VarError> for AdapterError {
943 fn from(e: VarError) -> Self {
944 let e: mz_catalog::memory::error::Error = e.into();
945 e.into()
946 }
947}
948
949impl From<rbac::UnauthorizedError> for AdapterError {
950 fn from(e: rbac::UnauthorizedError) -> Self {
951 AdapterError::Unauthorized(e)
952 }
953}
954
955impl From<mz_sql_parser::ast::IdentError> for AdapterError {
956 fn from(value: mz_sql_parser::ast::IdentError) -> Self {
957 AdapterError::PlanError(PlanError::InvalidIdent(value))
958 }
959}
960
961impl From<mz_pgwire_common::ConnectionError> for AdapterError {
962 fn from(value: mz_pgwire_common::ConnectionError) -> Self {
963 match value {
964 mz_pgwire_common::ConnectionError::TooManyConnections { current, limit } => {
965 AdapterError::ResourceExhaustion {
966 resource_type: "connection".into(),
967 limit_name: "max_connections".into(),
968 desired: (current + 1).to_string(),
969 limit: limit.to_string(),
970 current: current.to_string(),
971 }
972 }
973 }
974 }
975}
976
977impl From<NetworkPolicyError> for AdapterError {
978 fn from(value: NetworkPolicyError) -> Self {
979 AdapterError::NetworkPolicyDenied(value)
980 }
981}
982
983impl From<ConnectionValidationError> for AdapterError {
984 fn from(e: ConnectionValidationError) -> AdapterError {
985 AdapterError::ConnectionValidation(e)
986 }
987}
988
989impl Error for AdapterError {}