1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
// Copyright Materialize, Inc. and contributors. All rights reserved.
//
// Use of this software is governed by the Business Source License
// included in the LICENSE file.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0.

use std::collections::BTreeMap;
use std::error::Error;
use std::fmt;
use std::num::TryFromIntError;

use crate::CollectionIdBundle;
use dec::TryFromDecimalError;
use itertools::Itertools;
use mz_catalog::builtin::MZ_INTROSPECTION_CLUSTER;
use mz_compute_client::controller::error as compute_error;
use mz_expr::EvalError;
use mz_ore::error::ErrorExt;
use mz_ore::stack::RecursionLimitError;
use mz_ore::str::StrExt;
use mz_pgwire_common::{ErrorResponse, Severity};
use mz_repr::adt::timestamp::TimestampError;
use mz_repr::explain::ExplainError;
use mz_repr::{NotNullViolation, Timestamp};
use mz_sql::plan::PlanError;
use mz_sql::rbac;
use mz_sql::session::vars::VarError;
use mz_storage_types::connections::ConnectionValidationError;
use mz_storage_types::controller::StorageError;
use smallvec::SmallVec;
use timely::progress::Antichain;
use tokio::sync::oneshot;
use tokio_postgres::error::SqlState;

use crate::optimize::OptimizerError;

/// Errors that can occur in the coordinator.
#[derive(Debug)]
pub enum AdapterError {
    /// A `SUBSCRIBE` was requested whose `UP TO` bound precedes its `as_of` timestamp
    AbsurdSubscribeBounds {
        as_of: mz_repr::Timestamp,
        up_to: mz_repr::Timestamp,
    },
    /// Attempted to use a potentially ambiguous column reference expression with a system table.
    // We don't allow this until https://github.com/MaterializeInc/materialize/issues/16650 is
    // resolved because it prevents us from adding columns to system tables.
    AmbiguousSystemColumnReference,
    /// An error occurred in a catalog operation.
    Catalog(mz_catalog::memory::error::Error),
    /// The cached plan or descriptor changed.
    ChangedPlan(String),
    /// The cursor already exists.
    DuplicateCursor(String),
    /// An error while evaluating an expression.
    Eval(EvalError),
    /// An error occurred while planning the statement.
    Explain(ExplainError),
    /// The ID allocator exhausted all valid IDs.
    IdExhaustionError,
    /// Unexpected internal state was encountered.
    Internal(String),
    /// Attempted to read from log sources of a replica with disabled introspection.
    IntrospectionDisabled {
        log_names: Vec<String>,
    },
    /// Attempted to create an object dependent on log sources that doesn't support
    /// log dependencies.
    InvalidLogDependency {
        object_type: String,
        log_names: Vec<String>,
    },
    /// No such cluster replica size has been configured.
    InvalidClusterReplicaAz {
        az: String,
        expected: Vec<String>,
    },
    /// SET TRANSACTION ISOLATION LEVEL was called in the middle of a transaction.
    InvalidSetIsolationLevel,
    /// SET cluster was called in the middle of a transaction.
    InvalidSetCluster,
    /// No such storage instance size has been configured.
    InvalidStorageClusterSize {
        size: String,
        expected: Vec<String>,
    },
    /// Creating a source or sink without specifying its size is forbidden.
    SourceOrSinkSizeRequired {
        expected: Vec<String>,
    },
    /// The selection value for a table mutation operation refers to an invalid object.
    InvalidTableMutationSelection,
    /// Expression violated a column's constraint
    ConstraintViolation(NotNullViolation),
    /// Transaction cluster was dropped in the middle of a transaction.
    ConcurrentClusterDrop,
    /// Target cluster has no replicas to service query.
    NoClusterReplicasAvailable(String),
    /// The named operation cannot be run in a transaction.
    OperationProhibitsTransaction(String),
    /// The named operation requires an active transaction.
    OperationRequiresTransaction(String),
    /// An error occurred while planning the statement.
    PlanError(PlanError),
    /// The named prepared statement already exists.
    PreparedStatementExists(String),
    /// Wrapper around parsing error
    ParseError(mz_sql_parser::parser::ParserStatementError),
    /// The transaction is in read-only mode.
    ReadOnlyTransaction,
    /// The transaction in in read-only mode and a read already occurred.
    ReadWriteUnavailable,
    /// The recursion limit of some operation was exceeded.
    RecursionLimit(RecursionLimitError),
    /// A query in a transaction referenced a relation outside the first query's
    /// time domain.
    RelationOutsideTimeDomain {
        relations: Vec<String>,
        names: Vec<String>,
    },
    /// A query tried to create more resources than is allowed in the system configuration.
    ResourceExhaustion {
        resource_type: String,
        limit_name: String,
        desired: String,
        limit: String,
        current: String,
    },
    /// Result size of a query is too large.
    ResultSize(String),
    /// The specified feature is not permitted in safe mode.
    SafeModeViolation(String),
    /// Waiting on a query timed out.
    ///
    /// Note this differs slightly from PG's implementation/semantics.
    StatementTimeout,
    /// The user canceled the query
    Canceled,
    /// An idle session in a transaction has timed out.
    IdleInTransactionSessionTimeout,
    /// The transaction is in single-subscribe mode.
    SubscribeOnlyTransaction,
    /// An error occurred in the the optimizer.
    Optimizer(OptimizerError),
    /// A query depends on items which are not allowed to be referenced from the current cluster.
    UnallowedOnCluster {
        depends_on: SmallVec<[String; 2]>,
        cluster: String,
    },
    /// A user tried to perform an action that they were unauthorized to do.
    Unauthorized(rbac::UnauthorizedError),
    /// The named cursor does not exist.
    UnknownCursor(String),
    /// The named role does not exist.
    UnknownLoginRole(String),
    UnknownPreparedStatement(String),
    /// The named cluster replica does not exist.
    UnknownClusterReplica {
        cluster_name: String,
        replica_name: String,
    },
    /// The named setting does not exist.
    UnrecognizedConfigurationParam(String),
    /// A generic error occurred.
    //
    // TODO(benesch): convert all those errors to structured errors.
    Unstructured(anyhow::Error),
    /// The named feature is not supported and will (probably) not be.
    Unsupported(&'static str),
    /// Attempted to read from log sources without selecting a target replica.
    UntargetedLogRead {
        log_names: Vec<String>,
    },
    /// The transaction is in write-only mode.
    WriteOnlyTransaction,
    /// The transaction only supports single table writes
    MultiTableWriteTransaction,
    /// The transaction can only execute a single statement.
    SingleStatementTransaction,
    /// The transaction can only execute simple DDL.
    DDLOnlyTransaction,
    /// Another session modified the Catalog while this transaction was open.
    DDLTransactionRace,
    /// Used to prevent us from durably committing state while a DDL transaction is open, should
    /// never be returned to the user.
    TransactionDryRun {
        /// New operations that were run in the transaction.
        new_ops: Vec<crate::catalog::Op>,
        /// New resulting `CatalogState`.
        new_state: crate::catalog::CatalogState,
    },
    /// An error occurred in the storage layer
    Storage(mz_storage_types::controller::StorageError<mz_repr::Timestamp>),
    /// An error occurred in the compute layer
    Compute(anyhow::Error),
    /// An error in the orchestrator layer
    Orchestrator(anyhow::Error),
    /// A statement tried to drop a role that had dependent objects.
    ///
    /// The map keys are role names and values are detailed error messages.
    DependentObject(BTreeMap<String, Vec<String>>),
    /// When performing an `ALTER` of some variety, re-planning the statement
    /// errored.
    InvalidAlter(&'static str, PlanError),
    /// An error occurred while validating a connection.
    ConnectionValidation(ConnectionValidationError),
    /// We refuse to create the materialized view, because it would never be refreshed, so it would
    /// never be queryable. This can happen when the only specified refreshes are further back in
    /// the past than the initial compaction window of the materialized view.
    MaterializedViewWouldNeverRefresh(Timestamp, Timestamp),
    /// A CREATE MATERIALIZED VIEW statement tried to acquire a read hold at a REFRESH AT time,
    /// but was unable to get a precise read hold.
    InputNotReadableAtRefreshAtTime(Timestamp, Vec<(Antichain<Timestamp>, CollectionIdBundle)>),
}

impl AdapterError {
    pub fn into_response(self, severity: Severity) -> ErrorResponse {
        ErrorResponse {
            severity,
            code: self.code(),
            message: self.to_string(),
            detail: self.detail(),
            hint: self.hint(),
            position: self.position(),
        }
    }

    pub fn position(&self) -> Option<usize> {
        match self {
            AdapterError::ParseError(err) => Some(err.error.pos),
            _ => None,
        }
    }

    /// Reports additional details about the error, if any are available.
    pub fn detail(&self) -> Option<String> {
        match self {
            AdapterError::AmbiguousSystemColumnReference => {
                Some("This is a limitation in Materialize that will be lifted in a future release. \
                See https://github.com/MaterializeInc/materialize/issues/16650 for details.".to_string())
            },
            AdapterError::Catalog(c) => c.detail(),
            AdapterError::Eval(e) => e.detail(),
            AdapterError::RelationOutsideTimeDomain { relations, names } => Some(format!(
                "The following relations in the query are outside the transaction's time domain:\n{}\n{}",
                relations
                    .iter()
                    .map(|r| r.quoted().to_string())
                    .collect::<Vec<_>>()
                    .join("\n"),
                match names.is_empty() {
                    true => "No relations are available.".to_string(),
                    false => format!(
                        "Only the following relations are available:\n{}",
                        names
                            .iter()
                            .map(|name| name.quoted().to_string())
                            .collect::<Vec<_>>()
                            .join("\n")
                    ),
                }
            )),
            AdapterError::SourceOrSinkSizeRequired { .. } => Some(
                "Either specify the cluster that will maintain this object via IN CLUSTER or \
                specify size via SIZE option."
                    .into(),
            ),
            AdapterError::SafeModeViolation(_) => Some(
                "The Materialize server you are connected to is running in \
                 safe mode, which limits the features that are available."
                    .into(),
            ),
            AdapterError::IntrospectionDisabled { log_names }
            | AdapterError::UntargetedLogRead { log_names } => Some(format!(
                "The query references the following log sources:\n    {}",
                log_names.join("\n    "),
            )),
            AdapterError::InvalidLogDependency { log_names, .. } => Some(format!(
                "The object depends on the following log sources:\n    {}",
                log_names.join("\n    "),
            )),
            AdapterError::PlanError(e) => e.detail(),
            AdapterError::Unauthorized(unauthorized) => unauthorized.detail(),
            AdapterError::DependentObject(dependent_objects) => {
                Some(dependent_objects
                    .iter()
                    .map(|(role_name, err_msgs)| err_msgs
                        .iter()
                        .map(|err_msg| format!("{role_name}: {err_msg}"))
                        .join("\n"))
                    .join("\n"))
            },
            AdapterError::Storage(storage_error) => {
                storage_error.source().map(|source_error| source_error.to_string_with_causes())
            }
            AdapterError::ReadOnlyTransaction => Some("SELECT queries cannot be combined with other query types, including SUBSCRIBE.".into()),
            AdapterError::InvalidAlter(_, e) => e.detail(),
            AdapterError::Optimizer(e) => e.detail(),
            AdapterError::ConnectionValidation(e) => e.detail(),
            AdapterError::MaterializedViewWouldNeverRefresh(last_refresh, earliest_possible) => {
                Some(format!(
                    "The specified last refresh is at {}, while the earliest possible time to compute the materialized \
                    view is {}.",
                    last_refresh,
                    earliest_possible,
                ))
            }
            AdapterError::UnallowedOnCluster { cluster, .. } => (cluster == MZ_INTROSPECTION_CLUSTER.name).then(||
                format!("The transaction is executing on the {cluster} cluster, maybe having been routed there by the first statement in the transaction.")
            ),
            AdapterError::InputNotReadableAtRefreshAtTime(oracle_read_ts, earliest_possible) => {
                Some(format!(
                    "The requested REFRESH AT time is {}, \
                    while the following input collections are readable at no earlier than the following times: [{}].",
                    oracle_read_ts,
                    earliest_possible.iter().map(|(antichain, id_bundle)|
                        format!(
                            "[{}]: {}",
                            id_bundle.iter().map(|id| format!("{}", id)).join(", "),
                            if antichain.len() == 1 {
                                format!("{}", antichain.as_option().expect("antichain contains exactly 1 timestamp"))
                            } else {
                                // This can't occur currently
                                format!("{:?}", antichain)
                            }
                        )
                    ).join("; "),
                ))
            }
            _ => None,
        }
    }

    /// Reports a hint for the user about how the error could be fixed.
    pub fn hint(&self) -> Option<String> {
        match self {
            AdapterError::AmbiguousSystemColumnReference => Some(
                "Rewrite the view to refer to all columns by name. Expand all wildcards and \
                convert all NATURAL JOINs to USING joins."
                    .to_string(),
            ),
            AdapterError::Catalog(c) => c.hint(),
            AdapterError::Eval(e) => e.hint(),
            AdapterError::InvalidClusterReplicaAz { expected, az: _ } => {
                Some(if expected.is_empty() {
                    "No availability zones configured; do not specify AVAILABILITY ZONE".into()
                } else {
                    format!("Valid availability zones are: {}", expected.join(", "))
                })
            }
            AdapterError::InvalidStorageClusterSize { expected, .. } => {
                Some(format!("Valid sizes are: {}", expected.join(", ")))
            }
            AdapterError::SourceOrSinkSizeRequired { expected } => Some(format!(
                "Try choosing one of the smaller sizes to start. Available sizes: {}",
                expected.join(", ")
            )),
            AdapterError::NoClusterReplicasAvailable(_) => {
                Some("You can create cluster replicas using CREATE CLUSTER REPLICA".into())
            }
            AdapterError::UntargetedLogRead { .. } => Some(
                "Use `SET cluster_replica = <replica-name>` to target a specific replica in the \
                 active cluster. Note that subsequent queries will only be answered by \
                 the selected replica, which might reduce availability. To undo the replica \
                 selection, use `RESET cluster_replica`."
                    .into(),
            ),
            AdapterError::ResourceExhaustion { resource_type, .. } => Some(format!(
                "Drop an existing {resource_type} or contact support to request a limit increase."
            )),
            AdapterError::StatementTimeout => Some(
                "Consider increasing the maximum allowed statement duration for this session by \
                 setting the statement_timeout session variable. For example, `SET \
                 statement_timeout = '60s'`."
                    .into(),
            ),
            AdapterError::PlanError(e) => e.hint(),
            AdapterError::UnallowedOnCluster { cluster, .. } => {
                (cluster != MZ_INTROSPECTION_CLUSTER.name).then(||
                    "Use `SET CLUSTER = <cluster-name>` to change your cluster and re-run the query."
                    .to_string()
                )
            }
            AdapterError::InvalidAlter(_, e) => e.hint(),
            AdapterError::Optimizer(e) => e.hint(),
            AdapterError::ConnectionValidation(e) => e.hint(),
            _ => None,
        }
    }

    pub fn code(&self) -> SqlState {
        // TODO(benesch): we should only use `SqlState::INTERNAL_ERROR` for
        // those errors that are truly internal errors. At the moment we have
        // a various classes of uncategorized errors that use this error code
        // inappropriately.
        match self {
            // DATA_EXCEPTION to match what Postgres returns for degenerate
            // range bounds
            AdapterError::AbsurdSubscribeBounds { .. } => SqlState::DATA_EXCEPTION,
            AdapterError::AmbiguousSystemColumnReference => SqlState::FEATURE_NOT_SUPPORTED,
            AdapterError::Catalog(e) => match &e.kind {
                mz_catalog::memory::error::ErrorKind::VarError(e) => match e {
                    VarError::ConstrainedParameter { .. } => SqlState::INVALID_PARAMETER_VALUE,
                    VarError::FixedValueParameter { .. } => SqlState::INVALID_PARAMETER_VALUE,
                    VarError::InvalidParameterType { .. } => SqlState::INVALID_PARAMETER_VALUE,
                    VarError::InvalidParameterValue { .. } => SqlState::INVALID_PARAMETER_VALUE,
                    VarError::ReadOnlyParameter(_) => SqlState::CANT_CHANGE_RUNTIME_PARAM,
                    VarError::UnknownParameter(_) => SqlState::UNDEFINED_OBJECT,
                    VarError::RequiresUnsafeMode { .. } => SqlState::CANT_CHANGE_RUNTIME_PARAM,
                    VarError::RequiresFeatureFlag { .. } => SqlState::CANT_CHANGE_RUNTIME_PARAM,
                },
                _ => SqlState::INTERNAL_ERROR,
            },
            AdapterError::ChangedPlan(_) => SqlState::FEATURE_NOT_SUPPORTED,
            AdapterError::DuplicateCursor(_) => SqlState::DUPLICATE_CURSOR,
            AdapterError::Eval(EvalError::CharacterNotValidForEncoding(_)) => {
                SqlState::PROGRAM_LIMIT_EXCEEDED
            }
            AdapterError::Eval(EvalError::CharacterTooLargeForEncoding(_)) => {
                SqlState::PROGRAM_LIMIT_EXCEEDED
            }
            AdapterError::Eval(EvalError::LengthTooLarge) => SqlState::PROGRAM_LIMIT_EXCEEDED,
            AdapterError::Eval(EvalError::NullCharacterNotPermitted) => {
                SqlState::PROGRAM_LIMIT_EXCEEDED
            }
            AdapterError::Eval(_) => SqlState::INTERNAL_ERROR,
            AdapterError::Explain(_) => SqlState::INTERNAL_ERROR,
            AdapterError::IdExhaustionError => SqlState::INTERNAL_ERROR,
            AdapterError::Internal(_) => SqlState::INTERNAL_ERROR,
            AdapterError::IntrospectionDisabled { .. } => SqlState::FEATURE_NOT_SUPPORTED,
            AdapterError::InvalidLogDependency { .. } => SqlState::FEATURE_NOT_SUPPORTED,
            AdapterError::InvalidClusterReplicaAz { .. } => SqlState::FEATURE_NOT_SUPPORTED,
            AdapterError::InvalidSetIsolationLevel => SqlState::ACTIVE_SQL_TRANSACTION,
            AdapterError::InvalidSetCluster => SqlState::ACTIVE_SQL_TRANSACTION,
            AdapterError::InvalidStorageClusterSize { .. } => SqlState::FEATURE_NOT_SUPPORTED,
            AdapterError::SourceOrSinkSizeRequired { .. } => SqlState::FEATURE_NOT_SUPPORTED,
            AdapterError::InvalidTableMutationSelection => SqlState::INVALID_TRANSACTION_STATE,
            AdapterError::ConstraintViolation(NotNullViolation(_)) => SqlState::NOT_NULL_VIOLATION,
            AdapterError::ConcurrentClusterDrop => SqlState::INVALID_TRANSACTION_STATE,
            AdapterError::NoClusterReplicasAvailable(_) => SqlState::FEATURE_NOT_SUPPORTED,
            AdapterError::OperationProhibitsTransaction(_) => SqlState::ACTIVE_SQL_TRANSACTION,
            AdapterError::OperationRequiresTransaction(_) => SqlState::NO_ACTIVE_SQL_TRANSACTION,
            AdapterError::ParseError(_) => SqlState::SYNTAX_ERROR,
            AdapterError::PlanError(PlanError::InvalidSchemaName) => SqlState::INVALID_SCHEMA_NAME,
            AdapterError::PlanError(_) => SqlState::INTERNAL_ERROR,
            AdapterError::PreparedStatementExists(_) => SqlState::DUPLICATE_PSTATEMENT,
            AdapterError::ReadOnlyTransaction => SqlState::READ_ONLY_SQL_TRANSACTION,
            AdapterError::ReadWriteUnavailable => SqlState::INVALID_TRANSACTION_STATE,
            AdapterError::SingleStatementTransaction => SqlState::INVALID_TRANSACTION_STATE,
            AdapterError::StatementTimeout => SqlState::QUERY_CANCELED,
            AdapterError::Canceled => SqlState::QUERY_CANCELED,
            AdapterError::IdleInTransactionSessionTimeout => {
                SqlState::IDLE_IN_TRANSACTION_SESSION_TIMEOUT
            }
            AdapterError::RecursionLimit(_) => SqlState::INTERNAL_ERROR,
            AdapterError::RelationOutsideTimeDomain { .. } => SqlState::INVALID_TRANSACTION_STATE,
            AdapterError::ResourceExhaustion { .. } => SqlState::INSUFFICIENT_RESOURCES,
            AdapterError::ResultSize(_) => SqlState::OUT_OF_MEMORY,
            AdapterError::SafeModeViolation(_) => SqlState::INTERNAL_ERROR,
            AdapterError::SubscribeOnlyTransaction => SqlState::INVALID_TRANSACTION_STATE,
            AdapterError::Optimizer(e) => match e {
                OptimizerError::PlanError(e) => {
                    AdapterError::PlanError(e.clone()).code() // Delegate to outer
                }
                OptimizerError::RecursionLimitError(e) => {
                    AdapterError::RecursionLimit(e.clone()).code() // Delegate to outer
                }
                OptimizerError::Internal(s) => {
                    AdapterError::Internal(s.clone()).code() // Delegate to outer
                }
                OptimizerError::EvalError(e) => {
                    AdapterError::Eval(e.clone()).code() // Delegate to outer
                }
                OptimizerError::TransformError(_) => SqlState::INTERNAL_ERROR,
                OptimizerError::UnmaterializableFunction(_) => SqlState::FEATURE_NOT_SUPPORTED,
                OptimizerError::UncallableFunction { .. } => SqlState::FEATURE_NOT_SUPPORTED,
            },
            AdapterError::UnallowedOnCluster { .. } => {
                SqlState::S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED
            }
            AdapterError::Unauthorized(_) => SqlState::INSUFFICIENT_PRIVILEGE,
            AdapterError::UnknownCursor(_) => SqlState::INVALID_CURSOR_NAME,
            AdapterError::UnknownPreparedStatement(_) => SqlState::UNDEFINED_PSTATEMENT,
            AdapterError::UnknownLoginRole(_) => SqlState::INVALID_AUTHORIZATION_SPECIFICATION,
            AdapterError::UnknownClusterReplica { .. } => SqlState::UNDEFINED_OBJECT,
            AdapterError::UnrecognizedConfigurationParam(_) => SqlState::UNDEFINED_OBJECT,
            AdapterError::Unsupported(..) => SqlState::FEATURE_NOT_SUPPORTED,
            AdapterError::Unstructured(_) => SqlState::INTERNAL_ERROR,
            AdapterError::UntargetedLogRead { .. } => SqlState::FEATURE_NOT_SUPPORTED,
            AdapterError::DDLTransactionRace => SqlState::T_R_SERIALIZATION_FAILURE,
            AdapterError::TransactionDryRun { .. } => SqlState::T_R_SERIALIZATION_FAILURE,
            // It's not immediately clear which error code to use here because a
            // "write-only transaction", "single table write transaction", or "ddl only
            // transaction" are not things in Postgres. This error code is the generic "bad txn
            // thing" code, so it's probably the best choice.
            AdapterError::WriteOnlyTransaction => SqlState::INVALID_TRANSACTION_STATE,
            AdapterError::MultiTableWriteTransaction => SqlState::INVALID_TRANSACTION_STATE,
            AdapterError::DDLOnlyTransaction => SqlState::INVALID_TRANSACTION_STATE,
            AdapterError::Storage(_) | AdapterError::Compute(_) | AdapterError::Orchestrator(_) => {
                SqlState::INTERNAL_ERROR
            }
            AdapterError::DependentObject(_) => SqlState::DEPENDENT_OBJECTS_STILL_EXIST,
            AdapterError::InvalidAlter(_, _) => SqlState::FEATURE_NOT_SUPPORTED,
            AdapterError::ConnectionValidation(_) => SqlState::SYSTEM_ERROR,
            // `DATA_EXCEPTION`, similarly to `AbsurdSubscribeBounds`.
            AdapterError::MaterializedViewWouldNeverRefresh(_, _) => SqlState::DATA_EXCEPTION,
            AdapterError::InputNotReadableAtRefreshAtTime(_, _) => SqlState::DATA_EXCEPTION,
        }
    }

    pub fn internal<E: std::fmt::Display>(context: &str, e: E) -> AdapterError {
        AdapterError::Internal(format!("{context}: {e}"))
    }
}

impl fmt::Display for AdapterError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            AdapterError::AbsurdSubscribeBounds { as_of, up_to } => {
                assert!(up_to < as_of);
                write!(
                    f,
                    r#"subscription lower ("as of") bound is beyond its upper ("up to") bound: {} < {}"#,
                    up_to, as_of
                )
            }
            AdapterError::AmbiguousSystemColumnReference => {
                write!(
                    f,
                    "cannot use wildcard expansions or NATURAL JOINs in a view that depends on \
                    system objects"
                )
            }
            AdapterError::ChangedPlan(e) => write!(f, "{}", e),
            AdapterError::Catalog(e) => e.fmt(f),
            AdapterError::DuplicateCursor(name) => {
                write!(f, "cursor {} already exists", name.quoted())
            }
            AdapterError::Eval(e) => e.fmt(f),
            AdapterError::Explain(e) => e.fmt(f),
            AdapterError::IdExhaustionError => f.write_str("ID allocator exhausted all valid IDs"),
            AdapterError::Internal(e) => write!(f, "internal error: {}", e),
            AdapterError::IntrospectionDisabled { .. } => write!(
                f,
                "cannot read log sources of replica with disabled introspection"
            ),
            AdapterError::InvalidLogDependency { object_type, .. } => {
                write!(f, "{object_type} objects cannot depend on log sources")
            }
            AdapterError::InvalidClusterReplicaAz { az, expected: _ } => {
                write!(f, "unknown cluster replica availability zone {az}",)
            }
            AdapterError::InvalidSetIsolationLevel => write!(
                f,
                "SET TRANSACTION ISOLATION LEVEL must be called before any query"
            ),
            AdapterError::InvalidSetCluster => {
                write!(f, "SET cluster cannot be called in an active transaction")
            }
            AdapterError::InvalidStorageClusterSize { size, .. } => {
                write!(f, "unknown source size {size}")
            }
            AdapterError::SourceOrSinkSizeRequired { .. } => {
                write!(f, "must specify either cluster or size option")
            }
            AdapterError::InvalidTableMutationSelection => {
                f.write_str("invalid selection: operation may only refer to user-defined tables")
            }
            AdapterError::ConstraintViolation(not_null_violation) => {
                write!(f, "{}", not_null_violation)
            }
            AdapterError::ConcurrentClusterDrop => {
                write!(f, "the transaction's active cluster has been dropped")
            }
            AdapterError::NoClusterReplicasAvailable(cluster) => {
                write!(
                    f,
                    "CLUSTER {} has no replicas available to service request",
                    cluster.quoted()
                )
            }
            AdapterError::OperationProhibitsTransaction(op) => {
                write!(f, "{} cannot be run inside a transaction block", op)
            }
            AdapterError::OperationRequiresTransaction(op) => {
                write!(f, "{} can only be used in transaction blocks", op)
            }
            AdapterError::ParseError(e) => e.fmt(f),
            AdapterError::PlanError(e) => e.fmt(f),
            AdapterError::PreparedStatementExists(name) => {
                write!(f, "prepared statement {} already exists", name.quoted())
            }
            AdapterError::ReadOnlyTransaction => f.write_str("transaction in read-only mode"),
            AdapterError::SingleStatementTransaction => {
                f.write_str("this transaction can only execute a single statement")
            }
            AdapterError::ReadWriteUnavailable => {
                f.write_str("transaction read-write mode must be set before any query")
            }
            AdapterError::StatementTimeout => {
                write!(f, "canceling statement due to statement timeout")
            }
            AdapterError::Canceled => {
                write!(f, "canceling statement due to user request")
            }
            AdapterError::IdleInTransactionSessionTimeout => {
                write!(
                    f,
                    "terminating connection due to idle-in-transaction timeout"
                )
            }
            AdapterError::RecursionLimit(e) => e.fmt(f),
            AdapterError::RelationOutsideTimeDomain { .. } => {
                write!(
                    f,
                    "Transactions can only reference objects in the same timedomain. \
                     See https://materialize.com/docs/sql/begin/#same-timedomain-error",
                )
            }
            AdapterError::ResourceExhaustion {
                resource_type,
                limit_name,
                desired,
                limit,
                current,
            } => {
                write!(
                    f,
                    "creating {resource_type} would violate {limit_name} limit (desired: {desired}, limit: {limit}, current: {current})"
                )
            }
            AdapterError::ResultSize(e) => write!(f, "{e}"),
            AdapterError::SafeModeViolation(feature) => {
                write!(f, "cannot create {} in safe mode", feature)
            }
            AdapterError::SubscribeOnlyTransaction => {
                f.write_str("SUBSCRIBE in transactions must be the only read statement")
            }
            AdapterError::Optimizer(e) => e.fmt(f),
            AdapterError::UnallowedOnCluster {
                depends_on,
                cluster,
            } => {
                let items = depends_on.into_iter().map(|item| item.quoted()).join(", ");
                write!(
                    f,
                    "querying the following items {items} is not allowed from the {} cluster",
                    cluster.quoted()
                )
            }
            AdapterError::Unauthorized(unauthorized) => {
                write!(f, "{unauthorized}")
            }
            AdapterError::UnknownCursor(name) => {
                write!(f, "cursor {} does not exist", name.quoted())
            }
            AdapterError::UnknownLoginRole(name) => {
                write!(f, "role {} does not exist", name.quoted())
            }
            AdapterError::Unsupported(features) => write!(f, "{} are not supported", features),
            AdapterError::Unstructured(e) => write!(f, "{}", e.display_with_causes()),
            AdapterError::WriteOnlyTransaction => f.write_str("transaction in write-only mode"),
            AdapterError::UnknownPreparedStatement(name) => {
                write!(f, "prepared statement {} does not exist", name.quoted())
            }
            AdapterError::UnknownClusterReplica {
                cluster_name,
                replica_name,
            } => write!(
                f,
                "cluster replica '{cluster_name}.{replica_name}' does not exist"
            ),
            AdapterError::UnrecognizedConfigurationParam(setting_name) => write!(
                f,
                "unrecognized configuration parameter {}",
                setting_name.quoted()
            ),
            AdapterError::UntargetedLogRead { .. } => {
                f.write_str("log source reads must target a replica")
            }
            AdapterError::MultiTableWriteTransaction => {
                f.write_str("write transactions only support writes to a single table")
            }
            AdapterError::DDLOnlyTransaction => f.write_str(
                "transactions which modify objects are restricted to just modifying objects",
            ),
            AdapterError::DDLTransactionRace => {
                f.write_str("object state changed while transaction was in progress")
            }
            AdapterError::TransactionDryRun { .. } => f.write_str("transaction dry run"),
            AdapterError::Storage(e) => e.fmt(f),
            AdapterError::Compute(e) => e.fmt(f),
            AdapterError::Orchestrator(e) => e.fmt(f),
            AdapterError::DependentObject(dependent_objects) => {
                let role_str = if dependent_objects.keys().count() == 1 {
                    "role"
                } else {
                    "roles"
                };
                write!(
                    f,
                    "{role_str} \"{}\" cannot be dropped because some objects depend on it",
                    dependent_objects.keys().join(", ")
                )
            }
            AdapterError::InvalidAlter(t, e) => {
                write!(f, "invalid ALTER {t}: {e}")
            }
            AdapterError::ConnectionValidation(e) => e.fmt(f),
            AdapterError::MaterializedViewWouldNeverRefresh(_, _) => {
                write!(
                    f,
                    "all the specified refreshes of the materialized view would be too far in the past, and thus they \
                    would never happen"
                )
            }
            AdapterError::InputNotReadableAtRefreshAtTime(_, _) => {
                write!(
                    f,
                    "REFRESH AT requested for a time where not all the inputs are readable"
                )
            }
        }
    }
}

impl From<anyhow::Error> for AdapterError {
    fn from(e: anyhow::Error) -> AdapterError {
        match e.downcast_ref::<PlanError>() {
            Some(plan_error) => AdapterError::PlanError(plan_error.clone()),
            None => AdapterError::Unstructured(e),
        }
    }
}

impl From<TryFromIntError> for AdapterError {
    fn from(e: TryFromIntError) -> AdapterError {
        AdapterError::Unstructured(e.into())
    }
}

impl From<TryFromDecimalError> for AdapterError {
    fn from(e: TryFromDecimalError) -> AdapterError {
        AdapterError::Unstructured(e.into())
    }
}

impl From<mz_catalog::memory::error::Error> for AdapterError {
    fn from(e: mz_catalog::memory::error::Error) -> AdapterError {
        AdapterError::Catalog(e)
    }
}

impl From<mz_catalog::durable::CatalogError> for AdapterError {
    fn from(e: mz_catalog::durable::CatalogError) -> Self {
        mz_catalog::memory::error::Error::from(e).into()
    }
}

impl From<EvalError> for AdapterError {
    fn from(e: EvalError) -> AdapterError {
        AdapterError::Eval(e)
    }
}

impl From<ExplainError> for AdapterError {
    fn from(e: ExplainError) -> AdapterError {
        match e {
            ExplainError::RecursionLimitError(e) => AdapterError::RecursionLimit(e),
            e => AdapterError::Explain(e),
        }
    }
}

impl From<mz_sql::catalog::CatalogError> for AdapterError {
    fn from(e: mz_sql::catalog::CatalogError) -> AdapterError {
        AdapterError::Catalog(mz_catalog::memory::error::Error::from(e))
    }
}

impl From<PlanError> for AdapterError {
    fn from(e: PlanError) -> AdapterError {
        AdapterError::PlanError(e)
    }
}

impl From<OptimizerError> for AdapterError {
    fn from(e: OptimizerError) -> AdapterError {
        use OptimizerError::*;
        match e {
            PlanError(e) => Self::PlanError(e),
            RecursionLimitError(e) => Self::RecursionLimit(e),
            EvalError(e) => Self::Eval(e),
            Internal(e) => Self::Internal(e),
            e => Self::Optimizer(e),
        }
    }
}

impl From<NotNullViolation> for AdapterError {
    fn from(e: NotNullViolation) -> AdapterError {
        AdapterError::ConstraintViolation(e)
    }
}

impl From<RecursionLimitError> for AdapterError {
    fn from(e: RecursionLimitError) -> AdapterError {
        AdapterError::RecursionLimit(e)
    }
}

impl From<oneshot::error::RecvError> for AdapterError {
    fn from(e: oneshot::error::RecvError) -> AdapterError {
        AdapterError::Unstructured(e.into())
    }
}

impl From<StorageError<mz_repr::Timestamp>> for AdapterError {
    fn from(e: StorageError<mz_repr::Timestamp>) -> Self {
        AdapterError::Storage(e)
    }
}

impl From<compute_error::InstanceExists> for AdapterError {
    fn from(e: compute_error::InstanceExists) -> Self {
        AdapterError::Compute(e.into())
    }
}

impl From<TimestampError> for AdapterError {
    fn from(e: TimestampError) -> Self {
        let e: EvalError = e.into();
        e.into()
    }
}

impl From<mz_sql_parser::parser::ParserStatementError> for AdapterError {
    fn from(e: mz_sql_parser::parser::ParserStatementError) -> Self {
        AdapterError::ParseError(e)
    }
}

impl From<VarError> for AdapterError {
    fn from(e: VarError) -> Self {
        let e: mz_catalog::memory::error::Error = e.into();
        e.into()
    }
}

impl From<rbac::UnauthorizedError> for AdapterError {
    fn from(e: rbac::UnauthorizedError) -> Self {
        AdapterError::Unauthorized(e)
    }
}

impl From<mz_sql_parser::ast::IdentError> for AdapterError {
    fn from(value: mz_sql_parser::ast::IdentError) -> Self {
        AdapterError::PlanError(PlanError::InvalidIdent(value))
    }
}

impl From<mz_sql::session::vars::ConnectionError> for AdapterError {
    fn from(value: mz_sql::session::vars::ConnectionError) -> Self {
        match value {
            mz_sql::session::vars::ConnectionError::TooManyConnections { current, limit } => {
                AdapterError::ResourceExhaustion {
                    resource_type: "connection".into(),
                    limit_name: "max_connections".into(),
                    desired: (current + 1).to_string(),
                    limit: limit.to_string(),
                    current: current.to_string(),
                }
            }
        }
    }
}

impl From<ConnectionValidationError> for AdapterError {
    fn from(e: ConnectionValidationError) -> AdapterError {
        AdapterError::ConnectionValidation(e)
    }
}

impl Error for AdapterError {}