Skip to main content

sea_query_postgres/
lib.rs

1#![forbid(unsafe_code)]
2
3use std::error::Error;
4
5use bytes::BytesMut;
6use postgres_types::{IsNull, ToSql, Type, to_sql_checked};
7
8use sea_query::{ArrayType, OptionEnum, QueryBuilder, Value, query::*};
9
10#[derive(Clone, Debug, PartialEq)]
11pub struct PostgresValue(pub Value);
12#[derive(Clone, Debug, PartialEq)]
13pub struct PostgresValues(pub Vec<PostgresValue>);
14
15impl PostgresValues {
16    pub fn as_params(&self) -> Vec<&(dyn ToSql + Sync)> {
17        self.0
18            .iter()
19            .map(|x| {
20                let y: &(dyn ToSql + Sync) = x;
21                y
22            })
23            .collect()
24    }
25
26    pub fn as_types(&self) -> Vec<Type> {
27        self.0
28            .iter()
29            .map(|x| &x.0)
30            .map(value_to_postgres_type)
31            .collect()
32    }
33}
34
35pub trait PostgresBinder {
36    fn build_postgres<T: QueryBuilder>(&self, query_builder: T) -> (String, PostgresValues);
37}
38
39macro_rules! impl_postgres_binder {
40    ($l:ident) => {
41        impl PostgresBinder for $l {
42            fn build_postgres<T: QueryBuilder>(
43                &self,
44                query_builder: T,
45            ) -> (String, PostgresValues) {
46                let (query, values) = self.build(query_builder);
47                (
48                    query,
49                    PostgresValues(values.into_iter().map(PostgresValue).collect()),
50                )
51            }
52        }
53    };
54}
55
56impl_postgres_binder!(SelectStatement);
57impl_postgres_binder!(UpdateStatement);
58impl_postgres_binder!(InsertStatement);
59impl_postgres_binder!(DeleteStatement);
60impl_postgres_binder!(WithQuery);
61
62impl ToSql for PostgresValue {
63    fn to_sql(
64        &self,
65        ty: &Type,
66        out: &mut BytesMut,
67    ) -> Result<IsNull, Box<dyn Error + Sync + Send>> {
68        macro_rules! to_sql {
69            ( $v: expr, $ty: ty ) => {
70                $v.map(|v| v as $ty).as_ref().to_sql(ty, out)
71            };
72        }
73        match &self.0 {
74            Value::Bool(v) => to_sql!(v, bool),
75            Value::TinyInt(v) => to_sql!(v, i8),
76            Value::SmallInt(v) => to_sql!(v, i16),
77            Value::Int(v) => to_sql!(v, i32),
78            Value::BigInt(v) => to_sql!(v, i64),
79            Value::TinyUnsigned(v) => to_sql!(v, u32),
80            Value::SmallUnsigned(v) => to_sql!(v, u32),
81            Value::Unsigned(v) => to_sql!(v, u32),
82            Value::BigUnsigned(v) => to_sql!(v, i64),
83            Value::Float(v) => to_sql!(v, f32),
84            Value::Double(v) => to_sql!(v, f64),
85            Value::String(v) => v.as_deref().to_sql(ty, out),
86            Value::Enum(v) => match v {
87                OptionEnum::Some(v) => Some(v.value.as_ref()).to_sql(ty, out),
88                OptionEnum::None(_) => Option::<&str>::None.to_sql(ty, out),
89            },
90            Value::Char(v) => v.map(|v| v.to_string()).to_sql(ty, out),
91            Value::Bytes(v) => v.as_deref().to_sql(ty, out),
92            #[cfg(feature = "with-json")]
93            Value::Json(v) => v.as_deref().to_sql(ty, out),
94            #[cfg(feature = "with-chrono")]
95            Value::ChronoDate(v) => v.to_sql(ty, out),
96            #[cfg(feature = "with-chrono")]
97            Value::ChronoTime(v) => v.to_sql(ty, out),
98            #[cfg(feature = "with-chrono")]
99            Value::ChronoDateTime(v) => v.to_sql(ty, out),
100            #[cfg(feature = "with-chrono")]
101            Value::ChronoDateTimeUtc(v) => v.to_sql(ty, out),
102            #[cfg(feature = "with-chrono")]
103            Value::ChronoDateTimeLocal(v) => v.to_sql(ty, out),
104            #[cfg(feature = "with-chrono")]
105            Value::ChronoDateTimeWithTimeZone(v) => v.to_sql(ty, out),
106            #[cfg(feature = "with-time")]
107            Value::TimeDate(v) => v.to_sql(ty, out),
108            #[cfg(feature = "with-time")]
109            Value::TimeTime(v) => v.to_sql(ty, out),
110            #[cfg(feature = "with-time")]
111            Value::TimeDateTime(v) => v.to_sql(ty, out),
112            #[cfg(feature = "with-time")]
113            Value::TimeDateTimeWithTimeZone(v) => v.to_sql(ty, out),
114            #[cfg(feature = "with-jiff")]
115            Value::JiffDate(v) => v.to_sql(ty, out),
116            #[cfg(feature = "with-jiff")]
117            Value::JiffTime(v) => v.to_sql(ty, out),
118            #[cfg(feature = "with-jiff")]
119            Value::JiffDateTime(v) => v.to_sql(ty, out),
120            #[cfg(feature = "with-jiff")]
121            Value::JiffTimestamp(v) => v.to_sql(ty, out),
122            #[cfg(feature = "with-rust_decimal")]
123            Value::Decimal(v) => v.to_sql(ty, out),
124            #[cfg(feature = "with-bigdecimal")]
125            Value::BigDecimal(v) => {
126                use bigdecimal::ToPrimitive;
127                v.as_deref()
128                    .map(|v| v.to_f64().expect("Fail to convert bigdecimal as f64"))
129                    .to_sql(ty, out)
130            }
131            #[cfg(feature = "with-uuid")]
132            Value::Uuid(v) => v.to_sql(ty, out),
133            #[cfg(feature = "postgres-array")]
134            Value::Array(_, Some(v)) => v
135                .iter()
136                .map(|v| PostgresValue(v.clone()))
137                .collect::<Vec<PostgresValue>>()
138                .to_sql(ty, out),
139            #[cfg(feature = "postgres-array")]
140            Value::Array(_, None) => Ok(IsNull::Yes),
141            #[cfg(feature = "postgres-vector")]
142            Value::Vector(Some(v)) => v.to_sql(ty, out),
143            #[cfg(feature = "postgres-vector")]
144            Value::Vector(None) => Ok(IsNull::Yes),
145            #[cfg(feature = "with-ipnetwork")]
146            Value::IpNetwork(v) => {
147                use cidr::IpCidr;
148                v.map(|v| {
149                    IpCidr::new(v.network(), v.prefix())
150                        .expect("Fail to convert IpNetwork to IpCidr")
151                })
152                .to_sql(ty, out)
153            }
154            #[cfg(feature = "with-mac_address")]
155            Value::MacAddress(v) => {
156                use eui48::MacAddress;
157                v.map(|v| MacAddress::new(v.bytes())).to_sql(ty, out)
158            }
159            #[cfg(feature = "postgres-range")]
160            Value::Range(None) => Ok(IsNull::Yes),
161            #[cfg(feature = "postgres-range")]
162            Value::Range(Some(v)) => v.to_sql(ty, out),
163        }
164    }
165
166    fn accepts(_ty: &Type) -> bool {
167        true
168    }
169
170    to_sql_checked!();
171}
172
173fn value_to_postgres_type(value: &Value) -> Type {
174    match value {
175        Value::Bool(_) => Type::BOOL,
176        Value::TinyInt(_) => Type::INT2,
177        Value::TinyUnsigned(_) => Type::INT2,
178        Value::SmallInt(_) => Type::INT2,
179        Value::SmallUnsigned(_) => Type::INT4,
180        Value::Int(_) => Type::INT4,
181        Value::BigInt(_) => Type::INT8,
182        Value::Unsigned(_) => Type::INT8,
183        Value::BigUnsigned(_) => Type::NUMERIC,
184        Value::Float(_) => Type::FLOAT4,
185        Value::Double(_) => Type::FLOAT8,
186        Value::String(_) => Type::TEXT,
187        Value::Enum(_) => Type::TEXT,
188        #[cfg(feature = "postgres-range")]
189        Value::Range(_) => Type::INT8_RANGE,
190        Value::Char(_) => Type::CHAR,
191        Value::Bytes(_) => Type::BYTEA,
192        #[cfg(feature = "with-json")]
193        Value::Json(_) => Type::JSON,
194        #[cfg(feature = "with-chrono")]
195        Value::ChronoDate(_) => Type::DATE,
196        #[cfg(feature = "with-chrono")]
197        Value::ChronoTime(_) => Type::TIME,
198        #[cfg(feature = "with-chrono")]
199        Value::ChronoDateTime(_) => Type::TIMESTAMP,
200        #[cfg(feature = "with-chrono")]
201        Value::ChronoDateTimeUtc(_) => Type::TIMESTAMP,
202        #[cfg(feature = "with-chrono")]
203        Value::ChronoDateTimeLocal(_) => Type::TIMESTAMP,
204        #[cfg(feature = "with-chrono")]
205        Value::ChronoDateTimeWithTimeZone(_) => Type::TIMESTAMPTZ,
206        #[cfg(feature = "with-time")]
207        Value::TimeDate(_) => Type::DATE,
208        #[cfg(feature = "with-time")]
209        Value::TimeTime(_) => Type::TIME,
210        #[cfg(feature = "with-time")]
211        Value::TimeDateTime(_) => Type::TIMESTAMP,
212        #[cfg(feature = "with-time")]
213        Value::TimeDateTimeWithTimeZone(_) => Type::TIMESTAMPTZ,
214        #[cfg(feature = "with-jiff")]
215        Value::JiffDate(_) => Type::DATE,
216        #[cfg(feature = "with-jiff")]
217        Value::JiffTime(_) => Type::TIME,
218        #[cfg(feature = "with-jiff")]
219        Value::JiffDateTime(_) => Type::TIMESTAMP,
220        #[cfg(feature = "with-jiff")]
221        Value::JiffTimestamp(_) => Type::TIMESTAMPTZ,
222        #[cfg(feature = "with-uuid")]
223        Value::Uuid(_) => Type::UUID,
224        #[cfg(feature = "with-rust_decimal")]
225        Value::Decimal(_) => Type::NUMERIC,
226        #[cfg(feature = "with-bigdecimal")]
227        Value::BigDecimal(_) => Type::NUMERIC,
228        #[cfg(feature = "postgres-array")]
229        Value::Array(ty, _) => array_type_to_pg_type(ty),
230        #[cfg(feature = "postgres-vector")]
231        Value::Vector(_) => Type::FLOAT4_ARRAY,
232        #[cfg(feature = "with-ipnetwork")]
233        Value::IpNetwork(_) => Type::INET,
234        #[cfg(feature = "with-mac_address")]
235        Value::MacAddress(_) => Type::MACADDR,
236    }
237}
238
239fn array_type_to_pg_type(ty: &ArrayType) -> Type {
240    match ty {
241        ArrayType::Bool => Type::BOOL_ARRAY,
242        ArrayType::TinyInt => Type::INT2_ARRAY,
243        ArrayType::TinyUnsigned => Type::INT2_ARRAY,
244        ArrayType::SmallInt => Type::INT2_ARRAY,
245        ArrayType::SmallUnsigned => Type::INT4_ARRAY,
246        ArrayType::Int => Type::INT4_ARRAY,
247        ArrayType::Unsigned => Type::INT8_ARRAY,
248        ArrayType::BigInt => Type::INT8_ARRAY,
249        ArrayType::BigUnsigned => Type::NUMERIC_ARRAY,
250        ArrayType::Float => Type::FLOAT4_ARRAY,
251        ArrayType::Double => Type::FLOAT8_ARRAY,
252        ArrayType::String => Type::TEXT_ARRAY,
253        ArrayType::Char => Type::CHAR_ARRAY,
254        ArrayType::Bytes => Type::BYTEA_ARRAY,
255        #[cfg(feature = "with-json")]
256        ArrayType::Json => Type::JSON_ARRAY,
257        #[cfg(feature = "with-chrono")]
258        ArrayType::ChronoDate => Type::DATE_ARRAY,
259        #[cfg(feature = "with-chrono")]
260        ArrayType::ChronoTime => Type::TIME_ARRAY,
261        #[cfg(feature = "with-chrono")]
262        ArrayType::ChronoDateTime => Type::TIMESTAMP_ARRAY,
263        #[cfg(feature = "with-chrono")]
264        ArrayType::ChronoDateTimeUtc => Type::TIMESTAMP_ARRAY,
265        #[cfg(feature = "with-chrono")]
266        ArrayType::ChronoDateTimeLocal => Type::TIMESTAMP_ARRAY,
267        #[cfg(feature = "with-chrono")]
268        ArrayType::ChronoDateTimeWithTimeZone => Type::TIMESTAMPTZ_ARRAY,
269        #[cfg(feature = "with-time")]
270        ArrayType::TimeDate => Type::DATE_ARRAY,
271        #[cfg(feature = "with-time")]
272        ArrayType::TimeTime => Type::TIME_ARRAY,
273        #[cfg(feature = "with-time")]
274        ArrayType::TimeDateTime => Type::TIMESTAMP_ARRAY,
275        #[cfg(feature = "with-time")]
276        ArrayType::TimeDateTimeWithTimeZone => Type::TIMESTAMPTZ_ARRAY,
277        #[cfg(feature = "with-jiff")]
278        ArrayType::JiffDate => Type::DATE_ARRAY,
279        #[cfg(feature = "with-jiff")]
280        ArrayType::JiffTime => Type::TIME_ARRAY,
281        #[cfg(feature = "with-jiff")]
282        ArrayType::JiffDateTime => Type::TIMESTAMP_ARRAY,
283        #[cfg(feature = "with-jiff")]
284        ArrayType::JiffTimestamp => Type::TIMESTAMPTZ_ARRAY,
285        #[cfg(feature = "with-uuid")]
286        ArrayType::Uuid => Type::UUID_ARRAY,
287        #[cfg(feature = "with-rust_decimal")]
288        ArrayType::Decimal => Type::NUMERIC_ARRAY,
289        #[cfg(feature = "with-bigdecimal")]
290        ArrayType::BigDecimal => Type::NUMERIC_ARRAY,
291        #[cfg(feature = "with-ipnetwork")]
292        ArrayType::IpNetwork => Type::INET_ARRAY,
293        #[cfg(feature = "with-mac_address")]
294        ArrayType::MacAddress => Type::MACADDR_ARRAY,
295        ArrayType::Enum(_) => Type::TEXT_ARRAY,
296        #[cfg(feature = "postgres-range")]
297        ArrayType::Range => Type::INT8_RANGE_ARRAY,
298    }
299}