Initial
This commit is contained in:
13
crates/erplt-db/Cargo.toml
Normal file
13
crates/erplt-db/Cargo.toml
Normal file
@@ -0,0 +1,13 @@
|
||||
[package]
|
||||
name = "erplt-db"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
erplt-config.path = "../erplt-config"
|
||||
diesel.workspace = true
|
||||
diesel_migrations.workspace = true
|
||||
serde.workspace = true
|
||||
toml.workspace = true
|
||||
anyhow.workspace = true
|
||||
tracing.workspace = true
|
||||
6
crates/erplt-db/src/lib.rs
Normal file
6
crates/erplt-db/src/lib.rs
Normal file
@@ -0,0 +1,6 @@
|
||||
mod models;
|
||||
mod pool;
|
||||
// pub mod schema;
|
||||
mod migrations;
|
||||
|
||||
pub use pool::{DbPool, connect, DbConnection};
|
||||
17
crates/erplt-db/src/migrations.rs
Normal file
17
crates/erplt-db/src/migrations.rs
Normal file
@@ -0,0 +1,17 @@
|
||||
use anyhow::Context;
|
||||
use diesel_migrations::{EmbeddedMigrations, MigrationHarness, embed_migrations};
|
||||
|
||||
|
||||
const MIGRATIONS: EmbeddedMigrations = embed_migrations!("../../migrations");
|
||||
|
||||
pub fn run_migrations(pool: &crate::DbPool) -> anyhow::Result<usize> {
|
||||
let mut connection = pool
|
||||
.get()
|
||||
.context("Failed to get database connection for migrations")?;
|
||||
|
||||
connection
|
||||
.run_pending_migrations(MIGRATIONS)
|
||||
.map(|migrations| migrations.len())
|
||||
.map_err(|e| anyhow::anyhow!(e) )
|
||||
.context("Failed to run database migrations")
|
||||
}
|
||||
0
crates/erplt-db/src/models/mod.rs
Normal file
0
crates/erplt-db/src/models/mod.rs
Normal file
30
crates/erplt-db/src/pool.rs
Normal file
30
crates/erplt-db/src/pool.rs
Normal file
@@ -0,0 +1,30 @@
|
||||
use anyhow::Context;
|
||||
use diesel::r2d2::ConnectionManager;
|
||||
|
||||
pub type DbBackend = diesel::pg::Pg;
|
||||
pub type DbConnection = diesel::PgConnection;
|
||||
pub type DbPool = diesel::r2d2::Pool<
|
||||
diesel::r2d2::ConnectionManager<DbConnection>
|
||||
>;
|
||||
|
||||
pub fn connect(url: &str) -> anyhow::Result<DbPool> {
|
||||
let config= erplt_config::Config::get();
|
||||
let manager = ConnectionManager::<DbConnection>::new(url);
|
||||
|
||||
tracing::info!("Creating database pool at {}", config.database.connect_url_redacted());
|
||||
|
||||
let pool = DbPool::builder()
|
||||
.max_size(config.database.max_pool_size)
|
||||
.min_idle(Some(config.database.min_idle))
|
||||
.connection_timeout(config.database.connection_timeout)
|
||||
.idle_timeout(Some(config.database.idle_timeout))
|
||||
.max_lifetime(Some(config.database.max_lifetime))
|
||||
.test_on_check_out(config.database.test_on_check_out)
|
||||
.build(manager)
|
||||
.context("Failed to create database connection pool")?;
|
||||
|
||||
pool.get()
|
||||
.context("Failed to connect to PostgreSQL")?;
|
||||
tracing::info!("Connected to database");
|
||||
Ok(pool)
|
||||
}
|
||||
Reference in New Issue
Block a user