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
// Rust-oracle - Rust binding for Oracle database
//
// URL: https://github.com/kubo/rust-oracle
//
//-----------------------------------------------------------------------------
// Copyright (c) 2017-2018 Kubo Takehiro <kubo@jiubao.org>. All rights reserved.
// This program is free software: you can modify it and/or redistribute it
// under the terms of:
//
// (i)  the Universal Permissive License v 1.0 or at your option, any
//      later version (http://oss.oracle.com/licenses/upl); and/or
//
// (ii) the Apache License v 2.0. (http://www.apache.org/licenses/LICENSE-2.0)
//-----------------------------------------------------------------------------

use crate::binding::dpiContext_getError;
use crate::binding::dpiErrorInfo;
use crate::to_rust_str;
use crate::AssertSend;
use crate::AssertSync;
use crate::Context;
#[cfg(doc)]
use crate::{Batch, BatchBuilder, Connection, Statement};
use std::error;
use std::ffi::CStr;
use std::fmt;
use std::mem::MaybeUninit;
use std::num;
use std::str;
use std::sync;

// DPI-1010: not connected
pub(crate) const DPI_ERR_NOT_CONNECTED: i32 = 1010;

// DPI-1019: buffer size of %u is too small
pub(crate) const DPI_ERR_BUFFER_SIZE_TOO_SMALL: i32 = 1019;

#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[non_exhaustive]
/// A list of error categories.
///
/// It is used with the [`Error`] type.
///
/// Use `_` to match “all other errors” in `match` expression because it has [`#[non_exhaustive]`](https://doc.rust-lang.org/reference/attributes/type_system.html#the-non_exhaustive-attribute) attribute.
pub enum ErrorKind {
    /// Error from an underlying Oracle client library.
    OciError,

    /// Error from an underlying ODPI-C layer.
    DpiError,

    /// Error when NULL value is got but the target rust type cannot handle NULL.
    /// Use `Option<...>` in this case.
    NullValue,

    /// Error when conversion from a string to an Oracle value fails
    ParseError,

    /// Error when conversion from a type to another fails due to out-of-range
    OutOfRange,

    /// Error when conversion from a type to another is not allowed.
    InvalidTypeConversion,

    /// Error when the bind parameter index is out of range. (one based)
    InvalidBindIndex,

    /// Error when the bind parameter name is not in the SQL.
    InvalidBindName,

    /// Error when the column index is out of range. (zero based)
    InvalidColumnIndex,

    /// Error when the column name is not in the SQL.
    InvalidColumnName,

    /// Error when the specified attribute name is not found.
    InvalidAttributeName,

    /// Error when invalid method is called such as calling execute for select statements.
    InvalidOperation,

    /// Error when an uninitialized bind value is accessed. Bind values
    /// must be initialized by [`Statement::bind`], [`Statement::execute`]
    /// or [`Connection::execute`] in advance.
    UninitializedBindValue,

    /// Error when no more rows exist in the SQL.
    NoDataFound,

    /// Error when [`BatchBuilder::with_batch_errors`] is set and [`Batch::execute`]
    /// fails by supplied batch data.
    /// See ["Error Handling with batch errors"](Batch#error-handling-with-batch-errors)
    BatchErrors,

    /// Internal error. When you get this error, please report it with a test case to reproduce it.
    InternalError,
}

/// The error type for oracle
///
/// **Note:** This enum will be changed to struct in the future.
#[non_exhaustive]
#[derive(Debug)]
pub enum Error {
    /// Error from an underlying Oracle client library.
    #[deprecated(note = "Use kind() to check the error category. Use db_error() to get DbError.")]
    OciError(DbError),

    /// Error from an underlying ODPI-C layer.
    #[deprecated(note = "Use kind() to check the error category. Use db_error() to get DbError.")]
    DpiError(DbError),

    /// Error when NULL value is got but the target rust type cannot handle NULL.
    /// Use `Option<...>` in this case.
    #[deprecated(note = "Use kind() to check the error category.")]
    NullValue,

    /// Error when conversion from a string to an Oracle value fails
    #[deprecated(
        note = "Use kind() to check the error category. Use source() to get the underlying error."
    )]
    ParseError(Box<dyn error::Error + Send + Sync>),

    /// Error when conversion from a type to another fails due to out-of-range
    #[deprecated(
        note = "Use kind() to check the error category. Use to_string() to get the message."
    )]
    OutOfRange(String),

    /// Error when conversion from a type to another is not allowed.
    #[deprecated(note = "Use kind() to check the error category.")]
    InvalidTypeConversion(String, String),

    /// Error when the bind parameter index is out of range. (one based)
    #[deprecated(note = "Use kind() to check the error category.")]
    InvalidBindIndex(usize),

    /// Error when the bind parameter name is not in the SQL.
    #[deprecated(note = "Use kind() to check the error category.")]
    InvalidBindName(String),

    /// Error when the column index is out of range. (zero based)
    #[deprecated(note = "Use kind() to check the error category.")]
    InvalidColumnIndex(usize),

    /// Error when the column name is not in the SQL.
    #[deprecated(note = "Use kind() to check the error category.")]
    InvalidColumnName(String),

    /// Error when the specified attribute name is not found.
    #[deprecated(note = "Use kind() to check the error category.")]
    InvalidAttributeName(String),

    /// Error when invalid method is called such as calling execute for select statements.
    #[deprecated(
        note = "Use kind() to check the error category. Use to_string() to get the message."
    )]
    InvalidOperation(String),

    /// Error when an uninitialized bind value is accessed. Bind values
    /// must be initialized by [`Statement::bind`], [`Statement::execute`]
    /// or [`Connection::execute`] in advance.
    #[deprecated(note = "Use kind() to check the error category.")]
    UninitializedBindValue,

    /// Error when no more rows exist in the SQL.
    #[deprecated(note = "Use kind() to check the error category.")]
    NoDataFound,

    #[deprecated(
        note = "Use kind() to check the error category. Use batch_errors() to get the db errors."
    )]
    BatchErrors(Vec<DbError>),

    /// Internal error. When you get this error, please report it with a test case to reproduce it.
    #[deprecated(
        note = "Use kind() to check the error category. Use to_string() to get the message."
    )]
    InternalError(String),
}

#[allow(deprecated)]
impl Error {
    /// Returns the corresponding [`ErrorKind`] for this error.
    pub fn kind(&self) -> ErrorKind {
        match self {
            Error::OciError(_) => ErrorKind::OciError,
            Error::DpiError(_) => ErrorKind::DpiError,
            Error::NullValue => ErrorKind::NullValue,
            Error::ParseError(_) => ErrorKind::ParseError,
            Error::OutOfRange(_) => ErrorKind::OutOfRange,
            Error::InvalidTypeConversion(_, _) => ErrorKind::InvalidTypeConversion,
            Error::InvalidBindIndex(_) => ErrorKind::InvalidBindIndex,
            Error::InvalidBindName(_) => ErrorKind::InvalidBindName,
            Error::InvalidColumnIndex(_) => ErrorKind::InvalidColumnIndex,
            Error::InvalidColumnName(_) => ErrorKind::InvalidColumnName,
            Error::InvalidAttributeName(_) => ErrorKind::InvalidAttributeName,
            Error::InvalidOperation(_) => ErrorKind::InvalidOperation,
            Error::UninitializedBindValue => ErrorKind::UninitializedBindValue,
            Error::NoDataFound => ErrorKind::NoDataFound,
            Error::BatchErrors(_) => ErrorKind::BatchErrors,
            Error::InternalError(_) => ErrorKind::InternalError,
        }
    }

    pub(crate) fn add_source<E>(self, _source: E) -> Error
    where
        E: Into<Box<dyn error::Error + Send + Sync>>,
    {
        // Do nothing now.
        // This is for the planned change.
        self
    }

    /// Returns [`DbError`].
    pub fn db_error(&self) -> Option<&DbError> {
        match self {
            Error::OciError(err) | Error::DpiError(err) => Some(err),
            _ => None,
        }
    }

    /// Returns batch errors.
    /// See ["Error Handling with batch errors"](Batch#error-handling-with-batch-errors)
    pub fn batch_errors(&self) -> Option<&Vec<DbError>> {
        match self {
            Error::BatchErrors(errs) => Some(errs),
            _ => None,
        }
    }

    /// Returns Oracle error code.
    /// For example 1 for "ORA-0001: unique constraint violated"
    pub fn oci_code(&self) -> Option<i32> {
        if let Error::OciError(dberr) = &self {
            if dberr.code != 0 {
                Some(dberr.code)
            } else {
                None
            }
        } else {
            None
        }
    }

    /// Returns [ODPI-C](https://oracle.github.io/odpi/) error code.
    pub fn dpi_code(&self) -> Option<i32> {
        if let Error::DpiError(dberr) = &self {
            dpi_error_in_message(&dberr.message)
        } else {
            None
        }
    }

    pub(crate) fn oci_error(dberr: DbError) -> Error {
        Error::OciError(dberr)
    }

    pub(crate) fn null_value() -> Error {
        Error::NullValue
    }

    pub(crate) fn parse_error<T>(source: T) -> Error
    where
        T: Into<Box<dyn error::Error + Send + Sync>>,
    {
        Error::ParseError(source.into())
    }

    pub(crate) fn out_of_range<T>(message: T) -> Error
    where
        T: Into<String>,
    {
        Error::OutOfRange(message.into())
    }

    pub(crate) fn invalid_type_conversion<T1, T2>(from: T1, to: T2) -> Error
    where
        T1: Into<String>,
        T2: Into<String>,
    {
        Error::InvalidTypeConversion(from.into(), to.into())
    }

    pub(crate) fn invalid_bind_index(index: usize) -> Error {
        Error::InvalidBindIndex(index)
    }

    pub(crate) fn invalid_bind_name<T>(name: T) -> Error
    where
        T: Into<String>,
    {
        Error::InvalidBindName(name.into())
    }

    pub(crate) fn invalid_column_index(index: usize) -> Error {
        Error::InvalidColumnIndex(index)
    }

    pub(crate) fn invalid_column_name<T>(name: T) -> Error
    where
        T: Into<String>,
    {
        Error::InvalidColumnName(name.into())
    }

    pub(crate) fn invalid_attribute_name<T>(name: T) -> Error
    where
        T: Into<String>,
    {
        Error::InvalidAttributeName(name.into())
    }

    pub(crate) fn invalid_operation<T>(message: T) -> Error
    where
        T: Into<String>,
    {
        Error::InvalidOperation(message.into())
    }

    pub(crate) fn uninitialized_bind_value() -> Error {
        Error::UninitializedBindValue
    }

    pub(crate) fn no_data_found() -> Error {
        Error::NoDataFound
    }

    pub(crate) fn make_batch_errors(errs: Vec<DbError>) -> Error {
        Error::BatchErrors(errs)
    }

    pub(crate) fn internal_error<T>(message: T) -> Error
    where
        T: Into<String>,
    {
        Error::InternalError(message.into())
    }
}

impl AssertSend for Error {}
impl AssertSync for Error {}

/// An error when parsing a string into an Oracle type fails.
/// This appears only in boxed data associated with [`Error::ParseError`].
#[derive(Eq, PartialEq, Clone)]
pub struct ParseOracleTypeError {
    typename: &'static str,
}

impl ParseOracleTypeError {
    pub fn new(typename: &'static str) -> ParseOracleTypeError {
        ParseOracleTypeError { typename }
    }
}

impl fmt::Display for ParseOracleTypeError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{} parse error", self.typename)
    }
}

impl fmt::Debug for ParseOracleTypeError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "ParseOracleTypeError")
    }
}

impl error::Error for ParseOracleTypeError {
    fn description(&self) -> &str {
        "Oracle type parse error"
    }

    fn cause(&self) -> Option<&dyn error::Error> {
        None
    }
}

/// Oracle database error or ODPI-C error
#[derive(Debug, Eq, PartialEq, Clone)]
pub struct DbError {
    code: i32,
    offset: u32,
    message: String,
    fn_name: String,
    action: String,
}

impl DbError {
    pub fn new(
        code: i32,
        offset: u32,
        message: String,
        fn_name: String,
        action: String,
    ) -> DbError {
        DbError {
            code,
            offset,
            message,
            fn_name,
            action,
        }
    }

    /// Oracle error code if OciError. always zero if DpiError
    pub fn code(&self) -> i32 {
        self.code
    }

    /// ? (used for Batch Errors?)
    pub fn offset(&self) -> u32 {
        self.offset
    }

    /// error message
    pub fn message(&self) -> &str {
        &self.message
    }

    /// function name in ODPI-C used by rust-oracle
    pub fn fn_name(&self) -> &str {
        &self.fn_name
    }

    /// action name in ODPI-C used by rust-oracle
    pub fn action(&self) -> &str {
        &self.action
    }
}

impl fmt::Display for Error {
    #[allow(deprecated)]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Error::OciError(err) => write!(f, "OCI Error: {}", err.message),
            Error::DpiError(err) => write!(f, "DPI Error: {}", err.message),
            Error::NullValue => write!(f, "NULL value found"),
            Error::ParseError(err) => write!(f, "{}", err),
            Error::OutOfRange(msg) => write!(f, "{}", msg),
            Error::InvalidTypeConversion(from, to) => {
                write!(f, "invalid type conversion from {} to {}", from, to)
            }
            Error::InvalidBindIndex(idx) => {
                write!(f, "invalid bind index {} (one-based)", idx)
            }
            Error::InvalidBindName(name) => write!(f, "invalid bind name {}", name),
            Error::InvalidColumnIndex(idx) => {
                write!(f, "invalid column index {} (zero-based)", idx)
            }
            Error::InvalidColumnName(name) => write!(f, "invalid column name {}", name),
            Error::InvalidAttributeName(name) => write!(f, "invalid attribute name {}", name),
            Error::InvalidOperation(msg) => write!(f, "{}", msg),
            Error::UninitializedBindValue => write!(f, "try to access uninitialized bind value"),
            Error::NoDataFound => write!(f, "no data found"),
            Error::BatchErrors(errs) => {
                write!(f, "batch errors (")?;
                for err in errs {
                    write!(f, "{}, ", err)?;
                }
                write!(f, ")")
            }
            Error::InternalError(msg) => write!(f, "{}", msg),
        }
    }
}

impl error::Error for Error {
    #[allow(deprecated)]
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
        match self {
            Error::ParseError(err) => Some(err.as_ref()),
            _ => None,
        }
    }
}

impl fmt::Display for DbError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.message)
    }
}

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

impl From<num::ParseIntError> for Error {
    fn from(err: num::ParseIntError) -> Self {
        Error::parse_error(err)
    }
}

impl From<num::ParseFloatError> for Error {
    fn from(err: num::ParseFloatError) -> Self {
        Error::parse_error(err)
    }
}

impl From<num::TryFromIntError> for Error {
    fn from(err: num::TryFromIntError) -> Self {
        Error::parse_error(err)
    }
}

impl From<str::Utf8Error> for Error {
    fn from(err: str::Utf8Error) -> Self {
        Error::parse_error(err)
    }
}

impl<T> From<sync::PoisonError<T>> for Error {
    fn from(err: sync::PoisonError<T>) -> Self {
        Error::internal_error(err.to_string())
    }
}

//
// functions to check errors
//

pub fn dberror_from_dpi_error(err: &dpiErrorInfo) -> DbError {
    DbError::new(
        err.code,
        err.offset,
        to_rust_str(err.message, err.messageLength),
        unsafe { CStr::from_ptr(err.fnName) }
            .to_string_lossy()
            .into_owned(),
        unsafe { CStr::from_ptr(err.action) }
            .to_string_lossy()
            .into_owned(),
    )
}

#[allow(deprecated)]
pub fn error_from_dpi_error(err: &dpiErrorInfo) -> Error {
    let err = dberror_from_dpi_error(err);
    if err.message().starts_with("DPI") {
        Error::DpiError(err)
    } else {
        Error::OciError(err)
    }
}

pub(crate) fn warning(ctxt: &Context) -> Option<DbError> {
    let err = unsafe {
        let mut err = MaybeUninit::uninit();
        dpiContext_getError(ctxt.context, err.as_mut_ptr());
        err.assume_init()
    };
    if err.isWarning != 0 {
        Some(dberror_from_dpi_error(&err))
    } else {
        None
    }
}

pub(crate) fn error_from_context(ctxt: &Context) -> Error {
    let err = unsafe {
        let mut err = MaybeUninit::uninit();
        dpiContext_getError(ctxt.context, err.as_mut_ptr());
        err.assume_init()
    };
    crate::error::error_from_dpi_error(&err)
}

fn dpi_error_in_message(message: &str) -> Option<i32> {
    let bytes = message.as_bytes();
    if !bytes.starts_with(b"DPI-") {
        return None;
    }
    let mut code = 0;
    for c in bytes.iter().skip(4) {
        if b'0' <= *c && *c <= b'9' {
            code *= 10;
            code += (*c - b'0') as i32;
        } else if *c == b':' {
            return Some(code);
        } else {
            break;
        }
    }
    None
}

#[macro_export]
#[doc(hidden)]
macro_rules! chkerr {
    ($ctxt:expr, $code:expr) => {{
        #[allow(unused_unsafe)]
        if unsafe { $code } != DPI_SUCCESS as i32 {
            return Err($crate::error::error_from_context($ctxt));
        }
    }};
    ($ctxt:expr, $code:expr, $cleanup:stmt) => {{
        #[allow(unused_unsafe)]
        if unsafe { $code } != DPI_SUCCESS as i32 {
            let err = $crate::error::error_from_context($ctxt);
            $cleanup
            return Err(err);
        }
    }};
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_dpi_error_in_message() {
        assert_eq!(None, dpi_error_in_message("ORA-1234"));
        assert_eq!(None, dpi_error_in_message("DPI-1234"));
        assert_eq!(Some(1234), dpi_error_in_message("DPI-1234: xxx"));
    }
}