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.
67#[macro_use]
8mod query_id;
9#[macro_use]
10mod clause_macro;
1112pub(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;
3738#[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::{
50IncompleteInsertOrIgnoreStatement, IncompleteInsertStatement, IncompleteReplaceStatement,
51InsertOrIgnoreStatement, 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::into_conflict_clause::IntoConflictValueClause;
59#[doc(inline)]
60pub use self::upsert::on_conflict_target::{ConflictTarget, OnConflictTarget};
61#[doc(inline)]
62pub use self::upsert::on_conflict_target_decorations::DecoratableTarget;
6364#[doc(inline)]
65pub use self::update_statement::changeset::AsChangeset;
66#[doc(inline)]
67pub use self::update_statement::target::{IntoUpdateTarget, UpdateTarget};
68#[doc(inline)]
69pub use self::update_statement::{BoxedUpdateStatement, UpdateStatement};
7071#[cfg(feature = "i-implement-a-third-party-backend-and-opt-into-breaking-changes")]
72pub use self::combination_clause::{
73All, Distinct, Except, Intersect, ParenthesisWrapper, SupportsCombinationClause, Union,
74};
75#[cfg(feature = "i-implement-a-third-party-backend-and-opt-into-breaking-changes")]
76pub use self::limit_clause::{LimitClause, NoLimitClause};
77#[cfg(feature = "i-implement-a-third-party-backend-and-opt-into-breaking-changes")]
78pub use self::limit_offset_clause::{BoxedLimitOffsetClause, LimitOffsetClause};
79#[cfg(feature = "i-implement-a-third-party-backend-and-opt-into-breaking-changes")]
80pub use self::offset_clause::{NoOffsetClause, OffsetClause};
81#[cfg(feature = "i-implement-a-third-party-backend-and-opt-into-breaking-changes")]
82pub use self::order_clause::{NoOrderClause, OrderClause};
8384#[doc(inline)]
pub use self::insert_statement::batch_insert::BatchInsert;#[diesel_derives::__diesel_public_if(
85 feature = "i-implement-a-third-party-backend-and-opt-into-breaking-changes"
86)]87#[doc(inline)]
88pub(crate) use self::insert_statement::batch_insert::BatchInsert;
89pub use self::insert_statement::{UndecoratedInsertRecord, ValuesClause};#[diesel_derives::__diesel_public_if(
90 feature = "i-implement-a-third-party-backend-and-opt-into-breaking-changes"
91)]92pub(crate) use self::insert_statement::{UndecoratedInsertRecord, ValuesClause};
9394#[cfg(feature = "i-implement-a-third-party-backend-and-opt-into-breaking-changes")]
95#[doc(inline)]
96pub use self::insert_statement::{DefaultValues, InsertOrIgnore, Replace};
9798#[cfg(feature = "i-implement-a-third-party-backend-and-opt-into-breaking-changes")]
99#[doc(inline)]
100pub use self::returning_clause::ReturningClause;
101102#[doc(inline)]
103#[doc(inline)]
pub use self::ast_pass::AstPassToSqlOptions;#[diesel_derives::__diesel_public_if(
104 feature = "i-implement-a-third-party-backend-and-opt-into-breaking-changes"
105)]106pub(crate) use self::ast_pass::AstPassToSqlOptions;
107108#[doc(inline)]
109#[doc(inline)]
pub use self::select_clause::SelectClauseExpression;#[diesel_derives::__diesel_public_if(
110 feature = "i-implement-a-third-party-backend-and-opt-into-breaking-changes"
111)]112pub(crate) use self::select_clause::SelectClauseExpression;
113114#[doc(inline)]
115#[doc(inline)]
pub use self::from_clause::{FromClause, NoFromClause};#[diesel_derives::__diesel_public_if(
116 feature = "i-implement-a-third-party-backend-and-opt-into-breaking-changes"
117)]118pub(crate) use self::from_clause::{FromClause, NoFromClause};
119#[doc(inline)]
pub use self::select_statement::BoxedSelectStatement;#[diesel_derives::__diesel_public_if(
120 feature = "i-implement-a-third-party-backend-and-opt-into-breaking-changes"
121)]122#[doc(inline)]
123pub(crate) use self::select_statement::BoxedSelectStatement;
124125#[doc(inline)]
pub use self::select_statement::SelectStatement;#[diesel_derives::__diesel_public_if(
126 feature = "i-implement-a-third-party-backend-and-opt-into-breaking-changes"
127)]128#[doc(inline)]
129pub(crate) use self::select_statement::SelectStatement;
130131pub(crate) use self::insert_statement::ColumnList;
132133#[cfg(feature = "postgres_backend")]
134pub use crate::pg::query_builder::only::Only;
135136#[cfg(feature = "postgres_backend")]
137pub use crate::pg::query_builder::tablesample::{Tablesample, TablesampleMethod};
138139#[cfg(feature = "postgres_backend")]
140pub(crate) use self::bind_collector::ByteWrapper;
141use crate::backend::Backend;
142use crate::result::QueryResult;
143use alloc::boxed::Box;
144use alloc::string::String;
145use alloc::vec::Vec;
146use core::error::Error;
147148pub(crate) use self::private::NotSpecialized;
149150#[doc(hidden)]
151pub type Binds = Vec<Option<Vec<u8>>>;
152/// A specialized Result type used with the query builder.
153pub type BuildQueryResult = Result<(), Box<dyn Error + Send + Sync>>;
154155/// Constructs a SQL query from a Diesel AST.
156///
157/// The only reason you should ever need to interact with this trait is if you
158/// are extending Diesel with support for a new backend. Plugins which extend
159/// the query builder with new capabilities will interact with [`AstPass`]
160/// instead.
161pub trait QueryBuilder<DB: Backend> {
162/// Add `sql` to the end of the query being constructed.
163fn push_sql(&mut self, sql: &str);
164165/// Quote `identifier`, and add it to the end of the query being
166 /// constructed.
167fn push_identifier(&mut self, identifier: &str) -> QueryResult<()>;
168169/// Add a placeholder for a bind parameter to the end of the query being
170 /// constructed.
171fn push_bind_param(&mut self);
172173/// Increases the internal counter for bind parameters without adding the
174 /// bind parameter itself to the query
175fn push_bind_param_value_only(&mut self) {}
176177/// Returns the constructed SQL query.
178fn finish(self) -> String;
179}
180181/// A complete SQL query with a return type.
182///
183/// This can be a select statement, or a command such as `update` or `insert`
184/// with a `RETURNING` clause. Unlike [`Expression`], types implementing this
185/// trait are guaranteed to be executable on their own.
186///
187/// A type which doesn't implement this trait may still represent a complete SQL
188/// query. For example, an `INSERT` statement without a `RETURNING` clause will
189/// not implement this trait, but can still be executed.
190///
191/// [`Expression`]: crate::expression::Expression
192pub trait Query {
193/// The SQL type that this query represents.
194 ///
195 /// This is the SQL type of the `SELECT` clause for select statements, and
196 /// the SQL type of the `RETURNING` clause for insert, update, or delete
197 /// statements.
198type SqlType;
199}
200201impl<T: Query> Queryfor &T {
202type SqlType = T::SqlType;
203}
204205/// Indicates that a type is a `SELECT` statement.
206///
207/// This trait differs from `Query` in two ways:
208/// - It is implemented only for select statements, rather than all queries
209/// which return a value.
210/// - It has looser constraints. A type implementing `SelectQuery` is known to
211/// be potentially valid if used as a subselect, but it is not necessarily
212/// able to be executed.
213pub trait SelectQuery {
214/// The SQL type of the `SELECT` clause
215type SqlType;
216}
217218/// An untyped fragment of SQL.
219///
220/// This may be a complete SQL command (such as an update statement without a
221/// `RETURNING` clause), or a subsection (such as our internal types used to
222/// represent a `WHERE` clause). Implementations of [`ExecuteDsl`] and
223/// [`LoadQuery`] will generally require that this trait be implemented.
224///
225/// [`ExecuteDsl`]: crate::query_dsl::methods::ExecuteDsl
226/// [`LoadQuery`]: crate::query_dsl::methods::LoadQuery
227#[diagnostic::on_unimplemented(
228 message = "`{Self}` is no valid SQL fragment for the `{DB}` backend",
229 note = "this usually means that the `{DB}` database system does not support \n\
230 this SQL syntax"
231)]
232pub trait QueryFragment<DB: Backend, SP = self::private::NotSpecialized> {
233/// Walk over this `QueryFragment` for all passes.
234 ///
235 /// This method is where the actual behavior of an AST node is implemented.
236 /// This method will contain the behavior required for all possible AST
237 /// passes. See [`AstPass`] for more details.
238fn walk_ast<'b>(&'b self, pass: AstPass<'_, 'b, DB>) -> QueryResult<()>;
239240/// Converts this `QueryFragment` to its SQL representation.
241 ///
242 /// This method should only be called by implementations of `Connection`.
243#[diesel_derives::__diesel_public_if(
244 feature = "i-implement-a-third-party-backend-and-opt-into-breaking-changes"
245)]
246fn to_sql(&self, out: &mut DB::QueryBuilder, backend: &DB) -> QueryResult<()> {
247let mut options = AstPassToSqlOptions::default();
248self.walk_ast(AstPass::to_sql(out, &mut options, backend))
249 }
250251/// Serializes all bind parameters in this query.
252 ///
253 /// A bind parameter is a value which is sent separately from the query
254 /// itself. It is represented in SQL with a placeholder such as `?` or `$1`.
255 ///
256 /// This method should only be called by implementations of `Connection`.
257#[diesel_derives::__diesel_public_if(
258 feature = "i-implement-a-third-party-backend-and-opt-into-breaking-changes"
259)]
260fn collect_binds<'b>(
261&'b self,
262 out: &mut DB::BindCollector<'b>,
263 metadata_lookup: &mut DB::MetadataLookup,
264 backend: &'b DB,
265 ) -> QueryResult<()> {
266self.walk_ast(AstPass::collect_binds(out, metadata_lookup, backend))
267 }
268269/// Is this query safe to store in the prepared statement cache?
270 ///
271 /// In order to keep our prepared statement cache at a reasonable size, we
272 /// avoid caching any queries which represent a potentially unbounded number
273 /// of SQL queries. Generally this will only return `true` for queries for
274 /// which `to_sql` will always construct exactly identical SQL.
275 ///
276 /// Some examples of where this method will return `false` are:
277 ///
278 /// - `SqlLiteral` (We don't know if the SQL was constructed dynamically, so
279 /// we must assume that it was)
280 /// - `In` and `NotIn` (Each value requires a separate bind param
281 /// placeholder)
282 ///
283 /// This method should only be called by implementations of `Connection`.
284#[diesel_derives::__diesel_public_if(
285 feature = "i-implement-a-third-party-backend-and-opt-into-breaking-changes"
286)]
287fn is_safe_to_cache_prepared(&self, backend: &DB) -> QueryResult<bool> {
288let mut result = true;
289self.walk_ast(AstPass::is_safe_to_cache_prepared(&mut result, backend))?;
290Ok(result)
291 }
292293/// Does walking this AST have any effect?
294#[diesel_derives::__diesel_public_if(
295 feature = "i-implement-a-third-party-backend-and-opt-into-breaking-changes"
296)]
297fn is_noop(&self, backend: &DB) -> QueryResult<bool> {
298let mut result = true;
299self.walk_ast(AstPass::is_noop(&mut result, backend))?;
300Ok(result)
301 }
302}
303304impl<T: ?Sized, DB> QueryFragment<DB> for Box<T>
305where
306DB: Backend,
307 T: QueryFragment<DB>,
308{
309fn walk_ast<'b>(&'b self, pass: AstPass<'_, 'b, DB>) -> QueryResult<()> {
310 QueryFragment::walk_ast(&**self, pass)
311 }
312}
313314impl<T: ?Sized, DB> QueryFragment<DB> for &T
315where
316DB: Backend,
317 T: QueryFragment<DB>,
318{
319fn walk_ast<'b>(&'b self, pass: AstPass<'_, 'b, DB>) -> QueryResult<()> {
320 QueryFragment::walk_ast(&**self, pass)
321 }
322}
323324impl<DB: Backend> QueryFragment<DB> for () {
325fn walk_ast<'b>(&'b self, _: AstPass<'_, 'b, DB>) -> QueryResult<()> {
326Ok(())
327 }
328}
329330impl<T, DB> QueryFragment<DB> for Option<T>
331where
332DB: Backend,
333 T: QueryFragment<DB>,
334{
335fn walk_ast<'b>(&'b self, out: AstPass<'_, 'b, DB>) -> QueryResult<()> {
336match *self {
337Some(ref c) => c.walk_ast(out),
338None => Ok(()),
339 }
340 }
341}
342343/// A trait used to construct type erased boxed variant of the current query node
344///
345/// Mainly useful for implementing third party backends
346#[diagnostic::on_unimplemented(
347 note = "this usually means that `{Self}` is no valid SQL for `{DB}`"
348)]
349pub trait IntoBoxedClause<'a, DB> {
350/// Resulting type
351type BoxedClause;
352353/// Convert the given query node in it's boxed representation
354fn into_boxed(self) -> Self::BoxedClause;
355}
356357/// Types that can be converted into a complete, typed SQL query.
358///
359/// This is used internally to automatically add the right select clause when
360/// none is specified, or to automatically add `RETURNING *` in certain contexts.
361///
362/// A type which implements this trait is guaranteed to be valid for execution.
363pub trait AsQuery {
364/// The SQL type of `Self::Query`
365type SqlType;
366367/// What kind of query does this type represent?
368type Query: Query<SqlType = Self::SqlType>;
369370/// Converts a type which semantically represents a SQL query into the
371 /// actual query being executed. See the trait level docs for more.
372// This method is part of our public API,
373 // so we won't change the name to just appease clippy
374 // (Also the trait is literally named `AsQuery` so
375 // naming the method similarity is fine)
376#[allow(clippy::wrong_self_convention)]
377fn as_query(self) -> Self::Query;
378}
379380impl<T: Query> AsQueryfor T {
381type SqlType = <T as Query>::SqlType;
382type Query = T;
383384fn as_query(self) -> <T as AsQuery>::Query {
385self386 }
387}
388389/// Takes a query `QueryFragment` expression as an argument and returns a type
390/// that implements `fmt::Display` and `fmt::Debug` to show the query.
391///
392/// The `Display` implementation will show the exact query being sent to the
393/// server, with a comment showing the values of the bind parameters. The
394/// `Debug` implementation will include the same information in a more
395/// structured form, and respects pretty printing.
396///
397/// # Example
398///
399/// ### Returning SQL from a count statement:
400///
401/// ```rust
402/// # include!("../doctest_setup.rs");
403/// #
404/// # use diesel::*;
405/// # use schema::*;
406/// #
407/// # fn main() {
408/// # use schema::users::dsl::*;
409/// let sql = debug_query::<DB, _>(&users.count()).to_string();
410/// # if cfg!(feature = "postgres") {
411/// # assert_eq!(sql, r#"SELECT COUNT(*) FROM "users" -- binds: []"#);
412/// # } else {
413/// assert_eq!(sql, "SELECT COUNT(*) FROM `users` -- binds: []");
414/// # }
415///
416/// let query = users.find(1);
417/// let debug = debug_query::<DB, _>(&query);
418/// # if cfg!(feature = "postgres") {
419/// # assert_eq!(debug.to_string(), "SELECT \"users\".\"id\", \"users\".\"name\" \
420/// # FROM \"users\" WHERE (\"users\".\"id\" = $1) -- binds: [1]");
421/// # } else {
422/// assert_eq!(
423/// debug.to_string(),
424/// "SELECT `users`.`id`, `users`.`name` FROM `users` \
425/// WHERE (`users`.`id` = ?) -- binds: [1]"
426/// );
427/// # }
428///
429/// let debug = format!("{:?}", debug);
430/// # if !cfg!(feature = "postgres") { // Escaping that string is a pain
431/// let expected = "Query { \
432/// sql: \"SELECT `users`.`id`, `users`.`name` FROM `users` WHERE \
433/// (`users`.`id` = ?)\", \
434/// binds: [1] \
435/// }";
436/// assert_eq!(debug, expected);
437/// # }
438/// # }
439/// ```
440pub fn debug_query<DB, T>(query: &T) -> DebugQuery<'_, T, DB> {
441DebugQuery::new(query)
442}
443444mod private {
445#[allow(missing_debug_implementations, missing_copy_implementations)]
446pub struct NotSpecialized;
447}
448449pub(crate) mod has_query;