Skip to content

Commit

Permalink
add doc for mod db
Browse files Browse the repository at this point in the history
  • Loading branch information
FrozenArcher committed Feb 24, 2024
1 parent 8c4ce29 commit 1592c96
Showing 1 changed file with 16 additions and 4 deletions.
20 changes: 16 additions & 4 deletions src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,19 @@ use derive_more::{Display, Error};
use log::info;
use sqlx::postgres::PgPoolOptions;
use sqlx::{Pool, Postgres};
use std::io;

/// `AppDB` represents for the database in use.
#[derive(Clone)]
pub enum AppDB {
Postgres(Pool<Postgres>),
/// Connect to a postgresql database.
Postgres(Pool<Postgres>), // Or any other database you use.
/// Manually return data.
Mock,
}

impl AppDB {
pub async fn postgres(config: &AppConfig) -> io::Result<Self> {
/// Generates a database connection to postgresql
pub async fn postgres(config: &AppConfig) -> std::io::Result<Self> {
let db_url = format!(
"postgres://{}:{}@{}/{}",
config.db_user, config.db_password, config.db_host, config.db_database
Expand All @@ -31,15 +34,21 @@ impl AppDB {
Ok(Self::Postgres(pool))
} else {
let msg = format!("failed to connect to database, config {:?}", config);
Err(io::Error::other(msg))
Err(std::io::Error::other(msg))
}
}

/// Does not connect to any database.
///
/// Any data is generated by hand.
pub fn mock() -> Self {
Self::Mock
}
}

// Example implementation to a database operation.
impl AppDB {
/// Tests whether the connection is successful.
pub async fn test_db(&self) -> DBResult<()> {
match self {
Self::Postgres(pool) => {
Expand All @@ -51,13 +60,16 @@ impl AppDB {
assert_eq!(row.0, 150);
Ok(())
}
// Does not implement for `Mock`
_ => Err(DBError::Unimplemented),
}
}
}

/// `DBResult` is used in database operation methods.
pub type DBResult<T> = std::result::Result<T, DBError>;

/// `DBError` represents for all the possible errors that may occur in a database operation.
#[derive(Debug, Error, Display)]
pub enum DBError {
SqlxError(sqlx::Error),
Expand Down

0 comments on commit 1592c96

Please sign in to comment.