Debian Codegraph @

src/pg/expression/extensions/tablesample_dsl.rs

raw
1 use crate::pg::query_builder::tablesample::{BernoulliMethod, SystemMethod};
2 use crate::query_builder::Tablesample;
3 use crate::Table;
4
5 /// The `tablesample` method
6 ///
7 /// The `TABLESAMPLE` clause is used to select a randomly sampled subset of rows from a table.
8 ///
9 /// This is only implemented for the Postgres backend. While `TABLESAMPLE` is standardized in
10 /// SQL:2003, in practice each RDBMS seems to implement a superset of the SQL:2003 syntax,
11 /// supporting a wide variety of sampling methods.
12 ///
13 /// Calling this function on a table (`mytable.tablesample(...)`) will result in the SQL
14 /// `FROM mytable TABLESAMPLE ...` --
15 /// `mytable.tablesample(...)` can be used just like any table in diesel since it implements
16 /// [Table](crate::Table).
17 ///
18 /// The `BernoulliMethod` and `SystemMethod` types can be used to indicate the sampling method for
19 /// a `TABLESAMPLE method(p)` clause where p is specified by the portion argument. The provided
20 /// percentage should be an integer between 0 and 100.
21 ///
22 /// To generate a `TABLESAMPLE ... REPEATABLE (f)` clause, you'll need to call
23 /// [`.with_seed(f)`](Tablesample::with_seed).
24 ///
25 /// Example:
26 ///
27 /// ```rust
28 /// # include!("../../../doctest_setup.rs");
29 /// # use schema::{posts, users};
30 /// # use diesel::dsl::*;
31 /// # fn main() {
32 /// # let connection = &mut establish_connection();
33 /// let random_user_ids = users::table
34 /// .tablesample_bernoulli(10)
35 /// .select((users::id))
36 /// .load::<i32>(connection);
37 /// # }
38 /// ```
39 /// Selects the ids for a random 10 percent of users.
40 ///
41 /// It can also be used in inner joins:
42 ///
43 /// ```rust
44 /// # include!("../../../doctest_setup.rs");
45 /// # use schema::{posts, users};
46 /// # use diesel::dsl::*;
47 /// # fn main() {
48 /// # let connection = &mut establish_connection();
49 /// # let _ =
50 /// users::table
51 /// .tablesample_system(10)
52 /// .with_seed(42.0)
53 /// .inner_join(posts::table)
54 /// .select((users::name, posts::title))
55 /// .load::<(String, String)>(connection);
56 /// # }
57 /// ```
58 /// That query selects all of the posts for all of the users in a random 10 percent storage pages,
59 /// returning the same results each time it is run due to the static seed of 42.0.
60 pub trait TablesampleDsl: Table {
61 /// See the trait-level docs.
62 fn tablesample_bernoulli(self, portion: i16) -> Tablesample<Self, BernoulliMethod> {
63 Tablesample::new(self, portion)
64 }
65
66 /// See the trait-level docs.
67 fn tablesample_system(self, portion: i16) -> Tablesample<Self, SystemMethod> {
68 Tablesample::new(self, portion)
69 }
70 }
71
72 impl<T: Table> TablesampleDsl for T {}