use std::fmt;
use sqlx::migrate::MigrateError;
use thiserror::Error;
use crate::{
db::MigrationFailureKind,
result::{ClassifyError, Diagnostic, DiagnosticKind, ErrorDescriptor, ErrorKind},
};
#[derive(Error)]
#[non_exhaustive]
pub enum SqlitePoolError {
#[error("SQLite operation failed")]
Sqlx(#[from] sqlx::Error),
}
impl fmt::Debug for SqlitePoolError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("SqlitePoolError")
.field("error_code", &self.error_code())
.field("source", &"[REDACTED]")
.finish()
}
}
impl ClassifyError for SqlitePoolError {
fn error_kind(&self) -> ErrorKind {
ErrorKind::Dependency
}
fn error_code(&self) -> crate::result::ErrorCode {
crate::result::ErrorCode::internal("sqlite_unavailable")
}
}
#[derive(Error)]
#[non_exhaustive]
pub enum SqliteBootstrapError {
#[error("migrate_on_startup requires a SQLx migrator")]
MissingMigrator,
#[error("failed to connect to SQLite: {diagnosis}")]
Connect {
diagnosis: SqliteDiagnostic,
#[source]
source: Box<SqlitePoolError>,
},
#[error("failed to run SQLite migrations: {diagnosis}")]
Migration {
diagnosis: SqliteDiagnostic,
kind: MigrationFailureKind,
#[source]
source: Box<MigrateError>,
},
}
impl fmt::Debug for SqliteBootstrapError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("SqliteBootstrapError")
.field("error_code", &self.error_code())
.field("diagnosis", &self.diagnosis())
.field("source", &"[REDACTED]")
.finish()
}
}
impl ClassifyError for SqliteBootstrapError {
fn error_kind(&self) -> ErrorKind {
match self {
Self::MissingMigrator => ErrorKind::Validation,
Self::Connect { .. } | Self::Migration { .. } => ErrorKind::Dependency,
}
}
fn error_code(&self) -> crate::result::ErrorCode {
crate::result::ErrorCode::internal(match self {
Self::MissingMigrator => "sqlite_migrator_required",
Self::Connect { .. } => "sqlite_connect_failed",
Self::Migration { .. } => "sqlite_migration_failed",
})
}
fn error_descriptor(&self) -> ErrorDescriptor {
ErrorDescriptor::new(self.error_kind(), self.error_code(), self.to_string())
.with_retryable(self.diagnosis().is_some_and(SqliteDiagnostic::retryable))
}
}
impl SqliteBootstrapError {
#[must_use]
pub const fn diagnosis(&self) -> Option<&SqliteDiagnostic> {
match self {
Self::Connect { diagnosis, .. } | Self::Migration { diagnosis, .. } => Some(diagnosis),
Self::MissingMigrator => None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum SqliteOperation {
Connect,
Migrate,
}
impl SqliteOperation {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Connect => "connect",
Self::Migrate => "migrate",
}
}
}
impl fmt::Display for SqliteOperation {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum SqliteDiagnosticKind {
InvalidConfiguration,
DatabaseMissing,
PermissionDenied,
DatabaseBusy,
StorageExhausted,
DatabaseCorrupt,
ConstraintViolation,
PoolExhausted,
Unavailable,
MigrationSourceInvalid,
MigrationMissing,
MigrationChecksumMismatch,
MigrationDirty,
MigrationVersionConflict,
MigrationExecutionFailed,
Unknown,
}
impl SqliteDiagnosticKind {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::InvalidConfiguration => "invalid_configuration",
Self::DatabaseMissing => "database_missing",
Self::PermissionDenied => "permission_denied",
Self::DatabaseBusy => "database_busy",
Self::StorageExhausted => "storage_exhausted",
Self::DatabaseCorrupt => "database_corrupt",
Self::ConstraintViolation => "constraint_violation",
Self::PoolExhausted => "pool_exhausted",
Self::Unavailable => "unavailable",
Self::MigrationSourceInvalid => "migration_source_invalid",
Self::MigrationMissing => "migration_missing",
Self::MigrationChecksumMismatch => "migration_checksum_mismatch",
Self::MigrationDirty => "migration_dirty",
Self::MigrationVersionConflict => "migration_version_conflict",
Self::MigrationExecutionFailed => "migration_execution_failed",
Self::Unknown => "unknown",
}
}
}
impl From<SqliteDiagnosticKind> for DiagnosticKind {
fn from(value: SqliteDiagnosticKind) -> Self {
match value {
SqliteDiagnosticKind::InvalidConfiguration => Self::InvalidConfiguration,
SqliteDiagnosticKind::DatabaseMissing | SqliteDiagnosticKind::MigrationMissing => {
Self::ResourceMissing
}
SqliteDiagnosticKind::PermissionDenied => Self::PermissionDenied,
SqliteDiagnosticKind::DatabaseBusy => Self::ResourceConflict,
SqliteDiagnosticKind::StorageExhausted | SqliteDiagnosticKind::PoolExhausted => {
Self::CapacityExhausted
}
SqliteDiagnosticKind::DatabaseCorrupt
| SqliteDiagnosticKind::MigrationChecksumMismatch
| SqliteDiagnosticKind::MigrationDirty
| SqliteDiagnosticKind::MigrationVersionConflict => Self::StateMismatch,
SqliteDiagnosticKind::Unavailable => Self::Unavailable,
SqliteDiagnosticKind::ConstraintViolation
| SqliteDiagnosticKind::MigrationSourceInvalid
| SqliteDiagnosticKind::MigrationExecutionFailed => Self::ExecutionFailed,
SqliteDiagnosticKind::Unknown => Self::Unknown,
}
}
}
impl fmt::Display for SqliteDiagnosticKind {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
}
}
#[derive(Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct SqliteDiagnostic {
operation: SqliteOperation,
kind: SqliteDiagnosticKind,
message: String,
hint: String,
retryable: bool,
}
impl fmt::Debug for SqliteDiagnostic {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("SqliteDiagnostic")
.field("operation", &self.operation)
.field("kind", &self.kind)
.field("message", &"[REDACTED]")
.field("hint", &"[REDACTED]")
.field("retryable", &self.retryable)
.finish()
}
}
impl SqliteDiagnostic {
#[must_use]
pub fn new(
operation: SqliteOperation,
kind: SqliteDiagnosticKind,
message: impl Into<String>,
hint: impl Into<String>,
retryable: bool,
) -> Self {
Self {
operation,
kind,
message: message.into(),
hint: hint.into(),
retryable,
}
}
#[must_use]
pub const fn operation(&self) -> SqliteOperation {
self.operation
}
#[must_use]
pub const fn kind(&self) -> SqliteDiagnosticKind {
self.kind
}
#[must_use]
pub fn message(&self) -> &str {
&self.message
}
#[must_use]
pub fn hint(&self) -> &str {
&self.hint
}
#[must_use]
pub const fn retryable(&self) -> bool {
self.retryable
}
#[must_use]
pub fn to_diagnostic(&self) -> Diagnostic {
self.clone().into()
}
}
impl fmt::Display for SqliteDiagnostic {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
formatter,
"{} during {}: {}; hint: {}",
self.kind, self.operation, self.message, self.hint
)
}
}
impl From<SqliteDiagnostic> for Diagnostic {
fn from(value: SqliteDiagnostic) -> Self {
Self::new(
"sqlite",
value.operation.as_str(),
DiagnosticKind::from(value.kind),
value.message,
)
.with_retryable(value.retryable)
.with_remediation(value.hint)
}
}
impl From<&SqliteDiagnostic> for Diagnostic {
fn from(value: &SqliteDiagnostic) -> Self {
value.to_diagnostic()
}
}
#[must_use]
pub fn diagnose_sqlx_error(operation: SqliteOperation, error: &sqlx::Error) -> SqliteDiagnostic {
let (kind, message, hint, retryable) = match error {
sqlx::Error::Configuration(_) => (
SqliteDiagnosticKind::InvalidConfiguration,
"SQLite connection configuration is invalid",
"verify database_url syntax and SQLite connection options",
false,
),
sqlx::Error::Database(error) => classify_database_error(error.as_ref()),
sqlx::Error::Io(error) => classify_io_error(error.kind()),
sqlx::Error::PoolTimedOut => (
SqliteDiagnosticKind::PoolExhausted,
"timed out while acquiring a SQLite connection",
"increase acquire_timeout, shorten transactions, or review pool capacity",
true,
),
sqlx::Error::PoolClosed => (
SqliteDiagnosticKind::Unavailable,
"SQLite pool is closed",
"check application shutdown and pool ownership",
false,
),
_ => (
SqliteDiagnosticKind::Unknown,
"SQLite operation failed with an unclassified error",
"inspect application logs for the underlying SQLx error",
false,
),
};
SqliteDiagnostic::new(operation, kind, message, hint, retryable)
}
#[must_use]
pub fn diagnose_pool_error(
operation: SqliteOperation,
error: &SqlitePoolError,
) -> SqliteDiagnostic {
match error {
SqlitePoolError::Sqlx(source) => diagnose_sqlx_error(operation, source),
}
}
#[must_use]
pub fn diagnose_migration_error(error: &MigrateError) -> SqliteDiagnostic {
match error {
MigrateError::Execute(source) => {
let diagnosis = diagnose_sqlx_error(SqliteOperation::Migrate, source);
if diagnosis.kind != SqliteDiagnosticKind::Unknown {
return diagnosis;
}
migration_diagnostic(
SqliteDiagnosticKind::MigrationExecutionFailed,
"SQLite migration execution failed",
"inspect the failing SQL statement and migration ordering",
)
}
MigrateError::ExecuteMigration(source, version) => {
let diagnosis = diagnose_sqlx_error(SqliteOperation::Migrate, source);
if diagnosis.kind != SqliteDiagnosticKind::Unknown {
return diagnosis;
}
migration_diagnostic(
SqliteDiagnosticKind::MigrationExecutionFailed,
format!("SQLite migration version {version} failed"),
"inspect the failing SQL statement and migration ordering",
)
}
_ => diagnose_migration_kind(MigrationFailureKind::from_error(error)),
}
}
fn diagnose_migration_kind(kind: MigrationFailureKind) -> SqliteDiagnostic {
match kind {
MigrationFailureKind::Source => migration_diagnostic(
SqliteDiagnosticKind::MigrationSourceInvalid,
"failed to resolve SQLite migration sources",
"verify migration paths, file names, and embedded migration assets",
),
MigrationFailureKind::VersionMissing { version }
| MigrationFailureKind::VersionNotPresent { version } => migration_diagnostic(
SqliteDiagnosticKind::MigrationMissing,
format!("SQLite migration version {version} is missing from the application"),
"restore the migration or deploy a binary containing the complete migration history",
),
MigrationFailureKind::VersionMismatch { version } => migration_diagnostic(
SqliteDiagnosticKind::MigrationChecksumMismatch,
format!("SQLite migration version {version} was modified after being applied"),
"do not edit applied migrations; add a new migration instead",
),
MigrationFailureKind::Dirty { version } => migration_diagnostic(
SqliteDiagnosticKind::MigrationDirty,
format!("SQLite migration version {version} is partially applied"),
"repair the database deliberately before retrying migrations",
),
MigrationFailureKind::VersionTooOld { version, latest }
| MigrationFailureKind::VersionTooNew { version, latest } => migration_diagnostic(
SqliteDiagnosticKind::MigrationVersionConflict,
format!("SQLite migration version {version} conflicts with latest version {latest}"),
"deploy a binary whose migration history matches the database",
),
MigrationFailureKind::Execute | MigrationFailureKind::ExecuteMigration { .. } => {
migration_diagnostic(
SqliteDiagnosticKind::MigrationExecutionFailed,
"SQLite migration execution failed",
"inspect the failing SQL statement and migration ordering",
)
}
MigrationFailureKind::Unsupported | MigrationFailureKind::Unknown => migration_diagnostic(
SqliteDiagnosticKind::Unknown,
"SQLite migration failed with an unclassified error",
"inspect application logs for the underlying SQLx migration error",
),
}
}
fn migration_diagnostic(
kind: SqliteDiagnosticKind,
message: impl Into<String>,
hint: &'static str,
) -> SqliteDiagnostic {
SqliteDiagnostic::new(SqliteOperation::Migrate, kind, message, hint, false)
}
fn classify_database_error(
error: &dyn sqlx::error::DatabaseError,
) -> (SqliteDiagnosticKind, &'static str, &'static str, bool) {
let primary_code = error
.code()
.and_then(|code| code.parse::<i32>().ok())
.map(|code| code & 0xff);
match primary_code {
Some(5 | 6) => (
SqliteDiagnosticKind::DatabaseBusy,
"SQLite database is locked",
"shorten write transactions, serialize writers, or increase busy_timeout",
true,
),
Some(8) => (
SqliteDiagnosticKind::PermissionDenied,
"SQLite database is read-only",
"disable writes or grant write access to the database and its directory",
false,
),
Some(10) => (
SqliteDiagnosticKind::Unavailable,
"SQLite storage I/O failed",
"check the database file, containing directory, and storage health",
true,
),
Some(11 | 26) => (
SqliteDiagnosticKind::DatabaseCorrupt,
"SQLite database is corrupt or has an invalid format",
"restore a verified backup or run an explicit SQLite recovery procedure",
false,
),
Some(13) => (
SqliteDiagnosticKind::StorageExhausted,
"SQLite storage is full",
"free storage space and verify filesystem quotas",
true,
),
Some(14) => (
SqliteDiagnosticKind::Unavailable,
"SQLite could not open a database or temporary file",
"verify file paths, directory permissions, and the create_if_missing setting",
false,
),
Some(19) => (
SqliteDiagnosticKind::ConstraintViolation,
"SQLite rejected an operation because a constraint was violated",
"validate application data and transaction ordering",
false,
),
_ => (
SqliteDiagnosticKind::Unknown,
"SQLite returned an unclassified database error",
"inspect application logs for the underlying SQLite error code",
false,
),
}
}
fn classify_io_error(
kind: std::io::ErrorKind,
) -> (SqliteDiagnosticKind, &'static str, &'static str, bool) {
match kind {
std::io::ErrorKind::NotFound => (
SqliteDiagnosticKind::DatabaseMissing,
"SQLite database path does not exist",
"create the containing directory and enable create_if_missing when intended",
false,
),
std::io::ErrorKind::PermissionDenied => (
SqliteDiagnosticKind::PermissionDenied,
"SQLite database path is not accessible",
"grant access to the database file and its containing directory",
false,
),
std::io::ErrorKind::TimedOut
| std::io::ErrorKind::Interrupted
| std::io::ErrorKind::WouldBlock => (
SqliteDiagnosticKind::Unavailable,
"SQLite storage is temporarily unavailable",
"retry after checking storage availability and lock contention",
true,
),
_ => (
SqliteDiagnosticKind::Unavailable,
"SQLite storage I/O failed",
"check the database file, containing directory, and storage health",
false,
),
}
}