Skip to content

Commit

Permalink
refactor db & add database test
Browse files Browse the repository at this point in the history
  • Loading branch information
FrozenArcher committed Feb 23, 2024
1 parent 3370bed commit 6201e09
Show file tree
Hide file tree
Showing 6 changed files with 69 additions and 12 deletions.
44 changes: 40 additions & 4 deletions src/db.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
use crate::config::AppConfig;
use derive_more::{Display, Error};
use log::info;
use sqlx::postgres::PgPoolOptions;
use sqlx::{Pool, Postgres};
use std::io;

#[derive(Clone)]
pub struct AppDB {
pub pool: Pool<Postgres>,
pub enum AppDB {
Postgres(Pool<Postgres>),
Mock,
}

impl AppDB {
pub async fn new(config: &AppConfig) -> io::Result<Self> {
pub async fn postgres(config: &AppConfig) -> io::Result<Self> {
let db_url = format!(
"postgres://{}:{}@{}/{}",
config.db_user, config.db_password, config.db_host, config.db_database
Expand All @@ -26,10 +28,44 @@ impl AppDB {
"connected to database {} at {}",
config.db_database, config.db_host
);
Ok(AppDB { pool })
Ok(Self::Postgres(pool))
} else {
let msg = format!("failed to connect to database, config {:?}", config);
Err(io::Error::other(msg))
}
}
pub fn mock() -> Self {
Self::Mock
}
}

impl AppDB {
pub async fn test_db(&self) -> DBResult<()> {
match self {
Self::Postgres(pool) => {
let row: (i64,) = sqlx::query_as("SELECT $1")
.bind(150_i64)
.fetch_one(pool)
.await?;

assert_eq!(row.0, 150);
Ok(())
}
_ => Err(DBError::Unimplemented),
}
}
}

pub type DBResult<T> = std::result::Result<T, DBError>;

#[derive(Debug, Error, Display)]
pub enum DBError {
SqlxError(sqlx::Error),
Unimplemented,
}

impl From<sqlx::Error> for DBError {
fn from(err: sqlx::Error) -> Self {
Self::SqlxError(err)
}
}
2 changes: 1 addition & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ pub struct AppState {

impl AppState {
pub async fn new(config: &AppConfig) -> std::io::Result<AppState> {
let db = AppDB::new(&config).await?;
let db = AppDB::postgres(&config).await?;
Ok(AppState { db })
}
}
Expand Down
9 changes: 2 additions & 7 deletions src/misc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,6 @@ pub async fn test_invalid() -> AppResult<()> {

#[get("/db")]
pub async fn test_db(data: web::Data<AppState>) -> AppResult<&'static str> {
let row: (i64,) = sqlx::query_as("SELECT $1")
.bind(150_i64)
.fetch_one(&data.db.pool)
.await?;

assert_eq!(row.0, 150);
AppResponse::Success("success").response()
data.db.test_db().await?;
AppResponse::Success("Test for db is success").response()
}
9 changes: 9 additions & 0 deletions src/response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ use derive_more::{Display, Error};
use log::warn;
use serde::Serialize;

use crate::db::DBError;

/// Result type returned by handler functions.
pub type AppResult<T> = actix_web::Result<web::Json<OkModel<T>>, AppError>;

Expand Down Expand Up @@ -64,6 +66,13 @@ impl From<sqlx::Error> for AppError {
}
}

impl From<DBError> for AppError {
fn from(err: DBError) -> Self {
warn!("{}", err);
Self::InternalError
}
}

/// App response types
///
/// # Examples
Expand Down
16 changes: 16 additions & 0 deletions src/tests/database.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
use crate::db::{AppDB, DBError};

#[actix_rt::test]
async fn test_db() {
let db = AppDB::mock();
let res = db.test_db().await;
if let Err(e) = res {
if let DBError::Unimplemented = e {
// test success
} else {
panic!("Error should be `Unimplemented`, got {}", e)
}
} else {
panic!("`db.test_db().await` should be `Err(Unimplemented)`, not `Ok()`.")
}
}
1 change: 1 addition & 0 deletions src/tests/mod.rs
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
mod database;
mod response;

0 comments on commit 6201e09

Please sign in to comment.