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//! Open a new [discussion] thread at diesel github repository
141//! and we will try to help you
142//!
143//! [discussion]: https://github.com/diesel-rs/diesel/discussions/categories/q-a
144//!
145//! # Crate feature flags
146//!
147//! The following feature flags are considered to be part of diesels public
148//! API. Any feature flag that is not listed here is **not** considered to
149//! be part of the public API and can disappear at any point in time:
150
151//!
152//! - `sqlite`: This feature enables the diesel sqlite backend. Enabling this feature requires per default
153//!   a compatible copy of `libsqlite3` for your target architecture. Alternatively, you can add `libsqlite3-sys`
154//!   with the `bundled` feature as a dependency to your crate so SQLite will be bundled:
155//!   ```toml
156//!   [dependencies]
157//!   libsqlite3-sys = { version = "0.29", features = ["bundled"] }
158//!   ```
159//! - `postgres`: This feature enables the diesel postgres backend. This features implies `postgres_backend`
160//!   Enabling this feature requires a compatible copy of `libpq` for your target architecture.
161//!   Alternatively, you can add `pq-sys` with the `bundled` feature as a dependency to your
162//!   crate so libpq will be bundled:
163//!   ```toml
164//!   [dependencies]
165//!   pq-sys = { version = "0.6", features = ["bundled"] }
166//!   openssl-sys = { version = "0.9.100", features = ["vendored"] }
167//!   ```
168//! - `mysql`: This feature enables the diesel mysql backend. This feature implies `mysql_backend`.
169//!   Enabling this feature requires a compatible copy of `libmysqlclient` for your target architecture.
170//!   Alternatively, you can add `mysqlclient-sys` with the `bundled` feature as a dependency to your
171//!   crate so libmysqlclient will be bundled:
172//!   ```toml
173//!   [dependencies]
174//!   mysqlclient-sys = { version = "0.4", features = ["bundled"] }
175//! - `postgres_backend`: This feature enables those parts of diesels postgres backend, that are not dependent
176//!   on `libpq`. Diesel does not provide any connection implementation with only this feature enabled.
177//!   This feature can be used to implement a custom implementation of diesels `Connection` trait for the
178//!   postgres backend outside of diesel itself, while reusing the existing query dsl extensions for the
179//!   postgres backend
180//! - `mysql_backend`: This feature enables those parts of diesels mysql backend, that are not dependent
181//!   on `libmysqlclient`. Diesel does not provide any connection implementation with only this feature enabled.
182//!   This feature can be used to implement a custom implementation of diesels `Connection` trait for the
183//!   mysql backend outside of diesel itself, while reusing the existing query dsl extensions for the
184//!   mysql backend
185//! - `returning_clauses_for_sqlite_3_35`: This feature enables support for `RETURNING` clauses in the sqlite backend.
186//!   Enabling this feature requires sqlite 3.35.0 or newer.
187//! - `32-column-tables`: This feature enables support for tables with up to 32 columns.
188//!   This feature is enabled by default. Consider disabling this feature if you write a library crate
189//!   providing general extensions for diesel or if you do not need to support tables with more than 16 columns
190//!   and you want to minimize your compile times.
191//! - `64-column-tables`: This feature enables support for tables with up to 64 columns. It implies the
192//!   `32-column-tables` feature. Enabling this feature will increase your compile times.
193//! - `128-column-tables`: This feature enables support for tables with up to 128 columns. It implies the
194//!   `64-column-tables` feature. Enabling this feature will increase your compile times significantly.
195//! - `i-implement-a-third-party-backend-and-opt-into-breaking-changes`: This feature opens up some otherwise
196//!   private API, that can be useful to implement a third party [`Backend`](crate::backend::Backend)
197//!   or write a custom [`Connection`] implementation. **Do not use this feature for
198//!   any other usecase**. By enabling this feature you explicitly opt out diesel stability guarantees. We explicitly
199//!   reserve us the right to break API's exported under this feature flag in any upcoming minor version release.
200//!   If you publish a crate depending on this feature flag consider to restrict the supported diesel version to the
201//!   currently released minor version.
202//! - `serde_json`: This feature flag enables support for (de)serializing json values from the database using
203//!   types provided by `serde_json`.
204//! - `chrono`: This feature flags enables support for (de)serializing date/time values from the database using
205//!   types provided by `chrono`
206//! - `uuid`: This feature flag enables support for (de)serializing uuid values from the database using types
207//!   provided by `uuid`
208//! - `network-address`: This feature flag enables support for (de)serializing
209//!   IP values from the database using types provided by `ipnetwork`.
210//! - `ipnet-address`: This feature flag enables support for (de)serializing IP
211//!   values from the database using types provided by `ipnet`.
212//! - `numeric`: This feature flag enables support for (de)serializing numeric values from the database using types
213//!   provided by `bigdecimal`
214//! - `r2d2`: This feature flag enables support for the `r2d2` connection pool implementation.
215//! - `extras`: This feature enables the feature flagged support for any third party crate. This implies the
216//!   following feature flags: `serde_json`, `chrono`, `uuid`, `network-address`, `numeric`, `r2d2`
217//! - `with-deprecated`: This feature enables items marked as `#[deprecated]`. It is enabled by default.
218//!   disabling this feature explicitly opts out diesels stability guarantee.
219//! - `without-deprecated`: This feature disables any item marked as `#[deprecated]`. Enabling this feature
220//!   explicitly opts out the stability guarantee given by diesel. This feature overrides the `with-deprecated`.
221//!   Note that this may also remove items that are not shown as `#[deprecated]` in our documentation, due to
222//!   various bugs in rustdoc. It can be used to check if you depend on any such hidden `#[deprecated]` item.
223//!
224//! By default the following features are enabled:
225//!
226//! - `with-deprecated`
227//! - `32-column-tables`
228
229#![cfg_attr(feature = "unstable", feature(trait_alias))]
230#![cfg_attr(feature = "unstable", feature(strict_provenance_lints))]
231#![cfg_attr(
232    feature = "unstable",
233    warn(fuzzy_provenance_casts, lossy_provenance_casts)
234)]
235#![cfg_attr(diesel_docsrs, feature(doc_cfg, rustdoc_internals))]
236#![cfg_attr(diesel_docsrs, expect(internal_features))]
237#![cfg_attr(feature = "128-column-tables", recursion_limit = "256")]
238// Built-in Lints
239#![warn(
240    unreachable_pub,
241    missing_debug_implementations,
242    missing_copy_implementations,
243    elided_lifetimes_in_paths,
244    missing_docs
245)]
246// Clippy lints
247#![allow(
248    clippy::match_same_arms,
249    clippy::needless_doctest_main,
250    clippy::map_unwrap_or,
251    clippy::redundant_field_names,
252    clippy::type_complexity
253)]
254#![warn(
255    clippy::unwrap_used,
256    clippy::print_stdout,
257    clippy::mut_mut,
258    clippy::non_ascii_literal,
259    clippy::similar_names,
260    clippy::unicode_not_nfc,
261    clippy::enum_glob_use,
262    clippy::if_not_else,
263    clippy::items_after_statements,
264    clippy::used_underscore_binding,
265    clippy::cast_possible_wrap,
266    clippy::cast_possible_truncation,
267    clippy::cast_sign_loss
268)]
269#![deny(unsafe_code)]
270#![cfg_attr(test, allow(clippy::unwrap_used))]
271
272extern crate diesel_derives;
273
274#[macro_use]
275#[doc(hidden)]
276pub mod macros;
277#[doc(hidden)]
278pub mod internal;
279
280#[cfg(test)]
281#[macro_use]
282extern crate cfg_if;
283
284#[cfg(test)]
285pub mod test_helpers;
286
287pub mod associations;
288pub mod backend;
289pub mod connection;
290pub mod data_types;
291pub mod deserialize;
292#[macro_use]
293pub mod expression;
294pub mod expression_methods;
295#[doc(hidden)]
296pub mod insertable;
297pub mod query_builder;
298pub mod query_dsl;
299pub mod query_source;
300#[cfg(feature = "r2d2")]
301pub mod r2d2;
302pub mod result;
303pub mod serialize;
304pub mod upsert;
305#[macro_use]
306pub mod sql_types;
307pub mod migration;
308pub mod row;
309
310#[cfg(feature = "mysql_backend")]
311pub mod mysql;
312#[cfg(feature = "postgres_backend")]
313pub mod pg;
314#[cfg(feature = "sqlite")]
315pub mod sqlite;
316
317#[macro_use]
318mod reexport_ambiguities;
319mod type_impls;
320mod util;
321
322#[doc(hidden)]
323#[cfg(all(feature = "with-deprecated", not(feature = "without-deprecated")))]
324#[deprecated(since = "2.0.0", note = "Use explicit macro imports instead")]
325pub use diesel_derives::{
326    AsChangeset, AsExpression, Associations, DieselNumericOps, FromSqlRow, Identifiable,
327    Insertable, QueryId, Queryable, QueryableByName, SqlType,
328};
329
330pub use diesel_derives::MultiConnection;
331
332pub mod dsl {
333    //! Includes various helper types and bare functions which are named too
334    //! generically to be included in prelude, but are often used when using Diesel.
335
336    #[allow(hidden_glob_reexports, non_camel_case_types, dead_code)]
mod helper_types_proxy {
    #[doc(inline)]
    pub use crate::helper_types::*;
    type abbrev = ();
    type array_append = ();
    type array_cat = ();
    type array_dims = ();
    type array_fill_with_lower_bound = ();
    type array_fill = ();
    type array_length = ();
    type array_lower = ();
    type array_ndims = ();
    type array_position_with_subscript = ();
    type array_position = ();
    type array_positions = ();
    type array_prepend = ();
    type array_remove = ();
    type array_replace = ();
    type array_sample = ();
    type array_shuffle = ();
    type array_to_json = ();
    type array_to_string_with_null_string = ();
    type array_to_string = ();
    type array_upper = ();
    type avg = ();
    type broadcast = ();
    type cardinality = ();
    type family = ();
    type first_value = ();
    type host = ();
    type hostmask = ();
    type inet_merge = ();
    type inet_same_family = ();
    type isempty = ();
    type json_array_length = ();
    type json_build_array_0 = ();
    type json_build_array_1 = ();
    type json_build_array_2 = ();
    type json_extract_path_1 = ();
    type json_extract_path_2 = ();
    type json_extract_path_text_1 = ();
    type json_extract_path_text_2 = ();
    type json_object_with_keys_and_values = ();
    type json_object = ();
    type json_populate_record = ();
    type json_strip_nulls = ();
    type json_typeof = ();
    type jsonb_array_length = ();
    type jsonb_build_array_0 = ();
    type jsonb_build_array_1 = ();
    type jsonb_build_array_2 = ();
    type jsonb_extract_path_1 = ();
    type jsonb_extract_path_2 = ();
    type jsonb_extract_path_text_1 = ();
    type jsonb_extract_path_text_2 = ();
    type jsonb_insert_with_insert_after = ();
    type jsonb_insert = ();
    type jsonb_object_with_keys_and_values = ();
    type jsonb_object = ();
    type jsonb_populate_record = ();
    type jsonb_pretty = ();
    type jsonb_set_create_if_missing = ();
    type jsonb_set_lax = ();
    type jsonb_set = ();
    type jsonb_strip_nulls = ();
    type jsonb_typeof = ();
    type lag_with_offset_and_default = ();
    type lag_with_offset = ();
    type lag = ();
    type last_value = ();
    type lead_with_offset_and_default = ();
    type lead_with_offset = ();
    type lead = ();
    type lower_inc = ();
    type lower_inf = ();
    type lower = ();
    type masklen = ();
    type max = ();
    type min = ();
    type multirange_merge = ();
    type netmask = ();
    type network = ();
    type nth_value = ();
    type range_merge = ();
    type row_to_json = ();
    type set_masklen = ();
    type sum = ();
    type to_json = ();
    type to_jsonb = ();
    type trim_array = ();
    type upper_inc = ();
    type upper_inf = ();
    type upper = ();
    type json = ();
    type json_array_0 = ();
    type json_array_1 = ();
    type json_array_2 = ();
    type json_array_length_with_path = ();
    type json_error_position = ();
    type json_group_array = ();
    type json_group_object = ();
    type json_object_0 = ();
    type json_object_1 = ();
    type json_object_2 = ();
    type json_patch = ();
    type json_pretty = ();
    type json_pretty_with_indentation = ();
    type json_quote = ();
    type json_remove_0 = ();
    type json_remove_1 = ();
    type json_remove_2 = ();
    type json_type = ();
    type json_type_with_path = ();
    type json_valid = ();
    type json_valid_with_flags = ();
    type jsonb = ();
    type jsonb_array_0 = ();
    type jsonb_array_1 = ();
    type jsonb_array_2 = ();
    type jsonb_group_array = ();
    type jsonb_group_object = ();
    type jsonb_object_0 = ();
    type jsonb_object_1 = ();
    type jsonb_object_2 = ();
    type jsonb_patch = ();
    type jsonb_remove_0 = ();
    type jsonb_remove_1 = ();
    type jsonb_remove_2 = ();
}make_proxy_mod!(helper_types_proxy, crate::helper_types);
337    #[doc(inline)]
338    pub use helper_types_proxy::*;
339
340    #[allow(hidden_glob_reexports, non_camel_case_types, dead_code)]
mod expression_dsl_proxy {
    #[doc(inline)]
    pub use crate::expression::dsl::*;
    type abbrev = ();
    type array_append = ();
    type array_cat = ();
    type array_dims = ();
    type array_fill_with_lower_bound = ();
    type array_fill = ();
    type array_length = ();
    type array_lower = ();
    type array_ndims = ();
    type array_position_with_subscript = ();
    type array_position = ();
    type array_positions = ();
    type array_prepend = ();
    type array_remove = ();
    type array_replace = ();
    type array_sample = ();
    type array_shuffle = ();
    type array_to_json = ();
    type array_to_string_with_null_string = ();
    type array_to_string = ();
    type array_upper = ();
    type avg = ();
    type broadcast = ();
    type cardinality = ();
    type family = ();
    type first_value = ();
    type host = ();
    type hostmask = ();
    type inet_merge = ();
    type inet_same_family = ();
    type isempty = ();
    type json_array_length = ();
    type json_build_array_0 = ();
    type json_build_array_1 = ();
    type json_build_array_2 = ();
    type json_extract_path_1 = ();
    type json_extract_path_2 = ();
    type json_extract_path_text_1 = ();
    type json_extract_path_text_2 = ();
    type json_object_with_keys_and_values = ();
    type json_object = ();
    type json_populate_record = ();
    type json_strip_nulls = ();
    type json_typeof = ();
    type jsonb_array_length = ();
    type jsonb_build_array_0 = ();
    type jsonb_build_array_1 = ();
    type jsonb_build_array_2 = ();
    type jsonb_extract_path_1 = ();
    type jsonb_extract_path_2 = ();
    type jsonb_extract_path_text_1 = ();
    type jsonb_extract_path_text_2 = ();
    type jsonb_insert_with_insert_after = ();
    type jsonb_insert = ();
    type jsonb_object_with_keys_and_values = ();
    type jsonb_object = ();
    type jsonb_populate_record = ();
    type jsonb_pretty = ();
    type jsonb_set_create_if_missing = ();
    type jsonb_set_lax = ();
    type jsonb_set = ();
    type jsonb_strip_nulls = ();
    type jsonb_typeof = ();
    type lag_with_offset_and_default = ();
    type lag_with_offset = ();
    type lag = ();
    type last_value = ();
    type lead_with_offset_and_default = ();
    type lead_with_offset = ();
    type lead = ();
    type lower_inc = ();
    type lower_inf = ();
    type lower = ();
    type masklen = ();
    type max = ();
    type min = ();
    type multirange_merge = ();
    type netmask = ();
    type network = ();
    type nth_value = ();
    type range_merge = ();
    type row_to_json = ();
    type set_masklen = ();
    type sum = ();
    type to_json = ();
    type to_jsonb = ();
    type trim_array = ();
    type upper_inc = ();
    type upper_inf = ();
    type upper = ();
    type json = ();
    type json_array_0 = ();
    type json_array_1 = ();
    type json_array_2 = ();
    type json_array_length_with_path = ();
    type json_error_position = ();
    type json_group_array = ();
    type json_group_object = ();
    type json_object_0 = ();
    type json_object_1 = ();
    type json_object_2 = ();
    type json_patch = ();
    type json_pretty = ();
    type json_pretty_with_indentation = ();
    type json_quote = ();
    type json_remove_0 = ();
    type json_remove_1 = ();
    type json_remove_2 = ();
    type json_type = ();
    type json_type_with_path = ();
    type json_valid = ();
    type json_valid_with_flags = ();
    type jsonb = ();
    type jsonb_array_0 = ();
    type jsonb_array_1 = ();
    type jsonb_array_2 = ();
    type jsonb_group_array = ();
    type jsonb_group_object = ();
    type jsonb_object_0 = ();
    type jsonb_object_1 = ();
    type jsonb_object_2 = ();
    type jsonb_patch = ();
    type jsonb_remove_0 = ();
    type jsonb_remove_1 = ();
    type jsonb_remove_2 = ();
}make_proxy_mod!(expression_dsl_proxy, crate::expression::dsl);
341    #[doc(inline)]
342    pub use expression_dsl_proxy::*;
343
344    #[doc(inline)]
345    pub use crate::query_builder::functions::{
346        delete, insert_into, insert_or_ignore_into, replace_into, select, sql_query, update,
347    };
348
349    #[doc(inline)]
350    #[cfg(feature = "postgres_backend")]
351    pub use crate::query_builder::functions::{copy_from, copy_to};
352
353    #[doc(inline)]
354    pub use diesel_derives::auto_type;
355
356    #[cfg(feature = "postgres_backend")]
357    #[doc(inline)]
358    pub use crate::pg::expression::extensions::OnlyDsl;
359
360    #[cfg(feature = "postgres_backend")]
361    #[doc(inline)]
362    pub use crate::pg::expression::extensions::TablesampleDsl;
363}
364
365pub mod helper_types {
366    //! Provide helper types for concisely writing the return type of functions.
367    //! As with iterators, it is unfortunately difficult to return a partially
368    //! constructed query without exposing the exact implementation of the
369    //! function. Without higher kinded types, these various DSLs can't be
370    //! combined into a single trait for boxing purposes.
371    //!
372    //! All types here are in the form `<FirstType as
373    //! DslName<OtherTypes>>::Output`. So the return type of
374    //! `users.filter(first_name.eq("John")).order(last_name.asc()).limit(10)` would
375    //! be `Limit<Order<FindBy<users, first_name, &str>, Asc<last_name>>>`
376    use super::query_builder::combination_clause::{self, CombinationClause};
377    use super::query_builder::{locking_clause as lock, AsQuery};
378    use super::query_dsl::methods::*;
379    use super::query_dsl::*;
380    use super::query_source::{aliasing, joins};
381    use crate::dsl::CountStar;
382    use crate::query_builder::select_clause::SelectClause;
383
384    #[doc(inline)]
385    pub use crate::expression::helper_types::*;
386
387    /// Represents the return type of [`.select(selection)`](crate::prelude::QueryDsl::select)
388    pub type Select<Source, Selection> = <Source as SelectDsl<Selection>>::Output;
389
390    /// Represents the return type of [`diesel::select(selection)`](crate::select)
391    #[allow(non_camel_case_types)] // required for `#[auto_type]`
392    pub type select<Selection> = crate::query_builder::SelectStatement<
393        crate::query_builder::NoFromClause,
394        SelectClause<Selection>,
395    >;
396
397    #[doc(hidden)]
398    #[deprecated(note = "Use `select` instead")]
399    pub type BareSelect<Selection> = crate::query_builder::SelectStatement<
400        crate::query_builder::NoFromClause,
401        SelectClause<Selection>,
402    >;
403
404    /// Represents the return type of [`.filter(predicate)`](crate::prelude::QueryDsl::filter)
405    pub type Filter<Source, Predicate> = <Source as FilterDsl<Predicate>>::Output;
406
407    /// Represents the return type of [`.filter(lhs.eq(rhs))`](crate::prelude::QueryDsl::filter)
408    pub type FindBy<Source, Column, Value> = Filter<Source, Eq<Column, Value>>;
409
410    /// Represents the return type of [`.for_update()`](crate::prelude::QueryDsl::for_update)
411    pub type ForUpdate<Source> = <Source as LockingDsl<lock::ForUpdate>>::Output;
412
413    /// Represents the return type of [`.for_no_key_update()`](crate::prelude::QueryDsl::for_no_key_update)
414    pub type ForNoKeyUpdate<Source> = <Source as LockingDsl<lock::ForNoKeyUpdate>>::Output;
415
416    /// Represents the return type of [`.for_share()`](crate::prelude::QueryDsl::for_share)
417    pub type ForShare<Source> = <Source as LockingDsl<lock::ForShare>>::Output;
418
419    /// Represents the return type of [`.for_key_share()`](crate::prelude::QueryDsl::for_key_share)
420    pub type ForKeyShare<Source> = <Source as LockingDsl<lock::ForKeyShare>>::Output;
421
422    /// Represents the return type of [`.skip_locked()`](crate::prelude::QueryDsl::skip_locked)
423    pub type SkipLocked<Source> = <Source as ModifyLockDsl<lock::SkipLocked>>::Output;
424
425    /// Represents the return type of [`.no_wait()`](crate::prelude::QueryDsl::no_wait)
426    pub type NoWait<Source> = <Source as ModifyLockDsl<lock::NoWait>>::Output;
427
428    /// Represents the return type of [`.find(pk)`](crate::prelude::QueryDsl::find)
429    pub type Find<Source, PK> = <Source as FindDsl<PK>>::Output;
430
431    /// Represents the return type of [`.or_filter(predicate)`](crate::prelude::QueryDsl::or_filter)
432    pub type OrFilter<Source, Predicate> = <Source as OrFilterDsl<Predicate>>::Output;
433
434    /// Represents the return type of [`.order(ordering)`](crate::prelude::QueryDsl::order)
435    pub type Order<Source, Ordering> = <Source as OrderDsl<Ordering>>::Output;
436
437    /// Represents the return type of [`.order_by(ordering)`](crate::prelude::QueryDsl::order_by)
438    ///
439    /// Type alias of [Order]
440    pub type OrderBy<Source, Ordering> = Order<Source, Ordering>;
441
442    /// Represents the return type of [`.then_order_by(ordering)`](crate::prelude::QueryDsl::then_order_by)
443    pub type ThenOrderBy<Source, Ordering> = <Source as ThenOrderDsl<Ordering>>::Output;
444
445    /// Represents the return type of [`.limit()`](crate::prelude::QueryDsl::limit)
446    pub type Limit<Source, DummyArgForAutoType = i64> =
447        <Source as LimitDsl<DummyArgForAutoType>>::Output;
448
449    /// Represents the return type of [`.offset()`](crate::prelude::QueryDsl::offset)
450    pub type Offset<Source, DummyArgForAutoType = i64> =
451        <Source as OffsetDsl<DummyArgForAutoType>>::Output;
452
453    /// Represents the return type of [`.inner_join(rhs)`](crate::prelude::QueryDsl::inner_join)
454    pub type InnerJoin<Source, Rhs> =
455        <Source as JoinWithImplicitOnClause<Rhs, joins::Inner>>::Output;
456
457    /// Represents the return type of [`.inner_join(rhs.on(on))`](crate::prelude::QueryDsl::inner_join)
458    pub type InnerJoinOn<Source, Rhs, On> =
459        <Source as InternalJoinDsl<Rhs, joins::Inner, On>>::Output;
460
461    /// Represents the return type of [`.left_join(rhs)`](crate::prelude::QueryDsl::left_join)
462    pub type LeftJoin<Source, Rhs> =
463        <Source as JoinWithImplicitOnClause<Rhs, joins::LeftOuter>>::Output;
464
465    /// Represents the return type of [`.left_join(rhs.on(on))`](crate::prelude::QueryDsl::left_join)
466    pub type LeftJoinOn<Source, Rhs, On> =
467        <Source as InternalJoinDsl<Rhs, joins::LeftOuter, On>>::Output;
468
469    /// Represents the return type of [`rhs.on(on)`](crate::query_dsl::JoinOnDsl::on)
470    pub type On<Source, On> = joins::OnClauseWrapper<Source, On>;
471
472    use super::associations::HasTable;
473    use super::query_builder::{AsChangeset, IntoUpdateTarget, UpdateStatement};
474
475    /// Represents the return type of [`update(lhs).set(rhs)`](crate::query_builder::UpdateStatement::set)
476    pub type Update<Target, Changes> = UpdateStatement<
477        <Target as HasTable>::Table,
478        <Target as IntoUpdateTarget>::WhereClause,
479        <Changes as AsChangeset>::Changeset,
480    >;
481
482    /// Represents the return type of [`.into_boxed::<'a, DB>()`](crate::prelude::QueryDsl::into_boxed)
483    pub type IntoBoxed<'a, Source, DB> = <Source as BoxedDsl<'a, DB>>::Output;
484
485    /// Represents the return type of [`.distinct()`](crate::prelude::QueryDsl::distinct)
486    pub type Distinct<Source> = <Source as DistinctDsl>::Output;
487
488    /// Represents the return type of [`.distinct_on(expr)`](crate::prelude::QueryDsl::distinct_on)
489    #[cfg(feature = "postgres_backend")]
490    pub type DistinctOn<Source, Expr> = <Source as DistinctOnDsl<Expr>>::Output;
491
492    /// Represents the return type of [`.single_value()`](SingleValueDsl::single_value)
493    pub type SingleValue<Source> = <Source as SingleValueDsl>::Output;
494
495    /// Represents the return type of [`.nullable()`](SelectNullableDsl::nullable)
496    pub type NullableSelect<Source> = <Source as SelectNullableDsl>::Output;
497
498    /// Represents the return type of [`.group_by(expr)`](crate::prelude::QueryDsl::group_by)
499    pub type GroupBy<Source, Expr> = <Source as GroupByDsl<Expr>>::Output;
500
501    /// Represents the return type of [`.having(predicate)`](crate::prelude::QueryDsl::having)
502    pub type Having<Source, Predicate> = <Source as HavingDsl<Predicate>>::Output;
503
504    /// Represents the return type of [`.union(rhs)`](crate::prelude::CombineDsl::union)
505    pub type Union<Source, Rhs> = CombinationClause<
506        combination_clause::Union,
507        combination_clause::Distinct,
508        <Source as CombineDsl>::Query,
509        <Rhs as AsQuery>::Query,
510    >;
511
512    /// Represents the return type of [`.union_all(rhs)`](crate::prelude::CombineDsl::union_all)
513    pub type UnionAll<Source, Rhs> = CombinationClause<
514        combination_clause::Union,
515        combination_clause::All,
516        <Source as CombineDsl>::Query,
517        <Rhs as AsQuery>::Query,
518    >;
519
520    /// Represents the return type of [`.intersect(rhs)`](crate::prelude::CombineDsl::intersect)
521    pub type Intersect<Source, Rhs> = CombinationClause<
522        combination_clause::Intersect,
523        combination_clause::Distinct,
524        <Source as CombineDsl>::Query,
525        <Rhs as AsQuery>::Query,
526    >;
527
528    /// Represents the return type of [`.intersect_all(rhs)`](crate::prelude::CombineDsl::intersect_all)
529    pub type IntersectAll<Source, Rhs> = CombinationClause<
530        combination_clause::Intersect,
531        combination_clause::All,
532        <Source as CombineDsl>::Query,
533        <Rhs as AsQuery>::Query,
534    >;
535
536    /// Represents the return type of [`.except(rhs)`](crate::prelude::CombineDsl::except)
537    pub type Except<Source, Rhs> = CombinationClause<
538        combination_clause::Except,
539        combination_clause::Distinct,
540        <Source as CombineDsl>::Query,
541        <Rhs as AsQuery>::Query,
542    >;
543
544    /// Represents the return type of [`.except_all(rhs)`](crate::prelude::CombineDsl::except_all)
545    pub type ExceptAll<Source, Rhs> = CombinationClause<
546        combination_clause::Except,
547        combination_clause::All,
548        <Source as CombineDsl>::Query,
549        <Rhs as AsQuery>::Query,
550    >;
551
552    type JoinQuerySource<Left, Right, Kind, On> = joins::JoinOn<joins::Join<Left, Right, Kind>, On>;
553
554    /// A query source representing the inner join between two tables.
555    ///
556    /// The third generic type (`On`) controls how the tables are
557    /// joined.
558    ///
559    /// By default, the implicit join established by [`joinable!`][]
560    /// will be used, allowing you to omit the exact join
561    /// condition. For example, for the inner join between three
562    /// tables that implement [`JoinTo`][], you only need to specify
563    /// the tables: `InnerJoinQuerySource<InnerJoinQuerySource<table1,
564    /// table2>, table3>`.
565    ///
566    /// [`JoinTo`]: crate::query_source::JoinTo
567    ///
568    /// If you use an explicit `ON` clause, you will need to specify
569    /// the `On` generic type.
570    ///
571    /// ```rust
572    /// # include!("doctest_setup.rs");
573    /// use diesel::{dsl, helper_types::InnerJoinQuerySource};
574    /// # use diesel::{backend::Backend, serialize::ToSql, sql_types};
575    /// use schema::*;
576    ///
577    /// # fn main() -> QueryResult<()> {
578    /// #     let conn = &mut establish_connection();
579    /// #
580    /// // If you have an explicit join like this...
581    /// let join_constraint = comments::columns::post_id.eq(posts::columns::id);
582    /// #     let query =
583    /// posts::table.inner_join(comments::table.on(join_constraint));
584    /// #
585    /// #     // Dummy usage just to ensure the example compiles.
586    /// #     let filter = posts::columns::id.eq(1);
587    /// #     let filter: &FilterExpression<_> = &filter;
588    /// #     query.filter(filter).select(posts::columns::id).get_result::<i32>(conn)?;
589    /// #
590    /// #     Ok(())
591    /// # }
592    ///
593    /// // ... you can use `InnerJoinQuerySource` like this.
594    /// type JoinConstraint = dsl::Eq<comments::columns::post_id, posts::columns::id>;
595    /// type MyInnerJoinQuerySource = InnerJoinQuerySource<posts::table, comments::table, JoinConstraint>;
596    /// # type FilterExpression<DB> = dyn BoxableExpression<MyInnerJoinQuerySource, DB, SqlType = sql_types::Bool>;
597    /// ```
598    pub type InnerJoinQuerySource<Left, Right, On = <Left as joins::JoinTo<Right>>::OnClause> =
599        JoinQuerySource<Left, Right, joins::Inner, On>;
600
601    /// A query source representing the left outer join between two tables.
602    ///
603    /// The third generic type (`On`) controls how the tables are
604    /// joined.
605    ///
606    /// By default, the implicit join established by [`joinable!`][]
607    /// will be used, allowing you to omit the exact join
608    /// condition. For example, for the left join between three
609    /// tables that implement [`JoinTo`][], you only need to specify
610    /// the tables: `LeftJoinQuerySource<LeftJoinQuerySource<table1,
611    /// table2>, table3>`.
612    ///
613    /// [`JoinTo`]: crate::query_source::JoinTo
614    ///
615    /// If you use an explicit `ON` clause, you will need to specify
616    /// the `On` generic type.
617    ///
618    /// ```rust
619    /// # include!("doctest_setup.rs");
620    /// use diesel::{dsl, helper_types::LeftJoinQuerySource};
621    /// # use diesel::{backend::Backend, serialize::ToSql, sql_types};
622    /// use schema::*;
623    ///
624    /// # fn main() -> QueryResult<()> {
625    /// #     let conn = &mut establish_connection();
626    /// #
627    /// // If you have an explicit join like this...
628    /// let join_constraint = comments::columns::post_id.eq(posts::columns::id);
629    /// #     let query =
630    /// posts::table.left_join(comments::table.on(join_constraint));
631    /// #
632    /// #     // Dummy usage just to ensure the example compiles.
633    /// #     let filter = posts::columns::id.eq(1);
634    /// #     let filter: &FilterExpression<_> = &filter;
635    /// #     query.filter(filter).select(posts::columns::id).get_result::<i32>(conn)?;
636    /// #
637    /// #     Ok(())
638    /// # }
639    ///
640    /// // ... you can use `LeftJoinQuerySource` like this.
641    /// type JoinConstraint = dsl::Eq<comments::columns::post_id, posts::columns::id>;
642    /// type MyLeftJoinQuerySource = LeftJoinQuerySource<posts::table, comments::table, JoinConstraint>;
643    /// # type FilterExpression<DB> = dyn BoxableExpression<MyLeftJoinQuerySource, DB, SqlType = sql_types::Bool>;
644    /// ```
645    pub type LeftJoinQuerySource<Left, Right, On = <Left as joins::JoinTo<Right>>::OnClause> =
646        JoinQuerySource<Left, Right, joins::LeftOuter, On>;
647
648    /// Maps `F` to `Alias<S>`
649    ///
650    /// Any column `F` that belongs to `S::Table` will be transformed into
651    /// [`AliasedField<S, Self>`](crate::query_source::AliasedField)
652    ///
653    /// Any column `F` that does not belong to `S::Table` will be left untouched.
654    ///
655    /// This also works with tuples and some expressions.
656    pub type AliasedFields<S, F> = <F as aliasing::FieldAliasMapper<S>>::Out;
657
658    #[doc(hidden)]
659    #[cfg(all(feature = "with-deprecated", not(feature = "without-deprecated")))]
660    #[deprecated(note = "Use `LoadQuery::RowIter` directly")]
661    pub type LoadIter<'conn, 'query, Q, Conn, U, B = crate::connection::DefaultLoadingMode> =
662        <Q as load_dsl::LoadQuery<'query, Conn, U, B>>::RowIter<'conn>;
663
664    /// Represents the return type of [`diesel::delete`]
665    #[allow(non_camel_case_types)] // required for `#[auto_type]`
666    pub type delete<T> = crate::query_builder::DeleteStatement<
667        <T as HasTable>::Table,
668        <T as IntoUpdateTarget>::WhereClause,
669    >;
670
671    /// Represents the return type of [`diesel::insert_into`]
672    #[allow(non_camel_case_types)] // required for `#[auto_type]`
673    pub type insert_into<T> = crate::query_builder::IncompleteInsertStatement<T>;
674
675    /// Represents the return type of [`diesel::update`]
676    #[allow(non_camel_case_types)] // required for `#[auto_type]`
677    pub type update<T> =
678        UpdateStatement<<T as HasTable>::Table, <T as IntoUpdateTarget>::WhereClause>;
679
680    /// Represents the return type of [`diesel::insert_or_ignore_into`]
681    #[allow(non_camel_case_types)] // required for `#[auto_type]`
682    pub type insert_or_ignore_into<T> = crate::query_builder::IncompleteInsertOrIgnoreStatement<T>;
683
684    /// Represents the return type of [`diesel::replace_into`]
685    #[allow(non_camel_case_types)] // required for `#[auto_type]`
686    pub type replace_into<T> = crate::query_builder::IncompleteReplaceStatement<T>;
687
688    /// Represents the return type of
689    /// [`IncompleteInsertStatement::values()`](crate::query_builder::IncompleteInsertStatement::values)
690    pub type Values<I, U> = crate::query_builder::InsertStatement<
691        <I as crate::query_builder::insert_statement::InsertAutoTypeHelper>::Table,
692        <U as crate::Insertable<
693            <I as crate::query_builder::insert_statement::InsertAutoTypeHelper>::Table,
694        >>::Values,
695        <I as crate::query_builder::insert_statement::InsertAutoTypeHelper>::Op,
696    >;
697
698    /// Represents the return type of
699    /// [`UpdateStatement::set()`](crate::query_builder::UpdateStatement::set)
700    pub type Set<U, V> = crate::query_builder::UpdateStatement<
701        <U as crate::query_builder::update_statement::UpdateAutoTypeHelper>::Table,
702        <U as crate::query_builder::update_statement::UpdateAutoTypeHelper>::Where,
703        <V as crate::AsChangeset>::Changeset,
704    >;
705
706    /// Represents the return type of
707    /// [`InsertStatement::returning`](crate::query_builder::InsertStatement::returning),
708    /// [`UpdateStatement::returning`] and
709    /// [`DeleteStatement::returning`](crate::query_builder::DeleteStatement::returning)
710    pub type Returning<Q, S> =
711        <Q as crate::query_builder::returning_clause::ReturningClauseHelper<S>>::WithReturning;
712
713    #[doc(hidden)] // used for `QueryDsl::count`
714    pub type Count<Q> = Select<Q, CountStar>;
715}
716
717pub mod prelude {
718
719    //! Re-exports important traits and types. Meant to be glob imported when using Diesel.
720
721    #[doc(inline)]
722    pub use crate::associations::{Associations, GroupedBy, Identifiable};
723    #[doc(inline)]
724    pub use crate::connection::Connection;
725    #[doc(inline)]
726    pub use crate::deserialize::{Queryable, QueryableByName};
727    #[doc(inline)]
728    pub use crate::expression::{
729        AppearsOnTable, BoxableExpression, Expression, IntoSql, Selectable, SelectableExpression,
730    };
731    // If [`IntoSql`](crate::expression::helper_types::IntoSql) the type gets imported at the
732    // same time as IntoSql the trait (this one) gets imported via the prelude, then
733    // methods of the trait won't be resolved because the type may take priority over the trait.
734    // That issue can be avoided by also importing it anonymously:
735    pub use crate::expression::IntoSql as _;
736
737    #[doc(inline)]
738    pub use crate::expression::functions::declare_sql_function;
739    #[doc(inline)]
740    pub use crate::expression::functions::define_sql_function;
741    #[cfg(all(feature = "with-deprecated", not(feature = "without-deprecated")))]
742    pub use crate::expression::functions::sql_function;
743
744    #[doc(inline)]
745    pub use crate::expression::SelectableHelper;
746    #[doc(inline)]
747    pub use crate::expression_methods::*;
748    #[doc(inline)]
749    pub use crate::insertable::Insertable;
750    #[doc(inline)]
751    pub use crate::macros::prelude::*;
752    #[doc(inline)]
753    pub use crate::query_builder::has_query::HasQuery;
754    #[doc(inline)]
755    pub use crate::query_builder::AsChangeset;
756    #[doc(inline)]
757    pub use crate::query_builder::DecoratableTarget;
758    #[doc(inline)]
759    pub use crate::query_dsl::{
760        BelongingToDsl, CombineDsl, JoinOnDsl, QueryDsl, RunQueryDsl, SaveChangesDsl,
761    };
762    pub use crate::query_source::SizeRestrictedColumn as _;
763    #[doc(inline)]
764    pub use crate::query_source::{Column, JoinTo, QuerySource, Table};
765    #[doc(inline)]
766    pub use crate::result::{
767        ConnectionError, ConnectionResult, OptionalEmptyChangesetExtension, OptionalExtension,
768        QueryResult,
769    };
770    #[doc(inline)]
771    pub use diesel_derives::table_proc as table;
772
773    #[cfg(feature = "mysql")]
774    #[doc(inline)]
775    pub use crate::mysql::MysqlConnection;
776    #[doc(inline)]
777    #[cfg(feature = "postgres_backend")]
778    pub use crate::pg::query_builder::copy::ExecuteCopyFromDsl;
779    #[cfg(feature = "postgres")]
780    #[doc(inline)]
781    pub use crate::pg::PgConnection;
782    #[cfg(feature = "sqlite")]
783    #[doc(inline)]
784    pub use crate::sqlite::SqliteConnection;
785}
786
787#[doc(inline)]
788pub use crate::macros::table;
789pub use crate::prelude::*;
790#[doc(inline)]
791pub use crate::query_builder::debug_query;
792#[doc(inline)]
793#[cfg(feature = "postgres")]
794pub use crate::query_builder::functions::{copy_from, copy_to};
795#[doc(inline)]
796pub use crate::query_builder::functions::{
797    delete, insert_into, insert_or_ignore_into, replace_into, select, sql_query, update,
798};
799pub use crate::result::Error::NotFound;
800
801extern crate self as diesel;