Skip to main content

TableQuery

Struct TableQuery 

Source
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

Source

pub fn with_slow_threshold(self, threshold: Option<Duration>) -> Self

设置慢查询阈值(链式)。超过该耗时的单次执行会 tracing::warn!。

通常由 ActionContext::table_query() 从全局 ObservabilityConfig 注入; 也可手动覆盖。None/不调用时不启用慢查询日志。

Source

pub fn with_request_id(self, request_id: RequestId) -> Self

设置本次查询关联的 request_id(链式),用于慢查询日志串联。

Source

pub fn with_regex_cache(self, cache: RegexCache) -> Self

注入共享有界正则缓存(链式)。通常由 ActionContext::table_query() 从 crate::tools::Tools 注入;未注入时使用默认容量缓存。

Source

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 标记列 前置于主排序键)。

Source

pub fn where_in_chunked( self, field: &str, values: Vec<Value>, ) -> Result<Self, BaseError>

追加 IN 条件,并按参数上限自动分块。

与 TableQuery::where_in 的 500 条上限不同,本入口把超长列表拆成多个 IN 子句并以 OR 连接,避免单条语句参数数量无限增长。

Source

pub fn where_any( self, field: &str, values: Vec<Value>, ) -> Result<Self, BaseError>

field = ANY($1) 数组参数入口。

PostgreSQL 后端把整个列表作为单个数组参数绑定,参数个数不随列表长度增长; 其它后端(或尚未注入连接池时)降级为 TableQuery::where_in_chunked。

Source

pub fn require_sourced_tx(self, required: bool) -> Self

要求事务必须显式携带数据源身份(多源应用由 ActionContext 注入)。

Source§

impl TableQuery

Source

pub fn select_fields(self, fields: &[&str]) -> Result<Self, BaseError>

选择要查询的字段。

会校验字段存在,并校验当前用户角色具备这些字段的读取权限。

Source

pub fn where_eq(self, field: &str, value: Value) -> Result<Self, BaseError>

添加等于条件 (WHERE field = value)

添加 WHERE 等于条件,并验证:

  1. 字段是否存在于表配置中
  2. 用户是否有字段的筛选权限
§参数
  • field:字段名
  • value:比较值
§返回值
  • Ok(Self):验证通过,返回 self 支持链式调用
  • Err(BaseError):验证失败,返回错误
§错误
  • BaseError::FieldNotFound:字段不存在
  • BaseError::FieldPermissionDenied:用户无筛选权限
§示例
ⓘ
use serde_json::json;

let query = query.where_eq("status", json!("active"))?;
Source

pub fn where_in( self, field: &str, values: Vec<Value>, ) -> Result<Self, BaseError>

添加包含条件 (WHERE field IN (values))

添加 WHERE IN 条件,并验证:

  1. 字段是否存在于表配置中
  2. 用户是否有字段的筛选权限
§参数
  • 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)])?;
Source

pub fn where_like(self, field: &str, pattern: String) -> Result<Self, BaseError>

添加模糊匹配条件 (WHERE field LIKE pattern)

添加 WHERE LIKE 条件,并验证:

  1. 字段是否存在于表配置中
  2. 用户是否有字段的筛选权限
§参数
  • field:字段名
  • pattern:匹配模式,支持 % 和 _ 通配符
§返回值
  • Ok(Self):验证通过,返回 self 支持链式调用
  • Err(BaseError):验证失败,返回错误
§错误
  • BaseError::FieldNotFound:字段不存在
  • BaseError::FieldPermissionDenied:用户无筛选权限
§示例
ⓘ
let query = query.where_like("name", "%alice%")?;
Source

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")?;
Source

pub fn where_ne(self, field: &str, value: Value) -> Result<Self, BaseError>

添加不等于条件 (WHERE field <> value)

添加 WHERE 不等于条件,并验证:

  1. 字段是否存在于表配置中
  2. 用户是否有字段的筛选权限
§参数
  • field:字段名
  • value:比较值
§返回值
  • Ok(Self):验证通过,返回 self 支持链式调用
  • Err(BaseError):验证失败,返回错误
§错误
  • BaseError::FieldNotFound:字段不存在
  • BaseError::FieldPermissionDenied:用户无筛选权限
Source

pub fn where_lt(self, field: &str, value: Value) -> Result<Self, BaseError>

添加小于条件 (WHERE field < value)

添加 WHERE 小于条件,并验证:

  1. 字段是否存在于表配置中
  2. 用户是否有字段的筛选权限
§参数
  • field:字段名
  • value:比较值
§返回值
  • Ok(Self):验证通过,返回 self 支持链式调用
  • Err(BaseError):验证失败,返回错误
§错误
  • BaseError::FieldNotFound:字段不存在
  • BaseError::FieldPermissionDenied:用户无筛选权限
Source

pub fn where_lte(self, field: &str, value: Value) -> Result<Self, BaseError>

添加小于等于条件 (WHERE field <= value)

添加 WHERE 小于等于条件,并验证:

  1. 字段是否存在于表配置中
  2. 用户是否有字段的筛选权限
§参数
  • field:字段名
  • value:比较值
§返回值
  • Ok(Self):验证通过,返回 self 支持链式调用
  • Err(BaseError):验证失败,返回错误
§错误
  • BaseError::FieldNotFound:字段不存在
  • BaseError::FieldPermissionDenied:用户无筛选权限
Source

pub fn where_gt(self, field: &str, value: Value) -> Result<Self, BaseError>

添加大于条件 (WHERE field > value)

添加 WHERE 大于条件,并验证:

  1. 字段是否存在于表配置中
  2. 用户是否有字段的筛选权限
§参数
  • field:字段名
  • value:比较值
§返回值
  • Ok(Self):验证通过,返回 self 支持链式调用
  • Err(BaseError):验证失败,返回错误
§错误
  • BaseError::FieldNotFound:字段不存在
  • BaseError::FieldPermissionDenied:用户无筛选权限
Source

pub fn where_gte(self, field: &str, value: Value) -> Result<Self, BaseError>

添加大于等于条件 (WHERE field >= value)

添加 WHERE 大于等于条件,并验证:

  1. 字段是否存在于表配置中
  2. 用户是否有字段的筛选权限
§参数
  • field:字段名
  • value:比较值
§返回值
  • Ok(Self):验证通过,返回 self 支持链式调用
  • Err(BaseError):验证失败,返回错误
§错误
  • BaseError::FieldNotFound:字段不存在
  • BaseError::FieldPermissionDenied:用户无筛选权限
Source

pub fn where_between( self, field: &str, lo: Value, hi: Value, ) -> Result<Self, BaseError>

添加区间条件 (WHERE field BETWEEN lo AND hi)

添加 WHERE BETWEEN 条件,并验证:

  1. 字段是否存在于表配置中
  2. 用户是否有字段的筛选权限

当 lo > hi 时 BETWEEN 返回空集(MySQL 标准行为,框架不做特殊处理)。

§参数
  • field:字段名
  • lo:区间下界(包含)
  • hi:区间上界(包含)
§返回值
  • Ok(Self):验证通过,返回 self 支持链式调用
  • Err(BaseError):验证失败,返回错误
§错误
  • BaseError::FieldNotFound:字段不存在
  • BaseError::FieldPermissionDenied:用户无筛选权限
Source

pub fn where_null(self, field: &str) -> Result<Self, BaseError>

添加空值判断 (WHERE field IS NULL)

添加 WHERE IS NULL 条件,并验证:

  1. 字段是否存在于表配置中
  2. 用户是否有字段的筛选权限
§参数
  • field:字段名
§返回值
  • Ok(Self):验证通过,返回 self 支持链式调用
  • Err(BaseError):验证失败,返回错误
§错误
  • BaseError::FieldNotFound:字段不存在
  • BaseError::FieldPermissionDenied:用户无筛选权限
Source

pub fn where_not_null(self, field: &str) -> Result<Self, BaseError>

添加非空值判断 (WHERE field IS NOT NULL)

添加 WHERE IS NOT NULL 条件,并验证:

  1. 字段是否存在于表配置中
  2. 用户是否有字段的筛选权限
§参数
  • field:字段名
§返回值
  • Ok(Self):验证通过,返回 self 支持链式调用
  • Err(BaseError):验证失败,返回错误
§错误
  • BaseError::FieldNotFound:字段不存在
  • BaseError::FieldPermissionDenied:用户无筛选权限
Source

pub fn where_not_in( self, field: &str, values: Vec<Value>, ) -> Result<Self, BaseError>

添加不在列表条件 (WHERE field NOT IN (values))

添加 WHERE NOT IN 条件,并验证:

  1. 字段是否存在于表配置中
  2. 用户是否有字段的筛选权限
§参数
  • field:字段名
  • values:排除值列表
§返回值
  • Ok(Self):验证通过,返回 self 支持链式调用
  • Err(BaseError):验证失败,返回错误
§错误
  • BaseError::FieldNotFound:字段不存在
  • BaseError::FieldPermissionDenied:用户无筛选权限
Source

pub fn order_by(self, field: &str, order: SortOrder) -> Result<Self, BaseError>

添加排序规则。

会校验字段存在、字段允许排序,以及当前用户角色具备排序权限。

Source

pub fn page(self, page: usize, page_size: usize) -> Result<Self, BaseError>

设置分页参数 (LIMIT and OFFSET)

设置查询的分页参数

§参数
  • page:当前页码,从 1 开始
  • page_size:每页大小
§返回值

返回 self 支持链式调用

§示例
ⓘ
let query = query.page(1, 20)?;
Source

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)仍在本地强制执行。

Source

pub fn with_trashed(self) -> Self

在读取路径包含软删除记录

默认情况下,配置了 soft_delete_field 的表会在 select/count/paginate 时自动追加 软删字段 IS NULL 过滤,隐藏已软删行。调用本方法后,本次查询 读取全量数据(含已软删行)。

§返回值

返回 self 支持链式调用

Source

pub fn where_primary_key_eq(self, value: Value) -> Result<Self, BaseError>

注入受信的主键等值条件。

内置 get/put/del 的主键定位是 Action 自有寻址机制,不是调用方可选的结构化 筛选,因此与 Self::scope_tenant 一样绕过 filterable 业务筛选权限; 值仍按主键字段类型校验(null 交由渲染器规范化为 IS NULL,匹配不到记录)。

Source

pub fn where_primary_keys(self, keys: &Record) -> Result<Self, BaseError>

注入复合主键等值条件(按声明顺序逐列 AND)。

Source

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) },
    ])?;
Source

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):字段不存在 / 无筛选权限 / 嵌套超限
Source

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):字段不存在 / 无筛选权限 / 嵌套超限
Source

pub fn get_query_params(&self) -> &QueryParams

获取查询参数的引用

用于测试或调试,获取当前构建的查询参数

§返回值

返回查询参数的引用

Source

pub fn apply_params(self, params: QueryParams) -> Result<Self, BaseError>

应用通用列表参数,并复用本类型现有的字段/筛选/排序/分页权限校验。

Source

pub fn get_user_roles(&self) -> &[String]

获取用户角色列表的引用

用于测试或调试,获取用户角色列表

§返回值

返回用户角色列表的引用

Source§

impl TableQuery

数据库执行方法(需要启用 mysql 或 postgres feature)

Source

pub async fn paginate_records( self, ) -> Result<PaginatedResult<Record>, BaseError>

执行分页查询并返回 schema-first Record。

未显式设置分页时会使用默认页码和默认每页大小,并确保数据查询带有 LIMIT/OFFSET。

Source

pub async fn count(self) -> Result<u64, BaseError>

执行 COUNT 查询获取总记录数

§返回值
  • Ok(u64):查询成功,返回总记录数
  • Err(BaseError):查询失败,返回错误
Source

pub async fn exists(self) -> Result<bool, BaseError>

判断是否存在至少一条匹配记录(SELECT 1 ... LIMIT 1 语义)。

与 count() == 0 相比不扫描全部匹配行,适合权限/去重前置判断。

Source

pub async fn all(self) -> Result<Vec<Record>, BaseError>

查询全部匹配记录。

Source

pub async fn all_in_tx( self, tx: &mut AnyTransaction, ) -> Result<Vec<Record>, BaseError>

在事务中查询全部匹配记录。

Source

pub async fn optional(self) -> Result<Option<Record>, BaseError>

查询可选单条记录。

Source

pub async fn one(self) -> Result<Record, BaseError>

查询单条记录;没有匹配记录时返回 BaseError::RecordNotFound。

Source§

impl TableQuery

Source

pub async fn insert(self, data: Record) -> Result<u64, BaseError>

执行 INSERT 操作

插入数据到表中,包括以下步骤:

  1. 按表定义验证所有字段值
  2. 检查用户是否有字段的写入权限
  3. 构建 INSERT SQL 语句
  4. 执行插入操作
§返回值
  • Ok(1):插入成功
  • Err(BaseError):插入失败
Source

pub async fn insert_in_tx( self, tx: &mut AnyTransaction, data: Record, ) -> Result<u64, BaseError>

在事务中执行 INSERT 操作

与 TableQuery::insert 完全一致的写权限校验/默认值填充/时间戳/必填校验 流程,但在调用方提供的事务内执行,可与其它写操作原子提交。

Source

pub async fn insert_returning( self, data: Record, target: ReturningTarget<'_>, ) -> Result<Record, BaseError>

执行 INSERT 并返回 RETURNING 结果。

§MySQL 限制

MySQL 没有 RETURNING:只有「目标就是整型主键」的请求能由 last_insert_id 满足;All、多列或非主键列的 Columns 返回明确的 BaseError::ConfigError,绝不用提交的输入伪造返回值。

Source

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,绝不按输入伪造返回值。

空批返回空向量,不生成语句。

Source

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。

Source

pub async fn insert_returning_pk_value( self, data: Record, ) -> Result<(u64, Value), BaseError>

执行 INSERT 并返回真实类型的主键值。

PostgreSQL 走 INSERT ... RETURNING <主键>;MySQL 走 last_insert_id (仅整型主键,非整型返回明确错误)。返回 (影响行数, 主键 JSON 值)。

Source

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):插入失败或主键非整型
Source

pub async fn insert_returning_id_in_tx( self, tx: &mut AnyTransaction, data: Record, ) -> Result<(u64, u64), BaseError>

在事务中执行 INSERT 并返回自增主键

与 TableQuery::insert_returning_id 一致,但在事务内执行;整型主键限制 同样适用。

Source

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 的既有行为。

Source

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。空批返回空向量。

Source

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 提供。

Source

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 提供。

Source

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。

Source

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 跳过的冲突行不计入。

Source

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 提供。

Source

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 的空赋值 白名单,语义不同,因此不在这里伪装)。

Source

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 校验)。

Source

pub async fn update(self, data: Record) -> Result<u64, BaseError>

执行 UPDATE 操作

更新表中的数据,包括以下步骤:

  1. 按表定义验证所有字段值
  2. 检查用户是否有字段的写入权限
  3. 构建 UPDATE SQL 语句
  4. 应用已配置的 WHERE 条件
  5. 执行更新操作
Source

pub async fn update_in_tx( self, tx: &mut AnyTransaction, data: Record, ) -> Result<u64, BaseError>

在事务中执行 UPDATE 操作

与 TableQuery::update 一致的字段校验/权限/WHERE 守卫/自动 updated_at 逻辑,但在事务内执行。

Source

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

执行 DELETE 操作

删除表中的数据,支持软删除和物理删除两种模式:

  1. 如果配置了软删除字段(soft_delete_field),执行 UPDATE 设置删除标记
  2. 如果未配置软删除字段,执行物理删除
  3. 应用已配置的 WHERE 条件
Source

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

Source§

fn clone(&self) -> Self

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
Source§

impl Debug for TableQuery

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

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> DynClone for T
where T: Clone,

Source§

fn __clone_box(&self, _: Private) -> *mut ()

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

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

Source§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
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> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. 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 = !

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