Skip to main content

yang_base/table/table_query/
build.rs

1//! 构造与运行期注入:两个 `new` 构造器(按 `mysql` feature 区分连接池签名)、
2//! 慢查询阈值 / request_id 链式注入,以及测试专用的无连接池构造器。
3
4use super::TableQuery;
5use crate::error::BaseError;
6use crate::table::{QueryParams, RegexCache, SortOrder, TableConfig, WhereCondition};
7use serde_json::Value;
8use std::collections::HashSet;
9use std::sync::Arc;
10
11impl TableQuery {
12    /// 创建新的查询构建器
13    ///
14    /// # 参数
15    ///
16    /// - `table_config`:表配置引用
17    /// - `user_roles`:用户角色列表(`Arc<[String]>` 共享所有权)
18    /// - `pool`:运行时数据库连接池句柄(MySQL / PostgreSQL 按后端分派,可选)
19    ///
20    /// # 返回值
21    ///
22    /// 返回新的 TableQuery 实例
23    #[cfg(any(feature = "mysql", feature = "postgres"))]
24    pub(crate) fn new(
25        table_config: Arc<TableConfig>,
26        user_roles: Arc<[String]>,
27        pool: Option<crate::database::AnyPool>,
28    ) -> Self {
29        let user_roles_set: HashSet<String> = user_roles.iter().cloned().collect();
30        Self {
31            table_config,
32            user_roles,
33            user_roles_set,
34            query_params: QueryParams::new(),
35            nulls_orders: std::collections::HashMap::new(),
36            any_conditions: Vec::new(),
37            include_trashed: false,
38            tenant_scope: None,
39            pool,
40            slow_threshold: None,
41            request_id: None,
42            regex_cache: RegexCache::default(),
43        }
44    }
45
46    /// 创建新的查询构建器(无数据库连接池)
47    ///
48    /// 当未启用任何数据库 feature 时使用此方法。
49    #[cfg(not(any(feature = "mysql", feature = "postgres")))]
50    pub(crate) fn new(
51        table_config: Arc<TableConfig>,
52        user_roles: Arc<[String]>,
53        _pool: Option<()>,
54    ) -> Self {
55        let user_roles_set: HashSet<String> = user_roles.iter().cloned().collect();
56        Self {
57            table_config,
58            user_roles,
59            user_roles_set,
60            query_params: QueryParams::new(),
61            nulls_orders: std::collections::HashMap::new(),
62            any_conditions: Vec::new(),
63            include_trashed: false,
64            tenant_scope: None,
65            slow_threshold: None,
66            request_id: None,
67            regex_cache: RegexCache::default(),
68        }
69    }
70
71    /// 设置慢查询阈值(链式)。超过该耗时的单次执行会 `tracing::warn!`。
72    ///
73    /// 通常由 `ActionContext::table_query()` 从全局 `ObservabilityConfig` 注入;
74    /// 也可手动覆盖。`None`/不调用时不启用慢查询日志。
75    pub fn with_slow_threshold(mut self, threshold: Option<std::time::Duration>) -> Self {
76        self.slow_threshold = threshold;
77        self
78    }
79
80    /// 设置本次查询关联的 request_id(链式),用于慢查询日志串联。
81    pub fn with_request_id(mut self, request_id: crate::action::RequestId) -> Self {
82        self.request_id = Some(request_id);
83        self
84    }
85
86    /// 注入共享有界正则缓存(链式)。通常由 `ActionContext::table_query()` 从
87    /// [`crate::tools::Tools`] 注入;未注入时使用默认容量缓存。
88    pub fn with_regex_cache(mut self, cache: RegexCache) -> Self {
89        self.regex_cache = cache;
90        self
91    }
92
93    /// 按字段排序并指定 NULL 的位置。
94    ///
95    /// 字段/权限校验与 [`TableQuery::order_by`] 完全一致。PostgreSQL 渲染原生
96    /// `NULLS FIRST/LAST`;MySQL 用 `field IS NULL` 排序表达式模拟(NULL 标记列
97    /// 前置于主排序键)。
98    pub fn order_nulls(
99        mut self,
100        field: &str,
101        order: SortOrder,
102        nulls_first: bool,
103    ) -> Result<Self, BaseError> {
104        self.validate_order_field(field)?;
105        self.query_params.order_by.push((field.to_string(), order));
106        self.nulls_orders.insert(field.to_string(), nulls_first);
107        Ok(self)
108    }
109
110    /// 追加 `IN` 条件,并按参数上限自动分块。
111    ///
112    /// 与 [`TableQuery::where_in`] 的 500 条上限不同,本入口把超长列表拆成多个
113    /// `IN` 子句并以 `OR` 连接,避免单条语句参数数量无限增长。
114    pub fn where_in_chunked(self, field: &str, values: Vec<Value>) -> Result<Self, BaseError> {
115        if values.is_empty() {
116            return Err(BaseError::ParamInvalid(
117                "values".to_string(),
118                "IN 列表不能为空".to_string(),
119            ));
120        }
121        let chunks = values
122            .chunks(Self::MAX_IN_LIST_SIZE)
123            .map(|chunk| WhereCondition::In {
124                field: field.to_string(),
125                values: chunk.to_vec(),
126            })
127            .collect::<Vec<_>>();
128        let condition = match chunks.len() {
129            1 => chunks.into_iter().next().expect("len == 1"),
130            _ => WhereCondition::Or { conditions: chunks },
131        };
132        self.where_tree(condition)
133    }
134
135    /// `field = ANY($1)` 数组参数入口。
136    ///
137    /// PostgreSQL 后端把整个列表作为单个数组参数绑定,参数个数不随列表长度增长;
138    /// 其它后端(或尚未注入连接池时)降级为 [`TableQuery::where_in_chunked`]。
139    #[cfg_attr(not(feature = "postgres"), allow(unused_mut))]
140    pub fn where_any(mut self, field: &str, values: Vec<Value>) -> Result<Self, BaseError> {
141        if values.is_empty() {
142            return Err(BaseError::ParamInvalid(
143                "values".to_string(),
144                "ANY 列表不能为空".to_string(),
145            ));
146        }
147        // 逐块复用 IN 的校验(字段存在性/筛选权限/值类型),避免绕过受保护层。
148        for chunk in values.chunks(Self::MAX_IN_LIST_SIZE) {
149            self.validate_condition_tree(
150                &WhereCondition::In {
151                    field: field.to_string(),
152                    values: chunk.to_vec(),
153                },
154                0,
155            )?;
156        }
157
158        #[cfg(feature = "postgres")]
159        if self
160            .pool
161            .as_ref()
162            .is_some_and(|pool| pool.backend() == yang_db::BackendKind::PostgreSql)
163        {
164            self.any_conditions.push((field.to_string(), values));
165            return Ok(self);
166        }
167
168        self.where_in_chunked(field, values)
169    }
170
171    /// 创建仅有表配置、无数据库连接池的查询构建器(测试用)
172    ///
173    /// 使用空的用户角色列表,适合访问无权限限制字段的单元测试。
174    #[cfg(all(test, feature = "mysql"))]
175    pub(crate) fn new_without_pool(table_config: Arc<TableConfig>) -> Self {
176        Self::new(table_config, Arc::from(vec![]), None)
177    }
178}
179
180#[cfg(all(test, feature = "mysql"))]
181mod tests {
182    use super::*;
183    use crate::table::{Field, Table};
184
185    fn query(table: Table) -> TableQuery {
186        let definition = table.build().expect("测试表定义应有效");
187        TableQuery::new(
188            definition.shared_config(),
189            Arc::from(vec!["admin".to_string()]),
190            None,
191        )
192    }
193
194    /// 超过 1000 条的 IN 列表必须拆成多个 `IN` 子句(每个不超过上限)。
195    #[test]
196    fn where_in_chunked_splits_large_lists() {
197        let values: Vec<Value> = (0..1200).map(|i| serde_json::json!(i)).collect();
198        let query = query(Table::new("tq_in_chunks").fields([Field::id("id")]))
199            .where_in_chunked("id", values)
200            .expect("分块 IN 应通过校验");
201
202        assert_eq!(query.query_params.where_conditions.len(), 1);
203        match &query.query_params.where_conditions[0] {
204            WhereCondition::Or { conditions } => {
205                assert_eq!(conditions.len(), 3, "1200 条应拆成 3 块");
206                for chunk in conditions {
207                    match chunk {
208                        WhereCondition::In { values, .. } => {
209                            assert!(!values.is_empty());
210                            assert!(values.len() <= TableQuery::MAX_IN_LIST_SIZE);
211                        }
212                        other => panic!("分块元素应为 IN,实际: {other:?}"),
213                    }
214                }
215            }
216            other => panic!("超长 IN 应折叠为 OR 组,实际: {other:?}"),
217        }
218    }
219
220    /// 非 PostgreSQL 后端上 `where_any` 降级为分块 IN,而不是报错。
221    #[test]
222    fn where_any_falls_back_to_chunked_in() {
223        let values: Vec<Value> = (0..1200).map(|i| serde_json::json!(i)).collect();
224        let query = query(Table::new("tq_any_fallback").fields([Field::id("id")]))
225            .where_any("id", values)
226            .expect("where_any 应通过校验");
227
228        assert!(query.any_conditions.is_empty());
229        assert!(matches!(
230            query.query_params.where_conditions[0],
231            WhereCondition::Or { .. }
232        ));
233    }
234}