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#[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
141pub(crate) use self::private::NotSpecialized;
142
143#[doc(hidden)]
144pub type Binds = Vec<Option<Vec<u8>>>;
145/// A specialized Result type used with the query builder.
146pub type BuildQueryResult = Result<(), Box<dyn Error + Send + Sync>>;
147
148/// Constructs a SQL query from a Diesel AST.
149///
150/// The only reason you should ever need to interact with this trait is if you
151/// are extending Diesel with support for a new backend. Plugins which extend
152/// the query builder with new capabilities will interact with [`AstPass`]
153/// instead.
154pub trait QueryBuilder<DB: Backend> {
155    /// Add `sql` to the end of the query being constructed.
156    fn push_sql(&mut self, sql: &str);
157
158    /// Quote `identifier`, and add it to the end of the query being
159    /// constructed.
160    fn push_identifier(&mut self, identifier: &str) -> QueryResult<()>;
161
162    /// Add a placeholder for a bind parameter to the end of the query being
163    /// constructed.
164    fn push_bind_param(&mut self);
165
166    /// Increases the internal counter for bind parameters without adding the
167    /// bind parameter itself to the query
168    fn push_bind_param_value_only(&mut self) {}
169
170    /// Returns the constructed SQL query.
171    fn finish(self) -> String;
172}
173
174/// A complete SQL query with a return type.
175///
176/// This can be a select statement, or a command such as `update` or `insert`
177/// with a `RETURNING` clause. Unlike [`Expression`], types implementing this
178/// trait are guaranteed to be executable on their own.
179///
180/// A type which doesn't implement this trait may still represent a complete SQL
181/// query. For example, an `INSERT` statement without a `RETURNING` clause will
182/// not implement this trait, but can still be executed.
183///
184/// [`Expression`]: crate::expression::Expression
185pub trait Query {
186    /// The SQL type that this query represents.
187    ///
188    /// This is the SQL type of the `SELECT` clause for select statements, and
189    /// the SQL type of the `RETURNING` clause for insert, update, or delete
190    /// statements.
191    type SqlType;
192}
193
194impl<T: Query> Query for &T {
195    type SqlType = T::SqlType;
196}
197
198/// Indicates that a type is a `SELECT` statement.
199///
200/// This trait differs from `Query` in two ways:
201/// - It is implemented only for select statements, rather than all queries
202///   which return a value.
203/// - It has looser constraints. A type implementing `SelectQuery` is known to
204///   be potentially valid if used as a subselect, but it is not necessarily
205///   able to be executed.
206pub trait SelectQuery {
207    /// The SQL type of the `SELECT` clause
208    type SqlType;
209}
210
211/// An untyped fragment of SQL.
212///
213/// This may be a complete SQL command (such as an update statement without a
214/// `RETURNING` clause), or a subsection (such as our internal types used to
215/// represent a `WHERE` clause). Implementations of [`ExecuteDsl`] and
216/// [`LoadQuery`] will generally require that this trait be implemented.
217///
218/// [`ExecuteDsl`]: crate::query_dsl::methods::ExecuteDsl
219/// [`LoadQuery`]: crate::query_dsl::methods::LoadQuery
220#[diagnostic::on_unimplemented(
221    message = "`{Self}` is no valid SQL fragment for the `{DB}` backend",
222    note = "this usually means that the `{DB}` database system does not support \n\
223            this SQL syntax"
224)]
225pub trait QueryFragment<DB: Backend, SP = self::private::NotSpecialized> {
226    /// Walk over this `QueryFragment` for all passes.
227    ///
228    /// This method is where the actual behavior of an AST node is implemented.
229    /// This method will contain the behavior required for all possible AST
230    /// passes. See [`AstPass`] for more details.
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
339#[diagnostic::on_unimplemented(
340    note = "this usually means that `{Self}` is no valid SQL for `{DB}`"
341)]
342pub trait IntoBoxedClause<'a, DB> {
343    /// Resulting type
344    type BoxedClause;
345
346    /// Convert the given query node in it's boxed representation
347    fn into_boxed(self) -> Self::BoxedClause;
348}
349
350/// Types that can be converted into a complete, typed SQL query.
351///
352/// This is used internally to automatically add the right select clause when
353/// none is specified, or to automatically add `RETURNING *` in certain contexts.
354///
355/// A type which implements this trait is guaranteed to be valid for execution.
356pub trait AsQuery {
357    /// The SQL type of `Self::Query`
358    type SqlType;
359
360    /// What kind of query does this type represent?
361    type Query: Query<SqlType = Self::SqlType>;
362
363    /// Converts a type which semantically represents a SQL query into the
364    /// actual query being executed. See the trait level docs for more.
365    // This method is part of our public API,
366    // so we won't change the name to just appease clippy
367    // (Also the trait is literally named `AsQuery` so
368    // naming the method similarity is fine)
369    #[allow(clippy::wrong_self_convention)]
370    fn as_query(self) -> Self::Query;
371}
372
373impl<T: Query> AsQuery for T {
374    type SqlType = <T as Query>::SqlType;
375    type Query = T;
376
377    fn as_query(self) -> <T as AsQuery>::Query {
378        self
379    }
380}
381
382/// Takes a query `QueryFragment` expression as an argument and returns a type
383/// that implements `fmt::Display` and `fmt::Debug` to show the query.
384///
385/// The `Display` implementation will show the exact query being sent to the
386/// server, with a comment showing the values of the bind parameters. The
387/// `Debug` implementation will include the same information in a more
388/// structured form, and respects pretty printing.
389///
390/// # Example
391///
392/// ### Returning SQL from a count statement:
393///
394/// ```rust
395/// # include!("../doctest_setup.rs");
396/// #
397/// # use diesel::*;
398/// # use schema::*;
399/// #
400/// # fn main() {
401/// #   use schema::users::dsl::*;
402/// let sql = debug_query::<DB, _>(&users.count()).to_string();
403/// # if cfg!(feature = "postgres") {
404/// #     assert_eq!(sql, r#"SELECT COUNT(*) FROM "users" -- binds: []"#);
405/// # } else {
406/// assert_eq!(sql, "SELECT COUNT(*) FROM `users` -- binds: []");
407/// # }
408///
409/// let query = users.find(1);
410/// let debug = debug_query::<DB, _>(&query);
411/// # if cfg!(feature = "postgres") {
412/// #     assert_eq!(debug.to_string(), "SELECT \"users\".\"id\", \"users\".\"name\" \
413/// #         FROM \"users\" WHERE (\"users\".\"id\" = $1) -- binds: [1]");
414/// # } else {
415/// assert_eq!(
416///     debug.to_string(),
417///     "SELECT `users`.`id`, `users`.`name` FROM `users` \
418///     WHERE (`users`.`id` = ?) -- binds: [1]"
419/// );
420/// # }
421///
422/// let debug = format!("{:?}", debug);
423/// # if !cfg!(feature = "postgres") { // Escaping that string is a pain
424/// let expected = "Query { \
425///     sql: \"SELECT `users`.`id`, `users`.`name` FROM `users` WHERE \
426///         (`users`.`id` = ?)\", \
427///     binds: [1] \
428/// }";
429/// assert_eq!(debug, expected);
430/// # }
431/// # }
432/// ```
433pub fn debug_query<DB, T>(query: &T) -> DebugQuery<'_, T, DB> {
434    DebugQuery::new(query)
435}
436
437mod private {
438    #[allow(missing_debug_implementations, missing_copy_implementations)]
439    pub struct NotSpecialized;
440}
441
442pub(crate) mod has_query;