Skip to main content

sql_builder/query/
select.rs

1use std::fmt::Display;
2
3use crate::{
4    BoundSql, ColumnRef, ConditionHolder, DynIden, Expr, FunctionCall, IntoColumnRef,
5    IntoCondition, IntoIden, IntoTableRef, IntoValueTuple, JoinOn, JoinType, OrderExpr,
6    QueryStatement, SubQueryStatement, TableRef, Value, ValueTuple, WindowStatement, WithClause,
7    WithQuery,
8};
9
10mod build;
11mod construction;
12mod grouping;
13mod join_custom;
14mod joins;
15mod modifiers;
16mod projection;
17mod sources;
18
19/// Select rows from an existing table
20///
21/// # Examples
22///
23/// ```
24/// use sql_builder::*;
25///
26/// let query = Query::select()
27///     .column("character")
28///     .column(("font", "name"))
29///     .from("character")
30///     .left_join("font", Expr::col(("character", "font_id")).equals(("font", "id")))
31///     .and_where(Expr::col("size_w").is_in([3, 4]))
32///     .and_where(Expr::col("character").like("A%"))
33///     .to_owned();
34///
35/// assert_eq!(
36///     query.to_string(MysqlQueryBuilder).unwrap(),
37///     r#"SELECT `character`, `font`.`name` FROM `character` LEFT JOIN `font` ON `character`.`font_id` = `font`.`id` WHERE `size_w` IN (3, 4) AND `character` LIKE 'A%'"#
38/// );
39/// assert_eq!(
40///     query.to_string(PostgresQueryBuilder).unwrap(),
41///     r#"SELECT "character", "font"."name" FROM "character" LEFT JOIN "font" ON "character"."font_id" = "font"."id" WHERE "size_w" IN (3, 4) AND "character" LIKE 'A%'"#
42/// );
43/// assert_eq!(
44///     query.to_string(SqliteQueryBuilder).unwrap(),
45///     r#"SELECT "character", "font"."name" FROM "character" LEFT JOIN "font" ON "character"."font_id" = "font"."id" WHERE "size_w" IN (3, 4) AND "character" LIKE 'A%'"#
46/// );
47/// ```
48#[derive(Default, Debug, Clone, PartialEq)]
49pub struct SelectStatement {
50    pub(crate) distinct: Option<SelectDistinct>,
51    pub(crate) selects: Vec<SelectExpr>,
52    pub(crate) into: Option<SelectInto>,
53    pub(crate) from: Vec<TableRef>,
54    pub(crate) join: Vec<JoinExpr>,
55    pub(crate) r#where: ConditionHolder,
56    pub(crate) groups: Vec<Expr>,
57    pub(crate) having: ConditionHolder,
58    pub(crate) unions: Vec<(UnionType, SelectStatement)>,
59    pub(crate) orders: Vec<OrderExpr>,
60    pub(crate) limit: Option<Value>,
61    pub(crate) offset: Option<Value>,
62    pub(crate) lock: Option<LockClause>,
63    pub(crate) window: Option<(DynIden, WindowStatement)>,
64    pub(crate) with: Option<Box<WithClause>>,
65    pub(crate) custom: Option<BoundSql>,
66}
67
68/// List of distinct keywords that can be used in select statement
69#[derive(Debug, Clone, PartialEq)]
70pub enum SelectDistinct {
71    All,
72    Distinct,
73    DistinctRow,
74    DistinctOn(Vec<ColumnRef>),
75}
76
77/// Window type in [`SelectExpr`]
78#[derive(Debug, Clone, PartialEq)]
79pub enum WindowSelectType {
80    /// Name in [`SelectStatement`]
81    Name(DynIden),
82    /// Inline query in [`SelectExpr`]
83    Query(WindowStatement),
84}
85
86/// Select expression used in select statement
87#[derive(Debug, Clone, PartialEq)]
88pub struct SelectExpr {
89    pub expr: Expr,
90    pub alias: Option<DynIden>,
91    pub window: Option<WindowSelectType>,
92}
93
94/// The table type of target table of SELECT INTO clause
95#[derive(Debug, Clone, PartialEq)]
96pub enum SelectIntoTableModifier {
97    Temporary,
98    Unlogged,
99}
100
101/// The INTO clause in SELECT statement
102#[derive(Debug, Clone, PartialEq)]
103pub struct SelectInto {
104    pub target_table: DynIden,
105    pub target_table_modifier: Option<SelectIntoTableModifier>,
106}
107
108/// Join expression used in select statement
109#[derive(Debug, Clone, PartialEq)]
110pub struct JoinExpr {
111    pub join: JoinType,
112    pub table: Box<TableRef>,
113    pub on: Option<JoinOn>,
114    pub lateral: bool,
115}
116
117/// List of lock types that can be used in select statement
118#[derive(Debug, Clone, Copy, PartialEq, Eq)]
119pub enum LockType {
120    /// Exclusive lock
121    Update,
122    /// PostgreSQL only; MySQL refuses to render it
123    NoKeyUpdate,
124    /// Shared lock
125    Share,
126    /// PostgreSQL only; MySQL refuses to render it
127    KeyShare,
128}
129
130/// List of lock behavior can be used in select statement
131#[derive(Debug, Clone, Copy, PartialEq, Eq)]
132pub enum LockBehavior {
133    Nowait,
134    SkipLocked,
135}
136
137#[derive(Debug, Clone, PartialEq)]
138pub struct LockClause {
139    pub(crate) r#type: LockType,
140    pub(crate) tables: Vec<TableRef>,
141    pub(crate) behavior: Option<LockBehavior>,
142}
143
144/// List of union types that can be used in union clause
145#[derive(Debug, Clone, Copy, PartialEq, Eq)]
146pub enum UnionType {
147    Intersect,
148    Distinct,
149    Except,
150    All,
151}
152
153impl<T> From<T> for SelectExpr
154where
155    T: Into<Expr>,
156{
157    fn from(expr: T) -> Self {
158        SelectExpr {
159            expr: expr.into(),
160            alias: None,
161            window: None,
162        }
163    }
164}
165
166impl Display for SelectIntoTableModifier {
167    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
168        match self {
169            SelectIntoTableModifier::Temporary => f.write_str("TEMPORARY"),
170            SelectIntoTableModifier::Unlogged => f.write_str("UNLOGGED"),
171        }
172    }
173}
174
175impl SelectInto {
176    /// Set the target table of SELECT INTO clause
177    pub fn table<T>(t: T) -> Self
178    where
179        T: IntoIden,
180    {
181        Self {
182            target_table: t.into_iden(),
183            target_table_modifier: None,
184        }
185    }
186
187    /// Set a modifier for the target table like Temporary or unlogged
188    pub fn modifier(mut self, modifier: SelectIntoTableModifier) -> Self {
189        self.target_table_modifier = Some(modifier);
190        self
191    }
192}
193
194impl From<WindowStatement> for WindowSelectType {
195    fn from(stmt: WindowStatement) -> Self {
196        Self::Query(stmt)
197    }
198}
199
200impl<T: IntoIden> From<T> for WindowSelectType {
201    fn from(iden: T) -> Self {
202        Self::Name(iden.into_iden())
203    }
204}
205
206/// Extension methods for building a [`SelectExpr`] from an expression.
207///
208/// This makes it ergonomic to attach select-specific modifiers (like `AS` and `OVER`) and pass the
209/// result into [`SelectStatement::expr`].
210///
211/// # Examples
212///
213/// ```
214/// use sql_builder::*;
215///
216/// let query = Query::select()
217///     .from("character")
218///     .expr(
219///         Expr::col("character")
220///             .max()
221///             .over(WindowStatement::partition_by("font_size"))
222///             .alias("C"),
223///     )
224///     .to_owned();
225///
226/// assert_eq!(
227///     query.to_string(MysqlQueryBuilder).unwrap(),
228///     r#"SELECT MAX(`character`) OVER ( PARTITION BY `font_size` ) AS `C` FROM `character`"#
229/// );
230/// ```
231pub trait SelectExprTrait: Sized {
232    fn alias<A>(self, alias: A) -> SelectExpr
233    where
234        A: IntoIden;
235
236    fn over(self, over_expr: impl Into<WindowSelectType>) -> SelectExpr;
237}
238
239impl SelectExprTrait for SelectExpr {
240    fn alias<A>(mut self, alias: A) -> SelectExpr
241    where
242        A: IntoIden,
243    {
244        self.alias = Some(alias.into_iden());
245        self
246    }
247
248    fn over(mut self, over_expr: impl Into<WindowSelectType>) -> SelectExpr {
249        self.window = Some(over_expr.into());
250        self
251    }
252}
253
254impl<T> SelectExprTrait for T
255where
256    T: Into<Expr>,
257{
258    fn alias<A>(self, alias: A) -> SelectExpr
259    where
260        A: IntoIden,
261    {
262        SelectExpr::from(self).alias(alias)
263    }
264
265    fn over(self, over_expr: impl Into<WindowSelectType>) -> SelectExpr {
266        SelectExpr::from(self).over(over_expr)
267    }
268}