Skip to main content

prax_postgres/
types.rs

1//! Type conversions for PostgreSQL.
2
3use std::str::FromStr;
4
5use prax_query::filter::FilterValue;
6use tokio_postgres::types::{IsNull, Kind, ToSql, Type};
7
8use crate::error::{PgError, PgResult};
9
10/// Polymorphic integer binding. `FilterValue::Int` always carries an i64
11/// (the widest scalar variant), but Postgres strictly validates client
12/// bindings against column types: binding an i64 to an `INT4` column
13/// fails with `WrongType { postgres: Int4, rust: "i64" }`. This wrapper
14/// inspects the target column type at bind time and narrows to i16 /
15/// i32 / i64 with a bounds check before forwarding to tokio-postgres'
16/// own impls.
17#[derive(Debug)]
18struct PgInt(i64);
19
20impl ToSql for PgInt {
21    fn to_sql(
22        &self,
23        ty: &Type,
24        out: &mut bytes::BytesMut,
25    ) -> Result<IsNull, Box<dyn std::error::Error + Sync + Send>> {
26        match *ty {
27            Type::INT2 => {
28                let v: i16 = self
29                    .0
30                    .try_into()
31                    .map_err(|_| format!("value {} overflows INT2", self.0))?;
32                v.to_sql(ty, out)
33            }
34            Type::INT4 => {
35                let v: i32 = self
36                    .0
37                    .try_into()
38                    .map_err(|_| format!("value {} overflows INT4", self.0))?;
39                v.to_sql(ty, out)
40            }
41            Type::INT8 => self.0.to_sql(ty, out),
42            _ => Err(format!("cannot bind integer to postgres type {ty:?}").into()),
43        }
44    }
45
46    fn accepts(ty: &Type) -> bool {
47        matches!(*ty, Type::INT2 | Type::INT4 | Type::INT8)
48    }
49
50    tokio_postgres::types::to_sql_checked!();
51}
52
53/// Polymorphic string binding. `FilterValue::String` always carries a
54/// Rust `String`, but Postgres rejects a String bound to a UUID column
55/// (`WrongType { postgres: Uuid, rust: "alloc::string::String" }`).
56/// This wrapper inspects the target column type at bind time and
57/// converts as appropriate; for plain TEXT/VARCHAR/CHAR/NAME and other
58/// types it forwards the String directly.
59#[derive(Debug)]
60struct PgString(String);
61
62impl PgString {
63    /// Whether a `PgString` can bind to `ty`. Must match the arms of
64    /// `PgString::to_sql` below: the specially-parsed types, user-defined
65    /// enums, and everything `String` itself accepts.
66    fn binds_to(ty: &Type) -> bool {
67        matches!(
68            *ty,
69            Type::UUID | Type::TIMESTAMPTZ | Type::TIMESTAMP | Type::DATE | Type::TIME
70        ) || matches!(ty.kind(), Kind::Enum(_))
71            || <String as ToSql>::accepts(ty)
72    }
73}
74
75/// Parse the text of a `FilterValue::String` bound to a TIMESTAMP
76/// (`timestamp without time zone`) parameter.
77///
78/// A naive ISO-8601 datetime (what `NaiveDateTime` lowers to) is stored
79/// as-is. An RFC 3339 datetime with an offset (what `DateTime<Utc>` lowers
80/// to, `...Z`) is converted to UTC and its naive UTC value stored, the
81/// convention `PgRow::get_datetime_utc` reads back.
82fn naive_timestamp_from_str(
83    s: &str,
84) -> Result<::chrono::NaiveDateTime, Box<dyn std::error::Error + Sync + Send>> {
85    if let Ok(naive) = ::chrono::NaiveDateTime::parse_from_str(s, "%Y-%m-%dT%H:%M:%S%.f") {
86        return Ok(naive);
87    }
88    match ::chrono::DateTime::parse_from_rfc3339(s) {
89        Ok(aware) => Ok(aware.naive_utc()),
90        Err(e) => Err(format!(
91            "FilterValue::String('{s}') is not a valid ISO-8601 naive or RFC 3339 \
92             datetime for TIMESTAMP: {e}"
93        )
94        .into()),
95    }
96}
97
98impl ToSql for PgString {
99    fn to_sql(
100        &self,
101        ty: &Type,
102        out: &mut bytes::BytesMut,
103    ) -> Result<IsNull, Box<dyn std::error::Error + Sync + Send>> {
104        match *ty {
105            Type::UUID => {
106                let parsed = ::uuid::Uuid::from_str(&self.0).map_err(|e| {
107                    format!("FilterValue::String('{}') is not a valid UUID: {e}", self.0)
108                })?;
109                parsed.to_sql(ty, out)
110            }
111            // chrono types round-trip through `FilterValue::String`
112            // (see `prax-query/src/filter.rs`). Postgres rejects a String
113            // bound to TIMESTAMPTZ/TIMESTAMP/DATE/TIME with WrongType,
114            // so re-parse and forward through tokio-postgres' chrono
115            // FromSql/ToSql impls.
116            Type::TIMESTAMPTZ => {
117                let parsed: ::chrono::DateTime<::chrono::Utc> =
118                    ::chrono::DateTime::parse_from_rfc3339(&self.0)
119                        .map_err(|e| {
120                            format!(
121                                "FilterValue::String('{}') is not a valid RFC3339 \
122                                 datetime for TIMESTAMPTZ: {e}",
123                                self.0
124                            )
125                        })?
126                        .with_timezone(&::chrono::Utc);
127                parsed.to_sql(ty, out)
128            }
129            Type::TIMESTAMP => naive_timestamp_from_str(&self.0)?.to_sql(ty, out),
130            Type::DATE => {
131                let parsed =
132                    ::chrono::NaiveDate::parse_from_str(&self.0, "%Y-%m-%d").map_err(|e| {
133                        format!(
134                            "FilterValue::String('{}') is not a valid \
135                             YYYY-MM-DD date for DATE: {e}",
136                            self.0
137                        )
138                    })?;
139                parsed.to_sql(ty, out)
140            }
141            Type::TIME => {
142                let parsed =
143                    ::chrono::NaiveTime::parse_from_str(&self.0, "%H:%M:%S%.f").map_err(|e| {
144                        format!(
145                            "FilterValue::String('{}') is not a valid \
146                                 HH:MM:SS time for TIME: {e}",
147                            self.0
148                        )
149                    })?;
150                parsed.to_sql(ty, out)
151            }
152            _ => {
153                // User-defined `ENUM` columns reach this arm; their
154                // wire format is just utf-8 bytes, so write the
155                // string body directly. Plain TEXT/VARCHAR/CHAR/NAME
156                // also takes this path through `String: ToSql`.
157                if matches!(ty.kind(), Kind::Enum(_)) {
158                    out.extend_from_slice(self.0.as_bytes());
159                    Ok(IsNull::No)
160                } else {
161                    self.0.to_sql(ty, out)
162                }
163            }
164        }
165    }
166
167    fn accepts(_ty: &Type) -> bool {
168        true
169    }
170
171    tokio_postgres::types::to_sql_checked!();
172}
173
174/// Untyped NULL binding. `FilterValue::Null` must bind successfully against
175/// a column of any type (nullable UUID, custom ENUM, TIMESTAMPTZ, INT4,
176/// ...), but `Option::<String>::None`'s `accepts()` delegates to
177/// `String::accepts()`, which only covers TEXT/VARCHAR/CHAR/NAME/UNKNOWN.
178/// tokio-postgres runs that `accepts()` check before `to_sql` is ever
179/// called, so a NULL bound against e.g. a nullable UUID column fails with
180/// "error serializing parameter N" even though NULL has no type-specific
181/// wire representation to get wrong. This wrapper accepts every type and
182/// always signals `IsNull::Yes`.
183#[derive(Debug)]
184struct PgNull;
185
186impl ToSql for PgNull {
187    fn to_sql(
188        &self,
189        _ty: &Type,
190        _out: &mut bytes::BytesMut,
191    ) -> Result<IsNull, Box<dyn std::error::Error + Sync + Send>> {
192        Ok(IsNull::Yes)
193    }
194
195    fn accepts(_ty: &Type) -> bool {
196        true
197    }
198
199    tokio_postgres::types::to_sql_checked!();
200}
201
202/// One element of a `FilterValue::Array` parameter. Delegates to the scalar
203/// binders so each element adapts to the array's element type (e.g. a
204/// `PgString` into `uuid[]`). `Vec<PgElem>: ToSql` (tokio-postgres) supplies
205/// the array wire format and rejects non-array target types.
206#[derive(Debug)]
207enum PgElem {
208    Null(PgNull),
209    Bool(bool),
210    Int(PgInt),
211    Float(f64),
212    String(PgString),
213    Json(serde_json::Value),
214    Bytes(Vec<u8>),
215}
216
217impl PgElem {
218    fn try_from_value(value: &FilterValue) -> PgResult<Self> {
219        Ok(match value {
220            FilterValue::Null => Self::Null(PgNull),
221            FilterValue::Bool(b) => Self::Bool(*b),
222            FilterValue::Int(i) => Self::Int(PgInt(*i)),
223            FilterValue::Float(f) => Self::Float(*f),
224            FilterValue::String(s) => Self::String(PgString(s.clone())),
225            FilterValue::Json(j) => Self::Json(j.clone()),
226            FilterValue::Bytes(b) => Self::Bytes(b.clone()),
227            FilterValue::List(_) | FilterValue::Array(_) => {
228                return Err(PgError::type_conversion(
229                    "nested arrays are not supported in FilterValue::Array",
230                ));
231            }
232            _ => {
233                return Err(PgError::type_conversion(
234                    "unsupported FilterValue variant in FilterValue::Array",
235                ));
236            }
237        })
238    }
239}
240
241impl ToSql for PgElem {
242    fn to_sql(
243        &self,
244        ty: &Type,
245        out: &mut bytes::BytesMut,
246    ) -> Result<IsNull, Box<dyn std::error::Error + Sync + Send>> {
247        // Element-wise `to_sql` is called unchecked by tokio-postgres' array
248        // impl, so every arm must verify the element type itself.
249        fn check(
250            ok: bool,
251            kind: &str,
252            ty: &Type,
253        ) -> Result<(), Box<dyn std::error::Error + Sync + Send>> {
254            if ok {
255                Ok(())
256            } else {
257                Err(format!("cannot bind {kind} array element to postgres type {ty:?}").into())
258            }
259        }
260        match self {
261            Self::Null(v) => v.to_sql(ty, out),
262            Self::Bool(v) => {
263                check(<bool as ToSql>::accepts(ty), "bool", ty)?;
264                v.to_sql(ty, out)
265            }
266            Self::Int(v) => v.to_sql(ty, out),
267            Self::Float(v) => {
268                check(<f64 as ToSql>::accepts(ty), "float", ty)?;
269                v.to_sql(ty, out)
270            }
271            Self::String(v) => {
272                check(PgString::binds_to(ty), "string", ty)?;
273                v.to_sql(ty, out)
274            }
275            Self::Json(v) => {
276                check(<serde_json::Value as ToSql>::accepts(ty), "json", ty)?;
277                v.to_sql(ty, out)
278            }
279            Self::Bytes(v) => {
280                check(<Vec<u8> as ToSql>::accepts(ty), "bytes", ty)?;
281                v.to_sql(ty, out)
282            }
283        }
284    }
285
286    fn accepts(_ty: &Type) -> bool {
287        true
288    }
289
290    tokio_postgres::types::to_sql_checked!();
291}
292
293/// Convert a FilterValue to a type that can be used as a PostgreSQL parameter.
294pub fn filter_value_to_sql(value: &FilterValue) -> PgResult<Box<dyn ToSql + Sync + Send>> {
295    match value {
296        FilterValue::Null => Ok(Box::new(PgNull)),
297        FilterValue::Bool(b) => Ok(Box::new(*b)),
298        FilterValue::Int(i) => Ok(Box::new(PgInt(*i))),
299        FilterValue::Float(f) => Ok(Box::new(*f)),
300        FilterValue::String(s) => Ok(Box::new(PgString(s.clone()))),
301        FilterValue::Json(j) => Ok(Box::new(j.clone())),
302        FilterValue::List(_) => {
303            // Typed IN filters expand to scalar placeholders upstream
304            // (prax-query/src/filter.rs), so this arm only fires for
305            // hand-built raw queries via `Sql::bind`.
306            Err(PgError::type_conversion(
307                "FilterValue::List cannot be bound as one parameter; use Filter::In for IN (...) or FilterValue::Array with = ANY($1)",
308            ))
309        }
310        FilterValue::Bytes(b) => Ok(Box::new(b.clone())),
311        FilterValue::Array(items) => {
312            let elems = items
313                .iter()
314                .map(PgElem::try_from_value)
315                .collect::<PgResult<Vec<_>>>()?;
316            Ok(Box::new(elems))
317        }
318        _ => Err(PgError::type_conversion("unsupported FilterValue variant")),
319    }
320}
321
322/// Convert filter values to PostgreSQL parameters.
323pub fn filter_values_to_params(
324    values: &[FilterValue],
325) -> PgResult<Vec<Box<dyn ToSql + Sync + Send>>> {
326    values.iter().map(filter_value_to_sql).collect()
327}
328
329/// PostgreSQL type mapping utilities.
330pub mod pg_types {
331    use super::*;
332
333    /// Get the PostgreSQL type for a Rust type name.
334    pub fn rust_type_to_pg(rust_type: &str) -> Option<Type> {
335        match rust_type {
336            "i16" => Some(Type::INT2),
337            "i32" => Some(Type::INT4),
338            "i64" => Some(Type::INT8),
339            "f32" => Some(Type::FLOAT4),
340            "f64" => Some(Type::FLOAT8),
341            "bool" => Some(Type::BOOL),
342            "String" | "&str" => Some(Type::TEXT),
343            "Vec<u8>" | "&[u8]" => Some(Type::BYTEA),
344            "chrono::NaiveDate" => Some(Type::DATE),
345            "chrono::NaiveTime" => Some(Type::TIME),
346            "chrono::NaiveDateTime" => Some(Type::TIMESTAMP),
347            "chrono::DateTime<chrono::Utc>" => Some(Type::TIMESTAMPTZ),
348            "uuid::Uuid" => Some(Type::UUID),
349            "serde_json::Value" => Some(Type::JSONB),
350            _ => None,
351        }
352    }
353
354    /// Get the Rust type for a PostgreSQL type.
355    pub fn pg_type_to_rust(pg_type: &Type) -> &'static str {
356        match *pg_type {
357            Type::BOOL => "bool",
358            Type::INT2 => "i16",
359            Type::INT4 => "i32",
360            Type::INT8 => "i64",
361            Type::FLOAT4 => "f32",
362            Type::FLOAT8 => "f64",
363            Type::TEXT | Type::VARCHAR | Type::CHAR | Type::NAME => "String",
364            Type::BYTEA => "Vec<u8>",
365            Type::DATE => "chrono::NaiveDate",
366            Type::TIME => "chrono::NaiveTime",
367            Type::TIMESTAMP => "chrono::NaiveDateTime",
368            Type::TIMESTAMPTZ => "chrono::DateTime<chrono::Utc>",
369            Type::UUID => "uuid::Uuid",
370            Type::JSON | Type::JSONB => "serde_json::Value",
371            _ => "unknown",
372        }
373    }
374}
375
376#[cfg(test)]
377mod tests {
378    use super::*;
379
380    #[test]
381    fn bytes_binds_as_bytea() {
382        let param = filter_value_to_sql(&FilterValue::Bytes(vec![0, 255])).unwrap();
383        let mut buf = bytes::BytesMut::new();
384        param.to_sql_checked(&Type::BYTEA, &mut buf).unwrap();
385        assert_eq!(&buf[..], &[0u8, 255][..]);
386    }
387
388    #[test]
389    fn nested_list_or_array_in_array_is_rejected() {
390        for inner in [FilterValue::List(vec![]), FilterValue::Array(vec![])] {
391            let err = filter_value_to_sql(&FilterValue::Array(vec![inner]))
392                .expect_err("nested collections must error");
393            assert!(matches!(err, PgError::TypeConversion(_)));
394            assert!(err.to_string().contains("nested"), "{err}");
395        }
396    }
397
398    fn bind_array(
399        items: Vec<FilterValue>,
400        ty: &Type,
401    ) -> (
402        Result<IsNull, Box<dyn std::error::Error + Sync + Send>>,
403        bytes::BytesMut,
404    ) {
405        let param = filter_value_to_sql(&FilterValue::Array(items)).unwrap();
406        let mut buf = bytes::BytesMut::new();
407        let res = param.to_sql_checked(ty, &mut buf);
408        (res, buf)
409    }
410
411    #[test]
412    fn array_binds_as_int_array() {
413        let items = vec![FilterValue::Int(1), FilterValue::Null];
414        let (res, buf) = bind_array(items.clone(), &Type::INT4_ARRAY);
415        res.unwrap();
416        // Header: ndim=1, has_null=1, elem oid INT4 (23); dim len 2, lbound 1;
417        // then elem 1 (len 4, value 1) and a NULL (len -1).
418        let mut expected = Vec::new();
419        for v in [1i32, 1, 23, 2, 1, 4, 1, -1] {
420            expected.extend_from_slice(&v.to_be_bytes());
421        }
422        assert_eq!(&buf[..], &expected[..]);
423        // Non-array target types are rejected, not panicked on.
424        assert!(bind_array(items, &Type::INT4).0.is_err());
425    }
426
427    #[test]
428    fn array_wrong_element_kind_errors() {
429        let cases = [
430            (FilterValue::Bool(true), Type::TEXT_ARRAY),
431            (FilterValue::Float(1.5), Type::INT4_ARRAY),
432            (FilterValue::Bytes(vec![1]), Type::TEXT_ARRAY),
433            (
434                FilterValue::Json(serde_json::json!({"a": 1})),
435                Type::INT4_ARRAY,
436            ),
437            (FilterValue::String("x".into()), Type::INT4_ARRAY),
438            (FilterValue::Int(1), Type::TEXT_ARRAY),
439        ];
440        for (item, ty) in cases {
441            let (res, _) = bind_array(vec![item.clone()], &ty);
442            assert!(res.is_err(), "{item:?} into {ty:?} must error");
443        }
444    }
445
446    /// Bind a one-element array and decode it back with `FromSql`.
447    fn assert_roundtrip<T>(item: FilterValue, ty: &Type, expected: T)
448    where
449        T: for<'a> tokio_postgres::types::FromSql<'a> + PartialEq + std::fmt::Debug,
450    {
451        let (res, buf) = bind_array(vec![item.clone()], ty);
452        res.unwrap_or_else(|e| panic!("{item:?} into {ty:?}: {e}"));
453        let decoded = <Vec<T> as tokio_postgres::types::FromSql>::from_sql(ty, &buf)
454            .unwrap_or_else(|e| panic!("decoding {item:?} as {ty:?}: {e}"));
455        assert_eq!(decoded, vec![expected], "{item:?} into {ty:?}");
456    }
457
458    /// Bind a `FilterValue::String` as a scalar parameter of type `ty` and
459    /// decode the bytes back as `T`.
460    fn scalar_roundtrip<T>(s: &str, ty: &Type) -> Result<T, String>
461    where
462        T: for<'a> tokio_postgres::types::FromSql<'a>,
463    {
464        let param =
465            filter_value_to_sql(&FilterValue::String(s.into())).map_err(|e| e.to_string())?;
466        let mut buf = bytes::BytesMut::new();
467        param
468            .to_sql_checked(ty, &mut buf)
469            .map_err(|e| e.to_string())?;
470        T::from_sql(ty, &buf).map_err(|e| e.to_string())
471    }
472
473    fn naive(s: &str) -> ::chrono::NaiveDateTime {
474        ::chrono::NaiveDateTime::parse_from_str(s, "%Y-%m-%dT%H:%M:%S%.f").unwrap()
475    }
476
477    #[test]
478    fn timestamp_accepts_naive_and_converts_offset_datetimes_to_utc() {
479        // NaiveDateTime's lowering: stored as-is.
480        assert_eq!(
481            scalar_roundtrip::<::chrono::NaiveDateTime>(
482                "2024-01-02T03:04:05.123456",
483                &Type::TIMESTAMP
484            ),
485            Ok(naive("2024-01-02T03:04:05.123456"))
486        );
487        // DateTime<Utc>'s lowering (`Z`): its UTC wall time.
488        assert_eq!(
489            scalar_roundtrip::<::chrono::NaiveDateTime>(
490                "2024-01-02T03:04:05.000001Z",
491                &Type::TIMESTAMP
492            ),
493            Ok(naive("2024-01-02T03:04:05.000001"))
494        );
495        // Any other offset is converted to UTC first.
496        assert_eq!(
497            scalar_roundtrip::<::chrono::NaiveDateTime>(
498                "2024-01-02T03:04:05+02:00",
499                &Type::TIMESTAMP
500            ),
501            Ok(naive("2024-01-02T01:04:05"))
502        );
503        let err =
504            scalar_roundtrip::<::chrono::NaiveDateTime>("yesterday", &Type::TIMESTAMP).unwrap_err();
505        assert!(err.contains("TIMESTAMP"), "{err}");
506    }
507
508    #[test]
509    fn timestamp_lowering_of_datetime_utc_binds() {
510        use prax_query::filter::ToFilterValue;
511        let at = ::chrono::DateTime::parse_from_rfc3339("2026-11-16T18:08:52.477200Z")
512            .unwrap()
513            .with_timezone(&::chrono::Utc);
514        let FilterValue::String(s) = at.to_filter_value() else {
515            panic!("DateTime<Utc> lowers to a string");
516        };
517        assert_eq!(
518            scalar_roundtrip::<::chrono::NaiveDateTime>(&s, &Type::TIMESTAMP),
519            Ok(at.naive_utc())
520        );
521    }
522
523    #[test]
524    fn timestamptz_binding_is_unchanged() {
525        let at = ::chrono::DateTime::parse_from_rfc3339("2024-01-02T03:04:05+02:00")
526            .unwrap()
527            .with_timezone(&::chrono::Utc);
528        assert_eq!(
529            scalar_roundtrip::<::chrono::DateTime<::chrono::Utc>>(
530                "2024-01-02T03:04:05+02:00",
531                &Type::TIMESTAMPTZ
532            ),
533            Ok(at)
534        );
535        // A naive string is still not a valid TIMESTAMPTZ value.
536        assert!(
537            scalar_roundtrip::<::chrono::DateTime<::chrono::Utc>>(
538                "2024-01-02T03:04:05",
539                &Type::TIMESTAMPTZ
540            )
541            .is_err()
542        );
543    }
544
545    #[test]
546    fn timestamp_array_elements_accept_offset_datetimes() {
547        assert_roundtrip(
548            FilterValue::String("2024-01-02T03:04:05Z".into()),
549            &Type::TIMESTAMP_ARRAY,
550            naive("2024-01-02T03:04:05"),
551        );
552    }
553
554    #[test]
555    fn array_matching_element_kinds_bind() {
556        assert_roundtrip(FilterValue::Bool(true), &Type::BOOL_ARRAY, true);
557        assert_roundtrip(FilterValue::Float(1.5), &Type::FLOAT8_ARRAY, 1.5f64);
558        assert_roundtrip(
559            FilterValue::Bytes(vec![1, 2]),
560            &Type::BYTEA_ARRAY,
561            vec![1u8, 2],
562        );
563        assert_roundtrip(
564            FilterValue::Json(serde_json::json!({"a": 1})),
565            &Type::JSONB_ARRAY,
566            serde_json::json!({"a": 1}),
567        );
568        assert_roundtrip(
569            FilterValue::String("x".into()),
570            &Type::TEXT_ARRAY,
571            "x".to_string(),
572        );
573        assert_roundtrip(FilterValue::Int(7), &Type::INT8_ARRAY, 7i64);
574    }
575
576    #[test]
577    fn string_array_elements_adapt_to_element_type() {
578        let uuid = "67e55044-10b1-426f-9247-bb680e5fe0c8";
579        assert_roundtrip(
580            FilterValue::String(uuid.into()),
581            &Type::UUID_ARRAY,
582            ::uuid::Uuid::from_str(uuid).unwrap(),
583        );
584        assert_roundtrip(
585            FilterValue::String("2024-01-02T03:04:05Z".into()),
586            &Type::TIMESTAMPTZ_ARRAY,
587            ::chrono::DateTime::parse_from_rfc3339("2024-01-02T03:04:05Z")
588                .unwrap()
589                .with_timezone(&::chrono::Utc),
590        );
591        assert_roundtrip(
592            FilterValue::String("2024-01-02T03:04:05.5".into()),
593            &Type::TIMESTAMP_ARRAY,
594            ::chrono::NaiveDateTime::parse_from_str(
595                "2024-01-02T03:04:05.5",
596                "%Y-%m-%dT%H:%M:%S%.f",
597            )
598            .unwrap(),
599        );
600        assert_roundtrip(
601            FilterValue::String("2024-01-02".into()),
602            &Type::DATE_ARRAY,
603            ::chrono::NaiveDate::from_ymd_opt(2024, 1, 2).unwrap(),
604        );
605        assert_roundtrip(
606            FilterValue::String("03:04:05".into()),
607            &Type::TIME_ARRAY,
608            ::chrono::NaiveTime::from_hms_opt(3, 4, 5).unwrap(),
609        );
610    }
611
612    #[test]
613    fn enum_array_binds_string_elements_verbatim() {
614        let mood = Type::new(
615            "mood".into(),
616            990_001,
617            Kind::Enum(vec!["happy".into(), "sad".into()]),
618            "public".into(),
619        );
620        let mood_array = Type::new("_mood".into(), 990_002, Kind::Array(mood), "public".into());
621        let (res, buf) = bind_array(vec![FilterValue::String("happy".into())], &mood_array);
622        res.unwrap();
623        // ndim=1, has_null=0, elem oid, dim len 1, lbound 1, elem len 5, body.
624        let mut expected = Vec::new();
625        for v in [1i32, 0, 990_001, 1, 1, 5] {
626            expected.extend_from_slice(&v.to_be_bytes());
627        }
628        expected.extend_from_slice(b"happy");
629        assert_eq!(&buf[..], &expected[..]);
630    }
631
632    #[test]
633    fn string_array_invalid_values_error() {
634        let cases = [
635            ("not-a-uuid", Type::UUID_ARRAY),
636            ("2024-13-45", Type::DATE_ARRAY),
637            ("nope", Type::DATE_ARRAY),
638            ("25:61:61", Type::TIME_ARRAY),
639            ("2024-01-02", Type::TIMESTAMPTZ_ARRAY),
640            ("garbage", Type::TIMESTAMP_ARRAY),
641        ];
642        for (s, ty) in cases {
643            let (res, _) = bind_array(vec![FilterValue::String(s.into())], &ty);
644            assert!(res.is_err(), "{s:?} into {ty:?} must error");
645        }
646    }
647
648    #[test]
649    fn list_bind_error_points_to_alternatives() {
650        let err = filter_value_to_sql(&FilterValue::List(vec![]))
651            .err()
652            .unwrap();
653        let msg = err.to_string();
654        assert!(
655            msg.contains("Filter::In") && msg.contains("ANY($1)"),
656            "{msg}"
657        );
658    }
659
660    #[test]
661    fn test_filter_value_to_sql() {
662        let result = filter_value_to_sql(&FilterValue::Int(42));
663        assert!(result.is_ok());
664
665        let result = filter_value_to_sql(&FilterValue::String("test".to_string()));
666        assert!(result.is_ok());
667
668        let result = filter_value_to_sql(&FilterValue::Bool(true));
669        assert!(result.is_ok());
670    }
671
672    #[test]
673    fn string_array_binds_as_a_text_array() {
674        // What `Vec<String>` (a `String[]` field) lowers to.
675        let array = FilterValue::Array(vec![
676            FilterValue::String("read".into()),
677            FilterValue::String("write".into()),
678        ]);
679        let param = filter_value_to_sql(&array).expect("string array binds");
680        let mut buf = bytes::BytesMut::new();
681        let encoded = param
682            .to_sql_checked(&Type::TEXT_ARRAY, &mut buf)
683            .expect("encodes as TEXT[]");
684        assert!(matches!(encoded, IsNull::No));
685        assert!(
686            param
687                .to_sql_checked(&Type::VARCHAR_ARRAY, &mut bytes::BytesMut::new())
688                .is_ok()
689        );
690        // A text array never satisfies a scalar column.
691        assert!(
692            param
693                .to_sql_checked(&Type::TEXT, &mut bytes::BytesMut::new())
694                .is_err()
695        );
696    }
697
698    #[test]
699    fn empty_array_binds_as_an_empty_text_array() {
700        let param = filter_value_to_sql(&FilterValue::Array(vec![])).expect("empty array binds");
701        assert!(
702            param
703                .to_sql_checked(&Type::TEXT_ARRAY, &mut bytes::BytesMut::new())
704                .is_ok()
705        );
706    }
707
708    #[test]
709    fn string_list_is_rejected_in_favour_of_array() {
710        let list = FilterValue::List(vec![FilterValue::String("read".into())]);
711        assert!(filter_value_to_sql(&list).is_err());
712    }
713
714    #[test]
715    fn test_pg_type_mapping() {
716        use pg_types::*;
717
718        assert_eq!(rust_type_to_pg("i32"), Some(Type::INT4));
719        assert_eq!(rust_type_to_pg("String"), Some(Type::TEXT));
720        assert_eq!(rust_type_to_pg("bool"), Some(Type::BOOL));
721
722        assert_eq!(pg_type_to_rust(&Type::INT4), "i32");
723        assert_eq!(pg_type_to_rust(&Type::TEXT), "String");
724    }
725}