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
use itertools::Itertools;
use query_structure::prelude::DomainError;
use query_structure::Filter;
use std::fmt::Display;
use thiserror::Error;
use user_facing_errors::{query_engine::DatabaseConstraint, KnownError};

#[derive(Debug, Error)]
#[error("{}", kind)]
pub struct ConnectorError {
    /// An optional error already rendered for users.
    pub user_facing_error: Option<KnownError>,
    /// The error information for internal use.
    pub kind: ErrorKind,
    /// Whether an error is transient and should be retried.
    pub transient: bool,
}

impl ConnectorError {
    pub fn from_kind(kind: ErrorKind) -> Self {
        let user_facing_error = match &kind {
            ErrorKind::NullConstraintViolation { constraint } => Some(KnownError::new(
                user_facing_errors::query_engine::NullConstraintViolation {
                    constraint: constraint.to_owned(),
                },
            )),
            ErrorKind::TableDoesNotExist { table } => {
                Some(KnownError::new(user_facing_errors::query_engine::TableDoesNotExist {
                    table: table.clone(),
                }))
            }
            ErrorKind::ColumnDoesNotExist { column } => {
                Some(KnownError::new(user_facing_errors::query_engine::ColumnDoesNotExist {
                    column: column.clone(),
                }))
            }
            ErrorKind::InvalidDatabaseUrl { details, url: _ } => {
                let details = user_facing_errors::quaint::invalid_connection_string_description(details);

                Some(KnownError::new(user_facing_errors::common::InvalidConnectionString {
                    details,
                }))
            }
            ErrorKind::ForeignKeyConstraintViolation { constraint } => {
                let field_name = match constraint {
                    DatabaseConstraint::Fields(fields) => fields.join(","),
                    DatabaseConstraint::Index(index) => format!("{index} (index)"),
                    DatabaseConstraint::ForeignKey => "foreign key".to_string(),
                    DatabaseConstraint::CannotParse => "(not available)".to_string(),
                };

                Some(KnownError::new(user_facing_errors::query_engine::ForeignKeyViolation {
                    field_name,
                }))
            }
            ErrorKind::ConversionError(message) => Some(KnownError::new(
                user_facing_errors::query_engine::InconsistentColumnData {
                    message: format!("{message}"),
                },
            )),
            ErrorKind::QueryInvalidInput(message) => Some(KnownError::new(
                user_facing_errors::query_engine::DatabaseAssertionViolation {
                    database_error: message.to_owned(),
                },
            )),
            ErrorKind::UnsupportedFeature(feature) => {
                Some(KnownError::new(user_facing_errors::query_engine::UnsupportedFeature {
                    feature: feature.clone(),
                }))
            }
            ErrorKind::MultiError(merror) => Some(KnownError::new(user_facing_errors::query_engine::MultiError {
                errors: format!("{merror}"),
            })),
            ErrorKind::UniqueConstraintViolation { constraint } => {
                Some(KnownError::new(user_facing_errors::query_engine::UniqueKeyViolation {
                    constraint: constraint.clone(),
                }))
            }

            ErrorKind::IncorrectNumberOfParameters { expected, actual } => Some(KnownError::new(
                user_facing_errors::common::IncorrectNumberOfParameters {
                    expected: *expected,
                    actual: *actual,
                },
            )),
            ErrorKind::QueryParameterLimitExceeded(message) => Some(KnownError::new(
                user_facing_errors::query_engine::QueryParameterLimitExceeded {
                    message: message.clone(),
                },
            )),

            ErrorKind::MissingFullTextSearchIndex => Some(KnownError::new(
                user_facing_errors::query_engine::MissingFullTextSearchIndex {},
            )),
            ErrorKind::TransactionAborted { message } => Some(KnownError::new(
                user_facing_errors::query_engine::InteractiveTransactionError { error: message.clone() },
            )),
            ErrorKind::TransactionWriteConflict => Some(KnownError::new(
                user_facing_errors::query_engine::TransactionWriteConflict {},
            )),
            ErrorKind::TransactionAlreadyClosed { message } => {
                Some(KnownError::new(user_facing_errors::common::TransactionAlreadyClosed {
                    message: message.clone(),
                }))
            }
            ErrorKind::ConnectionClosed => Some(KnownError::new(user_facing_errors::common::ConnectionClosed)),
            ErrorKind::MongoReplicaSetRequired => Some(KnownError::new(
                user_facing_errors::query_engine::MongoReplicaSetRequired {},
            )),
            ErrorKind::RawDatabaseError { code, message } => Some(user_facing_errors::KnownError::new(
                user_facing_errors::query_engine::RawQueryFailed {
                    code: code.clone(),
                    message: message.clone(),
                },
            )),
            ErrorKind::ExternalError(id) => Some(user_facing_errors::KnownError::new(
                user_facing_errors::query_engine::ExternalError { id: id.to_owned() },
            )),
            ErrorKind::RecordDoesNotExist { cause } => Some(KnownError::new(
                user_facing_errors::query_engine::RecordRequiredButNotFound { cause: cause.clone() },
            )),
            _ => None,
        };

        ConnectorError {
            user_facing_error,
            kind,
            transient: false,
        }
    }

    pub fn set_transient(&mut self, transient: bool) {
        self.transient = transient;
    }

    pub fn is_transient(&self) -> bool {
        self.transient
    }
}

#[derive(Debug, Error)]
pub enum ErrorKind {
    #[error("Unique constraint failed: {}", constraint)]
    UniqueConstraintViolation { constraint: DatabaseConstraint },

    #[error("Null constraint failed: {}", constraint)]
    NullConstraintViolation { constraint: DatabaseConstraint },

    #[error("Foreign key constraint failed")]
    ForeignKeyConstraintViolation { constraint: DatabaseConstraint },

    #[error("Record does not exist: {cause}")]
    RecordDoesNotExist { cause: String },

    #[error("Column '{}' does not exist.", column)]
    ColumnDoesNotExist { column: String },

    #[error("Table '{}' does not exist.", table)]
    TableDoesNotExist { table: String },

    #[error("Error creating a database connection. ({})", _0)]
    ConnectionError(anyhow::Error),

    #[error("Error querying the database: {}", _0)]
    QueryError(Box<dyn std::error::Error + Send + Sync>),

    #[error("The provided arguments are not supported.")]
    InvalidConnectionArguments,

    #[error("The column value was different from the model")]
    ColumnReadFailure(Box<dyn std::error::Error + Send + Sync>),

    #[error("Field cannot be null: {}", field)]
    FieldCannotBeNull { field: String },

    #[error("{}", _0)]
    DomainError(DomainError),

    #[error("Record not found: {:?}", _0)]
    RecordNotFoundForWhere(Filter),

    #[error(
        "Violating a relation {} between {} and {}",
        relation_name,
        model_a_name,
        model_b_name
    )]
    RelationViolation {
        relation_name: String,
        model_a_name: String,
        model_b_name: String,
    },

    #[error(
        "The relation {} has no record for the model {} connected to a record for the model {} on your write path.",
        relation_name,
        parent_name,
        child_name
    )]
    RecordsNotConnected {
        relation_name: String,
        parent_name: String,
        child_name: String,
    },

    #[error("Conversion error: {}", _0)]
    ConversionError(anyhow::Error),

    #[error("Invalid input provided to query: {}", _0)]
    QueryInvalidInput(String),

    #[error("Conversion error: {}", _0)]
    InternalConversionError(String),

    #[error("Database creation error: {}", _0)]
    DatabaseCreationError(&'static str),

    #[error("Database '{}' does not exist.", db_name)]
    DatabaseDoesNotExist { db_name: String },

    #[error("Access denied to database '{}'", db_name)]
    DatabaseAccessDenied { db_name: String },

    #[error("Authentication failed for user '{}'", user)]
    AuthenticationFailed { user: String },

    #[error("Database error. error code: {}, error message: {}", code, message)]
    RawDatabaseError { code: String, message: String },

    #[error("Raw API error: {0}")]
    RawApiError(String),

    #[error("{}", details)]
    InvalidDatabaseUrl { details: String, url: String },

    #[error("Unsupported connector feature: {0}")]
    UnsupportedFeature(String),

    #[error("Multiple errors occurred: {}", 0)]
    MultiError(MultiError),

    #[error(
        "Incorrect number of parameters given to a statement. Expected {}: got: {}.",
        expected,
        actual
    )]
    IncorrectNumberOfParameters { expected: usize, actual: usize },

    #[error("Server terminated the connection.")]
    ConnectionClosed,

    #[error("Transaction aborted: {}", message)]
    TransactionAborted { message: String },

    #[error("{}", message)]
    TransactionAlreadyClosed { message: String },

    #[error("Transaction write conflict")]
    TransactionWriteConflict,

    #[error("ROLLBACK statement has no corresponding BEGIN statement")]
    RollbackWithoutBegin,

    #[error("The query parameter limit supported by your database is exceeded: {0}.")]
    QueryParameterLimitExceeded(String),

    #[error("Cannot find a fulltext index to use for the search")]
    MissingFullTextSearchIndex,

    #[error("Replica Set required for Transactions")]
    MongoReplicaSetRequired,

    #[error("Unsupported connector: {0}")]
    UnsupportedConnector(String),

    #[error("External connector error")]
    ExternalError(i32),

    #[error("Invalid driver adapter: {0}")]
    InvalidDriverAdapter(String),
}

impl From<DomainError> for ConnectorError {
    fn from(e: DomainError) -> ConnectorError {
        ConnectorError::from_kind(ErrorKind::DomainError(e))
    }
}

#[derive(Debug)]
pub struct MultiError {
    pub errors: Vec<ErrorKind>,
}

impl Display for MultiError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let errors = self
            .errors
            .iter()
            .enumerate()
            .map(|(i, err)| format!("{}) {}", i + 1, err))
            .collect_vec();

        write!(f, "{}", errors.join("\n"))
    }
}