Skip to main content

Db

Struct Db 

Source
pub struct Db { /* private fields */ }
Expand description

Db 门面 —— 配置驱动的数据库访问入口

封装 PostgreSQL/MySQL/SQLite 三种后端,提供统一的 CRUD 接口。 通过 factory::create_db()DatabaseConfig 自动创建并连接测试。

§示例

let db = create_db(&config.database).await?;
let user = db.find_by_id("user", 1).await?;

Implementations§

Source§

impl Db

Source

pub fn postgres(pool: PgPool) -> Self

从 PostgreSQL 连接池创建 Db 实例

Source

pub fn mysql(pool: MySqlPool) -> Self

从 MySQL 连接池创建 Db 实例

Source

pub fn sqlite(pool: SqlitePool) -> Self

从 SQLite 连接池创建 Db 实例

Source

pub fn pg_pool(&self) -> &PgPool

获取 PostgreSQL 连接池引用(非 PG 则 panic)

Source

pub fn mysql_pool(&self) -> &MySqlPool

获取 MySQL 连接池引用(非 MySQL 则 panic)

Source

pub fn sqlite_pool(&self) -> &SqlitePool

获取 SQLite 连接池引用(非 SQLite 则 panic)

Source

pub async fn find_by_id( &self, table: &str, id: impl Into<Value>, ) -> DbResult<Option<Row>>

按主键 ID 查询单条记录(主键默认 id

自动识别 ID 类型(UUID / 整数 / 字符串),添加正确的 SQL 类型转换后缀。

§参数
  • table: 表名
  • id: 主键值(支持 i64&strUuid 等实现了 Into<Value> 的类型)
§返回值
  • Ok(Some(row)): 记录存在
  • Ok(None): 记录不存在
  • Err(_): 数据库错误
Source

pub async fn query_one( &self, sql: &str, params: &[&str], ) -> DbResult<Option<Row>>

执行原始 SQL 查询(单条),返回 Option<Row>

参数使用 $1$2 占位符,按顺序绑定。

Source

pub async fn query(&self, sql: &str, params: &[&str]) -> DbResult<Vec<Row>>

执行原始 SQL 查询(多条),返回 Vec<Row>

Source

pub async fn query_page( &self, sql: &str, params: &[&str], page: &PageQuery, ) -> DbResult<(Vec<Row>, u64)>

分页查询:自动包裹 COUNT 和 LIMIT/OFFSET

返回 (数据列表, 总条数)。传入的 SQL 应为无 LIMIT/OFFSET 的完整查询。

Source

pub async fn count(&self, sql: &str, params: &[&str]) -> DbResult<u64>

执行 COUNT 查询,返回行数(自动转换为 u64)

Source

pub async fn insert(&self, row: &Row) -> DbResult<Row>

插入单条记录(Row 需设置 table 和字段值)

PostgreSQL 使用 RETURNING * 直接返回插入后的完整行; MySQL/SQLite 插入后通过主键回查。

§错误
  • Row 缺少表名 → Argument 错误
  • 没有变更字段 → Argument 错误
Source

pub async fn batch_insert(&self, rows: &[Row]) -> DbResult<u64>

批量插入记录,返回受影响行数

所有 Row 必须来自同一张表且变更字段一致。

Source

pub async fn update(&self, row: &Row) -> DbResult<Option<Row>>

更新单条记录(根据 Row 的 changes 和主键)

仅更新 changes 中标记的字段,主键必须存在于 data 中。 PostgreSQL 使用 RETURNING * 返回更新后的行。

Source

pub async fn batch_update( &self, table: &str, sets: &Row, where_sql: &str, where_params: &[&str], ) -> DbResult<u64>

批量更新(按 WHERE 条件),返回受影响行数

  • sets: 要更新的字段值(Row 含 changes)
  • where_sql: WHERE 子句(不含 WHERE 关键字),参数使用 $1 占位符
  • where_params: WHERE 子句的参数值
Source

pub async fn delete_by_id( &self, table: &str, id: impl Into<Value>, ) -> DbResult<bool>

按主键删除记录,返回是否成功删除

Source

pub async fn batch_delete_by_ids( &self, table: &str, ids: &[impl AsRef<str>], ) -> DbResult<u64>

批量按主键删除,返回受影响行数

Source

pub async fn execute(&self, sql: &str, params: &[&str]) -> DbResult<u64>

执行 INSERT/UPDATE/DELETE 等写操作,返回受影响行数

Source

pub async fn transaction<F, Fut, T>(&self, f: F) -> DbResult<T>
where F: FnOnce(ActiveTx) -> Fut + Send, Fut: Future<Output = (ActiveTx, DbResult<T>)> + Send, T: Send,

在事务闭包中执行操作,自动 BEGIN/COMMIT/ROLLBACK

闭包返回 Ok 则 COMMIT,返回 Err 则 ROLLBACK。 可通过 ActiveTx::set_rollback_only() 强制回滚。

§示例
db.transaction(|mut tx| async move {
    let user = Row::table("user").id(1);
    tx.execute("UPDATE user SET name=$1 WHERE id=$2", &["Alice", "1"]).await?;
    (tx, Ok(()))
}).await?;

Trait Implementations§

Source§

impl Clone for Db

Source§

fn clone(&self) -> Db

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more

Auto Trait Implementations§

§

impl Freeze for Db

§

impl !RefUnwindSafe for Db

§

impl Send for Db

§

impl Sync for Db

§

impl Unpin for Db

§

impl UnsafeUnpin for Db

§

impl !UnwindSafe for Db

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more