This commit is contained in:
2026-09-07 22:47:34 +03:00
commit 3fcee5ea9a
27 changed files with 1849 additions and 0 deletions

View 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

View File

@@ -0,0 +1,6 @@
mod models;
mod pool;
// pub mod schema;
mod migrations;
pub use pool::{DbPool, connect, DbConnection};

View 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")
}

View File

View 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)
}