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]: ../expression_methods/index.html
12//! [dsl]: ../dsl/index.html
13//! [`QueryDsl`]: trait.QueryDsl.html
14//! [`RunQueryDsl`]: trait.RunQueryDsl.html
15
16use backend::Backend;
17use connection::Connection;
18use expression::count::CountStar;
19use expression::Expression;
20use helper_types::*;
21use query_builder::locking_clause as lock;
22use query_source::{joins, Table};
23use result::{first_or_not_found, QueryResult};
24
25mod belonging_to_dsl;
26#[doc(hidden)]
27pub mod boxed_dsl;
28mod distinct_dsl;
29#[doc(hidden)]
30pub mod filter_dsl;
31mod group_by_dsl;
32mod join_dsl;
33#[doc(hidden)]
34pub mod limit_dsl;
35#[doc(hidden)]
36pub mod load_dsl;
37mod locking_dsl;
38mod nullable_select_dsl;
39mod offset_dsl;
40mod order_dsl;
41mod save_changes_dsl;
42#[doc(hidden)]
43pub mod select_dsl;
44mod single_value_dsl;
45
46pub use self::belonging_to_dsl::BelongingToDsl;
47#[doc(hidden)]
48pub use self::group_by_dsl::GroupByDsl;
49pub use self::join_dsl::{InternalJoinDsl, JoinOnDsl, JoinWithImplicitOnClause};
50#[doc(hidden)]
51pub use self::load_dsl::LoadQuery;
52pub use self::save_changes_dsl::{SaveChangesDsl, UpdateAndFetchResults};
53
54/// The traits used by `QueryDsl`.
55///
56/// Each trait in this module represents exactly one method from `QueryDsl`.
57/// Apps should general rely on `QueryDsl` directly, rather than these traits.
58/// However, generic code may need to include a where clause that references
59/// these traits.
60pub mod methods {
61    pub use super::boxed_dsl::BoxedDsl;
62    pub use super::distinct_dsl::*;
63    #[doc(inline)]
64    pub use super::filter_dsl::*;
65    pub use super::limit_dsl::LimitDsl;
66    pub use super::load_dsl::{ExecuteDsl, LoadQuery};
67    #[cfg(feature = "with-deprecated")]
68    #[allow(deprecated)]
69    pub use super::locking_dsl::ForUpdateDsl;
70    pub use super::locking_dsl::{LockingDsl, ModifyLockDsl};
71    pub use super::nullable_select_dsl::SelectNullableDsl;
72    pub use super::offset_dsl::OffsetDsl;
73    pub use super::order_dsl::{OrderDsl, ThenOrderDsl};
74    pub use super::select_dsl::SelectDsl;
75    pub use super::single_value_dsl::SingleValueDsl;
76}
77
78/// Methods used to construct select statements.
79pub trait QueryDsl: Sized {
80    /// Adds the `DISTINCT` keyword to a query.
81    ///
82    /// This method will override any previous distinct clause that was present.
83    /// For example, on PostgreSQL, `foo.distinct_on(bar).distinct()` will
84    /// create the same query as `foo.distinct()`.
85    ///
86    /// # Example
87    ///
88    /// ```rust
89    /// # #[macro_use] extern crate diesel;
90    /// # include!("../doctest_setup.rs");
91    /// #
92    /// # fn main() {
93    /// #     run_test().unwrap();
94    /// # }
95    /// #
96    /// # fn run_test() -> QueryResult<()> {
97    /// #     use schema::users::dsl::*;
98    /// #     let connection = establish_connection();
99    /// #     connection.execute("DELETE FROM users").unwrap();
100    /// diesel::insert_into(users)
101    ///     .values(&vec![name.eq("Sean"); 3])
102    ///     .execute(&connection)?;
103    /// let names = users.select(name).load::<String>(&connection)?;
104    /// let distinct_names = users.select(name).distinct().load::<String>(&connection)?;
105    ///
106    /// assert_eq!(vec!["Sean"; 3], names);
107    /// assert_eq!(vec!["Sean"; 1], distinct_names);
108    /// #     Ok(())
109    /// # }
110    /// ```
111    fn distinct(self) -> Distinct<Self>
112    where
113        Self: methods::DistinctDsl,
114    {
115        methods::DistinctDsl::distinct(self)
116    }
117
118    /// Adds the `DISTINCT ON` clause to a query.
119    ///
120    /// # Example
121    ///
122    /// ```rust
123    /// # #[macro_use] extern crate diesel;
124    /// # include!("../doctest_setup.rs");
125    /// # use schema::animals;
126    /// #
127    /// # #[derive(Queryable, Debug, PartialEq)]
128    /// # struct Animal {
129    /// #     species: String,
130    /// #     name: Option<String>,
131    /// #     legs: i32,
132    /// # }
133    /// #
134    /// # impl Animal {
135    /// #     fn new<S: Into<String>>(species: S, name: Option<&str>, legs: i32) -> Self {
136    /// #         Animal {
137    /// #             species: species.into(),
138    /// #             name: name.map(Into::into),
139    /// #             legs
140    /// #         }
141    /// #     }
142    /// # }
143    /// #
144    /// # fn main() {
145    /// #     use self::animals::dsl::*;
146    /// #     let connection = establish_connection();
147    /// #     connection.execute("DELETE FROM animals").unwrap();
148    /// diesel::insert_into(animals)
149    ///     .values(&vec![
150    ///         (species.eq("dog"), name.eq(Some("Jack")), legs.eq(4)),
151    ///         (species.eq("dog"), name.eq(None), legs.eq(4)),
152    ///         (species.eq("spider"), name.eq(None), legs.eq(8)),
153    ///     ])
154    ///     .execute(&connection)
155    ///     .unwrap();
156    /// let all_animals = animals.select((species, name, legs)).load(&connection);
157    /// let distinct_animals = animals.select((species, name, legs)).distinct_on(species).load(&connection);
158    ///
159    /// assert_eq!(Ok(vec![Animal::new("dog", Some("Jack"), 4),
160    ///                    Animal::new("dog", None, 4),
161    ///                    Animal::new("spider", None, 8)]), all_animals);
162    /// assert_eq!(Ok(vec![Animal::new("dog", Some("Jack"), 4),
163    ///                    Animal::new("spider", None, 8)]), distinct_animals);
164    /// # }
165    /// ```
166    #[cfg(feature = "postgres")]
167    fn distinct_on<Expr>(self, expr: Expr) -> DistinctOn<Self, Expr>
168    where
169        Self: methods::DistinctOnDsl<Expr>,
170    {
171        methods::DistinctOnDsl::distinct_on(self, expr)
172    }
173
174    // FIXME: Needs usage example and doc rewrite
175    /// Adds a `SELECT` clause to the query.
176    ///
177    /// If there was already a select clause present, it will be overridden.
178    /// For example, `foo.select(bar).select(baz)` will produce the same
179    /// query as `foo.select(baz)`.
180    ///
181    /// By default, the select clause will be roughly equivalent to `SELECT *`
182    /// (however, Diesel will list all columns to ensure that they are in the
183    /// order we expect).
184    ///
185    /// `select` has slightly stricter bounds on its arguments than other
186    /// methods. In particular, when used with a left outer join, `.nullable`
187    /// must be called on columns that come from the right side of a join. It
188    /// can be called on the column itself, or on an expression containing that
189    /// column. `title.nullable()`, `lower(title).nullable()`, and `(id,
190    /// title).nullable()` would all be valid.
191    ///
192    /// # Examples
193    ///
194    /// ```rust
195    /// # #[macro_use] extern crate diesel;
196    /// # include!("../doctest_setup.rs");
197    /// # use schema::users;
198    /// #
199    /// # fn main() {
200    /// #     run_test().unwrap();
201    /// # }
202    /// #
203    /// # fn run_test() -> QueryResult<()> {
204    /// #     use self::users::dsl::*;
205    /// #     let connection = establish_connection();
206    /// // By default, all columns will be selected
207    /// let all_users = users.load::<(i32, String)>(&connection)?;
208    /// assert_eq!(vec![(1, String::from("Sean")), (2, String::from("Tess"))], all_users);
209    ///
210    /// let all_names = users.select(name).load::<String>(&connection)?;
211    /// assert_eq!(vec!["Sean", "Tess"], all_names);
212    /// #     Ok(())
213    /// # }
214    /// ```
215    ///
216    /// ### When used with a left join
217    ///
218    /// ```rust
219    /// # #[macro_use] extern crate diesel;
220    /// # include!("../doctest_setup.rs");
221    /// # use schema::{users, posts};
222    /// #
223    /// # #[derive(Queryable, PartialEq, Eq, Debug)]
224    /// # struct User {
225    /// #     id: i32,
226    /// #     name: String,
227    /// # }
228    /// #
229    /// # impl User {
230    /// #     fn new(id: i32, name: &str) -> Self {
231    /// #         User {
232    /// #             id,
233    /// #             name: name.into(),
234    /// #         }
235    /// #     }
236    /// # }
237    /// #
238    /// # #[derive(Queryable, PartialEq, Eq, Debug)]
239    /// # struct Post {
240    /// #     id: i32,
241    /// #     user_id: i32,
242    /// #     title: String,
243    /// # }
244    /// #
245    /// # impl Post {
246    /// #     fn new(id: i32, user_id: i32, title: &str) -> Self {
247    /// #         Post {
248    /// #             id,
249    /// #             user_id,
250    /// #             title: title.into(),
251    /// #         }
252    /// #     }
253    /// # }
254    /// #
255    /// # fn main() {
256    /// #     run_test().unwrap();
257    /// # }
258    /// #
259    /// # fn run_test() -> QueryResult<()> {
260    /// #     let connection = establish_connection();
261    /// #     connection.execute("DELETE FROM posts")?;
262    /// #     diesel::insert_into(posts::table)
263    /// #         .values((posts::user_id.eq(1), posts::title.eq("Sean's Post")))
264    /// #         .execute(&connection)?;
265    /// #     let post_id = posts::table.select(posts::id)
266    /// #         .first::<i32>(&connection)?;
267    /// let join = users::table.left_join(posts::table);
268    ///
269    /// // By default, all columns from both tables are selected
270    /// let all_data = join.load::<(User, Option<Post>)>(&connection)?;
271    /// let expected_data = vec![
272    ///     (User::new(1, "Sean"), Some(Post::new(post_id, 1, "Sean's Post"))),
273    ///     (User::new(2, "Tess"), None),
274    /// ];
275    /// assert_eq!(expected_data, all_data);
276    ///
277    /// // Since `posts` is on the right side of a left join, `.nullable` is
278    /// // needed.
279    /// let names_and_titles = join.select((users::name, posts::title.nullable()))
280    ///     .load::<(String, Option<String>)>(&connection)?;
281    /// let expected_data = vec![
282    ///     (String::from("Sean"), Some(String::from("Sean's Post"))),
283    ///     (String::from("Tess"), None),
284    /// ];
285    /// assert_eq!(expected_data, names_and_titles);
286    /// #     Ok(())
287    /// # }
288    /// ```
289    fn select<Selection>(self, selection: Selection) -> Select<Self, Selection>
290    where
291        Selection: Expression,
292        Self: methods::SelectDsl<Selection>,
293    {
294        methods::SelectDsl::select(self, selection)
295    }
296
297    /// Get the count of a query. This is equivalent to `.select(count_star())`
298    ///
299    /// # Example
300    ///
301    /// ```rust
302    /// # #[macro_use] extern crate diesel;
303    /// # include!("../doctest_setup.rs");
304    /// #
305    /// # fn main() {
306    /// #     use schema::users::dsl::*;
307    /// #     let connection = establish_connection();
308    /// let count = users.count().get_result(&connection);
309    /// assert_eq!(Ok(2), count);
310    /// # }
311    /// ```
312    fn count(self) -> Select<Self, CountStar>
313    where
314        Self: methods::SelectDsl<CountStar>,
315    {
316        use dsl::count_star;
317
318        QueryDsl::select(self, count_star())
319    }
320
321    /// Join two tables using a SQL `INNER JOIN`.
322    ///
323    /// If you have invoked [`joinable!`] for the two tables, you can pass that
324    /// table directly.  Otherwise you will need to use [`.on`] to specify the `ON`
325    /// clause.
326    ///
327    /// [`joinable!`]: ../macro.joinable.html
328    /// [`.on`]: trait.JoinOnDsl.html#method.on
329    ///
330    /// You can join to as many tables as you'd like in a query, with the
331    /// restriction that no table can appear in the query more than once. The reason
332    /// for this restriction is that one of the appearances would require aliasing,
333    /// and we do not currently have a fleshed out story for dealing with table
334    /// aliases.
335    ///
336    /// You will also need to call [`allow_tables_to_appear_in_same_query!`].
337    /// If you are using `infer_schema!` or `diesel print-schema`, this will
338    /// have been generated for you.
339    /// See the documentation for [`allow_tables_to_appear_in_same_query!`] for
340    /// details.
341    ///
342    /// Diesel expects multi-table joins to be semantically grouped based on the
343    /// relationships. For example, `users.inner_join(posts.inner_join(comments))`
344    /// is not the same as `users.inner_join(posts).inner_join(comments)`. The first
345    /// would deserialize into `(User, (Post, Comment))` and generate the following
346    /// SQL:
347    ///
348    /// ```sql
349    /// SELECT * FROM users
350    ///     INNER JOIN posts ON posts.user_id = users.id
351    ///     INNER JOIN comments ON comments.post_id = posts.id
352    /// ```
353    ///
354    /// While the second query would deserialize into `(User, Post, Comment)` and
355    /// generate the following SQL:
356    ///
357    /// ```sql
358    /// SELECT * FROM users
359    ///     INNER JOIN posts ON posts.user_id = users.id
360    ///     INNER JOIN comments ON comments.user_id = users.id
361    /// ```
362    ///
363    /// [associations]: ../associations/index.html
364    /// [`allow_tables_to_appear_in_same_query!`]: ../macro.allow_tables_to_appear_in_same_query.html
365    ///
366    /// # Examples
367    ///
368    /// ### With implicit `ON` clause
369    ///
370    /// ```rust
371    /// # #[macro_use] extern crate diesel;
372    /// # include!("../doctest_setup.rs");
373    /// # use schema::{users, posts};
374    /// # /*
375    /// joinable!(posts -> users (user_id));
376    /// allow_tables_to_appear_in_same_query!(users, posts);
377    /// # */
378    ///
379    /// # fn main() {
380    /// #     use self::users::dsl::{users, name};
381    /// #     use self::posts::dsl::{posts, user_id, title};
382    /// #     let connection = establish_connection();
383    /// let data = users.inner_join(posts)
384    ///     .select((name, title))
385    ///     .load(&connection);
386    ///
387    /// let expected_data = vec![
388    ///     (String::from("Sean"), String::from("My first post")),
389    ///     (String::from("Sean"), String::from("About Rust")),
390    ///     (String::from("Tess"), String::from("My first post too")),
391    /// ];
392    /// assert_eq!(Ok(expected_data), data);
393    /// # }
394    /// ```
395    ///
396    /// ### With explicit `ON` clause
397    ///
398    /// ```rust
399    /// # #[macro_use] extern crate diesel;
400    /// # include!("../doctest_setup.rs");
401    /// # use schema::{users, posts};
402    /// #
403    /// # /*
404    /// allow_tables_to_appear_in_same_query!(users, posts);
405    /// # */
406    ///
407    /// # fn main() {
408    /// #     use self::users::dsl::{users, name};
409    /// #     use self::posts::dsl::{posts, user_id, title};
410    /// #     let connection = establish_connection();
411    /// diesel::insert_into(posts)
412    ///     .values(&vec![
413    ///         (user_id.eq(1), title.eq("Sean's post")),
414    ///         (user_id.eq(2), title.eq("Sean is a jerk")),
415    ///     ])
416    ///     .execute(&connection)
417    ///     .unwrap();
418    ///
419    /// let data = users
420    ///     .inner_join(posts.on(title.like(name.concat("%"))))
421    ///     .select((name, title))
422    ///     .load(&connection);
423    /// let expected_data = vec![
424    ///     (String::from("Sean"), String::from("Sean's post")),
425    ///     (String::from("Sean"), String::from("Sean is a jerk")),
426    /// ];
427    /// assert_eq!(Ok(expected_data), data);
428    /// # }
429    /// ```
430    fn inner_join<Rhs>(self, rhs: Rhs) -> Self::Output
431    where
432        Self: JoinWithImplicitOnClause<Rhs, joins::Inner>,
433    {
434        self.join_with_implicit_on_clause(rhs, joins::Inner)
435    }
436
437    /// Join two tables using a SQL `LEFT OUTER JOIN`.
438    ///
439    /// Behaves similarly to [`inner_join`], but will produce a left join
440    /// instead. See [`inner_join`] for usage examples.
441    ///
442    /// [`inner_join`]: #method.inner_join
443    fn left_outer_join<Rhs>(self, rhs: Rhs) -> Self::Output
444    where
445        Self: JoinWithImplicitOnClause<Rhs, joins::LeftOuter>,
446    {
447        self.join_with_implicit_on_clause(rhs, joins::LeftOuter)
448    }
449
450    /// Alias for [`left_outer_join`].
451    ///
452    /// [`left_outer_join`]: #method.left_outer_join
453    fn left_join<Rhs>(self, rhs: Rhs) -> Self::Output
454    where
455        Self: JoinWithImplicitOnClause<Rhs, joins::LeftOuter>,
456    {
457        self.left_outer_join(rhs)
458    }
459
460    /// Adds to the `WHERE` clause of a query.
461    ///
462    /// If there is already a `WHERE` clause, the result will be `old AND new`.
463    ///
464    /// # Example:
465    ///
466    /// ```rust
467    /// # #[macro_use] extern crate diesel;
468    /// # include!("../doctest_setup.rs");
469    /// #
470    /// # fn main() {
471    /// #     use schema::users::dsl::*;
472    /// #     let connection = establish_connection();
473    /// let seans_id = users.filter(name.eq("Sean")).select(id)
474    ///     .first(&connection);
475    /// assert_eq!(Ok(1), seans_id);
476    /// let tess_id = users.filter(name.eq("Tess")).select(id)
477    ///     .first(&connection);
478    /// assert_eq!(Ok(2), tess_id);
479    /// # }
480    /// ```
481    fn filter<Predicate>(self, predicate: Predicate) -> Filter<Self, Predicate>
482    where
483        Self: methods::FilterDsl<Predicate>,
484    {
485        methods::FilterDsl::filter(self, predicate)
486    }
487
488    /// Adds to the `WHERE` clause of a query using `OR`
489    ///
490    /// If there is already a `WHERE` clause, the result will be `(old OR new)`.
491    /// Calling `foo.filter(bar).or_filter(baz)`
492    /// is identical to `foo.filter(bar.or(baz))`.
493    /// However, the second form is much harder to do dynamically.
494    ///
495    /// # Example:
496    ///
497    /// ```rust
498    /// # #[macro_use] extern crate diesel;
499    /// # include!("../doctest_setup.rs");
500    /// #
501    /// # fn main() {
502    /// #     run_test().unwrap();
503    /// # }
504    /// #
505    /// # fn run_test() -> QueryResult<()> {
506    /// #     use schema::animals::dsl::*;
507    /// #     let connection = establish_connection();
508    /// #     diesel::delete(animals).execute(&connection)?;
509    /// diesel::insert_into(animals)
510    ///     .values(&vec![
511    ///         (species.eq("cat"), legs.eq(4), name.eq("Sinatra")),
512    ///         (species.eq("dog"), legs.eq(3), name.eq("Fido")),
513    ///         (species.eq("spider"), legs.eq(8), name.eq("Charlotte")),
514    ///     ])
515    ///     .execute(&connection)?;
516    ///
517    /// let good_animals = animals
518    ///     .filter(name.eq("Fido"))
519    ///     .or_filter(legs.eq(4))
520    ///     .select(name)
521    ///     .get_results::<Option<String>>(&connection)?;
522    /// let expected = vec![
523    ///     Some(String::from("Sinatra")),
524    ///     Some(String::from("Fido")),
525    /// ];
526    /// assert_eq!(expected, good_animals);
527    /// #     Ok(())
528    /// # }
529    /// ```
530    fn or_filter<Predicate>(self, predicate: Predicate) -> OrFilter<Self, Predicate>
531    where
532        Self: methods::OrFilterDsl<Predicate>,
533    {
534        methods::OrFilterDsl::or_filter(self, predicate)
535    }
536
537    /// Attempts to find a single record from the given table by primary key.
538    ///
539    /// # Example
540    ///
541    /// ```rust
542    /// # #[macro_use] extern crate diesel;
543    /// # include!("../doctest_setup.rs");
544    /// #
545    /// # fn main() {
546    /// #     use schema::users::dsl::*;
547    /// #     use diesel::result::Error::NotFound;
548    /// #     let connection = establish_connection();
549    /// let sean = (1, "Sean".to_string());
550    /// let tess = (2, "Tess".to_string());
551    /// assert_eq!(Ok(sean), users.find(1).first(&connection));
552    /// assert_eq!(Ok(tess), users.find(2).first(&connection));
553    /// assert_eq!(Err::<(i32, String), _>(NotFound), users.find(3).first(&connection));
554    /// # }
555    /// ```
556    fn find<PK>(self, id: PK) -> Find<Self, PK>
557    where
558        Self: methods::FindDsl<PK>,
559    {
560        methods::FindDsl::find(self, id)
561    }
562
563    /// Sets the order clause of a query.
564    ///
565    /// If there was already a order clause, it will be overridden. See
566    /// also:
567    /// [`.desc()`](../expression_methods/trait.ExpressionMethods.html#method.desc)
568    /// and
569    /// [`.asc()`](../expression_methods/trait.ExpressionMethods.html#method.asc)
570    ///
571    /// Ordering by multiple columns can be achieved by passing a tuple of those
572    /// columns.
573    /// To construct an order clause of an unknown number of columns,
574    /// see [`QueryDsl::then_order_by`](#method.then_order_by)
575    ///
576    /// # Examples
577    ///
578    /// ```rust
579    /// # #[macro_use] extern crate diesel;
580    /// # include!("../doctest_setup.rs");
581    /// #
582    /// # fn main() {
583    /// #     run_test();
584    /// # }
585    /// #
586    /// # fn run_test() -> QueryResult<()> {
587    /// #     use schema::users::dsl::*;
588    /// #     let connection = establish_connection();
589    /// #     connection.execute("DELETE FROM users")?;
590    /// diesel::insert_into(users)
591    ///     .values(&vec![
592    ///         name.eq("Saul"),
593    ///         name.eq("Steve"),
594    ///         name.eq("Stan"),
595    ///     ])
596    ///     .execute(&connection)?;
597    ///
598    /// let ordered_names = users.select(name)
599    ///     .order(name.desc())
600    ///     .load::<String>(&connection)?;
601    /// assert_eq!(vec!["Steve", "Stan", "Saul"], ordered_names);
602    ///
603    /// diesel::insert_into(users).values(name.eq("Stan")).execute(&connection)?;
604    ///
605    /// let data = users.select((name, id))
606    ///     .order((name.asc(), id.desc()))
607    ///     .load(&connection)?;
608    /// let expected_data = vec![
609    ///     (String::from("Saul"), 3),
610    ///     (String::from("Stan"), 6),
611    ///     (String::from("Stan"), 5),
612    ///     (String::from("Steve"), 4),
613    /// ];
614    /// assert_eq!(expected_data, data);
615    /// #    Ok(())
616    /// # }
617    /// ```
618    fn order<Expr>(self, expr: Expr) -> Order<Self, Expr>
619    where
620        Expr: Expression,
621        Self: methods::OrderDsl<Expr>,
622    {
623        methods::OrderDsl::order(self, expr)
624    }
625
626    /// Alias for `order`
627    fn order_by<Expr>(self, expr: Expr) -> Order<Self, Expr>
628    where
629        Expr: Expression,
630        Self: methods::OrderDsl<Expr>,
631    {
632        QueryDsl::order(self, expr)
633    }
634
635    /// Appends to the `ORDER BY` clause of this SQL query.
636    ///
637    /// Unlike `.order`, this method will append rather than replace.
638    /// In other words,
639    /// `.order_by(foo).order_by(bar)` is equivalent to `.order_by(bar)`.
640    /// In contrast,
641    /// `.order_by(foo).then_order_by(bar)` is equivalent to `.order((foo, bar))`.
642    /// This method is only present on boxed queries.
643    ///
644    /// # Examples
645    ///
646    /// ```rust
647    /// # #[macro_use] extern crate diesel;
648    /// # include!("../doctest_setup.rs");
649    /// #
650    /// # fn main() {
651    /// #     run_test();
652    /// # }
653    /// #
654    /// # fn run_test() -> QueryResult<()> {
655    /// #     use schema::users::dsl::*;
656    /// #     let connection = establish_connection();
657    /// #     connection.execute("DELETE FROM users")?;
658    /// diesel::insert_into(users)
659    ///     .values(&vec![
660    ///         name.eq("Saul"),
661    ///         name.eq("Steve"),
662    ///         name.eq("Stan"),
663    ///         name.eq("Stan"),
664    ///     ])
665    ///     .execute(&connection)?;
666    ///
667    /// let data = users.select((name, id))
668    ///     .order_by(name.asc())
669    ///     .then_order_by(id.desc())
670    ///     .load(&connection)?;
671    /// let expected_data = vec![
672    ///     (String::from("Saul"), 3),
673    ///     (String::from("Stan"), 6),
674    ///     (String::from("Stan"), 5),
675    ///     (String::from("Steve"), 4),
676    /// ];
677    /// assert_eq!(expected_data, data);
678    /// #    Ok(())
679    /// # }
680    /// ```
681    fn then_order_by<Order>(self, order: Order) -> ThenOrderBy<Self, Order>
682    where
683        Self: methods::ThenOrderDsl<Order>,
684    {
685        methods::ThenOrderDsl::then_order_by(self, order)
686    }
687
688    /// Sets the limit clause of the query.
689    ///
690    /// If there was already a limit clause, it will be overridden.
691    ///
692    /// # Example
693    ///
694    /// ```rust
695    /// # #[macro_use] extern crate diesel;
696    /// # include!("../doctest_setup.rs");
697    /// # use schema::users;
698    /// #
699    /// # fn main() {
700    /// #     run_test().unwrap();
701    /// # }
702    /// #
703    /// # fn run_test() -> QueryResult<()> {
704    /// #     use users::dsl::*;
705    /// #     let connection = establish_connection();
706    /// #     diesel::delete(users).execute(&connection)?;
707    /// #     diesel::insert_into(users)
708    /// #        .values(&vec![
709    /// #            name.eq("Sean"),
710    /// #            name.eq("Bastien"),
711    /// #            name.eq("Pascal"),
712    /// #        ])
713    /// #        .execute(&connection)?;
714    /// #
715    /// // Using a limit
716    /// let limited = users.select(name)
717    ///     .order(id)
718    ///     .limit(1)
719    ///     .load::<String>(&connection)?;
720    ///
721    /// // Without a limit
722    /// let no_limit = users.select(name)
723    ///     .order(id)
724    ///     .load::<String>(&connection)?;
725    ///
726    /// assert_eq!(vec!["Sean"], limited);
727    /// assert_eq!(vec!["Sean", "Bastien", "Pascal"], no_limit);
728    /// #    Ok(())
729    /// # }
730    /// ```
731    fn limit(self, limit: i64) -> Limit<Self>
732    where
733        Self: methods::LimitDsl,
734    {
735        methods::LimitDsl::limit(self, limit)
736    }
737
738    /// Sets the offset clause of the query.
739    ///
740    /// If there was already a offset clause, it will be overridden.
741    ///
742    /// # Example
743    ///
744    /// ```rust
745    /// # #[macro_use] extern crate diesel;
746    /// # include!("../doctest_setup.rs");
747    /// # use schema::users;
748    /// #
749    /// # fn main() {
750    /// #     run_test().unwrap();
751    /// # }
752    /// #
753    /// # fn run_test() -> QueryResult<()> {
754    /// #     use users::dsl::*;
755    /// #     let connection = establish_connection();
756    /// #     diesel::delete(users).execute(&connection)?;
757    /// #     diesel::insert_into(users)
758    /// #        .values(&vec![
759    /// #            name.eq("Sean"),
760    /// #            name.eq("Bastien"),
761    /// #            name.eq("Pascal"),
762    /// #        ])
763    /// #        .execute(&connection)?;
764    /// #
765    /// // Using an offset
766    /// let offset = users.select(name)
767    ///     .order(id)
768    ///     .limit(2)
769    ///     .offset(1)
770    ///     .load::<String>(&connection)?;
771    ///
772    /// // No Offset
773    /// let no_offset = users.select(name)
774    ///     .order(id)
775    ///     .limit(2)
776    ///     .load::<String>(&connection)?;
777    ///
778    /// assert_eq!(vec!["Bastien", "Pascal"], offset);
779    /// assert_eq!(vec!["Sean", "Bastien"], no_offset);
780    /// #     Ok(())
781    /// # }
782    /// ```
783    fn offset(self, offset: i64) -> Offset<Self>
784    where
785        Self: methods::OffsetDsl,
786    {
787        methods::OffsetDsl::offset(self, offset)
788    }
789
790    /// Adds `FOR UPDATE` to the end of the select statement.
791    ///
792    /// This method is only available for MySQL and PostgreSQL. SQLite does not
793    /// provide any form of row locking.
794    ///
795    /// Additionally, `.for_update` cannot be used on queries with a distinct
796    /// clause, group by clause, having clause, or any unions. Queries with
797    /// a `FOR UPDATE` clause cannot be boxed.
798    ///
799    /// # Example
800    ///
801    /// ```ignore
802    /// // Executes `SELECT * FROM users FOR UPDATE`
803    /// users.for_update().load(&connection)
804    /// ```
805    #[cfg(feature = "with-deprecated")]
806    #[allow(deprecated)]
807    fn for_update(self) -> ForUpdate<Self>
808    where
809        Self: methods::ForUpdateDsl,
810    {
811        methods::ForUpdateDsl::for_update(self)
812    }
813
814    /// Adds `FOR UPDATE` to the end of the select statement.
815    ///
816    /// This method is only available for MySQL and PostgreSQL. SQLite does not
817    /// provide any form of row locking.
818    ///
819    /// Additionally, `.for_update` cannot be used on queries with a distinct
820    /// clause, group by clause, having clause, or any unions. Queries with
821    /// a `FOR UPDATE` clause cannot be boxed.
822    ///
823    /// # Example
824    ///
825    /// ```ignore
826    /// // Executes `SELECT * FROM users FOR UPDATE`
827    /// users.for_update().load(&connection)
828    /// ```
829    #[cfg(not(feature = "with-deprecated"))]
830    fn for_update(self) -> ForUpdate<Self>
831    where
832        Self: methods::LockingDsl<lock::ForUpdate>,
833    {
834        methods::LockingDsl::with_lock(self, lock::ForUpdate)
835    }
836
837    /// Adds `FOR NO KEY UPDATE` to the end of the select statement.
838    ///
839    /// This method is only available for PostgreSQL. SQLite does not
840    /// provide any form of row locking, and MySQL does not support anything
841    /// finer than row-level locking.
842    ///
843    /// Additionally, `.for_no_key_update` cannot be used on queries with a distinct
844    /// clause, group by clause, having clause, or any unions. Queries with
845    /// a `FOR NO KEY UPDATE` clause cannot be boxed.
846    ///
847    /// # Example
848    ///
849    /// ```ignore
850    /// // Executes `SELECT * FROM users FOR NO KEY UPDATE`
851    /// users.for_no_key_update().load(&connection)
852    /// ```
853    fn for_no_key_update(self) -> ForNoKeyUpdate<Self>
854    where
855        Self: methods::LockingDsl<lock::ForNoKeyUpdate>,
856    {
857        methods::LockingDsl::with_lock(self, lock::ForNoKeyUpdate)
858    }
859
860    /// Adds `FOR SHARE` to the end of the select statement.
861    ///
862    /// This method is only available for MySQL and PostgreSQL. SQLite does not
863    /// provide any form of row locking.
864    ///
865    /// Additionally, `.for_share` cannot be used on queries with a distinct
866    /// clause, group by clause, having clause, or any unions. Queries with
867    /// a `FOR SHARE` clause cannot be boxed.
868    ///
869    /// # Example
870    ///
871    /// ```ignore
872    /// // Executes `SELECT * FROM users FOR SHARE`
873    /// users.for_share().load(&connection)
874    /// ```
875    fn for_share(self) -> ForShare<Self>
876    where
877        Self: methods::LockingDsl<lock::ForShare>,
878    {
879        methods::LockingDsl::with_lock(self, lock::ForShare)
880    }
881
882    /// Adds `FOR KEY SHARE` to the end of the select statement.
883    ///
884    /// This method is only available for PostgreSQL. SQLite does not
885    /// provide any form of row locking, and MySQL does not support anything
886    /// finer than row-level locking.
887    ///
888    /// Additionally, `.for_key_share` cannot be used on queries with a distinct
889    /// clause, group by clause, having clause, or any unions. Queries with
890    /// a `FOR KEY SHARE` clause cannot be boxed.
891    ///
892    /// # Example
893    ///
894    /// ```ignore
895    /// // Executes `SELECT * FROM users FOR KEY SHARE`
896    /// users.for_key_share().load(&connection)
897    /// ```
898    fn for_key_share(self) -> ForKeyShare<Self>
899    where
900        Self: methods::LockingDsl<lock::ForKeyShare>,
901    {
902        methods::LockingDsl::with_lock(self, lock::ForKeyShare)
903    }
904
905    /// Adds `SKIP LOCKED` to the end of a `FOR UPDATE` clause.
906    ///
907    /// This modifier is only supported in PostgreSQL 9.5+ and MySQL 8+.
908    ///
909    /// # Example
910    ///
911    /// ```ignore
912    /// // Executes `SELECT * FROM users FOR UPDATE SKIP LOCKED`
913    /// users.for_update().skip_locked().load(&connection)
914    /// ```
915    fn skip_locked(self) -> SkipLocked<Self>
916    where
917        Self: methods::ModifyLockDsl<lock::SkipLocked>,
918    {
919        methods::ModifyLockDsl::modify_lock(self, lock::SkipLocked)
920    }
921
922    /// Adds `NOWAIT` to the end of a `FOR UPDATE` clause.
923    ///
924    /// This modifier is only supported in PostgreSQL 9.5+ and MySQL 8+.
925    ///
926    /// # Example
927    ///
928    /// ```ignore
929    /// // Executes `SELECT * FROM users FOR UPDATE NOWAIT`
930    /// users.for_update().no_wait().load(&connection)
931    /// ```
932    fn no_wait(self) -> NoWait<Self>
933    where
934        Self: methods::ModifyLockDsl<lock::NoWait>,
935    {
936        methods::ModifyLockDsl::modify_lock(self, lock::NoWait)
937    }
938
939    /// Boxes the pieces of a query into a single type.
940    ///
941    /// This is useful for cases where you want to conditionally modify a query,
942    /// but need the type to remain the same. The backend must be specified as
943    /// part of this. It is not possible to box a query and have it be useable
944    /// on multiple backends.
945    ///
946    /// A boxed query will incur a minor performance penalty, as the query builder
947    /// can no longer be inlined by the compiler. For most applications this cost
948    /// will be minimal.
949    ///
950    /// ### Example
951    ///
952    /// ```rust
953    /// # #[macro_use] extern crate diesel;
954    /// # include!("../doctest_setup.rs");
955    /// # use schema::users;
956    /// #
957    /// # fn main() {
958    /// #     use std::collections::HashMap;
959    /// #     let connection = establish_connection();
960    /// #     let mut params = HashMap::new();
961    /// #     params.insert("name", "Sean");
962    /// let mut query = users::table.into_boxed();
963    /// if let Some(name) = params.get("name") {
964    ///     query = query.filter(users::name.eq(name));
965    /// }
966    /// let users = query.load(&connection);
967    /// #     let expected = vec![(1, String::from("Sean"))];
968    /// #     assert_eq!(Ok(expected), users);
969    /// # }
970    /// ```
971    ///
972    /// Diesel queries also have a similar problem to [`Iterator`][iterator], where
973    /// returning them from a function requires exposing the implementation of that
974    /// function. The [`helper_types`][helper_types] module exists to help with this,
975    /// but you might want to hide the return type or have it conditionally change.
976    /// Boxing can achieve both.
977    ///
978    /// [iterator]: https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html
979    /// [helper_types]: ../helper_types/index.html
980    ///
981    /// ### Example
982    ///
983    /// ```rust
984    /// # #[macro_use] extern crate diesel;
985    /// # include!("../doctest_setup.rs");
986    /// # use schema::users;
987    /// #
988    /// # fn main() {
989    /// #     let connection = establish_connection();
990    /// fn users_by_name<'a>(name: &'a str) -> users::BoxedQuery<'a, DB> {
991    ///     users::table.filter(users::name.eq(name)).into_boxed()
992    /// }
993    ///
994    /// assert_eq!(Ok(1), users_by_name("Sean").select(users::id).first(&connection));
995    /// assert_eq!(Ok(2), users_by_name("Tess").select(users::id).first(&connection));
996    /// # }
997    /// ```
998    fn into_boxed<'a, DB>(self) -> IntoBoxed<'a, Self, DB>
999    where
1000        DB: Backend,
1001        Self: methods::BoxedDsl<'a, DB>,
1002    {
1003        methods::BoxedDsl::internal_into_boxed(self)
1004    }
1005
1006    /// Wraps this select statement in parenthesis, allowing it to be used
1007    /// as an expression.
1008    ///
1009    /// SQL allows queries such as `foo = (SELECT ...)`, as long as the
1010    /// subselect returns only a single column, and 0 or 1 rows. This method
1011    /// indicates that you expect the query to only return a single value (this
1012    /// will be enforced by adding `LIMIT 1`).
1013    ///
1014    /// The SQL type of this will always be `Nullable`, as the query returns
1015    /// `NULL` if the table is empty or it otherwise returns 0 rows.
1016    ///
1017    /// # Example
1018    ///
1019    /// ```rust
1020    /// # #[macro_use] extern crate diesel;
1021    /// # include!("../doctest_setup.rs");
1022    /// #
1023    /// # fn main() {
1024    /// #     run_test();
1025    /// # }
1026    /// #
1027    /// # fn run_test() -> QueryResult<()> {
1028    /// #     use diesel::insert_into;
1029    /// #     use schema::users::dsl::*;
1030    /// #     use schema::posts;
1031    /// #     let connection = establish_connection();
1032    /// insert_into(posts::table)
1033    ///     .values(posts::user_id.eq(1))
1034    ///     .execute(&connection)?;
1035    /// let last_post = posts::table
1036    ///     .order(posts::id.desc());
1037    /// let most_recently_active_user = users.select(name)
1038    ///     .filter(id.nullable().eq(last_post.select(posts::user_id).single_value()))
1039    ///     .first::<String>(&connection)?;
1040    /// assert_eq!("Sean", most_recently_active_user);
1041    /// #     Ok(())
1042    /// # }
1043    /// ```
1044    fn single_value(self) -> SingleValue<Self>
1045    where
1046        Self: methods::SingleValueDsl,
1047    {
1048        methods::SingleValueDsl::single_value(self)
1049    }
1050
1051    /// Coerce the SQL type of the select clause to it's nullable equivalent.
1052    ///
1053    /// This is use full for writing queries that contain subselects on non null
1054    /// fields comparing them to nullable fields.
1055    /// ```rust
1056    /// # #[macro_use] extern crate diesel;
1057    /// # include!("../doctest_setup.rs");
1058    /// #
1059    /// # fn main() {
1060    /// #    run_test();
1061    /// # }
1062    /// #
1063    /// # fn run_test() -> QueryResult<()> {
1064    /// #     let connection = establish_connection();
1065    /// table! {
1066    ///     users {
1067    ///         id -> Integer,
1068    ///         name -> Text,
1069    ///     }
1070    /// }
1071    ///
1072    /// table! {
1073    ///     posts {
1074    ///         id -> Integer,
1075    ///         by_user -> Nullable<Text>,
1076    ///     }
1077    /// }
1078    ///
1079    /// # let _: Vec<(i32, Option<String>)> =
1080    /// posts::table.filter(
1081    ///    posts::by_user.eq_any(users::table.select(users::name).nullable())
1082    /// ).load(&connection)?;
1083    /// #     Ok(())
1084    /// # }
1085    fn nullable(self) -> NullableSelect<Self>
1086    where
1087        Self: methods::SelectNullableDsl,
1088    {
1089        methods::SelectNullableDsl::nullable(self)
1090    }
1091}
1092
1093impl<T: Table> QueryDsl for T {}
1094
1095/// Methods used to execute queries.
1096pub trait RunQueryDsl<Conn>: Sized {
1097    /// Executes the given command, returning the number of rows affected.
1098    ///
1099    /// `execute` is usually used in conjunction with [`insert_into`](../fn.insert_into.html),
1100    /// [`update`](../fn.update.html) and [`delete`](../fn.delete.html) where the number of
1101    /// affected rows is often enough information.
1102    ///
1103    /// When asking the database to return data from a query, [`load`](#method.load) should
1104    /// probably be used instead.
1105    ///
1106    /// # Example
1107    ///
1108    /// ```rust
1109    /// # #[macro_use] extern crate diesel;
1110    /// # include!("../doctest_setup.rs");
1111    /// #
1112    /// # fn main() {
1113    /// #     run_test();
1114    /// # }
1115    /// #
1116    /// # fn run_test() -> QueryResult<()> {
1117    /// #     use diesel::insert_into;
1118    /// #     use schema::users::dsl::*;
1119    /// #     let connection = establish_connection();
1120    /// let inserted_rows = insert_into(users)
1121    ///     .values(name.eq("Ruby"))
1122    ///     .execute(&connection)?;
1123    /// assert_eq!(1, inserted_rows);
1124    ///
1125    /// let inserted_rows = insert_into(users)
1126    ///     .values(&vec![name.eq("Jim"), name.eq("James")])
1127    ///     .execute(&connection)?;
1128    /// assert_eq!(2, inserted_rows);
1129    /// #     Ok(())
1130    /// # }
1131    /// ```
1132    fn execute(self, conn: &Conn) -> QueryResult<usize>
1133    where
1134        Conn: Connection,
1135        Self: methods::ExecuteDsl<Conn>,
1136    {
1137        methods::ExecuteDsl::execute(self, conn)
1138    }
1139
1140    /// Executes the given query, returning a `Vec` with the returned rows.
1141    ///
1142    /// When using the query builder,
1143    /// the return type can be
1144    /// a tuple of the values,
1145    /// or a struct which implements [`Queryable`].
1146    ///
1147    /// When this method is called on [`sql_query`],
1148    /// the return type can only be a struct which implements [`QueryableByName`]
1149    ///
1150    /// For insert, update, and delete operations where only a count of affected is needed,
1151    /// [`execute`] should be used instead.
1152    ///
1153    /// [`Queryable`]: ../deserialize/trait.Queryable.html
1154    /// [`QueryableByName`]: ../deserialize/trait.QueryableByName.html
1155    /// [`execute`]: fn.execute.html
1156    /// [`sql_query`]: ../fn.sql_query.html
1157    ///
1158    /// # Examples
1159    ///
1160    /// ## Returning a single field
1161    ///
1162    /// ```rust
1163    /// # #[macro_use] extern crate diesel;
1164    /// # include!("../doctest_setup.rs");
1165    /// #
1166    /// # fn main() {
1167    /// #     run_test();
1168    /// # }
1169    /// #
1170    /// # fn run_test() -> QueryResult<()> {
1171    /// #     use diesel::insert_into;
1172    /// #     use schema::users::dsl::*;
1173    /// #     let connection = establish_connection();
1174    /// let data = users.select(name)
1175    ///     .load::<String>(&connection)?;
1176    /// assert_eq!(vec!["Sean", "Tess"], data);
1177    /// #     Ok(())
1178    /// # }
1179    /// ```
1180    ///
1181    /// ## Returning a tuple
1182    ///
1183    /// ```rust
1184    /// # #[macro_use] extern crate diesel;
1185    /// # include!("../doctest_setup.rs");
1186    /// #
1187    /// # fn main() {
1188    /// #     run_test();
1189    /// # }
1190    /// #
1191    /// # fn run_test() -> QueryResult<()> {
1192    /// #     use diesel::insert_into;
1193    /// #     use schema::users::dsl::*;
1194    /// #     let connection = establish_connection();
1195    /// let data = users
1196    ///     .load::<(i32, String)>(&connection)?;
1197    /// let expected_data = vec![
1198    ///     (1, String::from("Sean")),
1199    ///     (2, String::from("Tess")),
1200    /// ];
1201    /// assert_eq!(expected_data, data);
1202    /// #     Ok(())
1203    /// # }
1204    /// ```
1205    ///
1206    /// ## Returning a struct
1207    ///
1208    /// ```rust
1209    /// # #[macro_use] extern crate diesel;
1210    /// # include!("../doctest_setup.rs");
1211    /// #
1212    /// #[derive(Queryable, PartialEq, Debug)]
1213    /// struct User {
1214    ///     id: i32,
1215    ///     name: String,
1216    /// }
1217    ///
1218    /// # fn main() {
1219    /// #     run_test();
1220    /// # }
1221    /// #
1222    /// # fn run_test() -> QueryResult<()> {
1223    /// #     use diesel::insert_into;
1224    /// #     use schema::users::dsl::*;
1225    /// #     let connection = establish_connection();
1226    /// let data = users
1227    ///     .load::<User>(&connection)?;
1228    /// let expected_data = vec![
1229    ///     User { id: 1, name: String::from("Sean"), },
1230    ///     User { id: 2, name: String::from("Tess"), },
1231    /// ];
1232    /// assert_eq!(expected_data, data);
1233    /// #     Ok(())
1234    /// # }
1235    /// ```
1236    fn load<U>(self, conn: &Conn) -> QueryResult<Vec<U>>
1237    where
1238        Self: LoadQuery<Conn, U>,
1239    {
1240        self.internal_load(conn)
1241    }
1242
1243    /// Runs the command, and returns the affected row.
1244    ///
1245    /// `Err(NotFound)` will be returned if the query affected 0 rows. You can
1246    /// call `.optional()` on the result of this if the command was optional to
1247    /// get back a `Result<Option<U>>`
1248    ///
1249    /// When this method is called on an insert, update, or delete statement,
1250    /// it will implicitly add a `RETURNING *` to the query,
1251    /// unless a returning clause was already specified.
1252    ///
1253    /// # Example
1254    ///
1255    /// ```rust
1256    /// # #[macro_use] extern crate diesel;
1257    /// # include!("../doctest_setup.rs");
1258    /// #
1259    /// # fn main() {
1260    /// #     run_test();
1261    /// # }
1262    /// #
1263    /// # #[cfg(feature = "postgres")]
1264    /// # fn run_test() -> QueryResult<()> {
1265    /// #     use diesel::{insert_into, update};
1266    /// #     use schema::users::dsl::*;
1267    /// #     let connection = establish_connection();
1268    /// let inserted_row = insert_into(users)
1269    ///     .values(name.eq("Ruby"))
1270    ///     .get_result(&connection)?;
1271    /// assert_eq!((3, String::from("Ruby")), inserted_row);
1272    ///
1273    /// // This will return `NotFound`, as there is no user with ID 4
1274    /// let update_result = update(users.find(4))
1275    ///     .set(name.eq("Jim"))
1276    ///     .get_result::<(i32, String)>(&connection);
1277    /// assert_eq!(Err(diesel::NotFound), update_result);
1278    /// #     Ok(())
1279    /// # }
1280    /// #
1281    /// # #[cfg(not(feature = "postgres"))]
1282    /// # fn run_test() -> QueryResult<()> {
1283    /// #     Ok(())
1284    /// # }
1285    /// ```
1286    fn get_result<U>(self, conn: &Conn) -> QueryResult<U>
1287    where
1288        Self: LoadQuery<Conn, U>,
1289    {
1290        first_or_not_found(self.load(conn))
1291    }
1292
1293    /// Runs the command, returning an `Vec` with the affected rows.
1294    ///
1295    /// This method is an alias for [`load`], but with a name that makes more
1296    /// sense for insert, update, and delete statements.
1297    ///
1298    /// [`load`]: #method.load
1299    fn get_results<U>(self, conn: &Conn) -> QueryResult<Vec<U>>
1300    where
1301        Self: LoadQuery<Conn, U>,
1302    {
1303        self.load(conn)
1304    }
1305
1306    /// Attempts to load a single record.
1307    ///
1308    /// This method is equivalent to `.limit(1).get_result()`
1309    ///
1310    /// Returns `Ok(record)` if found, and `Err(NotFound)` if no results are
1311    /// returned. If the query truly is optional, you can call `.optional()` on
1312    /// the result of this to get a `Result<Option<U>>`.
1313    ///
1314    /// # Example:
1315    ///
1316    /// ```rust
1317    /// # #[macro_use] extern crate diesel;
1318    /// # include!("../doctest_setup.rs");
1319    /// # fn main() {
1320    /// #     run_test();
1321    /// # }
1322    /// #
1323    /// # fn run_test() -> QueryResult<()> {
1324    /// #     use schema::users::dsl::*;
1325    /// #     let connection = establish_connection();
1326    /// diesel::insert_into(users)
1327    ///     .values(&vec![name.eq("Sean"), name.eq("Pascal")])
1328    ///     .execute(&connection)?;
1329    ///
1330    /// let first_name = users.order(id).select(name).first(&connection);
1331    /// assert_eq!(Ok(String::from("Sean")), first_name);
1332    ///
1333    /// let not_found = users
1334    ///     .filter(name.eq("Foo"))
1335    ///     .first::<(i32, String)>(&connection);
1336    /// assert_eq!(Err(diesel::NotFound), not_found);
1337    /// #     Ok(())
1338    /// # }
1339    /// ```
1340    fn first<U>(self, conn: &Conn) -> QueryResult<U>
1341    where
1342        Self: methods::LimitDsl,
1343        Limit<Self>: LoadQuery<Conn, U>,
1344    {
1345        methods::LimitDsl::limit(self, 1).get_result(conn)
1346    }
1347}
1348
1349// Note: We could have a blanket `AsQuery` impl here, which would apply to
1350// everything we want it to. However, when a query is invalid, we specifically
1351// want the error to happen on the where clause of the method instead of trait
1352// resolution. Otherwise our users will get an error saying `<3 page long type>:
1353// ExecuteDsl is not satisfied` instead of a specific error telling them what
1354// part of their query is wrong.
1355impl<T, Conn> RunQueryDsl<Conn> for T where T: Table {}