Skip to main content

QueryBuilder

Struct QueryBuilder 

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

Implementations§

Source§

impl<'a> QueryBuilder<'a>

Source

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

选择可信 SQL 表达式。

本方法不校验输入;外部列名请使用 [Self::field_identifier]。

Source

pub fn expr(self, expression: SelectExpr) -> Self

添加受控聚合表达式。

Source

pub fn select_expr(self, expression: SqlExpr, alias: &FieldRef) -> Self

添加受控服务端标量表达式(如 now() / Unix 时间戳),可带输出别名。

表达式片段来自 crate::SqlExpr 白名单,动态偏移量走绑定参数; 占位符编号与后续 WHERE 参数连续。

Source

pub fn set_expr(self, field: &FieldRef, expression: SqlExpr) -> Self

登记受控服务端表达式赋值:UPDATE 的 SET 子句与单条 INSERT 的 VALUES 子句 都会生效(如 last_seen = now())。

表达式参数编号接续 JSON 列参数,WHERE 参数继续接续。批量插入与 UPSERT 暂不支持该入口,会返回 DbError::InvalidArgument。

Source

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

选择多个可信 SQL 表达式;外部列名请使用 [Self::field_identifiers]。

Source

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

标记字段为 JSON 类型

Source

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

标记字段为 JSONB 类型(插入绑定与 JSON 相同)

Source

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

标记字段为 UUID 类型

Source

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

标记字段为 DATE 类型

Source

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

标记字段为 TIME 类型

Source

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

标记字段为 DATETIME 类型

Source

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

标记字段为 TIMESTAMP 类型

Source

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

标记字段为 TIMESTAMPTZ(带时区)类型

Source

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

标记字段为 DECIMAL 类型

Source

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

标记字段为 BLOB(BYTEA)类型

Source

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

标记字段为 TEXT 类型

Source

pub fn field_type(self, field: &FieldRef, field_type: FieldType) -> Self

标记字段为任意 PostgreSQL 类型(数组 / INET / CIDR / MACADDR 等没有 专用链式方法的类型)。

FieldType::Array 的插入路径会把 JSON 数组按元素类型递归转换为 SqlValue::Array,作为单个数组参数绑定。

注意:数组绑定按首个非 NULL 元素推断驱动类型——整数元素绑定为 BIGINT[],浮点元素绑定为 DOUBLE PRECISION[];与 INT4[] / REAL[] 列不兼容。网络/位串字段会追加 ::inet / ::macaddr 等显式转换。

Source

pub fn distinct(self) -> Self

去重

Source

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

DISTINCT ON (...):按给定字段分组取首行。

PostgreSQL 要求 DISTINCT ON 表达式与 ORDER BY 的最左表达式一致; 该约束在构建 SQL 时校验(try_to_sql 返回 InvalidArgument)。 与 Self::distinct 互斥。

Source

pub fn with(self, name: &str, query: QueryBuilder<'a>) -> Self

追加一个 WITH <name> AS (<query>) 公共表表达式。

名称在渲染期按单段标识符校验并加引号;CTE 主体可继续携带自己的 WITH、 集合运算与排序/分页。

Source

pub fn with_recursive(self, name: &str, query: QueryBuilder<'a>) -> Self

追加一个递归 CTE;整条语句渲染为 WITH RECURSIVE ...。

Source

pub fn window_expr( self, function: WindowFunction, spec: WindowSpec, alias: &FieldRef, ) -> Self

添加窗口函数投影(<function> OVER (<spec>) AS <alias>)。

Source

pub fn window(self, name: &str, spec: WindowSpec) -> Self

定义命名窗口:WINDOW <name> AS (<spec>)。

投影通过 WindowSpec::reference 以 OVER "<name>" 复用该定义。 名称在渲染期按单段标识符校验并加引号。

Source

pub fn union(self, other: QueryBuilder<'a>) -> Result<Self, DbError>

使用 UNION 组合一个显式投影且输出列数相同的查询。

Source

pub fn union_all(self, other: QueryBuilder<'a>) -> Result<Self, DbError>

使用 UNION ALL 组合一个显式投影且输出列数相同的查询。

Source

pub fn intersect(self, other: QueryBuilder<'a>) -> Result<Self, DbError>

使用 INTERSECT 组合一个显式投影且输出列数相同的查询。

Source

pub fn intersect_all(self, other: QueryBuilder<'a>) -> Result<Self, DbError>

使用 INTERSECT ALL 组合一个显式投影且输出列数相同的查询。

Source

pub fn except(self, other: QueryBuilder<'a>) -> Result<Self, DbError>

使用 EXCEPT 组合一个显式投影且输出列数相同的查询。

Source

pub fn except_all(self, other: QueryBuilder<'a>) -> Result<Self, DbError>

使用 EXCEPT ALL 组合一个显式投影且输出列数相同的查询。

Source

pub fn grouping_sets(self, sets: Vec<Vec<FieldRef>>) -> Self

GROUP BY GROUPING SETS ((a, b), (a), ())。

可与其他分组字段或 ROLLUP/CUBE 组合;内层空集合表示总计行。

Source

pub fn rollup(self, fields: Vec<FieldRef>) -> Self

GROUP BY ROLLUP (a, b)。

Source

pub fn cube(self, fields: Vec<FieldRef>) -> Self

GROUP BY CUBE (a, b)。

Source

pub fn on_conflict(self, columns: &[&FieldRef]) -> Self

设置 UPSERT 的冲突目标列(PostgreSQL ON CONFLICT (...))

例:.on_conflict(&[yang_db::field!("email")]);传空切片等价于未指定目标, 此时仅允许配合 Self::do_nothing 使用(DO NOTHING);DO UPDATE 会在 客户端返回 crate::DbError::InvalidArgument,不会把语法错误留给数据库。

Source

pub fn on_conflict_constraint(self, constraint: &FieldRef) -> Self

使用命名约束作为冲突目标:ON CONFLICT ON CONSTRAINT <name>。

constraint 只需传入约束名(按单段标识符校验并加引号)。

Source

pub fn on_conflict_with_predicate( self, columns: &[&FieldRef], predicate: &str, ) -> Self

带部分唯一索引谓词的冲突目标: ON CONFLICT (<columns>) WHERE (<predicate>) DO UPDATE ...。

predicate 是受信 SQL 表达式(如 "active" 或 "tenant_id > 0"),按原样 包进括号;分号、注释标记(--、/*、*/)与 NUL 会被拒绝并返回 crate::DbError::InvalidArgument,避免把调用方输入变成第二条语句。

Source

pub fn update_columns(self, columns: &[&FieldRef]) -> Self

限制 DO UPDATE SET 只更新给定列白名单。

未调用时更新所有非冲突列。白名单中的列必须存在于插入数据中。

Source

pub fn do_nothing(self) -> Self

显式 DO NOTHING:忽略冲突目标对应的更新列与 upsert_where_and 条件。

注意:与 Self::upsert_returning 组合时,被跳过的冲突行不会出现在 RETURNING 中,可能得到 RowNotFound;需要行数请使用 Self::upsert。

Source

pub fn upsert_where_and<V>( self, field: &FieldRef, op: CompareOp, value: V, ) -> Result<Self, DbError>
where V: Into<SqlValue>,

为 DO UPDATE 追加 WHERE 条件(多个条件之间为 AND)。

占位符编号接续插入值与 SET 参数。

Source

pub fn returning(self, column: &FieldRef) -> Self

设置 insert 的 RETURNING 列(默认 "id")

PostgreSQL 无 last_insert_id(),insert 通过 RETURNING <col> 取回主键。 当自增主键列名不是 id 时,用本方法指定。

Source

pub fn returning_columns(self, columns: &[&FieldRef]) -> Self

设置多列 RETURNING:RETURNING "a", "b", ...。

列名与别名都按 PostgreSQL 标识符规则校验并加引号;非法标识符在执行前返回 crate::DbError::InvalidArgument。可与其他 returning_* 方法链式调用, 后调用者覆盖先前的目标。

Source

pub fn returning_column_as(self, column: &FieldRef, alias: &FieldRef) -> Self

追加一个带输出别名的 RETURNING 列:RETURNING "col" AS "alias"。

连续调用会按顺序累加;若当前目标是 RETURNING * 或单列(含默认 id), 第一次调用会以本列作为新的显式列表起点(单列/整行目标被替换)。 别名必须是单段 PostgreSQL 标识符(渲染期按标识符规则校验并加引号, 非法别名返回 InvalidArgument)。

Source

pub fn returning_all(self) -> Self

设置 RETURNING *,配合 Self::insert_returning 等按整行解码。

Source

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

Source

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

添加 OR 条件

遇到不支持的操作符或模式匹配收到非字符串模式时返回 Err(DbError::UnsupportedOperator)。

Source

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

添加 IN 条件

Source

pub fn where_exists(self, subquery: Subquery) -> Self

添加受控 EXISTS 子查询。

Source

pub fn where_not_exists(self, subquery: Subquery) -> Self

添加受控 NOT EXISTS 子查询。

Source

pub fn where_in_subquery(self, field: &FieldRef, subquery: Subquery) -> Self

添加受控 IN 子查询,外层字段必须是合法的单段或两段标识符。

Source

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

添加 BETWEEN 条件

Source

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

添加 IS NULL 条件

Source

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

添加 IS NOT NULL 条件

Source

pub fn where_predicate(self, predicate: &Predicate) -> Result<Self, DbError>

应用由上层权限模块编译的受控布尔查询树。

Source

pub fn where_not(self, condition: Condition) -> Self

对给定条件取反:渲染为 NOT (<condition>),可与 AND/OR 条件安全组合。

Source

pub fn where_column( self, left: &FieldRef, op: CompareOp, right: &FieldRef, ) -> Result<Self, DbError>

两个受控字段之间的比较(如 LATERAL 子查询中的关联条件 orders.employee_id = employees.id)。

两侧都是已校验的 crate::FieldRef,值不参与拼接。LIKE 不适用于 列比较,返回 UnsupportedOperator。

Source

pub fn where_json_contains<V>(self, field: &FieldRef, value: V) -> Self
where V: Into<SqlValue>,

JSON/JSONB 包含谓词:field @> $n。

值必须是 SqlValue::Json(或 SqlValue::Null,渲染为 SQL NULL 恒不命中), 其余类型在渲染期返回 InvalidArgument。

Source

pub fn where_json_contained_by<V>(self, field: &FieldRef, value: V) -> Self
where V: Into<SqlValue>,

JSON/JSONB 被包含谓词:field <@ $n。

值约束同 Self::where_json_contains。

Source

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

JSON/JSONB 顶层键存在谓词:field ? $n(键名走绑定参数)。

Source

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

JSONB 路径存在谓词:jsonb_path_exists((field)::jsonb, $n::jsonpath)。

path 与 jsonpath 字面量语法一致(如 $.items[*] ? (@.price > 10)), 以绑定参数传入,不拼接进 SQL 文本。

Source

pub fn where_json_path_match<V>( self, field: &FieldRef, path: &str, vars: V, ) -> Self
where V: Into<SqlValue>,

JSONB 路径谓词:jsonb_path_match((field)::jsonb, $n::jsonpath, $m::jsonb)。

vars 为 jsonpath 表达式中 $var 的取值对象(建议传 serde_json::json!({..})), 与 path 一样以绑定参数传入。

Source

pub fn where_range_contains<V>(self, field: &FieldRef, value: V) -> Self
where V: Into<SqlValue>,

范围包含谓词:field @> $n。

右值必须由 SqlValue::Range 或 SqlValue::Multirange 构造,例如 SqlValue::Range("[1,10)".to_string());渲染时追加 ::int4range / ::int4multirange 显式转换。该快捷谓词仅支持整数范围;tsrange 等其他范围类型请使用原生 SQL 显式转换(如 $1::tsrange)。

Source

pub fn where_range_overlaps<V>(self, field: &FieldRef, value: V) -> Self
where V: Into<SqlValue>,

范围重叠谓词:field && $n。

右值约束同 Self::where_range_contains。

Source

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

全文检索谓词:to_tsvector('simple', field) @@ plainto_tsquery('simple', $n)。

查询串按纯文本解析(空格分词),以绑定参数传入。

Source

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

全文检索(to_tsquery 变体):查询串可含 &、|、! 等布尔操作符。

Source

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

数组任一元素相等:field = ANY($n)(数组作为单个绑定参数)。

Source

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

数组全部元素相等:field = ALL($n)(数组作为单个绑定参数)。

Source

pub fn where_expr( self, field: &FieldRef, op: CompareOp, expression: SqlExpr, ) -> Result<Self, DbError>

字段与服务端受控表达式的比较(如 updated_at < now())。

LIKE 不适用于表达式比较,返回 UnsupportedOperator。

Source

pub fn having_cond<V>( self, field: &FieldRef, op: CompareOp, value: V, ) -> Result<Self, DbError>
where V: Into<SqlValue>,

添加 HAVING 条件(仅支持 6 个比较操作符)

Source

pub fn having_expr<V>( self, expression: SelectExpr, op: CompareOp, value: V, ) -> Result<Self, DbError>
where V: Into<SqlValue>,

添加 HAVING 聚合表达式比较(如 HAVING COUNT(*) > 1)。

左侧来自受控 crate::SelectExpr,表达式本体渲染,不携带输出别名; 值走绑定参数。模式匹配/NULL-safe 比较不适用于聚合表达式,返回 UnsupportedOperator。

Source

pub fn join(self, table: &TableRef, left: &FieldRef, right: &FieldRef) -> Self

使用可信表/ON 表达式的 INNER JOIN。

外部表名/列名请先用 crate::postgres::identifier::quote_identifier / crate::postgres::identifier::quote_qualified 校验后再拼入表达式。

Source

pub fn left_join( self, table: &TableRef, left: &FieldRef, right: &FieldRef, ) -> Self

LEFT JOIN

Source

pub fn right_join( self, table: &TableRef, left: &FieldRef, right: &FieldRef, ) -> Self

RIGHT JOIN

Source

pub fn full_join( self, table: &TableRef, left: &FieldRef, right: &FieldRef, ) -> Self

FULL OUTER JOIN(PostgreSQL 渲染为 FULL JOIN)。

Source

pub fn cross_join(self, table: &TableRef) -> Self

CROSS JOIN(无连接条件)。

Source

pub fn natural_join(self, table: &TableRef) -> Self

NATURAL JOIN(按两表同名同类型列自动连接,无连接条件)。

Source

pub fn join_using(self, table: &TableRef, columns: &[&FieldRef]) -> Self

INNER JOIN ... USING (col, ...):用同名列连接,避免重复输出连接列。

Source

pub fn left_join_lateral( self, query: QueryBuilder<'a>, alias: &FieldRef, left: &FieldRef, right: &FieldRef, ) -> Self

LEFT JOIN LATERAL (<subquery>) AS "alias" ON ...。

子查询可引用左侧表的列(横向关联);alias 必须是单段标识符。

Source

pub fn order(self, field: &FieldRef, order: SortOrder) -> Self

按可信 SQL 表达式排序;外部列名请先用 crate::postgres::identifier::quote_identifier 校验后再拼入表达式。

Source

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

按可信 SQL 表达式分组;外部列名请先用 crate::postgres::identifier::quote_identifier 校验后再拼入表达式。

Source

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

限制返回数量

Source

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

偏移量

Source

pub fn try_to_sql(&self) -> Result<String, DbError>

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

与 Self::to_sql 不同,本方法不会吞掉 SQL 生成错误。调用方需要区分非法表名、 缺少 GROUP BY 等生产级配置错误时,应优先使用本方法。

Source

pub fn try_to_sql_with_lock( &self, lock: RowLock, of: &[&FieldRef], nowait: bool, skip_locked: bool, ) -> Result<String, DbError>

渲染带完整行锁组合的 SELECT(调试/自定义执行入口)。

lock 决定锁模式(含 NO KEY UPDATE / KEY SHARE);of 为 FOR ... OF 的表/别名列表(空切片表示不加 OF);nowait 与 skip_locked 互斥,同时为 true 时返回 crate::error::DbError::InvalidArgument。 ForUpdateSkipLocked / ForShareSkipLocked 隐含 SKIP LOCKED。

例:FOR NO KEY UPDATE OF "orders" SKIP LOCKED。

Source

pub fn to_sql(&self) -> String

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

兼容历史 String 返回值;生成失败时返回固定的不可执行哨兵,避免旧降级逻辑把 未校验表名或不完整查询拼成看似可执行的 SQL。需要错误细节请使用 Self::try_to_sql。

Source

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

查询单条记录(自动追加 LIMIT 1)

Source

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

查询多条记录

Source

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

查询单个字段值(自动追加 LIMIT 1)

Source

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

统计记录数量(COUNT(*))

Source

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

计算字段总和(SUM)

使用 CAST(SUM(field) AS DOUBLE PRECISION) 统一返回 f64, 与 MySQL 后端的 AS DOUBLE 对应(PostgreSQL 的等价类型为 DOUBLE PRECISION)。

Source

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

计算字段平均值(AVG)

使用 CAST(AVG(field) AS DOUBLE PRECISION) 统一返回 f64。

Source

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

获取字段最小值(MIN)

Source

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

获取字段最大值(MAX)

Source

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

插入数据

执行 INSERT 操作并通过 RETURNING <col> 取回自增主键(PostgreSQL 无 last_insert_id())。<col> 默认 "id",可用 QueryBuilder::returning 覆盖。

§返回
  • Ok(u64): 插入成功,返回 RETURNING 列的值(自增主键)
  • Err(DbError): 插入失败

RETURNING 值为负数时返回 [DbError::InvalidArgument];Pool 路径会在 提交前回滚,不会留下已写入的行(事务内调用由调用方负责回滚)。

Source

pub async fn insert_returning<T, R>(self, data: &T) -> Result<R, DbError>
where T: Serialize, R: for<'r> FromRow<'r, PgRow> + Send + Unpin,

插入数据并按真实列类型取回 RETURNING 结果。

默认 RETURNING <id>,可用 QueryBuilder::returning 指定单列或 QueryBuilder::returning_all 取整行。R 为调用方的 FromRow 结构体, 各列按数据库真实类型解码(不再经过 i64 / CAST)。

§返回
  • Ok(R): 插入行按 R 解码后的结果
  • Err(DbError): 插入或解码失败
Source

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

批量插入数据

使用默认批大小 [INSERT_BATCH_SIZE](500)分批执行,返回总受影响行数。 批量插入不使用 RETURNING,仅返回 rows_affected()。

Source

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

批量插入数据(自定义批次大小)

允许调用方根据网络延迟、数据大小等自定义每批最大记录数(必须 > 0)。

Source

pub async fn insert_batch_returning<T, R>( self, data: &[T], ) -> Result<Vec<R>, DbError>
where T: Serialize, R: for<'r> FromRow<'r, PgRow> + Send + Unpin,

批量插入并返回 RETURNING 行(按列的真实类型解码)。

目标由 Self::returning / Self::returning_columns / Self::returning_column_as / Self::returning_all 决定。所有分片在同一个 事务内执行:任一分片失败或解码失败都会整体回滚,返回已插入的全部行。

Source

pub async fn upsert_batch_returning<T, R>( self, data: &[T], conflict_columns: &[&FieldRef], ) -> Result<Vec<R>, DbError>
where T: Serialize, R: for<'r> FromRow<'r, PgRow> + Send + Unpin,

批量 UPSERT 并返回 RETURNING 行(按列的真实类型解码)。

冲突列必须显式传入(do_nothing() 时可省略);冲突列为空且非 DO NOTHING 时在客户端返回 crate::error::DbError::InvalidArgument。所有分片在同一事务内执行。

Source

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

更新数据

执行 UPDATE 操作。为防止误操作,必须提供 WHERE 条件,否则返回 MissingWhereClause。返回受影响的行数。

Source

pub async fn update_returning<T, R>(self, data: &T) -> Result<Vec<R>, DbError>
where T: Serialize, R: for<'r> FromRow<'r, PgRow> + Send + Unpin,

更新数据并返回 RETURNING 行。

与 Self::update 相同地要求 WHERE 条件;返回按真实列类型解码的更新后行。 默认 RETURNING <id>,可用 QueryBuilder::returning / QueryBuilder::returning_all 调整。

Source

pub async fn increment( self, field: &FieldRef, amount: i64, ) -> Result<u64, DbError>

原子增加字段值;增量使用绑定参数,且必须提供 WHERE。

Source

pub async fn decrement( self, field: &FieldRef, amount: i64, ) -> Result<u64, DbError>

原子减少字段值;增量使用绑定参数,且必须提供 WHERE。

Source

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

删除数据

执行 DELETE 操作。为防止误操作,必须提供 WHERE 条件,否则返回 MissingWhereClause。返回受影响的行数。

Source

pub async fn delete_returning<R>(self) -> Result<Vec<R>, DbError>
where R: for<'r> FromRow<'r, PgRow> + Send + Unpin,

删除数据并返回 RETURNING 行。

与 Self::delete 相同地要求 WHERE 条件;返回按真实列类型解码的被删行。 默认 RETURNING <id>,可用 QueryBuilder::returning / QueryBuilder::returning_all 调整。

Source

pub async fn insert_from_select( self, columns: &[&FieldRef], source: QueryBuilder<'a>, ) -> Result<u64, DbError>

INSERT INTO ... SELECT ...:把源查询结果插入目标表。

columns 为目标列列表(可为空表示整行);源查询由 QueryBuilder 构建, 支持 CTE、集合运算与排序/分页。返回受影响行数。

Source

pub async fn update_from<T>( self, data: &T, from: &TableRef, target_field: &FieldRef, source_field: &FieldRef, ) -> Result<u64, DbError>
where T: Serialize,

UPDATE ... SET ... FROM <from> WHERE <conds> AND <target_field> = <source_field>。

与 Self::update 一样必须提供至少一个 WHERE 条件,避免误更新; 联表条件会与 WHERE 条件一起进入 WHERE。返回受影响行数。

Source

pub async fn delete_using( self, using: &TableRef, target_field: &FieldRef, source_field: &FieldRef, ) -> Result<u64, DbError>

DELETE FROM ... USING <using> WHERE <conds> AND <target_field> = <source_field>。

与 Self::delete 一样必须提供至少一个 WHERE 条件;联表条件会与 WHERE 条件一起进入 WHERE。返回受影响行数。

Source

pub async fn update_batch<T>( self, records: &[T], where_field: &FieldRef, ) -> Result<u64, DbError>
where T: Serialize,

批量更新记录

使用 CASE WHEN 策略在单次查询中更新多条记录,自动分批(每批 [UPDATE_BATCH_SIZE],1000;宽表按列数自动缩小),所有批次在同一事务中 执行保证原子性。返回总受影响行数。

Source

pub async fn update_batch_with_size<T>( self, records: &[T], where_field: &FieldRef, batch_size: usize, ) -> Result<u64, DbError>
where T: Serialize,

批量更新记录(自定义批次大小)

与 QueryBuilder::update_batch 相同,但允许调用方自定义每批最大记录数; 宽表会自动按列数缩小批大小,避免超出协议占位符上限。

Source

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

UPSERT - 插入或更新记录

使用 PostgreSQL INSERT ... ON CONFLICT (...) DO UPDATE SET col = EXCLUDED.col 语法。冲突目标必须用 QueryBuilder::on_conflict / QueryBuilder::on_conflict_constraint / QueryBuilder::on_conflict_with_predicate 显式指定;未指定且非 QueryBuilder::do_nothing 时在客户端返回 crate::DbError::InvalidArgument。返回 rows_affected()。

Source

pub async fn upsert_returning<T, R>(self, data: &T) -> Result<R, DbError>
where T: Serialize, R: for<'r> FromRow<'r, PgRow> + Send + Unpin,

UPSERT 并返回 RETURNING 行(按真实列类型解码)。

冲突目标必须显式指定(见 Self::on_conflict);默认 RETURNING <id>, 可用 QueryBuilder::returning_all / QueryBuilder::returning_columns 调整。

Source

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

批量 UPSERT:多行 VALUES + ON CONFLICT ... DO UPDATE,返回受影响行数。

冲突列由调用方显式传入(不做静默默认);使用 id 时请显式传 &[field!("id")]。本方法的冲突列参数优先于 builder 上的 Self::on_conflict 设置。更新列默认取「插入列集 - 冲突列」,可用 Self::update_columns 收窄;Self::do_nothing 时渲染 ON CONFLICT DO NOTHING。默认每批 [INSERT_BATCH_SIZE](500)行。

Source

pub async fn upsert_batch_with_size<T>( self, data: &[T], conflict_columns: &[&FieldRef], batch_size: usize, ) -> Result<u64, DbError>
where T: Serialize,

批量 UPSERT(自定义批次大小)。

一条语句本身原子:单批直接执行,多批包在事务中保证整体回滚。 批大小会按列数进一步收敛,避免超出协议占位符上限。

Source

pub async fn merge( self, source: &TableRef, target_key: &FieldRef, source_key: &FieldRef, columns: &[&FieldRef], ) -> Result<u64, DbError>

MERGE(PostgreSQL 15+):按 target_key = source_key 匹配源表,命中则更新 columns,未命中则从源表插入 columns。

§版本要求

MERGE 语句自 PostgreSQL 15 起提供;在更低版本上服务端会返回语法错误。 本方法不做版本探测,调用方需自行保证服务端版本(推荐 PG 16/17)。

不支持 where / set_expr:匹配条件请放入 ON 参数。返回受影响行数。

执行前会读取 server_version_num(PostgreSQL 15 起提供 MERGE);低于 150000 时直接返回 crate::DbError::UnsupportedOperator,不会把不支持的语法发到服务端。

Source

pub async fn merge_with_options( self, source: &TableRef, target_key: &FieldRef, source_key: &FieldRef, columns: &[&FieldRef], options: MergeOptions, ) -> Result<u64, DbError>

带可选分支的 MERGE(PostgreSQL 15+)。

支持 WHEN MATCHED AND <condition> 与 PostgreSQL 17+ 的 WHEN NOT MATCHED BY SOURCE THEN DELETE/UPDATE;后者在更低版本上返回 crate::DbError::UnsupportedOperator,不会把不支持的语法发到服务端。 其余语义与 Self::merge 相同。

Auto Trait Implementations§

§

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

§

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

§

impl<'a> Forget for QueryBuilder<'a>

§

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

§

impl<'a> Move 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>

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 = !

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

fn try_from(value: U) -> Result<T, !>

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