Skip to main content

yang_base/table/table_query/
build.rs

1//! 构造与运行期注入:两个 `new` 构造器(按 `mysql` feature 区分连接池签名)、
2//! 慢查询阈值 / request_id 链式注入,以及测试专用的无连接池构造器。
3
4use super::TableQuery;
5use crate::table::{QueryParams, TableConfig};
6use std::collections::HashSet;
7use std::sync::Arc;
8
9impl TableQuery {
10    /// 创建新的查询构建器
11    ///
12    /// # 参数
13    ///
14    /// - `table_config`:表配置引用
15    /// - `user_roles`:用户角色列表(`Arc<[String]>` 共享所有权)
16    /// - `pool`:数据库连接池引用(可选)
17    ///
18    /// # 返回值
19    ///
20    /// 返回新的 TableQuery 实例
21    #[cfg(feature = "mysql")]
22    pub(crate) fn new(
23        table_config: Arc<TableConfig>,
24        user_roles: Arc<[String]>,
25        pool: Option<Arc<sqlx::MySqlPool>>,
26    ) -> Self {
27        let user_roles_set: HashSet<String> = user_roles.iter().cloned().collect();
28        Self {
29            table_config,
30            user_roles,
31            user_roles_set,
32            query_params: QueryParams::new(),
33            include_trashed: false,
34            tenant_scope: None,
35            pool,
36            slow_threshold: None,
37            request_id: None,
38        }
39    }
40
41    /// 创建新的查询构建器(无数据库连接池)
42    ///
43    /// 当未启用 `mysql` feature 时使用此方法。
44    #[cfg(not(feature = "mysql"))]
45    pub(crate) fn new(
46        table_config: Arc<TableConfig>,
47        user_roles: Arc<[String]>,
48        _pool: Option<()>,
49    ) -> Self {
50        let user_roles_set: HashSet<String> = user_roles.iter().cloned().collect();
51        Self {
52            table_config,
53            user_roles,
54            user_roles_set,
55            query_params: QueryParams::new(),
56            include_trashed: false,
57            tenant_scope: None,
58            slow_threshold: None,
59            request_id: None,
60        }
61    }
62
63    /// 设置慢查询阈值(链式)。超过该耗时的单次执行会 `tracing::warn!`。
64    ///
65    /// 通常由 `ActionContext::table_query()` 从全局 `ObservabilityConfig` 注入;
66    /// 也可手动覆盖。`None`/不调用时不启用慢查询日志。
67    pub fn with_slow_threshold(mut self, threshold: Option<std::time::Duration>) -> Self {
68        self.slow_threshold = threshold;
69        self
70    }
71
72    /// 设置本次查询关联的 request_id(链式),用于慢查询日志串联。
73    pub fn with_request_id(mut self, request_id: crate::action::RequestId) -> Self {
74        self.request_id = Some(request_id);
75        self
76    }
77
78    /// 创建仅有表配置、无数据库连接池的查询构建器(测试用)
79    ///
80    /// 使用空的用户角色列表,适合访问无权限限制字段的单元测试。
81    #[cfg(all(test, feature = "mysql"))]
82    pub(crate) fn new_without_pool(table_config: Arc<TableConfig>) -> Self {
83        Self::new(table_config, Arc::from(vec![]), None)
84    }
85}