use super::TableQuery;
use crate::error::BaseError;
use crate::table::{QueryParams, RegexCache, SortOrder, TableConfig, WhereCondition};
use serde_json::Value;
use std::collections::HashSet;
use std::sync::Arc;
impl TableQuery {
#[cfg(any(feature = "mysql", feature = "postgres"))]
#[allow(dead_code)] pub(crate) fn new(
table_config: Arc<TableConfig>,
user_roles: Arc<[String]>,
pool: Option<crate::database::AnyPool>,
) -> Self {
Self::new_sourced(
table_config,
user_roles,
pool,
crate::datasource::DatasourceId::default_source(),
)
}
#[cfg(any(feature = "mysql", feature = "postgres"))]
pub(crate) fn new_sourced(
table_config: Arc<TableConfig>,
user_roles: Arc<[String]>,
pool: Option<crate::database::AnyPool>,
pool_source: crate::datasource::DatasourceId,
) -> Self {
let user_roles_set: HashSet<String> = user_roles.iter().cloned().collect();
Self {
table_config,
user_roles,
user_roles_set,
query_params: QueryParams::new(),
nulls_orders: std::collections::HashMap::new(),
any_conditions: Vec::new(),
include_trashed: false,
tenant_scope: None,
pool,
pool_source,
require_sourced_tx: false,
slow_threshold: None,
request_id: None,
regex_cache: RegexCache::default(),
}
}
#[cfg(not(any(feature = "mysql", feature = "postgres")))]
pub(crate) fn new(
table_config: Arc<TableConfig>,
user_roles: Arc<[String]>,
_pool: Option<()>,
) -> Self {
let user_roles_set: HashSet<String> = user_roles.iter().cloned().collect();
Self {
table_config,
user_roles,
user_roles_set,
query_params: QueryParams::new(),
nulls_orders: std::collections::HashMap::new(),
any_conditions: Vec::new(),
include_trashed: false,
tenant_scope: None,
pool_source: crate::datasource::DatasourceId::default_source(),
require_sourced_tx: false,
slow_threshold: None,
request_id: None,
regex_cache: RegexCache::default(),
}
}
pub fn with_slow_threshold(mut self, threshold: Option<std::time::Duration>) -> Self {
self.slow_threshold = threshold;
self
}
pub fn with_request_id(mut self, request_id: crate::action::RequestId) -> Self {
self.request_id = Some(request_id);
self
}
pub fn with_regex_cache(mut self, cache: RegexCache) -> Self {
self.regex_cache = cache;
self
}
pub fn order_nulls(
mut self,
field: &str,
order: SortOrder,
nulls_first: bool,
) -> Result<Self, BaseError> {
self.validate_order_field(field)?;
self.query_params.order_by.push((field.to_string(), order));
self.nulls_orders.insert(field.to_string(), nulls_first);
Ok(self)
}
pub fn where_in_chunked(self, field: &str, values: Vec<Value>) -> Result<Self, BaseError> {
if values.is_empty() {
return Err(BaseError::ParamInvalid(
"values".to_string(),
"IN 列表不能为空".to_string(),
));
}
let chunks = values
.chunks(Self::MAX_IN_LIST_SIZE)
.map(|chunk| WhereCondition::In {
field: field.to_string(),
values: chunk.to_vec(),
})
.collect::<Vec<_>>();
let condition = match chunks.len() {
1 => chunks.into_iter().next().expect("len == 1"),
_ => WhereCondition::Or { conditions: chunks },
};
self.where_tree(condition)
}
#[cfg_attr(not(feature = "postgres"), allow(unused_mut))]
pub fn where_any(mut self, field: &str, values: Vec<Value>) -> Result<Self, BaseError> {
if values.is_empty() {
return Err(BaseError::ParamInvalid(
"values".to_string(),
"ANY 列表不能为空".to_string(),
));
}
for chunk in values.chunks(Self::MAX_IN_LIST_SIZE) {
self.validate_condition_tree(
&WhereCondition::In {
field: field.to_string(),
values: chunk.to_vec(),
},
0,
)?;
}
#[cfg(feature = "postgres")]
if self
.pool
.as_ref()
.is_some_and(|pool| pool.backend() == yang_db::BackendKind::PostgreSql)
{
self.any_conditions.push((field.to_string(), values));
return Ok(self);
}
self.where_in_chunked(field, values)
}
pub fn require_sourced_tx(mut self, required: bool) -> Self {
self.require_sourced_tx = required;
self
}
#[cfg(any(feature = "mysql", feature = "postgres"))]
pub(crate) fn ensure_same_source(
&self,
tx: &crate::database::AnyTransaction,
) -> Result<(), crate::error::BaseError> {
let mismatch = |expected: String| crate::error::BaseError::DatasourceMismatch {
table: self.table_config.table_name.clone(),
expected,
actual: format!(
"{}:{:?}",
tx.source()
.map_or_else(|| "unscoped".to_string(), ToString::to_string),
tx.backend()
),
};
let Some(pool) = &self.pool else {
return Err(crate::error::BaseError::ConfigError(
"TableQuery 未绑定连接池,不能执行事务".to_string(),
));
};
if pool.backend() != tx.backend() {
return Err(mismatch(format!(
"{}:{:?}",
self.pool_source,
pool.backend()
)));
}
if self.require_sourced_tx && tx.source().is_none() {
return Err(mismatch("sourced-transaction".to_string()));
}
match tx.source() {
Some(source) if source == &self.pool_source => Ok(()),
Some(_) => Err(mismatch(self.pool_source.to_string())),
None if self.pool_source.is_default() => Ok(()),
None => Err(mismatch(self.pool_source.to_string())),
}
}
#[cfg(all(test, feature = "mysql"))]
pub(crate) fn new_without_pool(table_config: Arc<TableConfig>) -> Self {
Self::new(table_config, Arc::from(vec![]), None)
}
}
#[cfg(all(test, feature = "mysql"))]
mod tests {
use super::*;
use crate::table::{Field, Table};
fn query(table: Table) -> TableQuery {
let definition = table.build().expect("测试表定义应有效");
TableQuery::new(
definition.shared_config(),
Arc::from(vec!["admin".to_string()]),
None,
)
}
#[test]
fn where_in_chunked_splits_large_lists() {
let values: Vec<Value> = (0..1200).map(|i| serde_json::json!(i)).collect();
let query = query(Table::new("tq_in_chunks").fields([Field::id("id")]))
.where_in_chunked("id", values)
.expect("分块 IN 应通过校验");
assert_eq!(query.query_params.where_conditions.len(), 1);
match &query.query_params.where_conditions[0] {
WhereCondition::Or { conditions } => {
assert_eq!(conditions.len(), 3, "1200 条应拆成 3 块");
for chunk in conditions {
match chunk {
WhereCondition::In { values, .. } => {
assert!(!values.is_empty());
assert!(values.len() <= TableQuery::MAX_IN_LIST_SIZE);
}
other => panic!("分块元素应为 IN,实际: {other:?}"),
}
}
}
other => panic!("超长 IN 应折叠为 OR 组,实际: {other:?}"),
}
}
#[test]
fn where_any_falls_back_to_chunked_in() {
let values: Vec<Value> = (0..1200).map(|i| serde_json::json!(i)).collect();
let query = query(Table::new("tq_any_fallback").fields([Field::id("id")]))
.where_any("id", values)
.expect("where_any 应通过校验");
assert!(query.any_conditions.is_empty());
assert!(matches!(
query.query_params.where_conditions[0],
WhereCondition::Or { .. }
));
}
}