1use crate::types::FromSqlError;
2use crate::types::Type;
3use crate::{errmsg_to_string, ffi, Result};
4use std::error;
5use std::ffi::{c_char, c_int, NulError};
6use std::fmt;
7use std::path::PathBuf;
8use std::str;
9
10#[derive(Debug)]
12#[non_exhaustive]
13pub enum Error {
14 SqliteFailure(ffi::Error, Option<String>),
16
17 SqliteSingleThreadedMode,
20
21 FromSqlConversionFailure(usize, Type, Box<dyn error::Error + Send + Sync + 'static>),
24
25 IntegralValueOutOfRange(usize, i64),
30
31 Utf8Error(str::Utf8Error),
33
34 NulError(NulError),
37
38 InvalidParameterName(String),
41
42 InvalidPath(PathBuf),
44
45 ExecuteReturnedResults,
48
49 QueryReturnedNoRows,
52
53 QueryReturnedMoreThanOneRow,
56
57 InvalidColumnIndex(usize),
60
61 InvalidColumnName(String),
64
65 InvalidColumnType(usize, String, Type),
69
70 StatementChangedRows(usize),
73
74 #[cfg(feature = "functions")]
78 InvalidFunctionParameterType(usize, Type),
79 #[cfg(feature = "vtab")]
82 InvalidFilterParameterType(usize, Type),
83
84 #[cfg(feature = "functions")]
87 UserFunctionError(Box<dyn error::Error + Send + Sync + 'static>),
88
89 ToSqlConversionFailure(Box<dyn error::Error + Send + Sync + 'static>),
92
93 InvalidQuery,
95
96 #[cfg(feature = "vtab")]
99 ModuleError(String),
100
101 UnwindingPanic,
103
104 #[cfg(feature = "functions")]
109 GetAuxWrongType,
110
111 MultipleStatement,
113 InvalidParameterCount(usize, usize),
117
118 #[cfg(feature = "blob")]
123 BlobSizeError,
124 #[cfg(feature = "modern_sqlite")] SqlInputError {
127 error: ffi::Error,
129 msg: String,
131 sql: String,
133 offset: c_int,
135 },
136 #[cfg(feature = "loadable_extension")]
138 InitError(ffi::InitError),
139 #[cfg(feature = "modern_sqlite")] InvalidDatabaseIndex(usize),
143}
144
145impl PartialEq for Error {
146 fn eq(&self, other: &Self) -> bool {
147 match (self, other) {
148 (Self::SqliteFailure(e1, s1), Self::SqliteFailure(e2, s2)) => e1 == e2 && s1 == s2,
149 (Self::SqliteSingleThreadedMode, Self::SqliteSingleThreadedMode) => true,
150 (Self::IntegralValueOutOfRange(i1, n1), Self::IntegralValueOutOfRange(i2, n2)) => {
151 i1 == i2 && n1 == n2
152 }
153 (Self::Utf8Error(e1), Self::Utf8Error(e2)) => e1 == e2,
154 (Self::NulError(e1), Self::NulError(e2)) => e1 == e2,
155 (Self::InvalidParameterName(n1), Self::InvalidParameterName(n2)) => n1 == n2,
156 (Self::InvalidPath(p1), Self::InvalidPath(p2)) => p1 == p2,
157 (Self::ExecuteReturnedResults, Self::ExecuteReturnedResults) => true,
158 (Self::QueryReturnedNoRows, Self::QueryReturnedNoRows) => true,
159 (Self::QueryReturnedMoreThanOneRow, Self::QueryReturnedMoreThanOneRow) => true,
160 (Self::InvalidColumnIndex(i1), Self::InvalidColumnIndex(i2)) => i1 == i2,
161 (Self::InvalidColumnName(n1), Self::InvalidColumnName(n2)) => n1 == n2,
162 (Self::InvalidColumnType(i1, n1, t1), Self::InvalidColumnType(i2, n2, t2)) => {
163 i1 == i2 && t1 == t2 && n1 == n2
164 }
165 (Self::StatementChangedRows(n1), Self::StatementChangedRows(n2)) => n1 == n2,
166 #[cfg(feature = "functions")]
167 (
168 Self::InvalidFunctionParameterType(i1, t1),
169 Self::InvalidFunctionParameterType(i2, t2),
170 ) => i1 == i2 && t1 == t2,
171 #[cfg(feature = "vtab")]
172 (
173 Self::InvalidFilterParameterType(i1, t1),
174 Self::InvalidFilterParameterType(i2, t2),
175 ) => i1 == i2 && t1 == t2,
176 (Self::InvalidQuery, Self::InvalidQuery) => true,
177 #[cfg(feature = "vtab")]
178 (Self::ModuleError(s1), Self::ModuleError(s2)) => s1 == s2,
179 (Self::UnwindingPanic, Self::UnwindingPanic) => true,
180 #[cfg(feature = "functions")]
181 (Self::GetAuxWrongType, Self::GetAuxWrongType) => true,
182 (Self::InvalidParameterCount(i1, n1), Self::InvalidParameterCount(i2, n2)) => {
183 i1 == i2 && n1 == n2
184 }
185 #[cfg(feature = "blob")]
186 (Self::BlobSizeError, Self::BlobSizeError) => true,
187 #[cfg(feature = "modern_sqlite")]
188 (
189 Self::SqlInputError {
190 error: e1,
191 msg: m1,
192 sql: s1,
193 offset: o1,
194 },
195 Self::SqlInputError {
196 error: e2,
197 msg: m2,
198 sql: s2,
199 offset: o2,
200 },
201 ) => e1 == e2 && m1 == m2 && s1 == s2 && o1 == o2,
202 #[cfg(feature = "loadable_extension")]
203 (Self::InitError(e1), Self::InitError(e2)) => e1 == e2,
204 #[cfg(feature = "modern_sqlite")]
205 (Self::InvalidDatabaseIndex(i1), Self::InvalidDatabaseIndex(i2)) => i1 == i2,
206 (..) => false,
207 }
208 }
209}
210
211impl From<str::Utf8Error> for Error {
212 #[cold]
213 fn from(err: str::Utf8Error) -> Self {
214 Self::Utf8Error(err)
215 }
216}
217
218impl From<NulError> for Error {
219 #[cold]
220 fn from(err: NulError) -> Self {
221 Self::NulError(err)
222 }
223}
224
225const UNKNOWN_COLUMN: usize = usize::MAX;
226
227impl From<FromSqlError> for Error {
230 #[cold]
231 fn from(err: FromSqlError) -> Self {
232 match err {
235 FromSqlError::OutOfRange(val) => Self::IntegralValueOutOfRange(UNKNOWN_COLUMN, val),
236 FromSqlError::InvalidBlobSize { .. } => {
237 Self::FromSqlConversionFailure(UNKNOWN_COLUMN, Type::Blob, Box::new(err))
238 }
239 FromSqlError::Other(source) => {
240 Self::FromSqlConversionFailure(UNKNOWN_COLUMN, Type::Null, source)
241 }
242 _ => Self::FromSqlConversionFailure(UNKNOWN_COLUMN, Type::Null, Box::new(err)),
243 }
244 }
245}
246
247#[cfg(feature = "loadable_extension")]
248impl From<ffi::InitError> for Error {
249 #[cold]
250 fn from(err: ffi::InitError) -> Self {
251 Self::InitError(err)
252 }
253}
254
255impl fmt::Display for Error {
256 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
257 match *self {
258 Self::SqliteFailure(ref err, None) => err.fmt(f),
259 Self::SqliteFailure(_, Some(ref s)) => write!(f, "{s}"),
260 Self::SqliteSingleThreadedMode => write!(
261 f,
262 "SQLite was compiled or configured for single-threaded use only"
263 ),
264 Self::FromSqlConversionFailure(i, ref t, ref err) => {
265 if i != UNKNOWN_COLUMN {
266 write!(f, "Conversion error from type {t} at index: {i}, {err}")
267 } else {
268 err.fmt(f)
269 }
270 }
271 Self::IntegralValueOutOfRange(col, val) => {
272 if col != UNKNOWN_COLUMN {
273 write!(f, "Integer {val} out of range at index {col}")
274 } else {
275 write!(f, "Integer {val} out of range")
276 }
277 }
278 Self::Utf8Error(ref err) => err.fmt(f),
279 Self::NulError(ref err) => err.fmt(f),
280 Self::InvalidParameterName(ref name) => write!(f, "Invalid parameter name: {name}"),
281 Self::InvalidPath(ref p) => write!(f, "Invalid path: {}", p.to_string_lossy()),
282 Self::ExecuteReturnedResults => {
283 write!(f, "Execute returned results - did you mean to call query?")
284 }
285 Self::QueryReturnedNoRows => write!(f, "Query returned no rows"),
286 Self::QueryReturnedMoreThanOneRow => write!(f, "Query returned more than one row"),
287 Self::InvalidColumnIndex(i) => write!(f, "Invalid column index: {i}"),
288 Self::InvalidColumnName(ref name) => write!(f, "Invalid column name: {name}"),
289 Self::InvalidColumnType(i, ref name, ref t) => {
290 write!(f, "Invalid column type {t} at index: {i}, name: {name}")
291 }
292 Self::InvalidParameterCount(i1, n1) => write!(
293 f,
294 "Wrong number of parameters passed to query. Got {i1}, needed {n1}"
295 ),
296 Self::StatementChangedRows(i) => write!(f, "Query changed {i} rows"),
297
298 #[cfg(feature = "functions")]
299 Self::InvalidFunctionParameterType(i, ref t) => {
300 write!(f, "Invalid function parameter type {t} at index {i}")
301 }
302 #[cfg(feature = "vtab")]
303 Self::InvalidFilterParameterType(i, ref t) => {
304 write!(f, "Invalid filter parameter type {t} at index {i}")
305 }
306 #[cfg(feature = "functions")]
307 Self::UserFunctionError(ref err) => err.fmt(f),
308 Self::ToSqlConversionFailure(ref err) => err.fmt(f),
309 Self::InvalidQuery => write!(f, "Query is not read-only"),
310 #[cfg(feature = "vtab")]
311 Self::ModuleError(ref desc) => write!(f, "{desc}"),
312 Self::UnwindingPanic => write!(f, "unwinding panic"),
313 #[cfg(feature = "functions")]
314 Self::GetAuxWrongType => write!(f, "get_aux called with wrong type"),
315 Self::MultipleStatement => write!(f, "Multiple statements provided"),
316 #[cfg(feature = "blob")]
317 Self::BlobSizeError => "Blob size is insufficient".fmt(f),
318 #[cfg(feature = "modern_sqlite")]
319 Self::SqlInputError {
320 ref msg,
321 offset,
322 ref sql,
323 ..
324 } => write!(f, "{msg} in {sql} at offset {offset}"),
325 #[cfg(feature = "loadable_extension")]
326 Self::InitError(ref err) => err.fmt(f),
327 #[cfg(feature = "modern_sqlite")]
328 Self::InvalidDatabaseIndex(i) => write!(f, "Invalid database index: {i}"),
329 }
330 }
331}
332
333impl error::Error for Error {
334 fn source(&self) -> Option<&(dyn error::Error + 'static)> {
335 match *self {
336 Self::SqliteFailure(ref err, _) => Some(err),
337 Self::Utf8Error(ref err) => Some(err),
338 Self::NulError(ref err) => Some(err),
339
340 Self::IntegralValueOutOfRange(..)
341 | Self::SqliteSingleThreadedMode
342 | Self::InvalidParameterName(_)
343 | Self::ExecuteReturnedResults
344 | Self::QueryReturnedNoRows
345 | Self::QueryReturnedMoreThanOneRow
346 | Self::InvalidColumnIndex(_)
347 | Self::InvalidColumnName(_)
348 | Self::InvalidColumnType(..)
349 | Self::InvalidPath(_)
350 | Self::InvalidParameterCount(..)
351 | Self::StatementChangedRows(_)
352 | Self::InvalidQuery
353 | Self::MultipleStatement => None,
354
355 #[cfg(feature = "functions")]
356 Self::InvalidFunctionParameterType(..) => None,
357 #[cfg(feature = "vtab")]
358 Self::InvalidFilterParameterType(..) => None,
359
360 #[cfg(feature = "functions")]
361 Self::UserFunctionError(ref err) => Some(&**err),
362
363 Self::FromSqlConversionFailure(_, _, ref err)
364 | Self::ToSqlConversionFailure(ref err) => Some(&**err),
365
366 #[cfg(feature = "vtab")]
367 Self::ModuleError(_) => None,
368
369 Self::UnwindingPanic => None,
370
371 #[cfg(feature = "functions")]
372 Self::GetAuxWrongType => None,
373
374 #[cfg(feature = "blob")]
375 Self::BlobSizeError => None,
376 #[cfg(feature = "modern_sqlite")]
377 Self::SqlInputError { ref error, .. } => Some(error),
378 #[cfg(feature = "loadable_extension")]
379 Self::InitError(ref err) => Some(err),
380 #[cfg(feature = "modern_sqlite")]
381 Self::InvalidDatabaseIndex(_) => None,
382 }
383 }
384}
385
386impl Error {
387 #[inline]
389 #[must_use]
390 pub fn sqlite_error(&self) -> Option<&ffi::Error> {
391 match self {
392 Self::SqliteFailure(error, _) => Some(error),
393 _ => None,
394 }
395 }
396
397 #[inline]
400 #[must_use]
401 pub fn sqlite_error_code(&self) -> Option<ffi::ErrorCode> {
402 self.sqlite_error().map(|error| error.code)
403 }
404}
405
406#[cold]
409pub fn error_from_sqlite_code(code: c_int, message: Option<String>) -> Error {
410 Error::SqliteFailure(ffi::Error::new(code), message)
411}
412
413macro_rules! err {
414 ($code:expr $(,)?) => {
415 $crate::error::error_from_sqlite_code($code, None)
416 };
417 ($code:expr, $msg:literal $(,)?) => {
418 $crate::error::error_from_sqlite_code($code, Some(format!($msg)))
419 };
420 ($code:expr, $err:expr $(,)?) => {
421 $crate::error::error_from_sqlite_code($code, Some(format!($err)))
422 };
423 ($code:expr, $fmt:expr, $($arg:tt)*) => {
424 $crate::error::error_from_sqlite_code($code, Some(format!($fmt, $($arg)*)))
425 };
426}
427
428#[cold]
429pub unsafe fn error_from_handle(db: *mut ffi::sqlite3, code: c_int) -> Error {
430 error_from_sqlite_code(code, error_msg(db, code))
431}
432
433unsafe fn error_msg(db: *mut ffi::sqlite3, code: c_int) -> Option<String> {
434 if db.is_null() || ffi::sqlite3_errcode(db) != code {
435 let err_str = ffi::sqlite3_errstr(code);
436 if err_str.is_null() {
437 None
438 } else {
439 Some(errmsg_to_string(err_str))
440 }
441 } else {
442 Some(errmsg_to_string(ffi::sqlite3_errmsg(db)))
443 }
444}
445
446pub unsafe fn decode_result_raw(db: *mut ffi::sqlite3, code: c_int) -> Result<()> {
447 if code == ffi::SQLITE_OK {
448 Ok(())
449 } else {
450 Err(error_from_handle(db, code))
451 }
452}
453
454#[cold]
455#[cfg(not(feature = "modern_sqlite"))] pub unsafe fn error_with_offset(db: *mut ffi::sqlite3, code: c_int, _sql: &str) -> Error {
457 error_from_handle(db, code)
458}
459
460#[cold]
461#[cfg(feature = "modern_sqlite")] pub unsafe fn error_with_offset(db: *mut ffi::sqlite3, code: c_int, sql: &str) -> Error {
463 if db.is_null() {
464 error_from_sqlite_code(code, None)
465 } else {
466 let error = ffi::Error::new(code);
467 let msg = error_msg(db, code);
468 if ffi::ErrorCode::Unknown == error.code {
469 let offset = ffi::sqlite3_error_offset(db);
470 if offset >= 0 {
471 return Error::SqlInputError {
472 error,
473 msg: msg.unwrap_or("error".to_owned()),
474 sql: sql.to_owned(),
475 offset,
476 };
477 }
478 }
479 Error::SqliteFailure(error, msg)
480 }
481}
482
483pub fn check(code: c_int) -> Result<()> {
484 if code != ffi::SQLITE_OK {
485 Err(error_from_sqlite_code(code, None))
486 } else {
487 Ok(())
488 }
489}
490
491pub unsafe fn to_sqlite_error(e: &Error, err_msg: *mut *mut c_char) -> c_int {
495 use crate::util::alloc;
496 match e {
497 Error::SqliteFailure(err, s) => {
498 if let Some(s) = s {
499 *err_msg = alloc(s);
500 }
501 err.extended_code
502 }
503 err => {
504 *err_msg = alloc(&err.to_string());
505 ffi::SQLITE_ERROR
506 }
507 }
508}