Skip to main content

rusqlite/
error.rs

1use crate::types::FromSqlError;
2use crate::types::Type;
3use crate::{Result, errmsg_to_string, ffi};
4use std::error;
5use std::ffi::{NulError, c_char, c_int};
6use std::fmt;
7use std::path::PathBuf;
8use std::str;
9
10// Just to keep MSRV low
11macro_rules! cfg_select {
12    ({ $($tt:tt)* }) => {{
13        $crate::cfg_select! { $($tt)* }
14    }};
15    (_ => { $($output:tt)* }) => {
16        $($output)*
17    };
18    (
19        $cfg:meta => $output:tt
20        $($( $rest:tt )+)?
21    ) => {{
22        #[cfg($cfg)]
23        cfg_select! { _ => $output }
24        $(
25            #[cfg(not($cfg))]
26            cfg_select! { $($rest)+ }
27        )?
28    }}
29}
30
31/// A stable category for errors produced by remote graph transfer operations.
32///
33/// The category is derived from narrow SQLite code and message pairs emitted
34/// by the remote transfer implementation. It lets callers present useful
35/// guidance without depending on native error text themselves.
36#[derive(Clone, Copy, Debug, Eq, PartialEq)]
37#[non_exhaustive]
38pub enum RemoteFailureKind {
39    /// The published manifest advanced after a session accepted its head.
40    StaleSession,
41    /// The requested branch update is not a fast-forward.
42    NonFastForward,
43    /// The request was rejected for an authorization reason.
44    Authorization,
45}
46
47/// Enum listing possible errors from rusqlite.
48#[derive(Debug)]
49#[non_exhaustive]
50pub enum Error {
51    /// An error from an underlying SQLite call.
52    SqliteFailure(ffi::Error, Option<String>),
53
54    /// Error reported when attempting to open a connection when SQLite was
55    /// configured to allow single-threaded use only.
56    SqliteSingleThreadedMode,
57
58    /// Error when the value of a particular column is requested, but it cannot
59    /// be converted to the requested Rust type.
60    FromSqlConversionFailure(usize, Type, Box<dyn error::Error + Send + Sync + 'static>),
61
62    /// Error when SQLite gives us an integral value outside the range of the
63    /// requested type (e.g., trying to get the value 1000 into a `u8`).
64    /// The associated `usize` is the column index,
65    /// and the associated `i64` is the value returned by SQLite.
66    IntegralValueOutOfRange(usize, i64),
67
68    /// Error converting a string to UTF-8.
69    Utf8Error(usize, str::Utf8Error),
70
71    /// Error converting a string to a C-compatible string because it contained
72    /// an embedded nul.
73    NulError(NulError),
74
75    /// Error when using SQL named parameters and passing a parameter name not
76    /// present in the SQL.
77    InvalidParameterName(String),
78
79    /// Error converting a file path to a string.
80    InvalidPath(PathBuf),
81
82    /// Error returned when an [`execute`](crate::Connection::execute) call
83    /// returns rows.
84    ExecuteReturnedResults,
85
86    /// Error when a query that was expected to return at least one row (e.g.,
87    /// for [`query_row`](crate::Connection::query_row)) did not return any.
88    QueryReturnedNoRows,
89
90    /// Error when a query that was expected to return only one row (e.g.,
91    /// for [`query_one`](crate::Connection::query_one)) did return more than one.
92    QueryReturnedMoreThanOneRow,
93
94    /// Error when the value of a particular column is requested, but the index
95    /// is out of range for the statement.
96    InvalidColumnIndex(usize),
97
98    /// Error when the value of a named column is requested, but no column
99    /// matches the name for the statement.
100    InvalidColumnName(String),
101
102    /// Error when the value of a particular column is requested, but the type
103    /// of the result in that column cannot be converted to the requested
104    /// Rust type.
105    InvalidColumnType(usize, String, Type),
106
107    /// Error when a query that was expected to insert one row did not insert
108    /// any or insert many.
109    StatementChangedRows(usize),
110
111    /// Error returned by
112    /// [`functions::Context::get`](crate::functions::Context::get) when the
113    /// function argument cannot be converted to the requested type.
114    #[cfg(feature = "functions")]
115    InvalidFunctionParameterType(usize, Type),
116    /// Error returned by [`vtab::Values::get`](crate::vtab::Values::get) when
117    /// the filter argument cannot be converted to the requested type.
118    #[cfg(feature = "vtab")]
119    InvalidFilterParameterType(usize, Type),
120
121    /// An error case available for implementors of custom user functions (e.g.,
122    /// [`create_scalar_function`](crate::Connection::create_scalar_function)).
123    #[cfg(feature = "functions")]
124    UserFunctionError(Box<dyn error::Error + Send + Sync + 'static>),
125
126    /// Error available for the implementors of the
127    /// [`ToSql`](crate::types::ToSql) trait.
128    ToSqlConversionFailure(Box<dyn error::Error + Send + Sync + 'static>),
129
130    /// Error when the SQL is not a `SELECT`, is not read-only.
131    InvalidQuery,
132
133    /// An error case available for implementors of custom modules (e.g.,
134    /// [`create_module`](crate::Connection::create_module)).
135    #[cfg(feature = "vtab")]
136    ModuleError(String),
137
138    /// An unwinding panic occurs in a UDF (user-defined function).
139    UnwindingPanic,
140
141    /// An error returned when
142    /// [`Context::get_aux`](crate::functions::Context::get_aux) attempts to
143    /// retrieve data of a different type than what had been stored using
144    /// [`Context::set_aux`](crate::functions::Context::set_aux).
145    #[cfg(feature = "functions")]
146    GetAuxWrongType,
147
148    /// Error when the SQL contains multiple statements.
149    MultipleStatement,
150    /// Error when the number of bound parameters does not match the number of
151    /// parameters in the query. The first `usize` is how many parameters were
152    /// given, the 2nd is how many were expected.
153    InvalidParameterCount(usize, usize),
154
155    /// Returned from various functions in the Blob IO positional API. For
156    /// example,
157    /// [`Blob::raw_read_at_exact`](crate::blob::Blob::raw_read_at_exact) will
158    /// return it if the blob has insufficient data.
159    #[cfg(feature = "blob")]
160    BlobSizeError,
161    /// Error referencing a specific token in the input SQL
162    SqlInputError {
163        /// error code
164        error: ffi::Error,
165        /// error message
166        msg: String,
167        /// SQL input
168        sql: String,
169        /// byte offset of the start of invalid token
170        offset: c_int,
171    },
172    /// Loadable extension initialization error
173    #[cfg(feature = "loadable_extension")]
174    InitError(ffi::InitError),
175    /// Error when the schema of a particular database is requested, but the index
176    /// is out of range.
177    InvalidDatabaseIndex(usize),
178}
179
180impl PartialEq for Error {
181    fn eq(&self, other: &Self) -> bool {
182        match (self, other) {
183            (Self::SqliteFailure(e1, s1), Self::SqliteFailure(e2, s2)) => e1 == e2 && s1 == s2,
184            (Self::SqliteSingleThreadedMode, Self::SqliteSingleThreadedMode) => true,
185            (Self::IntegralValueOutOfRange(i1, n1), Self::IntegralValueOutOfRange(i2, n2)) => {
186                i1 == i2 && n1 == n2
187            }
188            (Self::Utf8Error(i1, e1), Self::Utf8Error(i2, e2)) => i1 == i2 && e1 == e2,
189            (Self::NulError(e1), Self::NulError(e2)) => e1 == e2,
190            (Self::InvalidParameterName(n1), Self::InvalidParameterName(n2)) => n1 == n2,
191            (Self::InvalidPath(p1), Self::InvalidPath(p2)) => p1 == p2,
192            (Self::ExecuteReturnedResults, Self::ExecuteReturnedResults) => true,
193            (Self::QueryReturnedNoRows, Self::QueryReturnedNoRows) => true,
194            (Self::QueryReturnedMoreThanOneRow, Self::QueryReturnedMoreThanOneRow) => true,
195            (Self::InvalidColumnIndex(i1), Self::InvalidColumnIndex(i2)) => i1 == i2,
196            (Self::InvalidColumnName(n1), Self::InvalidColumnName(n2)) => n1 == n2,
197            (Self::InvalidColumnType(i1, n1, t1), Self::InvalidColumnType(i2, n2, t2)) => {
198                i1 == i2 && t1 == t2 && n1 == n2
199            }
200            (Self::StatementChangedRows(n1), Self::StatementChangedRows(n2)) => n1 == n2,
201            #[cfg(feature = "functions")]
202            (
203                Self::InvalidFunctionParameterType(i1, t1),
204                Self::InvalidFunctionParameterType(i2, t2),
205            ) => i1 == i2 && t1 == t2,
206            #[cfg(feature = "vtab")]
207            (
208                Self::InvalidFilterParameterType(i1, t1),
209                Self::InvalidFilterParameterType(i2, t2),
210            ) => i1 == i2 && t1 == t2,
211            (Self::InvalidQuery, Self::InvalidQuery) => true,
212            #[cfg(feature = "vtab")]
213            (Self::ModuleError(s1), Self::ModuleError(s2)) => s1 == s2,
214            (Self::UnwindingPanic, Self::UnwindingPanic) => true,
215            #[cfg(feature = "functions")]
216            (Self::GetAuxWrongType, Self::GetAuxWrongType) => true,
217            (Self::InvalidParameterCount(i1, n1), Self::InvalidParameterCount(i2, n2)) => {
218                i1 == i2 && n1 == n2
219            }
220            #[cfg(feature = "blob")]
221            (Self::BlobSizeError, Self::BlobSizeError) => true,
222            (
223                Self::SqlInputError {
224                    error: e1,
225                    msg: m1,
226                    sql: s1,
227                    offset: o1,
228                },
229                Self::SqlInputError {
230                    error: e2,
231                    msg: m2,
232                    sql: s2,
233                    offset: o2,
234                },
235            ) => e1 == e2 && m1 == m2 && s1 == s2 && o1 == o2,
236            #[cfg(feature = "loadable_extension")]
237            (Self::InitError(e1), Self::InitError(e2)) => e1 == e2,
238            (Self::InvalidDatabaseIndex(i1), Self::InvalidDatabaseIndex(i2)) => i1 == i2,
239            (..) => false,
240        }
241    }
242}
243
244impl From<str::Utf8Error> for Error {
245    #[cold]
246    fn from(err: str::Utf8Error) -> Self {
247        Self::Utf8Error(UNKNOWN_COLUMN, err)
248    }
249}
250
251impl From<NulError> for Error {
252    #[cold]
253    fn from(err: NulError) -> Self {
254        Self::NulError(err)
255    }
256}
257
258const UNKNOWN_COLUMN: usize = usize::MAX;
259
260/// The conversion isn't precise, but it's convenient to have it
261/// to allow use of `get_raw(…).as_…()?` in callbacks that take `Error`.
262impl From<FromSqlError> for Error {
263    #[cold]
264    fn from(err: FromSqlError) -> Self {
265        // The error type requires index and type fields, but they aren't known in this
266        // context.
267        match err {
268            FromSqlError::OutOfRange(val) => Self::IntegralValueOutOfRange(UNKNOWN_COLUMN, val),
269            FromSqlError::InvalidBlobSize { .. } => {
270                Self::FromSqlConversionFailure(UNKNOWN_COLUMN, Type::Blob, Box::new(err))
271            }
272            FromSqlError::Other(source) => {
273                Self::FromSqlConversionFailure(UNKNOWN_COLUMN, Type::Null, source)
274            }
275            _ => Self::FromSqlConversionFailure(UNKNOWN_COLUMN, Type::Null, Box::new(err)),
276        }
277    }
278}
279
280#[cfg(feature = "loadable_extension")]
281impl From<ffi::InitError> for Error {
282    #[cold]
283    fn from(err: ffi::InitError) -> Self {
284        Self::InitError(err)
285    }
286}
287
288impl fmt::Display for Error {
289    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
290        match *self {
291            Self::SqliteFailure(ref err, None) => err.fmt(f),
292            Self::SqliteFailure(_, Some(ref s)) => write!(f, "{s}"),
293            Self::SqliteSingleThreadedMode => write!(
294                f,
295                "SQLite was compiled or configured for single-threaded use only"
296            ),
297            Self::FromSqlConversionFailure(i, ref t, ref err) => {
298                if i == UNKNOWN_COLUMN {
299                    err.fmt(f)
300                } else {
301                    write!(f, "Conversion error from type {t} at index: {i}, {err}")
302                }
303            }
304            Self::IntegralValueOutOfRange(col, val) => {
305                if col == UNKNOWN_COLUMN {
306                    write!(f, "Integer {val} out of range")
307                } else {
308                    write!(f, "Integer {val} out of range at index {col}")
309                }
310            }
311            Self::Utf8Error(col, ref err) => {
312                if col == UNKNOWN_COLUMN {
313                    err.fmt(f)
314                } else {
315                    write!(f, "{err} at index {col}")
316                }
317            }
318            Self::NulError(ref err) => err.fmt(f),
319            Self::InvalidParameterName(ref name) => write!(f, "Invalid parameter name: {name}"),
320            Self::InvalidPath(ref p) => write!(f, "Invalid path: {}", p.to_string_lossy()),
321            Self::ExecuteReturnedResults => {
322                write!(f, "Execute returned results - did you mean to call query?")
323            }
324            Self::QueryReturnedNoRows => write!(f, "Query returned no rows"),
325            Self::QueryReturnedMoreThanOneRow => write!(f, "Query returned more than one row"),
326            Self::InvalidColumnIndex(i) => write!(f, "Invalid column index: {i}"),
327            Self::InvalidColumnName(ref name) => write!(f, "Invalid column name: {name}"),
328            Self::InvalidColumnType(i, ref name, ref t) => {
329                write!(f, "Invalid column type {t} at index: {i}, name: {name}")
330            }
331            Self::InvalidParameterCount(i1, n1) => write!(
332                f,
333                "Wrong number of parameters passed to query. Got {i1}, needed {n1}"
334            ),
335            Self::StatementChangedRows(i) => write!(f, "Query changed {i} rows"),
336
337            #[cfg(feature = "functions")]
338            Self::InvalidFunctionParameterType(i, ref t) => {
339                write!(f, "Invalid function parameter type {t} at index {i}")
340            }
341            #[cfg(feature = "vtab")]
342            Self::InvalidFilterParameterType(i, ref t) => {
343                write!(f, "Invalid filter parameter type {t} at index {i}")
344            }
345            #[cfg(feature = "functions")]
346            Self::UserFunctionError(ref err) => err.fmt(f),
347            Self::ToSqlConversionFailure(ref err) => err.fmt(f),
348            Self::InvalidQuery => write!(f, "Query is not read-only"),
349            #[cfg(feature = "vtab")]
350            Self::ModuleError(ref desc) => write!(f, "{desc}"),
351            Self::UnwindingPanic => write!(f, "unwinding panic"),
352            #[cfg(feature = "functions")]
353            Self::GetAuxWrongType => write!(f, "get_aux called with wrong type"),
354            Self::MultipleStatement => write!(f, "Multiple statements provided"),
355            #[cfg(feature = "blob")]
356            Self::BlobSizeError => "Blob size is insufficient".fmt(f),
357            Self::SqlInputError {
358                ref msg,
359                offset,
360                ref sql,
361                ..
362            } => write!(f, "{msg} in {sql} at offset {offset}"),
363            #[cfg(feature = "loadable_extension")]
364            Self::InitError(ref err) => err.fmt(f),
365            Self::InvalidDatabaseIndex(i) => write!(f, "Invalid database index: {i}"),
366        }
367    }
368}
369
370impl error::Error for Error {
371    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
372        match *self {
373            Self::SqliteFailure(ref err, _) => Some(err),
374            Self::Utf8Error(_, ref err) => Some(err),
375            Self::NulError(ref err) => Some(err),
376
377            Self::IntegralValueOutOfRange(..)
378            | Self::SqliteSingleThreadedMode
379            | Self::InvalidParameterName(_)
380            | Self::ExecuteReturnedResults
381            | Self::QueryReturnedNoRows
382            | Self::QueryReturnedMoreThanOneRow
383            | Self::InvalidColumnIndex(_)
384            | Self::InvalidColumnName(_)
385            | Self::InvalidColumnType(..)
386            | Self::InvalidPath(_)
387            | Self::InvalidParameterCount(..)
388            | Self::StatementChangedRows(_)
389            | Self::InvalidQuery
390            | Self::MultipleStatement => None,
391
392            #[cfg(feature = "functions")]
393            Self::InvalidFunctionParameterType(..) => None,
394            #[cfg(feature = "vtab")]
395            Self::InvalidFilterParameterType(..) => None,
396
397            #[cfg(feature = "functions")]
398            Self::UserFunctionError(ref err) => Some(&**err),
399
400            Self::FromSqlConversionFailure(_, _, ref err)
401            | Self::ToSqlConversionFailure(ref err) => Some(&**err),
402
403            #[cfg(feature = "vtab")]
404            Self::ModuleError(_) => None,
405
406            Self::UnwindingPanic => None,
407
408            #[cfg(feature = "functions")]
409            Self::GetAuxWrongType => None,
410
411            #[cfg(feature = "blob")]
412            Self::BlobSizeError => None,
413            Self::SqlInputError { ref error, .. } => Some(error),
414            #[cfg(feature = "loadable_extension")]
415            Self::InitError(ref err) => Some(err),
416            Self::InvalidDatabaseIndex(_) => None,
417        }
418    }
419}
420
421impl Error {
422    /// Classify a known remote graph-transfer failure, if this error matches
423    /// one of the native transfer failures with stable caller meaning.
424    ///
425    /// This deliberately recognizes exact native code and message pairs for
426    /// stale sessions and non-fast-forward branch updates. Unrelated SQLite
427    /// constraint or busy errors return `None`.
428    #[must_use]
429    pub fn remote_failure_kind(&self) -> Option<RemoteFailureKind> {
430        let Self::SqliteFailure(error, message) = self else {
431            return None;
432        };
433
434        match (error.code, error.extended_code, message.as_deref()) {
435            (
436                ffi::ErrorCode::DatabaseBusy,
437                ffi::SQLITE_BUSY,
438                Some("published manifest changed since the accepted session head"),
439            ) => Some(RemoteFailureKind::StaleSession),
440            (
441                ffi::ErrorCode::ConstraintViolation,
442                ffi::SQLITE_CONSTRAINT,
443                Some("not a fast-forward of the remote branch (use force to overwrite)"),
444            ) => Some(RemoteFailureKind::NonFastForward),
445            (ffi::ErrorCode::AuthorizationForStatementDenied, ffi::SQLITE_AUTH, _)
446            | (ffi::ErrorCode::SystemIoFailure, ffi::SQLITE_IOERR_AUTH, _) => {
447                Some(RemoteFailureKind::Authorization)
448            }
449            _ => None,
450        }
451    }
452
453    /// Returns the underlying SQLite error if this is [`Error::SqliteFailure`].
454    #[inline]
455    #[must_use]
456    pub fn sqlite_error(&self) -> Option<&ffi::Error> {
457        match self {
458            Self::SqliteFailure(error, _) => Some(error),
459            _ => None,
460        }
461    }
462
463    /// Returns the underlying SQLite error code if this is
464    /// [`Error::SqliteFailure`].
465    #[inline]
466    #[must_use]
467    pub fn sqlite_error_code(&self) -> Option<ffi::ErrorCode> {
468        self.sqlite_error().map(|error| error.code)
469    }
470
471    /// Returns the underlying SQLite extended error code if this is
472    /// [`Error::SqliteFailure`].
473    #[inline]
474    #[must_use]
475    pub fn sqlite_extended_error_code(&self) -> Option<c_int> {
476        self.sqlite_error().map(|error| error.extended_code)
477    }
478}
479
480// These are public but not re-exported by lib.rs, so only visible within crate.
481
482#[cold]
483pub fn error_from_sqlite_code(code: c_int, message: Option<String>) -> Error {
484    Error::SqliteFailure(ffi::Error::new(code), message)
485}
486
487macro_rules! err {
488    ($code:expr $(,)?) => {
489        $crate::error::error_from_sqlite_code($code, None)
490    };
491    ($code:expr, $msg:literal $(,)?) => {
492        $crate::error::error_from_sqlite_code($code, Some(format!($msg)))
493    };
494    ($code:expr, $err:expr $(,)?) => {
495        $crate::error::error_from_sqlite_code($code, Some(format!($err)))
496    };
497    ($code:expr, $fmt:expr, $($arg:tt)*) => {
498        $crate::error::error_from_sqlite_code($code, Some(format!($fmt, $($arg)*)))
499    };
500}
501
502#[cold]
503pub unsafe fn error_from_handle(db: *mut ffi::sqlite3, code: c_int) -> Error {
504    error_from_sqlite_code(code, unsafe { error_msg(db, code) })
505}
506
507unsafe fn error_msg(db: *mut ffi::sqlite3, code: c_int) -> Option<String> {
508    unsafe {
509        if db.is_null() || ffi::sqlite3_errcode(db) != code {
510            let err_str = ffi::sqlite3_errstr(code);
511            if err_str.is_null() {
512                None
513            } else {
514                Some(errmsg_to_string(err_str))
515            }
516        } else {
517            Some(errmsg_to_string(ffi::sqlite3_errmsg(db)))
518        }
519    }
520}
521
522pub unsafe fn decode_result_raw(db: *mut ffi::sqlite3, code: c_int) -> Result<()> {
523    if code == ffi::SQLITE_OK {
524        Ok(())
525    } else {
526        Err(unsafe { error_from_handle(db, code) })
527    }
528}
529
530#[cold]
531#[allow(unused_variables)]
532pub unsafe fn error_with_offset(db: *mut ffi::sqlite3, code: c_int, sql: &str) -> Error {
533    unsafe {
534        if db.is_null() {
535            error_from_sqlite_code(code, None)
536        } else {
537            let error = ffi::Error::new(code);
538            let msg = error_msg(db, code);
539            if ffi::ErrorCode::Unknown == error.code {
540                let offset = ffi::sqlite3_error_offset(db);
541                if offset >= 0 {
542                    return Error::SqlInputError {
543                        error,
544                        msg: msg.unwrap_or("error".to_owned()),
545                        sql: sql.to_owned(),
546                        offset,
547                    };
548                }
549            }
550            Error::SqliteFailure(error, msg)
551        }
552    }
553}
554
555pub fn check(code: c_int) -> Result<()> {
556    if code == ffi::SQLITE_OK {
557        Ok(())
558    } else {
559        Err(error_from_sqlite_code(code, None))
560    }
561}
562
563/// Transform Rust error to SQLite error (message and code).
564/// # Safety
565/// This function is unsafe because it uses raw pointer
566pub unsafe fn to_sqlite_error(e: &Error, err_msg: *mut *mut c_char) -> c_int {
567    use crate::util::alloc;
568
569    match e {
570        Error::SqliteFailure(err, s) => {
571            if let Some(s) = s {
572                unsafe { *err_msg = alloc(s) };
573            }
574            err.extended_code
575        }
576        err => {
577            unsafe { *err_msg = alloc(&err.to_string()) };
578            ffi::SQLITE_ERROR
579        }
580    }
581}
582
583/// Set error code and message
584/// # Safety
585/// This function is unsafe because it uses raw pointer
586#[cfg(feature = "modern_sqlite")] // 3.51.0
587pub unsafe fn set_errmsg(
588    db: *mut ffi::sqlite3,
589    code: c_int,
590    msg: Option<&std::ffi::CStr>,
591) -> Result<()> {
592    unsafe {
593        decode_result_raw(
594            db,
595            ffi::sqlite3_set_errmsg(
596                db,
597                code,
598                msg.map_or(std::ptr::null(), std::ffi::CStr::as_ptr),
599            ),
600        )
601    }
602}
603#[cfg(test)]
604mod remote_failure_tests {
605    use super::{Error, RemoteFailureKind};
606    use crate::ffi;
607
608    #[test]
609    fn remote_failure_kind_classifies_only_known_native_errors() {
610        let stale = Error::SqliteFailure(
611            ffi::Error::new(ffi::SQLITE_BUSY),
612            Some("published manifest changed since the accepted session head".into()),
613        );
614        assert_eq!(
615            stale.remote_failure_kind(),
616            Some(RemoteFailureKind::StaleSession)
617        );
618
619        let non_fast_forward = Error::SqliteFailure(
620            ffi::Error::new(ffi::SQLITE_CONSTRAINT),
621            Some("not a fast-forward of the remote branch (use force to overwrite)".into()),
622        );
623        assert_eq!(
624            non_fast_forward.remote_failure_kind(),
625            Some(RemoteFailureKind::NonFastForward)
626        );
627
628        for code in [ffi::SQLITE_AUTH, ffi::SQLITE_IOERR_AUTH] {
629            let authorization = Error::SqliteFailure(ffi::Error::new(code), None);
630            assert_eq!(
631                authorization.remote_failure_kind(),
632                Some(RemoteFailureKind::Authorization)
633            );
634        }
635    }
636
637    #[test]
638    fn remote_failure_kind_rejects_wrong_or_inconsistent_codes_and_messages() {
639        let missing_message = Error::SqliteFailure(ffi::Error::new(ffi::SQLITE_BUSY), None);
640        assert_eq!(missing_message.remote_failure_kind(), None);
641
642        let wrong_stale_message = Error::SqliteFailure(
643            ffi::Error::new(ffi::SQLITE_BUSY),
644            Some("another operation is busy".into()),
645        );
646        assert_eq!(wrong_stale_message.remote_failure_kind(), None);
647
648        let wrong_stale_code = Error::SqliteFailure(
649            ffi::Error::new(ffi::SQLITE_BUSY_SNAPSHOT),
650            Some("published manifest changed since the accepted session head".into()),
651        );
652        assert_eq!(wrong_stale_code.remote_failure_kind(), None);
653
654        let wrong_constraint_message = Error::SqliteFailure(
655            ffi::Error::new(ffi::SQLITE_CONSTRAINT),
656            Some("a different constraint failed".into()),
657        );
658        assert_eq!(wrong_constraint_message.remote_failure_kind(), None);
659
660        let wrong_constraint_code = Error::SqliteFailure(
661            ffi::Error::new(ffi::SQLITE_CONSTRAINT_UNIQUE),
662            Some("not a fast-forward of the remote branch (use force to overwrite)".into()),
663        );
664        assert_eq!(wrong_constraint_code.remote_failure_kind(), None);
665
666        let inconsistent_primary_code = Error::SqliteFailure(
667            ffi::Error {
668                code: ffi::ErrorCode::Unknown,
669                extended_code: ffi::SQLITE_BUSY,
670            },
671            Some("published manifest changed since the accepted session head".into()),
672        );
673        assert_eq!(inconsistent_primary_code.remote_failure_kind(), None);
674
675        let inconsistent_authorization_code = Error::SqliteFailure(
676            ffi::Error {
677                code: ffi::ErrorCode::Unknown,
678                extended_code: ffi::SQLITE_AUTH,
679            },
680            None,
681        );
682        assert_eq!(inconsistent_authorization_code.remote_failure_kind(), None);
683
684        let unrelated_error = Error::SqliteFailure(
685            ffi::Error::new(ffi::SQLITE_ERROR),
686            Some("authorization failed".into()),
687        );
688        assert_eq!(unrelated_error.remote_failure_kind(), None);
689
690        assert_eq!(Error::InvalidQuery.remote_failure_kind(), None);
691    }
692}