Skip to main content

QueryBuilder

Struct QueryBuilder 

Source
pub struct QueryBuilder<'a> { /* private fields */ }
Expand description

查询构建器

Implementations§

Source§

impl<'a> QueryBuilder<'a>

Source

pub fn field(self, field: &str) -> Self

选择字段

Source

pub fn fields(self, fields: &[&str]) -> Self

选择多个字段

Source

pub fn json(self, field: &str) -> Self

标记字段为 JSON 类型

Source

pub fn datetime(self, field: &str) -> Self

标记字段为 DATETIME 类型

Source

pub fn timestamp(self, field: &str) -> Self

标记字段为 TIMESTAMP 类型

Source

pub fn decimal(self, field: &str) -> Self

标记字段为 DECIMAL 类型

Source

pub fn blob(self, field: &str) -> Self

标记字段为 BLOB 类型

Source

pub fn text(self, field: &str) -> Self

标记字段为 TEXT 类型

Source

pub fn distinct(self) -> Self

去重

Source

pub fn where_and<V>(self, field: &str, op: &str, value: V) -> Self
where V: Into<SqlValue>,

添加 AND 条件

Source

pub fn where_or<V>(self, field: &str, op: &str, value: V) -> Self
where V: Into<SqlValue>,

添加 OR 条件

Source

pub fn where_in<V>(self, field: &str, values: Vec<V>) -> Self
where V: Into<SqlValue>,

添加 IN 条件

Source

pub fn where_between<V>(self, field: &str, start: V, end: V) -> Self
where V: Into<SqlValue>,

添加 BETWEEN 条件

Source

pub fn join(self, table: &str, on: &str) -> Self

INNER JOIN

Source

pub fn left_join(self, table: &str, on: &str) -> Self

LEFT JOIN

Source

pub fn right_join(self, table: &str, on: &str) -> Self

RIGHT JOIN

Source

pub fn order(self, field: &str, asc: bool) -> Self

排序

Source

pub fn group(self, field: &str) -> Self

分组

Source

pub fn limit(self, limit: u64) -> Self

限制返回数量

Source

pub fn offset(self, offset: u64) -> Self

偏移量

Source

pub fn to_sql(&self) -> String

获取生成的 SQL(用于调试)

§返回
  • 生成的完整 SQL 语句字符串
Source

pub async fn find<T>(self) -> Result<Option<T>, DbError>
where T: for<'r> FromRow<'r, MySqlRow> + Send + Unpin,

查询单条记录

自动添加 LIMIT 1 到查询,返回单条记录或 None

§类型参数
  • T: 结果类型,必须实现 FromRow trait
§返回
  • Ok(Some(T)): 查询成功,返回单条记录
  • Ok(None): 查询成功,但没有匹配的记录
  • Err(DbError): 查询执行失败
§示例
use yang_db::Database;
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize, sqlx::FromRow)]
struct User {
    id: i32,
    name: String,
}

let db = Database::connect("mysql://root:password@localhost/test").await?;
let user: Option<User> = db.table("users")
    .where_and("id", "=", 1)
    .find()
    .await?;

match user {
    Some(u) => println!("找到用户: {:?}", u),
    None => println!("用户不存在"),
}
Source

pub async fn select<T>(self) -> Result<Vec<T>, DbError>
where T: for<'r> FromRow<'r, MySqlRow> + Send + Unpin,

查询多条记录

执行 SELECT 查询并返回所有匹配的记录

§类型参数
  • T: 结果类型,必须实现 FromRow trait
§返回
  • Ok(Vec): 查询成功,返回匹配的记录列表(可能为空)
  • Err(DbError): 查询执行失败
§示例
use yang_db::Database;
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize, sqlx::FromRow)]
struct User {
    id: i32,
    name: String,
}

let db = Database::connect("mysql://root:password@localhost/test").await?;
let users: Vec<User> = db.table("users")
    .where_and("status", "=", 1)
    .order("name", true)
    .select()
    .await?;

println!("找到 {} 个用户", users.len());
for user in users {
    println!("用户: {:?}", user);
}
Source

pub async fn value<T>(self, field: &str) -> Result<Option<T>, DbError>
where T: for<'r> Decode<'r, MySql> + Type<MySql> + Send + Unpin,

查询单个字段值

执行 SELECT 查询并返回指定字段的单个值。自动添加 LIMIT 1 到查询。

§参数
  • field: 要查询的字段名
§类型参数
  • T: 字段值类型,必须实现 sqlx::Decode 和 sqlx::Type trait
§返回
  • Ok(Some(T)): 查询成功,返回字段值
  • Ok(None): 查询成功,但没有匹配的记录
  • Err(DbError): 查询执行失败
§示例
use yang_db::Database;

let db = Database::connect("mysql://root:password@localhost/test").await?;

// 查询用户名
let name: Option<String> = db.table("users")
    .where_and("id", "=", 1)
    .value("name")
    .await?;

match name {
    Some(n) => println!("用户名: {}", n),
    None => println!("用户不存在"),
}

// 查询用户数量
let count: Option<i64> = db.table("users")
    .where_and("status", "=", 1)
    .value("COUNT(*)")
    .await?;

println!("活跃用户数: {}", count.unwrap_or(0));
Source

pub async fn count(self) -> Result<i64, DbError>

统计记录数量

执行 COUNT(*) 查询并返回匹配条件的记录数量。

§返回
  • Ok(i64): 查询成功,返回记录数量
  • Err(DbError): 查询执行失败
§示例
use yang_db::Database;

let db = Database::connect("mysql://root:password@localhost/test").await?;

// 统计所有用户数量
let total_users = db.table("users")
    .count()
    .await?;
println!("总用户数: {}", total_users);

// 统计活跃用户数量
let active_users = db.table("users")
    .where_and("status", "=", 1)
    .count()
    .await?;
println!("活跃用户数: {}", active_users);
Source

pub async fn sum(self, field: &str) -> Result<Option<f64>, DbError>

计算字段总和

执行 SUM(field) 查询并返回指定字段的总和。

§参数
  • field: 要求和的字段名
§返回
  • Ok(Some(f64)): 查询成功,返回字段总和
  • Ok(None): 查询成功,但没有匹配的记录或字段值全为 NULL
  • Err(DbError): 查询执行失败
§注意

MySQL 的 SUM() 函数对于整数字段返回 DECIMAL 类型,对于浮点数字段返回 DOUBLE 类型。 本方法使用 CAST 将结果转换为 DOUBLE,以统一返回类型。

§示例
use yang_db::Database;

let db = Database::connect("mysql://root:password@localhost/test").await?;

// 计算所有订单总金额
let total_amount = db.table("orders")
    .sum("amount")
    .await?;

match total_amount {
    Some(sum) => println!("订单总金额: {:.2}", sum),
    None => println!("没有订单或金额全为 NULL"),
}

// 计算已完成订单的总金额
let completed_amount = db.table("orders")
    .where_and("status", "=", "completed")
    .sum("amount")
    .await?;

println!("已完成订单总金额: {:.2}", completed_amount.unwrap_or(0.0));
Source

pub async fn insert<T>(self, data: &T) -> Result<u64, DbError>
where T: Serialize,

插入数据

执行 INSERT 操作,将数据插入到表中。

§类型参数
  • T: 数据类型,必须实现 Serialize trait
§参数
  • data: 要插入的数据
§返回
  • Ok(u64): 插入成功,返回插入记录的 ID(自增主键)
  • Err(DbError): 插入失败
§示例
use yang_db::Database;
use serde::{Deserialize, Serialize};
use serde_json::json;

let db = Database::connect("mysql://root:password@localhost/test").await?;

// 使用 JSON 对象插入
let user_data = json!({
    "name": "张三",
    "email": "zhangsan@example.com",
    "age": 25
});

let user_id = db.table("users")
    .insert(&user_data)
    .await?;

println!("插入成功,用户 ID: {}", user_id);

// 插入带 JSON 字段的数据
let order_data = json!({
    "user_id": user_id,
    "total": 199.99,
    "items": [{"id": 1, "qty": 2}, {"id": 2, "qty": 1}]
});

let order_id = db.table("orders")
    .json("items")  // 标记 items 字段为 JSON 类型
    .insert(&order_data)
    .await?;

println!("订单插入成功,订单 ID: {}", order_id);
Source

pub async fn insert_batch<T>(self, data: &[T]) -> Result<u64, DbError>
where T: Serialize,

批量插入数据

执行批量 INSERT 操作,将多条数据一次性插入到表中。 相比多次调用 insert(),批量插入性能更高,因为只需要一次数据库往返。

§类型参数
  • T: 数据类型,必须实现 Serialize trait
§参数
  • data: 要插入的数据切片
§返回
  • Ok(u64): 插入成功,返回受影响的行数
  • Err(DbError): 插入失败
§注意
  • 所有记录必须具有相同的字段结构
  • 字段顺序以第一条记录为准
  • 如果某条记录缺少字段,将使用 NULL 值
  • 批量插入使用单个 INSERT 语句,性能优于多次单条插入
§示例
use yang_db::Database;
use serde::{Deserialize, Serialize};
use serde_json::json;

let db = Database::connect("mysql://root:password@localhost/test").await?;

// 批量插入多个用户
let users = vec![
    json!({"name": "张三", "email": "zhangsan@example.com", "age": 25}),
    json!({"name": "李四", "email": "lisi@example.com", "age": 30}),
    json!({"name": "王五", "email": "wangwu@example.com", "age": 28}),
];

let affected_rows = db.table("users")
    .insert_batch(&users)
    .await?;

println!("批量插入成功,影响 {} 行", affected_rows);

// 批量插入带 JSON 字段的数据
let orders = vec![
    json!({
        "user_id": 1,
        "total": 199.99,
        "items": [{"id": 1, "qty": 2}]
    }),
    json!({
        "user_id": 2,
        "total": 299.99,
        "items": [{"id": 2, "qty": 1}]
    }),
];

let affected_rows = db.table("orders")
    .json("items")  // 标记 items 字段为 JSON 类型
    .insert_batch(&orders)
    .await?;

println!("批量插入订单成功,影响 {} 行", affected_rows);
Source

pub async fn update<T>(self, data: &T) -> Result<u64, DbError>
where T: Serialize,

更新数据

执行 UPDATE 操作,更新表中的数据。 为了防止误操作,必须提供 WHERE 条件,否则会返回错误。

§类型参数
  • T: 数据类型,必须实现 Serialize trait
§参数
  • data: 要更新的数据
§返回
  • Ok(u64): 更新成功,返回受影响的行数
  • Err(DbError): 更新失败
§示例
use yang_db::Database;
use serde_json::json;

let db = Database::connect("mysql://root:password@localhost/test").await?;

// 更新用户信息
let update_data = json!({
    "name": "李四",
    "age": 30
});

let rows_affected = db.table("users")
    .where_and("id", "=", 1)
    .update(&update_data)
    .await?;

println!("更新了 {} 行数据", rows_affected);
Source

pub async fn delete(self) -> Result<u64, DbError>

删除数据

执行 DELETE 操作,删除表中的数据。 为了防止误操作,必须提供 WHERE 条件,否则会返回错误。

§返回
  • Ok(u64): 删除成功,返回受影响的行数
  • Err(DbError): 删除失败
§示例
use yang_db::Database;

let db = Database::connect("mysql://root:password@localhost/test").await?;

// 删除指定用户
let rows_affected = db.table("users")
    .where_and("id", "=", 1)
    .delete()
    .await?;

println!("删除了 {} 行数据", rows_affected);

Auto Trait Implementations§

§

impl<'a> Freeze for QueryBuilder<'a>

§

impl<'a> !RefUnwindSafe for QueryBuilder<'a>

§

impl<'a> Send for QueryBuilder<'a>

§

impl<'a> Sync for QueryBuilder<'a>

§

impl<'a> Unpin for QueryBuilder<'a>

§

impl<'a> UnsafeUnpin for QueryBuilder<'a>

§

impl<'a> !UnwindSafe for QueryBuilder<'a>

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> 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, 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