1#![allow(deprecated)]
2
3use chrono::{DateTime, NaiveDate, NaiveDateTime, NaiveTime, Utc};
4use serde_json::Value as JsonValue;
5
6use crate::DbError;
7
8#[derive(Debug, Clone, Copy)]
10pub enum ComparisonOperator {
11 Eq,
13 Ne,
15 Gt,
17 Lt,
19 Gte,
21 Lte,
23}
24
25impl ComparisonOperator {
26 fn parse(op: &str) -> Result<Self, DbError> {
27 match op {
28 "=" => Ok(Self::Eq),
29 "!=" => Ok(Self::Ne),
30 ">" => Ok(Self::Gt),
31 "<" => Ok(Self::Lt),
32 ">=" => Ok(Self::Gte),
33 "<=" => Ok(Self::Lte),
34 _ => Err(DbError::UnsupportedOperator(op.to_string())),
35 }
36 }
37
38 fn as_sql(self) -> &'static str {
39 match self {
40 Self::Eq => "=",
41 Self::Ne => "!=",
42 Self::Gt => ">",
43 Self::Lt => "<",
44 Self::Gte => ">=",
45 Self::Lte => "<=",
46 }
47 }
48}
49
50#[derive(Debug, Clone)]
52pub struct Subquery {
53 table: String,
54 field: String,
55 conditions: Vec<Condition>,
56}
57
58impl Subquery {
59 pub fn new(table: &str, field: &str) -> Result<Self, DbError> {
61 super::identifier::quote_identifier(table)?;
62 super::identifier::quote_qualified(field)?;
63 Ok(Self {
64 table: table.to_string(),
65 field: field.to_string(),
66 conditions: Vec::new(),
67 })
68 }
69
70 pub fn where_value<V>(mut self, field: &str, op: &str, value: V) -> Result<Self, DbError>
72 where
73 V: Into<SqlValue>,
74 {
75 super::identifier::quote_qualified(field)?;
76 let value = value.into();
77 let condition = match op {
78 "=" => Condition::Eq(field.to_string(), value),
79 "!=" => Condition::Ne(field.to_string(), value),
80 ">" => Condition::Gt(field.to_string(), value),
81 "<" => Condition::Lt(field.to_string(), value),
82 ">=" => Condition::Gte(field.to_string(), value),
83 "<=" => Condition::Lte(field.to_string(), value),
84 _ => return Err(DbError::UnsupportedOperator(op.to_string())),
85 };
86 self.conditions.push(condition);
87 Ok(self)
88 }
89
90 pub fn where_column(mut self, left: &str, op: &str, right: &str) -> Result<Self, DbError> {
92 super::identifier::quote_qualified(left)?;
93 super::identifier::quote_qualified(right)?;
94 self.conditions.push(Condition::ColumnComparison(
95 left.to_string(),
96 ComparisonOperator::parse(op)?,
97 right.to_string(),
98 ));
99 Ok(self)
100 }
101}
102
103#[derive(Debug, Clone)]
108#[non_exhaustive]
109pub enum SqlValue {
110 Null,
111 Bool(bool),
112 Int(i64),
113 Float(f64),
114 String(String),
115 Bytes(Vec<u8>),
116 Json(JsonValue),
117 DateTime(NaiveDateTime),
118 Timestamp(i64),
119 Decimal(bigdecimal::BigDecimal),
121 Uuid(uuid::Uuid),
123 DateTimeTz(DateTime<Utc>),
125 Date(NaiveDate),
127 Time(NaiveTime),
129 Interval(i64),
131 Array(Vec<SqlValue>),
138 TypedArray {
146 element_type: &'static str,
148 values: Vec<SqlValue>,
150 },
151 Inet(String),
153 Cidr(String),
155 MacAddr(String),
157 MacAddr8(String),
159 Range(String),
164 Multirange(String),
167}
168
169#[derive(Debug, Clone)]
171#[non_exhaustive]
172pub enum Condition {
173 Eq(String, SqlValue),
175 Ne(String, SqlValue),
177 Gt(String, SqlValue),
179 Lt(String, SqlValue),
181 Gte(String, SqlValue),
183 Lte(String, SqlValue),
185 In(String, Vec<SqlValue>),
187 NotIn(String, Vec<SqlValue>),
189 Between(String, SqlValue, SqlValue),
191 Like(String, String),
193 ILike(String, String),
195 NotILike(String, String),
197 RegexMatch(String, String),
199 RegexIMatch(String, String),
201 NotRegexMatch(String, String),
203 NotRegexIMatch(String, String),
205 IsDistinctFrom(String, SqlValue),
207 IsNotDistinctFrom(String, SqlValue),
209 IsNull(String),
211 IsNotNull(String),
213 ColumnComparison(String, ComparisonOperator, String),
215 Exists(Box<Subquery>),
217 NotExists(Box<Subquery>),
219 InSubquery(String, Box<Subquery>),
221 FieldExpr(String, ComparisonOperator, crate::SqlExpr),
223 JsonContains(String, SqlValue),
225 JsonContainedBy(String, SqlValue),
227 JsonHasKey(String, String),
229 Any(String, SqlValue),
231 All(String, SqlValue),
233 RangeContains(String, SqlValue),
235 RangeOverlaps(String, SqlValue),
237 JsonPathExists(String, String),
239 JsonPathMatch(String, String, SqlValue),
241 FullText(String, String),
243 FullTextQuery(String, String),
245 Not(Box<Condition>),
247 And(Vec<Condition>),
249 Or(Vec<Condition>),
251}
252
253impl From<i32> for SqlValue {
255 fn from(v: i32) -> Self {
256 SqlValue::Int(v as i64)
257 }
258}
259
260impl From<i64> for SqlValue {
261 fn from(v: i64) -> Self {
262 SqlValue::Int(v)
263 }
264}
265
266impl From<u64> for SqlValue {
267 fn from(v: u64) -> Self {
268 if v > i64::MAX as u64 {
272 SqlValue::String(v.to_string())
273 } else {
274 SqlValue::Int(v as i64)
275 }
276 }
277}
278
279impl From<f64> for SqlValue {
280 fn from(v: f64) -> Self {
281 SqlValue::Float(v)
282 }
283}
284
285impl From<f32> for SqlValue {
286 fn from(v: f32) -> Self {
287 SqlValue::Float(v as f64)
288 }
289}
290
291impl From<String> for SqlValue {
292 fn from(v: String) -> Self {
293 SqlValue::String(v)
294 }
295}
296
297impl From<&str> for SqlValue {
298 fn from(v: &str) -> Self {
299 SqlValue::String(v.to_string())
300 }
301}
302
303impl From<bool> for SqlValue {
304 fn from(v: bool) -> Self {
305 SqlValue::Bool(v)
306 }
307}
308
309impl From<Vec<u8>> for SqlValue {
310 fn from(v: Vec<u8>) -> Self {
311 SqlValue::Bytes(v)
312 }
313}
314
315impl From<Vec<i64>> for SqlValue {
317 fn from(v: Vec<i64>) -> Self {
318 SqlValue::Array(v.into_iter().map(SqlValue::Int).collect())
319 }
320}
321
322impl From<Vec<String>> for SqlValue {
324 fn from(v: Vec<String>) -> Self {
325 SqlValue::Array(v.into_iter().map(SqlValue::String).collect())
326 }
327}
328
329impl From<Vec<f64>> for SqlValue {
331 fn from(v: Vec<f64>) -> Self {
332 SqlValue::Array(v.into_iter().map(SqlValue::Float).collect())
333 }
334}
335
336impl From<Vec<bool>> for SqlValue {
338 fn from(v: Vec<bool>) -> Self {
339 SqlValue::Array(v.into_iter().map(SqlValue::Bool).collect())
340 }
341}
342
343impl From<JsonValue> for SqlValue {
344 fn from(v: JsonValue) -> Self {
345 SqlValue::Json(v)
346 }
347}
348
349impl From<NaiveDateTime> for SqlValue {
350 fn from(v: NaiveDateTime) -> Self {
351 SqlValue::DateTime(v)
352 }
353}
354
355impl From<bigdecimal::BigDecimal> for SqlValue {
356 fn from(v: bigdecimal::BigDecimal) -> Self {
357 SqlValue::Decimal(v)
358 }
359}
360
361impl From<uuid::Uuid> for SqlValue {
362 fn from(v: uuid::Uuid) -> Self {
363 SqlValue::Uuid(v)
364 }
365}
366
367impl From<DateTime<Utc>> for SqlValue {
368 fn from(v: DateTime<Utc>) -> Self {
369 SqlValue::DateTimeTz(v)
370 }
371}
372
373impl From<NaiveDate> for SqlValue {
374 fn from(v: NaiveDate) -> Self {
375 SqlValue::Date(v)
376 }
377}
378
379impl From<NaiveTime> for SqlValue {
380 fn from(v: NaiveTime) -> Self {
381 SqlValue::Time(v)
382 }
383}
384
385impl From<chrono::Duration> for SqlValue {
386 fn from(v: chrono::Duration) -> Self {
387 SqlValue::Interval(v.num_microseconds().unwrap_or_default())
388 }
389}
390
391impl SqlValue {
393 pub fn interval_micros(micros: i64) -> Self {
395 SqlValue::Interval(micros)
396 }
397}
398
399impl<T> From<Option<T>> for SqlValue
400where
401 T: Into<SqlValue>,
402{
403 fn from(v: Option<T>) -> Self {
404 match v {
405 Some(val) => val.into(),
406 None => SqlValue::Null,
407 }
408 }
409}
410
411#[deprecated(
420 since = "0.1.3",
421 note = "使用 condition_to_sql_owned_checked 获取结构化错误"
422)]
423pub fn condition_to_sql(condition: &Condition, params: &mut Vec<SqlValue>) -> String {
424 condition_to_sql_owned(condition.clone(), params)
427}
428
429const FAIL_CLOSED_CONDITION: &str = "/* invalid condition */ 1 = 0";
430
431#[deprecated(
433 since = "0.1.3",
434 note = "使用 condition_to_sql_owned_checked 获取结构化错误"
435)]
436pub fn condition_to_sql_owned(condition: Condition, params: &mut Vec<SqlValue>) -> String {
437 condition_to_sql_owned_checked(condition, params)
438 .unwrap_or_else(|_| FAIL_CLOSED_CONDITION.to_string())
439}
440
441pub fn condition_to_sql_owned_checked(
450 condition: Condition,
451 params: &mut Vec<SqlValue>,
452) -> Result<String, DbError> {
453 let rendered = render_condition_checked(condition, params.len())?;
454 params.extend(rendered.params);
455 Ok(rendered.sql)
456}
457
458pub(crate) fn render_condition_checked(
459 condition: Condition,
460 parameter_offset: usize,
461) -> Result<crate::sql_types::RenderedCondition<SqlValue>, DbError> {
462 crate::dialect::render_condition(
465 crate::dialect::POSTGRES,
466 into_node(condition),
467 parameter_offset,
468 )
469}
470
471fn into_node(condition: Condition) -> crate::dialect::CondNode<SqlValue> {
473 use crate::dialect::CondNode as Node;
474 match condition {
475 Condition::Eq(field, value) => Node::Eq(field, value),
476 Condition::Ne(field, value) => Node::Ne(field, value),
477 Condition::Gt(field, value) => Node::Gt(field, value),
478 Condition::Lt(field, value) => Node::Lt(field, value),
479 Condition::Gte(field, value) => Node::Gte(field, value),
480 Condition::Lte(field, value) => Node::Lte(field, value),
481 Condition::In(field, values) => Node::In(field, values),
482 Condition::NotIn(field, values) => Node::NotIn(field, values),
483 Condition::Between(field, start, end) => Node::Between(field, start, end),
484 Condition::Like(field, pattern) => Node::Like(field, SqlValue::String(pattern)),
485 Condition::ILike(field, pattern) => {
486 Node::PatternMatch(field, "ILIKE", SqlValue::String(pattern))
487 }
488 Condition::NotILike(field, pattern) => {
489 Node::PatternMatch(field, "NOT ILIKE", SqlValue::String(pattern))
490 }
491 Condition::RegexMatch(field, pattern) => {
492 Node::PatternMatch(field, "~", SqlValue::String(pattern))
493 }
494 Condition::RegexIMatch(field, pattern) => {
495 Node::PatternMatch(field, "~*", SqlValue::String(pattern))
496 }
497 Condition::NotRegexMatch(field, pattern) => {
498 Node::PatternMatch(field, "!~", SqlValue::String(pattern))
499 }
500 Condition::NotRegexIMatch(field, pattern) => {
501 Node::PatternMatch(field, "!~*", SqlValue::String(pattern))
502 }
503 Condition::IsDistinctFrom(field, value) => Node::DistinctFrom(field, true, value),
504 Condition::IsNotDistinctFrom(field, value) => Node::DistinctFrom(field, false, value),
505 Condition::IsNull(field) => Node::IsNull(field),
506 Condition::IsNotNull(field) => Node::IsNotNull(field),
507 Condition::ColumnComparison(left, op, right) => {
508 Node::ColumnComparison(left, op.as_sql(), right)
509 }
510 Condition::Exists(subquery) => Node::Exists(Box::new(into_subquery_node(*subquery))),
511 Condition::NotExists(subquery) => Node::NotExists(Box::new(into_subquery_node(*subquery))),
512 Condition::InSubquery(field, subquery) => {
513 Node::InSubquery(field, Box::new(into_subquery_node(*subquery)))
514 }
515 Condition::FieldExpr(field, operator, expression) => {
516 Node::ExprComparison(field, operator.as_sql(), expression)
517 }
518 Condition::JsonContains(field, value) => Node::JsonContains(field, value),
519 Condition::JsonContainedBy(field, value) => Node::JsonContainedBy(field, value),
520 Condition::JsonHasKey(field, key) => Node::JsonHasKey(field, SqlValue::String(key)),
521 Condition::Any(field, value) => Node::Any(field, value),
522 Condition::All(field, value) => Node::All(field, value),
523 Condition::RangeContains(field, value) => Node::RangeContains(field, value),
524 Condition::RangeOverlaps(field, value) => Node::RangeOverlaps(field, value),
525 Condition::JsonPathExists(field, path) => {
526 Node::JsonPathExists(field, SqlValue::String(path))
527 }
528 Condition::JsonPathMatch(field, path, vars) => {
529 Node::JsonPathMatch(field, SqlValue::String(path), vars)
530 }
531 Condition::FullText(field, query) => Node::FullText(field, SqlValue::String(query)),
532 Condition::FullTextQuery(field, query) => {
533 Node::FullTextQuery(field, SqlValue::String(query))
534 }
535 Condition::Not(condition) => Node::Not(Box::new(into_node(*condition))),
536 Condition::And(conditions) => Node::And(conditions.into_iter().map(into_node).collect()),
537 Condition::Or(conditions) => Node::Or(conditions.into_iter().map(into_node).collect()),
538 }
539}
540
541fn into_subquery_node(subquery: Subquery) -> crate::dialect::SubqueryNode<SqlValue> {
543 crate::dialect::SubqueryNode {
544 table: subquery.table,
545 field: subquery.field,
546 conditions: subquery.conditions.into_iter().map(into_node).collect(),
547 }
548}
549
550#[cfg(test)]
551#[allow(deprecated)]
552#[allow(clippy::unwrap_used, clippy::expect_used)]
553mod tests {
554 use super::*;
555
556 #[test]
557 fn test_checked_rejects_empty_in_condition() {
558 let mut params = Vec::new();
559 let result =
560 condition_to_sql_owned_checked(Condition::In("id".to_string(), vec![]), &mut params);
561
562 assert!(matches!(result, Err(crate::DbError::InvalidArgument(_))));
563 assert!(params.is_empty());
564 }
565
566 #[test]
567 fn test_checked_rejects_empty_boolean_condition() {
568 let mut params = Vec::new();
569 let result = condition_to_sql_owned_checked(Condition::And(vec![]), &mut params);
570
571 assert!(matches!(result, Err(crate::DbError::InvalidArgument(_))));
572 assert!(params.is_empty());
573 }
574
575 #[test]
576 fn test_checked_failure_does_not_partially_mutate_caller_params() {
577 let mut params = vec![SqlValue::Int(99)];
578 let condition = Condition::And(vec![
579 Condition::Eq("users.id".to_string(), SqlValue::Int(1)),
580 Condition::Eq("users.id --".to_string(), SqlValue::Int(2)),
581 ]);
582
583 assert!(condition_to_sql_owned_checked(condition, &mut params).is_err());
584 assert_eq!(params.len(), 1);
585 assert!(matches!(params[0], SqlValue::Int(99)));
586 }
587
588 #[test]
589 fn test_checked_placeholder_order_starts_after_existing_params() {
590 let mut params = vec![SqlValue::Int(99)];
591 let condition = Condition::And(vec![
592 Condition::Eq("users.id".to_string(), SqlValue::Int(1)),
593 Condition::Between(
594 "users.score".to_string(),
595 SqlValue::Int(10),
596 SqlValue::Int(20),
597 ),
598 ]);
599
600 let sql = match condition_to_sql_owned_checked(condition, &mut params) {
601 Ok(sql) => sql,
602 Err(error) => panic!("合法条件不应渲染失败: {error}"),
603 };
604 assert_eq!(
605 sql,
606 "(\"users\".\"id\" = $2 AND \"users\".\"score\" BETWEEN $3 AND $4)"
607 );
608 assert_eq!(params.len(), 4);
609 assert!(matches!(params[0], SqlValue::Int(99)));
610 assert!(matches!(params[1], SqlValue::Int(1)));
611 assert!(matches!(params[2], SqlValue::Int(10)));
612 assert!(matches!(params[3], SqlValue::Int(20)));
613 }
614
615 #[test]
616 fn test_legacy_renderer_fails_closed_without_raw_payload_or_params() {
617 let mut params = Vec::new();
618 let sql = condition_to_sql_owned(
619 Condition::Eq("id; DROP TABLE users".to_string(), SqlValue::Int(1)),
620 &mut params,
621 );
622
623 assert_eq!(sql, FAIL_CLOSED_CONDITION);
624 assert!(!sql.contains("DROP TABLE"));
625 assert!(params.is_empty());
626 }
627
628 #[test]
629 fn test_condition_eq_uses_dollar_placeholder() {
630 let mut params = Vec::new();
631 let cond = Condition::Eq("name".to_string(), SqlValue::String("test".to_string()));
632 let sql = condition_to_sql(&cond, &mut params);
633 assert_eq!(sql, "\"name\" = $1");
634 assert_eq!(params.len(), 1);
635 }
636
637 #[test]
638 fn test_condition_in_numbered_sequentially() {
639 let mut params = Vec::new();
640 let cond = Condition::In(
641 "id".to_string(),
642 vec![SqlValue::Int(1), SqlValue::Int(2), SqlValue::Int(3)],
643 );
644 let sql = condition_to_sql(&cond, &mut params);
645 assert_eq!(sql, "\"id\" IN ($1, $2, $3)");
646 assert_eq!(params.len(), 3);
647 }
648
649 #[test]
650 fn test_condition_in_empty() {
651 let mut params = Vec::new();
652 let cond = Condition::In("id".to_string(), vec![]);
653 let sql = condition_to_sql(&cond, &mut params);
654 assert_eq!(sql, FAIL_CLOSED_CONDITION);
655 assert_eq!(params.len(), 0);
656 }
657
658 #[test]
659 fn test_condition_between() {
660 let mut params = Vec::new();
661 let cond = Condition::Between("age".to_string(), SqlValue::Int(18), SqlValue::Int(65));
662 let sql = condition_to_sql(&cond, &mut params);
663 assert_eq!(sql, "\"age\" BETWEEN $1 AND $2");
664 assert_eq!(params.len(), 2);
665 }
666
667 #[test]
668 fn test_placeholder_continues_from_existing_params() {
669 let mut params = vec![SqlValue::Int(100), SqlValue::String("x".to_string())];
671 let cond = Condition::Eq("id".to_string(), SqlValue::Int(1));
672 let sql = condition_to_sql(&cond, &mut params);
673 assert_eq!(sql, "\"id\" = $3");
674 assert_eq!(params.len(), 3);
675 }
676
677 #[test]
678 fn test_condition_and_priority_and_numbering() {
679 let mut params = Vec::new();
680 let cond = Condition::And(vec![
682 Condition::Or(vec![
683 Condition::Eq("name".to_string(), SqlValue::String("test".to_string())),
684 Condition::Eq("name".to_string(), SqlValue::String("demo".to_string())),
685 ]),
686 Condition::Gt("age".to_string(), SqlValue::Int(18)),
687 ]);
688 let sql = condition_to_sql(&cond, &mut params);
689 assert_eq!(sql, "((\"name\" = $1 OR \"name\" = $2) AND \"age\" > $3)");
690 assert_eq!(params.len(), 3);
691 }
692
693 #[test]
694 fn test_is_null_and_not_null_no_params() {
695 let mut params = Vec::new();
696 let cond = Condition::And(vec![
697 Condition::IsNull("a".to_string()),
698 Condition::IsNotNull("b".to_string()),
699 ]);
700 let sql = condition_to_sql(&cond, &mut params);
701 assert_eq!(sql, "(\"a\" IS NULL AND \"b\" IS NOT NULL)");
702 assert_eq!(params.len(), 0);
703 }
704
705 #[test]
706 fn test_owned_equals_borrowed() {
707 let cond = Condition::And(vec![
708 Condition::Eq("a".to_string(), SqlValue::Int(1)),
709 Condition::Like("b".to_string(), "%x%".to_string()),
710 ]);
711 let mut p1 = vec![];
712 let mut p2 = vec![];
713 let s1 = condition_to_sql_owned(cond.clone(), &mut p1);
714 let s2 = condition_to_sql(&cond, &mut p2);
715 assert_eq!(s1, s2);
716 assert_eq!(p1.len(), p2.len());
717 assert_eq!(format!("{:?}", p1), format!("{:?}", p2));
718 }
719
720 #[test]
721 fn test_not_renders_and_composes_with_and_or() {
722 let mut params = Vec::new();
723 let condition = Condition::And(vec![
724 Condition::Not(Box::new(Condition::Eq(
725 "status".to_string(),
726 SqlValue::String("deleted".to_string()),
727 ))),
728 Condition::Or(vec![
729 Condition::Gt("age".to_string(), SqlValue::Int(18)),
730 Condition::Not(Box::new(Condition::IsNull("email".to_string()))),
731 ]),
732 ]);
733 let sql = condition_to_sql_owned_checked(condition, &mut params).unwrap();
734 assert_eq!(
735 sql,
736 "(NOT (\"status\" = $1) AND (\"age\" > $2 OR NOT (\"email\" IS NULL)))"
737 );
738 assert_eq!(params.len(), 2);
739 }
740
741 #[test]
742 fn test_field_expr_placeholder_continues_after_existing_params() {
743 let mut params = vec![SqlValue::Int(99)];
744 let condition = Condition::FieldExpr(
745 "updated_at".to_string(),
746 ComparisonOperator::Lt,
747 crate::SqlExpr::unix_timestamp_add(30),
748 );
749 let sql = condition_to_sql_owned_checked(condition, &mut params).unwrap();
750 assert_eq!(sql, "\"updated_at\" < EXTRACT(EPOCH FROM now()) + $2");
751 assert_eq!(params.len(), 2);
752 assert!(matches!(params[1], SqlValue::Int(30)));
753 }
754
755 #[test]
756 fn test_field_expr_without_param_does_not_consume_numbering() {
757 let mut params = Vec::new();
758 let condition = Condition::FieldExpr(
759 "updated_at".to_string(),
760 ComparisonOperator::Gte,
761 crate::SqlExpr::now(),
762 );
763 let sql = condition_to_sql_owned_checked(condition, &mut params).unwrap();
764 assert_eq!(sql, "\"updated_at\" >= now()");
765 assert!(params.is_empty());
766 }
767
768 #[test]
769 fn test_new_sql_value_from_conversions() {
770 use chrono::TimeZone;
771
772 let decimal = bigdecimal::BigDecimal::from(42);
773 assert!(matches!(
774 SqlValue::from(decimal),
775 SqlValue::Decimal(value) if value.to_string() == "42"
776 ));
777 let uuid = uuid::Uuid::parse_str("00000000-0000-0000-0000-000000000001").unwrap();
778 assert!(matches!(SqlValue::from(uuid), SqlValue::Uuid(_)));
779 let date = chrono::NaiveDate::from_ymd_opt(2026, 11, 8).unwrap();
780 assert!(matches!(SqlValue::from(date), SqlValue::Date(_)));
781 let time = chrono::NaiveTime::from_hms_opt(12, 30, 0).unwrap();
782 assert!(matches!(SqlValue::from(time), SqlValue::Time(_)));
783 let tz = chrono::Utc.with_ymd_and_hms(2026, 11, 8, 12, 0, 0).unwrap();
784 assert!(matches!(SqlValue::from(tz), SqlValue::DateTimeTz(_)));
785 assert!(matches!(
786 SqlValue::from(chrono::Duration::seconds(2)),
787 SqlValue::Interval(2_000_000)
788 ));
789 assert!(matches!(
790 SqlValue::interval_micros(-5),
791 SqlValue::Interval(-5)
792 ));
793 }
794
795 #[test]
796 fn test_array_from_vec_conversions_preserve_element_types() {
797 assert!(matches!(
798 SqlValue::from(vec![1_i64, 2]),
799 SqlValue::Array(values)
800 if matches!(values.as_slice(), [SqlValue::Int(1), SqlValue::Int(2)])
801 ));
802 assert!(matches!(
803 SqlValue::from(vec!["a".to_string(), "b".to_string()]),
804 SqlValue::Array(values)
805 if matches!(&values[0], SqlValue::String(value) if value == "a")
806 && matches!(&values[1], SqlValue::String(value) if value == "b")
807 ));
808 assert!(matches!(
809 SqlValue::from(vec![1.5_f64, 2.5]),
810 SqlValue::Array(values)
811 if matches!(&values[0], SqlValue::Float(value) if *value == 1.5)
812 && matches!(&values[1], SqlValue::Float(value) if *value == 2.5)
813 ));
814 assert!(matches!(
815 SqlValue::from(vec![true, false]),
816 SqlValue::Array(values)
817 if matches!(values.as_slice(), [SqlValue::Bool(true), SqlValue::Bool(false)])
818 ));
819 assert!(matches!(
821 SqlValue::from(Vec::<i64>::new()),
822 SqlValue::Array(values) if values.is_empty()
823 ));
824 }
825
826 #[test]
827 fn test_array_value_renders_as_one_param() {
828 let mut params = Vec::new();
829 let condition = Condition::Eq(
830 "tags".to_string(),
831 SqlValue::from(vec!["a".to_string(), "b".to_string()]),
832 );
833 let sql = condition_to_sql_owned_checked(condition, &mut params).unwrap();
834 assert_eq!(sql, "\"tags\" = $1");
835 assert_eq!(params.len(), 1, "数组必须作为单个绑定参数渲染");
836 assert!(matches!(¶ms[0], SqlValue::Array(values) if values.len() == 2));
837 }
838
839 #[test]
840 fn test_any_all_render_array_binding_and_numbering() {
841 let mut params = vec![SqlValue::Int(99)];
842 let condition = Condition::Any("tags".to_string(), SqlValue::from(vec!["a".to_string()]));
843 let sql = condition_to_sql_owned_checked(condition, &mut params).unwrap();
844 assert_eq!(sql, "\"tags\" = ANY($2)");
845 assert_eq!(params.len(), 2);
846
847 let mut params = Vec::new();
848 let condition = Condition::All("nums".to_string(), SqlValue::from(vec![1_i64, 2]));
849 let sql = condition_to_sql_owned_checked(condition, &mut params).unwrap();
850 assert_eq!(sql, "\"nums\" = ALL($1)");
851 assert_eq!(params.len(), 1);
852 assert!(matches!(¶ms[0], SqlValue::Array(values) if values.len() == 2));
853 }
854
855 #[test]
856 fn test_any_rejects_non_array_value_fail_closed() {
857 let mut params = Vec::new();
858 let error = condition_to_sql_owned_checked(
859 Condition::Any("tags".to_string(), SqlValue::String("a".to_string())),
860 &mut params,
861 )
862 .expect_err("ANY 只接受 SqlValue::Array");
863 assert!(matches!(error, DbError::InvalidArgument(_)));
864 assert!(params.is_empty(), "失败时不得污染调用方参数");
865
866 let mut params = Vec::new();
867 let error = condition_to_sql_owned_checked(
868 Condition::All("tags".to_string(), SqlValue::Null),
869 &mut params,
870 )
871 .expect_err("ALL 只接受 SqlValue::Array");
872 assert!(matches!(error, DbError::InvalidArgument(_)));
873 assert!(params.is_empty());
874 }
875
876 #[test]
877 fn test_json_predicates_render_operators_and_bind_values() {
878 let payload = SqlValue::Json(serde_json::json!({"role": "admin"}));
879
880 let mut params = Vec::new();
881 let sql = condition_to_sql_owned_checked(
882 Condition::JsonContains("data".to_string(), payload),
883 &mut params,
884 )
885 .unwrap();
886 assert_eq!(sql, "(\"data\")::jsonb @> $1");
887 assert_eq!(params.len(), 1);
888 assert!(matches!(¶ms[0], SqlValue::Json(_)));
889
890 let mut params = Vec::new();
891 let sql = condition_to_sql_owned_checked(
892 Condition::JsonContainedBy(
893 "data".to_string(),
894 SqlValue::Json(serde_json::json!({"role": "admin"})),
895 ),
896 &mut params,
897 )
898 .unwrap();
899 assert_eq!(sql, "(\"data\")::jsonb <@ $1");
900 assert_eq!(params.len(), 1);
901
902 let mut params = Vec::new();
903 let sql = condition_to_sql_owned_checked(
904 Condition::JsonHasKey("data".to_string(), "weird'key".to_string()),
905 &mut params,
906 )
907 .unwrap();
908 assert_eq!(
909 sql, "(\"data\")::jsonb ? $1",
910 "键名必须参数化,不得拼接进 SQL 文本"
911 );
912 assert!(!sql.contains("weird'key"));
913 assert!(matches!(¶ms[0], SqlValue::String(key) if key == "weird'key"));
914 }
915
916 #[test]
917 fn test_json_predicate_null_renders_sql_null_without_param() {
918 let mut params = Vec::new();
919 let sql = condition_to_sql_owned_checked(
920 Condition::JsonContains("data".to_string(), SqlValue::Null),
921 &mut params,
922 )
923 .unwrap();
924 assert_eq!(sql, "NULL");
925 assert!(params.is_empty());
926 }
927
928 #[test]
929 fn test_json_predicate_rejects_non_json_value() {
930 let mut params = Vec::new();
931 let error = condition_to_sql_owned_checked(
932 Condition::JsonContainedBy("data".to_string(), SqlValue::Int(1)),
933 &mut params,
934 )
935 .expect_err("JSON 谓词只接受 SqlValue::Json");
936 assert!(matches!(error, DbError::InvalidArgument(_)));
937 assert!(params.is_empty());
938 }
939
940 #[test]
941 fn test_json_predicates_compose_and_number_sequentially() {
942 let mut params = Vec::new();
943 let condition = Condition::And(vec![
944 Condition::JsonContains(
945 "data".to_string(),
946 SqlValue::Json(serde_json::json!({"role": "admin"})),
947 ),
948 Condition::JsonHasKey("data".to_string(), "active".to_string()),
949 ]);
950 let sql = condition_to_sql_owned_checked(condition, &mut params).unwrap();
951 assert_eq!(sql, "((\"data\")::jsonb @> $1 AND (\"data\")::jsonb ? $2)");
952 assert_eq!(params.len(), 2);
953 assert!(matches!(¶ms[1], SqlValue::String(key) if key == "active"));
954 }
955
956 #[test]
957 fn test_range_predicates_render_operators_and_explicit_casts() {
958 let mut params = Vec::new();
959 let sql = condition_to_sql_owned_checked(
960 Condition::RangeContains("span".to_string(), SqlValue::Range("[1,10)".to_string())),
961 &mut params,
962 )
963 .unwrap();
964 assert_eq!(sql, "\"span\" @> $1::int4range");
965 assert_eq!(params.len(), 1);
966 assert!(matches!(¶ms[0], SqlValue::Range(text) if text == "[1,10)"));
967
968 let mut params = vec![SqlValue::Int(99)];
969 let sql = condition_to_sql_owned_checked(
970 Condition::RangeOverlaps(
971 "spans".to_string(),
972 SqlValue::Multirange("{[1,10),[20,30)}".to_string()),
973 ),
974 &mut params,
975 )
976 .unwrap();
977 assert_eq!(sql, "\"spans\" && $2::int4multirange");
978 assert_eq!(params.len(), 2, "范围值必须作为单个绑定参数");
979 }
980
981 #[test]
982 fn test_range_predicates_reject_non_range_values_and_null_fails_closed() {
983 let mut params = Vec::new();
984 let error = condition_to_sql_owned_checked(
985 Condition::RangeContains("span".to_string(), SqlValue::String("[1,10)".to_string())),
986 &mut params,
987 )
988 .expect_err("范围谓词只接受 Range/Multirange");
989 assert!(matches!(error, DbError::InvalidArgument(_)));
990 assert!(params.is_empty());
991
992 let mut params = Vec::new();
993 let sql = condition_to_sql_owned_checked(
994 Condition::RangeOverlaps("span".to_string(), SqlValue::Null),
995 &mut params,
996 )
997 .unwrap();
998 assert_eq!(sql, "NULL");
999 assert!(params.is_empty());
1000 }
1001
1002 #[test]
1003 fn test_json_path_predicates_bind_path_and_vars() {
1004 let mut params = Vec::new();
1005 let sql = condition_to_sql_owned_checked(
1006 Condition::JsonPathExists("data".to_string(), "$.role".to_string()),
1007 &mut params,
1008 )
1009 .unwrap();
1010 assert_eq!(sql, "jsonb_path_exists((\"data\")::jsonb, $1::jsonpath)");
1011 assert!(!sql.contains("$.role"), "路径必须参数化,不得拼进 SQL");
1012 assert!(matches!(¶ms[0], SqlValue::String(path) if path == "$.role"));
1013
1014 let mut params = Vec::new();
1015 let sql = condition_to_sql_owned_checked(
1016 Condition::JsonPathMatch(
1017 "data".to_string(),
1018 "$.age > $min".to_string(),
1019 SqlValue::Json(serde_json::json!({"min": 18})),
1020 ),
1021 &mut params,
1022 )
1023 .unwrap();
1024 assert_eq!(
1025 sql,
1026 "jsonb_path_match((\"data\")::jsonb, $1::jsonpath, $2::jsonb)"
1027 );
1028 assert_eq!(params.len(), 2);
1029 assert!(!sql.contains("min"));
1030 }
1031
1032 #[test]
1033 fn test_full_text_predicates_use_simple_config_and_bind_query() {
1034 let mut params = Vec::new();
1035 let sql = condition_to_sql_owned_checked(
1036 Condition::FullText("body".to_string(), "hello world".to_string()),
1037 &mut params,
1038 )
1039 .unwrap();
1040 assert_eq!(
1041 sql,
1042 "to_tsvector('simple', \"body\") @@ plainto_tsquery('simple', $1)"
1043 );
1044 assert!(!sql.contains("hello world"));
1045 assert!(matches!(¶ms[0], SqlValue::String(query) if query == "hello world"));
1046
1047 let mut params = Vec::new();
1048 let sql = condition_to_sql_owned_checked(
1049 Condition::FullTextQuery("body".to_string(), "hello & world".to_string()),
1050 &mut params,
1051 )
1052 .unwrap();
1053 assert_eq!(
1054 sql,
1055 "to_tsvector('simple', \"body\") @@ to_tsquery('simple', $1)"
1056 );
1057 assert_eq!(params.len(), 1);
1058 }
1059
1060 #[test]
1061 fn test_phase_c_conditions_number_sequentially_inside_and() {
1062 let mut params = Vec::new();
1063 let condition = Condition::And(vec![
1064 Condition::FullText("body".to_string(), "rust".to_string()),
1065 Condition::JsonPathExists("meta".to_string(), "$.ok".to_string()),
1066 Condition::RangeContains("span".to_string(), SqlValue::Range("[1,5)".to_string())),
1067 ]);
1068 let sql = condition_to_sql_owned_checked(condition, &mut params).unwrap();
1069 assert_eq!(params.len(), 3);
1070 assert!(sql.contains("$1"));
1071 assert!(sql.contains("$2::jsonpath"));
1072 assert!(sql.contains("$3::int4range"));
1073 }
1074}