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