/
mcmare
/
RustAPI
Обзор
Документация
Войти
/
mcmare
/
RustAPI
Код
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
main
engine/src/db/mod.rs
94 строки
3 KB
mcmare
Add multi-DB CRUD engine: pooled connections, auto table creation, create/read/list/update/delete
18 июл 2026, 16:21
18 июл 2026, 16:21
c40e4bc
Код
Авторство
О чём код?
pub mod crud; mod schema; use anyhow::{Context, Result}; use sqlx::{ mysql::MySqlPoolOptions, postgres::PgPoolOptions, sqlite::{SqliteConnectOptions, SqlitePoolOptions}, MySqlPool, PgPool, SqlitePool, }; use std::{collections::HashMap, str::FromStr}; use crate::config::{ConnectionDef, DbDriver, EndpointDef, EndpointKind}; #[derive(Clone)] pub enum DbPool { Postgres(PgPool), MySql(MySqlPool), Sqlite(SqlitePool), } impl DbPool { async fn connect(def: &ConnectionDef) -> Result<Self> { Ok(match def.driver { DbDriver::Postgres => DbPool::Postgres( PgPoolOptions::new() .connect(&def.url) .await .context("failed to connect")?, ), DbDriver::MySql => DbPool::MySql( MySqlPoolOptions::new() .connect(&def.url) .await .context("failed to connect")?, ), DbDriver::Sqlite => { let options = SqliteConnectOptions::from_str(&def.url) .context("invalid sqlite url")? .create_if_missing(true); DbPool::Sqlite( SqlitePoolOptions::new() .connect_with(options) .await .context("failed to connect")?, ) } }) } pub async fn ping(&self) -> bool { match self { DbPool::Postgres(p) => sqlx::query("SELECT 1").execute(p).await.is_ok(), DbPool::MySql(p) => sqlx::query("SELECT 1").execute(p).await.is_ok(), DbPool::Sqlite(p) => sqlx::query("SELECT 1").execute(p).await.is_ok(), } } } /// Connects every declared connection eagerly so config errors surface at startup. pub async fn connect_all(connections: &HashMap<String, ConnectionDef>) -> Result<HashMap<String, DbPool>> { let mut pools = HashMap::with_capacity(connections.len()); for (name, def) in connections { let pool = DbPool::connect(def) .await .with_context(|| format!("connection '{name}'"))?; pools.insert(name.clone(), pool); } Ok(pools) } /// Runs `CREATE TABLE IF NOT EXISTS` for every CRUD endpoint's table, derived from its /// output schema. Does not diff/alter existing tables — an operator-managed table with a /// different shape is left untouched. pub async fn ensure_tables(endpoints: &[EndpointDef], pools: &HashMap<String, DbPool>) -> Result<()> { for ep in endpoints { if let EndpointKind::Crud { connection, table, primary_key, output, .. } = &ep.kind { let pool = pools .get(connection) .expect("connection existence already validated at config load"); schema::ensure_table(pool, table, primary_key, output) .await .with_context(|| format!("{}: auto-create table '{table}'", ep.source_file.display()))?; } } Ok(()) }