Skip to main content

diesel/expression/
sql_literal.rs

1use crate::expression::*;
2use crate::query_builder::*;
3use crate::query_dsl::RunQueryDslSupport;
4use crate::result::QueryResult;
5use crate::sql_types::DieselNumericOps;
6use alloc::string::String;
7use core::marker::PhantomData;
8
9#[derive(#[automatically_derived]
impl<ST: ::core::fmt::Debug, T: ::core::fmt::Debug> ::core::fmt::Debug for
    SqlLiteral<ST, T> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field3_finish(f, "SqlLiteral",
            "sql", &self.sql, "inner", &self.inner, "_marker", &&self._marker)
    }
}Debug, #[automatically_derived]
impl<ST: ::core::clone::Clone, T: ::core::clone::Clone> ::core::clone::Clone
    for SqlLiteral<ST, T> {
    #[inline]
    fn clone(&self) -> SqlLiteral<ST, T> {
        SqlLiteral {
            sql: ::core::clone::Clone::clone(&self.sql),
            inner: ::core::clone::Clone::clone(&self.inner),
            _marker: ::core::clone::Clone::clone(&self._marker),
        }
    }
}Clone, const _: () =
    {
        use diesel;
        use diesel::internal::derives::numeric_ops as ops;
        use diesel::expression::{Expression, AsExpression};
        use diesel::sql_types::ops::{Add, Sub, Mul, Div};
        use diesel::sql_types::{SqlType, SingleValue};
        impl<ST, T, __Rhs> ::core::ops::Add<__Rhs> for SqlLiteral<ST, T> where
            Self: Expression, Self: Expression,
            <Self as Expression>::SqlType: Add,
            <<Self as Expression>::SqlType as Add>::Rhs: SqlType +
            SingleValue,
            __Rhs: AsExpression<<<Self as Expression>::SqlType as Add>::Rhs> {
            type Output = ops::Add<Self, __Rhs::Expression>;
            fn add(self, rhs: __Rhs) -> Self::Output {
                ops::Add::new(self, rhs.as_expression())
            }
        }
        impl<ST, T, __Rhs> ::core::ops::Sub<__Rhs> for SqlLiteral<ST, T> where
            Self: Expression, Self: Expression,
            <Self as Expression>::SqlType: Sub,
            <<Self as Expression>::SqlType as Sub>::Rhs: SqlType +
            SingleValue,
            __Rhs: AsExpression<<<Self as Expression>::SqlType as Sub>::Rhs> {
            type Output = ops::Sub<Self, __Rhs::Expression>;
            fn sub(self, rhs: __Rhs) -> Self::Output {
                ops::Sub::new(self, rhs.as_expression())
            }
        }
        impl<ST, T, __Rhs> ::core::ops::Mul<__Rhs> for SqlLiteral<ST, T> where
            Self: Expression, Self: Expression,
            <Self as Expression>::SqlType: Mul,
            <<Self as Expression>::SqlType as Mul>::Rhs: SqlType +
            SingleValue,
            __Rhs: AsExpression<<<Self as Expression>::SqlType as Mul>::Rhs> {
            type Output = ops::Mul<Self, __Rhs::Expression>;
            fn mul(self, rhs: __Rhs) -> Self::Output {
                ops::Mul::new(self, rhs.as_expression())
            }
        }
        impl<ST, T, __Rhs> ::core::ops::Div<__Rhs> for SqlLiteral<ST, T> where
            Self: Expression, Self: Expression,
            <Self as Expression>::SqlType: Div,
            <<Self as Expression>::SqlType as Div>::Rhs: SqlType +
            SingleValue,
            __Rhs: AsExpression<<<Self as Expression>::SqlType as Div>::Rhs> {
            type Output = ops::Div<Self, __Rhs::Expression>;
            fn div(self, rhs: __Rhs) -> Self::Output {
                ops::Div::new(self, rhs.as_expression())
            }
        }
    };DieselNumericOps)]
10#[must_use = "Queries are only executed when calling `load`, `get_result`, or similar."]
11/// Returned by the [`sql()`] function.
12///
13/// [`sql()`]: crate::dsl::sql()
14pub struct SqlLiteral<ST, T = self::private::Empty> {
15    sql: String,
16    inner: T,
17    _marker: PhantomData<ST>,
18}
19
20impl<ST, T> SqlLiteral<ST, T>
21where
22    ST: TypedExpressionType,
23{
24    pub(crate) fn new(sql: String, inner: T) -> Self {
25        SqlLiteral {
26            sql,
27            inner,
28            _marker: PhantomData,
29        }
30    }
31
32    /// Bind a value for use with this SQL query.
33    ///
34    /// # Safety
35    ///
36    /// This function should be used with care, as Diesel cannot validate that
37    /// the value is of the right type nor can it validate that you have passed
38    /// the correct number of parameters.
39    ///
40    /// # Examples
41    ///
42    /// ```rust
43    /// # include!("../doctest_setup.rs");
44    /// #
45    /// # table! {
46    /// #    users {
47    /// #        id -> Integer,
48    /// #        name -> VarChar,
49    /// #    }
50    /// # }
51    /// #
52    /// # fn main() {
53    /// #     use self::users::dsl::*;
54    /// #     use diesel::dsl::sql;
55    /// #     use diesel::sql_types::{Integer, Text, Bool};
56    /// #     let connection = &mut establish_connection();
57    /// let seans_id = users
58    ///     .select(id)
59    ///     .filter(sql::<Bool>("name = ").bind::<Text, _>("Sean"))
60    ///     .get_result(connection);
61    /// assert_eq!(Ok(1), seans_id);
62    ///
63    /// let tess_id = sql::<Integer>("SELECT id FROM users WHERE name = ")
64    ///     .bind::<Text, _>("Tess")
65    ///     .get_result(connection);
66    /// assert_eq!(Ok(2), tess_id);
67    /// # }
68    /// ```
69    ///
70    /// ### Multiple Bind Params
71    ///
72    /// ```rust
73    /// # include!("../doctest_setup.rs");
74    /// #
75    /// # table! {
76    /// #    users {
77    /// #        id -> Integer,
78    /// #        name -> VarChar,
79    /// #    }
80    /// # }
81    /// #
82    /// # fn main() {
83    /// #     use self::users::dsl::*;
84    /// #     use diesel::dsl::sql;
85    /// #     use diesel::sql_types::{Integer, Text, Bool};
86    /// #     let connection = &mut establish_connection();
87    /// #     diesel::insert_into(users).values(name.eq("Ryan"))
88    /// #           .execute(connection).unwrap();
89    /// let query = users
90    ///     .select(name)
91    ///     .filter(
92    ///         sql::<Bool>("id > ")
93    ///             .bind::<Integer, _>(1)
94    ///             .sql(" AND name <> ")
95    ///             .bind::<Text, _>("Ryan"),
96    ///     )
97    ///     .get_results(connection);
98    /// let expected = vec!["Tess".to_string()];
99    /// assert_eq!(Ok(expected), query);
100    /// # }
101    /// ```
102    pub fn bind<BindST, U>(self, bind_value: U) -> UncheckedBind<Self, U::Expression>
103    where
104        BindST: SqlType + TypedExpressionType,
105        U: AsExpression<BindST>,
106    {
107        UncheckedBind::new(self, bind_value.as_expression())
108    }
109
110    /// Append raw SQL to this literal.
111    ///
112    /// The SQL built so far renders first, then the given SQL text. This
113    /// allows interleaving raw SQL fragments with [`bind`] calls when the
114    /// expression DSL cannot express the fragment.
115    ///
116    /// # Safety
117    ///
118    /// Diesel passes the given string to the database as written. It must
119    /// therefore never contain values that come from outside your own code,
120    /// because anything interpolated into the SQL text can carry an SQL
121    /// injection. Pass such values with [`bind`] instead.
122    ///
123    /// # Examples
124    ///
125    /// ```rust
126    /// # include!("../doctest_setup.rs");
127    /// #
128    /// # table! {
129    /// #    users {
130    /// #        id -> Integer,
131    /// #        name -> VarChar,
132    /// #    }
133    /// # }
134    /// #
135    /// # fn main() {
136    /// #     use self::users::dsl::*;
137    /// #     use diesel::dsl::sql;
138    /// #     use diesel::sql_types::Bool;
139    /// #     let connection = &mut establish_connection();
140    /// #     diesel::insert_into(users).values(name.eq("Ryan"))
141    /// #           .execute(connection).unwrap();
142    /// let query = users
143    ///     .select(name)
144    ///     .filter(sql::<Bool>("id > 1").sql(" AND name <> 'Ryan'"))
145    ///     .get_results(connection);
146    /// let expected = vec!["Tess".to_string()];
147    /// assert_eq!(Ok(expected), query);
148    /// # }
149    /// ```
150    ///
151    /// [`bind`]: Self::bind()
152    pub fn sql(self, sql: &str) -> SqlLiteral<ST, Self> {
153        SqlLiteral::new(sql.into(), self)
154    }
155}
156
157impl<ST, T> Expression for SqlLiteral<ST, T>
158where
159    ST: TypedExpressionType,
160{
161    type SqlType = ST;
162}
163
164impl<ST, T, DB> QueryFragment<DB> for SqlLiteral<ST, T>
165where
166    DB: Backend,
167    T: QueryFragment<DB>,
168{
169    fn walk_ast<'b>(&'b self, mut out: AstPass<'_, 'b, DB>) -> QueryResult<()> {
170        out.unsafe_to_cache_prepared();
171        self.inner.walk_ast(out.reborrow())?;
172        out.push_sql(&self.sql);
173        Ok(())
174    }
175}
176
177impl<ST, T> QueryId for SqlLiteral<ST, T> {
178    type QueryId = ();
179
180    const HAS_STATIC_QUERY_ID: bool = false;
181}
182
183impl<ST, T> Query for SqlLiteral<ST, T>
184where
185    Self: Expression,
186{
187    type SqlType = ST;
188}
189
190impl<ST, T> RunQueryDslSupport for SqlLiteral<ST, T> {}
191
192impl<QS, ST, T> SelectableExpression<QS> for SqlLiteral<ST, T> where Self: Expression {}
193
194impl<QS, ST, T> AppearsOnTable<QS> for SqlLiteral<ST, T> where Self: Expression {}
195
196impl<ST, T, GB> ValidGrouping<GB> for SqlLiteral<ST, T> {
197    type IsAggregate = is_aggregate::Never;
198}
199
200/// Use literal SQL in the query builder.
201///
202/// Available for when you truly cannot represent something using the expression
203/// DSL. You will need to provide the SQL type of the expression, in addition to
204/// the SQL.
205///
206/// This function is intended for use when you need a small bit of raw SQL in
207/// your query. If you want to write the entire query using raw SQL, use
208/// [`sql_query`](crate::sql_query()) instead.
209///
210/// Query parameters can be bound into the literal SQL using [`SqlLiteral::bind()`].
211///
212/// # Safety
213///
214/// The compiler will be unable to verify the correctness of the annotated type.
215/// If you give the wrong type, it'll either return an error when deserializing
216/// the query result or produce unexpected values.
217///
218/// Diesel also passes the given string to the database as written. It must
219/// therefore never contain values that come from outside your own code,
220/// because anything interpolated into the SQL text can carry an SQL
221/// injection. Pass such values with [`SqlLiteral::bind()`] instead.
222///
223/// # Examples
224///
225/// ```rust
226/// # include!("../doctest_setup.rs");
227/// # fn main() {
228/// #     run_test_1().unwrap();
229/// #     run_test_2().unwrap();
230/// # }
231/// #
232/// # fn run_test_1() -> QueryResult<()> {
233/// #     use schema::users::dsl::*;
234/// #     use diesel::sql_types::Bool;
235/// use diesel::dsl::sql;
236/// #     let connection = &mut establish_connection();
237/// let user = users
238///     .filter(sql::<Bool>("name = 'Sean'"))
239///     .first(connection)?;
240/// let expected = (1, String::from("Sean"));
241/// assert_eq!(expected, user);
242/// #     Ok(())
243/// # }
244/// #
245/// # fn run_test_2() -> QueryResult<()> {
246/// #     use crate::schema::users::dsl::*;
247/// #     use diesel::dsl::sql;
248/// #     use diesel::sql_types::{Bool, Integer, Text};
249/// #     let connection = &mut establish_connection();
250/// #     diesel::insert_into(users)
251/// #         .values(name.eq("Ryan"))
252/// #         .execute(connection).unwrap();
253/// let query = users
254///     .select(name)
255///     .filter(
256///         sql::<Bool>("id > ")
257///             .bind::<Integer, _>(1)
258///             .sql(" AND name <> ")
259///             .bind::<Text, _>("Ryan"),
260///     )
261///     .get_results(connection);
262/// let expected = vec!["Tess".to_string()];
263/// assert_eq!(Ok(expected), query);
264/// #     Ok(())
265/// # }
266/// ```
267/// [`SqlLiteral::bind()`]: crate::expression::SqlLiteral::bind()
268pub fn sql<ST>(sql: &str) -> SqlLiteral<ST>
269where
270    ST: TypedExpressionType,
271{
272    SqlLiteral::new(sql.into(), self::private::Empty)
273}
274
275#[derive(const _: () =
    {
        use diesel;
        #[allow(non_camel_case_types)]
        impl<Query: diesel::query_builder::QueryId,
            Value: diesel::query_builder::QueryId>
            diesel::query_builder::QueryId for UncheckedBind<Query, Value> {
            type QueryId =
                UncheckedBind<<Query as
                diesel::query_builder::QueryId>::QueryId,
                <Value as diesel::query_builder::QueryId>::QueryId>;
            const HAS_STATIC_QUERY_ID: bool =
                <Query as diesel::query_builder::QueryId>::HAS_STATIC_QUERY_ID
                        &&
                        <Value as
                            diesel::query_builder::QueryId>::HAS_STATIC_QUERY_ID &&
                    true;
            const IS_WINDOW_FUNCTION: bool =
                <Query as diesel::query_builder::QueryId>::IS_WINDOW_FUNCTION
                        ||
                        <Value as
                            diesel::query_builder::QueryId>::IS_WINDOW_FUNCTION ||
                    false;
        }
    };QueryId, #[automatically_derived]
impl<Query: ::core::fmt::Debug, Value: ::core::fmt::Debug> ::core::fmt::Debug
    for UncheckedBind<Query, Value> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f, "UncheckedBind",
            "query", &self.query, "value", &&self.value)
    }
}Debug, #[automatically_derived]
impl<Query: ::core::clone::Clone, Value: ::core::clone::Clone>
    ::core::clone::Clone for UncheckedBind<Query, Value> {
    #[inline]
    fn clone(&self) -> UncheckedBind<Query, Value> {
        UncheckedBind {
            query: ::core::clone::Clone::clone(&self.query),
            value: ::core::clone::Clone::clone(&self.value),
        }
    }
}Clone, #[automatically_derived]
impl<Query: ::core::marker::Copy, Value: ::core::marker::Copy>
    ::core::marker::Copy for UncheckedBind<Query, Value> {
}Copy)]
276#[must_use = "Queries are only executed when calling `load`, `get_result`, or similar."]
277/// Returned by the [`SqlLiteral::bind()`] method when binding a value to a fragment of SQL.
278pub struct UncheckedBind<Query, Value> {
279    query: Query,
280    value: Value,
281}
282
283impl<Query, Value> UncheckedBind<Query, Value>
284where
285    Query: Expression,
286{
287    pub(crate) fn new(query: Query, value: Value) -> Self {
288        UncheckedBind { query, value }
289    }
290
291    /// Append raw SQL after this literal and the values bound to it.
292    ///
293    /// The literal and its bound values render first, then the given SQL
294    /// text. This allows interleaving raw SQL fragments with
295    /// [`SqlLiteral::bind()`] calls when the expression DSL cannot express
296    /// the fragment.
297    ///
298    /// # Safety
299    ///
300    /// Diesel passes the given string to the database as written. It must
301    /// therefore never contain values that come from outside your own code,
302    /// because anything interpolated into the SQL text can carry an SQL
303    /// injection. Pass such values with [`SqlLiteral::bind()`] instead.
304    ///
305    /// # Examples
306    ///
307    /// ```rust
308    /// # include!("../doctest_setup.rs");
309    /// #
310    /// # table! {
311    /// #    users {
312    /// #        id -> Integer,
313    /// #        name -> VarChar,
314    /// #    }
315    /// # }
316    /// #
317    /// # fn main() {
318    /// #     use self::users::dsl::*;
319    /// #     use diesel::dsl::sql;
320    /// #     use diesel::sql_types::{Integer, Bool};
321    /// #     let connection = &mut establish_connection();
322    /// #     diesel::insert_into(users).values(name.eq("Ryan"))
323    /// #           .execute(connection).unwrap();
324    /// let query = users
325    ///     .select(name)
326    ///     .filter(
327    ///         sql::<Bool>("id > ")
328    ///             .bind::<Integer, _>(1)
329    ///             .sql(" AND name <> 'Ryan'"),
330    ///     )
331    ///     .get_results(connection);
332    /// let expected = vec!["Tess".to_string()];
333    /// assert_eq!(Ok(expected), query);
334    /// # }
335    /// ```
336    pub fn sql(self, sql: &str) -> SqlLiteral<Query::SqlType, Self> {
337        SqlLiteral::new(sql.into(), self)
338    }
339}
340
341impl<Query, Value> Expression for UncheckedBind<Query, Value>
342where
343    Query: Expression,
344{
345    type SqlType = Query::SqlType;
346}
347
348impl<Query, Value, DB> QueryFragment<DB> for UncheckedBind<Query, Value>
349where
350    DB: Backend,
351    Query: QueryFragment<DB>,
352    Value: QueryFragment<DB>,
353{
354    fn walk_ast<'b>(&'b self, mut out: AstPass<'_, 'b, DB>) -> QueryResult<()> {
355        self.query.walk_ast(out.reborrow())?;
356        self.value.walk_ast(out.reborrow())?;
357        Ok(())
358    }
359}
360
361impl<Q, Value> Query for UncheckedBind<Q, Value>
362where
363    Q: Query,
364{
365    type SqlType = Q::SqlType;
366}
367
368impl<Query, Value, GB> ValidGrouping<GB> for UncheckedBind<Query, Value> {
369    type IsAggregate = is_aggregate::Never;
370}
371
372impl<QS, Query, Value> SelectableExpression<QS> for UncheckedBind<Query, Value> where
373    Self: AppearsOnTable<QS>
374{
375}
376
377impl<QS, Query, Value> AppearsOnTable<QS> for UncheckedBind<Query, Value> where Self: Expression {}
378
379impl<Query, Value> RunQueryDslSupport for UncheckedBind<Query, Value> {}
380
381mod private {
382    use crate::backend::{Backend, DieselReserveSpecialization};
383    use crate::query_builder::{QueryFragment, QueryId};
384
385    #[derive(#[automatically_derived]
impl ::core::fmt::Debug for Empty {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f, "Empty")
    }
}Debug, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for Empty { }
#[automatically_derived]
impl ::core::clone::Clone for Empty {
    #[inline]
    fn clone(&self) -> Empty { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for Empty { }Copy, const _: () =
    {
        use diesel;
        #[allow(non_camel_case_types)]
        impl diesel::query_builder::QueryId for Empty {
            type QueryId = Empty<>;
            const HAS_STATIC_QUERY_ID: bool = true;
            const IS_WINDOW_FUNCTION: bool = false;
        }
    };QueryId)]
386    pub struct Empty;
387
388    impl<DB> QueryFragment<DB> for Empty
389    where
390        DB: Backend + DieselReserveSpecialization,
391    {
392        fn walk_ast<'b>(
393            &'b self,
394            _pass: crate::query_builder::AstPass<'_, 'b, DB>,
395        ) -> crate::QueryResult<()> {
396            Ok(())
397        }
398    }
399}