Skip to main content

giong_postgres/
types.rs

1//! Converting between Rust values and PostgreSQL values.
2//!
3//! | Rust | PostgreSQL |
4//! |---|---|
5//! | `bool` | `boolean` |
6//! | `i16`, `i32`, `i64` | `smallint`, `integer`, `bigint` (any of them, checked for range); `oid` |
7//! | `f32`, `f64` | `real`, `double precision` |
8//! | `&str`, `String` | `text`, `varchar`, `char(n)`, `name`; as parameters, any type the server can parse from text (`uuid`, `numeric`, `date`, `json`...); as results, any column this table does not list |
9//! | `&[u8]`, `Vec<u8>` | `bytea` |
10//! | `SystemTime` | `timestamptz` |
11//! | `Option<T>` | `NULL` or a value |
12//!
13//! Integers convert between the three integer types when the value fits, and
14//! fail with an error naming the parameter or column when it does not, so a
15//! conversion never loses anything silently.
16
17use std::time::{Duration, SystemTime, UNIX_EPOCH};
18
19use crate::error::Error;
20pub use crate::protocol::Encoded;
21
22/// A PostgreSQL type, identified by its OID.
23#[derive(Clone, Copy, PartialEq, Eq, Hash)]
24pub struct Type(u32);
25
26macro_rules! types {
27    ($($(#[$doc:meta])* $name:ident = $oid:expr, $sql:expr;)*) => {
28        impl Type {
29            $($(#[$doc])* pub const $name: Type = Type($oid);)*
30
31            /// The type's name in SQL, for the built-in types this crate knows.
32            pub fn name(self) -> Option<&'static str> {
33                match self.0 {
34                    $($oid => Some($sql),)*
35                    _ => None,
36                }
37            }
38        }
39    };
40}
41
42types! {
43    /// `boolean`
44    BOOL = 16, "boolean";
45    /// `bytea`
46    BYTEA = 17, "bytea";
47    /// `"char"`, the one-byte internal type
48    CHAR = 18, "\"char\"";
49    /// `name`
50    NAME = 19, "name";
51    /// `bigint`
52    INT8 = 20, "bigint";
53    /// `smallint`
54    INT2 = 21, "smallint";
55    /// `integer`
56    INT4 = 23, "integer";
57    /// `text`
58    TEXT = 25, "text";
59    /// `oid`
60    OID = 26, "oid";
61    /// `json`
62    JSON = 114, "json";
63    /// `real`
64    FLOAT4 = 700, "real";
65    /// `double precision`
66    FLOAT8 = 701, "double precision";
67    /// `unknown`, the type of an untyped literal
68    UNKNOWN = 705, "unknown";
69    /// `character(n)`
70    BPCHAR = 1042, "character";
71    /// `character varying`
72    VARCHAR = 1043, "character varying";
73    /// `date`
74    DATE = 1082, "date";
75    /// `time`
76    TIME = 1083, "time";
77    /// `timestamp` (without time zone)
78    TIMESTAMP = 1114, "timestamp";
79    /// `timestamptz`
80    TIMESTAMPTZ = 1184, "timestamptz";
81    /// `interval`
82    INTERVAL = 1186, "interval";
83    /// `numeric`
84    NUMERIC = 1700, "numeric";
85    /// `uuid`
86    UUID = 2950, "uuid";
87    /// `jsonb`
88    JSONB = 3802, "jsonb";
89}
90
91impl Type {
92    /// The type with this OID.
93    pub fn from_oid(oid: u32) -> Self {
94        Type(oid)
95    }
96
97    /// The OID.
98    pub fn oid(self) -> u32 {
99        self.0
100    }
101
102    /// Whether the text and binary forms of this type are the same UTF-8
103    /// bytes.
104    fn is_text(self) -> bool {
105        matches!(
106            self,
107            Type::TEXT | Type::VARCHAR | Type::BPCHAR | Type::NAME | Type::UNKNOWN
108        )
109    }
110
111    /// Whether results of this type are asked for in binary. The rest come as
112    /// text, so that any column can be read as a string.
113    pub(crate) fn binary_result(self) -> bool {
114        matches!(
115            self,
116            Type::BOOL
117                | Type::BYTEA
118                | Type::INT2
119                | Type::INT4
120                | Type::INT8
121                | Type::OID
122                | Type::FLOAT4
123                | Type::FLOAT8
124                | Type::TIMESTAMPTZ
125        )
126    }
127}
128
129impl std::fmt::Display for Type {
130    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
131        match self.name() {
132            Some(name) => f.write_str(name),
133            None => write!(f, "type with OID {}", self.0),
134        }
135    }
136}
137
138impl std::fmt::Debug for Type {
139    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
140        write!(f, "Type({self})")
141    }
142}
143
144/// The format a value arrived in.
145///
146/// These are the only two formats of PostgreSQL's protocol, so the enum is
147/// complete: a `match` on it needs no wildcard arm.
148#[derive(Clone, Copy, Debug, PartialEq, Eq)]
149pub enum Format {
150    /// Text, as `psql` shows it.
151    Text,
152    /// PostgreSQL's binary format for the type.
153    Binary,
154}
155
156// ----------------------------------------------------------------- ToSql
157
158/// A Rust value that can be a statement parameter.
159///
160/// The server says which type each parameter has (from the SQL, as if the
161/// parameter were an untyped literal); `to_sql` appends the value in that
162/// type's binary format or as text, and says which. Implement it for your own
163/// types by delegating to one of the implementations here.
164pub trait ToSql {
165    /// Appends the value for a parameter of type `ty` to `out`.
166    ///
167    /// Return an error made with [`Error::conversion`] when the value cannot
168    /// be a `ty`; it is reported with the parameter's number.
169    fn to_sql(&self, ty: Type, out: &mut Vec<u8>) -> Result<Encoded, Error>;
170}
171
172fn wrong_param(rust: &str, ty: Type, instead: &str) -> Error {
173    Error::conversion(format!("a {rust} cannot be a {ty}{instead}"))
174}
175
176/// What to pass instead for a parameter of type `ty`.
177fn suggestion(ty: Type) -> &'static str {
178    match ty {
179        Type::BOOL => "; pass a bool",
180        Type::INT2 | Type::INT4 | Type::INT8 | Type::OID => "; pass an i16, i32 or i64",
181        Type::FLOAT4 => "; pass an f32",
182        Type::FLOAT8 => "; pass an f64 or f32",
183        Type::BYTEA => "; pass a &[u8] or Vec<u8>",
184        Type::TIMESTAMPTZ => "; pass a SystemTime or a string such as \"2026-01-31 12:00:00+00\"",
185        t if t.is_text() => "; pass a &str or String",
186        _ => "; pass the value as a &str in the type's text form, or cast the parameter in SQL",
187    }
188}
189
190fn put_int(v: i64, rust: &str, ty: Type, out: &mut Vec<u8>) -> Result<Encoded, Error> {
191    let range = |name: &str| {
192        Error::conversion(format!(
193            "{v} does not fit in a {name}; change the column type or pass a smaller value"
194        ))
195    };
196    match ty {
197        Type::INT2 => {
198            let v = i16::try_from(v).map_err(|_| range("smallint"))?;
199            out.extend_from_slice(&v.to_be_bytes());
200        }
201        Type::INT4 => {
202            let v = i32::try_from(v).map_err(|_| range("integer"))?;
203            out.extend_from_slice(&v.to_be_bytes());
204        }
205        Type::INT8 => out.extend_from_slice(&v.to_be_bytes()),
206        Type::OID => {
207            let v = u32::try_from(v).map_err(|_| range("oid"))?;
208            out.extend_from_slice(&v.to_be_bytes());
209        }
210        // Exact in text; the server rounds for the float types as it would a
211        // literal.
212        Type::NUMERIC | Type::FLOAT4 | Type::FLOAT8 => {
213            out.extend_from_slice(v.to_string().as_bytes());
214            return Ok(Encoded::Text);
215        }
216        _ => return Err(wrong_param(rust, ty, suggestion(ty))),
217    }
218    Ok(Encoded::Binary)
219}
220
221macro_rules! int_to_sql {
222    ($($t:ty),*) => {$(
223        impl ToSql for $t {
224            fn to_sql(&self, ty: Type, out: &mut Vec<u8>) -> Result<Encoded, Error> {
225                put_int(i64::from(*self), stringify!($t), ty, out)
226            }
227        }
228    )*};
229}
230
231int_to_sql!(i16, i32, i64);
232
233impl ToSql for f64 {
234    fn to_sql(&self, ty: Type, out: &mut Vec<u8>) -> Result<Encoded, Error> {
235        match ty {
236            Type::FLOAT8 => out.extend_from_slice(&self.to_bits().to_be_bytes()),
237            Type::FLOAT4 => {
238                let narrow = *self as f32;
239                if f64::from(narrow) != *self && !self.is_nan() {
240                    return Err(Error::conversion(format!(
241                        "{self} cannot be stored in a real without losing precision; \
242                         pass an f32, or make the column double precision"
243                    )));
244                }
245                out.extend_from_slice(&narrow.to_bits().to_be_bytes());
246            }
247            Type::NUMERIC => return put_float_text(*self, out),
248            _ => return Err(wrong_param("f64", ty, suggestion(ty))),
249        }
250        Ok(Encoded::Binary)
251    }
252}
253
254impl ToSql for f32 {
255    fn to_sql(&self, ty: Type, out: &mut Vec<u8>) -> Result<Encoded, Error> {
256        match ty {
257            Type::FLOAT4 => out.extend_from_slice(&self.to_bits().to_be_bytes()),
258            Type::FLOAT8 => out.extend_from_slice(&f64::from(*self).to_bits().to_be_bytes()),
259            Type::NUMERIC => return put_float_text(f64::from(*self), out),
260            _ => return Err(wrong_param("f32", ty, suggestion(ty))),
261        }
262        Ok(Encoded::Binary)
263    }
264}
265
266/// A float as `numeric` text; Rust prints the shortest form that reads back
267/// as the same float.
268fn put_float_text(v: f64, out: &mut Vec<u8>) -> Result<Encoded, Error> {
269    let text = if v.is_nan() {
270        "NaN".to_owned()
271    } else if v.is_infinite() {
272        if v > 0.0 { "Infinity" } else { "-Infinity" }.to_owned()
273    } else {
274        v.to_string()
275    };
276    out.extend_from_slice(text.as_bytes());
277    Ok(Encoded::Text)
278}
279
280impl ToSql for bool {
281    fn to_sql(&self, ty: Type, out: &mut Vec<u8>) -> Result<Encoded, Error> {
282        if ty != Type::BOOL {
283            return Err(wrong_param("bool", ty, suggestion(ty)));
284        }
285        out.push(*self as u8);
286        Ok(Encoded::Binary)
287    }
288}
289
290impl ToSql for str {
291    fn to_sql(&self, ty: Type, out: &mut Vec<u8>) -> Result<Encoded, Error> {
292        if ty == Type::BYTEA {
293            return Err(wrong_param("string", ty, "; pass a &[u8] or Vec<u8>"));
294        }
295        crate::protocol::check_text("a string parameter", self)?;
296        out.extend_from_slice(self.as_bytes());
297        // For text types both forms are the same bytes; for the others the
298        // server parses the text as it would a literal.
299        Ok(if ty.is_text() {
300            Encoded::Binary
301        } else {
302            Encoded::Text
303        })
304    }
305}
306
307impl ToSql for String {
308    fn to_sql(&self, ty: Type, out: &mut Vec<u8>) -> Result<Encoded, Error> {
309        self.as_str().to_sql(ty, out)
310    }
311}
312
313impl ToSql for [u8] {
314    fn to_sql(&self, ty: Type, out: &mut Vec<u8>) -> Result<Encoded, Error> {
315        if ty != Type::BYTEA {
316            return Err(wrong_param("byte slice", ty, suggestion(ty)));
317        }
318        out.extend_from_slice(self);
319        Ok(Encoded::Binary)
320    }
321}
322
323impl ToSql for Vec<u8> {
324    fn to_sql(&self, ty: Type, out: &mut Vec<u8>) -> Result<Encoded, Error> {
325        self.as_slice().to_sql(ty, out)
326    }
327}
328
329impl<const N: usize> ToSql for [u8; N] {
330    fn to_sql(&self, ty: Type, out: &mut Vec<u8>) -> Result<Encoded, Error> {
331        self.as_slice().to_sql(ty, out)
332    }
333}
334
335/// Microseconds between the Unix epoch and PostgreSQL's, 2000-01-01 UTC.
336const PG_EPOCH_MICROS: i64 = 946_684_800_000_000;
337
338impl ToSql for SystemTime {
339    fn to_sql(&self, ty: Type, out: &mut Vec<u8>) -> Result<Encoded, Error> {
340        if ty != Type::TIMESTAMPTZ {
341            let instead = if ty == Type::TIMESTAMP {
342                "; a timestamp without time zone has no fixed moment: make the column \
343                 timestamptz, or pass the wall-clock time as a string"
344            } else {
345                suggestion(ty)
346            };
347            return Err(wrong_param("SystemTime", ty, instead));
348        }
349        let unix_micros = match self.duration_since(UNIX_EPOCH) {
350            Ok(after) => i64::try_from(after.as_micros()).ok(),
351            Err(before) => i64::try_from(before.duration().as_micros())
352                .ok()
353                .map(|m| -m),
354        };
355        let micros = unix_micros
356            .and_then(|m| m.checked_sub(PG_EPOCH_MICROS))
357            .ok_or_else(|| Error::conversion(format!("{self:?} is out of timestamptz's range")))?;
358        out.extend_from_slice(&micros.to_be_bytes());
359        Ok(Encoded::Binary)
360    }
361}
362
363impl<T: ToSql> ToSql for Option<T> {
364    fn to_sql(&self, ty: Type, out: &mut Vec<u8>) -> Result<Encoded, Error> {
365        match self {
366            Some(v) => v.to_sql(ty, out),
367            None => Ok(Encoded::Null),
368        }
369    }
370}
371
372impl<T: ToSql + ?Sized> ToSql for &T {
373    fn to_sql(&self, ty: Type, out: &mut Vec<u8>) -> Result<Encoded, Error> {
374        (**self).to_sql(ty, out)
375    }
376}
377
378impl<T: ToSql + ?Sized> ToSql for Box<T> {
379    fn to_sql(&self, ty: Type, out: &mut Vec<u8>) -> Result<Encoded, Error> {
380        (**self).to_sql(ty, out)
381    }
382}
383
384// --------------------------------------------------------------- FromSql
385
386/// A Rust value that a column can be read as, with
387/// [`Row::get`](crate::Row::get).
388///
389/// `'a` is the lifetime of the row, so that `&str` and `&[u8]` can borrow
390/// from it without copying.
391///
392/// **Which format a column arrives in** depends on its type alone, not on
393/// the Rust type it is read as: `boolean`, `bytea`, `smallint`, `integer`,
394/// `bigint`, `oid`, `real`, `double precision` and `timestamptz` come in
395/// binary, and every other type (`uuid`, `numeric`, `date`, `jsonb`, enums,
396/// arrays...) as text, as `psql` would show it. An implementation for one of
397/// those types reads the text, and should still check `format` and refuse
398/// the format it does not handle with [`Error::conversion`], rather than
399/// assume it, so that a value in another format is an error and never a
400/// wrong value.
401///
402/// This list is part of the API: within 1.x no type moves from text to
403/// binary, so an implementation written for a type that arrives as text
404/// keeps receiving text. Faster decoding for more types, when it comes,
405/// comes as new Rust types read in binary, not as a new format for these.
406///
407/// ```
408/// use giong_postgres::types::Format;
409/// use giong_postgres::{Error, FromSql, Type};
410///
411/// /// A `uuid` column, kept as its text.
412/// struct Uuid(String);
413///
414/// impl<'a> FromSql<'a> for Uuid {
415///     fn from_sql(ty: Type, format: Format, raw: &'a [u8]) -> Result<Self, Error> {
416///         if ty != Type::UUID || format != Format::Text {
417///             return Err(Error::conversion(format!("expected uuid as text, got {ty} as {format:?}")));
418///         }
419///         let text = std::str::from_utf8(raw).map_err(|_| Error::conversion("uuid is not UTF-8"))?;
420///         Ok(Uuid(text.to_owned()))
421///     }
422/// }
423/// ```
424pub trait FromSql<'a>: Sized {
425    /// Converts a value that is not `NULL`, of type `ty`, in `format`.
426    ///
427    /// Return an error made with [`Error::conversion`] saying why the value
428    /// cannot be converted; it is reported with the column's name.
429    fn from_sql(ty: Type, format: Format, raw: &'a [u8]) -> Result<Self, Error>;
430
431    /// Converts `NULL`. The default refuses it.
432    fn from_null(ty: Type) -> Result<Self, Error> {
433        let _ = ty;
434        Err(Error::conversion(format!(
435            "the value is NULL; read it as Option<{}>",
436            std::any::type_name::<Self>()
437        )))
438    }
439}
440
441/// What to read a column of type `ty` as.
442fn read_as(ty: Type) -> &'static str {
443    match ty {
444        Type::BOOL => "; read it as bool",
445        Type::INT2 | Type::INT4 | Type::INT8 => "; read it as i16, i32 or i64",
446        Type::OID => "; read it as i64",
447        Type::FLOAT4 => "; read it as f32 or f64",
448        Type::FLOAT8 => "; read it as f64",
449        Type::BYTEA => "; read it as Vec<u8> or &[u8]",
450        Type::TIMESTAMPTZ => "; read it as SystemTime, or cast it to text in SQL",
451        _ => "; read it as String or &str",
452    }
453}
454
455fn wrong_column<T>(ty: Type) -> Error {
456    Error::conversion(format!(
457        "a {ty} cannot be read as {}{}",
458        std::any::type_name::<T>(),
459        read_as(ty)
460    ))
461}
462
463fn fixed<const N: usize>(raw: &[u8], ty: Type) -> Result<[u8; N], Error> {
464    raw.try_into().map_err(|_| {
465        Error::conversion(format!(
466            "the server sent {} bytes for a {ty}, which has {N}",
467            raw.len()
468        ))
469    })
470}
471
472fn get_int(ty: Type, format: Format, raw: &[u8]) -> Option<Result<i64, Error>> {
473    if format != Format::Binary {
474        return None;
475    }
476    Some(match ty {
477        Type::INT2 => fixed::<2>(raw, ty).map(|b| i64::from(i16::from_be_bytes(b))),
478        Type::INT4 => fixed::<4>(raw, ty).map(|b| i64::from(i32::from_be_bytes(b))),
479        Type::INT8 => fixed::<8>(raw, ty).map(i64::from_be_bytes),
480        Type::OID => fixed::<4>(raw, ty).map(|b| i64::from(u32::from_be_bytes(b))),
481        _ => return None,
482    })
483}
484
485macro_rules! int_from_sql {
486    ($($t:ty),*) => {$(
487        impl<'a> FromSql<'a> for $t {
488            fn from_sql(ty: Type, format: Format, raw: &'a [u8]) -> Result<Self, Error> {
489                let v = get_int(ty, format, raw).ok_or_else(|| wrong_column::<$t>(ty))??;
490                <$t>::try_from(v).map_err(|_| {
491                    Error::conversion(format!(
492                        "{v} does not fit in an {}; read it as i64", stringify!($t)
493                    ))
494                })
495            }
496        }
497    )*};
498}
499
500int_from_sql!(i16, i32, i64);
501
502impl<'a> FromSql<'a> for f64 {
503    fn from_sql(ty: Type, format: Format, raw: &'a [u8]) -> Result<Self, Error> {
504        match (ty, format) {
505            (Type::FLOAT8, Format::Binary) => {
506                Ok(f64::from_bits(u64::from_be_bytes(fixed(raw, ty)?)))
507            }
508            (Type::FLOAT4, Format::Binary) => Ok(f64::from(f32::from_bits(u32::from_be_bytes(
509                fixed(raw, ty)?,
510            )))),
511            _ => Err(wrong_column::<f64>(ty)),
512        }
513    }
514}
515
516impl<'a> FromSql<'a> for f32 {
517    fn from_sql(ty: Type, format: Format, raw: &'a [u8]) -> Result<Self, Error> {
518        match (ty, format) {
519            (Type::FLOAT4, Format::Binary) => {
520                Ok(f32::from_bits(u32::from_be_bytes(fixed(raw, ty)?)))
521            }
522            (Type::FLOAT8, _) => Err(Error::conversion(
523                "a double precision cannot be read as f32 without losing precision; read it as f64",
524            )),
525            _ => Err(wrong_column::<f32>(ty)),
526        }
527    }
528}
529
530impl<'a> FromSql<'a> for bool {
531    fn from_sql(ty: Type, format: Format, raw: &'a [u8]) -> Result<Self, Error> {
532        if (ty, format) != (Type::BOOL, Format::Binary) {
533            return Err(wrong_column::<bool>(ty));
534        }
535        Ok(fixed::<1>(raw, ty)?[0] != 0)
536    }
537}
538
539impl<'a> FromSql<'a> for &'a str {
540    fn from_sql(ty: Type, format: Format, raw: &'a [u8]) -> Result<Self, Error> {
541        if format != Format::Text && !ty.is_text() {
542            return Err(wrong_column::<&str>(ty));
543        }
544        std::str::from_utf8(raw)
545            .map_err(|_| Error::conversion(format!("the {ty} value is not valid UTF-8")))
546    }
547}
548
549impl<'a> FromSql<'a> for String {
550    fn from_sql(ty: Type, format: Format, raw: &'a [u8]) -> Result<Self, Error> {
551        if format != Format::Text && !ty.is_text() {
552            return Err(wrong_column::<String>(ty));
553        }
554        <&str>::from_sql(ty, format, raw).map(str::to_owned)
555    }
556}
557
558impl<'a> FromSql<'a> for &'a [u8] {
559    fn from_sql(ty: Type, format: Format, raw: &'a [u8]) -> Result<Self, Error> {
560        if (ty, format) != (Type::BYTEA, Format::Binary) {
561            return Err(wrong_column::<&[u8]>(ty));
562        }
563        Ok(raw)
564    }
565}
566
567impl<'a> FromSql<'a> for Vec<u8> {
568    fn from_sql(ty: Type, format: Format, raw: &'a [u8]) -> Result<Self, Error> {
569        <&[u8]>::from_sql(ty, format, raw).map(<[u8]>::to_vec)
570    }
571}
572
573impl<'a> FromSql<'a> for SystemTime {
574    fn from_sql(ty: Type, format: Format, raw: &'a [u8]) -> Result<Self, Error> {
575        if (ty, format) != (Type::TIMESTAMPTZ, Format::Binary) {
576            return Err(wrong_column::<SystemTime>(ty));
577        }
578        let micros = i64::from_be_bytes(fixed(raw, ty)?);
579        if micros == i64::MAX || micros == i64::MIN {
580            return Err(Error::conversion(
581                "the timestamptz is infinity or -infinity, which SystemTime cannot hold; \
582                 read it as Option and use NULL instead, or filter it out in SQL",
583            ));
584        }
585        let unix = micros
586            .checked_add(PG_EPOCH_MICROS)
587            .ok_or_else(|| Error::conversion("the timestamptz is out of SystemTime's range"))?;
588        let t = if unix >= 0 {
589            UNIX_EPOCH.checked_add(Duration::from_micros(unix as u64))
590        } else {
591            UNIX_EPOCH.checked_sub(Duration::from_micros(unix.unsigned_abs()))
592        };
593        t.ok_or_else(|| Error::conversion("the timestamptz is out of SystemTime's range"))
594    }
595}
596
597impl<'a, T: FromSql<'a>> FromSql<'a> for Option<T> {
598    fn from_sql(ty: Type, format: Format, raw: &'a [u8]) -> Result<Self, Error> {
599        T::from_sql(ty, format, raw).map(Some)
600    }
601
602    fn from_null(_: Type) -> Result<Self, Error> {
603        Ok(None)
604    }
605}
606
607#[cfg(test)]
608mod tests {
609    use super::*;
610
611    fn enc(v: &dyn ToSql, ty: Type) -> Result<(Encoded, Vec<u8>), Error> {
612        let mut out = Vec::new();
613        v.to_sql(ty, &mut out).map(|e| (e, out))
614    }
615
616    #[test]
617    fn integers_convert_when_they_fit() {
618        assert_eq!(
619            enc(&7i64, Type::INT4).unwrap(),
620            (Encoded::Binary, vec![0, 0, 0, 7])
621        );
622        assert_eq!(enc(&7i16, Type::INT8).unwrap().1, 7i64.to_be_bytes());
623        assert_eq!(
624            enc(&7i32, Type::NUMERIC).unwrap(),
625            (Encoded::Text, b"7".to_vec())
626        );
627        let e = enc(&3_000_000_000i64, Type::INT4).unwrap_err();
628        assert!(
629            e.to_string().contains("does not fit in a integer")
630                || e.to_string().contains("does not fit in a"),
631            "{e}"
632        );
633        let e = enc(&1i32, Type::TEXT).unwrap_err();
634        assert!(e.to_string().contains("pass a &str"), "{e}");
635
636        assert_eq!(
637            i16::from_sql(Type::INT8, Format::Binary, &7i64.to_be_bytes()).unwrap(),
638            7
639        );
640        let e = i16::from_sql(Type::INT8, Format::Binary, &70_000i64.to_be_bytes()).unwrap_err();
641        assert!(e.to_string().contains("read it as i64"), "{e}");
642        assert!(i32::from_sql(Type::INT4, Format::Binary, &[0, 0, 7]).is_err());
643        assert!(i32::from_sql(Type::TEXT, Format::Text, b"7").is_err());
644    }
645
646    #[test]
647    fn floats_never_lose_precision_silently() {
648        assert!(enc(&0.5f64, Type::FLOAT4).is_ok());
649        assert!(enc(&0.1f64, Type::FLOAT4).is_err());
650        assert_eq!(enc(&0.1f64, Type::NUMERIC).unwrap().1, b"0.1");
651        assert_eq!(
652            enc(&f64::NEG_INFINITY, Type::NUMERIC).unwrap().1,
653            b"-Infinity"
654        );
655        let bits = 1.5f32.to_bits().to_be_bytes();
656        assert_eq!(
657            f64::from_sql(Type::FLOAT4, Format::Binary, &bits).unwrap(),
658            1.5
659        );
660        assert!(f32::from_sql(
661            Type::FLOAT8,
662            Format::Binary,
663            &1.5f64.to_bits().to_be_bytes()
664        )
665        .is_err());
666    }
667
668    #[test]
669    fn strings_go_as_text_to_types_the_server_parses() {
670        assert_eq!(enc(&"abc", Type::TEXT).unwrap().0, Encoded::Binary);
671        assert_eq!(
672            enc(&"6c1b0a3e-0000-4000-8000-000000000000", Type::UUID)
673                .unwrap()
674                .0,
675            Encoded::Text
676        );
677        assert!(enc(&"abc", Type::BYTEA).is_err());
678        assert!(enc(&"a\0c", Type::TEXT).is_err());
679        assert_eq!(
680            <&str>::from_sql(Type::UUID, Format::Text, b"x").unwrap(),
681            "x"
682        );
683        assert!(String::from_sql(Type::INT4, Format::Binary, &[0, 0, 0, 1]).is_err());
684        assert!(String::from_sql(Type::TEXT, Format::Text, &[0xff]).is_err());
685    }
686
687    #[test]
688    fn timestamps_round_trip() {
689        let t = UNIX_EPOCH + Duration::from_micros(1_767_225_600_123_456);
690        let (how, bytes) = enc(&t, Type::TIMESTAMPTZ).unwrap();
691        assert_eq!(how, Encoded::Binary);
692        assert_eq!(
693            SystemTime::from_sql(Type::TIMESTAMPTZ, Format::Binary, &bytes).unwrap(),
694            t
695        );
696        let before = UNIX_EPOCH - Duration::from_secs(86_400 * 365 * 40);
697        let (_, bytes) = enc(&before, Type::TIMESTAMPTZ).unwrap();
698        assert_eq!(
699            SystemTime::from_sql(Type::TIMESTAMPTZ, Format::Binary, &bytes).unwrap(),
700            before
701        );
702        // 2000-01-01 is zero.
703        let (_, bytes) = enc(
704            &(UNIX_EPOCH + Duration::from_secs(946_684_800)),
705            Type::TIMESTAMPTZ,
706        )
707        .unwrap();
708        assert_eq!(bytes, [0; 8]);
709        assert!(
710            SystemTime::from_sql(Type::TIMESTAMPTZ, Format::Binary, &i64::MAX.to_be_bytes())
711                .is_err()
712        );
713        assert!(enc(&t, Type::TIMESTAMP)
714            .unwrap_err()
715            .to_string()
716            .contains("timestamptz"));
717    }
718
719    #[test]
720    fn null_needs_an_option() {
721        assert_eq!(enc(&None::<i32>, Type::INT4).unwrap().0, Encoded::Null);
722        assert_eq!(Option::<i32>::from_null(Type::INT4).unwrap(), None);
723        let e = i32::from_null(Type::INT4).unwrap_err();
724        assert!(e.to_string().contains("Option<i32>"), "{e}");
725    }
726
727    #[test]
728    fn types_have_names() {
729        assert_eq!(Type::INT4.to_string(), "integer");
730        assert_eq!(Type::from_oid(99999).to_string(), "type with OID 99999");
731    }
732}