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