pub mod query; pub mod rows; pub mod part; pub mod types; use anyhow::Context; use sqlx::{PgConnection, PgPool, Postgres}; use sqlx::migrate::Migrator; use sqlx::postgres::{PgArguments, PgConnectOptions, PgPoolOptions, PgQueryResult}; use sqlx::query::Query; pub struct CoveDB { pg_connect_options: PgConnectOptions, db_pool: PgPool, } impl CoveDB { pub async fn new(host: &str, port: u16, username: &str, password: &str, database: &str) -> Result { let pg_connect_options = ::Options::new() .host(host) .port(port) .username(username) .password(password) .database(database); let db_pool = CoveDB::create_pool(10, pg_connect_options.clone()).await?; let db = CoveDB { pg_connect_options, db_pool }; Ok(db) } async fn create_pool(max_connections: u32, options: PgConnectOptions) -> Result { PgPoolOptions::new() .max_connections(max_connections) .connect_with(options) .await .context("Failed to create database connection") } pub async fn run_migrations(&self) -> Result<(), anyhow::Error> { let m = Migrator::new(std::path::Path::new("./migrations")).await?; m.run(&self.db_pool).await?; Ok(()) } pub async fn run_system_migrations(&self) -> Result<(), anyhow::Error> { let m = Migrator::new(std::path::Path::new("./system-migrations")).await?; let db_pool = CoveDB::create_pool(5, self.pg_connect_options.clone().database("postgres")).await?; m.run(&db_pool).await?; Ok(()) } } impl CoveDBImpl for CoveDB { fn get_pool(&self) -> &PgPool { &self.db_pool } } pub trait CoveDBImpl { fn get_pool(&self) -> &PgPool; async fn run_query>(&self, query: Query<'_, Postgres, PgArguments>) -> Result { let result = query.execute(self.get_pool()) .await .context("Failed to execute query")?; Ok(result.into()) } }