pub struct TableQuery { /* private fields */ }Expand description
表查询构建器
基于不可变表定义创建受保护的查询构建器,支持:
- 字段选择和权限验证
- WHERE 条件构建
- 排序规则
- 分页查询
§字段
- 内部表契约:由
super::TableDefinition提供字段定义和权限配置 user_roles:用户角色列表,用于权限检查query_params:查询参数,包含字段选择、WHERE 条件、排序规则和分页参数pool:运行时数据库连接池句柄(MySQL / PostgreSQL 按后端分派)
§示例
use yang_base::table::{Field, SortOrder, Table};
use std::sync::Arc;
use serde_json::json;
let table = Table::new("users")
.fields(vec![Field::id("id"), Field::string("name", 50)])
.build()?;
let query = table.bind(Arc::new(pool)).query(["admin"]);
// 选择字段
let query = query.select_fields(&["id", "name"])?;
// 添加 WHERE 条件
let query = query.where_eq("status", json!(1))?;
// 添加排序
let query = query.order_by("created_at", SortOrder::Desc)?;
// 设置分页
let query = query.page(1, 20)?;Implementations§
Source§impl TableQuery
impl TableQuery
Sourcepub fn with_slow_threshold(self, threshold: Option<Duration>) -> Self
pub fn with_slow_threshold(self, threshold: Option<Duration>) -> Self
设置慢查询阈值(链式)。超过该耗时的单次执行会 tracing::warn!。
通常由 ActionContext::table_query() 从全局 ObservabilityConfig 注入;
也可手动覆盖。None/不调用时不启用慢查询日志。
Sourcepub fn with_request_id(self, request_id: RequestId) -> Self
pub fn with_request_id(self, request_id: RequestId) -> Self
设置本次查询关联的 request_id(链式),用于慢查询日志串联。
Sourcepub fn with_regex_cache(self, cache: RegexCache) -> Self
pub fn with_regex_cache(self, cache: RegexCache) -> Self
注入共享有界正则缓存(链式)。通常由 ActionContext::table_query() 从
crate::tools::Tools 注入;未注入时使用默认容量缓存。
Sourcepub fn order_nulls(
self,
field: &str,
order: SortOrder,
nulls_first: bool,
) -> Result<Self, BaseError>
pub fn order_nulls( self, field: &str, order: SortOrder, nulls_first: bool, ) -> Result<Self, BaseError>
按字段排序并指定 NULL 的位置。
字段/权限校验与 TableQuery::order_by 完全一致。PostgreSQL 渲染原生
NULLS FIRST/LAST;MySQL 用 field IS NULL 排序表达式模拟(NULL 标记列
前置于主排序键)。
Sourcepub fn where_in_chunked(
self,
field: &str,
values: Vec<Value>,
) -> Result<Self, BaseError>
pub fn where_in_chunked( self, field: &str, values: Vec<Value>, ) -> Result<Self, BaseError>
追加 IN 条件,并按参数上限自动分块。
与 TableQuery::where_in 的 500 条上限不同,本入口把超长列表拆成多个
IN 子句并以 OR 连接,避免单条语句参数数量无限增长。
Sourcepub fn where_any(
self,
field: &str,
values: Vec<Value>,
) -> Result<Self, BaseError>
pub fn where_any( self, field: &str, values: Vec<Value>, ) -> Result<Self, BaseError>
field = ANY($1) 数组参数入口。
PostgreSQL 后端把整个列表作为单个数组参数绑定,参数个数不随列表长度增长;
其它后端(或尚未注入连接池时)降级为 TableQuery::where_in_chunked。
Sourcepub fn require_sourced_tx(self, required: bool) -> Self
pub fn require_sourced_tx(self, required: bool) -> Self
要求事务必须显式携带数据源身份(多源应用由 ActionContext 注入)。
Source§impl TableQuery
impl TableQuery
Sourcepub fn select_fields(self, fields: &[&str]) -> Result<Self, BaseError>
pub fn select_fields(self, fields: &[&str]) -> Result<Self, BaseError>
选择要查询的字段。
会校验字段存在,并校验当前用户角色具备这些字段的读取权限。
Sourcepub fn where_eq(self, field: &str, value: Value) -> Result<Self, BaseError>
pub fn where_eq(self, field: &str, value: Value) -> Result<Self, BaseError>
添加等于条件 (WHERE field = value)
添加 WHERE 等于条件,并验证:
- 字段是否存在于表配置中
- 用户是否有字段的筛选权限
§参数
field:字段名value:比较值
§返回值
Ok(Self):验证通过,返回 self 支持链式调用Err(BaseError):验证失败,返回错误
§错误
BaseError::FieldNotFound:字段不存在BaseError::FieldPermissionDenied:用户无筛选权限
§示例
use serde_json::json;
let query = query.where_eq("status", json!("active"))?;Sourcepub fn where_in(
self,
field: &str,
values: Vec<Value>,
) -> Result<Self, BaseError>
pub fn where_in( self, field: &str, values: Vec<Value>, ) -> Result<Self, BaseError>
添加包含条件 (WHERE field IN (values))
添加 WHERE IN 条件,并验证:
- 字段是否存在于表配置中
- 用户是否有字段的筛选权限
§参数
field:字段名values:值列表
§返回值
Ok(Self):验证通过,返回 self 支持链式调用Err(BaseError):验证失败,返回错误
§错误
BaseError::FieldNotFound:字段不存在BaseError::FieldPermissionDenied:用户无筛选权限
§示例
use serde_json::json;
let query = query.where_in("status", vec![json!(1), json!(2), json!(3)])?;Sourcepub fn where_like(self, field: &str, pattern: String) -> Result<Self, BaseError>
pub fn where_like(self, field: &str, pattern: String) -> Result<Self, BaseError>
添加模糊匹配条件 (WHERE field LIKE pattern)
添加 WHERE LIKE 条件,并验证:
- 字段是否存在于表配置中
- 用户是否有字段的筛选权限
§参数
field:字段名pattern:匹配模式,支持 % 和 _ 通配符
§返回值
Ok(Self):验证通过,返回 self 支持链式调用Err(BaseError):验证失败,返回错误
§错误
BaseError::FieldNotFound:字段不存在BaseError::FieldPermissionDenied:用户无筛选权限
§示例
let query = query.where_like("name", "%alice%")?;Sourcepub fn where_contains(
self,
field: &str,
keyword: &str,
) -> Result<Self, BaseError>
pub fn where_contains( self, field: &str, keyword: &str, ) -> Result<Self, BaseError>
添加模糊匹配条件 (WHERE field LIKE ‘%keyword%’)
便捷方法:自动将 keyword 用 % 包裹,并转义其中的 % 和 _ 通配符,
避免用户输入中的通配符被解释为 SQL LIKE 语法。
§参数
field:字段名keyword:搜索关键词(无需手动加%)
§返回值
Ok(Self):验证通过,返回 self 支持链式调用Err(BaseError):验证失败(字段不存在 / 无权限 / 转义后超长)
§示例
// WHERE name LIKE '%alice%',且 "%" / "_" 被转义
let query = query.where_contains("name", "alice")?;Sourcepub fn where_between(
self,
field: &str,
lo: Value,
hi: Value,
) -> Result<Self, BaseError>
pub fn where_between( self, field: &str, lo: Value, hi: Value, ) -> Result<Self, BaseError>
添加区间条件 (WHERE field BETWEEN lo AND hi)
添加 WHERE BETWEEN 条件,并验证:
- 字段是否存在于表配置中
- 用户是否有字段的筛选权限
当 lo > hi 时 BETWEEN 返回空集(MySQL 标准行为,框架不做特殊处理)。
§参数
field:字段名lo:区间下界(包含)hi:区间上界(包含)
§返回值
Ok(Self):验证通过,返回 self 支持链式调用Err(BaseError):验证失败,返回错误
§错误
BaseError::FieldNotFound:字段不存在BaseError::FieldPermissionDenied:用户无筛选权限
Sourcepub fn where_null(self, field: &str) -> Result<Self, BaseError>
pub fn where_null(self, field: &str) -> Result<Self, BaseError>
Sourcepub fn where_not_null(self, field: &str) -> Result<Self, BaseError>
pub fn where_not_null(self, field: &str) -> Result<Self, BaseError>
Sourcepub fn order_by(self, field: &str, order: SortOrder) -> Result<Self, BaseError>
pub fn order_by(self, field: &str, order: SortOrder) -> Result<Self, BaseError>
添加排序规则。
会校验字段存在、字段允许排序,以及当前用户角色具备排序权限。
Sourcepub fn search(self, keyword: Option<&str>) -> Result<Self, BaseError>
pub fn search(self, keyword: Option<&str>) -> Result<Self, BaseError>
对声明了 searchable 且当前角色可读的文本字段应用一次 OR LIKE 搜索。
关键词搜索只认独立的 searchable 位(crate::table::Field::searchable),与
结构化 where 的 filterable 校验(validate_filter_field)互不开放。搜索字段
来自表定义迭代(必然存在)且已逐一验证 is_text / searchable / 可读 /
非 hidden,因此这里自行构造 OR 组、不经过 where_or 的 filterable 门槛;
但 LIKE pattern 长度上限(QRY-1)仍在本地强制执行。
Sourcepub fn with_trashed(self) -> Self
pub fn with_trashed(self) -> Self
在读取路径包含软删除记录
默认情况下,配置了 soft_delete_field 的表会在 select/count/paginate
时自动追加 软删字段 IS NULL 过滤,隐藏已软删行。调用本方法后,本次查询
读取全量数据(含已软删行)。
§返回值
返回 self 支持链式调用
Sourcepub fn where_primary_key_eq(self, value: Value) -> Result<Self, BaseError>
pub fn where_primary_key_eq(self, value: Value) -> Result<Self, BaseError>
注入受信的主键等值条件。
内置 get/put/del 的主键定位是 Action 自有寻址机制,不是调用方可选的结构化
筛选,因此与 Self::scope_tenant 一样绕过 filterable 业务筛选权限;
值仍按主键字段类型校验(null 交由渲染器规范化为 IS NULL,匹配不到记录)。
Sourcepub fn where_primary_keys(self, keys: &Record) -> Result<Self, BaseError>
pub fn where_primary_keys(self, keys: &Record) -> Result<Self, BaseError>
注入复合主键等值条件(按声明顺序逐列 AND)。
Sourcepub fn where_or(
self,
conditions: Vec<WhereCondition>,
) -> Result<Self, BaseError>
pub fn where_or( self, conditions: Vec<WhereCondition>, ) -> Result<Self, BaseError>
添加一个 OR 逻辑组 (WHERE … AND (c1 OR c2 OR …))
组内每个子条件递归校验字段存在性与筛选权限;通过后整组以 Or 节点追加到
顶层条件列表,与既有条件以隐式 AND 连接。空组等价于恒假(1=0)。
子条件可由 WhereCondition 直接构造,亦可嵌套 And/Or 组(深度上限
MAX_WHERE_DEPTH)。
§参数
conditions:OR 组的子条件列表
§返回值
Ok(Self):校验通过,返回 self 支持链式调用Err(BaseError):字段不存在 / 无筛选权限 / 嵌套超限
§示例
use yang_base::table::WhereCondition;
use serde_json::json;
// WHERE status = 'active' AND (age >= 18 OR vip = true)
let query = query
.where_eq("status", json!("active"))?
.where_or(vec![
WhereCondition::Gte { field: "age".into(), value: json!(18) },
WhereCondition::Eq { field: "vip".into(), value: json!(true) },
])?;Sourcepub fn where_and(
self,
conditions: Vec<WhereCondition>,
) -> Result<Self, BaseError>
pub fn where_and( self, conditions: Vec<WhereCondition>, ) -> Result<Self, BaseError>
添加一个 AND 逻辑组 (WHERE … AND (c1 AND c2 AND …))
语义同 TableQuery::where_or,但组内子条件以 AND 连接。主要用于在 OR 组
内部嵌套 AND 子组;顶层多个条件本就隐式 AND,单独使用通常无必要。空组等价
于恒真(1=1)。
§参数
conditions:AND 组的子条件列表
§返回值
Ok(Self):校验通过,返回 self 支持链式调用Err(BaseError):字段不存在 / 无筛选权限 / 嵌套超限
Sourcepub fn where_tree(self, condition: WhereCondition) -> Result<Self, BaseError>
pub fn where_tree(self, condition: WhereCondition) -> Result<Self, BaseError>
追加一棵任意 WHERE 条件(叶子或 And/Or 组),递归校验后并入顶层条件。
这是以 WhereCondition 表示的类型化布尔树桥接到受保护层的统一入口:
整棵树先经 validate_condition_tree 递归校验字段存在性、筛选权限与
嵌套深度,通过后作为单个条件追加(与既有条件隐式 AND 连接)。
§参数
condition:任意WhereCondition(叶子或逻辑组)
§返回值
Ok(Self):校验通过,返回 self 支持链式调用Err(BaseError):字段不存在 / 无筛选权限 / 嵌套超限
Sourcepub fn get_query_params(&self) -> &QueryParams
pub fn get_query_params(&self) -> &QueryParams
Sourcepub fn apply_params(self, params: QueryParams) -> Result<Self, BaseError>
pub fn apply_params(self, params: QueryParams) -> Result<Self, BaseError>
应用通用列表参数,并复用本类型现有的字段/筛选/排序/分页权限校验。
Sourcepub fn get_user_roles(&self) -> &[String]
pub fn get_user_roles(&self) -> &[String]
Source§impl TableQuery
数据库执行方法(需要启用 mysql 或 postgres feature)
impl TableQuery
数据库执行方法(需要启用 mysql 或 postgres feature)
Sourcepub async fn paginate_records(
self,
) -> Result<PaginatedResult<Record>, BaseError>
pub async fn paginate_records( self, ) -> Result<PaginatedResult<Record>, BaseError>
执行分页查询并返回 schema-first Record。
未显式设置分页时会使用默认页码和默认每页大小,并确保数据查询带有 LIMIT/OFFSET。
Sourcepub async fn exists(self) -> Result<bool, BaseError>
pub async fn exists(self) -> Result<bool, BaseError>
判断是否存在至少一条匹配记录(SELECT 1 ... LIMIT 1 语义)。
与 count() == 0 相比不扫描全部匹配行,适合权限/去重前置判断。
Source§impl TableQuery
impl TableQuery
Sourcepub async fn insert(self, data: Record) -> Result<u64, BaseError>
pub async fn insert(self, data: Record) -> Result<u64, BaseError>
执行 INSERT 操作
插入数据到表中,包括以下步骤:
- 按表定义验证所有字段值
- 检查用户是否有字段的写入权限
- 构建 INSERT SQL 语句
- 执行插入操作
§返回值
Ok(1):插入成功Err(BaseError):插入失败
Sourcepub async fn insert_in_tx(
self,
tx: &mut AnyTransaction,
data: Record,
) -> Result<u64, BaseError>
pub async fn insert_in_tx( self, tx: &mut AnyTransaction, data: Record, ) -> Result<u64, BaseError>
在事务中执行 INSERT 操作
与 TableQuery::insert 完全一致的写权限校验/默认值填充/时间戳/必填校验
流程,但在调用方提供的事务内执行,可与其它写操作原子提交。
Sourcepub async fn insert_returning(
self,
data: Record,
target: ReturningTarget<'_>,
) -> Result<Record, BaseError>
pub async fn insert_returning( self, data: Record, target: ReturningTarget<'_>, ) -> Result<Record, BaseError>
执行 INSERT 并返回 RETURNING 结果。
ReturningTarget::Pk:只返回主键列,UUID / text / numeric 等非整型主键 也能正确回填;ReturningTarget::Columns:直接RETURNING <列...>(单列/多列均可);ReturningTarget::All:返回整行。
§MySQL 限制
MySQL 没有 RETURNING:只有「目标就是整型主键」的请求能由 last_insert_id
满足;All、多列或非主键列的 Columns 返回明确的
BaseError::ConfigError,绝不用提交的输入伪造返回值。
Sourcepub async fn insert_batch_returning(
self,
data: &[Record],
target: ReturningTarget<'_>,
) -> Result<Vec<Record>, BaseError>
pub async fn insert_batch_returning( self, data: &[Record], target: ReturningTarget<'_>, ) -> Result<Vec<Record>, BaseError>
批量 INSERT 并返回 RETURNING 行,保持输入顺序。
PostgreSQL 走驱动的 insert_batch_returning:所有分片在同一事务内执行,
任一分片失败或解码失败都会整体回滚。MySQL 没有 RETURNING,返回明确的
BaseError::ConfigError,绝不按输入伪造返回值。
空批返回空向量,不生成语句。
Sourcepub async fn insert_batch_returning_in_tx(
self,
tx: &mut AnyTransaction,
data: &[Record],
target: ReturningTarget<'_>,
) -> Result<Vec<Record>, BaseError>
pub async fn insert_batch_returning_in_tx( self, tx: &mut AnyTransaction, data: &[Record], target: ReturningTarget<'_>, ) -> Result<Vec<Record>, BaseError>
在调用方事务内批量 INSERT 并返回 RETURNING 行。
校验/默认值/类型规则与 TableQuery::insert_batch_returning 完全一致,
只是执行在调用方事务内。MySQL 同样明确返回 BaseError::ConfigError。
Sourcepub async fn insert_returning_pk_value(
self,
data: Record,
) -> Result<(u64, Value), BaseError>
pub async fn insert_returning_pk_value( self, data: Record, ) -> Result<(u64, Value), BaseError>
执行 INSERT 并返回真实类型的主键值。
PostgreSQL 走 INSERT ... RETURNING <主键>;MySQL 走 last_insert_id
(仅整型主键,非整型返回明确错误)。返回 (影响行数, 主键 JSON 值)。
Sourcepub async fn insert_returning_id(
self,
data: Record,
) -> Result<(u64, u64), BaseError>
pub async fn insert_returning_id( self, data: Record, ) -> Result<(u64, u64), BaseError>
执行 INSERT 操作并返回自增主键(整型兼容入口)
内部经 TableQuery::insert_returning_pk_value 取回真实类型主键后再转成
u64;非整型主键在触库前返回明确的 BaseError::ParamInvalid。需要
UUID / text / numeric 主键时改用 insert_returning_pk_value() 或
TableQuery::insert_returning。
§返回值
Ok((1, id)):插入成功,返回 (影响行数, 主键值)。表无自增列时id为 0。Err(BaseError):插入失败或主键非整型
Sourcepub async fn insert_returning_id_in_tx(
self,
tx: &mut AnyTransaction,
data: Record,
) -> Result<(u64, u64), BaseError>
pub async fn insert_returning_id_in_tx( self, tx: &mut AnyTransaction, data: Record, ) -> Result<(u64, u64), BaseError>
在事务中执行 INSERT 并返回自增主键
与 TableQuery::insert_returning_id 一致,但在事务内执行;整型主键限制
同样适用。
Sourcepub async fn upsert_batch(
self,
rows: Vec<Record>,
conflict_columns: &[&str],
) -> Result<u64, BaseError>
pub async fn upsert_batch( self, rows: Vec<Record>, conflict_columns: &[&str], ) -> Result<u64, BaseError>
PostgreSQL 批量 UPSERT(非事务):多行 INSERT ... ON CONFLICT (...) DO UPDATE。
conflict_columns 必须显式给出,且必须命中表上的唯一索引/约束——PostgreSQL
的 ON CONFLICT 不做隐式推断,空切片会在触库前返回
BaseError::ParamInvalid。
冲突时更新的列使用默认白名单:插入列 − 冲突列 − 框架保护列(主键、租户
字段、created_at/deleted_at、source_file/company 等审计归属列)。
需要精确控制时用 TableQuery::upsert_batch_with_update_columns。
返回受影响行数;空批返回 Ok(0),不生成语句。
仅 postgres feature 提供。MySQL 继续使用
TableQuery::upsert_batch_in_tx 的 ON DUPLICATE KEY UPDATE 语义,
本方法不改变 MySQL 的既有行为。
Sourcepub async fn upsert_batch_returning(
self,
rows: Vec<Record>,
conflict_columns: &[&str],
target: ReturningTarget<'_>,
) -> Result<Vec<Record>, BaseError>
pub async fn upsert_batch_returning( self, rows: Vec<Record>, conflict_columns: &[&str], target: ReturningTarget<'_>, ) -> Result<Vec<Record>, BaseError>
批量 UPSERT 并返回 RETURNING 行(保持输入顺序)。
conflict_columns 语义与 TableQuery::upsert_batch 完全相同:PostgreSQL
必须显式给出且命中唯一索引/约束;冲突时按默认白名单更新,返回写入后的行
(新插入行与冲突更新行都会出现在结果里)。
MySQL 没有 RETURNING,明确返回 BaseError::ConfigError。空批返回空向量。
Sourcepub async fn upsert_batch_with_update_columns(
self,
rows: Vec<Record>,
conflict_columns: &[&str],
update_columns: &[&str],
) -> Result<u64, BaseError>
pub async fn upsert_batch_with_update_columns( self, rows: Vec<Record>, conflict_columns: &[&str], update_columns: &[&str], ) -> Result<u64, BaseError>
PostgreSQL 批量 UPSERT,并显式指定 DO UPDATE SET 的更新列白名单。
更新列必须:存在于表定义、由调用方在待写行里提供、且不包含任何冲突列;
另外主键/租户/创建时间/自动列永远不允许出现在赋值列里。配置了 updated_at
时会被自动追加(语义同逐行 update)。
仅 postgres feature 提供。
Sourcepub async fn upsert_batch_do_nothing(
self,
rows: Vec<Record>,
conflict_columns: &[&str],
) -> Result<u64, BaseError>
pub async fn upsert_batch_do_nothing( self, rows: Vec<Record>, conflict_columns: &[&str], ) -> Result<u64, BaseError>
PostgreSQL 批量 UPSERT,冲突行保持原值(ON CONFLICT (...) DO NOTHING)。
与 TableQuery::upsert_batch 相同的前置处理;返回真正插入的行数。
仅 postgres feature 提供。
Sourcepub async fn upsert_batch_with_conflict_predicate(
self,
rows: Vec<Record>,
conflict_columns: &[&str],
predicate: Option<&str>,
) -> Result<u64, BaseError>
pub async fn upsert_batch_with_conflict_predicate( self, rows: Vec<Record>, conflict_columns: &[&str], predicate: Option<&str>, ) -> Result<u64, BaseError>
PostgreSQL 批量 UPSERT,冲突目标带部分唯一索引谓词
(ON CONFLICT (cols) WHERE (<predicate>) DO UPDATE ...)。
前置校验与默认更新列白名单同 TableQuery::upsert_batch;predicate 为
yang-db 的受信 SQL 表达式(拒绝分号 / 注释标记 / NUL)。表声明租户字段时,
冲突列仍必须包含该字段。
仅 postgres feature 提供。需要在调用方事务内执行时用
TableQuery::upsert_batch_in_tx_with_conflict_predicate。
Sourcepub async fn upsert_batch_in_tx(
self,
tx: &mut AnyTransaction,
rows: Vec<Record>,
columns: &[&str],
) -> Result<u64, BaseError>
pub async fn upsert_batch_in_tx( self, tx: &mut AnyTransaction, rows: Vec<Record>, columns: &[&str], ) -> Result<u64, BaseError>
在调用方事务内批量 upsert,返回受影响行数。
第三参数按运行时后端解释:
- MySQL:
INSERT ... ON DUPLICATE KEY UPDATE的赋值列白名单(既有语义, 未改变); - PostgreSQL:
ON CONFLICT的冲突列,必填且必须命中唯一索引/约束。 冲突时更新全部非冲突插入列(yang-db默认);调用方不得依赖隐式冲突推断。
空批返回 Ok(0),不生成语句。MySQL 的校验/默认值/时间戳/ODKU 行为与既有
实现完全一致。
§MySQL 调用方义务(框架不兜、也兜不了)
- 冲突键由表上的唯一索引决定,本方法无法指定;
- 本方法没有 WHERE。身份列(如
source_key)必须由调用方自己从update_columns里排除:把它放进赋值列,跨源命中就会把归属静默改写—— 而逐行路径的where_eq(id)+where_eq(owner)至少还会撞唯一索引响亮失败。 - 调用方应在事务前做归属预检,并在同一事务内做写后归属再断言。
§MySQL 返回值
rows_affected 之和 ∈ [N, 2N](1=插入,2=更新且值有变;sqlx 带
CLIENT_FOUND_ROWS ⇒「命中但值未变」也计 1)。不是行数(要行数用
rows.len()),也分不出 inserted/updated。
§PostgreSQL 返回值
插入与更新各计 1 行;DO NOTHING 跳过的冲突行不计入。
Sourcepub async fn upsert_batch_in_tx_with_update_columns(
self,
tx: &mut AnyTransaction,
rows: Vec<Record>,
conflict_columns: &[&str],
update_columns: &[&str],
) -> Result<u64, BaseError>
pub async fn upsert_batch_in_tx_with_update_columns( self, tx: &mut AnyTransaction, rows: Vec<Record>, conflict_columns: &[&str], update_columns: &[&str], ) -> Result<u64, BaseError>
在调用方事务内批量 UPSERT,并显式指定 PostgreSQL 的更新列白名单。
与 TableQuery::upsert_batch_with_update_columns 的校验/默认值/时间戳
规则完全一致,只是执行在调用方事务内。仅 postgres feature 提供。
Sourcepub async fn upsert_batch_do_nothing_in_tx(
self,
tx: &mut AnyTransaction,
rows: Vec<Record>,
conflict_columns: &[&str],
) -> Result<u64, BaseError>
pub async fn upsert_batch_do_nothing_in_tx( self, tx: &mut AnyTransaction, rows: Vec<Record>, conflict_columns: &[&str], ) -> Result<u64, BaseError>
在调用方事务内执行 PostgreSQL 批量 UPSERT,冲突行保持原值
(ON CONFLICT (...) DO NOTHING)。
仅 postgres feature 提供;MySQL 事务返回明确的
BaseError::ConfigError(MySQL 的 DO NOTHING 等价入口是 ODKU 的空赋值
白名单,语义不同,因此不在这里伪装)。
Sourcepub async fn upsert_batch_in_tx_with_conflict_predicate(
self,
tx: &mut AnyTransaction,
rows: Vec<Record>,
columns: &[&str],
predicate: Option<&str>,
) -> Result<u64, BaseError>
pub async fn upsert_batch_in_tx_with_conflict_predicate( self, tx: &mut AnyTransaction, rows: Vec<Record>, columns: &[&str], predicate: Option<&str>, ) -> Result<u64, BaseError>
在调用方事务内批量 upsert,并为冲突目标指定部分唯一索引谓词
(ON CONFLICT (<columns>) WHERE (<predicate>) DO ...)。
predicate 为 None 时与原 TableQuery::upsert_batch_in_tx 完全一致。
- PostgreSQL:把谓词透传给
yang-db的postgres::QueryBuilder::on_conflict_with_predicate。 - MySQL:
ON DUPLICATE KEY UPDATE没有部分索引冲突谓词。传入Some(_)时明确返回BaseError::ConfigError,绝不静默丢弃谓词。
表声明租户字段时,冲突列必须包含该字段(PostgreSQL 校验)。
Sourcepub async fn update(self, data: Record) -> Result<u64, BaseError>
pub async fn update(self, data: Record) -> Result<u64, BaseError>
执行 UPDATE 操作
更新表中的数据,包括以下步骤:
- 按表定义验证所有字段值
- 检查用户是否有字段的写入权限
- 构建 UPDATE SQL 语句
- 应用已配置的 WHERE 条件
- 执行更新操作
Sourcepub async fn update_in_tx(
self,
tx: &mut AnyTransaction,
data: Record,
) -> Result<u64, BaseError>
pub async fn update_in_tx( self, tx: &mut AnyTransaction, data: Record, ) -> Result<u64, BaseError>
在事务中执行 UPDATE 操作
与 TableQuery::update 一致的字段校验/权限/WHERE 守卫/自动 updated_at
逻辑,但在事务内执行。
Sourcepub async fn delete(self) -> Result<u64, BaseError>
pub async fn delete(self) -> Result<u64, BaseError>
执行 DELETE 操作
删除表中的数据,支持软删除和物理删除两种模式:
- 如果配置了软删除字段(soft_delete_field),执行 UPDATE 设置删除标记
- 如果未配置软删除字段,执行物理删除
- 应用已配置的 WHERE 条件
Sourcepub async fn delete_in_tx(
self,
tx: &mut AnyTransaction,
) -> Result<u64, BaseError>
pub async fn delete_in_tx( self, tx: &mut AnyTransaction, ) -> Result<u64, BaseError>
在事务中执行 DELETE 操作
与 TableQuery::delete 一致:配置了软删除字段时走 UPDATE 标记(同样在
事务内),否则物理删除;WHERE 守卫与软删语义完全复用。
Trait Implementations§
Source§impl Clone for TableQuery
impl Clone for TableQuery
Auto Trait Implementations§
impl !RefUnwindSafe for TableQuery
impl !UnwindSafe for TableQuery
impl Forget for TableQuery
impl Freeze for TableQuery
impl Move for TableQuery
impl Send for TableQuery
impl Sync for TableQuery
impl Unpin for TableQuery
impl UnsafeUnpin for TableQuery
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
Source§fn in_current_span(self) -> Instrumented<Self> ⓘ
fn in_current_span(self) -> Instrumented<Self> ⓘ
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
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 moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
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