1use std::collections::{BTreeMap, BTreeSet};
11use std::error::Error;
12use std::fmt;
13use std::num::TryFromIntError;
14
15use dec::TryFromDecimalError;
16use itertools::Itertools;
17use mz_catalog::builtin::MZ_CATALOG_SERVER_CLUSTER;
18use mz_compute_client::controller::error as compute_error;
19use mz_compute_client::controller::error::InstanceMissing;
20
21use mz_compute_types::ComputeInstanceId;
22use mz_expr::EvalError;
23use mz_ore::error::ErrorExt;
24use mz_ore::stack::RecursionLimitError;
25use mz_ore::str::StrExt;
26use mz_pgwire_common::{ErrorResponse, Severity};
27use mz_repr::adt::timestamp::TimestampError;
28use mz_repr::explain::ExplainError;
29use mz_repr::{ColumnDiff, ColumnName, KeyDiff, NotNullViolation, RelationDescDiff, Timestamp};
30use mz_sql::plan::PlanError;
31use mz_sql::rbac;
32use mz_sql::session::vars::VarError;
33use mz_storage_types::connections::ConnectionValidationError;
34use mz_storage_types::controller::StorageError;
35use mz_storage_types::errors::CollectionMissing;
36use smallvec::SmallVec;
37use timely::progress::Antichain;
38use tokio::sync::oneshot;
39use tokio_postgres::error::SqlState;
40
41use crate::coord::NetworkPolicyError;
42use crate::optimize::OptimizerError;
43use crate::peek_client::CollectionLookupError;
44
45#[derive(Debug)]
47pub enum AdapterError {
48 AbsurdSubscribeBounds {
50 as_of: mz_repr::Timestamp,
51 up_to: mz_repr::Timestamp,
52 },
53 AmbiguousSystemColumnReference,
57 Catalog(mz_catalog::memory::error::Error),
59 ChangedPlan(String),
64 DuplicateCursor(String),
66 Eval(EvalError),
68 Explain(ExplainError),
70 IdExhaustionError,
72 Internal(String),
74 IntrospectionDisabled {
76 log_names: Vec<String>,
77 },
78 InvalidLogDependency {
81 object_type: String,
82 log_names: Vec<String>,
83 },
84 InvalidClusterReplicaAz {
86 az: String,
87 expected: Vec<String>,
88 },
89 InvalidSetIsolationLevel,
91 InvalidSetCluster,
93 InvalidStorageClusterSize {
95 size: String,
96 expected: Vec<String>,
97 },
98 SourceOrSinkSizeRequired {
100 expected: Vec<String>,
101 },
102 InvalidTableMutationSelection {
104 object_name: String,
106 object_type: String,
108 },
109 ConstraintViolation(NotNullViolation),
111 CopyFormatError(String),
113 ConcurrentClusterDrop,
115 ConcurrentDependencyDrop {
117 dependency_kind: &'static str,
118 dependency_id: String,
119 },
120 CollectionUnreadable {
121 id: String,
122 },
123 NoClusterReplicasAvailable {
125 name: String,
126 is_managed: bool,
127 },
128 OperationProhibitsTransaction(String),
130 OperationRequiresTransaction(String),
132 PlanError(PlanError),
134 PreparedStatementExists(String),
136 ParseError(mz_sql_parser::parser::ParserStatementError),
138 ReadOnlyTransaction,
140 ReadWriteUnavailable,
142 RecursionLimit(RecursionLimitError),
144 RelationOutsideTimeDomain {
147 relations: Vec<String>,
148 names: Vec<String>,
149 },
150 ResourceExhaustion {
152 resource_type: String,
153 limit_name: String,
154 desired: String,
155 limit: String,
156 current: String,
157 },
158 ResultSize(String),
160 SafeModeViolation(String),
162 WrongSetOfLocks,
164 StatementTimeout,
168 Canceled,
170 IdleInTransactionSessionTimeout,
172 SubscribeOnlyTransaction,
174 Optimizer(OptimizerError),
176 UnallowedOnCluster {
178 depends_on: SmallVec<[String; 2]>,
179 cluster: String,
180 },
181 Unauthorized(rbac::UnauthorizedError),
183 UnknownCursor(String),
185 UnknownLoginRole(String),
187 UnknownPreparedStatement(String),
188 UnknownClusterReplica {
190 cluster_name: String,
191 replica_name: String,
192 },
193 UnrecognizedConfigurationParam(String),
195 Unstructured(anyhow::Error),
199 Unsupported(&'static str),
201 UnavailableFeature {
205 feature: String,
206 docs: Option<String>,
207 },
208 UntargetedLogRead {
210 log_names: Vec<String>,
211 },
212 WriteOnlyTransaction,
214 SingleStatementTransaction,
216 DDLOnlyTransaction,
218 DDLTransactionRace,
220 Storage(mz_storage_types::controller::StorageError),
222 Compute(anyhow::Error),
224 Orchestrator(anyhow::Error),
226 DependentObject(BTreeMap<String, Vec<String>>),
230 InvalidAlter(&'static str, PlanError),
233 ConnectionValidation(ConnectionValidationError),
235 MaterializedViewWouldNeverRefresh(Timestamp, Timestamp),
239 InputNotReadableAtRefreshAtTime(Timestamp, Antichain<Timestamp>),
242 RtrTimeout(String),
244 RtrDropFailure(String),
246 UnreadableSinkCollection,
248 UserSessionsDisallowed,
250 NetworkPolicyDenied(NetworkPolicyError),
252 ReadOnly,
255 AlterClusterTimeout,
256 AlterClusterWhilePendingReplicas,
257 AuthenticationError(AuthenticationError),
258 ReplacementSchemaMismatch(RelationDescDiff),
260 ReplaceMaterializedViewSealed {
262 name: String,
263 },
264 ImpossibleTimestampConstraints {
266 constraints: String,
267 },
268 OidcGroupSyncFailed(String),
270}
271
272#[derive(Debug, thiserror::Error)]
273pub enum AuthenticationError {
274 #[error("invalid credentials")]
275 InvalidCredentials,
276 #[error("role is not allowed to login")]
277 NonLogin,
278 #[error("role does not exist")]
279 RoleNotFound,
280 #[error("password is required")]
281 PasswordRequired,
282}
283
284impl AdapterError {
285 pub fn into_response(self, severity: Severity) -> ErrorResponse {
286 ErrorResponse {
287 severity,
288 code: self.code(),
289 message: self.to_string(),
290 detail: self.detail(),
291 hint: self.hint(),
292 position: self.position(),
293 }
294 }
295
296 pub fn position(&self) -> Option<usize> {
297 match self {
298 AdapterError::ParseError(err) => Some(err.error.pos),
299 _ => None,
300 }
301 }
302
303 pub fn detail(&self) -> Option<String> {
305 match self {
306 AdapterError::AmbiguousSystemColumnReference => {
307 Some("This is a current limitation in Materialize".into())
308 }
309 AdapterError::Catalog(c) => c.detail(),
310 AdapterError::Eval(e) => e.detail(),
311 AdapterError::RelationOutsideTimeDomain { relations, names } => Some(format!(
312 "The following relations in the query are outside the transaction's time domain:\n{}\n{}",
313 relations
314 .iter()
315 .map(|r| r.quoted().to_string())
316 .collect::<Vec<_>>()
317 .join("\n"),
318 match names.is_empty() {
319 true => "No relations are available.".to_string(),
320 false => format!(
321 "Only the following relations are available:\n{}",
322 names
323 .iter()
324 .map(|name| name.quoted().to_string())
325 .collect::<Vec<_>>()
326 .join("\n")
327 ),
328 }
329 )),
330 AdapterError::SourceOrSinkSizeRequired { .. } => Some(
331 "Either specify the cluster that will maintain this object via IN CLUSTER or \
332 specify size via SIZE option."
333 .into(),
334 ),
335 AdapterError::InvalidTableMutationSelection {
336 object_name,
337 object_type,
338 } => Some(format!(
339 "{object_type} '{}' may not be used in this operation; \
340 the selection may refer to views and materialized views, but transitive \
341 dependencies must not include sources or source-export tables",
342 object_name.quoted()
343 )),
344 AdapterError::SafeModeViolation(_) => Some(
345 "The Materialize server you are connected to is running in \
346 safe mode, which limits the features that are available."
347 .into(),
348 ),
349 AdapterError::IntrospectionDisabled { log_names }
350 | AdapterError::UntargetedLogRead { log_names } => Some(format!(
351 "The query references the following log sources:\n {}",
352 log_names.join("\n "),
353 )),
354 AdapterError::InvalidLogDependency { log_names, .. } => Some(format!(
355 "The object depends on the following log sources:\n {}",
356 log_names.join("\n "),
357 )),
358 AdapterError::PlanError(e) => e.detail(),
359 AdapterError::Unauthorized(unauthorized) => unauthorized.detail(),
360 AdapterError::DependentObject(dependent_objects) => Some(
361 dependent_objects
362 .iter()
363 .map(|(role_name, err_msgs)| {
364 err_msgs
365 .iter()
366 .map(|err_msg| format!("{role_name}: {err_msg}"))
367 .join("\n")
368 })
369 .join("\n"),
370 ),
371 AdapterError::Storage(storage_error) => storage_error
372 .source()
373 .map(|source_error| source_error.to_string_with_causes()),
374 AdapterError::ReadOnlyTransaction => Some(
375 "SELECT queries cannot be combined with other query types, including SUBSCRIBE."
376 .into(),
377 ),
378 AdapterError::InvalidAlter(_, e) => e.detail(),
379 AdapterError::Optimizer(e) => e.detail(),
380 AdapterError::ConnectionValidation(e) => e.detail(),
381 AdapterError::MaterializedViewWouldNeverRefresh(last_refresh, earliest_possible) => {
382 Some(format!(
383 "The specified last refresh is at {}, while the earliest possible time to compute the materialized \
384 view is {}.",
385 last_refresh, earliest_possible,
386 ))
387 }
388 AdapterError::UnallowedOnCluster { cluster, .. } => {
389 (cluster == MZ_CATALOG_SERVER_CLUSTER.name).then(|| {
390 format!(
391 "The transaction is executing on the \
392 {cluster} cluster, maybe having been routed \
393 there by the first statement in the transaction."
394 )
395 })
396 }
397 AdapterError::InputNotReadableAtRefreshAtTime(oracle_read_ts, least_valid_read) => {
398 Some(format!(
399 "The requested REFRESH AT time is {}, \
400 but not all input collections are readable earlier than [{}].",
401 oracle_read_ts,
402 if least_valid_read.len() == 1 {
403 format!(
404 "{}",
405 least_valid_read
406 .as_option()
407 .expect("antichain contains exactly 1 timestamp")
408 )
409 } else {
410 format!("{:?}", least_valid_read)
412 }
413 ))
414 }
415 AdapterError::RtrTimeout(name) => Some(format!(
416 "{name} failed to ingest data up to the real-time recency point"
417 )),
418 AdapterError::RtrDropFailure(name) => Some(format!(
419 "{name} dropped before ingesting data to the real-time recency point"
420 )),
421 AdapterError::UserSessionsDisallowed => {
422 Some("Your organization has been blocked. Please contact support.".to_string())
423 }
424 AdapterError::NetworkPolicyDenied(reason) => Some(format!("{reason}.")),
425 AdapterError::ReplacementSchemaMismatch(diff) => {
426 let mut lines: Vec<_> = diff.column_diffs.iter().map(|(idx, diff)| {
427 let pos = idx + 1;
428 match diff {
429 ColumnDiff::Missing { name } => {
430 let name = name.as_str().quoted();
431 format!("missing column {name} at position {pos}")
432 }
433 ColumnDiff::Extra { name } => {
434 let name = name.as_str().quoted();
435 format!("extra column {name} at position {pos}")
436 }
437 ColumnDiff::TypeMismatch { name, left, right } => {
438 let name = name.as_str().quoted();
439 format!("column {name} at position {pos}: type mismatch (target: {left:?}, replacement: {right:?})")
440 }
441 ColumnDiff::NullabilityMismatch { name, left, right } => {
442 let name = name.as_str().quoted();
443 let left = if *left { "NULL" } else { "NOT NULL" };
444 let right = if *right { "NULL" } else { "NOT NULL" };
445 format!("column {name} at position {pos}: nullability mismatch (target: {left}, replacement: {right})")
446 }
447 ColumnDiff::NameMismatch { left, right } => {
448 let left = left.as_str().quoted();
449 let right = right.as_str().quoted();
450 format!("column at position {pos}: name mismatch (target: {left}, replacement: {right})")
451 }
452 }
453 }).collect();
454
455 if let Some(KeyDiff { left, right }) = &diff.key_diff {
456 let format_keys = |keys: &BTreeSet<Vec<ColumnName>>| {
457 if keys.is_empty() {
458 "(none)".to_string()
459 } else {
460 keys.iter()
461 .map(|key| {
462 let cols = key.iter().map(|c| c.as_str()).join(", ");
463 format!("{{{cols}}}")
464 })
465 .join(", ")
466 }
467 };
468 lines.push(format!(
469 "keys differ (target: {}, replacement: {})",
470 format_keys(left),
471 format_keys(right)
472 ));
473 }
474 Some(lines.join("\n"))
475 }
476 AdapterError::ReplaceMaterializedViewSealed { .. } => Some(
477 "The materialized view has already computed its output until the end of time, \
478 so replacing its definition would have no effect."
479 .into(),
480 ),
481 AdapterError::ImpossibleTimestampConstraints { constraints } => {
482 Some(format!("Constraints:\n{}", constraints))
483 }
484 _ => None,
485 }
486 }
487
488 pub fn hint(&self) -> Option<String> {
490 match self {
491 AdapterError::AmbiguousSystemColumnReference => Some(
492 "Rewrite the view to refer to all columns by name. Expand all wildcards and \
493 convert all NATURAL JOINs to USING joins."
494 .to_string(),
495 ),
496 AdapterError::Catalog(c) => c.hint(),
497 AdapterError::Eval(e) => e.hint(),
498 AdapterError::InvalidClusterReplicaAz { expected, az: _ } => {
499 Some(if expected.is_empty() {
500 "No availability zones configured; do not specify AVAILABILITY ZONE".into()
501 } else {
502 format!("Valid availability zones are: {}", expected.join(", "))
503 })
504 }
505 AdapterError::InvalidStorageClusterSize { expected, .. } => {
506 Some(format!("Valid sizes are: {}", expected.join(", ")))
507 }
508 AdapterError::SourceOrSinkSizeRequired { expected } => Some(format!(
509 "Try choosing one of the smaller sizes to start. Available sizes: {}",
510 expected.join(", ")
511 )),
512 AdapterError::NoClusterReplicasAvailable { is_managed, .. } => {
513 Some(if *is_managed {
514 "Use ALTER CLUSTER to adjust the replication factor of the cluster. \
515 Example:`ALTER CLUSTER <cluster-name> SET (REPLICATION FACTOR 1)`".into()
516 } else {
517 "Use CREATE CLUSTER REPLICA to attach cluster replicas to the cluster".into()
518 })
519 }
520 AdapterError::UntargetedLogRead { .. } => Some(
521 "Use `SET cluster_replica = <replica-name>` to target a specific replica in the \
522 active cluster. Note that subsequent queries will only be answered by \
523 the selected replica, which might reduce availability. To undo the replica \
524 selection, use `RESET cluster_replica`."
525 .into(),
526 ),
527 AdapterError::ResourceExhaustion { resource_type, .. } => Some(format!(
528 "Drop an existing {resource_type} or contact support to request a limit increase."
529 )),
530 AdapterError::StatementTimeout => Some(
531 "Consider increasing the maximum allowed statement duration for this session by \
532 setting the statement_timeout session variable. For example, `SET \
533 statement_timeout = '120s'`."
534 .into(),
535 ),
536 AdapterError::PlanError(e) => e.hint(),
537 AdapterError::UnallowedOnCluster { cluster, .. } => {
538 (cluster != MZ_CATALOG_SERVER_CLUSTER.name).then(||
539 "Use `SET CLUSTER = <cluster-name>` to change your cluster and re-run the query."
540 .to_string()
541 )
542 }
543 AdapterError::InvalidAlter(_, e) => e.hint(),
544 AdapterError::Optimizer(e) => e.hint(),
545 AdapterError::ConnectionValidation(e) => e.hint(),
546 AdapterError::InputNotReadableAtRefreshAtTime(_, _) => Some(
547 "You can use `REFRESH AT greatest(mz_now(), <explicit timestamp>)` to refresh \
548 either at the explicitly specified timestamp, or now if the given timestamp would \
549 be in the past.".to_string()
550 ),
551 AdapterError::AlterClusterTimeout => Some(
552 "Consider increasing the timeout duration in the alter cluster statement.".into(),
553 ),
554 AdapterError::DDLTransactionRace => Some(
555 "Currently, DDL transactions fail when any other DDL happens concurrently, \
556 even on unrelated schemas/clusters.".into()
557 ),
558 AdapterError::CollectionUnreadable { .. } => Some(
559 "This could be because the collection has recently been dropped.".into()
560 ),
561 _ => None,
562 }
563 }
564
565 pub fn code(&self) -> SqlState {
566 match self {
571 AdapterError::AbsurdSubscribeBounds { .. } => SqlState::DATA_EXCEPTION,
574 AdapterError::AmbiguousSystemColumnReference => SqlState::FEATURE_NOT_SUPPORTED,
575 AdapterError::Catalog(e) => match &e.kind {
576 mz_catalog::memory::error::ErrorKind::VarError(e) => match e {
577 VarError::ConstrainedParameter { .. } => SqlState::INVALID_PARAMETER_VALUE,
578 VarError::FixedValueParameter { .. } => SqlState::INVALID_PARAMETER_VALUE,
579 VarError::InvalidParameterType { .. } => SqlState::INVALID_PARAMETER_VALUE,
580 VarError::InvalidParameterValue { .. } => SqlState::INVALID_PARAMETER_VALUE,
581 VarError::ReadOnlyParameter(_) => SqlState::CANT_CHANGE_RUNTIME_PARAM,
582 VarError::UnknownParameter(_) => SqlState::UNDEFINED_OBJECT,
583 VarError::RequiresUnsafeMode { .. } => SqlState::CANT_CHANGE_RUNTIME_PARAM,
584 VarError::RequiresFeatureFlag { .. } => SqlState::CANT_CHANGE_RUNTIME_PARAM,
585 },
586 _ => SqlState::INTERNAL_ERROR,
587 },
588 AdapterError::ChangedPlan(_) => SqlState::FEATURE_NOT_SUPPORTED,
589 AdapterError::DuplicateCursor(_) => SqlState::DUPLICATE_CURSOR,
590 AdapterError::Eval(EvalError::CharacterNotValidForEncoding(_)) => {
591 SqlState::PROGRAM_LIMIT_EXCEEDED
592 }
593 AdapterError::Eval(EvalError::CharacterTooLargeForEncoding(_)) => {
594 SqlState::PROGRAM_LIMIT_EXCEEDED
595 }
596 AdapterError::Eval(EvalError::LengthTooLarge) => SqlState::PROGRAM_LIMIT_EXCEEDED,
597 AdapterError::Eval(EvalError::NullCharacterNotPermitted) => {
598 SqlState::PROGRAM_LIMIT_EXCEEDED
599 }
600 AdapterError::Eval(_) => SqlState::INTERNAL_ERROR,
601 AdapterError::Explain(_) => SqlState::INTERNAL_ERROR,
602 AdapterError::IdExhaustionError => SqlState::INTERNAL_ERROR,
603 AdapterError::Internal(_) => SqlState::INTERNAL_ERROR,
604 AdapterError::IntrospectionDisabled { .. } => SqlState::FEATURE_NOT_SUPPORTED,
605 AdapterError::InvalidLogDependency { .. } => SqlState::FEATURE_NOT_SUPPORTED,
606 AdapterError::InvalidClusterReplicaAz { .. } => SqlState::FEATURE_NOT_SUPPORTED,
607 AdapterError::InvalidSetIsolationLevel => SqlState::ACTIVE_SQL_TRANSACTION,
608 AdapterError::InvalidSetCluster => SqlState::ACTIVE_SQL_TRANSACTION,
609 AdapterError::InvalidStorageClusterSize { .. } => SqlState::FEATURE_NOT_SUPPORTED,
610 AdapterError::SourceOrSinkSizeRequired { .. } => SqlState::FEATURE_NOT_SUPPORTED,
611 AdapterError::InvalidTableMutationSelection { .. } => {
612 SqlState::INVALID_TRANSACTION_STATE
613 }
614 AdapterError::ConstraintViolation(NotNullViolation(_)) => SqlState::NOT_NULL_VIOLATION,
615 AdapterError::CopyFormatError(_) => SqlState::BAD_COPY_FILE_FORMAT,
616 AdapterError::ConcurrentClusterDrop => SqlState::INVALID_TRANSACTION_STATE,
617 AdapterError::ConcurrentDependencyDrop { .. } => SqlState::UNDEFINED_OBJECT,
618 AdapterError::CollectionUnreadable { .. } => SqlState::NO_DATA_FOUND,
619 AdapterError::NoClusterReplicasAvailable { .. } => SqlState::FEATURE_NOT_SUPPORTED,
620 AdapterError::OperationProhibitsTransaction(_) => SqlState::ACTIVE_SQL_TRANSACTION,
621 AdapterError::OperationRequiresTransaction(_) => SqlState::NO_ACTIVE_SQL_TRANSACTION,
622 AdapterError::ParseError(_) => SqlState::SYNTAX_ERROR,
623 AdapterError::PlanError(PlanError::InvalidSchemaName) => SqlState::INVALID_SCHEMA_NAME,
624 AdapterError::PlanError(PlanError::ColumnAlreadyExists { .. }) => {
625 SqlState::DUPLICATE_COLUMN
626 }
627 AdapterError::PlanError(PlanError::UnknownParameter(_)) => {
628 SqlState::UNDEFINED_PARAMETER
629 }
630 AdapterError::PlanError(PlanError::ParameterNotAllowed(_)) => {
631 SqlState::UNDEFINED_PARAMETER
632 }
633 AdapterError::PlanError(_) => SqlState::INTERNAL_ERROR,
634 AdapterError::PreparedStatementExists(_) => SqlState::DUPLICATE_PSTATEMENT,
635 AdapterError::ReadOnlyTransaction => SqlState::READ_ONLY_SQL_TRANSACTION,
636 AdapterError::ReadWriteUnavailable => SqlState::INVALID_TRANSACTION_STATE,
637 AdapterError::SingleStatementTransaction => SqlState::INVALID_TRANSACTION_STATE,
638 AdapterError::WrongSetOfLocks => SqlState::LOCK_NOT_AVAILABLE,
639 AdapterError::StatementTimeout => SqlState::QUERY_CANCELED,
640 AdapterError::Canceled => SqlState::QUERY_CANCELED,
641 AdapterError::IdleInTransactionSessionTimeout => {
642 SqlState::IDLE_IN_TRANSACTION_SESSION_TIMEOUT
643 }
644 AdapterError::RecursionLimit(_) => SqlState::INTERNAL_ERROR,
645 AdapterError::RelationOutsideTimeDomain { .. } => SqlState::INVALID_TRANSACTION_STATE,
646 AdapterError::ResourceExhaustion { .. } => SqlState::INSUFFICIENT_RESOURCES,
647 AdapterError::ResultSize(_) => SqlState::OUT_OF_MEMORY,
648 AdapterError::SafeModeViolation(_) => SqlState::INTERNAL_ERROR,
649 AdapterError::SubscribeOnlyTransaction => SqlState::INVALID_TRANSACTION_STATE,
650 AdapterError::Optimizer(e) => match e {
651 OptimizerError::PlanError(PlanError::InvalidSchemaName) => {
652 SqlState::INVALID_SCHEMA_NAME
653 }
654 OptimizerError::PlanError(PlanError::ColumnAlreadyExists { .. }) => {
655 SqlState::DUPLICATE_COLUMN
656 }
657 OptimizerError::PlanError(PlanError::UnknownParameter(_)) => {
658 SqlState::UNDEFINED_PARAMETER
659 }
660 OptimizerError::PlanError(PlanError::ParameterNotAllowed(_)) => {
661 SqlState::UNDEFINED_PARAMETER
662 }
663 OptimizerError::PlanError(_) => SqlState::INTERNAL_ERROR,
664 OptimizerError::RecursionLimitError(e) => {
665 AdapterError::RecursionLimit(e.clone()).code() }
667 OptimizerError::Internal(s) => {
668 AdapterError::Internal(s.clone()).code() }
670 OptimizerError::EvalError(e) => {
671 AdapterError::Eval(e.clone()).code() }
673 OptimizerError::TransformError(_) => SqlState::INTERNAL_ERROR,
674 OptimizerError::UnmaterializableFunction(_) => SqlState::FEATURE_NOT_SUPPORTED,
675 OptimizerError::UncallableFunction { .. } => SqlState::FEATURE_NOT_SUPPORTED,
676 OptimizerError::UnsupportedTemporalExpression(_) => SqlState::FEATURE_NOT_SUPPORTED,
677 OptimizerError::RestrictedFunction(_) => SqlState::INSUFFICIENT_PRIVILEGE,
678 OptimizerError::InternalUnsafeMfpPlan(_) => SqlState::INTERNAL_ERROR,
681 },
682 AdapterError::UnallowedOnCluster { .. } => {
683 SqlState::S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED
684 }
685 AdapterError::Unauthorized(_) => SqlState::INSUFFICIENT_PRIVILEGE,
686 AdapterError::UnknownCursor(_) => SqlState::INVALID_CURSOR_NAME,
687 AdapterError::UnknownPreparedStatement(_) => SqlState::UNDEFINED_PSTATEMENT,
688 AdapterError::UnknownLoginRole(_) => SqlState::INVALID_AUTHORIZATION_SPECIFICATION,
689 AdapterError::UnknownClusterReplica { .. } => SqlState::UNDEFINED_OBJECT,
690 AdapterError::UnrecognizedConfigurationParam(_) => SqlState::UNDEFINED_OBJECT,
691 AdapterError::Unsupported(..) => SqlState::FEATURE_NOT_SUPPORTED,
692 AdapterError::UnavailableFeature { .. } => SqlState::FEATURE_NOT_SUPPORTED,
693 AdapterError::Unstructured(_) => SqlState::INTERNAL_ERROR,
694 AdapterError::UntargetedLogRead { .. } => SqlState::FEATURE_NOT_SUPPORTED,
695 AdapterError::DDLTransactionRace => SqlState::T_R_SERIALIZATION_FAILURE,
696 AdapterError::WriteOnlyTransaction => SqlState::INVALID_TRANSACTION_STATE,
701 AdapterError::DDLOnlyTransaction => SqlState::INVALID_TRANSACTION_STATE,
702 AdapterError::Storage(_) | AdapterError::Compute(_) | AdapterError::Orchestrator(_) => {
703 SqlState::INTERNAL_ERROR
704 }
705 AdapterError::DependentObject(_) => SqlState::DEPENDENT_OBJECTS_STILL_EXIST,
706 AdapterError::InvalidAlter(_, _) => SqlState::FEATURE_NOT_SUPPORTED,
707 AdapterError::ConnectionValidation(_) => SqlState::SYSTEM_ERROR,
708 AdapterError::MaterializedViewWouldNeverRefresh(_, _) => SqlState::DATA_EXCEPTION,
710 AdapterError::InputNotReadableAtRefreshAtTime(_, _) => SqlState::DATA_EXCEPTION,
711 AdapterError::RtrTimeout(_) => SqlState::QUERY_CANCELED,
712 AdapterError::RtrDropFailure(_) => SqlState::UNDEFINED_OBJECT,
713 AdapterError::UnreadableSinkCollection => SqlState::from_code("MZ009"),
714 AdapterError::UserSessionsDisallowed => SqlState::from_code("MZ010"),
715 AdapterError::NetworkPolicyDenied(_) => SqlState::from_code("MZ011"),
716 AdapterError::ReadOnly => SqlState::READ_ONLY_SQL_TRANSACTION,
719 AdapterError::AlterClusterTimeout => SqlState::QUERY_CANCELED,
720 AdapterError::AlterClusterWhilePendingReplicas => SqlState::OBJECT_IN_USE,
721 AdapterError::ReplacementSchemaMismatch(_) => SqlState::FEATURE_NOT_SUPPORTED,
722 AdapterError::AuthenticationError(AuthenticationError::InvalidCredentials) => {
723 SqlState::INVALID_PASSWORD
724 }
725 AdapterError::AuthenticationError(_) => SqlState::INVALID_AUTHORIZATION_SPECIFICATION,
726 AdapterError::ReplaceMaterializedViewSealed { .. } => {
727 SqlState::OBJECT_NOT_IN_PREREQUISITE_STATE
728 }
729 AdapterError::ImpossibleTimestampConstraints { .. } => SqlState::DATA_EXCEPTION,
731 AdapterError::OidcGroupSyncFailed(_) => SqlState::INTERNAL_ERROR,
732 }
733 }
734
735 pub fn internal<E: std::fmt::Display>(context: &str, e: E) -> AdapterError {
736 AdapterError::Internal(format!("{context}: {e}"))
737 }
738
739 pub fn concurrent_dependency_drop_from_instance_missing(e: InstanceMissing) -> Self {
746 AdapterError::ConcurrentDependencyDrop {
747 dependency_kind: "cluster",
748 dependency_id: e.0.to_string(),
749 }
750 }
751
752 pub fn concurrent_dependency_drop_from_collection_missing(e: CollectionMissing) -> Self {
753 AdapterError::ConcurrentDependencyDrop {
754 dependency_kind: "collection",
755 dependency_id: e.0.to_string(),
756 }
757 }
758
759 pub fn concurrent_dependency_drop_from_collection_lookup_error(
760 e: CollectionLookupError,
761 compute_instance: ComputeInstanceId,
762 ) -> Self {
763 match e {
764 CollectionLookupError::InstanceMissing(id) => AdapterError::ConcurrentDependencyDrop {
765 dependency_kind: "cluster",
766 dependency_id: id.to_string(),
767 },
768 CollectionLookupError::CollectionMissing(id) => {
769 AdapterError::ConcurrentDependencyDrop {
770 dependency_kind: "collection",
771 dependency_id: id.to_string(),
772 }
773 }
774 CollectionLookupError::InstanceShutDown => AdapterError::ConcurrentDependencyDrop {
775 dependency_kind: "cluster",
776 dependency_id: compute_instance.to_string(),
777 },
778 }
779 }
780
781 pub fn concurrent_dependency_drop_from_watch_set_install_error(
782 e: compute_error::CollectionLookupError,
783 ) -> Self {
784 match e {
785 compute_error::CollectionLookupError::InstanceMissing(id) => {
786 AdapterError::ConcurrentDependencyDrop {
787 dependency_kind: "cluster",
788 dependency_id: id.to_string(),
789 }
790 }
791 compute_error::CollectionLookupError::CollectionMissing(id) => {
792 AdapterError::ConcurrentDependencyDrop {
793 dependency_kind: "collection",
794 dependency_id: id.to_string(),
795 }
796 }
797 }
798 }
799
800 pub fn concurrent_dependency_drop_from_instance_peek_error(
801 e: mz_compute_client::controller::instance_client::PeekError,
802 compute_instance: ComputeInstanceId,
803 ) -> AdapterError {
804 use mz_compute_client::controller::instance_client::PeekError::*;
805 match e {
806 ReplicaMissing(id) => AdapterError::ConcurrentDependencyDrop {
807 dependency_kind: "replica",
808 dependency_id: id.to_string(),
809 },
810 InstanceShutDown => AdapterError::ConcurrentDependencyDrop {
811 dependency_kind: "cluster",
812 dependency_id: compute_instance.to_string(),
813 },
814 e @ ReadHoldIdMismatch(_) => AdapterError::internal("instance peek error", e),
815 e @ ReadHoldInsufficient(_) => AdapterError::internal("instance peek error", e),
816 }
817 }
818
819 pub fn concurrent_dependency_drop_from_collection_update_error(
820 e: compute_error::CollectionUpdateError,
821 ) -> Self {
822 use compute_error::CollectionUpdateError::*;
823 match e {
824 InstanceMissing(id) => AdapterError::ConcurrentDependencyDrop {
825 dependency_kind: "cluster",
826 dependency_id: id.to_string(),
827 },
828 CollectionMissing(id) => AdapterError::ConcurrentDependencyDrop {
829 dependency_kind: "collection",
830 dependency_id: id.to_string(),
831 },
832 }
833 }
834
835 pub fn concurrent_dependency_drop_from_peek_error(
836 e: mz_compute_client::controller::error::PeekError,
837 ) -> AdapterError {
838 use mz_compute_client::controller::error::PeekError::*;
839 match e {
840 InstanceMissing(id) => AdapterError::ConcurrentDependencyDrop {
841 dependency_kind: "cluster",
842 dependency_id: id.to_string(),
843 },
844 CollectionMissing(id) => AdapterError::ConcurrentDependencyDrop {
845 dependency_kind: "collection",
846 dependency_id: id.to_string(),
847 },
848 ReplicaMissing(id) => AdapterError::ConcurrentDependencyDrop {
849 dependency_kind: "replica",
850 dependency_id: id.to_string(),
851 },
852 e @ (ReadHoldIdMismatch(_) | SinceViolation(_)) => {
853 AdapterError::internal("peek error", e)
854 }
855 }
856 }
857
858 pub fn concurrent_dependency_drop_from_dataflow_creation_error(
859 e: compute_error::DataflowCreationError,
860 ) -> Self {
861 use compute_error::DataflowCreationError::*;
862 match e {
863 InstanceMissing(id) => AdapterError::ConcurrentDependencyDrop {
864 dependency_kind: "cluster",
865 dependency_id: id.to_string(),
866 },
867 CollectionMissing(id) => AdapterError::ConcurrentDependencyDrop {
868 dependency_kind: "collection",
869 dependency_id: id.to_string(),
870 },
871 ReplicaMissing(id) => AdapterError::ConcurrentDependencyDrop {
872 dependency_kind: "replica",
873 dependency_id: id.to_string(),
874 },
875 MissingAsOf | SinceViolation(..) | EmptyAsOfForSubscribe | EmptyAsOfForCopyTo => {
876 AdapterError::internal("dataflow creation error", e)
877 }
878 }
879 }
880}
881
882impl fmt::Display for AdapterError {
883 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
884 match self {
885 AdapterError::AbsurdSubscribeBounds { as_of, up_to } => {
886 write!(
887 f,
888 "subscription lower bound (`AS OF`) is greater than its upper bound (`UP TO`): \
889 {as_of} > {up_to}",
890 )
891 }
892 AdapterError::AmbiguousSystemColumnReference => {
893 write!(
894 f,
895 "cannot use wildcard expansions or NATURAL JOINs in a view that depends on \
896 system objects"
897 )
898 }
899 AdapterError::ChangedPlan(e) => write!(f, "{}", e),
900 AdapterError::Catalog(e) => e.fmt(f),
901 AdapterError::DuplicateCursor(name) => {
902 write!(f, "cursor {} already exists", name.quoted())
903 }
904 AdapterError::Eval(e) => e.fmt(f),
905 AdapterError::Explain(e) => e.fmt(f),
906 AdapterError::IdExhaustionError => f.write_str("ID allocator exhausted all valid IDs"),
907 AdapterError::Internal(e) => write!(f, "internal error: {}", e),
908 AdapterError::IntrospectionDisabled { .. } => write!(
909 f,
910 "cannot read log sources of replica with disabled introspection"
911 ),
912 AdapterError::InvalidLogDependency { object_type, .. } => {
913 write!(f, "{object_type} objects cannot depend on log sources")
914 }
915 AdapterError::InvalidClusterReplicaAz { az, expected: _ } => {
916 write!(f, "unknown cluster replica availability zone {az}",)
917 }
918 AdapterError::InvalidSetIsolationLevel => write!(
919 f,
920 "SET TRANSACTION ISOLATION LEVEL must be called before any query"
921 ),
922 AdapterError::InvalidSetCluster => {
923 write!(f, "SET cluster cannot be called in an active transaction")
924 }
925 AdapterError::InvalidStorageClusterSize { size, .. } => {
926 write!(f, "unknown source size {size}")
927 }
928 AdapterError::SourceOrSinkSizeRequired { .. } => {
929 write!(f, "must specify either cluster or size option")
930 }
931 AdapterError::InvalidTableMutationSelection { .. } => {
932 write!(
933 f,
934 "invalid selection: operation may only (transitively) refer to non-source, non-system tables"
935 )
936 }
937 AdapterError::ReplaceMaterializedViewSealed { name } => {
938 write!(
939 f,
940 "materialized view {name} is sealed and thus cannot be replaced"
941 )
942 }
943 AdapterError::ConstraintViolation(not_null_violation) => {
944 write!(f, "{}", not_null_violation)
945 }
946 AdapterError::CopyFormatError(e) => write!(f, "{e}"),
947 AdapterError::ConcurrentClusterDrop => {
948 write!(f, "the transaction's active cluster has been dropped")
949 }
950 AdapterError::ConcurrentDependencyDrop {
951 dependency_kind,
952 dependency_id,
953 } => {
954 write!(f, "{dependency_kind} '{dependency_id}' was dropped")
955 }
956 AdapterError::CollectionUnreadable { id } => {
957 write!(f, "collection '{id}' is not readable at any timestamp")
958 }
959 AdapterError::NoClusterReplicasAvailable { name, .. } => {
960 write!(
961 f,
962 "CLUSTER {} has no replicas available to service request",
963 name.quoted()
964 )
965 }
966 AdapterError::OperationProhibitsTransaction(op) => {
967 write!(f, "{} cannot be run inside a transaction block", op)
968 }
969 AdapterError::OperationRequiresTransaction(op) => {
970 write!(f, "{} can only be used in transaction blocks", op)
971 }
972 AdapterError::ParseError(e) => e.fmt(f),
973 AdapterError::PlanError(e) => e.fmt(f),
974 AdapterError::PreparedStatementExists(name) => {
975 write!(f, "prepared statement {} already exists", name.quoted())
976 }
977 AdapterError::ReadOnlyTransaction => f.write_str("transaction in read-only mode"),
978 AdapterError::SingleStatementTransaction => {
979 f.write_str("this transaction can only execute a single statement")
980 }
981 AdapterError::ReadWriteUnavailable => {
982 f.write_str("transaction read-write mode must be set before any query")
983 }
984 AdapterError::WrongSetOfLocks => {
985 write!(f, "internal error, wrong set of locks acquired")
986 }
987 AdapterError::StatementTimeout => {
988 write!(f, "canceling statement due to statement timeout")
989 }
990 AdapterError::Canceled => {
991 write!(f, "canceling statement due to user request")
992 }
993 AdapterError::IdleInTransactionSessionTimeout => {
994 write!(
995 f,
996 "terminating connection due to idle-in-transaction timeout"
997 )
998 }
999 AdapterError::RecursionLimit(e) => e.fmt(f),
1000 AdapterError::RelationOutsideTimeDomain { .. } => {
1001 write!(
1002 f,
1003 "Transactions can only reference objects in the same timedomain. \
1004 See https://materialize.com/docs/sql/begin/#same-timedomain-error",
1005 )
1006 }
1007 AdapterError::ResourceExhaustion {
1008 resource_type,
1009 limit_name,
1010 desired,
1011 limit,
1012 current,
1013 } => {
1014 write!(
1015 f,
1016 "creating {resource_type} would violate {limit_name} limit (desired: {desired}, limit: {limit}, current: {current})"
1017 )
1018 }
1019 AdapterError::ResultSize(e) => write!(f, "{e}"),
1020 AdapterError::SafeModeViolation(feature) => {
1021 write!(f, "cannot create {} in safe mode", feature)
1022 }
1023 AdapterError::SubscribeOnlyTransaction => {
1024 f.write_str("SUBSCRIBE in transactions must be the only read statement")
1025 }
1026 AdapterError::Optimizer(e) => e.fmt(f),
1027 AdapterError::UnallowedOnCluster {
1028 depends_on,
1029 cluster,
1030 } => {
1031 let items = depends_on.into_iter().map(|item| item.quoted()).join(", ");
1032 write!(
1033 f,
1034 "querying the following items {items} is not allowed from the {} cluster",
1035 cluster.quoted()
1036 )
1037 }
1038 AdapterError::Unauthorized(unauthorized) => {
1039 write!(f, "{unauthorized}")
1040 }
1041 AdapterError::UnknownCursor(name) => {
1042 write!(f, "cursor {} does not exist", name.quoted())
1043 }
1044 AdapterError::UnknownLoginRole(name) => {
1045 write!(f, "role {} does not exist", name.quoted())
1046 }
1047 AdapterError::Unsupported(features) => write!(f, "{} are not supported", features),
1048 AdapterError::Unstructured(e) => write!(f, "{}", e.display_with_causes()),
1049 AdapterError::WriteOnlyTransaction => f.write_str("transaction in write-only mode"),
1050 AdapterError::UnknownPreparedStatement(name) => {
1051 write!(f, "prepared statement {} does not exist", name.quoted())
1052 }
1053 AdapterError::UnknownClusterReplica {
1054 cluster_name,
1055 replica_name,
1056 } => write!(
1057 f,
1058 "cluster replica '{cluster_name}.{replica_name}' does not exist"
1059 ),
1060 AdapterError::UnrecognizedConfigurationParam(setting_name) => write!(
1061 f,
1062 "unrecognized configuration parameter {}",
1063 setting_name.quoted()
1064 ),
1065 AdapterError::UntargetedLogRead { .. } => {
1066 f.write_str("log source reads must target a replica")
1067 }
1068 AdapterError::DDLOnlyTransaction => f.write_str(
1069 "transactions which modify objects are restricted to just modifying objects",
1070 ),
1071 AdapterError::DDLTransactionRace => f.write_str(
1072 "another session modified the catalog while this DDL transaction was open",
1073 ),
1074 AdapterError::Storage(e) => e.fmt(f),
1075 AdapterError::Compute(e) => e.fmt(f),
1076 AdapterError::Orchestrator(e) => e.fmt(f),
1077 AdapterError::DependentObject(dependent_objects) => {
1078 let role_str = if dependent_objects.keys().count() == 1 {
1079 "role"
1080 } else {
1081 "roles"
1082 };
1083 write!(
1084 f,
1085 "{role_str} \"{}\" cannot be dropped because some objects depend on it",
1086 dependent_objects.keys().join(", ")
1087 )
1088 }
1089 AdapterError::InvalidAlter(t, e) => {
1090 write!(f, "invalid ALTER {t}: {e}")
1091 }
1092 AdapterError::ConnectionValidation(e) => e.fmt(f),
1093 AdapterError::MaterializedViewWouldNeverRefresh(_, _) => {
1094 write!(
1095 f,
1096 "all the specified refreshes of the materialized view would be too far in the past, and thus they \
1097 would never happen"
1098 )
1099 }
1100 AdapterError::InputNotReadableAtRefreshAtTime(_, _) => {
1101 write!(
1102 f,
1103 "REFRESH AT requested for a time where not all the inputs are readable"
1104 )
1105 }
1106 AdapterError::RtrTimeout(_) => {
1107 write!(
1108 f,
1109 "timed out before ingesting the source's visible frontier when real-time-recency query issued"
1110 )
1111 }
1112 AdapterError::RtrDropFailure(_) => write!(
1113 f,
1114 "real-time source dropped before ingesting the upstream system's visible frontier"
1115 ),
1116 AdapterError::UnreadableSinkCollection => {
1117 write!(f, "collection is not readable at any time")
1118 }
1119 AdapterError::UserSessionsDisallowed => write!(f, "login blocked"),
1120 AdapterError::NetworkPolicyDenied(_) => write!(f, "session denied"),
1121 AdapterError::ReadOnly => write!(f, "cannot write in read-only mode"),
1122 AdapterError::AlterClusterTimeout => {
1123 write!(f, "canceling statement, provided timeout lapsed")
1124 }
1125 AdapterError::AuthenticationError(e) => {
1126 write!(f, "authentication error {e}")
1127 }
1128 AdapterError::UnavailableFeature { feature, docs } => {
1129 write!(f, "{} is not supported in this environment.", feature)?;
1130 if let Some(docs) = docs {
1131 write!(
1132 f,
1133 " For more information consult the documentation at {docs}"
1134 )?;
1135 }
1136 Ok(())
1137 }
1138 AdapterError::AlterClusterWhilePendingReplicas => {
1139 write!(f, "cannot alter clusters with pending updates")
1140 }
1141 AdapterError::ReplacementSchemaMismatch(_) => {
1142 write!(f, "replacement schema differs from target schema")
1143 }
1144 AdapterError::ImpossibleTimestampConstraints { .. } => {
1145 write!(f, "could not find a valid timestamp for the query")
1146 }
1147 AdapterError::OidcGroupSyncFailed(msg) => {
1148 write!(f, "OIDC group-to-role sync failed: {msg}")
1149 }
1150 }
1151 }
1152}
1153
1154impl From<anyhow::Error> for AdapterError {
1155 fn from(e: anyhow::Error) -> AdapterError {
1156 match e.downcast::<PlanError>() {
1157 Ok(plan_error) => AdapterError::PlanError(plan_error),
1158 Err(e) => AdapterError::Unstructured(e),
1159 }
1160 }
1161}
1162
1163impl From<TryFromIntError> for AdapterError {
1164 fn from(e: TryFromIntError) -> AdapterError {
1165 AdapterError::Unstructured(e.into())
1166 }
1167}
1168
1169impl From<TryFromDecimalError> for AdapterError {
1170 fn from(e: TryFromDecimalError) -> AdapterError {
1171 AdapterError::Unstructured(e.into())
1172 }
1173}
1174
1175impl From<mz_catalog::memory::error::Error> for AdapterError {
1176 fn from(e: mz_catalog::memory::error::Error) -> AdapterError {
1177 AdapterError::Catalog(e)
1178 }
1179}
1180
1181impl From<mz_catalog::durable::CatalogError> for AdapterError {
1182 fn from(e: mz_catalog::durable::CatalogError) -> Self {
1183 mz_catalog::memory::error::Error::from(e).into()
1184 }
1185}
1186
1187impl From<mz_catalog::durable::DurableCatalogError> for AdapterError {
1188 fn from(e: mz_catalog::durable::DurableCatalogError) -> Self {
1189 mz_catalog::durable::CatalogError::from(e).into()
1190 }
1191}
1192
1193impl From<EvalError> for AdapterError {
1194 fn from(e: EvalError) -> AdapterError {
1195 AdapterError::Eval(e)
1196 }
1197}
1198
1199impl From<ExplainError> for AdapterError {
1200 fn from(e: ExplainError) -> AdapterError {
1201 match e {
1202 ExplainError::RecursionLimitError(e) => AdapterError::RecursionLimit(e),
1203 e => AdapterError::Explain(e),
1204 }
1205 }
1206}
1207
1208impl From<mz_sql::catalog::CatalogError> for AdapterError {
1209 fn from(e: mz_sql::catalog::CatalogError) -> AdapterError {
1210 AdapterError::Catalog(mz_catalog::memory::error::Error::from(e))
1211 }
1212}
1213
1214impl From<PlanError> for AdapterError {
1215 fn from(e: PlanError) -> AdapterError {
1216 match e {
1217 PlanError::UnknownCursor(name) => AdapterError::UnknownCursor(name),
1218 _ => AdapterError::PlanError(e),
1219 }
1220 }
1221}
1222
1223impl From<OptimizerError> for AdapterError {
1224 fn from(e: OptimizerError) -> AdapterError {
1225 use OptimizerError::*;
1226 match e {
1227 PlanError(e) => Self::PlanError(e),
1228 RecursionLimitError(e) => Self::RecursionLimit(e),
1229 EvalError(e) => Self::Eval(e),
1230 InternalUnsafeMfpPlan(e) => Self::Internal(e),
1231 Internal(e) => Self::Internal(e),
1232 RestrictedFunction(func) => {
1233 Self::Unauthorized(mz_sql::rbac::UnauthorizedError::RestrictedSystemObject {
1234 object_name: format!("function {func}"),
1235 })
1236 }
1237 e => Self::Optimizer(e),
1238 }
1239 }
1240}
1241
1242impl From<NotNullViolation> for AdapterError {
1243 fn from(e: NotNullViolation) -> AdapterError {
1244 AdapterError::ConstraintViolation(e)
1245 }
1246}
1247
1248impl From<RecursionLimitError> for AdapterError {
1249 fn from(e: RecursionLimitError) -> AdapterError {
1250 AdapterError::RecursionLimit(e)
1251 }
1252}
1253
1254impl From<oneshot::error::RecvError> for AdapterError {
1255 fn from(e: oneshot::error::RecvError) -> AdapterError {
1256 AdapterError::Unstructured(e.into())
1257 }
1258}
1259
1260impl From<StorageError> for AdapterError {
1261 fn from(e: StorageError) -> Self {
1262 AdapterError::Storage(e)
1263 }
1264}
1265
1266impl From<compute_error::InstanceExists> for AdapterError {
1267 fn from(e: compute_error::InstanceExists) -> Self {
1268 AdapterError::Compute(e.into())
1269 }
1270}
1271
1272impl From<TimestampError> for AdapterError {
1273 fn from(e: TimestampError) -> Self {
1274 let e: EvalError = e.into();
1275 e.into()
1276 }
1277}
1278
1279impl From<mz_sql_parser::parser::ParserStatementError> for AdapterError {
1280 fn from(e: mz_sql_parser::parser::ParserStatementError) -> Self {
1281 AdapterError::ParseError(e)
1282 }
1283}
1284
1285impl From<VarError> for AdapterError {
1286 fn from(e: VarError) -> Self {
1287 let e: mz_catalog::memory::error::Error = e.into();
1288 e.into()
1289 }
1290}
1291
1292impl From<rbac::UnauthorizedError> for AdapterError {
1293 fn from(e: rbac::UnauthorizedError) -> Self {
1294 AdapterError::Unauthorized(e)
1295 }
1296}
1297
1298impl From<mz_sql_parser::ast::IdentError> for AdapterError {
1299 fn from(value: mz_sql_parser::ast::IdentError) -> Self {
1300 AdapterError::PlanError(PlanError::InvalidIdent(value))
1301 }
1302}
1303
1304impl From<mz_pgwire_common::ConnectionError> for AdapterError {
1305 fn from(value: mz_pgwire_common::ConnectionError) -> Self {
1306 match value {
1307 mz_pgwire_common::ConnectionError::TooManyConnections { current, limit } => {
1308 AdapterError::ResourceExhaustion {
1309 resource_type: "connection".into(),
1310 limit_name: "max_connections".into(),
1311 desired: (current + 1).to_string(),
1312 limit: limit.to_string(),
1313 current: current.to_string(),
1314 }
1315 }
1316 }
1317 }
1318}
1319
1320impl From<NetworkPolicyError> for AdapterError {
1321 fn from(value: NetworkPolicyError) -> Self {
1322 AdapterError::NetworkPolicyDenied(value)
1323 }
1324}
1325
1326impl From<ConnectionValidationError> for AdapterError {
1327 fn from(e: ConnectionValidationError) -> AdapterError {
1328 AdapterError::ConnectionValidation(e)
1329 }
1330}
1331
1332impl Error for AdapterError {}