yang_base/table/table_query/
build.rs1use 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 #[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 #[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 pub fn with_slow_threshold(mut self, threshold: Option<std::time::Duration>) -> Self {
76 self.slow_threshold = threshold;
77 self
78 }
79
80 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 pub fn with_regex_cache(mut self, cache: RegexCache) -> Self {
89 self.regex_cache = cache;
90 self
91 }
92
93 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 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 #[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 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 #[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 #[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 #[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}