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    #[allow(dead_code)] // 兼容构造器:测试与外部 crate 仍可使用,生产主路径走 new_sourced。
25    pub(crate) fn new(
26        table_config: Arc<TableConfig>,
27        user_roles: Arc<[String]>,
28        pool: Option<crate::database::AnyPool>,
29    ) -> Self {
30        Self::new_sourced(
31            table_config,
32            user_roles,
33            pool,
34            crate::datasource::DatasourceId::default_source(),
35        )
36    }
37
38    /// 创建带逻辑数据源身份的查询构建器。
39    #[cfg(any(feature = "mysql", feature = "postgres"))]
40    pub(crate) fn new_sourced(
41        table_config: Arc<TableConfig>,
42        user_roles: Arc<[String]>,
43        pool: Option<crate::database::AnyPool>,
44        pool_source: crate::datasource::DatasourceId,
45    ) -> Self {
46        let user_roles_set: HashSet<String> = user_roles.iter().cloned().collect();
47        Self {
48            table_config,
49            user_roles,
50            user_roles_set,
51            query_params: QueryParams::new(),
52            nulls_orders: std::collections::HashMap::new(),
53            any_conditions: Vec::new(),
54            include_trashed: false,
55            tenant_scope: None,
56            pool,
57            pool_source,
58            require_sourced_tx: false,
59            slow_threshold: None,
60            request_id: None,
61            regex_cache: RegexCache::default(),
62        }
63    }
64
65    /// 创建新的查询构建器(无数据库连接池)
66    ///
67    /// 当未启用任何数据库 feature 时使用此方法。
68    #[cfg(not(any(feature = "mysql", feature = "postgres")))]
69    pub(crate) fn new(
70        table_config: Arc<TableConfig>,
71        user_roles: Arc<[String]>,
72        _pool: Option<()>,
73    ) -> Self {
74        let user_roles_set: HashSet<String> = user_roles.iter().cloned().collect();
75        Self {
76            table_config,
77            user_roles,
78            user_roles_set,
79            query_params: QueryParams::new(),
80            nulls_orders: std::collections::HashMap::new(),
81            any_conditions: Vec::new(),
82            include_trashed: false,
83            tenant_scope: None,
84            pool_source: crate::datasource::DatasourceId::default_source(),
85            require_sourced_tx: false,
86            slow_threshold: None,
87            request_id: None,
88            regex_cache: RegexCache::default(),
89        }
90    }
91
92    /// 设置慢查询阈值(链式)。超过该耗时的单次执行会 `tracing::warn!`。
93    ///
94    /// 通常由 `ActionContext::table_query()` 从全局 `ObservabilityConfig` 注入;
95    /// 也可手动覆盖。`None`/不调用时不启用慢查询日志。
96    pub fn with_slow_threshold(mut self, threshold: Option<std::time::Duration>) -> Self {
97        self.slow_threshold = threshold;
98        self
99    }
100
101    /// 设置本次查询关联的 request_id(链式),用于慢查询日志串联。
102    pub fn with_request_id(mut self, request_id: crate::action::RequestId) -> Self {
103        self.request_id = Some(request_id);
104        self
105    }
106
107    /// 注入共享有界正则缓存(链式)。通常由 `ActionContext::table_query()` 从
108    /// [`crate::tools::Tools`] 注入;未注入时使用默认容量缓存。
109    pub fn with_regex_cache(mut self, cache: RegexCache) -> Self {
110        self.regex_cache = cache;
111        self
112    }
113
114    /// 按字段排序并指定 NULL 的位置。
115    ///
116    /// 字段/权限校验与 [`TableQuery::order_by`] 完全一致。PostgreSQL 渲染原生
117    /// `NULLS FIRST/LAST`;MySQL 用 `field IS NULL` 排序表达式模拟(NULL 标记列
118    /// 前置于主排序键)。
119    pub fn order_nulls(
120        mut self,
121        field: &str,
122        order: SortOrder,
123        nulls_first: bool,
124    ) -> Result<Self, BaseError> {
125        self.validate_order_field(field)?;
126        self.query_params.order_by.push((field.to_string(), order));
127        self.nulls_orders.insert(field.to_string(), nulls_first);
128        Ok(self)
129    }
130
131    /// 追加 `IN` 条件,并按参数上限自动分块。
132    ///
133    /// 与 [`TableQuery::where_in`] 的 500 条上限不同,本入口把超长列表拆成多个
134    /// `IN` 子句并以 `OR` 连接,避免单条语句参数数量无限增长。
135    pub fn where_in_chunked(self, field: &str, values: Vec<Value>) -> Result<Self, BaseError> {
136        if values.is_empty() {
137            return Err(BaseError::ParamInvalid(
138                "values".to_string(),
139                "IN 列表不能为空".to_string(),
140            ));
141        }
142        let chunks = values
143            .chunks(Self::MAX_IN_LIST_SIZE)
144            .map(|chunk| WhereCondition::In {
145                field: field.to_string(),
146                values: chunk.to_vec(),
147            })
148            .collect::<Vec<_>>();
149        let condition = match chunks.len() {
150            1 => chunks.into_iter().next().expect("len == 1"),
151            _ => WhereCondition::Or { conditions: chunks },
152        };
153        self.where_tree(condition)
154    }
155
156    /// `field = ANY($1)` 数组参数入口。
157    ///
158    /// PostgreSQL 后端把整个列表作为单个数组参数绑定,参数个数不随列表长度增长;
159    /// 其它后端(或尚未注入连接池时)降级为 [`TableQuery::where_in_chunked`]。
160    #[cfg_attr(not(feature = "postgres"), allow(unused_mut))]
161    pub fn where_any(mut self, field: &str, values: Vec<Value>) -> Result<Self, BaseError> {
162        if values.is_empty() {
163            return Err(BaseError::ParamInvalid(
164                "values".to_string(),
165                "ANY 列表不能为空".to_string(),
166            ));
167        }
168        // 逐块复用 IN 的校验(字段存在性/筛选权限/值类型),避免绕过受保护层。
169        for chunk in values.chunks(Self::MAX_IN_LIST_SIZE) {
170            self.validate_condition_tree(
171                &WhereCondition::In {
172                    field: field.to_string(),
173                    values: chunk.to_vec(),
174                },
175                0,
176            )?;
177        }
178
179        #[cfg(feature = "postgres")]
180        if self
181            .pool
182            .as_ref()
183            .is_some_and(|pool| pool.backend() == yang_db::BackendKind::PostgreSql)
184        {
185            self.any_conditions.push((field.to_string(), values));
186            return Ok(self);
187        }
188
189        self.where_in_chunked(field, values)
190    }
191
192    /// 要求事务必须显式携带数据源身份(多源应用由 ActionContext 注入)。
193    pub fn require_sourced_tx(mut self, required: bool) -> Self {
194        self.require_sourced_tx = required;
195        self
196    }
197
198    /// 校验事务与表查询属于同一数据源(先比后端,再比逻辑源)。
199    ///
200    /// 旧构造器创建的事务没有逻辑源(`None`);只有默认源的表允许这种事务,
201    /// 具名源表必须显式使用同源事务。
202    #[cfg(any(feature = "mysql", feature = "postgres"))]
203    pub(crate) fn ensure_same_source(
204        &self,
205        tx: &crate::database::AnyTransaction,
206    ) -> Result<(), crate::error::BaseError> {
207        let mismatch = |expected: String| crate::error::BaseError::DatasourceMismatch {
208            table: self.table_config.table_name.clone(),
209            expected,
210            actual: format!(
211                "{}:{:?}",
212                tx.source()
213                    .map_or_else(|| "unscoped".to_string(), ToString::to_string),
214                tx.backend()
215            ),
216        };
217        let Some(pool) = &self.pool else {
218            return Err(crate::error::BaseError::ConfigError(
219                "TableQuery 未绑定连接池,不能执行事务".to_string(),
220            ));
221        };
222        if pool.backend() != tx.backend() {
223            return Err(mismatch(format!(
224                "{}:{:?}",
225                self.pool_source,
226                pool.backend()
227            )));
228        }
229        if self.require_sourced_tx && tx.source().is_none() {
230            return Err(mismatch("sourced-transaction".to_string()));
231        }
232        match tx.source() {
233            Some(source) if source == &self.pool_source => Ok(()),
234            Some(_) => Err(mismatch(self.pool_source.to_string())),
235            None if self.pool_source.is_default() => Ok(()),
236            None => Err(mismatch(self.pool_source.to_string())),
237        }
238    }
239
240    /// 创建仅有表配置、无数据库连接池的查询构建器(测试用)
241    ///
242    /// 使用空的用户角色列表,适合访问无权限限制字段的单元测试。
243    #[cfg(all(test, feature = "mysql"))]
244    pub(crate) fn new_without_pool(table_config: Arc<TableConfig>) -> Self {
245        Self::new(table_config, Arc::from(vec![]), None)
246    }
247}
248
249#[cfg(all(test, feature = "mysql"))]
250mod tests {
251    use super::*;
252    use crate::table::{Field, Table};
253
254    fn query(table: Table) -> TableQuery {
255        let definition = table.build().expect("测试表定义应有效");
256        TableQuery::new(
257            definition.shared_config(),
258            Arc::from(vec!["admin".to_string()]),
259            None,
260        )
261    }
262
263    /// 超过 1000 条的 IN 列表必须拆成多个 `IN` 子句(每个不超过上限)。
264    #[test]
265    fn where_in_chunked_splits_large_lists() {
266        let values: Vec<Value> = (0..1200).map(|i| serde_json::json!(i)).collect();
267        let query = query(Table::new("tq_in_chunks").fields([Field::id("id")]))
268            .where_in_chunked("id", values)
269            .expect("分块 IN 应通过校验");
270
271        assert_eq!(query.query_params.where_conditions.len(), 1);
272        match &query.query_params.where_conditions[0] {
273            WhereCondition::Or { conditions } => {
274                assert_eq!(conditions.len(), 3, "1200 条应拆成 3 块");
275                for chunk in conditions {
276                    match chunk {
277                        WhereCondition::In { values, .. } => {
278                            assert!(!values.is_empty());
279                            assert!(values.len() <= TableQuery::MAX_IN_LIST_SIZE);
280                        }
281                        other => panic!("分块元素应为 IN,实际: {other:?}"),
282                    }
283                }
284            }
285            other => panic!("超长 IN 应折叠为 OR 组,实际: {other:?}"),
286        }
287    }
288
289    /// 非 PostgreSQL 后端上 `where_any` 降级为分块 IN,而不是报错。
290    #[test]
291    fn where_any_falls_back_to_chunked_in() {
292        let values: Vec<Value> = (0..1200).map(|i| serde_json::json!(i)).collect();
293        let query = query(Table::new("tq_any_fallback").fields([Field::id("id")]))
294            .where_any("id", values)
295            .expect("where_any 应通过校验");
296
297        assert!(query.any_conditions.is_empty());
298        assert!(matches!(
299            query.query_params.where_conditions[0],
300            WhereCondition::Or { .. }
301        ));
302    }
303}