Skip to main content

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