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
// 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::fmt;

use backtrace::Backtrace;

use ore::str::StrExt;
use sql::catalog::CatalogError as SqlCatalogError;

#[derive(Debug)]
pub struct Error {
    pub(crate) kind: ErrorKind,
    pub(crate) _backtrace: Backtrace,
}

#[derive(Debug)]
pub enum ErrorKind {
    Corruption {
        detail: String,
    },
    IdExhaustion,
    OidExhaustion,
    Sql(SqlCatalogError),
    DatabaseAlreadyExists(String),
    DefaultIndexDisabled {
        idx_on: String,
        default_idx: String,
    },
    SchemaAlreadyExists(String),
    RoleAlreadyExists(String),
    ItemAlreadyExists(String),
    ReservedSchemaName(String),
    ReservedRoleName(String),
    ReadOnlySystemSchema(String),
    ReadOnlyItem(String),
    SchemaNotEmpty(String),
    InvalidTemporaryDependency(String),
    InvalidTemporarySchema,
    MandatoryTableIndex(String),
    UnsatisfiableLoggingDependency {
        depender_name: String,
    },
    Storage(rusqlite::Error),
    Persistence(persist::error::Error),
    AmbiguousRename {
        depender: String,
        dependee: String,
        message: String,
    },
    TypeRename(String),
    ExperimentalModeRequired,
    ExperimentalModeUnavailable,
    FailedMigration {
        last_seen_version: String,
        this_version: &'static str,
        cause: String,
    },
}

impl Error {
    pub(crate) fn new(kind: ErrorKind) -> Error {
        Error {
            kind,
            _backtrace: Backtrace::new_unresolved(),
        }
    }

    /// Reports additional details about the error, if any are available.
    pub fn detail(&self) -> Option<String> {
        match &self.kind {
            ErrorKind::ReservedSchemaName(_) => {
                Some("The prefixes \"mz_\" and \"pg_\" are reserved for system schemas.".into())
            }
            ErrorKind::ReservedRoleName(_) => {
                Some("The prefixes \"mz_\" and \"pg_\" are reserved for system roles.".into())
            }
            _ => None,
        }
    }

    /// Reports a hint for the user about how the error could be fixed.
    pub fn hint(&self) -> Option<String> {
        match &self.kind {
            ErrorKind::DefaultIndexDisabled { default_idx, .. } => Some(format!(
                "You can enable the default index using ALTER INDEX {} SET ENABLED",
                default_idx
            )),
            _ => None,
        }
    }
}

impl From<rusqlite::Error> for Error {
    fn from(e: rusqlite::Error) -> Error {
        Error::new(ErrorKind::Storage(e))
    }
}

impl From<SqlCatalogError> for Error {
    fn from(e: SqlCatalogError) -> Error {
        Error::new(ErrorKind::Sql(e))
    }
}

impl From<persist::error::Error> for Error {
    fn from(e: persist::error::Error) -> Error {
        Error::new(ErrorKind::Persistence(e))
    }
}

impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match &self.kind {
            ErrorKind::Corruption { .. }
            | ErrorKind::IdExhaustion
            | ErrorKind::OidExhaustion
            | ErrorKind::DatabaseAlreadyExists(_)
            | ErrorKind::SchemaAlreadyExists(_)
            | ErrorKind::RoleAlreadyExists(_)
            | ErrorKind::ItemAlreadyExists(_)
            | ErrorKind::ReservedSchemaName(_)
            | ErrorKind::ReservedRoleName(_)
            | ErrorKind::ReadOnlySystemSchema(_)
            | ErrorKind::ReadOnlyItem(_)
            | ErrorKind::SchemaNotEmpty(_)
            | ErrorKind::InvalidTemporaryDependency(_)
            | ErrorKind::InvalidTemporarySchema
            | ErrorKind::MandatoryTableIndex(_)
            | ErrorKind::UnsatisfiableLoggingDependency { .. }
            | ErrorKind::AmbiguousRename { .. }
            | ErrorKind::TypeRename(_)
            | ErrorKind::ExperimentalModeRequired
            | ErrorKind::ExperimentalModeUnavailable
            | ErrorKind::FailedMigration { .. }
            | ErrorKind::DefaultIndexDisabled { .. } => None,
            ErrorKind::Sql(e) => Some(e),
            ErrorKind::Storage(e) => Some(e),
            ErrorKind::Persistence(e) => Some(e),
        }
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match &self.kind {
            ErrorKind::Corruption { detail } => write!(f, "corrupt catalog: {}", detail),
            ErrorKind::IdExhaustion => write!(f, "id counter overflows i64"),
            ErrorKind::OidExhaustion => write!(f, "oid counter overflows u32"),
            ErrorKind::Sql(e) => write!(f, "{}", e),
            ErrorKind::DatabaseAlreadyExists(name) => {
                write!(f, "database '{}' already exists", name)
            }
            ErrorKind::SchemaAlreadyExists(name) => write!(f, "schema '{}' already exists", name),
            ErrorKind::RoleAlreadyExists(name) => {
                write!(f, "role '{}' already exists", name)
            }
            ErrorKind::ItemAlreadyExists(name) => {
                write!(f, "catalog item '{}' already exists", name)
            }
            ErrorKind::ReservedSchemaName(name) => {
                write!(f, "unacceptable schema name '{}'", name)
            }
            ErrorKind::ReservedRoleName(name) => {
                write!(f, "role name {} is reserved", name.quoted())
            }
            ErrorKind::ReadOnlySystemSchema(name) => {
                write!(f, "system schema '{}' cannot be modified", name)
            }
            ErrorKind::ReadOnlyItem(name) => write!(f, "system item '{}' cannot be modified", name),
            ErrorKind::SchemaNotEmpty(name) => write!(f, "cannot drop non-empty schema '{}'", name),
            ErrorKind::InvalidTemporaryDependency(name) => write!(
                f,
                "non-temporary items cannot depend on temporary item '{}'",
                name
            ),
            ErrorKind::InvalidTemporarySchema => {
                write!(f, "cannot create temporary item in non-temporary schema")
            }
            ErrorKind::MandatoryTableIndex(index_name) => write!(
                f,
                "cannot drop '{}' as it is the default index for a table",
                index_name
            ),
            ErrorKind::UnsatisfiableLoggingDependency { depender_name } => write!(
                f,
                "catalog item '{}' depends on system logging, but logging is disabled",
                depender_name
            ),
            ErrorKind::Storage(e) => write!(f, "sqlite error: {}", e),
            ErrorKind::Persistence(e) => write!(f, "persistence error: {}", e),
            ErrorKind::AmbiguousRename {
                depender,
                dependee,
                message,
            } => {
                if depender == dependee {
                    write!(f, "renaming conflict: in {}, {}", dependee, message)
                } else {
                    write!(
                        f,
                        "renaming conflict: in {}, which uses {}, {}",
                        depender, dependee, message
                    )
                }
            }
            ErrorKind::TypeRename(typ) => write!(f, "cannot rename type: {}", typ),
            ErrorKind::ExperimentalModeRequired => write!(
                f,
                r#"Materialize previously started with --experimental to
enable experimental features, so now must be started in experimental
mode. For more details, see
https://materialize.com/docs/cli#experimental-mode"#
            ),
            ErrorKind::ExperimentalModeUnavailable => write!(
                f,
                r#"Experimental mode is only available on new nodes. For
more details, see https://materialize.com/docs/cli#experimental-mode"#
            ),
            ErrorKind::FailedMigration {
                last_seen_version,
                this_version,
                cause,
            } => {
                write!(
                    f,
                    "cannot migrate from catalog version {} to version {} (earlier versions might still work): {}",
                    last_seen_version, this_version, cause
                )
            }
            ErrorKind::DefaultIndexDisabled {
                idx_on,
                default_idx,
            } => {
                write!(
                    f,
                    "cannot perform operation on {} while its default index ({}) is disabled",
                    idx_on.quoted(),
                    default_idx.quoted()
                )
            }
        }
    }
}