sqlint/ast/function/row_number.rs
1use crate::ast::{Column, IntoOrderDefinition, Over};
2
3#[derive(Debug, Default, Clone, PartialEq)]
4/// A window function that assigns a sequential integer
5/// number to each row in the query’s result set.
6pub struct RowNumber<'a> {
7 pub(crate) over: Over<'a>,
8}
9
10impl<'a> RowNumber<'a> {
11 /// Define the order of the row number. Is the row order if not set.
12 pub fn order_by<T>(mut self, value: T) -> Self
13 where
14 T: IntoOrderDefinition<'a>,
15 {
16 self.over.ordering = self.over.ordering.append(value.into_order_definition());
17 self
18 }
19
20 /// Define the partitioning of the row number
21 pub fn partition_by<T>(mut self, partition: T) -> Self
22 where
23 T: Into<Column<'a>>,
24 {
25 self.over.partitioning.push(partition.into());
26 self
27 }
28}
29
30/// A number from 1 to n in specified order
31///
32/// ```rust
33/// # use sqlint::{ast::*, visitor::{Visitor, Sqlite}};
34/// # fn main() -> Result<(), sqlint::error::Error> {
35/// let fun = Function::from(row_number().order_by("created_at").partition_by("name"));
36///
37/// let query = Select::from_table("users")
38/// .column("id")
39/// .value(fun.alias("num"));
40///
41/// let (sql, _) = Sqlite::build(query)?;
42///
43/// assert_eq!(
44/// "SELECT `id`, ROW_NUMBER() OVER(PARTITION BY `name` ORDER BY `created_at`) AS `num` FROM `users`",
45/// sql
46/// );
47/// # Ok(())
48/// # }
49/// ```
50pub fn row_number<'a>() -> RowNumber<'a> {
51 RowNumber::default()
52}