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
// Copyright (c) 2016 Anatoly Ikorsky
//
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. All files in the project carrying such notice may not be copied,
// modified, or distributed except according to those terms.

pub use url::ParseError;

mod tls;

use mysql_common::{
    named_params::MixedParamsError, params::MissingNamedParameterError,
    proto::codec::error::PacketCodecError, row::Row, value::Value,
};
use thiserror::Error;

use std::{io, result};

/// Result type alias for this library.
pub type Result<T> = result::Result<T, Error>;

/// This type enumerates library errors.
#[derive(Debug, Error)]
pub enum Error {
    #[error("Driver error: `{}'", _0)]
    Driver(#[source] DriverError),

    #[error("Input/output error: {}", _0)]
    Io(#[source] IoError),

    #[error("Other error: {}", _0)]
    Other(#[source] Box<dyn std::error::Error + Send + Sync + 'static>),

    #[error("Server error: `{}'", _0)]
    Server(#[source] ServerError),

    #[error("URL error: `{}'", _0)]
    Url(#[source] UrlError),
}

impl Error {
    /// Returns true if the error means that connection is broken.
    pub fn is_fatal(&self) -> bool {
        match self {
            Error::Driver(_) | Error::Io(_) | Error::Other(_) | Error::Url(_) => true,
            Error::Server(_) => false,
        }
    }
}

/// This type enumerates IO errors.
#[derive(Debug, Error)]
pub enum IoError {
    #[error("Input/output error: {}", _0)]
    Io(#[source] io::Error),
    #[cfg(any(feature = "native-tls-tls", feature = "rustls-tls"))]
    #[error("TLS error: `{}'", _0)]
    Tls(#[source] tls::TlsError),
}

/// This type represents MySql server error.
#[derive(Debug, Error, Clone, Eq, PartialEq)]
#[error("ERROR {} ({}): {}", state, code, message)]
pub struct ServerError {
    pub code: u16,
    pub message: String,
    pub state: String,
}

/// This type enumerates connection URL errors.
#[derive(Debug, Error, Clone, Eq, PartialEq)]
pub enum UrlError {
    #[error("Connection URL parameter `{}' requires feature `{}'", param, feature)]
    FeatureRequired { feature: String, param: String },

    #[error("Invalid or incomplete connection URL")]
    Invalid,

    #[error("Invalid value `{}' for connection URL parameter `{}'", value, param)]
    InvalidParamValue { param: String, value: String },

    #[error("Invalid pool constraints: pool_min ({}) > pool_max ({}).", min, max)]
    InvalidPoolConstraints { min: usize, max: usize },

    #[error("URL parse error: {}", _0)]
    Parse(#[source] ParseError),

    #[error("Unknown connection URL parameter `{}'", param)]
    UnknownParameter { param: String },

    #[error("Unsupported connection URL scheme `{}'", scheme)]
    UnsupportedScheme { scheme: String },
}

/// This type enumerates driver errors.
#[derive(Debug, Error)]
pub enum DriverError {
    #[error("Can't parse server version from string `{}'.", version_string)]
    CantParseServerVersion { version_string: String },

    #[error("Connection to the server is closed.")]
    ConnectionClosed,

    #[error("Error converting from mysql value.")]
    FromValue { value: Value },

    #[error("Error converting from mysql row.")]
    FromRow { row: Row },

    #[error("Missing named parameter `{}'.", String::from_utf8_lossy(&name))]
    MissingNamedParam { name: Vec<u8> },

    #[error("Named and positional parameters mixed in one statement.")]
    MixedParams,

    #[error("Named parameters supplied for positional query.")]
    NamedParamsForPositionalQuery,

    #[error("Transactions couldn't be nested.")]
    NestedTransaction,

    #[error("Packet out of order.")]
    PacketOutOfOrder,

    #[error("Pool was disconnected.")]
    PoolDisconnected,

    #[error("`SET TRANSACTION READ (ONLY|WRITE)' is not supported in your MySQL version.")]
    ReadOnlyTransNotSupported,

    #[error(
        "Statement takes {} parameters but {} was supplied.",
        required,
        supplied
    )]
    StmtParamsMismatch { required: u16, supplied: u16 },

    #[error("Unexpected packet.")]
    UnexpectedPacket { payload: Vec<u8> },

    #[error("Unknown authentication plugin `{}'.", name)]
    UnknownAuthPlugin { name: String },

    #[error("Packet too large.")]
    PacketTooLarge,

    #[error("Bad compressed packet header.")]
    BadCompressedPacketHeader,

    #[error("Named pipe connections temporary disabled (see tokio-rs/tokio#3118)")]
    NamedPipesDisabled,

    #[error("`mysql_old_password` plugin is insecure and disabled by default")]
    MysqlOldPasswordDisabled,

    #[error("LOCAL INFILE error: {}", _0)]
    LocalInfile(#[from] LocalInfileError),

    #[error("No private key found in the file specified")]
    NoKeyFound,

    #[error("Client asked for SSL but server does not have this capability")]
    NoClientSslFlagFromServer,
}

#[derive(Debug, Error)]
pub enum LocalInfileError {
    #[error("The given path is not in the while list: {}", _0)]
    PathIsNotInTheWhiteList(String),
    #[error("Error reading `INFILE` data: {}", _0)]
    ReadError(#[from] io::Error),
    #[error("Can't handle local infile request. Handler is not specified.")]
    NoHandler,
    #[error(transparent)]
    OtherError(Box<dyn std::error::Error + Send + Sync + 'static>),
}

impl LocalInfileError {
    pub fn other<T>(err: T) -> Self
    where
        T: std::error::Error + Send + Sync + 'static,
    {
        Self::OtherError(Box::new(err))
    }
}

impl From<LocalInfileError> for Error {
    fn from(err: LocalInfileError) -> Self {
        Self::Driver(err.into())
    }
}

impl From<DriverError> for Error {
    fn from(err: DriverError) -> Self {
        Error::Driver(err)
    }
}

impl From<IoError> for Error {
    fn from(io: IoError) -> Self {
        Error::Io(io)
    }
}

impl From<io::Error> for IoError {
    fn from(err: io::Error) -> Self {
        IoError::Io(err)
    }
}

impl From<io::Error> for Error {
    fn from(err: io::Error) -> Self {
        Error::Io(err.into())
    }
}

impl From<ServerError> for Error {
    fn from(err: ServerError) -> Self {
        Error::Server(err)
    }
}

impl From<UrlError> for Error {
    fn from(err: UrlError) -> Self {
        Error::Url(err)
    }
}

#[cfg(feature = "native-tls-tls")]
impl From<native_tls::Error> for IoError {
    fn from(err: native_tls::Error) -> Self {
        IoError::Tls(tls::TlsError::TlsError(err))
    }
}

impl From<mysql_common::packets::ServerError<'_>> for ServerError {
    fn from(packet: mysql_common::packets::ServerError<'_>) -> Self {
        ServerError {
            code: packet.error_code(),
            message: packet.message_str().into(),
            state: packet.sql_state_str().into(),
        }
    }
}

impl From<mysql_common::packets::ServerError<'_>> for Error {
    fn from(packet: mysql_common::packets::ServerError<'_>) -> Self {
        Error::Server(packet.into())
    }
}

// For convenience
impl From<(Error, crate::io::Stream)> for Error {
    fn from((err, _): (Error, crate::io::Stream)) -> Self {
        err
    }
}

impl From<MissingNamedParameterError> for DriverError {
    fn from(err: MissingNamedParameterError) -> Self {
        DriverError::MissingNamedParam { name: err.0 }
    }
}

impl From<MissingNamedParameterError> for Error {
    fn from(err: MissingNamedParameterError) -> Self {
        Error::Driver(err.into())
    }
}

impl From<MixedParamsError> for DriverError {
    fn from(_err: MixedParamsError) -> Self {
        DriverError::MixedParams
    }
}

impl From<MixedParamsError> for Error {
    fn from(err: MixedParamsError) -> Self {
        Error::Driver(err.into())
    }
}

impl From<ParseError> for UrlError {
    fn from(err: ParseError) -> Self {
        UrlError::Parse(err)
    }
}

impl From<ParseError> for Error {
    fn from(err: ParseError) -> Self {
        Error::Url(err.into())
    }
}

impl From<PacketCodecError> for IoError {
    fn from(err: PacketCodecError) -> Self {
        match err {
            PacketCodecError::Io(err) => err.into(),
            PacketCodecError::PacketTooLarge => {
                io::Error::new(io::ErrorKind::Other, "packet too large").into()
            }
            PacketCodecError::PacketsOutOfSync => {
                io::Error::new(io::ErrorKind::Other, "packet out of order").into()
            }
            PacketCodecError::BadCompressedPacketHeader => {
                io::Error::new(io::ErrorKind::Other, "bad compressed packet header").into()
            }
        }
    }
}

impl From<PacketCodecError> for Error {
    fn from(err: PacketCodecError) -> Self {
        Error::Io(err.into())
    }
}