yang_base/table/query_params.rs
1//! 查询参数结构
2//!
3//! 提供统一的查询参数定义,包括 WHERE 条件、排序规则和分页参数。
4//!
5//! # 主要组件
6//!
7//! - `WhereCondition`:WHERE 条件枚举
8//! - `QueryParams`:查询参数结构体
9//! - `PaginatedResult`:分页结果结构体
10//!
11//! # 示例
12//!
13//! ```rust
14//! use yang_base::table::{WhereCondition, QueryParams, SortOrder};
15//! use serde_json::json;
16//!
17//! // 创建查询参数
18//! let mut params = QueryParams::new();
19//!
20//! // 添加字段选择
21//! params.fields = Some(vec!["id".to_string(), "name".to_string()]);
22//!
23//! // 添加 WHERE 条件
24//! params.where_conditions.push(WhereCondition::Eq {
25//! field: "status".to_string(),
26//! value: json!("active"),
27//! });
28//!
29//! params.where_conditions.push(WhereCondition::In {
30//! field: "role".to_string(),
31//! values: vec![json!("admin"), json!("user")],
32//! });
33//!
34//! // 添加排序规则
35//! params.order_by.push(("created_at".to_string(), SortOrder::Desc));
36//!
37//! // 设置分页参数
38//! params.page = Some(1);
39//! params.page_size = Some(20);
40//! ```
41
42use serde::{Deserialize, Serialize};
43use serde_json::Value;
44
45/// 默认每页条数。
46pub const DEFAULT_QUERY_PAGE_SIZE: usize = 10;
47
48/// 查询请求模型允许的最大每页条数。
49pub const MAX_QUERY_PAGE_SIZE: usize = 100;
50
51/// WHERE 条件枚举
52///
53/// 定义各种查询条件类型,支持常见的 SQL WHERE 子句操作。
54///
55/// # 变体
56///
57/// - `Eq`:等于条件 (field = value)
58/// - `In`:包含于列表条件 (field IN (values))
59/// - `Like`:模糊匹配条件 (field LIKE pattern)
60/// - `Gt`:大于条件 (field > value)
61/// - `Gte`:大于等于条件 (field >= value)
62/// - `Lt`:小于条件 (field < value)
63/// - `Lte`:小于等于条件 (field <= value)
64/// - `IsNull`:空值判断 (field IS NULL)
65/// - `IsNotNull`:非空值判断 (field IS NOT NULL)
66///
67/// # 示例
68///
69/// ```rust
70/// use yang_base::table::WhereCondition;
71/// use serde_json::json;
72///
73/// // 等于条件
74/// let eq_condition = WhereCondition::Eq {
75/// field: "status".to_string(),
76/// value: json!("active"),
77/// };
78///
79/// // 包含条件
80/// let in_condition = WhereCondition::In {
81/// field: "role".to_string(),
82/// values: vec![json!("admin"), json!("user")],
83/// };
84///
85/// // 模糊匹配
86/// let like_condition = WhereCondition::Like {
87/// field: "name".to_string(),
88/// pattern: "%alice%".to_string(),
89/// };
90///
91/// // 大于条件
92/// let gt_condition = WhereCondition::Gt {
93/// field: "age".to_string(),
94/// value: json!(18),
95/// };
96///
97/// // 空值判断
98/// let is_null_condition = WhereCondition::IsNull {
99/// field: "deleted_at".to_string(),
100/// };
101/// ```
102#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
103#[serde(tag = "type", rename_all = "snake_case")]
104#[non_exhaustive]
105pub enum WhereCondition {
106 /// 等于条件 (field = value)
107 ///
108 /// # 字段
109 ///
110 /// - `field`:字段名
111 /// - `value`:比较值
112 Eq {
113 /// 字段名
114 field: String,
115 /// 比较值
116 value: Value,
117 },
118
119 /// 包含于列表条件 (field IN (values))
120 ///
121 /// # 字段
122 ///
123 /// - `field`:字段名
124 /// - `values`:值列表
125 In {
126 /// 字段名
127 field: String,
128 /// 值列表
129 values: Vec<Value>,
130 },
131
132 /// 模糊匹配条件 (field LIKE pattern)
133 ///
134 /// # 字段
135 ///
136 /// - `field`:字段名
137 /// - `pattern`:匹配模式,支持 % 和 _ 通配符
138 Like {
139 /// 字段名
140 field: String,
141 /// 匹配模式
142 pattern: String,
143 },
144
145 /// 大于条件 (field > value)
146 ///
147 /// # 字段
148 ///
149 /// - `field`:字段名
150 /// - `value`:比较值
151 Gt {
152 /// 字段名
153 field: String,
154 /// 比较值
155 value: Value,
156 },
157
158 /// 大于等于条件 (field >= value)
159 ///
160 /// # 字段
161 ///
162 /// - `field`:字段名
163 /// - `value`:比较值
164 Gte {
165 /// 字段名
166 field: String,
167 /// 比较值
168 value: Value,
169 },
170
171 /// 小于条件 (field < value)
172 ///
173 /// # 字段
174 ///
175 /// - `field`:字段名
176 /// - `value`:比较值
177 Lt {
178 /// 字段名
179 field: String,
180 /// 比较值
181 value: Value,
182 },
183
184 /// 小于等于条件 (field <= value)
185 ///
186 /// # 字段
187 ///
188 /// - `field`:字段名
189 /// - `value`:比较值
190 Lte {
191 /// 字段名
192 field: String,
193 /// 比较值
194 value: Value,
195 },
196
197 /// 空值判断 (field IS NULL)
198 ///
199 /// # 字段
200 ///
201 /// - `field`:字段名
202 IsNull {
203 /// 字段名
204 field: String,
205 },
206
207 /// 非空值判断 (field IS NOT NULL)
208 ///
209 /// # 字段
210 ///
211 /// - `field`:字段名
212 IsNotNull {
213 /// 字段名
214 field: String,
215 },
216
217 /// 不等于条件 (field <> value)
218 ///
219 /// # 字段
220 ///
221 /// - `field`:字段名
222 /// - `value`:比较值
223 Ne {
224 /// 字段名
225 field: String,
226 /// 比较值
227 value: Value,
228 },
229
230 /// 区间条件 (field BETWEEN lo AND hi)
231 ///
232 /// # 字段
233 ///
234 /// - `field`:字段名
235 /// - `lo`:区间下界
236 /// - `hi`:区间上界
237 Between {
238 /// 字段名
239 field: String,
240 /// 区间下界
241 lo: Value,
242 /// 区间上界
243 hi: Value,
244 },
245
246 /// 不在列表条件 (field NOT IN (values))
247 ///
248 /// # 字段
249 ///
250 /// - `field`:字段名
251 /// - `values`:值列表
252 NotIn {
253 /// 字段名
254 field: String,
255 /// 值列表
256 values: Vec<Value>,
257 },
258
259 /// 逻辑与组(嵌套子条件全部成立),SQL 渲染为 `(c1 AND c2 AND ...)`
260 ///
261 /// 空组等价于恒真(`1=1`),与顶层「无条件」语义一致。
262 ///
263 /// # 字段
264 ///
265 /// - `conditions`:子条件列表,递归可含 `And`/`Or` 组
266 And {
267 /// 子条件列表
268 conditions: Vec<WhereCondition>,
269 },
270
271 /// 逻辑或组(嵌套子条件任一成立),SQL 渲染为 `(c1 OR c2 OR ...)`
272 ///
273 /// 空组等价于恒假(`1=0`),避免拼出非法的空括号。
274 ///
275 /// # 字段
276 ///
277 /// - `conditions`:子条件列表,递归可含 `And`/`Or` 组
278 Or {
279 /// 子条件列表
280 conditions: Vec<WhereCondition>,
281 },
282}
283
284impl WhereCondition {
285 /// 获取条件涉及的字段名
286 ///
287 /// 叶子条件返回 `Some(字段名)`;逻辑组(`And`/`Or`)无单一字段,返回 `None`。
288 ///
289 /// # 返回值
290 ///
291 /// 叶子返回 `Some(&str)`,组节点返回 `None`
292 ///
293 /// # 示例
294 ///
295 /// ```rust
296 /// use yang_base::table::WhereCondition;
297 /// use serde_json::json;
298 ///
299 /// let condition = WhereCondition::Eq {
300 /// field: "status".to_string(),
301 /// value: json!("active"),
302 /// };
303 ///
304 /// assert_eq!(condition.field(), Some("status"));
305 /// ```
306 pub fn field(&self) -> Option<&str> {
307 match self {
308 WhereCondition::Eq { field, .. }
309 | WhereCondition::In { field, .. }
310 | WhereCondition::Like { field, .. }
311 | WhereCondition::Gt { field, .. }
312 | WhereCondition::Gte { field, .. }
313 | WhereCondition::Lt { field, .. }
314 | WhereCondition::Lte { field, .. }
315 | WhereCondition::IsNull { field }
316 | WhereCondition::IsNotNull { field }
317 | WhereCondition::Ne { field, .. }
318 | WhereCondition::Between { field, .. }
319 | WhereCondition::NotIn { field, .. } => Some(field),
320 // 逻辑组无单一字段
321 WhereCondition::And { .. } | WhereCondition::Or { .. } => None,
322 }
323 }
324}
325
326/// 查询参数结构体
327///
328/// 包含完整的查询参数,包括字段选择、WHERE 条件、排序规则和分页参数。
329///
330/// # 字段
331///
332/// - `fields`:字段选择列表,None 表示选择所有字段
333/// - `where_conditions`:WHERE 条件列表
334/// - `order_by`:排序规则列表,元组格式为 (字段名, 排序方向)
335/// - `page`:当前页码,从 1 开始
336/// - `page_size`:每页大小
337///
338/// # 示例
339///
340/// ```rust
341/// use yang_base::table::{QueryParams, WhereCondition, SortOrder};
342/// use serde_json::json;
343///
344/// let mut params = QueryParams::new();
345///
346/// // 选择特定字段
347/// params.fields = Some(vec!["id".to_string(), "name".to_string(), "email".to_string()]);
348///
349/// // 添加 WHERE 条件
350/// params.where_conditions.push(WhereCondition::Eq {
351/// field: "status".to_string(),
352/// value: json!("active"),
353/// });
354///
355/// params.where_conditions.push(WhereCondition::Gt {
356/// field: "age".to_string(),
357/// value: json!(18),
358/// });
359///
360/// // 添加排序规则
361/// params.order_by.push(("created_at".to_string(), SortOrder::Desc));
362/// params.order_by.push(("name".to_string(), SortOrder::Asc));
363///
364/// // 设置分页参数
365/// params.page = Some(1);
366/// params.page_size = Some(20);
367/// ```
368#[derive(Debug, Clone, Serialize, Deserialize, Default)]
369pub struct QueryParams {
370 /// 字段选择列表
371 ///
372 /// - `None`:选择所有字段
373 /// - `Some(vec)`:选择指定字段
374 #[serde(skip_serializing_if = "Option::is_none")]
375 pub fields: Option<Vec<String>>,
376
377 /// WHERE 条件列表
378 ///
379 /// 多个条件之间使用 AND 连接
380 #[serde(default)]
381 pub where_conditions: Vec<WhereCondition>,
382
383 /// 排序规则列表
384 ///
385 /// 元组格式为 (字段名, 排序方向)
386 #[serde(default)]
387 pub order_by: Vec<(String, crate::table::SortOrder)>,
388
389 /// 当前页码
390 ///
391 /// 从 1 开始,None 表示不分页
392 #[serde(skip_serializing_if = "Option::is_none")]
393 pub page: Option<usize>,
394
395 /// 每页大小
396 ///
397 /// None 表示使用默认值或不分页
398 #[serde(skip_serializing_if = "Option::is_none")]
399 pub page_size: Option<usize>,
400}
401
402impl QueryParams {
403 /// 创建新的查询参数
404 ///
405 /// # 返回值
406 ///
407 /// 返回空的查询参数实例
408 ///
409 /// # 示例
410 ///
411 /// ```rust
412 /// use yang_base::table::QueryParams;
413 ///
414 /// let params = QueryParams::new();
415 /// assert!(params.fields.is_none());
416 /// assert!(params.where_conditions.is_empty());
417 /// assert!(params.order_by.is_empty());
418 /// assert!(params.page.is_none());
419 /// assert!(params.page_size.is_none());
420 /// ```
421 pub fn new() -> Self {
422 Self::default()
423 }
424
425 /// 设置字段选择列表
426 ///
427 /// # 参数
428 ///
429 /// - `fields`:字段名列表
430 ///
431 /// # 返回值
432 ///
433 /// 返回 self 以支持链式调用
434 ///
435 /// # 示例
436 ///
437 /// ```rust
438 /// use yang_base::table::QueryParams;
439 ///
440 /// let params = QueryParams::new()
441 /// .with_fields(vec!["id".to_string(), "name".to_string()]);
442 ///
443 /// assert_eq!(params.fields, Some(vec!["id".to_string(), "name".to_string()]));
444 /// ```
445 pub fn with_fields(mut self, fields: Vec<String>) -> Self {
446 self.fields = Some(fields);
447 self
448 }
449
450 /// 添加 WHERE 条件
451 ///
452 /// # 参数
453 ///
454 /// - `condition`:WHERE 条件
455 ///
456 /// # 返回值
457 ///
458 /// 返回 self 以支持链式调用
459 ///
460 /// # 示例
461 ///
462 /// ```rust
463 /// use yang_base::table::{QueryParams, WhereCondition};
464 /// use serde_json::json;
465 ///
466 /// let params = QueryParams::new()
467 /// .with_condition(WhereCondition::Eq {
468 /// field: "status".to_string(),
469 /// value: json!("active"),
470 /// });
471 ///
472 /// assert_eq!(params.where_conditions.len(), 1);
473 /// ```
474 pub fn with_condition(mut self, condition: WhereCondition) -> Self {
475 self.where_conditions.push(condition);
476 self
477 }
478
479 /// 添加排序规则
480 ///
481 /// # 参数
482 ///
483 /// - `field`:字段名
484 /// - `order`:排序方向
485 ///
486 /// # 返回值
487 ///
488 /// 返回 self 以支持链式调用
489 ///
490 /// # 示例
491 ///
492 /// ```rust
493 /// use yang_base::table::{QueryParams, SortOrder};
494 ///
495 /// let params = QueryParams::new()
496 /// .with_order_by("created_at".to_string(), SortOrder::Desc);
497 ///
498 /// assert_eq!(params.order_by.len(), 1);
499 /// ```
500 pub fn with_order_by(mut self, field: String, order: crate::table::SortOrder) -> Self {
501 self.order_by.push((field, order));
502 self
503 }
504
505 /// 设置分页参数
506 ///
507 /// # 参数
508 ///
509 /// - `page`:当前页码,从 1 开始
510 /// - `page_size`:每页大小
511 ///
512 /// # 返回值
513 ///
514 /// 返回 self 以支持链式调用
515 ///
516 /// # 示例
517 ///
518 /// ```rust
519 /// use yang_base::table::QueryParams;
520 ///
521 /// let params = QueryParams::new()
522 /// .with_pagination(1, 20);
523 ///
524 /// assert_eq!(params.page, Some(1));
525 /// assert_eq!(params.page_size, Some(20));
526 /// ```
527 pub fn with_pagination(mut self, page: usize, page_size: usize) -> Self {
528 self.page = Some(page);
529 self.page_size = Some(page_size);
530 self
531 }
532
533 /// 归一化分页参数
534 ///
535 /// 将 `page` 中小于 1 的值(含 0)归一为 1,避免直接构造 `QueryParams`
536 /// 时 `page == 0` 导致 LIMIT/OFFSET 计算下溢。`page_size` 保持原值。
537 ///
538 /// # 示例
539 ///
540 /// ```rust
541 /// use yang_base::table::QueryParams;
542 ///
543 /// let mut params = QueryParams::new().with_pagination(0, 20);
544 /// params.normalize();
545 /// assert_eq!(params.page, Some(1));
546 /// ```
547 pub fn normalize(&mut self) {
548 if let Some(page) = self.page {
549 if page == 0 {
550 self.page = Some(1);
551 }
552 }
553 if let Some(page_size) = self.page_size {
554 if page_size == 0 {
555 self.page_size = Some(DEFAULT_QUERY_PAGE_SIZE);
556 } else if page_size > MAX_QUERY_PAGE_SIZE {
557 self.page_size = Some(MAX_QUERY_PAGE_SIZE);
558 }
559 }
560 }
561}
562
563/// 分页结果结构体
564///
565/// 包含分页查询的完整结果,包括数据列表和分页元信息。
566///
567/// # 类型参数
568///
569/// - `T`:数据项类型,必须实现 Serialize 和 Deserialize
570///
571/// # 字段
572///
573/// - `data`:数据列表
574/// - `total`:总记录数
575/// - `page`:当前页码,从 1 开始
576/// - `page_size`:每页大小
577/// - `total_pages`:总页数
578///
579/// # 示例
580///
581/// ```rust
582/// use yang_base::table::PaginatedResult;
583/// use serde::{Deserialize, Serialize};
584///
585/// #[derive(Debug, Serialize, Deserialize)]
586/// struct User {
587/// id: i64,
588/// name: String,
589/// }
590///
591/// let users = vec![
592/// User { id: 1, name: "Alice".to_string() },
593/// User { id: 2, name: "Bob".to_string() },
594/// ];
595///
596/// let result = PaginatedResult::new(users, 100, 1, 20);
597///
598/// assert_eq!(result.data.len(), 2);
599/// assert_eq!(result.total, 100);
600/// assert_eq!(result.page, 1);
601/// assert_eq!(result.page_size, 20);
602/// assert_eq!(result.total_pages, 5);
603/// ```
604#[derive(Debug, Clone, Serialize, Deserialize)]
605pub struct PaginatedResult<T>
606where
607 T: Serialize,
608{
609 /// 数据列表
610 pub data: Vec<T>,
611
612 /// 总记录数
613 pub total: usize,
614
615 /// 当前页码
616 ///
617 /// 从 1 开始
618 pub page: usize,
619
620 /// 每页大小
621 pub page_size: usize,
622
623 /// 总页数
624 pub total_pages: usize,
625}
626
627impl<T> PaginatedResult<T>
628where
629 T: Serialize,
630{
631 /// 创建新的分页结果
632 ///
633 /// # 参数
634 ///
635 /// - `data`:数据列表
636 /// - `total`:总记录数
637 /// - `page`:当前页码,从 1 开始
638 /// - `page_size`:每页大小
639 ///
640 /// # 返回值
641 ///
642 /// 返回分页结果实例,自动计算总页数
643 ///
644 /// # 示例
645 ///
646 /// ```rust
647 /// use yang_base::table::PaginatedResult;
648 /// use serde::{Deserialize, Serialize};
649 ///
650 /// #[derive(Debug, Serialize, Deserialize)]
651 /// struct User {
652 /// id: i64,
653 /// name: String,
654 /// }
655 ///
656 /// let users = vec![
657 /// User { id: 1, name: "Alice".to_string() },
658 /// User { id: 2, name: "Bob".to_string() },
659 /// ];
660 ///
661 /// let result = PaginatedResult::new(users, 100, 1, 20);
662 ///
663 /// assert_eq!(result.total_pages, 5);
664 /// ```
665 pub fn new(data: Vec<T>, total: usize, page: usize, page_size: usize) -> Self {
666 let total_pages = if page_size > 0 {
667 total.div_ceil(page_size)
668 } else {
669 0
670 };
671
672 Self {
673 data,
674 total,
675 page,
676 page_size,
677 total_pages,
678 }
679 }
680
681 /// 创建空的分页结果
682 ///
683 /// # 参数
684 ///
685 /// - `page`:当前页码
686 /// - `page_size`:每页大小
687 ///
688 /// # 返回值
689 ///
690 /// 返回空的分页结果实例
691 ///
692 /// # 示例
693 ///
694 /// ```rust
695 /// use yang_base::table::PaginatedResult;
696 /// use serde::{Deserialize, Serialize};
697 ///
698 /// #[derive(Debug, Serialize, Deserialize)]
699 /// struct User {
700 /// id: i64,
701 /// name: String,
702 /// }
703 ///
704 /// let result: PaginatedResult<User> = PaginatedResult::empty(1, 20);
705 ///
706 /// assert_eq!(result.data.len(), 0);
707 /// assert_eq!(result.total, 0);
708 /// assert_eq!(result.total_pages, 0);
709 /// ```
710 pub fn empty(page: usize, page_size: usize) -> Self {
711 Self {
712 data: Vec::new(),
713 total: 0,
714 page,
715 page_size,
716 total_pages: 0,
717 }
718 }
719
720 /// 判断是否有下一页
721 ///
722 /// # 返回值
723 ///
724 /// 如果有下一页返回 true,否则返回 false
725 ///
726 /// # 示例
727 ///
728 /// ```rust
729 /// use yang_base::table::PaginatedResult;
730 /// use serde::{Deserialize, Serialize};
731 ///
732 /// #[derive(Debug, Serialize, Deserialize)]
733 /// struct User {
734 /// id: i64,
735 /// name: String,
736 /// }
737 ///
738 /// let result: PaginatedResult<User> = PaginatedResult::new(vec![], 100, 1, 20);
739 /// assert!(result.has_next());
740 ///
741 /// let result: PaginatedResult<User> = PaginatedResult::new(vec![], 100, 5, 20);
742 /// assert!(!result.has_next());
743 /// ```
744 pub fn has_next(&self) -> bool {
745 self.page < self.total_pages
746 }
747
748 /// 判断是否有上一页
749 ///
750 /// # 返回值
751 ///
752 /// 如果有上一页返回 true,否则返回 false
753 ///
754 /// # 示例
755 ///
756 /// ```rust
757 /// use yang_base::table::PaginatedResult;
758 /// use serde::{Deserialize, Serialize};
759 ///
760 /// #[derive(Debug, Serialize, Deserialize)]
761 /// struct User {
762 /// id: i64,
763 /// name: String,
764 /// }
765 ///
766 /// let result: PaginatedResult<User> = PaginatedResult::new(vec![], 100, 1, 20);
767 /// assert!(!result.has_prev());
768 ///
769 /// let result: PaginatedResult<User> = PaginatedResult::new(vec![], 100, 2, 20);
770 /// assert!(result.has_prev());
771 /// ```
772 pub fn has_prev(&self) -> bool {
773 self.page > 1
774 }
775}