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 #[allow(dead_code)] 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 #[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 #[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 pub fn with_slow_threshold(mut self, threshold: Option<std::time::Duration>) -> Self {
97 self.slow_threshold = threshold;
98 self
99 }
100
101 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 pub fn with_regex_cache(mut self, cache: RegexCache) -> Self {
110 self.regex_cache = cache;
111 self
112 }
113
114 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 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 #[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 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 pub fn require_sourced_tx(mut self, required: bool) -> Self {
194 self.require_sourced_tx = required;
195 self
196 }
197
198 #[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 #[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 #[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 #[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}