1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
//! The PostgreSQL backend

use super::query_builder::PgQueryBuilder;
use super::{PgMetadataLookup, PgValue};
use crate::backend::*;
use crate::deserialize::Queryable;
use crate::pg::metadata_lookup::PgMetadataCacheKey;
use crate::query_builder::bind_collector::RawBytesBindCollector;
use crate::sql_types::TypeMetadata;

/// The PostgreSQL backend
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, Default)]
pub struct Pg;

#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, Queryable)]
pub struct InnerPgTypeMetadata {
    pub(in crate::pg) oid: u32,
    pub(in crate::pg) array_oid: u32,
}

impl From<(u32, u32)> for InnerPgTypeMetadata {
    fn from((oid, array_oid): (u32, u32)) -> Self {
        Self { oid, array_oid }
    }
}

/// This error indicates that a type lookup for a custom
/// postgres type failed
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
#[cfg_attr(
    feature = "i-implement-a-third-party-backend-and-opt-into-breaking-changes",
    cfg(feature = "i-implement-a-third-party-backend-and-opt-into-breaking-changes")
)]
#[allow(unreachable_pub)]
pub struct FailedToLookupTypeError(Box<PgMetadataCacheKey<'static>>);

impl FailedToLookupTypeError {
    /// Construct a new instance of this error type
    /// containing information about which type lookup failed
    #[cfg(feature = "i-implement-a-third-party-backend-and-opt-into-breaking-changes")]
    pub fn new(cache_key: PgMetadataCacheKey<'static>) -> Self {
        Self::new_internal(cache_key)
    }

    pub(in crate::pg) fn new_internal(cache_key: PgMetadataCacheKey<'static>) -> Self {
        Self(Box::new(cache_key))
    }
}

impl std::error::Error for FailedToLookupTypeError {}

impl std::fmt::Display for FailedToLookupTypeError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if let Some(schema) = self.0.schema.as_ref() {
            write!(
                f,
                "Failed to find a type oid for `{}`.`{}`",
                schema, self.0.type_name
            )
        } else {
            write!(f, "Failed to find a type oid for `{}`", self.0.type_name)
        }
    }
}

/// The [OIDs] for a SQL type
///
/// [OIDs]: https://www.postgresql.org/docs/current/static/datatype-oid.html
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[must_use]
pub struct PgTypeMetadata(pub(in crate::pg) Result<InnerPgTypeMetadata, FailedToLookupTypeError>);

impl PgTypeMetadata {
    /// Create a new instance of this type based on known constant [OIDs].
    ///
    /// Please refer to [PgMetadataLookup] for a way to query [OIDs]
    /// of custom types at run time
    ///
    /// [OIDs]: https://www.postgresql.org/docs/current/static/datatype-oid.html
    /// [PgMetadataLookup]: struct.PgMetadataLookup.html
    pub fn new(type_oid: u32, array_oid: u32) -> Self {
        Self(Ok(InnerPgTypeMetadata {
            oid: type_oid,
            array_oid,
        }))
    }

    /// Create a new instance of this type based on dynamically lookup informations
    ///
    /// This function is useful for third party crates that may implement a custom
    /// postgres connection type and want to bring their own lookup mechanism.
    ///
    /// Otherwise refer to [PgMetadataLookup] for a way to automatically
    /// implement the corresponding lookup functionality
    #[cfg(feature = "i-implement-a-third-party-backend-and-opt-into-breaking-changes")]
    pub fn from_result(r: Result<(u32, u32), FailedToLookupTypeError>) -> Self {
        Self(r.map(|(oid, array_oid)| InnerPgTypeMetadata { oid, array_oid }))
    }

    /// The [OID] of `T`
    ///
    /// [OID]: https://www.postgresql.org/docs/current/static/datatype-oid.html
    pub fn oid(&self) -> Result<u32, impl std::error::Error + Send + Sync> {
        self.0.as_ref().map(|i| i.oid).map_err(Clone::clone)
    }

    /// The [OID] of `T[]`
    ///
    /// [OID]: https://www.postgresql.org/docs/current/static/datatype-oid.html
    pub fn array_oid(&self) -> Result<u32, impl std::error::Error + Send + Sync> {
        self.0.as_ref().map(|i| i.array_oid).map_err(Clone::clone)
    }
}

impl Backend for Pg {
    type QueryBuilder = PgQueryBuilder;
}

impl<'a> HasBindCollector<'a> for Pg {
    type BindCollector = RawBytesBindCollector<Pg>;
}

impl<'a> HasRawValue<'a> for Pg {
    type RawValue = PgValue<'a>;
}

impl TypeMetadata for Pg {
    type TypeMetadata = PgTypeMetadata;
    type MetadataLookup = dyn PgMetadataLookup;
}

impl SqlDialect for Pg {
    type ReturningClause = sql_dialect::returning_clause::PgLikeReturningClause;

    type OnConflictClause = PgOnConflictClaues;

    type InsertWithDefaultKeyword = sql_dialect::default_keyword_for_insert::IsoSqlDefaultKeyword;
    type BatchInsertSupport = sql_dialect::batch_insert_support::PostgresLikeBatchInsertSupport;
    type ConcatClause = sql_dialect::concat_clause::ConcatWithPipesClause;

    type DefaultValueClauseForInsert = sql_dialect::default_value_clause::AnsiDefaultValueClause;

    type EmptyFromClauseSyntax = sql_dialect::from_clause_syntax::AnsiSqlFromClauseSyntax;
    type SelectStatementSyntax = sql_dialect::select_statement_syntax::AnsiSqlSelectStatement;

    type ExistsSyntax = sql_dialect::exists_syntax::AnsiSqlExistsSyntax;
    type ArrayComparison = PgStyleArrayComparision;
}

impl DieselReserveSpecialization for Pg {}
impl TrustedBackend for Pg {}

#[derive(Debug, Copy, Clone)]
pub struct PgOnConflictClaues;

impl sql_dialect::on_conflict_clause::SupportsOnConflictClause for PgOnConflictClaues {}

#[derive(Debug, Copy, Clone)]
pub struct PgStyleArrayComparision;