1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
use crate::{Migration, Report};
use std::fmt;
use std::path::PathBuf;
use thiserror::Error as TError;
#[derive(Debug)]
pub struct Error {
kind: Kind,
report: Option<Report>,
}
impl Error {
pub(crate) fn new(kind: Kind, report: Option<Report>) -> Error {
Error { kind, report }
}
pub fn report(&self) -> Option<&Report> {
self.report.as_ref()
}
pub fn kind(&self) -> &Kind {
&self.kind
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.kind)
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
self.kind.source()
}
}
#[derive(Debug, TError)]
pub enum Kind {
#[error("migration name must be in the format V{{number}}__{{name}}")]
InvalidName,
#[error("migration version must be a valid integer")]
InvalidVersion,
#[error("applied migration {0} is different than filesystem one {1}")]
DivergentVersion(Migration, Migration),
#[error("migration {0} is missing from the filesystem")]
MissingVersion(Migration),
#[error("invalid migrations path {0}, {1}")]
InvalidMigrationPath(PathBuf, std::io::Error),
#[error("Error parsing config: {0}")]
ConfigError(String),
#[error("`{0}`, `{1}`")]
Connection(String, #[source] Box<dyn std::error::Error + Sync + Send>),
}
pub trait WrapMigrationError<T, E> {
fn migration_err(self, msg: &str, report: Option<&Vec<Migration>>) -> Result<T, Error>;
}
impl<T, E> WrapMigrationError<T, E> for Result<T, E>
where
E: std::error::Error + Send + Sync + 'static,
{
fn migration_err(
self,
msg: &str,
applied_migrations: Option<&Vec<Migration>>,
) -> Result<T, Error> {
match self {
Ok(report) => Ok(report),
Err(err) => Err(Error {
kind: Kind::Connection(msg.into(), Box::new(err)),
report: applied_migrations.map(|am| Report::new(am.clone())),
}),
}
}
}