Skip to main content

vantage_sql/primitives/
identifier.rs

1use vantage_expressions::{Expression, Expressive};
2
3/// SQL identifier with optional qualification and alias.
4///
5/// Quoting is determined by the `Expressive<T>` impl — each backend
6/// renders with its own quote style (`"` for PostgreSQL/SQLite,
7/// `` ` `` for MySQL). This means `Identifier` is quote-agnostic;
8/// the quoting happens only when `.expr()` is called for a specific type.
9///
10/// Embedded quote characters ARE escaped (doubled) when rendering, so an
11/// identifier built from a runtime value cannot break out of its quotes.
12/// It is still a NAME, not a value: prefer binding values as parameters
13/// (`expr("… = {}", [v])`) and reserve identifiers for schema elements.
14///
15/// # Examples
16///
17/// ```ignore
18/// use vantage_sql::primitives::identifier::ident;
19///
20/// // Simple column — quoting depends on which Expressive<T> is used
21/// let expr = mysql_expr!("SELECT {} FROM {}", (ident("name")), (ident("product")));
22///
23/// // Qualified (table.column)
24/// let expr = mysql_expr!("SELECT {}", (ident("name").dot_of("u")));
25///
26/// // With alias
27/// let expr = mysql_expr!("SELECT {}", (ident("name").with_alias("n")));
28/// ```
29#[derive(Debug, Clone)]
30pub struct Identifier {
31    parts: Vec<String>,
32    alias: Option<String>,
33}
34
35impl Identifier {
36    /// Single identifier: `name`.
37    pub fn new(name: impl Into<String>) -> Self {
38        Self {
39            parts: vec![name.into()],
40            alias: None,
41        }
42    }
43
44    /// Prepends a qualifier: `ident("name").dot_of("u")` → `u.name`.
45    /// Chaining adds further left: `ident("col").dot_of("t").dot_of("s")` → `s.t.col`.
46    pub fn dot_of(mut self, prefix: impl Into<String>) -> Self {
47        self.parts.insert(0, prefix.into());
48        self
49    }
50
51    /// Adds an AS alias.
52    pub fn with_alias(mut self, alias: impl Into<String>) -> Self {
53        self.alias = Some(alias.into());
54        self
55    }
56
57    /// Returns the identifier name (parts joined with dots, no quotes).
58    pub fn name(&self) -> String {
59        self.parts.join(".")
60    }
61
62    /// Returns the alias, if any.
63    pub fn alias(&self) -> Option<&str> {
64        self.alias.as_deref()
65    }
66
67    /// Render with a given quote character. Used by backend `Expressive` impls.
68    ///
69    /// Every quote character inside a part is DOUBLED, the escape all three
70    /// supported dialects use (`"a""b"`, `` `a``b` ``). Identifiers were
71    /// historically code-defined, so an unescaped `format!` was safe by
72    /// construction; that stopped being true once vista scripts could read
73    /// runtime values (an observation's `args`), where `ident(args.col)` on
74    /// a value containing a quote would otherwise terminate the identifier
75    /// and let the rest of the value be parsed as SQL.
76    fn render_with(&self, q: char) -> String {
77        let quote = |p: &str| format!("{q}{}{q}", p.replace(q, &format!("{q}{q}")));
78        let base = self
79            .parts
80            .iter()
81            .map(|p| quote(p))
82            .collect::<Vec<_>>()
83            .join(".");
84        match &self.alias {
85            Some(alias) => format!("{base} AS {}", quote(alias)),
86            None => base,
87        }
88    }
89}
90
91/// Shorthand for `Identifier::new(name)`.
92pub fn ident(name: impl Into<String>) -> Identifier {
93    Identifier::new(name)
94}
95
96// Each backend impl owns its quoting style.
97
98#[cfg(feature = "sqlite")]
99impl Expressive<crate::sqlite::types::AnySqliteType> for Identifier {
100    fn expr(&self) -> Expression<crate::sqlite::types::AnySqliteType> {
101        Expression::new(self.render_with('"'), vec![])
102    }
103}
104
105#[cfg(feature = "sqlite")]
106impl From<Identifier> for Expression<crate::sqlite::types::AnySqliteType> {
107    fn from(id: Identifier) -> Self {
108        id.expr()
109    }
110}
111
112#[cfg(feature = "postgres")]
113impl Expressive<crate::postgres::types::AnyPostgresType> for Identifier {
114    fn expr(&self) -> Expression<crate::postgres::types::AnyPostgresType> {
115        Expression::new(self.render_with('"'), vec![])
116    }
117}
118
119#[cfg(feature = "postgres")]
120impl From<Identifier> for Expression<crate::postgres::types::AnyPostgresType> {
121    fn from(id: Identifier) -> Self {
122        id.expr()
123    }
124}
125
126#[cfg(feature = "mysql")]
127impl Expressive<crate::mysql::types::AnyMysqlType> for Identifier {
128    fn expr(&self) -> Expression<crate::mysql::types::AnyMysqlType> {
129        Expression::new(self.render_with('`'), vec![])
130    }
131}
132
133#[cfg(feature = "mysql")]
134impl From<Identifier> for Expression<crate::mysql::types::AnyMysqlType> {
135    fn from(id: Identifier) -> Self {
136        id.expr()
137    }
138}
139
140#[cfg(test)]
141mod tests {
142    use super::*;
143
144    #[test]
145    fn parts_and_alias_quote_normally() {
146        let id = ident("name").dot_of("u").with_alias("n");
147        assert_eq!(id.render_with('"'), r#""u"."name" AS "n""#);
148    }
149
150    #[test]
151    fn embedded_quotes_are_doubled_not_escaped_out_of() {
152        // The break-out attempt: a value that would close the identifier and
153        // continue as SQL. Doubling keeps it one (absurd but inert) name.
154        let id = ident(r#"x" ; DROP TABLE users --"#);
155        assert_eq!(id.render_with('"'), r#""x"" ; DROP TABLE users --""#);
156        let id = ident("a`b");
157        assert_eq!(id.render_with('`'), "`a``b`");
158    }
159
160    #[test]
161    fn alias_is_escaped_too() {
162        let id = ident("col").with_alias(r#"a"b"#);
163        assert_eq!(id.render_with('"'), r#""col" AS "a""b""#);
164    }
165}