From e437cfc717417891486a77af469d134c6bf5dbdd Mon Sep 17 00:00:00 2001 From: Teddy Wing Date: Sun, 30 May 2021 02:05:55 +0200 Subject: database: Use a custom `Error` type Get rid of the boxed errors to make matching on errors easier. --- Cargo.lock | 1 + Cargo.toml | 1 + src/database.rs | 28 ++++++++++++++-------------- 3 files changed, 16 insertions(+), 14 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 3308487..74750ec 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1007,6 +1007,7 @@ dependencies = [ "reqwest", "serde", "sqlx", + "thiserror", "tokio", ] diff --git a/Cargo.toml b/Cargo.toml index 182ccdf..4099777 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,6 +7,7 @@ edition = "2018" git2 = "0.13.20" reqwest = { version = "0.11.3", features = ["blocking", "json"] } serde = { version = "1.0.126", features = ["derive"] } +thiserror = "1.0.25" tokio = { version = "1.6.1", features = ["macros", "rt"] } [dependencies.sqlx] diff --git a/src/database.rs b/src/database.rs index 954f6b3..085494e 100644 --- a/src/database.rs +++ b/src/database.rs @@ -1,4 +1,5 @@ use sqlx::{self, ConnectOptions, Connection, Executor, Row}; +use thiserror; use crate::github; @@ -21,15 +22,20 @@ impl From for Repo { } +#[derive(Debug, thiserror::Error)] +pub enum Error { + #[error("database error")] + Db(#[from] sqlx::Error), +} + + #[derive(Debug)] pub struct Db { connection: sqlx::SqliteConnection, } impl Db { - pub async fn connect( - path: &str, - ) -> Result> { + pub async fn connect(path: &str) -> Result { Ok( Db { connection: sqlx::sqlite::SqliteConnectOptions::new() @@ -41,7 +47,7 @@ impl Db { ) } - pub async fn create(&mut self) -> Result<(), Box> { + pub async fn create(&mut self) -> Result<(), Error> { let mut tx = self.connection.begin().await?; tx.execute(r#" @@ -62,10 +68,7 @@ impl Db { Ok(()) } - pub async fn repo_get( - &mut self, - id: i64, - ) -> Result> { + pub async fn repo_get(&mut self, id: i64) -> Result { let mut tx = self.connection.begin().await?; // NOTE: Returns `RowNotFound` if not found. @@ -85,10 +88,7 @@ impl Db { ) } - pub async fn repo_insert( - &mut self, - repo: Repo, - ) -> Result<(), Box> { + pub async fn repo_insert(&mut self, repo: Repo) -> Result<(), Error> { let mut tx = self.connection.begin().await?; sqlx::query(r#" @@ -108,12 +108,12 @@ impl Db { Ok(()) } - pub fn repo_is_updated() -> Result> { + pub fn repo_is_updated() -> Result { // select id from repositories where updated_at > datetime("2020-07-13T17:57:56Z"); Ok(false) } - pub fn repo_update(repo: &Repo) -> Result<(), Box> { + pub fn repo_update(repo: &Repo) -> Result<(), Error> { Ok(()) } } -- cgit v1.2.3