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/// ```
403/// use giong_postgres::types::Format;
404/// use giong_postgres::{Error, FromSql, Type};
405///
406/// /// A `uuid` column, kept as its text.
407/// struct Uuid(String);
408///
409/// impl<'a> FromSql<'a> for Uuid {
410///     fn from_sql(ty: Type, format: Format, raw: &'a [u8]) -> Result<Self, Error> {
411///         if ty != Type::UUID || format != Format::Text {
412///             return Err(Error::conversion(format!("expected uuid as text, got {ty} as {format:?}")));
413///         }
414///         let text = std::str::from_utf8(raw).map_err(|_| Error::conversion("uuid is not UTF-8"))?;
415///         Ok(Uuid(text.to_owned()))
416///     }
417/// }
418/// ```
419pub trait FromSql<'a>: Sized {
420    /// Converts a value that is not `NULL`, of type `ty`, in `format`.
421    ///
422    /// Return an error made with [`Error::conversion`] saying why the value
423    /// cannot be converted; it is reported with the column's name.
424    fn from_sql(ty: Type, format: Format, raw: &'a [u8]) -> Result<Self, Error>;
425
426    /// Converts `NULL`. The default refuses it.
427    fn from_null(ty: Type) -> Result<Self, Error> {
428        let _ = ty;
429        Err(Error::conversion(format!(
430            "the value is NULL; read it as Option<{}>",
431            std::any::type_name::<Self>()
432        )))
433    }
434}
435
436/// What to read a column of type `ty` as.
437fn read_as(ty: Type) -> &'static str {
438    match ty {
439        Type::BOOL => "; read it as bool",
440        Type::INT2 | Type::INT4 | Type::INT8 => "; read it as i16, i32 or i64",
441        Type::OID => "; read it as i64",
442        Type::FLOAT4 => "; read it as f32 or f64",
443        Type::FLOAT8 => "; read it as f64",
444        Type::BYTEA => "; read it as Vec<u8> or &[u8]",
445        Type::TIMESTAMPTZ => "; read it as SystemTime, or cast it to text in SQL",
446        _ => "; read it as String or &str",
447    }
448}
449
450fn wrong_column<T>(ty: Type) -> Error {
451    Error::conversion(format!(
452        "a {ty} cannot be read as {}{}",
453        std::any::type_name::<T>(),
454        read_as(ty)
455    ))
456}
457
458fn fixed<const N: usize>(raw: &[u8], ty: Type) -> Result<[u8; N], Error> {
459    raw.try_into().map_err(|_| {
460        Error::conversion(format!(
461            "the server sent {} bytes for a {ty}, which has {N}",
462            raw.len()
463        ))
464    })
465}
466
467fn get_int(ty: Type, format: Format, raw: &[u8]) -> Option<Result<i64, Error>> {
468    if format != Format::Binary {
469        return None;
470    }
471    Some(match ty {
472        Type::INT2 => fixed::<2>(raw, ty).map(|b| i64::from(i16::from_be_bytes(b))),
473        Type::INT4 => fixed::<4>(raw, ty).map(|b| i64::from(i32::from_be_bytes(b))),
474        Type::INT8 => fixed::<8>(raw, ty).map(i64::from_be_bytes),
475        Type::OID => fixed::<4>(raw, ty).map(|b| i64::from(u32::from_be_bytes(b))),
476        _ => return None,
477    })
478}
479
480macro_rules! int_from_sql {
481    ($($t:ty),*) => {$(
482        impl<'a> FromSql<'a> for $t {
483            fn from_sql(ty: Type, format: Format, raw: &'a [u8]) -> Result<Self, Error> {
484                let v = get_int(ty, format, raw).ok_or_else(|| wrong_column::<$t>(ty))??;
485                <$t>::try_from(v).map_err(|_| {
486                    Error::conversion(format!(
487                        "{v} does not fit in an {}; read it as i64", stringify!($t)
488                    ))
489                })
490            }
491        }
492    )*};
493}
494
495int_from_sql!(i16, i32, i64);
496
497impl<'a> FromSql<'a> for f64 {
498    fn from_sql(ty: Type, format: Format, raw: &'a [u8]) -> Result<Self, Error> {
499        match (ty, format) {
500            (Type::FLOAT8, Format::Binary) => {
501                Ok(f64::from_bits(u64::from_be_bytes(fixed(raw, ty)?)))
502            }
503            (Type::FLOAT4, Format::Binary) => Ok(f64::from(f32::from_bits(u32::from_be_bytes(
504                fixed(raw, ty)?,
505            )))),
506            _ => Err(wrong_column::<f64>(ty)),
507        }
508    }
509}
510
511impl<'a> FromSql<'a> for f32 {
512    fn from_sql(ty: Type, format: Format, raw: &'a [u8]) -> Result<Self, Error> {
513        match (ty, format) {
514            (Type::FLOAT4, Format::Binary) => {
515                Ok(f32::from_bits(u32::from_be_bytes(fixed(raw, ty)?)))
516            }
517            (Type::FLOAT8, _) => Err(Error::conversion(
518                "a double precision cannot be read as f32 without losing precision; read it as f64",
519            )),
520            _ => Err(wrong_column::<f32>(ty)),
521        }
522    }
523}
524
525impl<'a> FromSql<'a> for bool {
526    fn from_sql(ty: Type, format: Format, raw: &'a [u8]) -> Result<Self, Error> {
527        if (ty, format) != (Type::BOOL, Format::Binary) {
528            return Err(wrong_column::<bool>(ty));
529        }
530        Ok(fixed::<1>(raw, ty)?[0] != 0)
531    }
532}
533
534impl<'a> FromSql<'a> for &'a str {
535    fn from_sql(ty: Type, format: Format, raw: &'a [u8]) -> Result<Self, Error> {
536        if format != Format::Text && !ty.is_text() {
537            return Err(wrong_column::<&str>(ty));
538        }
539        std::str::from_utf8(raw)
540            .map_err(|_| Error::conversion(format!("the {ty} value is not valid UTF-8")))
541    }
542}
543
544impl<'a> FromSql<'a> for String {
545    fn from_sql(ty: Type, format: Format, raw: &'a [u8]) -> Result<Self, Error> {
546        if format != Format::Text && !ty.is_text() {
547            return Err(wrong_column::<String>(ty));
548        }
549        <&str>::from_sql(ty, format, raw).map(str::to_owned)
550    }
551}
552
553impl<'a> FromSql<'a> for &'a [u8] {
554    fn from_sql(ty: Type, format: Format, raw: &'a [u8]) -> Result<Self, Error> {
555        if (ty, format) != (Type::BYTEA, Format::Binary) {
556            return Err(wrong_column::<&[u8]>(ty));
557        }
558        Ok(raw)
559    }
560}
561
562impl<'a> FromSql<'a> for Vec<u8> {
563    fn from_sql(ty: Type, format: Format, raw: &'a [u8]) -> Result<Self, Error> {
564        <&[u8]>::from_sql(ty, format, raw).map(<[u8]>::to_vec)
565    }
566}
567
568impl<'a> FromSql<'a> for SystemTime {
569    fn from_sql(ty: Type, format: Format, raw: &'a [u8]) -> Result<Self, Error> {
570        if (ty, format) != (Type::TIMESTAMPTZ, Format::Binary) {
571            return Err(wrong_column::<SystemTime>(ty));
572        }
573        let micros = i64::from_be_bytes(fixed(raw, ty)?);
574        if micros == i64::MAX || micros == i64::MIN {
575            return Err(Error::conversion(
576                "the timestamptz is infinity or -infinity, which SystemTime cannot hold; \
577                 read it as Option and use NULL instead, or filter it out in SQL",
578            ));
579        }
580        let unix = micros
581            .checked_add(PG_EPOCH_MICROS)
582            .ok_or_else(|| Error::conversion("the timestamptz is out of SystemTime's range"))?;
583        let t = if unix >= 0 {
584            UNIX_EPOCH.checked_add(Duration::from_micros(unix as u64))
585        } else {
586            UNIX_EPOCH.checked_sub(Duration::from_micros(unix.unsigned_abs()))
587        };
588        t.ok_or_else(|| Error::conversion("the timestamptz is out of SystemTime's range"))
589    }
590}
591
592impl<'a, T: FromSql<'a>> FromSql<'a> for Option<T> {
593    fn from_sql(ty: Type, format: Format, raw: &'a [u8]) -> Result<Self, Error> {
594        T::from_sql(ty, format, raw).map(Some)
595    }
596
597    fn from_null(_: Type) -> Result<Self, Error> {
598        Ok(None)
599    }
600}
601
602#[cfg(test)]
603mod tests {
604    use super::*;
605
606    fn enc(v: &dyn ToSql, ty: Type) -> Result<(Encoded, Vec<u8>), Error> {
607        let mut out = Vec::new();
608        v.to_sql(ty, &mut out).map(|e| (e, out))
609    }
610
611    #[test]
612    fn integers_convert_when_they_fit() {
613        assert_eq!(
614            enc(&7i64, Type::INT4).unwrap(),
615            (Encoded::Binary, vec![0, 0, 0, 7])
616        );
617        assert_eq!(enc(&7i16, Type::INT8).unwrap().1, 7i64.to_be_bytes());
618        assert_eq!(
619            enc(&7i32, Type::NUMERIC).unwrap(),
620            (Encoded::Text, b"7".to_vec())
621        );
622        let e = enc(&3_000_000_000i64, Type::INT4).unwrap_err();
623        assert!(
624            e.to_string().contains("does not fit in a integer")
625                || e.to_string().contains("does not fit in a"),
626            "{e}"
627        );
628        let e = enc(&1i32, Type::TEXT).unwrap_err();
629        assert!(e.to_string().contains("pass a &str"), "{e}");
630
631        assert_eq!(
632            i16::from_sql(Type::INT8, Format::Binary, &7i64.to_be_bytes()).unwrap(),
633            7
634        );
635        let e = i16::from_sql(Type::INT8, Format::Binary, &70_000i64.to_be_bytes()).unwrap_err();
636        assert!(e.to_string().contains("read it as i64"), "{e}");
637        assert!(i32::from_sql(Type::INT4, Format::Binary, &[0, 0, 7]).is_err());
638        assert!(i32::from_sql(Type::TEXT, Format::Text, b"7").is_err());
639    }
640
641    #[test]
642    fn floats_never_lose_precision_silently() {
643        assert!(enc(&0.5f64, Type::FLOAT4).is_ok());
644        assert!(enc(&0.1f64, Type::FLOAT4).is_err());
645        assert_eq!(enc(&0.1f64, Type::NUMERIC).unwrap().1, b"0.1");
646        assert_eq!(
647            enc(&f64::NEG_INFINITY, Type::NUMERIC).unwrap().1,
648            b"-Infinity"
649        );
650        let bits = 1.5f32.to_bits().to_be_bytes();
651        assert_eq!(
652            f64::from_sql(Type::FLOAT4, Format::Binary, &bits).unwrap(),
653            1.5
654        );
655        assert!(f32::from_sql(
656            Type::FLOAT8,
657            Format::Binary,
658            &1.5f64.to_bits().to_be_bytes()
659        )
660        .is_err());
661    }
662
663    #[test]
664    fn strings_go_as_text_to_types_the_server_parses() {
665        assert_eq!(enc(&"abc", Type::TEXT).unwrap().0, Encoded::Binary);
666        assert_eq!(
667            enc(&"6c1b0a3e-0000-4000-8000-000000000000", Type::UUID)
668                .unwrap()
669                .0,
670            Encoded::Text
671        );
672        assert!(enc(&"abc", Type::BYTEA).is_err());
673        assert!(enc(&"a\0c", Type::TEXT).is_err());
674        assert_eq!(
675            <&str>::from_sql(Type::UUID, Format::Text, b"x").unwrap(),
676            "x"
677        );
678        assert!(String::from_sql(Type::INT4, Format::Binary, &[0, 0, 0, 1]).is_err());
679        assert!(String::from_sql(Type::TEXT, Format::Text, &[0xff]).is_err());
680    }
681
682    #[test]
683    fn timestamps_round_trip() {
684        let t = UNIX_EPOCH + Duration::from_micros(1_767_225_600_123_456);
685        let (how, bytes) = enc(&t, Type::TIMESTAMPTZ).unwrap();
686        assert_eq!(how, Encoded::Binary);
687        assert_eq!(
688            SystemTime::from_sql(Type::TIMESTAMPTZ, Format::Binary, &bytes).unwrap(),
689            t
690        );
691        let before = UNIX_EPOCH - Duration::from_secs(86_400 * 365 * 40);
692        let (_, bytes) = enc(&before, Type::TIMESTAMPTZ).unwrap();
693        assert_eq!(
694            SystemTime::from_sql(Type::TIMESTAMPTZ, Format::Binary, &bytes).unwrap(),
695            before
696        );
697        // 2000-01-01 is zero.
698        let (_, bytes) = enc(
699            &(UNIX_EPOCH + Duration::from_secs(946_684_800)),
700            Type::TIMESTAMPTZ,
701        )
702        .unwrap();
703        assert_eq!(bytes, [0; 8]);
704        assert!(
705            SystemTime::from_sql(Type::TIMESTAMPTZ, Format::Binary, &i64::MAX.to_be_bytes())
706                .is_err()
707        );
708        assert!(enc(&t, Type::TIMESTAMP)
709            .unwrap_err()
710            .to_string()
711            .contains("timestamptz"));
712    }
713
714    #[test]
715    fn null_needs_an_option() {
716        assert_eq!(enc(&None::<i32>, Type::INT4).unwrap().0, Encoded::Null);
717        assert_eq!(Option::<i32>::from_null(Type::INT4).unwrap(), None);
718        let e = i32::from_null(Type::INT4).unwrap_err();
719        assert!(e.to_string().contains("Option<i32>"), "{e}");
720    }
721
722    #[test]
723    fn types_have_names() {
724        assert_eq!(Type::INT4.to_string(), "integer");
725        assert_eq!(Type::from_oid(99999).to_string(), "type with OID 99999");
726    }
727}