Crate baichun_framework_db

Crate baichun_framework_db 

Source
Expand description

§baichun-framework-db

baichun-framework-db 是一个基于 SQLx 的数据库访问层,提供了简单而强大的数据库操作接口。 支持 MySQL、PostgreSQL 和 SQLite 数据库,并提供了连接池管理、事务支持等功能。

§主要功能

  • 连接池管理:自动配置最佳连接数,支持连接健康检查和超时处理
  • 多数据库支持:MySQL、PostgreSQL、SQLite
  • 异步操作:基于 tokio 的异步运行时
  • 事务支持:自动事务管理,支持嵌套事务
  • 错误处理:详细的错误类型和追踪

§快速开始

use baichun_framework_db::{DatabaseConfig, init, get_pool};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // 创建数据库配置
    let config = DatabaseConfig::new()
        .url("mysql://user:pass@localhost/db_name")
        .max_connections(10)
        .min_connections(5);

    // 初始化数据库连接池
    init(config).await?;

    // 获取连接池实例
    let pool = get_pool();

    // 执行查询
    let rows = pool.execute("SELECT * FROM users WHERE id = ?", &[&1]).await?;

    Ok(())
}

Re-exports§

pub use config::DatabaseConfig;
pub use error::Error as DbError;
pub use error::Result as DbResult;
pub use executor::Executor;
pub use executor::TransactionManager;
pub use pool::get_pool;
pub use pool::init;
pub use pool::DbMetrics;
pub use pool::DbPool;
pub use pool::DB_POOL;

Modules§

config
数据库配置模块
error
数据库错误处理模块
executor
数据库执行器模块
pool
数据库连接池模块