vantage_sql/primitives/
group_concat.rs1use std::fmt::{Debug, Display};
2use vantage_expressions::{Expression, Expressive, ExpressiveEnum};
3
4#[derive(Debug, Clone)]
8pub struct GroupConcat<T: Debug + Display + Clone> {
9 expr: Expression<T>,
10 separator: String,
11 distinct: bool,
12}
13
14impl<T: Debug + Display + Clone> GroupConcat<T> {
15 pub fn new(expr: impl Expressive<T>) -> Self {
16 Self {
17 expr: expr.expr(),
18 separator: ",".to_string(),
19 distinct: false,
20 }
21 }
22
23 pub fn separator(mut self, sep: impl Into<String>) -> Self {
24 self.separator = sep.into();
25 self
26 }
27
28 pub fn distinct(mut self) -> Self {
29 self.distinct = true;
30 self
31 }
32}
33
34#[cfg(feature = "sqlite")]
35impl Expressive<crate::sqlite::types::AnySqliteType>
36 for GroupConcat<crate::sqlite::types::AnySqliteType>
37{
38 fn expr(&self) -> Expression<crate::sqlite::types::AnySqliteType> {
39 let distinct_kw = if self.distinct { "DISTINCT " } else { "" };
40 let template = format!("GROUP_CONCAT({}{{}}, '{}')", distinct_kw, self.separator);
41 Expression::new(&template, vec![ExpressiveEnum::Nested(self.expr.clone())])
42 }
43}
44
45#[cfg(feature = "postgres")]
46impl Expressive<crate::postgres::types::AnyPostgresType>
47 for GroupConcat<crate::postgres::types::AnyPostgresType>
48{
49 fn expr(&self) -> Expression<crate::postgres::types::AnyPostgresType> {
50 let distinct_kw = if self.distinct { "DISTINCT " } else { "" };
51 let template = format!("STRING_AGG({}{{}}, '{}')", distinct_kw, self.separator);
52 Expression::new(&template, vec![ExpressiveEnum::Nested(self.expr.clone())])
53 }
54}
55
56#[cfg(feature = "mysql")]
57impl Expressive<crate::mysql::types::AnyMysqlType>
58 for GroupConcat<crate::mysql::types::AnyMysqlType>
59{
60 fn expr(&self) -> Expression<crate::mysql::types::AnyMysqlType> {
61 let distinct_kw = if self.distinct { "DISTINCT " } else { "" };
62 let template = format!(
63 "GROUP_CONCAT({}{{}} SEPARATOR '{}')",
64 distinct_kw, self.separator
65 );
66 Expression::new(&template, vec![ExpressiveEnum::Nested(self.expr.clone())])
67 }
68}