Skip to main content

diesel/query_builder/
mod.rs

1//! Contains traits responsible for the actual construction of SQL statements
2//!
3//! The types in this module are part of Diesel's public API, but are generally
4//! only useful for implementing Diesel plugins. Applications should generally
5//! not need to care about the types inside of this module.
6
7#[macro_use]
8mod query_id;
9#[macro_use]
10mod clause_macro;
11
12pub(crate) mod ast_pass;
13pub mod bind_collector;
14mod collected_query;
15pub(crate) mod combination_clause;
16mod debug_query;
17mod delete_statement;
18mod distinct_clause;
19pub(crate) mod from_clause;
20pub(crate) mod functions;
21pub(crate) mod group_by_clause;
22mod having_clause;
23pub(crate) mod insert_statement;
24pub(crate) mod limit_clause;
25pub(crate) mod limit_offset_clause;
26pub(crate) mod locking_clause;
27pub(crate) mod nodes;
28pub(crate) mod offset_clause;
29pub(crate) mod order_clause;
30pub(crate) mod returning_clause;
31pub(crate) mod select_clause;
32pub(crate) mod select_statement;
33mod sql_query;
34pub(crate) mod update_statement;
35pub(crate) mod upsert;
36pub(crate) mod where_clause;
37
38#[doc(inline)]
39pub use self::ast_pass::AstPass;
40#[doc(inline)]
41pub use self::bind_collector::{BindCollector, MoveableBindCollector};
42#[doc(inline)]
43pub use self::collected_query::CollectedQuery;
44#[doc(inline)]
45pub use self::debug_query::DebugQuery;
46#[doc(inline)]
47pub use self::delete_statement::{BoxedDeleteStatement, DeleteStatement};
48#[doc(inline)]
49pub use self::insert_statement::{
50    IncompleteInsertOrIgnoreStatement, IncompleteInsertStatement, IncompleteReplaceStatement,
51    InsertOrIgnoreStatement, InsertStatement, ReplaceStatement,
52};
53#[doc(inline)]
54pub use self::query_id::QueryId;
55#[doc(inline)]
56pub use self::sql_query::{BoxedSqlQuery, SqlQuery};
57#[doc(inline)]
58pub use self::upsert::on_conflict_target_decorations::DecoratableTarget;
59
60#[doc(inline)]
61pub use self::update_statement::changeset::AsChangeset;
62#[doc(inline)]
63pub use self::update_statement::target::{IntoUpdateTarget, UpdateTarget};
64#[doc(inline)]
65pub use self::update_statement::{BoxedUpdateStatement, UpdateStatement};
66
67#[cfg(feature = "i-implement-a-third-party-backend-and-opt-into-breaking-changes")]
68pub use self::combination_clause::{
69    All, Distinct, Except, Intersect, ParenthesisWrapper, SupportsCombinationClause, Union,
70};
71#[cfg(feature = "i-implement-a-third-party-backend-and-opt-into-breaking-changes")]
72pub use self::limit_clause::{LimitClause, NoLimitClause};
73#[cfg(feature = "i-implement-a-third-party-backend-and-opt-into-breaking-changes")]
74pub use self::limit_offset_clause::{BoxedLimitOffsetClause, LimitOffsetClause};
75#[cfg(feature = "i-implement-a-third-party-backend-and-opt-into-breaking-changes")]
76pub use self::offset_clause::{NoOffsetClause, OffsetClause};
77#[cfg(feature = "i-implement-a-third-party-backend-and-opt-into-breaking-changes")]
78pub use self::order_clause::{NoOrderClause, OrderClause};
79
80#[doc(inline)]
pub use self::insert_statement::batch_insert::BatchInsert;#[diesel_derives::__diesel_public_if(
81    feature = "i-implement-a-third-party-backend-and-opt-into-breaking-changes"
82)]
83#[doc(inline)]
84pub(crate) use self::insert_statement::batch_insert::BatchInsert;
85pub use self::insert_statement::{UndecoratedInsertRecord, ValuesClause};#[diesel_derives::__diesel_public_if(
86    feature = "i-implement-a-third-party-backend-and-opt-into-breaking-changes"
87)]
88pub(crate) use self::insert_statement::{UndecoratedInsertRecord, ValuesClause};
89
90#[cfg(feature = "i-implement-a-third-party-backend-and-opt-into-breaking-changes")]
91#[doc(inline)]
92pub use self::insert_statement::{DefaultValues, InsertOrIgnore, Replace};
93
94#[cfg(feature = "i-implement-a-third-party-backend-and-opt-into-breaking-changes")]
95#[doc(inline)]
96pub use self::returning_clause::ReturningClause;
97
98#[doc(inline)]
99#[doc(inline)]
pub use self::ast_pass::AstPassToSqlOptions;#[diesel_derives::__diesel_public_if(
100    feature = "i-implement-a-third-party-backend-and-opt-into-breaking-changes"
101)]
102pub(crate) use self::ast_pass::AstPassToSqlOptions;
103
104#[doc(inline)]
105#[doc(inline)]
pub use self::select_clause::SelectClauseExpression;#[diesel_derives::__diesel_public_if(
106    feature = "i-implement-a-third-party-backend-and-opt-into-breaking-changes"
107)]
108pub(crate) use self::select_clause::SelectClauseExpression;
109
110#[doc(inline)]
111#[doc(inline)]
pub use self::from_clause::{FromClause, NoFromClause};#[diesel_derives::__diesel_public_if(
112    feature = "i-implement-a-third-party-backend-and-opt-into-breaking-changes"
113)]
114pub(crate) use self::from_clause::{FromClause, NoFromClause};
115#[doc(inline)]
pub use self::select_statement::BoxedSelectStatement;#[diesel_derives::__diesel_public_if(
116    feature = "i-implement-a-third-party-backend-and-opt-into-breaking-changes"
117)]
118#[doc(inline)]
119pub(crate) use self::select_statement::BoxedSelectStatement;
120
121#[doc(inline)]
pub use self::select_statement::SelectStatement;#[diesel_derives::__diesel_public_if(
122    feature = "i-implement-a-third-party-backend-and-opt-into-breaking-changes"
123)]
124#[doc(inline)]
125pub(crate) use self::select_statement::SelectStatement;
126
127pub(crate) use self::insert_statement::ColumnList;
128
129#[cfg(feature = "postgres_backend")]
130pub use crate::pg::query_builder::only::Only;
131
132#[cfg(feature = "postgres_backend")]
133pub use crate::pg::query_builder::tablesample::{Tablesample, TablesampleMethod};
134
135#[cfg(feature = "postgres_backend")]
136pub(crate) use self::bind_collector::ByteWrapper;
137use crate::backend::Backend;
138use crate::result::QueryResult;
139use alloc::boxed::Box;
140use alloc::string::String;
141use alloc::vec::Vec;
142use core::error::Error;
143
144pub(crate) use self::private::NotSpecialized;
145
146#[doc(hidden)]
147pub type Binds = Vec<Option<Vec<u8>>>;
148/// A specialized Result type used with the query builder.
149pub type BuildQueryResult = Result<(), Box<dyn Error + Send + Sync>>;
150
151/// Constructs a SQL query from a Diesel AST.
152///
153/// The only reason you should ever need to interact with this trait is if you
154/// are extending Diesel with support for a new backend. Plugins which extend
155/// the query builder with new capabilities will interact with [`AstPass`]
156/// instead.
157pub trait QueryBuilder<DB: Backend> {
158    /// Add `sql` to the end of the query being constructed.
159    fn push_sql(&mut self, sql: &str);
160
161    /// Quote `identifier`, and add it to the end of the query being
162    /// constructed.
163    fn push_identifier(&mut self, identifier: &str) -> QueryResult<()>;
164
165    /// Add a placeholder for a bind parameter to the end of the query being
166    /// constructed.
167    fn push_bind_param(&mut self);
168
169    /// Increases the internal counter for bind parameters without adding the
170    /// bind parameter itself to the query
171    fn push_bind_param_value_only(&mut self) {}
172
173    /// Returns the constructed SQL query.
174    fn finish(self) -> String;
175}
176
177/// A complete SQL query with a return type.
178///
179/// This can be a select statement, or a command such as `update` or `insert`
180/// with a `RETURNING` clause. Unlike [`Expression`], types implementing this
181/// trait are guaranteed to be executable on their own.
182///
183/// A type which doesn't implement this trait may still represent a complete SQL
184/// query. For example, an `INSERT` statement without a `RETURNING` clause will
185/// not implement this trait, but can still be executed.
186///
187/// [`Expression`]: crate::expression::Expression
188pub trait Query {
189    /// The SQL type that this query represents.
190    ///
191    /// This is the SQL type of the `SELECT` clause for select statements, and
192    /// the SQL type of the `RETURNING` clause for insert, update, or delete
193    /// statements.
194    type SqlType;
195}
196
197impl<T: Query> Query for &T {
198    type SqlType = T::SqlType;
199}
200
201/// Indicates that a type is a `SELECT` statement.
202///
203/// This trait differs from `Query` in two ways:
204/// - It is implemented only for select statements, rather than all queries
205///   which return a value.
206/// - It has looser constraints. A type implementing `SelectQuery` is known to
207///   be potentially valid if used as a subselect, but it is not necessarily
208///   able to be executed.
209pub trait SelectQuery {
210    /// The SQL type of the `SELECT` clause
211    type SqlType;
212}
213
214/// An untyped fragment of SQL.
215///
216/// This may be a complete SQL command (such as an update statement without a
217/// `RETURNING` clause), or a subsection (such as our internal types used to
218/// represent a `WHERE` clause). Implementations of [`ExecuteDsl`] and
219/// [`LoadQuery`] will generally require that this trait be implemented.
220///
221/// [`ExecuteDsl`]: crate::query_dsl::methods::ExecuteDsl
222/// [`LoadQuery`]: crate::query_dsl::methods::LoadQuery
223#[diagnostic::on_unimplemented(
224    message = "`{Self}` is no valid SQL fragment for the `{DB}` backend",
225    note = "this usually means that the `{DB}` database system does not support \n\
226            this SQL syntax"
227)]
228pub trait QueryFragment<DB: Backend, SP = self::private::NotSpecialized> {
229    /// Walk over this `QueryFragment` for all passes.
230    ///
231    /// This method is where the actual behavior of an AST node is implemented.
232    /// This method will contain the behavior required for all possible AST
233    /// passes. See [`AstPass`] for more details.
234    fn walk_ast<'b>(&'b self, pass: AstPass<'_, 'b, DB>) -> QueryResult<()>;
235
236    /// Converts this `QueryFragment` to its SQL representation.
237    ///
238    /// This method should only be called by implementations of `Connection`.
239    #[diesel_derives::__diesel_public_if(
240        feature = "i-implement-a-third-party-backend-and-opt-into-breaking-changes"
241    )]
242    fn to_sql(&self, out: &mut DB::QueryBuilder, backend: &DB) -> QueryResult<()> {
243        let mut options = AstPassToSqlOptions::default();
244        self.walk_ast(AstPass::to_sql(out, &mut options, backend))
245    }
246
247    /// Serializes all bind parameters in this query.
248    ///
249    /// A bind parameter is a value which is sent separately from the query
250    /// itself. It is represented in SQL with a placeholder such as `?` or `$1`.
251    ///
252    /// This method should only be called by implementations of `Connection`.
253    #[diesel_derives::__diesel_public_if(
254        feature = "i-implement-a-third-party-backend-and-opt-into-breaking-changes"
255    )]
256    fn collect_binds<'b>(
257        &'b self,
258        out: &mut DB::BindCollector<'b>,
259        metadata_lookup: &mut DB::MetadataLookup,
260        backend: &'b DB,
261    ) -> QueryResult<()> {
262        self.walk_ast(AstPass::collect_binds(out, metadata_lookup, backend))
263    }
264
265    /// Is this query safe to store in the prepared statement cache?
266    ///
267    /// In order to keep our prepared statement cache at a reasonable size, we
268    /// avoid caching any queries which represent a potentially unbounded number
269    /// of SQL queries. Generally this will only return `true` for queries for
270    /// which `to_sql` will always construct exactly identical SQL.
271    ///
272    /// Some examples of where this method will return `false` are:
273    ///
274    /// - `SqlLiteral` (We don't know if the SQL was constructed dynamically, so
275    ///   we must assume that it was)
276    /// - `In` and `NotIn` (Each value requires a separate bind param
277    ///   placeholder)
278    ///
279    /// This method should only be called by implementations of `Connection`.
280    #[diesel_derives::__diesel_public_if(
281        feature = "i-implement-a-third-party-backend-and-opt-into-breaking-changes"
282    )]
283    fn is_safe_to_cache_prepared(&self, backend: &DB) -> QueryResult<bool> {
284        let mut result = true;
285        self.walk_ast(AstPass::is_safe_to_cache_prepared(&mut result, backend))?;
286        Ok(result)
287    }
288
289    /// Does walking this AST have any effect?
290    #[diesel_derives::__diesel_public_if(
291        feature = "i-implement-a-third-party-backend-and-opt-into-breaking-changes"
292    )]
293    fn is_noop(&self, backend: &DB) -> QueryResult<bool> {
294        let mut result = true;
295        self.walk_ast(AstPass::is_noop(&mut result, backend))?;
296        Ok(result)
297    }
298}
299
300impl<T: ?Sized, DB> QueryFragment<DB> for Box<T>
301where
302    DB: Backend,
303    T: QueryFragment<DB>,
304{
305    fn walk_ast<'b>(&'b self, pass: AstPass<'_, 'b, DB>) -> QueryResult<()> {
306        QueryFragment::walk_ast(&**self, pass)
307    }
308}
309
310impl<T: ?Sized, DB> QueryFragment<DB> for &T
311where
312    DB: Backend,
313    T: QueryFragment<DB>,
314{
315    fn walk_ast<'b>(&'b self, pass: AstPass<'_, 'b, DB>) -> QueryResult<()> {
316        QueryFragment::walk_ast(&**self, pass)
317    }
318}
319
320impl<DB: Backend> QueryFragment<DB> for () {
321    fn walk_ast<'b>(&'b self, _: AstPass<'_, 'b, DB>) -> QueryResult<()> {
322        Ok(())
323    }
324}
325
326impl<T, DB> QueryFragment<DB> for Option<T>
327where
328    DB: Backend,
329    T: QueryFragment<DB>,
330{
331    fn walk_ast<'b>(&'b self, out: AstPass<'_, 'b, DB>) -> QueryResult<()> {
332        match *self {
333            Some(ref c) => c.walk_ast(out),
334            None => Ok(()),
335        }
336    }
337}
338
339/// A trait used to construct type erased boxed variant of the current query node
340///
341/// Mainly useful for implementing third party backends
342#[diagnostic::on_unimplemented(
343    note = "this usually means that `{Self}` is no valid SQL for `{DB}`"
344)]
345pub trait IntoBoxedClause<'a, DB> {
346    /// Resulting type
347    type BoxedClause;
348
349    /// Convert the given query node in it's boxed representation
350    fn into_boxed(self) -> Self::BoxedClause;
351}
352
353/// Types that can be converted into a complete, typed SQL query.
354///
355/// This is used internally to automatically add the right select clause when
356/// none is specified, or to automatically add `RETURNING *` in certain contexts.
357///
358/// A type which implements this trait is guaranteed to be valid for execution.
359pub trait AsQuery {
360    /// The SQL type of `Self::Query`
361    type SqlType;
362
363    /// What kind of query does this type represent?
364    type Query: Query<SqlType = Self::SqlType>;
365
366    /// Converts a type which semantically represents a SQL query into the
367    /// actual query being executed. See the trait level docs for more.
368    // This method is part of our public API,
369    // so we won't change the name to just appease clippy
370    // (Also the trait is literally named `AsQuery` so
371    // naming the method similarity is fine)
372    #[allow(clippy::wrong_self_convention)]
373    fn as_query(self) -> Self::Query;
374}
375
376impl<T: Query> AsQuery for T {
377    type SqlType = <T as Query>::SqlType;
378    type Query = T;
379
380    fn as_query(self) -> <T as AsQuery>::Query {
381        self
382    }
383}
384
385/// Takes a query `QueryFragment` expression as an argument and returns a type
386/// that implements `fmt::Display` and `fmt::Debug` to show the query.
387///
388/// The `Display` implementation will show the exact query being sent to the
389/// server, with a comment showing the values of the bind parameters. The
390/// `Debug` implementation will include the same information in a more
391/// structured form, and respects pretty printing.
392///
393/// # Example
394///
395/// ### Returning SQL from a count statement:
396///
397/// ```rust
398/// # include!("../doctest_setup.rs");
399/// #
400/// # use diesel::*;
401/// # use schema::*;
402/// #
403/// # fn main() {
404/// #   use schema::users::dsl::*;
405/// let sql = debug_query::<DB, _>(&users.count()).to_string();
406/// # if cfg!(feature = "postgres") {
407/// #     assert_eq!(sql, r#"SELECT COUNT(*) FROM "users" -- binds: []"#);
408/// # } else {
409/// assert_eq!(sql, "SELECT COUNT(*) FROM `users` -- binds: []");
410/// # }
411///
412/// let query = users.find(1);
413/// let debug = debug_query::<DB, _>(&query);
414/// # if cfg!(feature = "postgres") {
415/// #     assert_eq!(debug.to_string(), "SELECT \"users\".\"id\", \"users\".\"name\" \
416/// #         FROM \"users\" WHERE (\"users\".\"id\" = $1) -- binds: [1]");
417/// # } else {
418/// assert_eq!(
419///     debug.to_string(),
420///     "SELECT `users`.`id`, `users`.`name` FROM `users` \
421///     WHERE (`users`.`id` = ?) -- binds: [1]"
422/// );
423/// # }
424///
425/// let debug = format!("{:?}", debug);
426/// # if !cfg!(feature = "postgres") { // Escaping that string is a pain
427/// let expected = "Query { \
428///     sql: \"SELECT `users`.`id`, `users`.`name` FROM `users` WHERE \
429///         (`users`.`id` = ?)\", \
430///     binds: [1] \
431/// }";
432/// assert_eq!(debug, expected);
433/// # }
434/// # }
435/// ```
436pub fn debug_query<DB, T>(query: &T) -> DebugQuery<'_, T, DB> {
437    DebugQuery::new(query)
438}
439
440mod private {
441    #[allow(missing_debug_implementations, missing_copy_implementations)]
442    pub struct NotSpecialized;
443}
444
445pub(crate) mod has_query;