sql_builder/query/window.rs
1use std::borrow::Cow;
2
3use crate::{Expr, IntoColumnRef, OrderExpr, ordered_statement};
4
5pub trait OverStatement {
6 #[doc(hidden)]
7 // Implementation for the trait.
8 fn add_partition_by(&mut self, partition: Expr) -> &mut Self;
9
10 /// Partition by column.
11 fn partition_by<T>(&mut self, col: T) -> &mut Self
12 where
13 T: IntoColumnRef,
14 {
15 self.add_partition_by(Expr::Column(col.into_column_ref()))
16 }
17
18 /// Partition by custom string.
19 fn partition_by_customs<I, T>(&mut self, cols: I) -> &mut Self
20 where
21 T: Into<Cow<'static, str>>,
22 I: IntoIterator<Item = T>,
23 {
24 cols.into_iter().for_each(|c| {
25 self.add_partition_by(Expr::Custom(c.into()));
26 });
27 self
28 }
29
30 /// Partition by vector of columns.
31 fn partition_by_columns<I, T>(&mut self, cols: I) -> &mut Self
32 where
33 T: IntoColumnRef,
34 I: IntoIterator<Item = T>,
35 {
36 cols.into_iter().for_each(|c| {
37 self.add_partition_by(Expr::Column(c.into_column_ref()));
38 });
39 self
40 }
41}
42
43/// frame_start or frame_end clause
44#[derive(Debug, Clone, PartialEq)]
45pub enum Frame {
46 UnboundedPreceding,
47 Preceding(u32),
48 CurrentRow,
49 Following(u32),
50 UnboundedFollowing,
51}
52
53/// Frame type
54#[derive(Debug, Clone, PartialEq)]
55pub enum FrameType {
56 Range,
57 Rows,
58}
59
60/// Frame clause
61#[derive(Debug, Clone, PartialEq)]
62pub struct FrameClause {
63 pub(crate) r#type: FrameType,
64 pub(crate) start: Frame,
65 pub(crate) end: Option<Frame>,
66}
67
68/// Window expression
69///
70/// # References:
71///
72/// 1. <https://dev.mysql.com/doc/refman/8.0/en/window-function-descriptions.html>
73/// 2. <https://www.sqlite.org/windowfunctions.html>
74/// 3. <https://www.postgresql.org/docs/current/tutorial-window.html>
75#[derive(Default, Debug, Clone, PartialEq)]
76pub struct WindowStatement {
77 pub(crate) partition_by: Vec<Expr>,
78 pub(crate) order_by: Vec<OrderExpr>,
79 pub(crate) frame: Option<FrameClause>,
80}
81
82impl WindowStatement {
83 /// Construct a new [`WindowStatement`]
84 pub fn new() -> Self {
85 Self::default()
86 }
87
88 pub fn take(&mut self) -> Self {
89 Self {
90 partition_by: std::mem::take(&mut self.partition_by),
91 order_by: std::mem::take(&mut self.order_by),
92 frame: self.frame.take(),
93 }
94 }
95
96 /// Construct a new [`WindowStatement`] with PARTITION BY column
97 pub fn partition_by<T>(col: T) -> Self
98 where
99 T: IntoColumnRef,
100 {
101 let mut window = Self::new();
102 window.add_partition_by(Expr::Column(col.into_column_ref()));
103 window
104 }
105
106 /// Construct a new [`WindowStatement`] with PARTITION BY custom
107 pub fn partition_by_custom<T>(col: T) -> Self
108 where
109 T: Into<Cow<'static, str>>,
110 {
111 let mut window = Self::new();
112 window.add_partition_by(Expr::cust(col));
113 window
114 }
115
116 /// frame clause for frame_start
117 /// # Examples:
118 ///
119 /// ```
120 /// use sql_builder::*;
121 ///
122 /// let query = Query::select()
123 /// .from("character")
124 /// .expr_window_as(
125 /// Expr::col("character"),
126 /// WindowStatement::partition_by("font_size")
127 /// .frame_start(FrameType::Rows, Frame::UnboundedPreceding)
128 /// .take(),
129 /// "C")
130 /// .to_owned();
131 ///
132 /// assert_eq!(
133 /// query.to_string(MysqlQueryBuilder).unwrap(),
134 /// r#"SELECT `character` OVER ( PARTITION BY `font_size` ROWS UNBOUNDED PRECEDING ) AS `C` FROM `character`"#
135 /// );
136 /// assert_eq!(
137 /// query.to_string(PostgresQueryBuilder).unwrap(),
138 /// r#"SELECT "character" OVER ( PARTITION BY "font_size" ROWS UNBOUNDED PRECEDING ) AS "C" FROM "character""#
139 /// );
140 /// assert_eq!(
141 /// query.to_string(SqliteQueryBuilder).unwrap(),
142 /// r#"SELECT "character" OVER ( PARTITION BY "font_size" ROWS UNBOUNDED PRECEDING ) AS "C" FROM "character""#
143 /// );
144 /// ```
145 pub fn frame_start(&mut self, r#type: FrameType, start: Frame) -> &mut Self {
146 self.frame(r#type, start, None)
147 }
148
149 /// frame clause for BETWEEN frame_start AND frame_end
150 ///
151 /// # Examples:
152 ///
153 /// ```
154 /// use sql_builder::*;
155 ///
156 /// let query = Query::select()
157 /// .from("character")
158 /// .expr_window_as(
159 /// Expr::col("character"),
160 /// WindowStatement::partition_by("font_size")
161 /// .frame_between(FrameType::Rows, Frame::UnboundedPreceding, Frame::UnboundedFollowing)
162 /// .take(),
163 /// "C")
164 /// .to_owned();
165 ///
166 /// assert_eq!(
167 /// query.to_string(MysqlQueryBuilder).unwrap(),
168 /// r#"SELECT `character` OVER ( PARTITION BY `font_size` ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING ) AS `C` FROM `character`"#
169 /// );
170 /// assert_eq!(
171 /// query.to_string(PostgresQueryBuilder).unwrap(),
172 /// r#"SELECT "character" OVER ( PARTITION BY "font_size" ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING ) AS "C" FROM "character""#
173 /// );
174 /// assert_eq!(
175 /// query.to_string(SqliteQueryBuilder).unwrap(),
176 /// r#"SELECT "character" OVER ( PARTITION BY "font_size" ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING ) AS "C" FROM "character""#
177 /// );
178 /// ```
179 pub fn frame_between(&mut self, r#type: FrameType, start: Frame, end: Frame) -> &mut Self {
180 self.frame(r#type, start, Some(end))
181 }
182
183 /// frame clause
184 pub fn frame(&mut self, r#type: FrameType, start: Frame, end: Option<Frame>) -> &mut Self {
185 let frame_clause = FrameClause { r#type, start, end };
186 self.frame = Some(frame_clause);
187 self
188 }
189}
190
191impl OverStatement for WindowStatement {
192 fn add_partition_by(&mut self, partition: Expr) -> &mut Self {
193 self.partition_by.push(partition);
194 self
195 }
196}
197
198ordered_statement!(WindowStatement, order_by);