diesel/pg/expression/extensions/
tablesample_dsl.rs

1use crate::pg::query_builder::tablesample::{BernoulliMethod, SystemMethod};
2use crate::query_builder::Tablesample;
3use 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).with_seed(42.0)
52///     .inner_join(posts::table)
53///     .select((users::name, posts::title))
54///     .load::<(String, String)>(connection);
55/// # }
56/// ```
57/// That query selects all of the posts for all of the users in a random 10 percent storage pages,
58/// returning the same results each time it is run due to the static seed of 42.0.
59///
60pub 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
72impl<T: Table> TablesampleDsl for T {}