postgres_types/
lib.rs

1//! Conversions to and from Postgres types.
2//!
3//! This crate is used by the `tokio-postgres` and `postgres` crates. You normally don't need to depend directly on it
4//! unless you want to define your own `ToSql` or `FromSql` definitions.
5//!
6//! # Derive
7//!
8//! If the `derive` cargo feature is enabled, you can derive `ToSql` and `FromSql` implementations for custom Postgres
9//! types. Explicitly, modify your `Cargo.toml` file to include the following:
10//!
11//! ```toml
12//! [dependencies]
13//! postgres-types = { version = "0.X.X", features = ["derive"] }
14//! ```
15//!
16//! ## Enums
17//!
18//! Postgres enums correspond to C-like enums in Rust:
19//!
20//! ```sql
21//! CREATE TYPE "Mood" AS ENUM (
22//!     'Sad',
23//!     'Ok',
24//!     'Happy'
25//! );
26//! ```
27//!
28//! ```rust
29//! # #[cfg(feature = "derive")]
30//! use postgres_types::{ToSql, FromSql};
31//!
32//! # #[cfg(feature = "derive")]
33//! #[derive(Debug, ToSql, FromSql)]
34//! enum Mood {
35//!     Sad,
36//!     Ok,
37//!     Happy,
38//! }
39//! ```
40//!
41//! ## Domains
42//!
43//! Postgres domains correspond to tuple structs with one member in Rust:
44//!
45//! ```sql
46//! CREATE DOMAIN "SessionId" AS BYTEA CHECK(octet_length(VALUE) = 16);
47//! ```
48//!
49//! ```rust
50//! # #[cfg(feature = "derive")]
51//! use postgres_types::{ToSql, FromSql};
52//!
53//! # #[cfg(feature = "derive")]
54//! #[derive(Debug, ToSql, FromSql)]
55//! struct SessionId(Vec<u8>);
56//! ```
57//!
58//! ## Newtypes
59//!
60//! The `#[postgres(transparent)]` attribute can be used on a single-field tuple struct to create a
61//! Rust-only wrapper type that will use the [`ToSql`] & [`FromSql`] implementation of the inner
62//! value :
63//! ```rust
64//! # #[cfg(feature = "derive")]
65//! use postgres_types::{ToSql, FromSql};
66//!
67//! # #[cfg(feature = "derive")]
68//! #[derive(Debug, ToSql, FromSql)]
69//! #[postgres(transparent)]
70//! struct UserId(i32);
71//! ```
72//!
73//! ## Composites
74//!
75//! Postgres composite types correspond to structs in Rust:
76//!
77//! ```sql
78//! CREATE TYPE "InventoryItem" AS (
79//!     name TEXT,
80//!     supplier_id INT,
81//!     price DOUBLE PRECISION
82//! );
83//! ```
84//!
85//! ```rust
86//! # #[cfg(feature = "derive")]
87//! use postgres_types::{ToSql, FromSql};
88//!
89//! # #[cfg(feature = "derive")]
90//! #[derive(Debug, ToSql, FromSql)]
91//! struct InventoryItem {
92//!     name: String,
93//!     supplier_id: i32,
94//!     price: Option<f64>,
95//! }
96//! ```
97//!
98//! ## Naming
99//!
100//! The derived implementations will enforce exact matches of type, field, and variant names between the Rust and
101//! Postgres types. The `#[postgres(name = "...")]` attribute can be used to adjust the name on a type, variant, or
102//! field:
103//!
104//! ```sql
105//! CREATE TYPE mood AS ENUM (
106//!     'sad',
107//!     'ok',
108//!     'happy'
109//! );
110//! ```
111//!
112//! ```rust
113//! # #[cfg(feature = "derive")]
114//! use postgres_types::{ToSql, FromSql};
115//!
116//! # #[cfg(feature = "derive")]
117//! #[derive(Debug, ToSql, FromSql)]
118//! #[postgres(name = "mood")]
119//! enum Mood {
120//!     #[postgres(name = "sad")]
121//!     Sad,
122//!     #[postgres(name = "ok")]
123//!     Ok,
124//!     #[postgres(name = "happy")]
125//!     Happy,
126//! }
127//! ```
128//!
129//! Alternatively, the `#[postgres(rename_all = "...")]` attribute can be used to rename all fields or variants
130//! with the chosen casing convention. This will not affect the struct or enum's type name. Note that
131//! `#[postgres(name = "...")]` takes precendence when used in conjunction with `#[postgres(rename_all = "...")]`:
132//!
133//! ```rust
134//! # #[cfg(feature = "derive")]
135//! use postgres_types::{ToSql, FromSql};
136//!
137//! # #[cfg(feature = "derive")]
138//! #[derive(Debug, ToSql, FromSql)]
139//! #[postgres(name = "mood", rename_all = "snake_case")]
140//! enum Mood {
141//!     #[postgres(name = "ok")]
142//!     Ok,             // ok
143//!     VeryHappy,      // very_happy
144//! }
145//! ```
146//!
147//! The following case conventions are supported:
148//! - `"lowercase"`
149//! - `"UPPERCASE"`
150//! - `"PascalCase"`
151//! - `"camelCase"`
152//! - `"snake_case"`
153//! - `"SCREAMING_SNAKE_CASE"`
154//! - `"kebab-case"`
155//! - `"SCREAMING-KEBAB-CASE"`
156//! - `"Train-Case"`
157//!
158//! ## Allowing Enum Mismatches
159//!
160//! By default the generated implementation of [`ToSql`] & [`FromSql`] for enums will require an exact match of the enum
161//! variants between the Rust and Postgres types.
162//! To allow mismatches, the `#[postgres(allow_mismatch)]` attribute can be used on the enum definition:
163//!
164//! ```sql
165//! CREATE TYPE mood AS ENUM (
166//!   'Sad',
167//!   'Ok',
168//!   'Happy'
169//! );
170//! ```
171//!
172//! ```rust
173//! # #[cfg(feature = "derive")]
174//! use postgres_types::{ToSql, FromSql};
175//!
176//! # #[cfg(feature = "derive")]
177//! #[derive(Debug, ToSql, FromSql)]
178//! #[postgres(allow_mismatch)]
179//! enum Mood {
180//!    Happy,
181//!    Meh,
182//! }
183//! ```
184#![warn(clippy::all, rust_2018_idioms, missing_docs)]
185use fallible_iterator::FallibleIterator;
186use postgres_protocol::types::{self, ArrayDimension};
187use std::any::type_name;
188use std::borrow::Cow;
189use std::collections::HashMap;
190use std::error::Error;
191use std::fmt;
192use std::hash::BuildHasher;
193use std::net::IpAddr;
194use std::sync::Arc;
195use std::time::{Duration, SystemTime, UNIX_EPOCH};
196
197#[cfg(feature = "derive")]
198pub use postgres_derive::{FromSql, ToSql};
199
200#[cfg(feature = "with-serde_json-1")]
201pub use crate::serde_json_1::Json;
202use crate::type_gen::{Inner, Other};
203
204#[doc(inline)]
205pub use postgres_protocol::Oid;
206
207#[doc(inline)]
208pub use pg_lsn::PgLsn;
209
210pub use crate::special::{Date, Timestamp};
211use bytes::BytesMut;
212
213// Number of seconds from 1970-01-01 to 2000-01-01
214const TIME_SEC_CONVERSION: u64 = 946_684_800;
215const USEC_PER_SEC: u64 = 1_000_000;
216const NSEC_PER_USEC: u64 = 1_000;
217
218/// Generates a simple implementation of `ToSql::accepts` which accepts the
219/// types passed to it.
220#[macro_export]
221macro_rules! accepts {
222    ($($expected:ident),+) => (
223        fn accepts(ty: &$crate::Type) -> bool {
224            matches!(*ty, $($crate::Type::$expected)|+)
225        }
226    )
227}
228
229/// Generates an implementation of `ToSql::to_sql_checked`.
230///
231/// All `ToSql` implementations should use this macro.
232#[macro_export]
233macro_rules! to_sql_checked {
234    () => {
235        fn to_sql_checked(
236            &self,
237            ty: &$crate::Type,
238            out: &mut $crate::private::BytesMut,
239        ) -> ::std::result::Result<
240            $crate::IsNull,
241            Box<dyn ::std::error::Error + ::std::marker::Sync + ::std::marker::Send>,
242        > {
243            $crate::__to_sql_checked(self, ty, out)
244        }
245    };
246}
247
248// WARNING: this function is not considered part of this crate's public API.
249// It is subject to change at any time.
250#[doc(hidden)]
251pub fn __to_sql_checked<T>(
252    v: &T,
253    ty: &Type,
254    out: &mut BytesMut,
255) -> Result<IsNull, Box<dyn Error + Sync + Send>>
256where
257    T: ToSql,
258{
259    if !T::accepts(ty) {
260        return Err(Box::new(WrongType::new::<T>(ty.clone())));
261    }
262    v.to_sql(ty, out)
263}
264
265#[cfg(feature = "with-bit-vec-0_6")]
266mod bit_vec_06;
267#[cfg(feature = "with-chrono-0_4")]
268mod chrono_04;
269#[cfg(feature = "with-cidr-0_2")]
270mod cidr_02;
271#[cfg(feature = "with-eui48-0_4")]
272mod eui48_04;
273#[cfg(feature = "with-eui48-1")]
274mod eui48_1;
275#[cfg(feature = "with-geo-types-0_6")]
276mod geo_types_06;
277#[cfg(feature = "with-geo-types-0_7")]
278mod geo_types_07;
279#[cfg(feature = "with-serde_json-1")]
280mod serde_json_1;
281#[cfg(feature = "with-smol_str-01")]
282mod smol_str_01;
283#[cfg(feature = "with-time-0_2")]
284mod time_02;
285#[cfg(feature = "with-time-0_3")]
286mod time_03;
287#[cfg(feature = "with-uuid-0_8")]
288mod uuid_08;
289#[cfg(feature = "with-uuid-1")]
290mod uuid_1;
291
292// The time::{date, time} macros produce compile errors if the crate package is renamed.
293#[cfg(feature = "with-time-0_2")]
294extern crate time_02 as time;
295
296mod pg_lsn;
297#[doc(hidden)]
298pub mod private;
299mod special;
300mod type_gen;
301
302/// A Postgres type.
303#[derive(PartialEq, Eq, Clone, Hash)]
304pub struct Type(Inner);
305
306impl fmt::Debug for Type {
307    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
308        fmt::Debug::fmt(&self.0, fmt)
309    }
310}
311
312impl fmt::Display for Type {
313    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
314        match self.schema() {
315            "public" | "pg_catalog" => {}
316            schema => write!(fmt, "{}.", schema)?,
317        }
318        fmt.write_str(self.name())
319    }
320}
321
322impl Type {
323    /// Creates a new `Type`.
324    pub fn new(name: String, oid: Oid, kind: Kind, schema: String) -> Type {
325        Type(Inner::Other(Arc::new(Other {
326            name,
327            oid,
328            kind,
329            schema,
330        })))
331    }
332
333    /// Returns the `Type` corresponding to the provided `Oid` if it
334    /// corresponds to a built-in type.
335    pub fn from_oid(oid: Oid) -> Option<Type> {
336        Inner::from_oid(oid).map(Type)
337    }
338
339    /// Returns the OID of the `Type`.
340    pub fn oid(&self) -> Oid {
341        self.0.oid()
342    }
343
344    /// Returns the kind of this type.
345    pub fn kind(&self) -> &Kind {
346        self.0.kind()
347    }
348
349    /// Returns the schema of this type.
350    pub fn schema(&self) -> &str {
351        match self.0 {
352            Inner::Other(ref u) => &u.schema,
353            _ => "pg_catalog",
354        }
355    }
356
357    /// Returns the name of this type.
358    pub fn name(&self) -> &str {
359        self.0.name()
360    }
361}
362
363/// Represents the kind of a Postgres type.
364#[derive(Debug, Clone, PartialEq, Eq, Hash)]
365#[non_exhaustive]
366pub enum Kind {
367    /// A simple type like `VARCHAR` or `INTEGER`.
368    Simple,
369    /// An enumerated type along with its variants.
370    Enum(Vec<String>),
371    /// A pseudo-type.
372    Pseudo,
373    /// An array type along with the type of its elements.
374    Array(Type),
375    /// A range type along with the type of its elements.
376    Range(Type),
377    /// A multirange type along with the type of its elements.
378    Multirange(Type),
379    /// A domain type along with its underlying type.
380    Domain(Type),
381    /// A composite type along with information about its fields.
382    Composite(Vec<Field>),
383}
384
385/// Information about a field of a composite type.
386#[derive(Debug, Clone, PartialEq, Eq, Hash)]
387pub struct Field {
388    name: String,
389    type_: Type,
390}
391
392impl Field {
393    /// Creates a new `Field`.
394    pub fn new(name: String, type_: Type) -> Field {
395        Field { name, type_ }
396    }
397
398    /// Returns the name of the field.
399    pub fn name(&self) -> &str {
400        &self.name
401    }
402
403    /// Returns the type of the field.
404    pub fn type_(&self) -> &Type {
405        &self.type_
406    }
407}
408
409/// An error indicating that a `NULL` Postgres value was passed to a `FromSql`
410/// implementation that does not support `NULL` values.
411#[derive(Debug, Clone, Copy)]
412pub struct WasNull;
413
414impl fmt::Display for WasNull {
415    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
416        fmt.write_str("a Postgres value was `NULL`")
417    }
418}
419
420impl Error for WasNull {}
421
422/// An error indicating that a conversion was attempted between incompatible
423/// Rust and Postgres types.
424#[derive(Debug)]
425pub struct WrongType {
426    postgres: Type,
427    rust: &'static str,
428}
429
430impl fmt::Display for WrongType {
431    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
432        write!(
433            fmt,
434            "cannot convert between the Rust type `{}` and the Postgres type `{}`",
435            self.rust, self.postgres,
436        )
437    }
438}
439
440impl Error for WrongType {}
441
442impl WrongType {
443    /// Creates a new `WrongType` error.
444    pub fn new<T>(ty: Type) -> WrongType {
445        WrongType {
446            postgres: ty,
447            rust: type_name::<T>(),
448        }
449    }
450}
451
452/// A trait for types that can be created from a Postgres value.
453///
454/// # Types
455///
456/// The following implementations are provided by this crate, along with the
457/// corresponding Postgres types:
458///
459/// | Rust type                         | Postgres type(s)                              |
460/// |-----------------------------------|-----------------------------------------------|
461/// | `bool`                            | BOOL                                          |
462/// | `i8`                              | "char"                                        |
463/// | `i16`                             | SMALLINT, SMALLSERIAL                         |
464/// | `i32`                             | INT, SERIAL                                   |
465/// | `u32`                             | OID                                           |
466/// | `i64`                             | BIGINT, BIGSERIAL                             |
467/// | `f32`                             | REAL                                          |
468/// | `f64`                             | DOUBLE PRECISION                              |
469/// | `&str`/`String`                   | VARCHAR, CHAR(n), TEXT, CITEXT, NAME, UNKNOWN |
470/// |                                   | LTREE, LQUERY, LTXTQUERY                      |
471/// | `&[u8]`/`Vec<u8>`                 | BYTEA                                         |
472/// | `HashMap<String, Option<String>>` | HSTORE                                        |
473/// | `SystemTime`                      | TIMESTAMP, TIMESTAMP WITH TIME ZONE           |
474/// | `IpAddr`                          | INET                                          |
475///
476/// In addition, some implementations are provided for types in third party
477/// crates. These are disabled by default; to opt into one of these
478/// implementations, activate the Cargo feature corresponding to the crate's
479/// name prefixed by `with-`. For example, the `with-serde_json-1` feature enables
480/// the implementation for the `serde_json::Value` type.
481///
482/// | Rust type                       | Postgres type(s)                    |
483/// |---------------------------------|-------------------------------------|
484/// | `chrono::NaiveDateTime`         | TIMESTAMP                           |
485/// | `chrono::DateTime<Utc>`         | TIMESTAMP WITH TIME ZONE            |
486/// | `chrono::DateTime<Local>`       | TIMESTAMP WITH TIME ZONE            |
487/// | `chrono::DateTime<FixedOffset>` | TIMESTAMP WITH TIME ZONE            |
488/// | `chrono::NaiveDate`             | DATE                                |
489/// | `chrono::NaiveTime`             | TIME                                |
490/// | `time::PrimitiveDateTime`       | TIMESTAMP                           |
491/// | `time::OffsetDateTime`          | TIMESTAMP WITH TIME ZONE            |
492/// | `time::Date`                    | DATE                                |
493/// | `time::Time`                    | TIME                                |
494/// | `eui48::MacAddress`             | MACADDR                             |
495/// | `geo_types::Point<f64>`         | POINT                               |
496/// | `geo_types::Rect<f64>`          | BOX                                 |
497/// | `geo_types::LineString<f64>`    | PATH                                |
498/// | `serde_json::Value`             | JSON, JSONB                         |
499/// | `uuid::Uuid`                    | UUID                                |
500/// | `bit_vec::BitVec`               | BIT, VARBIT                         |
501/// | `eui48::MacAddress`             | MACADDR                             |
502/// | `cidr::InetCidr`                | CIDR                                |
503/// | `cidr::InetAddr`                | INET                                |
504/// | `smol_str::SmolStr`             | VARCHAR, CHAR(n), TEXT, CITEXT,     |
505/// |                                 | NAME, UNKNOWN, LTREE, LQUERY,       |
506/// |                                 | LTXTQUERY                           |
507///
508/// # Nullability
509///
510/// In addition to the types listed above, `FromSql` is implemented for
511/// `Option<T>` where `T` implements `FromSql`. An `Option<T>` represents a
512/// nullable Postgres value.
513///
514/// # Arrays
515///
516/// `FromSql` is implemented for `Vec<T>`, `Box<[T]>` and `[T; N]` where `T`
517/// implements `FromSql`, and corresponds to one-dimensional Postgres arrays.
518///
519/// **Note:** the impl for arrays only exist when the Cargo feature `array-impls`
520/// is enabled.
521pub trait FromSql<'a>: Sized {
522    /// Creates a new value of this type from a buffer of data of the specified
523    /// Postgres `Type` in its binary format.
524    ///
525    /// The caller of this method is responsible for ensuring that this type
526    /// is compatible with the Postgres `Type`.
527    fn from_sql(ty: &Type, raw: &'a [u8]) -> Result<Self, Box<dyn Error + Sync + Send>>;
528
529    /// Creates a new value of this type from a `NULL` SQL value.
530    ///
531    /// The caller of this method is responsible for ensuring that this type
532    /// is compatible with the Postgres `Type`.
533    ///
534    /// The default implementation returns `Err(Box::new(WasNull))`.
535    #[allow(unused_variables)]
536    fn from_sql_null(ty: &Type) -> Result<Self, Box<dyn Error + Sync + Send>> {
537        Err(Box::new(WasNull))
538    }
539
540    /// A convenience function that delegates to `from_sql` and `from_sql_null` depending on the
541    /// value of `raw`.
542    fn from_sql_nullable(
543        ty: &Type,
544        raw: Option<&'a [u8]>,
545    ) -> Result<Self, Box<dyn Error + Sync + Send>> {
546        match raw {
547            Some(raw) => Self::from_sql(ty, raw),
548            None => Self::from_sql_null(ty),
549        }
550    }
551
552    /// Determines if a value of this type can be created from the specified
553    /// Postgres `Type`.
554    fn accepts(ty: &Type) -> bool;
555}
556
557/// A trait for types which can be created from a Postgres value without borrowing any data.
558///
559/// This is primarily useful for trait bounds on functions.
560pub trait FromSqlOwned: for<'a> FromSql<'a> {}
561
562impl<T> FromSqlOwned for T where T: for<'a> FromSql<'a> {}
563
564impl<'a, T: FromSql<'a>> FromSql<'a> for Option<T> {
565    fn from_sql(ty: &Type, raw: &'a [u8]) -> Result<Option<T>, Box<dyn Error + Sync + Send>> {
566        <T as FromSql>::from_sql(ty, raw).map(Some)
567    }
568
569    fn from_sql_null(_: &Type) -> Result<Option<T>, Box<dyn Error + Sync + Send>> {
570        Ok(None)
571    }
572
573    fn accepts(ty: &Type) -> bool {
574        <T as FromSql>::accepts(ty)
575    }
576}
577
578impl<'a, T: FromSql<'a>> FromSql<'a> for Vec<T> {
579    fn from_sql(ty: &Type, raw: &'a [u8]) -> Result<Vec<T>, Box<dyn Error + Sync + Send>> {
580        let member_type = match *ty.kind() {
581            Kind::Array(ref member) => member,
582            _ => panic!("expected array type"),
583        };
584
585        let array = types::array_from_sql(raw)?;
586        if array.dimensions().count()? > 1 {
587            return Err("array contains too many dimensions".into());
588        }
589
590        array
591            .values()
592            .map(|v| T::from_sql_nullable(member_type, v))
593            .collect()
594    }
595
596    fn accepts(ty: &Type) -> bool {
597        match *ty.kind() {
598            Kind::Array(ref inner) => T::accepts(inner),
599            _ => false,
600        }
601    }
602}
603
604#[cfg(feature = "array-impls")]
605impl<'a, T: FromSql<'a>, const N: usize> FromSql<'a> for [T; N] {
606    fn from_sql(ty: &Type, raw: &'a [u8]) -> Result<Self, Box<dyn Error + Sync + Send>> {
607        let member_type = match *ty.kind() {
608            Kind::Array(ref member) => member,
609            _ => panic!("expected array type"),
610        };
611
612        let array = types::array_from_sql(raw)?;
613        if array.dimensions().count()? > 1 {
614            return Err("array contains too many dimensions".into());
615        }
616
617        let mut values = array.values();
618        let out = array_init::try_array_init(|i| {
619            let v = values
620                .next()?
621                .ok_or_else(|| -> Box<dyn Error + Sync + Send> {
622                    format!("too few elements in array (expected {}, got {})", N, i).into()
623                })?;
624            T::from_sql_nullable(member_type, v)
625        })?;
626        if values.next()?.is_some() {
627            return Err(format!(
628                "excess elements in array (expected {}, got more than that)",
629                N,
630            )
631            .into());
632        }
633
634        Ok(out)
635    }
636
637    fn accepts(ty: &Type) -> bool {
638        match *ty.kind() {
639            Kind::Array(ref inner) => T::accepts(inner),
640            _ => false,
641        }
642    }
643}
644
645impl<'a, T: FromSql<'a>> FromSql<'a> for Box<[T]> {
646    fn from_sql(ty: &Type, raw: &'a [u8]) -> Result<Self, Box<dyn Error + Sync + Send>> {
647        Vec::<T>::from_sql(ty, raw).map(Vec::into_boxed_slice)
648    }
649
650    fn accepts(ty: &Type) -> bool {
651        Vec::<T>::accepts(ty)
652    }
653}
654
655impl<'a> FromSql<'a> for Vec<u8> {
656    fn from_sql(_: &Type, raw: &'a [u8]) -> Result<Vec<u8>, Box<dyn Error + Sync + Send>> {
657        Ok(types::bytea_from_sql(raw).to_owned())
658    }
659
660    accepts!(BYTEA);
661}
662
663impl<'a> FromSql<'a> for &'a [u8] {
664    fn from_sql(_: &Type, raw: &'a [u8]) -> Result<&'a [u8], Box<dyn Error + Sync + Send>> {
665        Ok(types::bytea_from_sql(raw))
666    }
667
668    accepts!(BYTEA);
669}
670
671impl<'a> FromSql<'a> for String {
672    fn from_sql(ty: &Type, raw: &'a [u8]) -> Result<String, Box<dyn Error + Sync + Send>> {
673        <&str as FromSql>::from_sql(ty, raw).map(ToString::to_string)
674    }
675
676    fn accepts(ty: &Type) -> bool {
677        <&str as FromSql>::accepts(ty)
678    }
679}
680
681impl<'a> FromSql<'a> for Box<str> {
682    fn from_sql(ty: &Type, raw: &'a [u8]) -> Result<Box<str>, Box<dyn Error + Sync + Send>> {
683        <&str as FromSql>::from_sql(ty, raw)
684            .map(ToString::to_string)
685            .map(String::into_boxed_str)
686    }
687
688    fn accepts(ty: &Type) -> bool {
689        <&str as FromSql>::accepts(ty)
690    }
691}
692
693impl<'a> FromSql<'a> for &'a str {
694    fn from_sql(ty: &Type, raw: &'a [u8]) -> Result<&'a str, Box<dyn Error + Sync + Send>> {
695        match *ty {
696            ref ty if ty.name() == "ltree" => types::ltree_from_sql(raw),
697            ref ty if ty.name() == "lquery" => types::lquery_from_sql(raw),
698            ref ty if ty.name() == "ltxtquery" => types::ltxtquery_from_sql(raw),
699            _ => types::text_from_sql(raw),
700        }
701    }
702
703    fn accepts(ty: &Type) -> bool {
704        match *ty {
705            Type::VARCHAR | Type::TEXT | Type::BPCHAR | Type::NAME | Type::UNKNOWN => true,
706            ref ty
707                if (ty.name() == "citext"
708                    || ty.name() == "ltree"
709                    || ty.name() == "lquery"
710                    || ty.name() == "ltxtquery") =>
711            {
712                true
713            }
714            _ => false,
715        }
716    }
717}
718
719macro_rules! simple_from {
720    ($t:ty, $f:ident, $($expected:ident),+) => {
721        impl<'a> FromSql<'a> for $t {
722            fn from_sql(_: &Type, raw: &'a [u8]) -> Result<$t, Box<dyn Error + Sync + Send>> {
723                types::$f(raw)
724            }
725
726            accepts!($($expected),+);
727        }
728    }
729}
730
731simple_from!(bool, bool_from_sql, BOOL);
732simple_from!(i8, char_from_sql, CHAR);
733simple_from!(i16, int2_from_sql, INT2);
734simple_from!(i32, int4_from_sql, INT4);
735simple_from!(u32, oid_from_sql, OID);
736simple_from!(i64, int8_from_sql, INT8);
737simple_from!(f32, float4_from_sql, FLOAT4);
738simple_from!(f64, float8_from_sql, FLOAT8);
739
740impl<'a, S> FromSql<'a> for HashMap<String, Option<String>, S>
741where
742    S: Default + BuildHasher,
743{
744    fn from_sql(
745        _: &Type,
746        raw: &'a [u8],
747    ) -> Result<HashMap<String, Option<String>, S>, Box<dyn Error + Sync + Send>> {
748        types::hstore_from_sql(raw)?
749            .map(|(k, v)| Ok((k.to_owned(), v.map(str::to_owned))))
750            .collect()
751    }
752
753    fn accepts(ty: &Type) -> bool {
754        ty.name() == "hstore"
755    }
756}
757
758impl<'a> FromSql<'a> for SystemTime {
759    fn from_sql(_: &Type, raw: &'a [u8]) -> Result<SystemTime, Box<dyn Error + Sync + Send>> {
760        let time = types::timestamp_from_sql(raw)?;
761        let epoch = UNIX_EPOCH + Duration::from_secs(TIME_SEC_CONVERSION);
762
763        let negative = time < 0;
764        let time = time.unsigned_abs();
765
766        let secs = time / USEC_PER_SEC;
767        let nsec = (time % USEC_PER_SEC) * NSEC_PER_USEC;
768        let offset = Duration::new(secs, nsec as u32);
769
770        let time = if negative {
771            epoch - offset
772        } else {
773            epoch + offset
774        };
775
776        Ok(time)
777    }
778
779    accepts!(TIMESTAMP, TIMESTAMPTZ);
780}
781
782impl<'a> FromSql<'a> for IpAddr {
783    fn from_sql(_: &Type, raw: &'a [u8]) -> Result<IpAddr, Box<dyn Error + Sync + Send>> {
784        let inet = types::inet_from_sql(raw)?;
785        Ok(inet.addr())
786    }
787
788    accepts!(INET);
789}
790
791/// An enum representing the nullability of a Postgres value.
792pub enum IsNull {
793    /// The value is NULL.
794    Yes,
795    /// The value is not NULL.
796    No,
797}
798
799/// A trait for types that can be converted into Postgres values.
800///
801/// # Types
802///
803/// The following implementations are provided by this crate, along with the
804/// corresponding Postgres types:
805///
806/// | Rust type                         | Postgres type(s)                     |
807/// |-----------------------------------|--------------------------------------|
808/// | `bool`                            | BOOL                                 |
809/// | `i8`                              | "char"                               |
810/// | `i16`                             | SMALLINT, SMALLSERIAL                |
811/// | `i32`                             | INT, SERIAL                          |
812/// | `u32`                             | OID                                  |
813/// | `i64`                             | BIGINT, BIGSERIAL                    |
814/// | `f32`                             | REAL                                 |
815/// | `f64`                             | DOUBLE PRECISION                     |
816/// | `&str`/`String`                   | VARCHAR, CHAR(n), TEXT, CITEXT, NAME |
817/// |                                   | LTREE, LQUERY, LTXTQUERY             |
818/// | `&[u8]`/`Vec<u8>`/`[u8; N]`       | BYTEA                                |
819/// | `HashMap<String, Option<String>>` | HSTORE                               |
820/// | `SystemTime`                      | TIMESTAMP, TIMESTAMP WITH TIME ZONE  |
821/// | `IpAddr`                          | INET                                 |
822///
823/// In addition, some implementations are provided for types in third party
824/// crates. These are disabled by default; to opt into one of these
825/// implementations, activate the Cargo feature corresponding to the crate's
826/// name prefixed by `with-`. For example, the `with-serde_json-1` feature enables
827/// the implementation for the `serde_json::Value` type.
828///
829/// | Rust type                       | Postgres type(s)                    |
830/// |---------------------------------|-------------------------------------|
831/// | `chrono::NaiveDateTime`         | TIMESTAMP                           |
832/// | `chrono::DateTime<Utc>`         | TIMESTAMP WITH TIME ZONE            |
833/// | `chrono::DateTime<Local>`       | TIMESTAMP WITH TIME ZONE            |
834/// | `chrono::DateTime<FixedOffset>` | TIMESTAMP WITH TIME ZONE            |
835/// | `chrono::NaiveDate`             | DATE                                |
836/// | `chrono::NaiveTime`             | TIME                                |
837/// | `time::PrimitiveDateTime`       | TIMESTAMP                           |
838/// | `time::OffsetDateTime`          | TIMESTAMP WITH TIME ZONE            |
839/// | `time::Date`                    | DATE                                |
840/// | `time::Time`                    | TIME                                |
841/// | `eui48::MacAddress`             | MACADDR                             |
842/// | `geo_types::Point<f64>`         | POINT                               |
843/// | `geo_types::Rect<f64>`          | BOX                                 |
844/// | `geo_types::LineString<f64>`    | PATH                                |
845/// | `serde_json::Value`             | JSON, JSONB                         |
846/// | `uuid::Uuid`                    | UUID                                |
847/// | `bit_vec::BitVec`               | BIT, VARBIT                         |
848/// | `eui48::MacAddress`             | MACADDR                             |
849///
850/// # Nullability
851///
852/// In addition to the types listed above, `ToSql` is implemented for
853/// `Option<T>` where `T` implements `ToSql`. An `Option<T>` represents a
854/// nullable Postgres value.
855///
856/// # Arrays
857///
858/// `ToSql` is implemented for `[u8; N]`, `Vec<T>`, `&[T]`, `Box<[T]>` and `[T; N]`
859/// where `T` implements `ToSql` and `N` is const usize, and corresponds to one-dimensional
860/// Postgres arrays with an index offset of 1.
861///
862/// **Note:** the impl for arrays only exist when the Cargo feature `array-impls`
863/// is enabled.
864pub trait ToSql: fmt::Debug {
865    /// Converts the value of `self` into the binary format of the specified
866    /// Postgres `Type`, appending it to `out`.
867    ///
868    /// The caller of this method is responsible for ensuring that this type
869    /// is compatible with the Postgres `Type`.
870    ///
871    /// The return value indicates if this value should be represented as
872    /// `NULL`. If this is the case, implementations **must not** write
873    /// anything to `out`.
874    fn to_sql(&self, ty: &Type, out: &mut BytesMut) -> Result<IsNull, Box<dyn Error + Sync + Send>>
875    where
876        Self: Sized;
877
878    /// Determines if a value of this type can be converted to the specified
879    /// Postgres `Type`.
880    fn accepts(ty: &Type) -> bool
881    where
882        Self: Sized;
883
884    /// An adaptor method used internally by Rust-Postgres.
885    ///
886    /// *All* implementations of this method should be generated by the
887    /// `to_sql_checked!()` macro.
888    fn to_sql_checked(
889        &self,
890        ty: &Type,
891        out: &mut BytesMut,
892    ) -> Result<IsNull, Box<dyn Error + Sync + Send>>;
893
894    /// Specify the encode format
895    fn encode_format(&self, _ty: &Type) -> Format {
896        Format::Binary
897    }
898}
899
900/// Supported Postgres message format types
901///
902/// Using Text format in a message assumes a Postgres `SERVER_ENCODING` of `UTF8`
903#[derive(Clone, Copy, Debug)]
904pub enum Format {
905    /// Text format (UTF-8)
906    Text,
907    /// Compact, typed binary format
908    Binary,
909}
910
911impl<'a, T> ToSql for &'a T
912where
913    T: ToSql,
914{
915    fn to_sql(
916        &self,
917        ty: &Type,
918        out: &mut BytesMut,
919    ) -> Result<IsNull, Box<dyn Error + Sync + Send>> {
920        (*self).to_sql(ty, out)
921    }
922
923    fn accepts(ty: &Type) -> bool {
924        T::accepts(ty)
925    }
926
927    fn encode_format(&self, ty: &Type) -> Format {
928        (*self).encode_format(ty)
929    }
930
931    to_sql_checked!();
932}
933
934impl<T: ToSql> ToSql for Option<T> {
935    fn to_sql(
936        &self,
937        ty: &Type,
938        out: &mut BytesMut,
939    ) -> Result<IsNull, Box<dyn Error + Sync + Send>> {
940        match *self {
941            Some(ref val) => val.to_sql(ty, out),
942            None => Ok(IsNull::Yes),
943        }
944    }
945
946    fn accepts(ty: &Type) -> bool {
947        <T as ToSql>::accepts(ty)
948    }
949
950    fn encode_format(&self, ty: &Type) -> Format {
951        match self {
952            Some(ref val) => val.encode_format(ty),
953            None => Format::Binary,
954        }
955    }
956
957    to_sql_checked!();
958}
959
960impl<'a, T: ToSql> ToSql for &'a [T] {
961    fn to_sql(&self, ty: &Type, w: &mut BytesMut) -> Result<IsNull, Box<dyn Error + Sync + Send>> {
962        let member_type = match *ty.kind() {
963            Kind::Array(ref member) => member,
964            _ => panic!("expected array type"),
965        };
966
967        // Arrays are normally one indexed by default but oidvector and int2vector *require* zero indexing
968        let lower_bound = match *ty {
969            Type::OID_VECTOR | Type::INT2_VECTOR => 0,
970            _ => 1,
971        };
972
973        let dimension = ArrayDimension {
974            len: downcast(self.len())?,
975            lower_bound,
976        };
977
978        types::array_to_sql(
979            Some(dimension),
980            member_type.oid(),
981            self.iter(),
982            |e, w| match e.to_sql(member_type, w)? {
983                IsNull::No => Ok(postgres_protocol::IsNull::No),
984                IsNull::Yes => Ok(postgres_protocol::IsNull::Yes),
985            },
986            w,
987        )?;
988        Ok(IsNull::No)
989    }
990
991    fn accepts(ty: &Type) -> bool {
992        match *ty.kind() {
993            Kind::Array(ref member) => T::accepts(member),
994            _ => false,
995        }
996    }
997
998    to_sql_checked!();
999}
1000
1001impl<'a> ToSql for &'a [u8] {
1002    fn to_sql(&self, _: &Type, w: &mut BytesMut) -> Result<IsNull, Box<dyn Error + Sync + Send>> {
1003        types::bytea_to_sql(self, w);
1004        Ok(IsNull::No)
1005    }
1006
1007    accepts!(BYTEA);
1008
1009    to_sql_checked!();
1010}
1011
1012#[cfg(feature = "array-impls")]
1013impl<const N: usize> ToSql for [u8; N] {
1014    fn to_sql(&self, _: &Type, w: &mut BytesMut) -> Result<IsNull, Box<dyn Error + Sync + Send>> {
1015        types::bytea_to_sql(&self[..], w);
1016        Ok(IsNull::No)
1017    }
1018
1019    accepts!(BYTEA);
1020
1021    to_sql_checked!();
1022}
1023
1024#[cfg(feature = "array-impls")]
1025impl<T: ToSql, const N: usize> ToSql for [T; N] {
1026    fn to_sql(&self, ty: &Type, w: &mut BytesMut) -> Result<IsNull, Box<dyn Error + Sync + Send>> {
1027        <&[T] as ToSql>::to_sql(&&self[..], ty, w)
1028    }
1029
1030    fn accepts(ty: &Type) -> bool {
1031        <&[T] as ToSql>::accepts(ty)
1032    }
1033
1034    to_sql_checked!();
1035}
1036
1037impl<T: ToSql> ToSql for Vec<T> {
1038    fn to_sql(&self, ty: &Type, w: &mut BytesMut) -> Result<IsNull, Box<dyn Error + Sync + Send>> {
1039        <&[T] as ToSql>::to_sql(&&**self, ty, w)
1040    }
1041
1042    fn accepts(ty: &Type) -> bool {
1043        <&[T] as ToSql>::accepts(ty)
1044    }
1045
1046    to_sql_checked!();
1047}
1048
1049impl<T: ToSql> ToSql for Box<[T]> {
1050    fn to_sql(&self, ty: &Type, w: &mut BytesMut) -> Result<IsNull, Box<dyn Error + Sync + Send>> {
1051        <&[T] as ToSql>::to_sql(&&**self, ty, w)
1052    }
1053
1054    fn accepts(ty: &Type) -> bool {
1055        <&[T] as ToSql>::accepts(ty)
1056    }
1057
1058    to_sql_checked!();
1059}
1060
1061impl<'a> ToSql for Cow<'a, [u8]> {
1062    fn to_sql(&self, ty: &Type, w: &mut BytesMut) -> Result<IsNull, Box<dyn Error + Sync + Send>> {
1063        <&[u8] as ToSql>::to_sql(&self.as_ref(), ty, w)
1064    }
1065
1066    fn accepts(ty: &Type) -> bool {
1067        <&[u8] as ToSql>::accepts(ty)
1068    }
1069
1070    to_sql_checked!();
1071}
1072
1073impl ToSql for Vec<u8> {
1074    fn to_sql(&self, ty: &Type, w: &mut BytesMut) -> Result<IsNull, Box<dyn Error + Sync + Send>> {
1075        <&[u8] as ToSql>::to_sql(&&**self, ty, w)
1076    }
1077
1078    fn accepts(ty: &Type) -> bool {
1079        <&[u8] as ToSql>::accepts(ty)
1080    }
1081
1082    to_sql_checked!();
1083}
1084
1085impl<'a> ToSql for &'a str {
1086    fn to_sql(&self, ty: &Type, w: &mut BytesMut) -> Result<IsNull, Box<dyn Error + Sync + Send>> {
1087        match ty.name() {
1088            "ltree" => types::ltree_to_sql(self, w),
1089            "lquery" => types::lquery_to_sql(self, w),
1090            "ltxtquery" => types::ltxtquery_to_sql(self, w),
1091            _ => types::text_to_sql(self, w),
1092        }
1093        Ok(IsNull::No)
1094    }
1095
1096    fn accepts(ty: &Type) -> bool {
1097        matches!(
1098            *ty,
1099            Type::VARCHAR | Type::TEXT | Type::BPCHAR | Type::NAME | Type::UNKNOWN
1100        ) || matches!(ty.name(), "citext" | "ltree" | "lquery" | "ltxtquery")
1101    }
1102
1103    to_sql_checked!();
1104}
1105
1106impl<'a> ToSql for Cow<'a, str> {
1107    fn to_sql(&self, ty: &Type, w: &mut BytesMut) -> Result<IsNull, Box<dyn Error + Sync + Send>> {
1108        <&str as ToSql>::to_sql(&self.as_ref(), ty, w)
1109    }
1110
1111    fn accepts(ty: &Type) -> bool {
1112        <&str as ToSql>::accepts(ty)
1113    }
1114
1115    to_sql_checked!();
1116}
1117
1118impl ToSql for String {
1119    fn to_sql(&self, ty: &Type, w: &mut BytesMut) -> Result<IsNull, Box<dyn Error + Sync + Send>> {
1120        <&str as ToSql>::to_sql(&&**self, ty, w)
1121    }
1122
1123    fn accepts(ty: &Type) -> bool {
1124        <&str as ToSql>::accepts(ty)
1125    }
1126
1127    to_sql_checked!();
1128}
1129
1130impl ToSql for Box<str> {
1131    fn to_sql(&self, ty: &Type, w: &mut BytesMut) -> Result<IsNull, Box<dyn Error + Sync + Send>> {
1132        <&str as ToSql>::to_sql(&&**self, ty, w)
1133    }
1134
1135    fn accepts(ty: &Type) -> bool {
1136        <&str as ToSql>::accepts(ty)
1137    }
1138
1139    to_sql_checked!();
1140}
1141
1142macro_rules! simple_to {
1143    ($t:ty, $f:ident, $($expected:ident),+) => {
1144        impl ToSql for $t {
1145            fn to_sql(&self,
1146                      _: &Type,
1147                      w: &mut BytesMut)
1148                      -> Result<IsNull, Box<dyn Error + Sync + Send>> {
1149                types::$f(*self, w);
1150                Ok(IsNull::No)
1151            }
1152
1153            accepts!($($expected),+);
1154
1155            to_sql_checked!();
1156        }
1157    }
1158}
1159
1160simple_to!(bool, bool_to_sql, BOOL);
1161simple_to!(i8, char_to_sql, CHAR);
1162simple_to!(i16, int2_to_sql, INT2);
1163simple_to!(i32, int4_to_sql, INT4);
1164simple_to!(u32, oid_to_sql, OID);
1165simple_to!(i64, int8_to_sql, INT8);
1166simple_to!(f32, float4_to_sql, FLOAT4);
1167simple_to!(f64, float8_to_sql, FLOAT8);
1168
1169impl<H> ToSql for HashMap<String, Option<String>, H>
1170where
1171    H: BuildHasher,
1172{
1173    fn to_sql(&self, _: &Type, w: &mut BytesMut) -> Result<IsNull, Box<dyn Error + Sync + Send>> {
1174        types::hstore_to_sql(
1175            self.iter().map(|(k, v)| (&**k, v.as_ref().map(|v| &**v))),
1176            w,
1177        )?;
1178        Ok(IsNull::No)
1179    }
1180
1181    fn accepts(ty: &Type) -> bool {
1182        ty.name() == "hstore"
1183    }
1184
1185    to_sql_checked!();
1186}
1187
1188impl ToSql for SystemTime {
1189    fn to_sql(&self, _: &Type, w: &mut BytesMut) -> Result<IsNull, Box<dyn Error + Sync + Send>> {
1190        let epoch = UNIX_EPOCH + Duration::from_secs(TIME_SEC_CONVERSION);
1191
1192        let to_usec =
1193            |d: Duration| d.as_secs() * USEC_PER_SEC + u64::from(d.subsec_nanos()) / NSEC_PER_USEC;
1194
1195        let time = match self.duration_since(epoch) {
1196            Ok(duration) => to_usec(duration) as i64,
1197            Err(e) => -(to_usec(e.duration()) as i64),
1198        };
1199
1200        types::timestamp_to_sql(time, w);
1201        Ok(IsNull::No)
1202    }
1203
1204    accepts!(TIMESTAMP, TIMESTAMPTZ);
1205
1206    to_sql_checked!();
1207}
1208
1209impl ToSql for IpAddr {
1210    fn to_sql(&self, _: &Type, w: &mut BytesMut) -> Result<IsNull, Box<dyn Error + Sync + Send>> {
1211        let netmask = match self {
1212            IpAddr::V4(_) => 32,
1213            IpAddr::V6(_) => 128,
1214        };
1215        types::inet_to_sql(*self, netmask, w);
1216        Ok(IsNull::No)
1217    }
1218
1219    accepts!(INET);
1220
1221    to_sql_checked!();
1222}
1223
1224fn downcast(len: usize) -> Result<i32, Box<dyn Error + Sync + Send>> {
1225    if len > i32::MAX as usize {
1226        Err("value too large to transmit".into())
1227    } else {
1228        Ok(len as i32)
1229    }
1230}
1231
1232mod sealed {
1233    pub trait Sealed {}
1234}
1235
1236/// A trait used by clients to abstract over `&dyn ToSql` and `T: ToSql`.
1237///
1238/// This cannot be implemented outside of this crate.
1239pub trait BorrowToSql: sealed::Sealed {
1240    /// Returns a reference to `self` as a `ToSql` trait object.
1241    fn borrow_to_sql(&self) -> &dyn ToSql;
1242}
1243
1244impl sealed::Sealed for &dyn ToSql {}
1245
1246impl BorrowToSql for &dyn ToSql {
1247    #[inline]
1248    fn borrow_to_sql(&self) -> &dyn ToSql {
1249        *self
1250    }
1251}
1252
1253impl<'a> sealed::Sealed for Box<dyn ToSql + Sync + 'a> {}
1254
1255impl<'a> BorrowToSql for Box<dyn ToSql + Sync + 'a> {
1256    #[inline]
1257    fn borrow_to_sql(&self) -> &dyn ToSql {
1258        self.as_ref()
1259    }
1260}
1261
1262impl<'a> sealed::Sealed for Box<dyn ToSql + Sync + Send + 'a> {}
1263impl<'a> BorrowToSql for Box<dyn ToSql + Sync + Send + 'a> {
1264    #[inline]
1265    fn borrow_to_sql(&self) -> &dyn ToSql {
1266        self.as_ref()
1267    }
1268}
1269
1270impl sealed::Sealed for &(dyn ToSql + Sync) {}
1271
1272/// In async contexts it is sometimes necessary to have the additional
1273/// Sync requirement on parameters for queries since this enables the
1274/// resulting Futures to be Send, hence usable in, e.g., tokio::spawn.
1275/// This instance is provided for those cases.
1276impl BorrowToSql for &(dyn ToSql + Sync) {
1277    #[inline]
1278    fn borrow_to_sql(&self) -> &dyn ToSql {
1279        *self
1280    }
1281}
1282
1283impl<T> sealed::Sealed for T where T: ToSql {}
1284
1285impl<T> BorrowToSql for T
1286where
1287    T: ToSql,
1288{
1289    #[inline]
1290    fn borrow_to_sql(&self) -> &dyn ToSql {
1291        self
1292    }
1293}