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;
21mod 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#[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;
85#[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#[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#[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#[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#[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#[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 std::error::Error;
140
141#[doc(hidden)]
142pub type Binds = Vec<Option<Vec<u8>>>;
143/// A specialized Result type used with the query builder.
144pub type BuildQueryResult = Result<(), Box<dyn Error + Send + Sync>>;
145
146/// Constructs a SQL query from a Diesel AST.
147///
148/// The only reason you should ever need to interact with this trait is if you
149/// are extending Diesel with support for a new backend. Plugins which extend
150/// the query builder with new capabilities will interact with [`AstPass`]
151/// instead.
152///
153pub trait QueryBuilder<DB: Backend> {
154    /// Add `sql` to the end of the query being constructed.
155    fn push_sql(&mut self, sql: &str);
156
157    /// Quote `identifier`, and add it to the end of the query being
158    /// constructed.
159    fn push_identifier(&mut self, identifier: &str) -> QueryResult<()>;
160
161    /// Add a placeholder for a bind parameter to the end of the query being
162    /// constructed.
163    fn push_bind_param(&mut self);
164
165    /// Increases the internal counter for bind parameters without adding the
166    /// bind parameter itself to the query
167    fn push_bind_param_value_only(&mut self) {}
168
169    /// Returns the constructed SQL query.
170    fn finish(self) -> String;
171}
172
173/// A complete SQL query with a return type.
174///
175/// This can be a select statement, or a command such as `update` or `insert`
176/// with a `RETURNING` clause. Unlike [`Expression`], types implementing this
177/// trait are guaranteed to be executable on their own.
178///
179/// A type which doesn't implement this trait may still represent a complete SQL
180/// query. For example, an `INSERT` statement without a `RETURNING` clause will
181/// not implement this trait, but can still be executed.
182///
183/// [`Expression`]: crate::expression::Expression
184pub trait Query {
185    /// The SQL type that this query represents.
186    ///
187    /// This is the SQL type of the `SELECT` clause for select statements, and
188    /// the SQL type of the `RETURNING` clause for insert, update, or delete
189    /// statements.
190    type SqlType;
191}
192
193impl<T: Query> Query for &T {
194    type SqlType = T::SqlType;
195}
196
197/// Indicates that a type is a `SELECT` statement.
198///
199/// This trait differs from `Query` in two ways:
200/// - It is implemented only for select statements, rather than all queries
201///   which return a value.
202/// - It has looser constraints. A type implementing `SelectQuery` is known to
203///   be potentially valid if used as a subselect, but it is not necessarily
204///   able to be executed.
205pub trait SelectQuery {
206    /// The SQL type of the `SELECT` clause
207    type SqlType;
208}
209
210/// An untyped fragment of SQL.
211///
212/// This may be a complete SQL command (such as an update statement without a
213/// `RETURNING` clause), or a subsection (such as our internal types used to
214/// represent a `WHERE` clause). Implementations of [`ExecuteDsl`] and
215/// [`LoadQuery`] will generally require that this trait be implemented.
216///
217/// [`ExecuteDsl`]: crate::query_dsl::methods::ExecuteDsl
218/// [`LoadQuery`]: crate::query_dsl::methods::LoadQuery
219#[diagnostic::on_unimplemented(
220    message = "`{Self}` is no valid SQL fragment for the `{DB}` backend",
221    note = "this usually means that the `{DB}` database system does not support \n\
222            this SQL syntax"
223)]
224pub trait QueryFragment<DB: Backend, SP = self::private::NotSpecialized> {
225    /// Walk over this `QueryFragment` for all passes.
226    ///
227    /// This method is where the actual behavior of an AST node is implemented.
228    /// This method will contain the behavior required for all possible AST
229    /// passes. See [`AstPass`] for more details.
230    ///
231    fn walk_ast<'b>(&'b self, pass: AstPass<'_, 'b, DB>) -> QueryResult<()>;
232
233    /// Converts this `QueryFragment` to its SQL representation.
234    ///
235    /// This method should only be called by implementations of `Connection`.
236    #[diesel_derives::__diesel_public_if(
237        feature = "i-implement-a-third-party-backend-and-opt-into-breaking-changes"
238    )]
239    fn to_sql(&self, out: &mut DB::QueryBuilder, backend: &DB) -> QueryResult<()> {
240        let mut options = AstPassToSqlOptions::default();
241        self.walk_ast(AstPass::to_sql(out, &mut options, backend))
242    }
243
244    /// Serializes all bind parameters in this query.
245    ///
246    /// A bind parameter is a value which is sent separately from the query
247    /// itself. It is represented in SQL with a placeholder such as `?` or `$1`.
248    ///
249    /// This method should only be called by implementations of `Connection`.
250    #[diesel_derives::__diesel_public_if(
251        feature = "i-implement-a-third-party-backend-and-opt-into-breaking-changes"
252    )]
253    fn collect_binds<'b>(
254        &'b self,
255        out: &mut DB::BindCollector<'b>,
256        metadata_lookup: &mut DB::MetadataLookup,
257        backend: &'b DB,
258    ) -> QueryResult<()> {
259        self.walk_ast(AstPass::collect_binds(out, metadata_lookup, backend))
260    }
261
262    /// Is this query safe to store in the prepared statement cache?
263    ///
264    /// In order to keep our prepared statement cache at a reasonable size, we
265    /// avoid caching any queries which represent a potentially unbounded number
266    /// of SQL queries. Generally this will only return `true` for queries for
267    /// which `to_sql` will always construct exactly identical SQL.
268    ///
269    /// Some examples of where this method will return `false` are:
270    ///
271    /// - `SqlLiteral` (We don't know if the SQL was constructed dynamically, so
272    ///   we must assume that it was)
273    /// - `In` and `NotIn` (Each value requires a separate bind param
274    ///   placeholder)
275    ///
276    /// This method should only be called by implementations of `Connection`.
277    #[diesel_derives::__diesel_public_if(
278        feature = "i-implement-a-third-party-backend-and-opt-into-breaking-changes"
279    )]
280    fn is_safe_to_cache_prepared(&self, backend: &DB) -> QueryResult<bool> {
281        let mut result = true;
282        self.walk_ast(AstPass::is_safe_to_cache_prepared(&mut result, backend))?;
283        Ok(result)
284    }
285
286    /// Does walking this AST have any effect?
287    #[diesel_derives::__diesel_public_if(
288        feature = "i-implement-a-third-party-backend-and-opt-into-breaking-changes"
289    )]
290    fn is_noop(&self, backend: &DB) -> QueryResult<bool> {
291        let mut result = true;
292        self.walk_ast(AstPass::is_noop(&mut result, backend))?;
293        Ok(result)
294    }
295}
296
297impl<T: ?Sized, DB> QueryFragment<DB> for Box<T>
298where
299    DB: Backend,
300    T: QueryFragment<DB>,
301{
302    fn walk_ast<'b>(&'b self, pass: AstPass<'_, 'b, DB>) -> QueryResult<()> {
303        QueryFragment::walk_ast(&**self, pass)
304    }
305}
306
307impl<T: ?Sized, DB> QueryFragment<DB> for &T
308where
309    DB: Backend,
310    T: QueryFragment<DB>,
311{
312    fn walk_ast<'b>(&'b self, pass: AstPass<'_, 'b, DB>) -> QueryResult<()> {
313        QueryFragment::walk_ast(&**self, pass)
314    }
315}
316
317impl<DB: Backend> QueryFragment<DB> for () {
318    fn walk_ast<'b>(&'b self, _: AstPass<'_, 'b, DB>) -> QueryResult<()> {
319        Ok(())
320    }
321}
322
323impl<T, DB> QueryFragment<DB> for Option<T>
324where
325    DB: Backend,
326    T: QueryFragment<DB>,
327{
328    fn walk_ast<'b>(&'b self, out: AstPass<'_, 'b, DB>) -> QueryResult<()> {
329        match *self {
330            Some(ref c) => c.walk_ast(out),
331            None => Ok(()),
332        }
333    }
334}
335
336/// A trait used to construct type erased boxed variant of the current query node
337///
338/// Mainly useful for implementing third party backends
339pub trait IntoBoxedClause<'a, DB> {
340    /// Resulting type
341    type BoxedClause;
342
343    /// Convert the given query node in it's boxed representation
344    fn into_boxed(self) -> Self::BoxedClause;
345}
346
347/// Types that can be converted into a complete, typed SQL query.
348///
349/// This is used internally to automatically add the right select clause when
350/// none is specified, or to automatically add `RETURNING *` in certain contexts.
351///
352/// A type which implements this trait is guaranteed to be valid for execution.
353pub trait AsQuery {
354    /// The SQL type of `Self::Query`
355    type SqlType;
356
357    /// What kind of query does this type represent?
358    type Query: Query<SqlType = Self::SqlType>;
359
360    /// Converts a type which semantically represents a SQL query into the
361    /// actual query being executed. See the trait level docs for more.
362    // This method is part of our public API,
363    // so we won't change the name to just appease clippy
364    // (Also the trait is literally named `AsQuery` so
365    // naming the method similarity is fine)
366    #[allow(clippy::wrong_self_convention)]
367    fn as_query(self) -> Self::Query;
368}
369
370impl<T: Query> AsQuery for T {
371    type SqlType = <T as Query>::SqlType;
372    type Query = T;
373
374    fn as_query(self) -> <T as AsQuery>::Query {
375        self
376    }
377}
378
379/// Takes a query `QueryFragment` expression as an argument and returns a type
380/// that implements `fmt::Display` and `fmt::Debug` to show the query.
381///
382/// The `Display` implementation will show the exact query being sent to the
383/// server, with a comment showing the values of the bind parameters. The
384/// `Debug` implementation will include the same information in a more
385/// structured form, and respects pretty printing.
386///
387/// # Example
388///
389/// ### Returning SQL from a count statement:
390///
391/// ```rust
392/// # include!("../doctest_setup.rs");
393/// #
394/// # use diesel::*;
395/// # use schema::*;
396/// #
397/// # fn main() {
398/// #   use schema::users::dsl::*;
399/// let sql = debug_query::<DB, _>(&users.count()).to_string();
400/// # if cfg!(feature = "postgres") {
401/// #     assert_eq!(sql, r#"SELECT COUNT(*) FROM "users" -- binds: []"#);
402/// # } else {
403/// assert_eq!(sql, "SELECT COUNT(*) FROM `users` -- binds: []");
404/// # }
405///
406/// let query = users.find(1);
407/// let debug = debug_query::<DB, _>(&query);
408/// # if cfg!(feature = "postgres") {
409/// #     assert_eq!(debug.to_string(), "SELECT \"users\".\"id\", \"users\".\"name\" \
410/// #         FROM \"users\" WHERE (\"users\".\"id\" = $1) -- binds: [1]");
411/// # } else {
412/// assert_eq!(debug.to_string(), "SELECT `users`.`id`, `users`.`name` FROM `users` \
413///     WHERE (`users`.`id` = ?) -- binds: [1]");
414/// # }
415///
416/// let debug = format!("{:?}", debug);
417/// # if !cfg!(feature = "postgres") { // Escaping that string is a pain
418/// let expected = "Query { \
419///     sql: \"SELECT `users`.`id`, `users`.`name` FROM `users` WHERE \
420///         (`users`.`id` = ?)\", \
421///     binds: [1] \
422/// }";
423/// assert_eq!(debug, expected);
424/// # }
425/// # }
426/// ```
427pub fn debug_query<DB, T>(query: &T) -> DebugQuery<'_, T, DB> {
428    DebugQuery::new(query)
429}
430
431mod private {
432    #[allow(missing_debug_implementations, missing_copy_implementations)]
433    pub struct NotSpecialized;
434}