error.rs
Overview
This file defines error handling constructs for interfacing with SQLite, encapsulating SQLite error codes and extended error codes into Rust-friendly types and messages. It provides an ErrorCode enumeration that represents various SQLite error conditions, an Error struct that holds both a primary error code and an extended error code, and utility functions for mapping numeric SQLite error codes to human-readable descriptions. Additionally, it optionally defines an InitError enumeration for loadable extension initialization errors, conditional on the loadable_extension feature.
The file's primary purpose is to convert raw SQLite error codes into strongly-typed Rust errors with descriptive messages, facilitating robust error management in database operations.
Enumerations and Structs
ErrorCode
An enum representing the canonical set of SQLite error codes.
Variants include:
InternalMalfunction: Internal logic error in SQLitePermissionDenied: Access permission deniedOperationAborted: Callback routine requested an abortDatabaseBusy: The database file is lockedDatabaseLocked: A table in the database is lockedOutOfMemory: Amalloc()failedReadOnly: Attempt to write a readonly databaseOperationInterrupted: Operation terminated by sqlite3_interrupt()SystemIoFailure: Some kind of disk I/O error occurredDatabaseCorrupt: The database disk image is malformedNotFound: Unknown opcode in sqlite3_file_control()DiskFull: Insertion failed because database is fullCannotOpen: Unable to open the database fileFileLockingProtocolFailed: Database lock protocol errorSchemaChanged: The database schema changedTooBig: String or BLOB exceeds size limitConstraintViolation: Abort due to constraint violationTypeMismatch: Data type mismatchApiMisuse: Library used incorrectlyNoLargeFileSupport: Uses OS features not supported on hostAuthorizationForStatementDenied: Authorization deniedParameterOutOfRange: 2nd parameter to sqlite3_bind out of rangeNotADatabase: File opened that is not a database fileUnknown: Fallback for unknown error codes
Attributes:
Error
A struct that represents a SQLite error, combining the main error code and the extended error code.
Fields:
code: ErrorCode— The primary error category.extended_code: c_int— The raw SQLite extended error code (including subcode information).
Methods:
pub fn new(result_code: c_int) -> SelfConstructs an
Errorfrom a raw SQLite result code integer. It masks the lower 8 bits to map to the primaryErrorCode, while preserving the full extended code.Parameters:
result_code: The SQLite error code integer.
Returns:
An
Errorinstance representing the mapped error.
Usage example:
let err = Error::new(sqlite_result_code); println!("Error: {}", err);
Trait Implementations:
fmt::Display— Formats the error for human-readable output, showing the extended code and its string description.error::Error— Implements the standard error trait with adescription()method that returns the error description string.
Functions
code_to_str
pub fn code_to_str(code: c_int) -> &'static str
Maps an SQLite raw error code (including extended codes) to a static string description.
Parameters:
code: The integer SQLite error code or extended code.
Returns:
A string slice describing the error.
Notes:
Contains a comprehensive match arm with mappings for all known SQLite error codes and extended codes.
Returns
"Unknown error code"for unrecognized codes.
Example:
let description = code_to_str(sqlite_code);
println!("Error description: {}", description);
Loadable Extension Error Handling (Feature-gated)
InitError
Defined only if the loadable_extension feature is enabled.
An enum representing errors during loadable SQLite extension initialization.
Variants:
VersionMismatch { compile_time: i32, runtime: i32 }Indicates a version mismatch between the extension compiled time and the runtime SQLite library.
NullFunctionPointerIndicates one or more null function pointers in
sqlite3_api_routines.
Trait Implementations:
fmt::Display— Provides formatted error messages for each variant.error::Error— Implements the standard error trait.
Implementation Details and Algorithms
The
Error::newmethod isolates the primary error code by masking the low 8 bits of the extended SQLite result code (result_code & 0xff). This matches SQLite's error code conventions where the lower 8 bits represent the basic error category and the higher bits encode extended error information.Extended error codes are defined in this file as constants (e.g.,
SQLITE_IOERR_BEGIN_ATOMIC) by combining the base error code with shifted values to create subcodes. These constants are used in thecode_to_strfunction to provide descriptive error messages.The
code_to_strfunction uses a largematchstatement to translate both primary and extended SQLite error codes to human-readable descriptions. This is essential for debugging and user feedback.The
Errorstruct stores both the base and extended codes, enabling more granular error handling if needed.
Interaction with Other Parts of the System
The error codes (
SQLITE_INTERNAL,SQLITE_PERM, etc.) are imported from a sibling module or the parent module (super::). This file relies on those constants being defined elsewhere, likely in bindings generated from SQLite's C headers.The
Errorstruct and related enums are intended to be used throughout the project wherever SQLite operations occur, providing consistent error handling and messaging.The
InitErrorenum integrates with the loadable extension feature, which is an advanced SQLite capability allowing runtime loading of extensions. This ties into dynamic function pointers and API structure validation.The test module verifies the correctness of the
Error::newconstructor by asserting that given SQLite codes map to the expectedErrorCodevariants and that the formatted string representations are non-empty.
Visual Diagram: Error Handling Structure
classDiagram
class ErrorCode {
<<enum>>
+InternalMalfunction
+PermissionDenied
+OperationAborted
+DatabaseBusy
+DatabaseLocked
+OutOfMemory
+ReadOnly
+OperationInterrupted
+SystemIoFailure
+DatabaseCorrupt
+NotFound
+DiskFull
+CannotOpen
+FileLockingProtocolFailed
+SchemaChanged
+TooBig
+ConstraintViolation
+TypeMismatch
+ApiMisuse
+NoLargeFileSupport
+AuthorizationForStatementDenied
+ParameterOutOfRange
+NotADatabase
+Unknown
}
class Error {
+code: ErrorCode
+extended_code: c_int
+new()
+fmt::Display
+error::Error
}
class InitError {
<<enum>>
+VersionMismatch
+NullFunctionPointer
+fmt::Display
+error::Error
}
Error --> ErrorCode : has
Error ..> "code_to_str()" : uses
InitError <|-- (feature: loadable_extension)
Testing
The module
testcontains unit tests for validating theError::newfunction.It checks that various SQLite error codes correctly map to
ErrorCodevariants.Also verifies that the
Displayimplementation produces non-empty strings.This ensures the error mapping and formatting are functioning as expected.
Key References
For detailed SQLite error codes and their meanings, see SQLite Error Codes.
For Rust error handling conventions and traits, refer to Error Handling in Rust.
For loadable extension architecture and API, consult SQLite Loadable Extensions.