diesel/
lib.rs

1//! # Diesel
2//!
3//! Diesel is an ORM and query builder designed to reduce the boilerplate for database interactions.
4//! If this is your first time reading this documentation,
5//! we recommend you start with the [getting started guide].
6//! We also have [many other long form guides].
7//!
8//! [getting started guide]: https://diesel.rs/guides/getting-started/
9//! [many other long form guides]: https://diesel.rs/guides
10//!
11//! # Where to find things
12//!
13//! ## Declaring your schema
14//!
15//! For Diesel to validate your queries at compile time
16//! it requires you to specify your schema in your code,
17//! which you can do with [the `table!` macro][`table!`].
18//! `diesel print-schema` can be used
19//! to automatically generate these macro calls
20//! (by connecting to your database and querying its schema).
21//!
22//!
23//! ## Getting started
24//!
25//! Queries usually start from either a table, or a function like [`update`].
26//! Those functions can be found [here](#functions).
27//!
28//! Diesel provides a [`prelude` module](prelude),
29//! which exports most of the typically used traits and types.
30//! We are conservative about what goes in this module,
31//! and avoid anything which has a generic name.
32//! Files which use Diesel are expected to have `use diesel::prelude::*;`.
33//!
34//! [`update`]: update()
35//!
36//! ## Constructing a query
37//!
38//! The tools the query builder gives you can be put into these three categories:
39//!
40//! - "Query builder methods" are things that map to portions of a whole query
41//!   (such as `ORDER` and `WHERE`). These methods usually have the same name
42//!   as the SQL they map to, except for `WHERE` which is called `filter` in Diesel
43//!   (To not conflict with the Rust keyword).
44//!   These methods live in [the `query_dsl` module](query_dsl).
45//! - "Expression methods" are things you would call on columns
46//!   or other individual values.
47//!   These methods live in [the `expression_methods` module](expression_methods)
48//!   You can often find these by thinking "what would this be called"
49//!   if it were a method
50//!   and typing that into the search bar
51//!   (e.g. `LIKE` is called `like` in Diesel).
52//!   Most operators are named based on the Rust function which maps to that
53//!   operator in [`std::ops`][]
54//!   (For example `==` is called `.eq`, and `!=` is called `.ne`).
55//! - "Bare functions" are normal SQL functions
56//!   such as `sum`.
57//!   They live in [the `dsl` module](dsl).
58//!   Diesel only supports a very small number of these functions.
59//!   You can declare additional functions you want to use
60//!   with [the `define_sql_function!` macro][`define_sql_function!`].
61//!
62//! [`std::ops`]: //doc.rust-lang.org/stable/std/ops/index.html
63//!
64//! ## Serializing and Deserializing
65//!
66//! Types which represent the result of a SQL query implement
67//! a trait called [`Queryable`].
68//!
69//! Diesel maps "Rust types" (e.g. `i32`) to and from "SQL types"
70//! (e.g. [`diesel::sql_types::Integer`]).
71//! You can find all the types supported by Diesel in [the `sql_types` module](sql_types).
72//! These types are only used to represent a SQL type.
73//! You should never put them on your `Queryable` structs.
74//!
75//! To find all the Rust types which can be used with a given SQL type,
76//! see the documentation for that SQL type.
77//!
78//! To find all the SQL types which can be used with a Rust type,
79//! go to the docs for either [`ToSql`] or [`FromSql`],
80//! go to the "Implementors" section,
81//! and find the Rust type you want to use.
82//!
83//! [`Queryable`]: deserialize::Queryable
84//! [`diesel::sql_types::Integer`]: sql_types::Integer
85//! [`ToSql`]: serialize::ToSql
86//! [`FromSql`]: deserialize::FromSql
87//!
88//! ## How to read diesels compile time error messages
89//!
90//! Diesel is known for generating large complicated looking errors. Usually
91//! most of these error messages can be broken down easily. The following
92//! section tries to give an overview of common error messages and how to read them.
93//! As a general note it's always useful to read the complete error message as emitted
94//! by rustc, including the `required because of …` part of the message.
95//! Your IDE might hide important parts!
96//!
97//! The following error messages are common:
98//!
99//! * `the trait bound (diesel::sql_types::Integer, …, diesel::sql_types::Text): load_dsl::private::CompatibleType<YourModel, Pg> is not satisfied`
100//!    while trying to execute a query:
101//!    This error indicates a mismatch between what your query returns and what your model struct
102//!    expects the query to return. The fields need to match in terms of field order, field type
103//!    and field count. If you are sure that everything matches, double check the enabled diesel
104//!    features (for support for types from other crates) and double check (via `cargo tree`)
105//!    that there is only one version of such a shared crate in your dependency tree.
106//!    Consider using [`#[derive(Selectable)]`](derive@crate::prelude::Selectable) +
107//!    `#[diesel(check_for_backend(diesel::pg::Pg))]`
108//!    to improve the generated error message.
109//! * `the trait bound i32: diesel::Expression is not satisfied` in the context of `Insertable`
110//!    model structs:
111//!    This error indicates a type mismatch between the field you are trying to insert into the database
112//!    and the actual database type. These error messages contain a line
113//!    like ` = note: required for i32 to implement AsExpression<diesel::sql_types::Text>`
114//!    that show both the provided rust side type (`i32` in that case) and the expected
115//!    database side type (`Text` in that case).
116//! * `the trait bound i32: AppearsOnTable<users::table> is not satisfied` in the context of `AsChangeset`
117//!    model structs:
118//!    This error indicates a type mismatch between the field you are trying to update and the actual
119//!    database type. Double check your type mapping.
120//! * `the trait bound SomeLargeType: QueryFragment<Sqlite, SomeMarkerType> is not satisfied` while
121//!    trying to execute a query.
122//!    This error message indicates that a given query is not supported by your backend. This usually
123//!    means that you are trying to use SQL features from one SQL dialect on a different database
124//!    system. Double check your query that everything required is supported by the selected
125//!    backend. If that's the case double check that the relevant feature flags are enabled
126//!    (for example, `returning_clauses_for_sqlite_3_35` for enabling support for returning clauses in newer
127//!    sqlite versions)
128//! * `the trait bound posts::title: SelectableExpression<users::table> is not satisfied` while
129//!    executing a query:
130//!    This error message indicates that you're trying to select a field from a table
131//!    that does not appear in your from clause. If your query joins the relevant table via
132//!    [`left_join`](crate::query_dsl::QueryDsl::left_join) you need to call
133//!    [`.nullable()`](crate::expression_methods::NullableExpressionMethods::nullable)
134//!    on the relevant column in your select clause.
135//!
136//!
137//! ## Getting help
138//!
139//! If you run into problems, Diesel has an active community.
140//! Either open a new [discussion] thread at diesel github repository or
141//! use the active Gitter room at
142//! [gitter.im/diesel-rs/diesel](https://gitter.im/diesel-rs/diesel)
143//!
144//! [discussion]: https://github.com/diesel-rs/diesel/discussions/categories/q-a
145//!
146//! # Crate feature flags
147//!
148//! The following feature flags are considered to be part of diesels public
149//! API. Any feature flag that is not listed here is **not** considered to
150//! be part of the public API and can disappear at any point in time:
151
152//!
153//! - `sqlite`: This feature enables the diesel sqlite backend. Enabling this feature requires per default
154//!   a compatible copy of `libsqlite3` for your target architecture. Alternatively, you can add `libsqlite3-sys`
155//!   with the `bundled` feature as a dependency to your crate so SQLite will be bundled:
156//!   ```toml
157//!   [dependencies]
158//!   libsqlite3-sys = { version = "0.29", features = ["bundled"] }
159//!   ```
160//! - `postgres`: This feature enables the diesel postgres backend. Enabling this feature requires a compatible
161//!   copy of `libpq` for your target architecture. This features implies `postgres_backend`
162//! - `mysql`: This feature enables the idesel mysql backend. Enabling this feature requires a compatible copy
163//!   of `libmysqlclient` for your target architecture. This feature implies `mysql_backend`
164//! - `postgres_backend`: This feature enables those parts of diesels postgres backend, that are not dependent
165//!   on `libpq`. Diesel does not provide any connection implementation with only this feature enabled.
166//!   This feature can be used to implement a custom implementation of diesels `Connection` trait for the
167//!   postgres backend outside of diesel itself, while reusing the existing query dsl extensions for the
168//!   postgres backend
169//! - `mysql_backend`: This feature enables those parts of diesels mysql backend, that are not dependent
170//!   on `libmysqlclient`. Diesel does not provide any connection implementation with only this feature enabled.
171//!   This feature can be used to implement a custom implementation of diesels `Connection` trait for the
172//!   mysql backend outside of diesel itself, while reusing the existing query dsl extensions for the
173//!   mysql backend
174//! - `returning_clauses_for_sqlite_3_35`: This feature enables support for `RETURNING` clauses in the sqlite backend.
175//!   Enabling this feature requires sqlite 3.35.0 or newer.
176//! - `32-column-tables`: This feature enables support for tables with up to 32 columns.
177//!   This feature is enabled by default. Consider disabling this feature if you write a library crate
178//!   providing general extensions for diesel or if you do not need to support tables with more than 16 columns
179//!   and you want to minimize your compile times.
180//! - `64-column-tables`: This feature enables support for tables with up to 64 columns. It implies the
181//!   `32-column-tables` feature. Enabling this feature will increase your compile times.
182//! - `128-column-tables`: This feature enables support for tables with up to 128 columns. It implies the
183//!   `64-column-tables` feature. Enabling this feature will increase your compile times significantly.
184//! - `i-implement-a-third-party-backend-and-opt-into-breaking-changes`: This feature opens up some otherwise
185//!   private API, that can be useful to implement a third party [`Backend`](crate::backend::Backend)
186//!   or write a custom [`Connection`] implementation. **Do not use this feature for
187//!   any other usecase**. By enabling this feature you explicitly opt out diesel stability guarantees. We explicitly
188//!   reserve us the right to break API's exported under this feature flag in any upcoming minor version release.
189//!   If you publish a crate depending on this feature flag consider to restrict the supported diesel version to the
190//!   currently released minor version.
191//! - `serde_json`: This feature flag enables support for (de)serializing json values from the database using
192//!   types provided by `serde_json`.
193//! - `chrono`: This feature flags enables support for (de)serializing date/time values from the database using
194//!   types provided by `chrono`
195//! - `uuid`: This feature flag enables support for (de)serializing uuid values from the database using types
196//!   provided by `uuid`
197//! - `network-address`: This feature flag enables support for (de)serializing
198//!   IP values from the database using types provided by `ipnetwork`.
199//! - `ipnet-address`: This feature flag enables support for (de)serializing IP
200//!   values from the database using types provided by `ipnet`.
201//! - `numeric`: This feature flag enables support for (de)serializing numeric values from the database using types
202//!   provided by `bigdecimal`
203//! - `r2d2`: This feature flag enables support for the `r2d2` connection pool implementation.
204//! - `extras`: This feature enables the feature flagged support for any third party crate. This implies the
205//!   following feature flags: `serde_json`, `chrono`, `uuid`, `network-address`, `numeric`, `r2d2`
206//! - `with-deprecated`: This feature enables items marked as `#[deprecated]`. It is enabled by default.
207//!   disabling this feature explicitly opts out diesels stability guarantee.
208//! - `without-deprecated`: This feature disables any item marked as `#[deprecated]`. Enabling this feature
209//!   explicitly opts out the stability guarantee given by diesel. This feature overrides the `with-deprecated`.
210//!   Note that this may also remove items that are not shown as `#[deprecated]` in our documentation, due to
211//!   various bugs in rustdoc. It can be used to check if you depend on any such hidden `#[deprecated]` item.
212//!
213//! By default the following features are enabled:
214//!
215//! - `with-deprecated`
216//! - `32-column-tables`
217
218#![cfg_attr(feature = "unstable", feature(trait_alias))]
219#![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))]
220#![cfg_attr(feature = "128-column-tables", recursion_limit = "256")]
221// Built-in Lints
222#![warn(
223    unreachable_pub,
224    missing_debug_implementations,
225    missing_copy_implementations,
226    elided_lifetimes_in_paths,
227    missing_docs
228)]
229// Clippy lints
230#![allow(
231    clippy::match_same_arms,
232    clippy::needless_doctest_main,
233    clippy::map_unwrap_or,
234    clippy::redundant_field_names,
235    clippy::type_complexity
236)]
237#![warn(
238    clippy::unwrap_used,
239    clippy::print_stdout,
240    clippy::mut_mut,
241    clippy::non_ascii_literal,
242    clippy::similar_names,
243    clippy::unicode_not_nfc,
244    clippy::enum_glob_use,
245    clippy::if_not_else,
246    clippy::items_after_statements,
247    clippy::used_underscore_binding,
248    clippy::cast_possible_wrap,
249    clippy::cast_possible_truncation,
250    clippy::cast_sign_loss
251)]
252#![deny(unsafe_code)]
253#![cfg_attr(test, allow(clippy::map_unwrap_or, clippy::unwrap_used))]
254
255extern crate diesel_derives;
256
257#[macro_use]
258#[doc(hidden)]
259pub mod macros;
260#[doc(hidden)]
261pub mod internal;
262
263#[cfg(test)]
264#[macro_use]
265extern crate cfg_if;
266
267#[cfg(test)]
268pub mod test_helpers;
269
270pub mod associations;
271pub mod backend;
272pub mod connection;
273pub mod data_types;
274pub mod deserialize;
275#[macro_use]
276pub mod expression;
277pub mod expression_methods;
278#[doc(hidden)]
279pub mod insertable;
280pub mod query_builder;
281pub mod query_dsl;
282pub mod query_source;
283#[cfg(feature = "r2d2")]
284pub mod r2d2;
285pub mod result;
286pub mod serialize;
287pub mod upsert;
288#[macro_use]
289pub mod sql_types;
290pub mod migration;
291pub mod row;
292
293#[cfg(feature = "mysql_backend")]
294pub mod mysql;
295#[cfg(feature = "postgres_backend")]
296pub mod pg;
297#[cfg(feature = "sqlite")]
298pub mod sqlite;
299
300mod type_impls;
301mod util;
302
303#[doc(hidden)]
304#[cfg(all(feature = "with-deprecated", not(feature = "without-deprecated")))]
305#[deprecated(since = "2.0.0", note = "Use explicit macro imports instead")]
306pub use diesel_derives::{
307    AsChangeset, AsExpression, Associations, DieselNumericOps, FromSqlRow, Identifiable,
308    Insertable, QueryId, Queryable, QueryableByName, SqlType,
309};
310
311pub use diesel_derives::MultiConnection;
312
313#[allow(unknown_lints, ambiguous_glob_reexports)]
314pub mod dsl {
315    //! Includes various helper types and bare functions which are named too
316    //! generically to be included in prelude, but are often used when using Diesel.
317
318    #[doc(inline)]
319    pub use crate::helper_types::*;
320
321    #[doc(inline)]
322    pub use crate::expression::dsl::*;
323
324    #[doc(inline)]
325    pub use crate::query_builder::functions::{
326        delete, insert_into, insert_or_ignore_into, replace_into, select, sql_query, update,
327    };
328
329    #[doc(inline)]
330    #[cfg(feature = "postgres_backend")]
331    pub use crate::query_builder::functions::{copy_from, copy_to};
332
333    #[doc(inline)]
334    pub use diesel_derives::auto_type;
335
336    #[cfg(feature = "postgres_backend")]
337    #[doc(inline)]
338    pub use crate::pg::expression::extensions::OnlyDsl;
339
340    #[cfg(feature = "postgres_backend")]
341    #[doc(inline)]
342    pub use crate::pg::expression::extensions::TablesampleDsl;
343}
344
345pub mod helper_types {
346    //! Provide helper types for concisely writing the return type of functions.
347    //! As with iterators, it is unfortunately difficult to return a partially
348    //! constructed query without exposing the exact implementation of the
349    //! function. Without higher kinded types, these various DSLs can't be
350    //! combined into a single trait for boxing purposes.
351    //!
352    //! All types here are in the form `<FirstType as
353    //! DslName<OtherTypes>>::Output`. So the return type of
354    //! `users.filter(first_name.eq("John")).order(last_name.asc()).limit(10)` would
355    //! be `Limit<Order<FindBy<users, first_name, &str>, Asc<last_name>>>`
356    use super::query_builder::combination_clause::{self, CombinationClause};
357    use super::query_builder::{locking_clause as lock, AsQuery};
358    use super::query_dsl::methods::*;
359    use super::query_dsl::*;
360    use super::query_source::{aliasing, joins};
361    use crate::query_builder::select_clause::SelectClause;
362
363    #[doc(inline)]
364    pub use crate::expression::helper_types::*;
365
366    /// Represents the return type of [`.select(selection)`](crate::prelude::QueryDsl::select)
367    pub type Select<Source, Selection> = <Source as SelectDsl<Selection>>::Output;
368
369    /// Represents the return type of [`diesel::select(selection)`](crate::select)
370    #[allow(non_camel_case_types)] // required for `#[auto_type]`
371    pub type select<Selection> = crate::query_builder::SelectStatement<
372        crate::query_builder::NoFromClause,
373        SelectClause<Selection>,
374    >;
375
376    #[doc(hidden)]
377    #[deprecated(note = "Use `select` instead")]
378    pub type BareSelect<Selection> = crate::query_builder::SelectStatement<
379        crate::query_builder::NoFromClause,
380        SelectClause<Selection>,
381    >;
382
383    /// Represents the return type of [`.filter(predicate)`](crate::prelude::QueryDsl::filter)
384    pub type Filter<Source, Predicate> = <Source as FilterDsl<Predicate>>::Output;
385
386    /// Represents the return type of [`.filter(lhs.eq(rhs))`](crate::prelude::QueryDsl::filter)
387    pub type FindBy<Source, Column, Value> = Filter<Source, Eq<Column, Value>>;
388
389    /// Represents the return type of [`.for_update()`](crate::prelude::QueryDsl::for_update)
390    pub type ForUpdate<Source> = <Source as LockingDsl<lock::ForUpdate>>::Output;
391
392    /// Represents the return type of [`.for_no_key_update()`](crate::prelude::QueryDsl::for_no_key_update)
393    pub type ForNoKeyUpdate<Source> = <Source as LockingDsl<lock::ForNoKeyUpdate>>::Output;
394
395    /// Represents the return type of [`.for_share()`](crate::prelude::QueryDsl::for_share)
396    pub type ForShare<Source> = <Source as LockingDsl<lock::ForShare>>::Output;
397
398    /// Represents the return type of [`.for_key_share()`](crate::prelude::QueryDsl::for_key_share)
399    pub type ForKeyShare<Source> = <Source as LockingDsl<lock::ForKeyShare>>::Output;
400
401    /// Represents the return type of [`.skip_locked()`](crate::prelude::QueryDsl::skip_locked)
402    pub type SkipLocked<Source> = <Source as ModifyLockDsl<lock::SkipLocked>>::Output;
403
404    /// Represents the return type of [`.no_wait()`](crate::prelude::QueryDsl::no_wait)
405    pub type NoWait<Source> = <Source as ModifyLockDsl<lock::NoWait>>::Output;
406
407    /// Represents the return type of [`.find(pk)`](crate::prelude::QueryDsl::find)
408    pub type Find<Source, PK> = <Source as FindDsl<PK>>::Output;
409
410    /// Represents the return type of [`.or_filter(predicate)`](crate::prelude::QueryDsl::or_filter)
411    pub type OrFilter<Source, Predicate> = <Source as OrFilterDsl<Predicate>>::Output;
412
413    /// Represents the return type of [`.order(ordering)`](crate::prelude::QueryDsl::order)
414    pub type Order<Source, Ordering> = <Source as OrderDsl<Ordering>>::Output;
415
416    /// Represents the return type of [`.order_by(ordering)`](crate::prelude::QueryDsl::order_by)
417    ///
418    /// Type alias of [Order]
419    pub type OrderBy<Source, Ordering> = Order<Source, Ordering>;
420
421    /// Represents the return type of [`.then_order_by(ordering)`](crate::prelude::QueryDsl::then_order_by)
422    pub type ThenOrderBy<Source, Ordering> = <Source as ThenOrderDsl<Ordering>>::Output;
423
424    /// Represents the return type of [`.limit()`](crate::prelude::QueryDsl::limit)
425    pub type Limit<Source, DummyArgForAutoType = i64> =
426        <Source as LimitDsl<DummyArgForAutoType>>::Output;
427
428    /// Represents the return type of [`.offset()`](crate::prelude::QueryDsl::offset)
429    pub type Offset<Source, DummyArgForAutoType = i64> =
430        <Source as OffsetDsl<DummyArgForAutoType>>::Output;
431
432    /// Represents the return type of [`.inner_join(rhs)`](crate::prelude::QueryDsl::inner_join)
433    pub type InnerJoin<Source, Rhs> =
434        <Source as JoinWithImplicitOnClause<Rhs, joins::Inner>>::Output;
435
436    /// Represents the return type of [`.inner_join(rhs.on(on))`](crate::prelude::QueryDsl::inner_join)
437    pub type InnerJoinOn<Source, Rhs, On> =
438        <Source as InternalJoinDsl<Rhs, joins::Inner, On>>::Output;
439
440    /// Represents the return type of [`.left_join(rhs)`](crate::prelude::QueryDsl::left_join)
441    pub type LeftJoin<Source, Rhs> =
442        <Source as JoinWithImplicitOnClause<Rhs, joins::LeftOuter>>::Output;
443
444    /// Represents the return type of [`.left_join(rhs.on(on))`](crate::prelude::QueryDsl::left_join)
445    pub type LeftJoinOn<Source, Rhs, On> =
446        <Source as InternalJoinDsl<Rhs, joins::LeftOuter, On>>::Output;
447
448    /// Represents the return type of [`rhs.on(on)`](crate::query_dsl::JoinOnDsl::on)
449    pub type On<Source, On> = joins::OnClauseWrapper<Source, On>;
450
451    use super::associations::HasTable;
452    use super::query_builder::{AsChangeset, IntoUpdateTarget, UpdateStatement};
453
454    /// Represents the return type of [`update(lhs).set(rhs)`](crate::query_builder::UpdateStatement::set)
455    pub type Update<Target, Changes> = UpdateStatement<
456        <Target as HasTable>::Table,
457        <Target as IntoUpdateTarget>::WhereClause,
458        <Changes as AsChangeset>::Changeset,
459    >;
460
461    /// Represents the return type of [`.into_boxed::<'a, DB>()`](crate::prelude::QueryDsl::into_boxed)
462    pub type IntoBoxed<'a, Source, DB> = <Source as BoxedDsl<'a, DB>>::Output;
463
464    /// Represents the return type of [`.distinct()`](crate::prelude::QueryDsl::distinct)
465    pub type Distinct<Source> = <Source as DistinctDsl>::Output;
466
467    /// Represents the return type of [`.distinct_on(expr)`](crate::prelude::QueryDsl::distinct_on)
468    #[cfg(feature = "postgres_backend")]
469    pub type DistinctOn<Source, Expr> = <Source as DistinctOnDsl<Expr>>::Output;
470
471    /// Represents the return type of [`.single_value()`](SingleValueDsl::single_value)
472    pub type SingleValue<Source> = <Source as SingleValueDsl>::Output;
473
474    /// Represents the return type of [`.nullable()`](SelectNullableDsl::nullable)
475    pub type NullableSelect<Source> = <Source as SelectNullableDsl>::Output;
476
477    /// Represents the return type of [`.group_by(expr)`](crate::prelude::QueryDsl::group_by)
478    pub type GroupBy<Source, Expr> = <Source as GroupByDsl<Expr>>::Output;
479
480    /// Represents the return type of [`.having(predicate)`](crate::prelude::QueryDsl::having)
481    pub type Having<Source, Predicate> = <Source as HavingDsl<Predicate>>::Output;
482
483    /// Represents the return type of [`.union(rhs)`](crate::prelude::CombineDsl::union)
484    pub type Union<Source, Rhs> = CombinationClause<
485        combination_clause::Union,
486        combination_clause::Distinct,
487        <Source as CombineDsl>::Query,
488        <Rhs as AsQuery>::Query,
489    >;
490
491    /// Represents the return type of [`.union_all(rhs)`](crate::prelude::CombineDsl::union_all)
492    pub type UnionAll<Source, Rhs> = CombinationClause<
493        combination_clause::Union,
494        combination_clause::All,
495        <Source as CombineDsl>::Query,
496        <Rhs as AsQuery>::Query,
497    >;
498
499    /// Represents the return type of [`.intersect(rhs)`](crate::prelude::CombineDsl::intersect)
500    pub type Intersect<Source, Rhs> = CombinationClause<
501        combination_clause::Intersect,
502        combination_clause::Distinct,
503        <Source as CombineDsl>::Query,
504        <Rhs as AsQuery>::Query,
505    >;
506
507    /// Represents the return type of [`.intersect_all(rhs)`](crate::prelude::CombineDsl::intersect_all)
508    pub type IntersectAll<Source, Rhs> = CombinationClause<
509        combination_clause::Intersect,
510        combination_clause::All,
511        <Source as CombineDsl>::Query,
512        <Rhs as AsQuery>::Query,
513    >;
514
515    /// Represents the return type of [`.except(rhs)`](crate::prelude::CombineDsl::except)
516    pub type Except<Source, Rhs> = CombinationClause<
517        combination_clause::Except,
518        combination_clause::Distinct,
519        <Source as CombineDsl>::Query,
520        <Rhs as AsQuery>::Query,
521    >;
522
523    /// Represents the return type of [`.except_all(rhs)`](crate::prelude::CombineDsl::except_all)
524    pub type ExceptAll<Source, Rhs> = CombinationClause<
525        combination_clause::Except,
526        combination_clause::All,
527        <Source as CombineDsl>::Query,
528        <Rhs as AsQuery>::Query,
529    >;
530
531    type JoinQuerySource<Left, Right, Kind, On> = joins::JoinOn<joins::Join<Left, Right, Kind>, On>;
532
533    /// A query source representing the inner join between two tables.
534    ///
535    /// The third generic type (`On`) controls how the tables are
536    /// joined.
537    ///
538    /// By default, the implicit join established by [`joinable!`][]
539    /// will be used, allowing you to omit the exact join
540    /// condition. For example, for the inner join between three
541    /// tables that implement [`JoinTo`][], you only need to specify
542    /// the tables: `InnerJoinQuerySource<InnerJoinQuerySource<table1,
543    /// table2>, table3>`.
544    ///
545    /// [`JoinTo`]: crate::query_source::JoinTo
546    ///
547    /// If you use an explicit `ON` clause, you will need to specify
548    /// the `On` generic type.
549    ///
550    /// ```rust
551    /// # include!("doctest_setup.rs");
552    /// use diesel::{dsl, helper_types::InnerJoinQuerySource};
553    /// # use diesel::{backend::Backend, serialize::ToSql, sql_types};
554    /// use schema::*;
555    ///
556    /// # fn main() -> QueryResult<()> {
557    /// #     let conn = &mut establish_connection();
558    /// #
559    /// // If you have an explicit join like this...
560    /// let join_constraint = comments::columns::post_id.eq(posts::columns::id);
561    /// #     let query =
562    /// posts::table.inner_join(comments::table.on(join_constraint));
563    /// #
564    /// #     // Dummy usage just to ensure the example compiles.
565    /// #     let filter = posts::columns::id.eq(1);
566    /// #     let filter: &FilterExpression<_> = &filter;
567    /// #     query.filter(filter).select(posts::columns::id).get_result::<i32>(conn)?;
568    /// #
569    /// #     Ok(())
570    /// # }
571    ///
572    /// // ... you can use `InnerJoinQuerySource` like this.
573    /// type JoinConstraint = dsl::Eq<comments::columns::post_id, posts::columns::id>;
574    /// type MyInnerJoinQuerySource = InnerJoinQuerySource<posts::table, comments::table, JoinConstraint>;
575    /// # type FilterExpression<DB> = dyn BoxableExpression<MyInnerJoinQuerySource, DB, SqlType = sql_types::Bool>;
576    /// ```
577    pub type InnerJoinQuerySource<Left, Right, On = <Left as joins::JoinTo<Right>>::OnClause> =
578        JoinQuerySource<Left, Right, joins::Inner, On>;
579
580    /// A query source representing the left outer join between two tables.
581    ///
582    /// The third generic type (`On`) controls how the tables are
583    /// joined.
584    ///
585    /// By default, the implicit join established by [`joinable!`][]
586    /// will be used, allowing you to omit the exact join
587    /// condition. For example, for the left join between three
588    /// tables that implement [`JoinTo`][], you only need to specify
589    /// the tables: `LeftJoinQuerySource<LeftJoinQuerySource<table1,
590    /// table2>, table3>`.
591    ///
592    /// [`JoinTo`]: crate::query_source::JoinTo
593    ///
594    /// If you use an explicit `ON` clause, you will need to specify
595    /// the `On` generic type.
596    ///
597    /// ```rust
598    /// # include!("doctest_setup.rs");
599    /// use diesel::{dsl, helper_types::LeftJoinQuerySource};
600    /// # use diesel::{backend::Backend, serialize::ToSql, sql_types};
601    /// use schema::*;
602    ///
603    /// # fn main() -> QueryResult<()> {
604    /// #     let conn = &mut establish_connection();
605    /// #
606    /// // If you have an explicit join like this...
607    /// let join_constraint = comments::columns::post_id.eq(posts::columns::id);
608    /// #     let query =
609    /// posts::table.left_join(comments::table.on(join_constraint));
610    /// #
611    /// #     // Dummy usage just to ensure the example compiles.
612    /// #     let filter = posts::columns::id.eq(1);
613    /// #     let filter: &FilterExpression<_> = &filter;
614    /// #     query.filter(filter).select(posts::columns::id).get_result::<i32>(conn)?;
615    /// #
616    /// #     Ok(())
617    /// # }
618    ///
619    /// // ... you can use `LeftJoinQuerySource` like this.
620    /// type JoinConstraint = dsl::Eq<comments::columns::post_id, posts::columns::id>;
621    /// type MyLeftJoinQuerySource = LeftJoinQuerySource<posts::table, comments::table, JoinConstraint>;
622    /// # type FilterExpression<DB> = dyn BoxableExpression<MyLeftJoinQuerySource, DB, SqlType = sql_types::Bool>;
623    /// ```
624    pub type LeftJoinQuerySource<Left, Right, On = <Left as joins::JoinTo<Right>>::OnClause> =
625        JoinQuerySource<Left, Right, joins::LeftOuter, On>;
626
627    /// Maps `F` to `Alias<S>`
628    ///
629    /// Any column `F` that belongs to `S::Table` will be transformed into
630    /// [`AliasedField<S, Self>`](crate::query_source::AliasedField)
631    ///
632    /// Any column `F` that does not belong to `S::Table` will be left untouched.
633    ///
634    /// This also works with tuples and some expressions.
635    pub type AliasedFields<S, F> = <F as aliasing::FieldAliasMapper<S>>::Out;
636
637    #[doc(hidden)]
638    #[cfg(all(feature = "with-deprecated", not(feature = "without-deprecated")))]
639    #[deprecated(note = "Use `LoadQuery::RowIter` directly")]
640    pub type LoadIter<'conn, 'query, Q, Conn, U, B = crate::connection::DefaultLoadingMode> =
641        <Q as load_dsl::LoadQuery<'query, Conn, U, B>>::RowIter<'conn>;
642
643    /// Represents the return type of [`diesel::delete`]
644    #[allow(non_camel_case_types)] // required for `#[auto_type]`
645    pub type delete<T> = crate::query_builder::DeleteStatement<
646        <T as HasTable>::Table,
647        <T as IntoUpdateTarget>::WhereClause,
648    >;
649
650    /// Represents the return type of [`diesel::insert_into`]
651    #[allow(non_camel_case_types)] // required for `#[auto_type]`
652    pub type insert_into<T> = crate::query_builder::IncompleteInsertStatement<T>;
653
654    /// Represents the return type of [`diesel::insert_or_ignore_into`]
655    #[allow(non_camel_case_types)] // required for `#[auto_type]`
656    pub type insert_or_ignore_into<T> = crate::query_builder::IncompleteInsertOrIgnoreStatement<T>;
657
658    /// Represents the return type of [`diesel::replace_into`]
659    #[allow(non_camel_case_types)] // required for `#[auto_type]`
660    pub type replace_into<T> = crate::query_builder::IncompleteReplaceStatement<T>;
661
662    /// Represents the return type of
663    /// [`IncompleteInsertStatement::values()`](crate::query_builder::IncompleteInsertStatement::values)
664    pub type Values<I, U> = crate::query_builder::InsertStatement<
665        <I as crate::query_builder::insert_statement::InsertAutoTypeHelper>::Table,
666        <U as crate::Insertable<
667            <I as crate::query_builder::insert_statement::InsertAutoTypeHelper>::Table,
668        >>::Values,
669        <I as crate::query_builder::insert_statement::InsertAutoTypeHelper>::Op,
670    >;
671
672    /// Represents the return type of
673    /// [`UpdateStatement::set()`](crate::query_builder::UpdateStatement::set)
674    pub type Set<U, V> = crate::query_builder::UpdateStatement<
675        <U as crate::query_builder::update_statement::UpdateAutoTypeHelper>::Table,
676        <U as crate::query_builder::update_statement::UpdateAutoTypeHelper>::Where,
677        <V as crate::AsChangeset>::Changeset,
678    >;
679}
680
681pub mod prelude {
682    //! Re-exports important traits and types. Meant to be glob imported when using Diesel.
683
684    #[doc(inline)]
685    pub use crate::associations::{Associations, GroupedBy, Identifiable};
686    #[doc(inline)]
687    pub use crate::connection::Connection;
688    #[doc(inline)]
689    pub use crate::deserialize::{Queryable, QueryableByName};
690    #[doc(inline)]
691    pub use crate::expression::{
692        AppearsOnTable, BoxableExpression, Expression, IntoSql, Selectable, SelectableExpression,
693    };
694    // If [`IntoSql`](crate::expression::helper_types::IntoSql) the type gets imported at the
695    // same time as IntoSql the trait (this one) gets imported via the prelude, then
696    // methods of the trait won't be resolved because the type may take priority over the trait.
697    // That issue can be avoided by also importing it anonymously:
698    pub use crate::expression::IntoSql as _;
699
700    #[doc(inline)]
701    pub use crate::expression::functions::define_sql_function;
702    #[cfg(all(feature = "with-deprecated", not(feature = "without-deprecated")))]
703    pub use crate::expression::functions::sql_function;
704
705    #[doc(inline)]
706    pub use crate::expression::SelectableHelper;
707    #[doc(inline)]
708    pub use crate::expression_methods::*;
709    #[doc(inline)]
710    pub use crate::insertable::Insertable;
711    #[doc(inline)]
712    pub use crate::macros::prelude::*;
713    #[doc(inline)]
714    pub use crate::query_builder::AsChangeset;
715    #[doc(inline)]
716    pub use crate::query_builder::DecoratableTarget;
717    #[doc(inline)]
718    pub use crate::query_dsl::{
719        BelongingToDsl, CombineDsl, JoinOnDsl, QueryDsl, RunQueryDsl, SaveChangesDsl,
720    };
721    pub use crate::query_source::SizeRestrictedColumn as _;
722    #[doc(inline)]
723    pub use crate::query_source::{Column, JoinTo, QuerySource, Table};
724    #[doc(inline)]
725    pub use crate::result::{
726        ConnectionError, ConnectionResult, OptionalEmptyChangesetExtension, OptionalExtension,
727        QueryResult,
728    };
729    #[doc(inline)]
730    pub use diesel_derives::table_proc as table;
731
732    #[cfg(feature = "mysql")]
733    #[doc(inline)]
734    pub use crate::mysql::MysqlConnection;
735    #[doc(inline)]
736    #[cfg(feature = "postgres_backend")]
737    pub use crate::pg::query_builder::copy::ExecuteCopyFromDsl;
738    #[cfg(feature = "postgres")]
739    #[doc(inline)]
740    pub use crate::pg::PgConnection;
741    #[cfg(feature = "sqlite")]
742    #[doc(inline)]
743    pub use crate::sqlite::SqliteConnection;
744}
745
746#[doc(inline)]
747pub use crate::macros::table;
748pub use crate::prelude::*;
749#[doc(inline)]
750pub use crate::query_builder::debug_query;
751#[doc(inline)]
752#[cfg(feature = "postgres")]
753pub use crate::query_builder::functions::{copy_from, copy_to};
754#[doc(inline)]
755pub use crate::query_builder::functions::{
756    delete, insert_into, insert_or_ignore_into, replace_into, select, sql_query, update,
757};
758pub use crate::result::Error::NotFound;
759
760extern crate self as diesel;