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