Skip to main content

diesel/expression/
cast.rs

1//! SQL `CAST(expr AS sql_type)` expression support
2
3use crate::expression::{AppearsOnTable, Expression, SelectableExpression, ValidGrouping};
4use crate::query_source::aliasing::{AliasSource, FieldAliasMapper};
5use crate::result::QueryResult;
6use crate::{query_builder, query_source, sql_types};
7
8use core::marker::PhantomData;
9
10pub(crate) mod private {
11    use super::*;
12
13    #[derive(Debug, Clone, Copy, diesel::query_builder::QueryId, sql_types::DieselNumericOps)]
14    pub struct Cast<E, ST> {
15        pub(super) expr: E,
16        pub(super) sql_type: PhantomData<ST>,
17    }
18}
19pub(crate) use private::Cast;
20
21impl<E, ST> Cast<E, ST> {
22    pub(crate) fn new(expr: E) -> Self {
23        Self {
24            expr,
25            sql_type: PhantomData,
26        }
27    }
28}
29
30impl<E, ST, GroupByClause> ValidGrouping<GroupByClause> for Cast<E, ST>
31where
32    E: ValidGrouping<GroupByClause>,
33{
34    type IsAggregate = E::IsAggregate;
35}
36
37impl<E, ST, QS> SelectableExpression<QS> for Cast<E, ST>
38where
39    Cast<E, ST>: AppearsOnTable<QS>,
40    E: SelectableExpression<QS>,
41{
42}
43
44impl<E, ST, QS> AppearsOnTable<QS> for Cast<E, ST>
45where
46    Cast<E, ST>: Expression,
47    E: AppearsOnTable<QS>,
48{
49}
50
51impl<E, ST> Expression for Cast<E, ST>
52where
53    E: Expression,
54    ST: sql_types::SingleValue,
55{
56    type SqlType = ST;
57}
58
59impl<E, ST, DB> query_builder::QueryFragment<DB> for Cast<E, ST>
60where
61    E: query_builder::QueryFragment<DB>,
62    DB: diesel::backend::Backend,
63    ST: KnownCastSqlTypeName<DB>,
64{
65    fn walk_ast<'b>(&'b self, mut out: query_builder::AstPass<'_, 'b, DB>) -> QueryResult<()> {
66        out.push_sql("CAST(");
67        self.expr.walk_ast(out.reborrow())?;
68        out.push_sql(" AS ");
69        out.push_sql(ST::SQL_TYPE_NAME);
70        out.push_sql(")");
71        Ok(())
72    }
73}
74
75/// We know what to write as `sql_type` in the `CAST(expr AS sql_type)` SQL for
76/// `Self`
77///
78/// That is what is returned by `Self::sql_type_name()`
79#[diagnostic::on_unimplemented(
80    note = "In order to use `CAST`, it is necessary that Diesel knows how to express the name \
81		of this type in the given backend.",
82    note = "If you run into this error message and believe that this cast should be supported \
83            open a PR that adds that trait implementation here: https://github.com/diesel-rs/diesel/blob/2fafe60a8f4ca3407dca5fe010a6092fa8a1858a/diesel/src/expression/cast.rs#L113."
84)]
85pub trait KnownCastSqlTypeName<DB> {
86    /// What to write as `sql_type` in the `CAST(expr AS sql_type)` SQL for
87    /// `Self`
88    const SQL_TYPE_NAME: &'static str;
89}
90
91impl<ST, DB> KnownCastSqlTypeName<DB> for sql_types::Nullable<ST>
92where
93    ST: KnownCastSqlTypeName<DB>,
94{
95    const SQL_TYPE_NAME: &'static str = <ST as KnownCastSqlTypeName<DB>>::SQL_TYPE_NAME;
96}
97
98macro_rules! type_name {
99    ($($backend: ty: $backend_feature: literal { $($type: ident => $val: literal,)+ })*) => {
100        $(
101            $(
102				#[cfg(feature = $backend_feature)]
103                impl KnownCastSqlTypeName<$backend> for sql_types::$type {
104                    const SQL_TYPE_NAME: &'static str = $val;
105                }
106            )*
107        )*
108    };
109}
110
111type_name! {
112    diesel::pg::Pg: "postgres_backend" {
113        Bool => "bool",
114        Int2 => "int2",
115        Int4 => "int4",
116        Int8 => "int8",
117        Float => "float4",
118        Double => "float8",
119        Numeric => "numeric",
120        Text => "text",
121        Date => "date",
122        Interval => "interval",
123        Time => "time",
124        Timestamp => "timestamp",
125        Uuid => "uuid",
126        Json => "json",
127        Jsonb => "jsonb",
128        Inet => "inet",
129        Cidr => "cidr",
130    }
131    diesel::mysql::Mysql: "mysql_backend" {
132        Int8 => "signed",
133        Text => "char",
134        Date => "date",
135        Datetime => "datetime",
136        Decimal => "decimal",
137        Time => "time",
138    }
139    diesel::mariadb::Mariadb: "mariadb_backend" {
140        Int8 => "signed",
141        Text => "char",
142        Date => "date",
143        Datetime => "datetime",
144        Decimal => "decimal",
145        Time => "time",
146        Uuid => "uuid",
147    }
148    diesel::sqlite::Sqlite: "sqlite" {
149        Int4 => "integer",
150        Int8 => "bigint",
151        Double => "real",
152        Text => "text",
153        Json => "json",
154        Jsonb => "jsonb",
155    }
156}
157
158impl<S, E, ST> FieldAliasMapper<S> for Cast<E, ST>
159where
160    S: AliasSource,
161    E: FieldAliasMapper<S>,
162{
163    type Out = Cast<<E as FieldAliasMapper<S>>::Out, ST>;
164
165    fn map(self, alias: &query_source::Alias<S>) -> Self::Out {
166        Cast {
167            expr: self.expr.map(alias),
168            sql_type: self.sql_type,
169        }
170    }
171}
172
173/// Marker trait: this SQL type (`Self`) can be cast to the target SQL type, but some values can be invalid
174pub trait FallibleCastsTo<ST> {}
175
176impl<ST1, ST2> FallibleCastsTo<sql_types::Nullable<ST2>> for sql_types::Nullable<ST1> where
177    ST1: FallibleCastsTo<ST2>
178{
179}
180
181/// Marker trait: this SQL type (`Self`) can be cast to the target SQL type
182/// (`ST`) using `CAST(expr AS target_sql_type)`
183pub trait CastsTo<ST>: FallibleCastsTo<ST> {}
184
185impl<ST1, ST2> CastsTo<sql_types::Nullable<ST2>> for sql_types::Nullable<ST1> where ST1: CastsTo<ST2>
186{}
187
188macro_rules! casts_impl {
189    (
190        $(
191            $($($feature: literal),+ : )? ($to: tt <- $from: tt),
192        )+
193    ) => {
194        $(
195            $(#[cfg(any($(feature = $feature,)+))])?
196            impl FallibleCastsTo<sql_types::$to> for sql_types::$from {}
197            $(#[cfg(any($(feature = $feature,)+))])?
198            impl CastsTo<sql_types::$to> for sql_types::$from {}
199        )+
200    };
201}
202
203casts_impl!(
204    (Bool <- Int4),
205    (Int4 <- Bool),
206    (Int4 <- Float4),
207    (Int8 <- Int4),
208    (Int8 <- Float4),
209    (Int8 <- Float8),
210    (Float4 <- Int4),
211    (Float4 <- Int8),
212    (Float8 <- Float4),
213    (Float8 <- Int4),
214    (Float8 <- Int8),
215    (Decimal <- Int4),
216    (Decimal <- Int8),
217    (Decimal <- Float4),
218    (Decimal <- Float8),
219    (Text <- Bool),
220    (Text <- Float4),
221    (Text <- Float8),
222    (Text <- Int4),
223    (Text <- Int8),
224    (Text <- Date),
225    (Text <- Json),
226    (Text <- Jsonb),
227    (Text <- Time),
228    (Json <- Jsonb),
229    (Jsonb <- Json),
230    "mysql_backend","mariadb_backend": (Text <- Datetime),
231    "postgres_backend","mariadb_backend": (Text <- Uuid),
232    "postgres_backend": (Text <- Inet),
233    "postgres_backend": (Text <- Cidr),
234    "postgres_backend": (Inet <- Cidr),
235    "postgres_backend": (Cidr <- Inet),
236);
237
238macro_rules! fallible_casts_impl {
239    (
240        $(
241            $($($feature: literal),+ : )? ($to: tt <- $from: tt),
242        )+
243    ) => {
244        $(
245            $(#[cfg(any($(feature = $feature,)+))])?
246            impl FallibleCastsTo<sql_types::$to> for sql_types::$from {}
247        )+
248    };
249}
250
251fallible_casts_impl!(
252    (Int4 <- Int8),
253    (Int4 <- Float8),
254    (Int4 <- Text),
255    (Int4 <- Decimal),
256    (Int8 <- Text),
257    (Int8 <- Decimal),
258    (Float4 <- Float8),
259    (Float4 <- Text),
260    (Float4 <- Decimal),
261    (Float8 <- Text),
262    (Float8 <- Decimal),
263    (Json <- Text),
264    (Jsonb <- Text),
265    (Bool <- Text),
266    (Date <- Text),
267    (Time <- Text),
268    (Decimal <- Text),
269    "mysql_backend","mariadb_backend": (Datetime <- Text),
270    "postgres_backend","mariadb_backend": (Uuid <- Text),
271    "postgres_backend": (Inet <- Text),
272    "postgres_backend": (Cidr <- Text),
273    "mariadb_backend": (Uuid <- Binary),
274);