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
10macro_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#[derive(Clone, Copy, Debug, Eq, PartialEq)]
37#[non_exhaustive]
38pub enum RemoteFailureKind {
39 StaleSession,
41 NonFastForward,
43 Authorization,
45}
46
47#[derive(Debug)]
49#[non_exhaustive]
50pub enum Error {
51 SqliteFailure(ffi::Error, Option<String>),
53
54 SqliteSingleThreadedMode,
57
58 FromSqlConversionFailure(usize, Type, Box<dyn error::Error + Send + Sync + 'static>),
61
62 IntegralValueOutOfRange(usize, i64),
67
68 Utf8Error(usize, str::Utf8Error),
70
71 NulError(NulError),
74
75 InvalidParameterName(String),
78
79 InvalidPath(PathBuf),
81
82 ExecuteReturnedResults,
85
86 QueryReturnedNoRows,
89
90 QueryReturnedMoreThanOneRow,
93
94 InvalidColumnIndex(usize),
97
98 InvalidColumnName(String),
101
102 InvalidColumnType(usize, String, Type),
106
107 StatementChangedRows(usize),
110
111 #[cfg(feature = "functions")]
115 InvalidFunctionParameterType(usize, Type),
116 #[cfg(feature = "vtab")]
119 InvalidFilterParameterType(usize, Type),
120
121 #[cfg(feature = "functions")]
124 UserFunctionError(Box<dyn error::Error + Send + Sync + 'static>),
125
126 ToSqlConversionFailure(Box<dyn error::Error + Send + Sync + 'static>),
129
130 InvalidQuery,
132
133 #[cfg(feature = "vtab")]
136 ModuleError(String),
137
138 UnwindingPanic,
140
141 #[cfg(feature = "functions")]
146 GetAuxWrongType,
147
148 MultipleStatement,
150 InvalidParameterCount(usize, usize),
154
155 #[cfg(feature = "blob")]
160 BlobSizeError,
161 SqlInputError {
163 error: ffi::Error,
165 msg: String,
167 sql: String,
169 offset: c_int,
171 },
172 #[cfg(feature = "loadable_extension")]
174 InitError(ffi::InitError),
175 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
260impl From<FromSqlError> for Error {
263 #[cold]
264 fn from(err: FromSqlError) -> Self {
265 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 #[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 #[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 #[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 #[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#[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
563pub 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#[cfg(feature = "modern_sqlite")] pub 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}