Skip to main content

yang_db/postgres/
condition.rs

1#![allow(deprecated)]
2
3use chrono::{DateTime, NaiveDate, NaiveDateTime, NaiveTime, Utc};
4use serde_json::Value as JsonValue;
5
6use crate::DbError;
7
8/// 受控列比较操作符。
9#[derive(Debug, Clone, Copy)]
10pub enum ComparisonOperator {
11    /// 等于。
12    Eq,
13    /// 不等于。
14    Ne,
15    /// 大于。
16    Gt,
17    /// 小于。
18    Lt,
19    /// 大于等于。
20    Gte,
21    /// 小于等于。
22    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/// 只能由安全标识符和绑定条件构造的 SELECT 子查询。
51#[derive(Debug, Clone)]
52pub struct Subquery {
53    table: String,
54    field: String,
55    conditions: Vec<Condition>,
56}
57
58impl Subquery {
59    /// 创建只投影一个字段的受控子查询。
60    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    /// 添加字段与绑定值的 AND 条件。
71    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    /// 添加两个已校验列之间的 AND 比较,用于关联子查询。
91    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/// SQL 值类型(PostgreSQL)
104///
105/// 与 MySQL 后端的 `SqlValue` 结构一致,独立定义以保持 `postgres` 模块自包含,
106/// 避免跨方言耦合。变体集合与 `From` 转换均与 MySQL 版本保持对齐。
107#[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    /// NUMERIC / DECIMAL,按精确十进制绑定,避免经 f64 丢精度。
120    Decimal(bigdecimal::BigDecimal),
121    /// UUID(`uuid` 扩展类型)。
122    Uuid(uuid::Uuid),
123    /// TIMESTAMPTZ(带时区)。
124    DateTimeTz(DateTime<Utc>),
125    /// DATE。
126    Date(NaiveDate),
127    /// TIME。
128    Time(NaiveTime),
129    /// INTERVAL,单位为微秒。
130    Interval(i64),
131    /// PostgreSQL 数组(`type[]`),元素按顺序作为单个数组绑定参数传输,
132    /// 不展开为多个标量参数。可承载的 From 转换见 `Vec<i64>` / `Vec<String>` /
133    /// `Vec<f64>` / `Vec<bool>`。
134    ///
135    /// 元素类型按首个非 NULL 元素推断;空数组/全 NULL 数组没有类型线索,
136    /// 类型敏感场景请用 [`SqlValue::TypedArray`]。
137    Array(Vec<SqlValue>),
138    /// 带显式元素类型的 PostgreSQL 数组(如 `int4[]` / `bytea[]`)。
139    ///
140    /// `element_type` 是受控的内置类型名(`int2`/`int4`/`int8`/`float4`/`float8`/
141    /// `bool`/`text`/`varchar`/`bytea`/`uuid`/`date`/`time`/`timestamp`/
142    /// `timestamptz`/`numeric`/`jsonb`/`inet`/`cidr`/`macaddr`/`macaddr8`),
143    /// 决定绑定使用的 Rust 数组类型;空数组与全 NULL 数组也能按真实列类型绑定,
144    /// 不再退化为 `text[]`。
145    TypedArray {
146        /// 元素类型名(受控白名单,见枚举文档)。
147        element_type: &'static str,
148        /// 元素值,按顺序绑定。
149        values: Vec<SqlValue>,
150    },
151    /// PostgreSQL `inet` 文本值;渲染时追加 `::inet`。
152    Inet(String),
153    /// PostgreSQL `cidr` 文本值;渲染时追加 `::cidr`。
154    Cidr(String),
155    /// PostgreSQL `macaddr` 文本值;渲染时追加 `::macaddr`。
156    MacAddr(String),
157    /// PostgreSQL `macaddr8` 文本值;渲染时追加 `::macaddr8`。
158    MacAddr8(String),
159    /// 范围文本值(如 `[1,10)`);按文本绑定并追加 `::int4range`。
160    ///
161    /// 目前仅内置默认的 32 位整数范围转换;其它范围类型需要在 SQL 文本中显式
162    /// 指定转换(`$1::tsrange` 等)。
163    Range(String),
164    /// 多范围文本值(如 `{[1,10),[20,30)}`);按文本绑定并追加
165    /// `::int4multirange`(PostgreSQL 14+)。
166    Multirange(String),
167}
168
169/// 查询条件(PostgreSQL)
170#[derive(Debug, Clone)]
171#[non_exhaustive]
172pub enum Condition {
173    /// 相等
174    Eq(String, SqlValue),
175    /// 不等
176    Ne(String, SqlValue),
177    /// 大于
178    Gt(String, SqlValue),
179    /// 小于
180    Lt(String, SqlValue),
181    /// 大于等于
182    Gte(String, SqlValue),
183    /// 小于等于
184    Lte(String, SqlValue),
185    /// IN 条件
186    In(String, Vec<SqlValue>),
187    /// NOT IN 条件
188    NotIn(String, Vec<SqlValue>),
189    /// BETWEEN 条件
190    Between(String, SqlValue, SqlValue),
191    /// LIKE 条件
192    Like(String, String),
193    /// 大小写不敏感 LIKE 条件(`ILIKE`)。
194    ILike(String, String),
195    /// 大小写不敏感 LIKE 取反(`NOT ILIKE`)。
196    NotILike(String, String),
197    /// POSIX 正则匹配(`~`)。
198    RegexMatch(String, String),
199    /// 大小写不敏感 POSIX 正则匹配(`~*`)。
200    RegexIMatch(String, String),
201    /// POSIX 正则不匹配(`!~`)。
202    NotRegexMatch(String, String),
203    /// 大小写不敏感 POSIX 正则不匹配(`!~*`)。
204    NotRegexIMatch(String, String),
205    /// NULL-safe 不相等(`IS DISTINCT FROM`)。
206    IsDistinctFrom(String, SqlValue),
207    /// NULL-safe 相等(`IS NOT DISTINCT FROM`)。
208    IsNotDistinctFrom(String, SqlValue),
209    /// IS NULL 条件
210    IsNull(String),
211    /// IS NOT NULL 条件
212    IsNotNull(String),
213    /// 两个标识符之间的受控比较。
214    ColumnComparison(String, ComparisonOperator, String),
215    /// EXISTS 子查询。
216    Exists(Box<Subquery>),
217    /// NOT EXISTS 子查询。
218    NotExists(Box<Subquery>),
219    /// IN 子查询。
220    InSubquery(String, Box<Subquery>),
221    /// 字段与受控服务端表达式的比较(如 `updated_at < now()`)。
222    FieldExpr(String, ComparisonOperator, crate::SqlExpr),
223    /// JSON/JSONB 包含谓词:`field @> $n`(右值必须是 [`SqlValue::Json`])。
224    JsonContains(String, SqlValue),
225    /// JSON/JSONB 被包含谓词:`field <@ $n`(右值必须是 [`SqlValue::Json`])。
226    JsonContainedBy(String, SqlValue),
227    /// JSON/JSONB 顶层键存在谓词:`field ? $n`(键名以绑定参数传入)。
228    JsonHasKey(String, String),
229    /// 数组包含任一元素:`field = ANY($n)`(右值必须是 [`SqlValue::Array`])。
230    Any(String, SqlValue),
231    /// 数组包含全部元素:`field = ALL($n)`(右值必须是 [`SqlValue::Array`])。
232    All(String, SqlValue),
233    /// 范围包含:`field @> $n`(右值必须是范围或多范围文本值)。
234    RangeContains(String, SqlValue),
235    /// 范围重叠:`field && $n`(右值必须是范围或多范围文本值)。
236    RangeOverlaps(String, SqlValue),
237    /// JSONB 路径存在:`jsonb_path_exists((field)::jsonb, $n::jsonpath)`。
238    JsonPathExists(String, String),
239    /// JSONB 路径谓词:`jsonb_path_match((field)::jsonb, $n::jsonpath, $m::jsonb)`。
240    JsonPathMatch(String, String, SqlValue),
241    /// 全文检索:`to_tsvector('simple', field) @@ plainto_tsquery('simple', $n)`。
242    FullText(String, String),
243    /// 全文检索(`to_tsquery` 变体,允许布尔查询语法)。
244    FullTextQuery(String, String),
245    /// NOT 包裹;渲染为 `NOT (...)`。
246    Not(Box<Condition>),
247    /// AND 组合
248    And(Vec<Condition>),
249    /// OR 组合
250    Or(Vec<Condition>),
251}
252
253// 实现 From trait 支持自动转换(与 MySQL 后端保持一致)
254impl 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        // u64 顶半区(> i64::MAX)强转 i64 会静默环绕成负数(NEW-11)。PG 无无符号类型,
269        // 此类值本就放不进 BIGINT,走十进制字符串:对 NUMERIC 列正确,对 int8 列会显式
270        // 报错(值确实溢出),均优于静默改写成负数。
271        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
315/// `BIGINT[]` / `INT8[]` 数组。
316impl 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
322/// `TEXT[]` / `VARCHAR[]` 数组。
323impl 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
329/// `DOUBLE PRECISION[]` / `FLOAT8[]` 数组。
330impl 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
336/// `BOOLEAN[]` / `BOOL[]` 数组。
337impl 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
391/// 以微秒构造 INTERVAL 值。
392impl SqlValue {
393    /// INTERVAL(微秒)。
394    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/// 将条件转换为 SQL 字符串和参数列表(借用版本)
412///
413/// # 参数
414/// - condition: 要转换的条件
415/// - params: 用于收集参数的可变向量(占位符编号基于其当前长度)
416///
417/// # 返回
418/// - SQL 字符串片段
419#[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    // 借用版本是消费版本的薄委托:整树 clone 一次后交给 owned 实现,
425    // 二者共享同一套 match 分支,避免逻辑重复。输出 SQL 与参数顺序完全一致。
426    condition_to_sql_owned(condition.clone(), params)
427}
428
429const FAIL_CLOSED_CONDITION: &str = "/* invalid condition */ 1 = 0";
430
431/// 兼容的 infallible 入口只委托 checked renderer;失败时返回固定不可执行条件。
432#[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
441/// 严格版条件转 SQL:非法标识符返回 [`DbError::InvalidArgument`]。
442///
443/// 只接受单段或两段限定标识符,不接受表达式;失败时调用方参数保持不变。
444///
445/// # 返回
446///
447/// - `Ok(String)`: SQL 片段
448/// - `Err(DbError::InvalidArgument)`: 包含非法标识符
449pub 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;这里只做公开条件树 → 内部树的转换。
463    // `parameter_offset` 保证 `$N` 编号接续调用方参数列表的既有长度。
464    crate::dialect::render_condition(
465        crate::dialect::POSTGRES,
466        into_node(condition),
467        parameter_offset,
468    )
469}
470
471/// 将公开条件树转换为方言无关的内部渲染树(值原样移动,不复制)。
472fn 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
541/// 将受控子查询转换为内部渲染节点。
542fn 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        // 模拟 UPDATE:SET 子句已压入 2 个参数后再生成 WHERE,编号应接续为 $3
670        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        // ("name" = $1 OR "name" = $2) AND "age" > $3
681        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        // 空数组是合法值(ANY 恒 false / ALL 恒 true 由 SQL 语义决定)。
820        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!(&params[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!(&params[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!(&params[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!(&params[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!(&params[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!(&params[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!(&params[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!(&params[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}