diesel/query_dsl/
mod.rs

1//! Traits that construct SELECT statements
2//!
3//! Traits in this module have methods that generally map to the keyword for the corresponding clause in SQL,
4//! unless it conflicts with a Rust keyword (such as `WHERE`/`where`).
5//!
6//! Methods for constructing queries lives on the [`QueryDsl`] trait.
7//! Methods for executing queries live on [`RunQueryDsl`].
8//!
9//! See also [`expression_methods`][expression_methods] and [`dsl`][dsl].
10//!
11//! [expression_methods]: super::expression_methods
12//! [dsl]: super::dsl
13
14use crate::backend::Backend;
15use crate::connection::Connection;
16use crate::expression::count::CountStar;
17use crate::expression::Expression;
18use crate::helper_types::*;
19use crate::query_builder::locking_clause as lock;
20use crate::query_source::{joins, Table};
21use crate::result::QueryResult;
22
23mod belonging_to_dsl;
24#[doc(hidden)]
25pub mod boxed_dsl;
26mod combine_dsl;
27mod distinct_dsl;
28#[doc(hidden)]
29pub mod filter_dsl;
30mod group_by_dsl;
31mod having_dsl;
32mod join_dsl;
33#[doc(hidden)]
34pub mod limit_dsl;
35#[doc(hidden)]
36pub mod load_dsl;
37mod locking_dsl;
38mod nullable_select_dsl;
39mod offset_dsl;
40pub(crate) mod order_dsl;
41#[doc(hidden)]
42pub mod positional_order_dsl;
43mod save_changes_dsl;
44#[doc(hidden)]
45pub mod select_dsl;
46mod single_value_dsl;
47
48pub use self::belonging_to_dsl::BelongingToDsl;
49pub use self::combine_dsl::CombineDsl;
50pub use self::join_dsl::{InternalJoinDsl, JoinOnDsl, JoinWithImplicitOnClause};
51#[cfg(feature = "i-implement-a-third-party-backend-and-opt-into-breaking-changes")]
52pub use self::load_dsl::CompatibleType;
53#[doc(hidden)]
54pub use self::load_dsl::LoadQuery;
55pub use self::save_changes_dsl::{SaveChangesDsl, UpdateAndFetchResults};
56
57/// The traits used by `QueryDsl`.
58///
59/// Each trait in this module represents exactly one method from `QueryDsl`.
60/// Apps should general rely on `QueryDsl` directly, rather than these traits.
61/// However, generic code may need to include a where clause that references
62/// these traits.
63pub mod methods {
64    pub use super::boxed_dsl::BoxedDsl;
65    pub use super::distinct_dsl::*;
66    #[doc(inline)]
67    pub use super::filter_dsl::*;
68    pub use super::group_by_dsl::GroupByDsl;
69    pub use super::having_dsl::HavingDsl;
70    pub use super::limit_dsl::LimitDsl;
71    pub use super::load_dsl::{ExecuteDsl, LoadQuery};
72    pub use super::locking_dsl::{LockingDsl, ModifyLockDsl};
73    pub use super::nullable_select_dsl::SelectNullableDsl;
74    pub use super::offset_dsl::OffsetDsl;
75    pub use super::order_dsl::{OrderDsl, ThenOrderDsl};
76    pub use super::select_dsl::SelectDsl;
77    pub use super::single_value_dsl::SingleValueDsl;
78
79    #[cfg(all(feature = "with-deprecated", not(feature = "without-deprecated")))]
80    #[doc(hidden)]
81    #[allow(deprecated)]
82    #[deprecated(note = "Use `LoadQuery::RowIter` directly")]
83    pub use super::load_dsl::LoadRet;
84}
85
86/// Methods used to construct select statements.
87pub trait QueryDsl: Sized {
88    /// Adds the `DISTINCT` keyword to a query.
89    ///
90    /// This method will override any previous distinct clause that was present.
91    /// For example, on PostgreSQL, `foo.distinct_on(bar).distinct()` will
92    /// create the same query as `foo.distinct()`.
93    ///
94    /// # Example
95    ///
96    /// ```rust
97    /// # include!("../doctest_setup.rs");
98    /// #
99    /// # fn main() {
100    /// #     run_test().unwrap();
101    /// # }
102    /// #
103    /// # fn run_test() -> QueryResult<()> {
104    /// #     use schema::users::dsl::*;
105    /// #     let connection = &mut establish_connection();
106    /// #     diesel::sql_query("DELETE FROM users").execute(connection).unwrap();
107    /// diesel::insert_into(users)
108    ///     .values(&vec![name.eq("Sean"); 3])
109    ///     .execute(connection)?;
110    /// let names = users.select(name).load::<String>(connection)?;
111    /// let distinct_names = users.select(name).distinct().load::<String>(connection)?;
112    ///
113    /// assert_eq!(vec!["Sean"; 3], names);
114    /// assert_eq!(vec!["Sean"; 1], distinct_names);
115    /// #     Ok(())
116    /// # }
117    /// ```
118    fn distinct(self) -> Distinct<Self>
119    where
120        Self: methods::DistinctDsl,
121    {
122        methods::DistinctDsl::distinct(self)
123    }
124
125    /// Adds the `DISTINCT ON` clause to a query.
126    ///
127    /// # Example
128    ///
129    /// ```rust
130    /// # include!("../doctest_setup.rs");
131    /// # use schema::animals;
132    /// #
133    /// # #[derive(Queryable, Debug, PartialEq)]
134    /// # struct Animal {
135    /// #     species: String,
136    /// #     name: Option<String>,
137    /// #     legs: i32,
138    /// # }
139    /// #
140    /// # impl Animal {
141    /// #     fn new<S: Into<String>>(species: S, name: Option<&str>, legs: i32) -> Self {
142    /// #         Animal {
143    /// #             species: species.into(),
144    /// #             name: name.map(Into::into),
145    /// #             legs
146    /// #         }
147    /// #     }
148    /// # }
149    /// #
150    /// # fn main() {
151    /// #     use self::animals::dsl::*;
152    /// #     let connection = &mut establish_connection();
153    /// #     diesel::sql_query("DELETE FROM animals").execute(connection).unwrap();
154    /// diesel::insert_into(animals)
155    ///     .values(&vec![
156    ///         (species.eq("dog"), name.eq(Some("Jack")), legs.eq(4)),
157    ///         (species.eq("dog"), name.eq(None), legs.eq(4)),
158    ///         (species.eq("spider"), name.eq(None), legs.eq(8)),
159    ///     ])
160    ///     .execute(connection)
161    ///     .unwrap();
162    /// let all_animals = animals.select((species, name, legs)).load(connection);
163    /// let distinct_animals = animals
164    ///     .select((species, name, legs))
165    ///     .order_by((species, legs))
166    ///     .distinct_on(species)
167    ///     .load(connection);
168    ///
169    /// assert_eq!(Ok(vec![Animal::new("dog", Some("Jack"), 4),
170    ///                    Animal::new("dog", None, 4),
171    ///                    Animal::new("spider", None, 8)]), all_animals);
172    /// assert_eq!(Ok(vec![Animal::new("dog", Some("Jack"), 4),
173    ///                    Animal::new("spider", None, 8)]), distinct_animals);
174    /// # }
175    /// ```
176    #[cfg(feature = "postgres_backend")]
177    fn distinct_on<Expr>(self, expr: Expr) -> DistinctOn<Self, Expr>
178    where
179        Self: methods::DistinctOnDsl<Expr>,
180    {
181        methods::DistinctOnDsl::distinct_on(self, expr)
182    }
183
184    // FIXME: Needs usage example and doc rewrite
185    /// Adds a `SELECT` clause to the query.
186    ///
187    /// If there was already a select clause present, it will be overridden.
188    /// For example, `foo.select(bar).select(baz)` will produce the same
189    /// query as `foo.select(baz)`.
190    ///
191    /// By default, the select clause will be roughly equivalent to `SELECT *`
192    /// (however, Diesel will list all columns to ensure that they are in the
193    /// order we expect).
194    ///
195    /// `select` has slightly stricter bounds on its arguments than other
196    /// methods. In particular, when used with a left outer join, `.nullable`
197    /// must be called on columns that come from the right side of a join. It
198    /// can be called on the column itself, or on an expression containing that
199    /// column. `title.nullable()`, `lower(title).nullable()`, and `(id,
200    /// title).nullable()` would all be valid.
201    ///
202    /// In order to use this method with columns from different tables
203    /// a method like [`.inner_join`] or [`.left_join`] needs to be called before
204    /// calling [`.select`] (See examples below).
205    /// This is because you can only access columns from tables
206    /// that appear in your query before that function call.
207    ///
208    /// [`.inner_join`]: QueryDsl::inner_join()
209    /// [`.left_join`]: QueryDsl::left_join()
210    /// [`.select`]: QueryDsl::select()
211    ///
212    /// # Examples
213    ///
214    /// ```rust
215    /// # include!("../doctest_setup.rs");
216    /// # use schema::users;
217    /// #
218    /// # fn main() {
219    /// #     run_test().unwrap();
220    /// # }
221    /// #
222    /// # fn run_test() -> QueryResult<()> {
223    /// #     use self::users::dsl::*;
224    /// #     let connection = &mut establish_connection();
225    /// // By default, all columns will be selected
226    /// let all_users = users.load::<(i32, String)>(connection)?;
227    /// assert_eq!(vec![(1, String::from("Sean")), (2, String::from("Tess"))], all_users);
228    ///
229    /// let all_names = users.select(name).load::<String>(connection)?;
230    /// assert_eq!(vec!["Sean", "Tess"], all_names);
231    /// #     Ok(())
232    /// # }
233    /// ```
234    ///
235    /// ### When used with a left join
236    ///
237    /// ```rust
238    /// # include!("../doctest_setup.rs");
239    /// # use schema::{users, posts};
240    /// #
241    /// # #[derive(Queryable, PartialEq, Eq, Debug)]
242    /// # struct User {
243    /// #     id: i32,
244    /// #     name: String,
245    /// # }
246    /// #
247    /// # impl User {
248    /// #     fn new(id: i32, name: &str) -> Self {
249    /// #         User {
250    /// #             id,
251    /// #             name: name.into(),
252    /// #         }
253    /// #     }
254    /// # }
255    /// #
256    /// # #[derive(Queryable, PartialEq, Eq, Debug)]
257    /// # struct Post {
258    /// #     id: i32,
259    /// #     user_id: i32,
260    /// #     title: String,
261    /// # }
262    /// #
263    /// # impl Post {
264    /// #     fn new(id: i32, user_id: i32, title: &str) -> Self {
265    /// #         Post {
266    /// #             id,
267    /// #             user_id,
268    /// #             title: title.into(),
269    /// #         }
270    /// #     }
271    /// # }
272    /// #
273    /// # fn main() {
274    /// #     run_test().unwrap();
275    /// # }
276    /// #
277    /// # fn run_test() -> QueryResult<()> {
278    /// #     let connection = &mut establish_connection();
279    /// #     diesel::sql_query("DELETE FROM posts").execute(connection)?;
280    /// #     diesel::insert_into(posts::table)
281    /// #         .values((posts::user_id.eq(1), posts::title.eq("Sean's Post")))
282    /// #         .execute(connection)?;
283    /// #     let post_id = posts::table.select(posts::id)
284    /// #         .first::<i32>(connection)?;
285    /// let join = users::table.left_join(posts::table);
286    ///
287    /// // By default, all columns from both tables are selected.
288    /// // If no explicit select clause is used this means that the result
289    /// // type of this query must contain all fields from the original schema in order.
290    /// let all_data = join.load::<(User, Option<Post>)>(connection)?;
291    /// let expected_data = vec![
292    ///     (User::new(1, "Sean"), Some(Post::new(post_id, 1, "Sean's Post"))),
293    ///     (User::new(2, "Tess"), None),
294    /// ];
295    /// assert_eq!(expected_data, all_data);
296    ///
297    /// // Since `posts` is on the right side of a left join, `.nullable` is
298    /// // needed.
299    /// let names_and_titles = join.select((users::name, posts::title.nullable()))
300    ///     .load::<(String, Option<String>)>(connection)?;
301    /// let expected_data = vec![
302    ///     (String::from("Sean"), Some(String::from("Sean's Post"))),
303    ///     (String::from("Tess"), None),
304    /// ];
305    /// assert_eq!(expected_data, names_and_titles);
306    /// #     Ok(())
307    /// # }
308    /// ```
309    fn select<Selection>(self, selection: Selection) -> Select<Self, Selection>
310    where
311        Selection: Expression,
312        Self: methods::SelectDsl<Selection>,
313    {
314        methods::SelectDsl::select(self, selection)
315    }
316
317    /// Get the count of a query. This is equivalent to `.select(count_star())`
318    ///
319    /// # Example
320    ///
321    /// ```rust
322    /// # include!("../doctest_setup.rs");
323    /// #
324    /// # fn main() {
325    /// #     use schema::users::dsl::*;
326    /// #     let connection = &mut establish_connection();
327    /// let count = users.count().get_result(connection);
328    /// assert_eq!(Ok(2), count);
329    /// # }
330    /// ```
331    fn count(self) -> Select<Self, CountStar>
332    where
333        Self: methods::SelectDsl<CountStar>,
334    {
335        use crate::dsl::count_star;
336
337        QueryDsl::select(self, count_star())
338    }
339
340    /// Join two tables using a SQL `INNER JOIN`.
341    ///
342    /// If you have invoked [`joinable!`] for the two tables, you can pass that
343    /// table directly.  Otherwise you will need to use [`.on`] to specify the `ON`
344    /// clause.
345    ///
346    /// [`joinable!`]: crate::joinable!
347    /// [`.on`]: JoinOnDsl::on()
348    ///
349    /// You can join to as many tables as you'd like in a query, with the
350    /// restriction that no table can appear in the query more than once. For
351    /// tables that appear more than once in a single query the usage of [`alias!`](crate::alias!)
352    /// is required.
353    ///
354    /// You will also need to call [`allow_tables_to_appear_in_same_query!`].
355    /// If you are using `diesel print-schema`, this will
356    /// have been generated for you.
357    /// See the documentation for [`allow_tables_to_appear_in_same_query!`] for
358    /// details.
359    ///
360    /// Diesel expects multi-table joins to be semantically grouped based on the
361    /// relationships. For example, `users.inner_join(posts.inner_join(comments))`
362    /// is not the same as `users.inner_join(posts).inner_join(comments)`. The first
363    /// would deserialize into `(User, (Post, Comment))` and generate the following
364    /// SQL:
365    ///
366    /// ```sql
367    /// SELECT * FROM users
368    ///     INNER JOIN (
369    ///         posts
370    ///         INNER JOIN comments ON comments.post_id = posts.id
371    ///     ) ON posts.user_id = users.id
372    ///
373    /// ```
374    ///
375    /// While the second query would deserialize into `(User, Post, Comment)` and
376    /// generate the following SQL:
377    ///
378    /// ```sql
379    /// SELECT * FROM users
380    ///     INNER JOIN posts ON posts.user_id = users.id
381    ///     INNER JOIN comments ON comments.user_id = users.id
382    /// ```
383    ///
384    /// The exact generated SQL may change in future diesel version as long as the
385    /// generated query continues to produce same results. The currently generated
386    /// SQL is referred as ["explicit join"](https://www.postgresql.org/docs/current/explicit-joins.html)
387    /// by the PostgreSQL documentation and may have implications on the chosen query plan
388    /// for large numbers of joins in the same query. Checkout the documentation of the
389    /// [`join_collapse_limit` parameter](https://www.postgresql.org/docs/current/runtime-config-query.html#GUC-JOIN-COLLAPSE-LIMIT)
390    /// to control this behaviour.
391    ///
392    /// [associations]: crate::associations
393    /// [`allow_tables_to_appear_in_same_query!`]: crate::allow_tables_to_appear_in_same_query!
394    ///
395    /// Note that in order to use this method with [`.select`], you will need to use it before calling
396    /// [`.select`] (See examples below). This is because you can only access columns from tables
397    /// that appear in your query before the call to [`.select`].
398    ///
399    /// [`.select`]: QueryDsl::select()
400    ///
401    /// # Examples
402    ///
403    /// ### With implicit `ON` clause
404    ///
405    /// ```rust
406    /// # include!("../doctest_setup.rs");
407    /// # use schema::{users, posts};
408    /// # /*
409    /// joinable!(posts -> users (user_id));
410    /// allow_tables_to_appear_in_same_query!(users, posts);
411    /// # */
412    ///
413    /// # fn main() {
414    /// #     use self::users::dsl::{users, name};
415    /// #     use self::posts::dsl::{posts, user_id, title};
416    /// #     let connection = &mut establish_connection();
417    /// let data = users.inner_join(posts)
418    ///     .select((name, title))
419    ///     .load(connection);
420    ///
421    /// let expected_data = vec![
422    ///     (String::from("Sean"), String::from("My first post")),
423    ///     (String::from("Sean"), String::from("About Rust")),
424    ///     (String::from("Tess"), String::from("My first post too")),
425    /// ];
426    /// assert_eq!(Ok(expected_data), data);
427    /// # }
428    /// ```
429    ///
430    /// ### With explicit `ON` clause
431    ///
432    /// ```rust
433    /// # include!("../doctest_setup.rs");
434    /// # use schema::{users, posts};
435    /// #
436    /// # /*
437    /// allow_tables_to_appear_in_same_query!(users, posts);
438    /// # */
439    ///
440    /// # fn main() {
441    /// #     use self::users::dsl::{users, name};
442    /// #     use self::posts::dsl::{posts, user_id, title};
443    /// #     let connection = &mut establish_connection();
444    /// diesel::insert_into(posts)
445    ///     .values(&vec![
446    ///         (user_id.eq(1), title.eq("Sean's post")),
447    ///         (user_id.eq(2), title.eq("Sean is a jerk")),
448    ///     ])
449    ///     .execute(connection)
450    ///     .unwrap();
451    ///
452    /// let data = users
453    ///     .inner_join(posts.on(title.like(name.concat("%"))))
454    ///     .select((name, title))
455    ///     .load(connection);
456    /// let expected_data = vec![
457    ///     (String::from("Sean"), String::from("Sean's post")),
458    ///     (String::from("Sean"), String::from("Sean is a jerk")),
459    /// ];
460    /// assert_eq!(Ok(expected_data), data);
461    /// # }
462    /// ```
463    ///
464    /// ### With explicit `ON` clause (struct)
465    ///
466    /// ```rust
467    /// # include!("../doctest_setup.rs");
468    /// # use schema::{users, posts};
469    /// #
470    /// # /*
471    /// allow_tables_to_appear_in_same_query!(users, posts);
472    /// # */
473    ///
474    /// # fn main() {
475    /// #     use self::users::dsl::{users, name};
476    /// #     use self::posts::dsl::{posts, user_id, title};
477    /// #     let connection = &mut establish_connection();
478    /// #[derive(Debug, PartialEq, Queryable)]
479    /// struct User {
480    ///     id: i32,
481    ///     name: String,
482    /// }
483    ///
484    /// #[derive(Debug, PartialEq, Queryable)]
485    /// struct Post {
486    ///     id: i32,
487    ///     user_id: i32,
488    ///     title: String,
489    /// }
490    ///
491    /// diesel::insert_into(posts)
492    ///     .values(&vec![
493    ///         (user_id.eq(1), title.eq("Sean's post")),
494    ///         (user_id.eq(2), title.eq("Sean is a jerk")),
495    ///     ])
496    ///     .execute(connection)
497    ///     .unwrap();
498    ///
499    /// // By default, all columns from both tables are selected.
500    /// // If no explicit select clause is used this means that the
501    /// // result type of this query must contain all fields from the
502    /// // original schema in order.
503    /// let data = users
504    ///     .inner_join(posts.on(title.like(name.concat("%"))))
505    ///     .load::<(User, Post)>(connection); // type could be elided
506    /// let expected_data = vec![
507    ///     (
508    ///         User { id: 1, name: String::from("Sean") },
509    ///         Post { id: 4, user_id: 1, title: String::from("Sean's post") },
510    ///     ),
511    ///     (
512    ///         User { id: 1, name: String::from("Sean") },
513    ///         Post { id: 5, user_id: 2, title: String::from("Sean is a jerk") },
514    ///     ),
515    /// ];
516    /// assert_eq!(Ok(expected_data), data);
517    /// # }
518    /// ```
519    fn inner_join<Rhs>(self, rhs: Rhs) -> InnerJoin<Self, Rhs>
520    where
521        Self: JoinWithImplicitOnClause<Rhs, joins::Inner>,
522    {
523        self.join_with_implicit_on_clause(rhs, joins::Inner)
524    }
525
526    /// Join two tables using a SQL `LEFT OUTER JOIN`.
527    ///
528    /// Behaves similarly to [`inner_join`], but will produce a left join
529    /// instead. See [`inner_join`] for usage examples.
530    ///
531    /// [`inner_join`]: QueryDsl::inner_join()
532    ///
533    /// Columns in the right hand table will become `Nullable` which means
534    /// you must call `nullable()` on the corresponding fields in the select
535    /// clause:
536    ///
537    /// ### Selecting after a left join
538    ///
539    /// ```rust
540    /// # include!("../doctest_setup.rs");
541    /// # use schema::{users, posts};
542    /// #
543    /// # #[derive(Queryable, PartialEq, Eq, Debug)]
544    /// # struct User {
545    /// #     id: i32,
546    /// #     name: String,
547    /// # }
548    /// #
549    /// # impl User {
550    /// #     fn new(id: i32, name: &str) -> Self {
551    /// #         User {
552    /// #             id,
553    /// #             name: name.into(),
554    /// #         }
555    /// #     }
556    /// # }
557    /// #
558    /// # #[derive(Queryable, PartialEq, Eq, Debug)]
559    /// # struct Post {
560    /// #     id: i32,
561    /// #     user_id: i32,
562    /// #     title: String,
563    /// # }
564    /// #
565    /// # impl Post {
566    /// #     fn new(id: i32, user_id: i32, title: &str) -> Self {
567    /// #         Post {
568    /// #             id,
569    /// #             user_id,
570    /// #             title: title.into(),
571    /// #         }
572    /// #     }
573    /// # }
574    /// #
575    /// # fn main() {
576    /// #     run_test().unwrap();
577    /// # }
578    /// #
579    /// # fn run_test() -> QueryResult<()> {
580    /// #     let connection = &mut establish_connection();
581    /// #     diesel::sql_query("DELETE FROM posts").execute(connection)?;
582    /// #     diesel::insert_into(posts::table)
583    /// #         .values((posts::user_id.eq(1), posts::title.eq("Sean's Post")))
584    /// #         .execute(connection)?;
585    /// #     let post_id = posts::table.select(posts::id)
586    /// #         .first::<i32>(connection)?;
587    /// let join = users::table.left_join(posts::table);
588    ///
589    /// // Since `posts` is on the right side of a left join, `.nullable` is
590    /// // needed.
591    /// let names_and_titles = join.select((users::name, posts::title.nullable()))
592    ///     .load::<(String, Option<String>)>(connection)?;
593    /// let expected_data = vec![
594    ///     (String::from("Sean"), Some(String::from("Sean's Post"))),
595    ///     (String::from("Tess"), None),
596    /// ];
597    /// assert_eq!(expected_data, names_and_titles);
598    /// #     Ok(())
599    /// # }
600    /// ```
601    fn left_outer_join<Rhs>(self, rhs: Rhs) -> LeftJoin<Self, Rhs>
602    where
603        Self: JoinWithImplicitOnClause<Rhs, joins::LeftOuter>,
604    {
605        self.join_with_implicit_on_clause(rhs, joins::LeftOuter)
606    }
607
608    /// Alias for [`left_outer_join`].
609    ///
610    /// [`left_outer_join`]: QueryDsl::left_outer_join()
611    fn left_join<Rhs>(self, rhs: Rhs) -> LeftJoin<Self, Rhs>
612    where
613        Self: JoinWithImplicitOnClause<Rhs, joins::LeftOuter>,
614    {
615        self.left_outer_join(rhs)
616    }
617
618    /// Adds to the `WHERE` clause of a query.
619    ///
620    /// If there is already a `WHERE` clause, the result will be `old AND new`.
621    ///
622    /// Note that in order to use this method with columns from different tables, you need to call
623    ///  [`.inner_join`] or [`.left_join`] beforehand.
624    /// This is because you can only access columns from tables
625    /// that appear in your query before the call to [`.filter`].
626    ///
627    /// [`.inner_join`]: QueryDsl::inner_join()
628    /// [`.left_join`]: QueryDsl::left_join()
629    /// [`.filter`]: QueryDsl::filter()
630    ///
631    /// # Example:
632    ///
633    /// ```rust
634    /// # include!("../doctest_setup.rs");
635    /// #
636    /// # fn main() {
637    /// #     use schema::users::dsl::*;
638    /// #     let connection = &mut establish_connection();
639    /// let seans_id = users.filter(name.eq("Sean")).select(id)
640    ///     .first(connection);
641    /// assert_eq!(Ok(1), seans_id);
642    /// let tess_id = users.filter(name.eq("Tess")).select(id)
643    ///     .first(connection);
644    /// assert_eq!(Ok(2), tess_id);
645    /// # }
646    /// ```
647    #[doc(alias = "where")]
648    fn filter<Predicate>(self, predicate: Predicate) -> Filter<Self, Predicate>
649    where
650        Self: methods::FilterDsl<Predicate>,
651    {
652        methods::FilterDsl::filter(self, predicate)
653    }
654
655    /// Adds to the `WHERE` clause of a query using `OR`
656    ///
657    /// If there is already a `WHERE` clause, the result will be `(old OR new)`.
658    /// Calling `foo.filter(bar).or_filter(baz)`
659    /// is identical to `foo.filter(bar.or(baz))`.
660    /// However, the second form is much harder to do dynamically.
661    ///
662    /// # Example:
663    ///
664    /// ```rust
665    /// # include!("../doctest_setup.rs");
666    /// #
667    /// # fn main() {
668    /// #     run_test().unwrap();
669    /// # }
670    /// #
671    /// # fn run_test() -> QueryResult<()> {
672    /// #     use schema::animals::dsl::*;
673    /// #     let connection = &mut establish_connection();
674    /// #     diesel::delete(animals).execute(connection)?;
675    /// diesel::insert_into(animals)
676    ///     .values(&vec![
677    ///         (species.eq("cat"), legs.eq(4), name.eq("Sinatra")),
678    ///         (species.eq("dog"), legs.eq(3), name.eq("Fido")),
679    ///         (species.eq("spider"), legs.eq(8), name.eq("Charlotte")),
680    ///     ])
681    ///     .execute(connection)?;
682    ///
683    /// let good_animals = animals
684    ///     .filter(name.eq("Fido"))
685    ///     .or_filter(legs.eq(4))
686    ///     .select(name)
687    ///     .get_results::<Option<String>>(connection)?;
688    /// let expected = vec![
689    ///     Some(String::from("Sinatra")),
690    ///     Some(String::from("Fido")),
691    /// ];
692    /// assert_eq!(expected, good_animals);
693    /// #     Ok(())
694    /// # }
695    /// ```
696    #[doc(alias = "where")]
697    fn or_filter<Predicate>(self, predicate: Predicate) -> OrFilter<Self, Predicate>
698    where
699        Self: methods::OrFilterDsl<Predicate>,
700    {
701        methods::OrFilterDsl::or_filter(self, predicate)
702    }
703
704    /// Attempts to find a single record from the given table by primary key.
705    ///
706    /// # Example
707    ///
708    /// ```rust
709    /// # include!("../doctest_setup.rs");
710    /// #
711    /// # fn main() {
712    /// #     use schema::users::dsl::*;
713    /// #     use diesel::result::Error::NotFound;
714    /// #     let connection = &mut establish_connection();
715    /// let sean = (1, "Sean".to_string());
716    /// let tess = (2, "Tess".to_string());
717    /// assert_eq!(Ok(sean), users.find(1).first(connection));
718    /// assert_eq!(Ok(tess), users.find(2).first(connection));
719    /// assert_eq!(Err::<(i32, String), _>(NotFound), users.find(3).first(connection));
720    /// # }
721    /// ```
722    fn find<PK>(self, id: PK) -> Find<Self, PK>
723    where
724        Self: methods::FindDsl<PK>,
725    {
726        methods::FindDsl::find(self, id)
727    }
728
729    /// Sets the order clause of a query.
730    ///
731    /// If there was already an order clause, it will be overridden. See
732    /// also:
733    /// [`.desc()`](crate::expression_methods::ExpressionMethods::desc())
734    /// and
735    /// [`.asc()`](crate::expression_methods::ExpressionMethods::asc())
736    ///
737    /// Ordering by multiple columns can be achieved by passing a tuple of those
738    /// columns.
739    /// To construct an order clause of an unknown number of columns,
740    /// see [`QueryDsl::then_order_by`](QueryDsl::then_order_by())
741    ///
742    /// # Examples
743    ///
744    /// ```rust
745    /// # include!("../doctest_setup.rs");
746    /// #
747    /// # fn main() {
748    /// #     run_test();
749    /// # }
750    /// #
751    /// # fn run_test() -> QueryResult<()> {
752    /// #     use schema::users::dsl::*;
753    /// #     let connection = &mut establish_connection();
754    /// #     diesel::sql_query("DELETE FROM users").execute(connection)?;
755    /// diesel::insert_into(users)
756    ///     .values(&vec![
757    ///         name.eq("Saul"),
758    ///         name.eq("Steve"),
759    ///         name.eq("Stan"),
760    ///     ])
761    ///     .execute(connection)?;
762    ///
763    /// let ordered_names = users.select(name)
764    ///     .order(name.desc())
765    ///     .load::<String>(connection)?;
766    /// assert_eq!(vec!["Steve", "Stan", "Saul"], ordered_names);
767    ///
768    /// diesel::insert_into(users).values(name.eq("Stan")).execute(connection)?;
769    ///
770    /// let data = users.select((name, id))
771    ///     .order((name.asc(), id.desc()))
772    ///     .load(connection)?;
773    /// let expected_data = vec![
774    ///     (String::from("Saul"), 3),
775    ///     (String::from("Stan"), 6),
776    ///     (String::from("Stan"), 5),
777    ///     (String::from("Steve"), 4),
778    /// ];
779    /// assert_eq!(expected_data, data);
780    /// #    Ok(())
781    /// # }
782    /// ```
783    fn order<Expr>(self, expr: Expr) -> Order<Self, Expr>
784    where
785        Expr: Expression,
786        Self: methods::OrderDsl<Expr>,
787    {
788        methods::OrderDsl::order(self, expr)
789    }
790
791    /// Alias for `order`
792    fn order_by<Expr>(self, expr: Expr) -> OrderBy<Self, Expr>
793    where
794        Expr: Expression,
795        Self: methods::OrderDsl<Expr>,
796    {
797        QueryDsl::order(self, expr)
798    }
799
800    /// Appends to the `ORDER BY` clause of this SQL query.
801    ///
802    /// Unlike `.order`, this method will append rather than replace.
803    /// In other words,
804    /// `.order_by(foo).order_by(bar)` is equivalent to `.order_by(bar)`.
805    /// In contrast,
806    /// `.order_by(foo).then_order_by(bar)` is equivalent to `.order((foo, bar))`.
807    /// This method is only present on boxed queries.
808    ///
809    /// # Examples
810    ///
811    /// ```rust
812    /// # include!("../doctest_setup.rs");
813    /// #
814    /// # fn main() {
815    /// #     run_test();
816    /// # }
817    /// #
818    /// # fn run_test() -> QueryResult<()> {
819    /// #     use schema::users::dsl::*;
820    /// #     let connection = &mut establish_connection();
821    /// #     diesel::sql_query("DELETE FROM users").execute(connection)?;
822    /// diesel::insert_into(users)
823    ///     .values(&vec![
824    ///         name.eq("Saul"),
825    ///         name.eq("Steve"),
826    ///         name.eq("Stan"),
827    ///         name.eq("Stan"),
828    ///     ])
829    ///     .execute(connection)?;
830    ///
831    /// let data = users.select((name, id))
832    ///     .order_by(name.asc())
833    ///     .then_order_by(id.desc())
834    ///     .load(connection)?;
835    /// let expected_data = vec![
836    ///     (String::from("Saul"), 3),
837    ///     (String::from("Stan"), 6),
838    ///     (String::from("Stan"), 5),
839    ///     (String::from("Steve"), 4),
840    /// ];
841    /// assert_eq!(expected_data, data);
842    /// #    Ok(())
843    /// # }
844    /// ```
845    fn then_order_by<Order>(self, order: Order) -> ThenOrderBy<Self, Order>
846    where
847        Self: methods::ThenOrderDsl<Order>,
848    {
849        methods::ThenOrderDsl::then_order_by(self, order)
850    }
851
852    /// Sets the limit clause of the query.
853    ///
854    /// If there was already a limit clause, it will be overridden.
855    ///
856    /// # Example
857    ///
858    /// ```rust
859    /// # include!("../doctest_setup.rs");
860    /// # use schema::users;
861    /// #
862    /// # fn main() {
863    /// #     run_test().unwrap();
864    /// # }
865    /// #
866    /// # fn run_test() -> QueryResult<()> {
867    /// #     use self::users::dsl::*;
868    /// #     let connection = &mut establish_connection();
869    /// #     diesel::delete(users).execute(connection)?;
870    /// #     diesel::insert_into(users)
871    /// #        .values(&vec![
872    /// #            name.eq("Sean"),
873    /// #            name.eq("Bastien"),
874    /// #            name.eq("Pascal"),
875    /// #        ])
876    /// #        .execute(connection)?;
877    /// #
878    /// // Using a limit
879    /// let limited = users.select(name)
880    ///     .order(id)
881    ///     .limit(1)
882    ///     .load::<String>(connection)?;
883    ///
884    /// // Without a limit
885    /// let no_limit = users.select(name)
886    ///     .order(id)
887    ///     .load::<String>(connection)?;
888    ///
889    /// assert_eq!(vec!["Sean"], limited);
890    /// assert_eq!(vec!["Sean", "Bastien", "Pascal"], no_limit);
891    /// #    Ok(())
892    /// # }
893    /// ```
894    fn limit(self, limit: i64) -> Limit<Self>
895    where
896        Self: methods::LimitDsl,
897    {
898        methods::LimitDsl::limit(self, limit)
899    }
900
901    /// Sets the offset clause of the query.
902    ///
903    /// If there was already a offset clause, it will be overridden.
904    ///
905    /// # Example
906    ///
907    /// ```rust
908    /// # include!("../doctest_setup.rs");
909    /// # use schema::users;
910    /// #
911    /// # fn main() {
912    /// #     run_test().unwrap();
913    /// # }
914    /// #
915    /// # fn run_test() -> QueryResult<()> {
916    /// #     use self::users::dsl::*;
917    /// #     let connection = &mut establish_connection();
918    /// #     diesel::delete(users).execute(connection)?;
919    /// #     diesel::insert_into(users)
920    /// #        .values(&vec![
921    /// #            name.eq("Sean"),
922    /// #            name.eq("Bastien"),
923    /// #            name.eq("Pascal"),
924    /// #        ])
925    /// #        .execute(connection)?;
926    /// #
927    /// // Using an offset
928    /// let offset = users.select(name)
929    ///     .order(id)
930    ///     .limit(2)
931    ///     .offset(1)
932    ///     .load::<String>(connection)?;
933    ///
934    /// // No Offset
935    /// let no_offset = users.select(name)
936    ///     .order(id)
937    ///     .limit(2)
938    ///     .load::<String>(connection)?;
939    ///
940    /// assert_eq!(vec!["Bastien", "Pascal"], offset);
941    /// assert_eq!(vec!["Sean", "Bastien"], no_offset);
942    /// #     Ok(())
943    /// # }
944    /// ```
945    fn offset(self, offset: i64) -> Offset<Self>
946    where
947        Self: methods::OffsetDsl,
948    {
949        methods::OffsetDsl::offset(self, offset)
950    }
951
952    /// Sets the `group by` clause of a query.
953    ///
954    /// **Note:** Queries having a `group by` clause require a custom select clause.
955    /// Use [`QueryDsl::select()`] to specify one.
956    ///
957    /// If there was already a group by clause, it will be overridden.
958    /// Grouping by multiple columns can be achieved by passing a tuple of those
959    /// columns.
960    ///
961    /// Diesel follows postgresql's group by semantic, this means any column
962    /// appearing in a group by clause is considered to be aggregated. If a
963    /// primary key is part of the group by clause every column from the
964    /// corresponding table is considered to be aggregated. Select clauses
965    /// cannot mix aggregated and non aggregated expressions.
966    ///
967    /// For group by clauses containing columns from more than one table it
968    /// is required to call [`allow_columns_to_appear_in_same_group_by_clause!`]
969    ///
970    /// [`allow_columns_to_appear_in_same_group_by_clause!`]: crate::allow_columns_to_appear_in_same_group_by_clause!
971    ///
972    /// # Examples
973    /// ```rust
974    /// # include!("../doctest_setup.rs");
975    /// # fn main() {
976    /// #     run_test();
977    /// # }
978    /// #
979    /// # fn run_test() -> QueryResult<()> {
980    /// #     use crate::schema::{users, posts};
981    /// #     use diesel::dsl::count;
982    /// #     let connection = &mut establish_connection();
983    /// let data = users::table.inner_join(posts::table)
984    ///     .group_by(users::id)
985    ///     .select((users::name, count(posts::id)))
986    /// #   .order_by(users::id.asc())
987    ///     .load::<(String, i64)>(connection)?;
988    ///
989    /// assert_eq!(vec![(String::from("Sean"), 2), (String::from("Tess"), 1)], data);
990    /// # Ok(())
991    /// # }
992    /// ```
993    fn group_by<GB>(self, group_by: GB) -> GroupBy<Self, GB>
994    where
995        GB: Expression,
996        Self: methods::GroupByDsl<GB>,
997    {
998        methods::GroupByDsl::group_by(self, group_by)
999    }
1000
1001    /// Adds to the `HAVING` clause of a query.
1002    ///
1003    /// # Examples
1004    /// ```rust
1005    /// # include!("../doctest_setup.rs");
1006    /// # fn main() {
1007    /// #     run_test();
1008    /// # }
1009    /// #
1010    /// # fn run_test() -> QueryResult<()> {
1011    /// #     use crate::schema::{users, posts};
1012    /// #     use diesel::dsl::count;
1013    /// #     let connection = &mut establish_connection();
1014    /// let data = users::table.inner_join(posts::table)
1015    ///     .group_by(users::id)
1016    ///     .having(count(posts::id).gt(1))
1017    ///     .select((users::name, count(posts::id)))
1018    ///     .load::<(String, i64)>(connection)?;
1019    ///
1020    /// assert_eq!(vec![(String::from("Sean"), 2)], data);
1021    /// # Ok(())
1022    /// # }
1023    /// ```
1024    fn having<Predicate>(self, predicate: Predicate) -> Having<Self, Predicate>
1025    where
1026        Self: methods::HavingDsl<Predicate>,
1027    {
1028        methods::HavingDsl::having(self, predicate)
1029    }
1030
1031    /// Adds `FOR UPDATE` to the end of the select statement.
1032    ///
1033    /// This method is only available for MySQL and PostgreSQL. SQLite does not
1034    /// provide any form of row locking.
1035    ///
1036    /// Additionally, `.for_update` cannot be used on queries with a distinct
1037    /// clause, group by clause, having clause, or any unions. Queries with
1038    /// a `FOR UPDATE` clause cannot be boxed.
1039    ///
1040    /// # Example
1041    ///
1042    /// ```
1043    /// # include!("../doctest_setup.rs");
1044    /// # fn main() {
1045    /// #     run_test();
1046    /// # }
1047    /// #
1048    /// # #[cfg(any(feature = "mysql", feature = "postgres"))]
1049    /// # fn run_test() -> QueryResult<()> {
1050    /// #     use crate::schema::users;
1051    /// #     let connection = &mut establish_connection();
1052    /// // Executes `SELECT * FROM users FOR UPDATE`
1053    /// let users_for_update = users::table.for_update().load(connection)?;
1054    /// # let u: Vec<(i32, String)> = users_for_update;
1055    /// # Ok(())
1056    /// # }
1057    /// # #[cfg(feature = "sqlite")]
1058    /// # fn run_test() -> QueryResult<()> { Ok(()) }
1059    /// ```
1060    fn for_update(self) -> ForUpdate<Self>
1061    where
1062        Self: methods::LockingDsl<lock::ForUpdate>,
1063    {
1064        methods::LockingDsl::with_lock(self, lock::ForUpdate)
1065    }
1066
1067    /// Adds `FOR NO KEY UPDATE` to the end of the select statement.
1068    ///
1069    /// This method is only available for PostgreSQL. SQLite does not
1070    /// provide any form of row locking, and MySQL does not support anything
1071    /// finer than row-level locking.
1072    ///
1073    /// Additionally, `.for_no_key_update` cannot be used on queries with a distinct
1074    /// clause, group by clause, having clause, or any unions. Queries with
1075    /// a `FOR NO KEY UPDATE` clause cannot be boxed.
1076    ///
1077    /// # Example
1078    ///
1079    /// ```
1080    /// # include!("../doctest_setup.rs");
1081    /// # fn main() {
1082    /// #     run_test();
1083    /// # }
1084    /// #
1085    /// # #[cfg(feature = "postgres")]
1086    /// # fn run_test() -> QueryResult<()> {
1087    /// #     use crate::schema::users;
1088    /// #     let connection = &mut establish_connection();
1089    /// // Executes `SELECT * FROM users FOR NO KEY UPDATE`
1090    /// let users_for_no_key_update = users::table.for_no_key_update().load(connection)?;
1091    /// # let u: Vec<(i32, String)> = users_for_no_key_update;
1092    /// # Ok(())
1093    /// # }
1094    /// # #[cfg(not(feature = "postgres"))]
1095    /// # fn run_test() -> QueryResult<()> { Ok(()) }
1096    /// ```
1097    fn for_no_key_update(self) -> ForNoKeyUpdate<Self>
1098    where
1099        Self: methods::LockingDsl<lock::ForNoKeyUpdate>,
1100    {
1101        methods::LockingDsl::with_lock(self, lock::ForNoKeyUpdate)
1102    }
1103
1104    /// Adds `FOR SHARE` to the end of the select statement.
1105    ///
1106    /// This method is only available for MySQL and PostgreSQL. SQLite does not
1107    /// provide any form of row locking.
1108    ///
1109    /// Additionally, `.for_share` cannot be used on queries with a distinct
1110    /// clause, group by clause, having clause, or any unions. Queries with
1111    /// a `FOR SHARE` clause cannot be boxed.
1112    ///
1113    /// # Example
1114    ///
1115    /// ```
1116    /// # include!("../doctest_setup.rs");
1117    /// # fn main() {
1118    /// #     run_test();
1119    /// # }
1120    /// #
1121    /// # #[cfg(any(feature = "mysql", feature = "postgres"))]
1122    /// # fn run_test() -> QueryResult<()> {
1123    /// #     use crate::schema::users;
1124    /// #     let connection = &mut establish_connection();
1125    /// // Executes `SELECT * FROM users FOR SHARE`
1126    /// let users_for_share = users::table.for_share().load(connection)?;
1127    /// # let u: Vec<(i32, String)> = users_for_share;
1128    /// # Ok(())
1129    /// # }
1130    /// # #[cfg(feature = "sqlite")]
1131    /// # fn run_test() -> QueryResult<()> { Ok(()) }
1132    /// ```
1133    fn for_share(self) -> ForShare<Self>
1134    where
1135        Self: methods::LockingDsl<lock::ForShare>,
1136    {
1137        methods::LockingDsl::with_lock(self, lock::ForShare)
1138    }
1139
1140    /// Adds `FOR KEY SHARE` to the end of the select statement.
1141    ///
1142    /// This method is only available for PostgreSQL. SQLite does not
1143    /// provide any form of row locking, and MySQL does not support anything
1144    /// finer than row-level locking.
1145    ///
1146    /// Additionally, `.for_key_share` cannot be used on queries with a distinct
1147    /// clause, group by clause, having clause, or any unions. Queries with
1148    /// a `FOR KEY SHARE` clause cannot be boxed.
1149    ///
1150    /// # Example
1151    ///
1152    /// ```
1153    /// # include!("../doctest_setup.rs");
1154    /// # fn main() {
1155    /// #     run_test();
1156    /// # }
1157    ///
1158    /// # #[cfg(feature = "postgres")]
1159    /// # fn run_test() -> QueryResult<()> {
1160    /// #     use crate::schema::users;
1161    /// #     let connection = &mut establish_connection();
1162    /// // Executes `SELECT * FROM users FOR KEY SHARE`
1163    /// let users_for_key_share = users::table.for_key_share().load(connection)?;
1164    /// # let u: Vec<(i32, String)> = users_for_key_share;
1165    /// # Ok(())
1166    /// # }
1167    /// # #[cfg(not(feature = "postgres"))]
1168    /// # fn run_test() -> QueryResult<()> { Ok(()) }
1169    /// ```
1170    fn for_key_share(self) -> ForKeyShare<Self>
1171    where
1172        Self: methods::LockingDsl<lock::ForKeyShare>,
1173    {
1174        methods::LockingDsl::with_lock(self, lock::ForKeyShare)
1175    }
1176
1177    /// Adds `SKIP LOCKED` to the end of a `FOR UPDATE` clause.
1178    ///
1179    /// This modifier is only supported in PostgreSQL 9.5+ and MySQL 8+.
1180    ///
1181    /// # Example
1182    ///
1183    /// ```
1184    /// # include!("../doctest_setup.rs");
1185    /// # fn main() {
1186    /// #     run_test();
1187    /// # }
1188    /// #
1189    /// # #[cfg(any(feature = "postgres", feature = "mysql"))]
1190    /// # fn run_test() -> QueryResult<()> {
1191    /// #     use crate::schema::users;
1192    /// #     let connection = &mut establish_connection();
1193    /// // Executes `SELECT * FROM users FOR UPDATE SKIP LOCKED`
1194    /// let user_skipped_locked = users::table.for_update().skip_locked().load(connection)?;
1195    /// # let u: Vec<(i32, String)> = user_skipped_locked;
1196    /// # Ok(())
1197    /// # }
1198    /// # #[cfg(feature = "sqlite")]
1199    /// # fn run_test() -> QueryResult<()> { Ok(()) }
1200    /// ```
1201    fn skip_locked(self) -> SkipLocked<Self>
1202    where
1203        Self: methods::ModifyLockDsl<lock::SkipLocked>,
1204    {
1205        methods::ModifyLockDsl::modify_lock(self, lock::SkipLocked)
1206    }
1207
1208    /// Adds `NOWAIT` to the end of a `FOR UPDATE` clause.
1209    ///
1210    /// This modifier is only supported in PostgreSQL 9.5+ and MySQL 8+.
1211    ///
1212    /// # Example
1213    ///
1214    /// ```
1215    /// # include!("../doctest_setup.rs");
1216    /// # fn main() {
1217    /// #     run_test();
1218    /// # }
1219    /// #
1220    /// # #[cfg(any(feature = "mysql", feature = "postgres"))]
1221    /// # fn run_test() -> QueryResult<()> {
1222    /// #     use crate::schema::users;
1223    /// #     let connection = &mut establish_connection();
1224    /// // Executes `SELECT * FROM users FOR UPDATE NOWAIT`
1225    /// let users_no_wait = users::table.for_update().no_wait().load(connection)?;
1226    /// # let u: Vec<(i32, String)> = users_no_wait;
1227    /// # Ok(())
1228    /// # }
1229    /// # #[cfg(feature = "sqlite")]
1230    /// # fn run_test() -> QueryResult<()> { Ok(()) }
1231    /// ```
1232    fn no_wait(self) -> NoWait<Self>
1233    where
1234        Self: methods::ModifyLockDsl<lock::NoWait>,
1235    {
1236        methods::ModifyLockDsl::modify_lock(self, lock::NoWait)
1237    }
1238
1239    /// Boxes the pieces of a query into a single type.
1240    ///
1241    /// This is useful for cases where you want to conditionally modify a query,
1242    /// but need the type to remain the same. The backend must be specified as
1243    /// part of this. It is not possible to box a query and have it be useable
1244    /// on multiple backends.
1245    ///
1246    /// A boxed query will incur a minor performance penalty, as the query builder
1247    /// can no longer be inlined by the compiler. For most applications this cost
1248    /// will be minimal.
1249    ///
1250    /// ### Example
1251    ///
1252    /// ```rust
1253    /// # include!("../doctest_setup.rs");
1254    /// # use schema::users;
1255    /// #
1256    /// # fn main() {
1257    /// #     use std::collections::HashMap;
1258    /// #     let connection = &mut establish_connection();
1259    /// #     let mut params = HashMap::new();
1260    /// #     params.insert("name", "Sean");
1261    /// let mut query = users::table.into_boxed();
1262    /// if let Some(name) = params.get("name") {
1263    ///     query = query.filter(users::name.eq(name));
1264    /// }
1265    /// let users = query.load(connection);
1266    /// #     let expected = vec![(1, String::from("Sean"))];
1267    /// #     assert_eq!(Ok(expected), users);
1268    /// # }
1269    /// ```
1270    ///
1271    /// Diesel queries also have a similar problem to [`Iterator`], where
1272    /// returning them from a function requires exposing the implementation of that
1273    /// function. The [`helper_types`][helper_types] module exists to help with this,
1274    /// but you might want to hide the return type or have it conditionally change.
1275    /// Boxing can achieve both.
1276    ///
1277    /// [helper_types]: crate::helper_types
1278    ///
1279    /// ### Example
1280    ///
1281    /// ```rust
1282    /// # include!("../doctest_setup.rs");
1283    /// # use schema::users;
1284    /// #
1285    /// # fn main() {
1286    /// #     let connection = &mut establish_connection();
1287    /// fn users_by_name(name: &str) -> users::BoxedQuery<DB> {
1288    ///     users::table.filter(users::name.eq(name)).into_boxed()
1289    /// }
1290    ///
1291    /// assert_eq!(Ok(1), users_by_name("Sean").select(users::id).first(connection));
1292    /// assert_eq!(Ok(2), users_by_name("Tess").select(users::id).first(connection));
1293    /// # }
1294    /// ```
1295    fn into_boxed<'a, DB>(self) -> IntoBoxed<'a, Self, DB>
1296    where
1297        DB: Backend,
1298        Self: methods::BoxedDsl<'a, DB>,
1299    {
1300        methods::BoxedDsl::internal_into_boxed(self)
1301    }
1302
1303    /// Wraps this select statement in parenthesis, allowing it to be used
1304    /// as an expression.
1305    ///
1306    /// SQL allows queries such as `foo = (SELECT ...)`, as long as the
1307    /// subselect returns only a single column, and 0 or 1 rows. This method
1308    /// indicates that you expect the query to only return a single value (this
1309    /// will be enforced by adding `LIMIT 1`).
1310    ///
1311    /// The SQL type of this will always be `Nullable`, as the query returns
1312    /// `NULL` if the table is empty or it otherwise returns 0 rows.
1313    ///
1314    /// # Example
1315    ///
1316    /// ```rust
1317    /// # include!("../doctest_setup.rs");
1318    /// #
1319    /// # fn main() {
1320    /// #     run_test();
1321    /// # }
1322    /// #
1323    /// # fn run_test() -> QueryResult<()> {
1324    /// #     use diesel::insert_into;
1325    /// #     use schema::users::dsl::*;
1326    /// #     use schema::posts;
1327    /// #     let connection = &mut establish_connection();
1328    /// insert_into(posts::table)
1329    ///     .values(posts::user_id.eq(1))
1330    ///     .execute(connection)?;
1331    /// let last_post = posts::table
1332    ///     .order(posts::id.desc());
1333    /// let most_recently_active_user = users.select(name)
1334    ///     .filter(id.nullable().eq(last_post.select(posts::user_id).single_value()))
1335    ///     .first::<String>(connection)?;
1336    /// assert_eq!("Sean", most_recently_active_user);
1337    /// #     Ok(())
1338    /// # }
1339    /// ```
1340    fn single_value(self) -> SingleValue<Self>
1341    where
1342        Self: methods::SingleValueDsl,
1343    {
1344        methods::SingleValueDsl::single_value(self)
1345    }
1346
1347    /// Coerce the SQL type of the select clause to it's nullable equivalent.
1348    ///
1349    /// This is useful for writing queries that contain subselects on non null
1350    /// fields comparing them to nullable fields.
1351    /// ```rust
1352    /// # include!("../doctest_setup.rs");
1353    /// #
1354    /// # fn main() {
1355    /// #    run_test();
1356    /// # }
1357    /// #
1358    /// # fn run_test() -> QueryResult<()> {
1359    /// #     let connection = &mut establish_connection();
1360    /// table! {
1361    ///     users {
1362    ///         id -> Integer,
1363    ///         name -> Text,
1364    ///     }
1365    /// }
1366    ///
1367    /// table! {
1368    ///     posts {
1369    ///         id -> Integer,
1370    ///         by_user -> Nullable<Text>,
1371    ///     }
1372    /// }
1373    ///
1374    /// allow_tables_to_appear_in_same_query!(users, posts);
1375    ///
1376    /// # let _: Vec<(i32, Option<String>)> =
1377    /// posts::table.filter(
1378    ///    posts::by_user.eq_any(users::table.select(users::name).nullable())
1379    /// ).load(connection)?;
1380    /// #     Ok(())
1381    /// # }
1382    fn nullable(self) -> NullableSelect<Self>
1383    where
1384        Self: methods::SelectNullableDsl,
1385    {
1386        methods::SelectNullableDsl::nullable(self)
1387    }
1388}
1389
1390impl<T: Table> QueryDsl for T {}
1391
1392/// Methods used to execute queries.
1393pub trait RunQueryDsl<Conn>: Sized {
1394    /// Executes the given command, returning the number of rows affected.
1395    ///
1396    /// `execute` is usually used in conjunction with [`insert_into`](crate::insert_into()),
1397    /// [`update`](crate::update()) and [`delete`](crate::delete()) where the number of
1398    /// affected rows is often enough information.
1399    ///
1400    /// When asking the database to return data from a query, [`load`](crate::query_dsl::RunQueryDsl::load()) should
1401    /// probably be used instead.
1402    ///
1403    /// # Example
1404    ///
1405    /// ```rust
1406    /// # include!("../doctest_setup.rs");
1407    /// #
1408    /// # fn main() {
1409    /// #     run_test();
1410    /// # }
1411    /// #
1412    /// # fn run_test() -> QueryResult<()> {
1413    /// #     use diesel::insert_into;
1414    /// #     use schema::users::dsl::*;
1415    /// #     let connection = &mut establish_connection();
1416    /// let inserted_rows = insert_into(users)
1417    ///     .values(name.eq("Ruby"))
1418    ///     .execute(connection)?;
1419    /// assert_eq!(1, inserted_rows);
1420    ///
1421    /// let inserted_rows = insert_into(users)
1422    ///     .values(&vec![name.eq("Jim"), name.eq("James")])
1423    ///     .execute(connection)?;
1424    /// assert_eq!(2, inserted_rows);
1425    /// #     Ok(())
1426    /// # }
1427    /// ```
1428    fn execute(self, conn: &mut Conn) -> QueryResult<usize>
1429    where
1430        Conn: Connection,
1431        Self: methods::ExecuteDsl<Conn>,
1432    {
1433        methods::ExecuteDsl::execute(self, conn)
1434    }
1435
1436    /// Executes the given query, returning a [`Vec`] with the returned rows.
1437    ///
1438    /// When using the query builder, the return type can be
1439    /// a tuple of the values, or a struct which implements [`Queryable`].
1440    ///
1441    /// When this method is called on [`sql_query`],
1442    /// the return type can only be a struct which implements [`QueryableByName`]
1443    ///
1444    /// For insert, update, and delete operations where only a count of affected is needed,
1445    /// [`execute`] should be used instead.
1446    ///
1447    /// [`Queryable`]: crate::deserialize::Queryable
1448    /// [`QueryableByName`]: crate::deserialize::QueryableByName
1449    /// [`execute`]: crate::query_dsl::RunQueryDsl::execute()
1450    /// [`sql_query`]: crate::sql_query()
1451    ///
1452    /// ## How to resolve compiler errors while loading data from the database
1453    ///
1454    /// In case you getting uncomprehensable compiler errors while loading data
1455    /// from the database into a type using [`#[derive(Queryable)]`](derive@crate::prelude::Queryable)
1456    /// you might want to consider
1457    /// using  [`#[derive(Selectable)]`](derive@crate::prelude::Selectable) +
1458    /// `#[diesel(check_for_backend(YourBackendType))]`
1459    /// to check for mismatching fields at compile time. This drastically improves
1460    /// the quality of the generated error messages by pointing to concrete type mismatches at
1461    /// field level.You need to specify the concrete database backend
1462    /// this specific struct is indented to be used with, as otherwise rustc cannot correctly
1463    /// identify the required deserialization implementation.
1464    ///
1465    /// # Examples
1466    ///
1467    /// ## Returning a single field
1468    ///
1469    /// ```rust
1470    /// # include!("../doctest_setup.rs");
1471    /// #
1472    /// # fn main() {
1473    /// #     run_test();
1474    /// # }
1475    /// #
1476    /// # fn run_test() -> QueryResult<()> {
1477    /// #     use diesel::insert_into;
1478    /// #     use schema::users::dsl::*;
1479    /// #     let connection = &mut establish_connection();
1480    /// let data = users.select(name)
1481    ///     .load::<String>(connection)?;
1482    /// assert_eq!(vec!["Sean", "Tess"], data);
1483    /// #     Ok(())
1484    /// # }
1485    /// ```
1486    ///
1487    /// ## Returning a tuple
1488    ///
1489    /// ```rust
1490    /// # include!("../doctest_setup.rs");
1491    /// #
1492    /// # fn main() {
1493    /// #     run_test();
1494    /// # }
1495    /// #
1496    /// # fn run_test() -> QueryResult<()> {
1497    /// #     use diesel::insert_into;
1498    /// #     use schema::users::dsl::*;
1499    /// #     let connection = &mut establish_connection();
1500    /// let data = users
1501    ///     .load::<(i32, String)>(connection)?;
1502    /// let expected_data = vec![
1503    ///     (1, String::from("Sean")),
1504    ///     (2, String::from("Tess")),
1505    /// ];
1506    /// assert_eq!(expected_data, data);
1507    /// #     Ok(())
1508    /// # }
1509    /// ```
1510    ///
1511    /// ## Returning a struct
1512    ///
1513    /// ```rust
1514    /// # include!("../doctest_setup.rs");
1515    /// #
1516    /// #[derive(Queryable, PartialEq, Debug)]
1517    /// struct User {
1518    ///     id: i32,
1519    ///     name: String,
1520    /// }
1521    ///
1522    /// # fn main() {
1523    /// #     run_test();
1524    /// # }
1525    /// #
1526    /// # fn run_test() -> QueryResult<()> {
1527    /// #     use diesel::insert_into;
1528    /// #     use schema::users::dsl::*;
1529    /// #     let connection = &mut establish_connection();
1530    /// let data = users
1531    ///     .load::<User>(connection)?;
1532    /// let expected_data = vec![
1533    ///     User { id: 1, name: String::from("Sean") },
1534    ///     User { id: 2, name: String::from("Tess") },
1535    /// ];
1536    /// assert_eq!(expected_data, data);
1537    /// #     Ok(())
1538    /// # }
1539    /// ```
1540    fn load<'query, U>(self, conn: &mut Conn) -> QueryResult<Vec<U>>
1541    where
1542        Self: LoadQuery<'query, Conn, U>,
1543    {
1544        self.internal_load(conn)?.collect()
1545    }
1546
1547    /// Executes the given query, returning an [`Iterator`] with the returned rows.
1548    ///
1549    /// The iterator's item is [`QueryResult<U>`](crate::result::QueryResult).
1550    ///
1551    /// You should normally prefer to use [`RunQueryDsl::load`] instead. This method
1552    /// is provided for situations where the result needs to be collected into a different
1553    /// container than a [`Vec`]
1554    ///
1555    /// When using the query builder, the return type can be
1556    /// a tuple of the values, or a struct which implements [`Queryable`].
1557    /// This type is specified by the first generic type of this function.
1558    ///
1559    /// The second generic type parameter specifies the so called loading mode,
1560    /// which describes how the connection implementation loads data from the database.
1561    /// All connections should provide a implementation for
1562    /// [`DefaultLoadingMode`](crate::connection::DefaultLoadingMode).
1563    ///
1564    /// They may provide additional modes. Checkout the documentation of the concrete
1565    /// connection types for details. For connection implementations that provide
1566    /// more than one loading mode it is **required** to specify this generic parameter.
1567    /// This is currently true for `PgConnection`.
1568    ///
1569    /// When this method is called on [`sql_query`],
1570    /// the return type can only be a struct which implements [`QueryableByName`]
1571    ///
1572    /// For insert, update, and delete operations where only a count of affected is needed,
1573    /// [`execute`] should be used instead.
1574    ///
1575    /// [`Queryable`]: crate::deserialize::Queryable
1576    /// [`QueryableByName`]: crate::deserialize::QueryableByName
1577    /// [`execute`]: crate::query_dsl::RunQueryDsl::execute()
1578    /// [`sql_query`]: crate::sql_query()
1579    ///
1580    /// # Examples
1581    ///
1582    /// ## Returning a single field
1583    ///
1584    /// ```rust
1585    /// # include!("../doctest_setup.rs");
1586    /// #
1587    /// # fn main() {
1588    /// #     run_test();
1589    /// # }
1590    /// #
1591    /// # fn run_test() -> QueryResult<()> {
1592    /// #     use diesel::insert_into;
1593    /// #     use schema::users::dsl::*;
1594    /// #     let connection = &mut establish_connection();
1595    /// use diesel::connection::DefaultLoadingMode;
1596    ///
1597    /// let data = users.select(name)
1598    ///     .load_iter::<String, DefaultLoadingMode>(connection)?
1599    ///     .collect::<QueryResult<Vec<_>>>()?;
1600    /// assert_eq!(vec!["Sean", "Tess"], data);
1601    /// #     Ok(())
1602    /// # }
1603    /// ```
1604    ///
1605    /// ## Returning a tuple
1606    ///
1607    /// ```rust
1608    /// # include!("../doctest_setup.rs");
1609    /// #
1610    /// # fn main() {
1611    /// #     run_test();
1612    /// # }
1613    /// #
1614    /// # fn run_test() -> QueryResult<()> {
1615    /// #     use diesel::insert_into;
1616    /// #     use schema::users::dsl::*;
1617    /// #     let connection = &mut establish_connection();
1618    /// use diesel::connection::DefaultLoadingMode;
1619    ///
1620    /// let data = users
1621    ///     .load_iter::<(i32, String), DefaultLoadingMode>(connection)?
1622    ///     .collect::<QueryResult<Vec<_>>>()?;
1623    /// let expected_data = vec![
1624    ///     (1, String::from("Sean")),
1625    ///     (2, String::from("Tess")),
1626    /// ];
1627    /// assert_eq!(expected_data, data);
1628    /// #     Ok(())
1629    /// # }
1630    /// ```
1631    ///
1632    /// ## Returning a struct
1633    ///
1634    /// ```rust
1635    /// # include!("../doctest_setup.rs");
1636    /// #
1637    /// #[derive(Queryable, PartialEq, Debug)]
1638    /// struct User {
1639    ///     id: i32,
1640    ///     name: String,
1641    /// }
1642    ///
1643    /// # fn main() {
1644    /// #     run_test();
1645    /// # }
1646    /// #
1647    /// # fn run_test() -> QueryResult<()> {
1648    /// #     use diesel::insert_into;
1649    /// #     use schema::users::dsl::*;
1650    /// #     let connection = &mut establish_connection();
1651    /// use diesel::connection::DefaultLoadingMode;
1652    ///
1653    /// let data = users
1654    ///     .load_iter::<User, DefaultLoadingMode>(connection)?
1655    ///     .collect::<QueryResult<Vec<_>>>()?;
1656    /// let expected_data = vec![
1657    ///     User { id: 1, name: String::from("Sean") },
1658    ///     User { id: 2, name: String::from("Tess") },
1659    /// ];
1660    /// assert_eq!(expected_data, data);
1661    /// #     Ok(())
1662    /// # }
1663    /// ```
1664    fn load_iter<'conn, 'query: 'conn, U, B>(
1665        self,
1666        conn: &'conn mut Conn,
1667    ) -> QueryResult<Self::RowIter<'conn>>
1668    where
1669        U: 'conn,
1670        Self: LoadQuery<'query, Conn, U, B> + 'conn,
1671    {
1672        self.internal_load(conn)
1673    }
1674
1675    /// Runs the command, and returns the affected row.
1676    ///
1677    /// `Err(NotFound)` will be returned if the query affected 0 rows. You can
1678    /// call `.optional()` on the result of this if the command was optional to
1679    /// get back a `Result<Option<U>>`
1680    ///
1681    /// When this method is called on an insert, update, or delete statement,
1682    /// it will implicitly add a `RETURNING *` to the query,
1683    /// unless a returning clause was already specified.
1684    ///
1685    /// This method only returns the first row that was affected, even if more
1686    /// rows are affected.
1687    ///
1688    /// # Example
1689    ///
1690    /// ```rust
1691    /// # include!("../doctest_setup.rs");
1692    /// #
1693    /// # fn main() {
1694    /// #     run_test();
1695    /// # }
1696    /// #
1697    /// # #[cfg(feature = "postgres")]
1698    /// # fn run_test() -> QueryResult<()> {
1699    /// #     use diesel::{insert_into, update};
1700    /// #     use schema::users::dsl::*;
1701    /// #     let connection = &mut establish_connection();
1702    /// let inserted_row = insert_into(users)
1703    ///     .values(name.eq("Ruby"))
1704    ///     .get_result(connection)?;
1705    /// assert_eq!((3, String::from("Ruby")), inserted_row);
1706    ///
1707    /// // This will return `NotFound`, as there is no user with ID 4
1708    /// let update_result = update(users.find(4))
1709    ///     .set(name.eq("Jim"))
1710    ///     .get_result::<(i32, String)>(connection);
1711    /// assert_eq!(Err(diesel::NotFound), update_result);
1712    /// #     Ok(())
1713    /// # }
1714    /// #
1715    /// # #[cfg(not(feature = "postgres"))]
1716    /// # fn run_test() -> QueryResult<()> {
1717    /// #     Ok(())
1718    /// # }
1719    /// ```
1720    fn get_result<'query, U>(self, conn: &mut Conn) -> QueryResult<U>
1721    where
1722        Self: LoadQuery<'query, Conn, U>,
1723    {
1724        match self.internal_load(conn)?.next() {
1725            Some(v) => v,
1726            None => Err(crate::result::Error::NotFound),
1727        }
1728    }
1729
1730    /// Runs the command, returning an `Vec` with the affected rows.
1731    ///
1732    /// This method is an alias for [`load`], but with a name that makes more
1733    /// sense for insert, update, and delete statements.
1734    ///
1735    /// [`load`]: crate::query_dsl::RunQueryDsl::load()
1736    fn get_results<'query, U>(self, conn: &mut Conn) -> QueryResult<Vec<U>>
1737    where
1738        Self: LoadQuery<'query, Conn, U>,
1739    {
1740        self.load(conn)
1741    }
1742
1743    /// Attempts to load a single record.
1744    ///
1745    /// This method is equivalent to `.limit(1).get_result()`
1746    ///
1747    /// Returns `Ok(record)` if found, and `Err(NotFound)` if no results are
1748    /// returned. If the query truly is optional, you can call `.optional()` on
1749    /// the result of this to get a `Result<Option<U>>`.
1750    ///
1751    /// # Example:
1752    ///
1753    /// ```rust
1754    /// # include!("../doctest_setup.rs");
1755    /// # fn main() {
1756    /// #     run_test();
1757    /// # }
1758    /// #
1759    /// # fn run_test() -> QueryResult<()> {
1760    /// #     use schema::users::dsl::*;
1761    /// #     let connection = &mut establish_connection();
1762    /// diesel::insert_into(users)
1763    ///     .values(&vec![name.eq("Sean"), name.eq("Pascal")])
1764    ///     .execute(connection)?;
1765    ///
1766    /// let first_name = users.order(id).select(name).first(connection);
1767    /// assert_eq!(Ok(String::from("Sean")), first_name);
1768    ///
1769    /// let not_found = users
1770    ///     .filter(name.eq("Foo"))
1771    ///     .first::<(i32, String)>(connection);
1772    /// assert_eq!(Err(diesel::NotFound), not_found);
1773    /// #     Ok(())
1774    /// # }
1775    /// ```
1776    fn first<'query, U>(self, conn: &mut Conn) -> QueryResult<U>
1777    where
1778        Self: methods::LimitDsl,
1779        Limit<Self>: LoadQuery<'query, Conn, U>,
1780    {
1781        methods::LimitDsl::limit(self, 1).get_result(conn)
1782    }
1783}
1784
1785// Note: We could have a blanket `AsQuery` impl here, which would apply to
1786// everything we want it to. However, when a query is invalid, we specifically
1787// want the error to happen on the where clause of the method instead of trait
1788// resolution. Otherwise our users will get an error saying `<3 page long type>:
1789// ExecuteDsl is not satisfied` instead of a specific error telling them what
1790// part of their query is wrong.
1791impl<T, Conn> RunQueryDsl<Conn> for T where T: Table {}