vantage_sql/primitives/
identifier.rs1use vantage_expressions::{Expression, Expressive};
2
3#[derive(Debug, Clone)]
29pub struct Identifier {
30 parts: Vec<String>,
31 alias: Option<String>,
32}
33
34impl Identifier {
35 pub fn new(name: impl Into<String>) -> Self {
37 Self {
38 parts: vec![name.into()],
39 alias: None,
40 }
41 }
42
43 pub fn dot_of(mut self, prefix: impl Into<String>) -> Self {
46 self.parts.insert(0, prefix.into());
47 self
48 }
49
50 pub fn with_alias(mut self, alias: impl Into<String>) -> Self {
52 self.alias = Some(alias.into());
53 self
54 }
55
56 fn render_with(&self, q: char) -> String {
58 let base = self
59 .parts
60 .iter()
61 .map(|p| format!("{q}{p}{q}"))
62 .collect::<Vec<_>>()
63 .join(".");
64 match &self.alias {
65 Some(alias) => format!("{base} AS {q}{alias}{q}"),
66 None => base,
67 }
68 }
69}
70
71pub fn ident(name: impl Into<String>) -> Identifier {
73 Identifier::new(name)
74}
75
76#[cfg(feature = "sqlite")]
79impl Expressive<crate::sqlite::types::AnySqliteType> for Identifier {
80 fn expr(&self) -> Expression<crate::sqlite::types::AnySqliteType> {
81 Expression::new(self.render_with('"'), vec![])
82 }
83}
84
85#[cfg(feature = "sqlite")]
86impl From<Identifier> for Expression<crate::sqlite::types::AnySqliteType> {
87 fn from(id: Identifier) -> Self {
88 id.expr()
89 }
90}
91
92#[cfg(feature = "postgres")]
93impl Expressive<crate::postgres::types::AnyPostgresType> for Identifier {
94 fn expr(&self) -> Expression<crate::postgres::types::AnyPostgresType> {
95 Expression::new(self.render_with('"'), vec![])
96 }
97}
98
99#[cfg(feature = "postgres")]
100impl From<Identifier> for Expression<crate::postgres::types::AnyPostgresType> {
101 fn from(id: Identifier) -> Self {
102 id.expr()
103 }
104}
105
106#[cfg(feature = "mysql")]
107impl Expressive<crate::mysql::types::AnyMysqlType> for Identifier {
108 fn expr(&self) -> Expression<crate::mysql::types::AnyMysqlType> {
109 Expression::new(self.render_with('`'), vec![])
110 }
111}
112
113#[cfg(feature = "mysql")]
114impl From<Identifier> for Expression<crate::mysql::types::AnyMysqlType> {
115 fn from(id: Identifier) -> Self {
116 id.expr()
117 }
118}