utopia_query/quote.rs
1//! Identifier quoting: `` `users`.`id` `` for MySQL, `"users"."id"` for PostgreSQL.
2
3use crate::error::{Error, Result};
4
5fn reject_control(identifier: &str) -> Result<()> {
6 if identifier.bytes().any(|b| b < 0x20 || b == 0x7f) {
7 return Err(Error::Validation("Identifier contains control character".into()));
8 }
9 Ok(())
10}
11
12fn push_wrapped(out: &mut String, segment: &str, wrap: char) {
13 out.push(wrap);
14 for c in segment.chars() {
15 if c == wrap {
16 out.push(wrap);
17 }
18 out.push(c);
19 }
20 out.push(wrap);
21}
22
23/// Quotes a possibly qualified identifier with `wrap`: each dot-separated
24/// segment is wrapped (the wrap character doubled inside), a final `*`
25/// stays bare, and `*` alone is returned as is. Control characters are
26/// refused.
27///
28/// PHP: `QuotesIdentifiers::quote()` (with `$wrapChar`).
29///
30/// ```
31/// use utopia_query::quote;
32///
33/// assert_eq!(quote("schema.users", '`')?, "`schema`.`users`");
34/// assert_eq!(quote("users.*", '"')?, "\"users\".*");
35/// # Ok::<(), utopia_query::Error>(())
36/// ```
37///
38/// ```php
39/// use Utopia\Query\Builder\MySQL;
40///
41/// echo (new MySQL())->from('schema.users')->build()->query, "\n"; // SELECT * FROM `schema`.`users`
42/// ```
43pub fn quote(identifier: &str, wrap: char) -> Result<String> {
44 if identifier == "*" {
45 return Ok("*".into());
46 }
47 reject_control(identifier)?;
48 let mut out = String::with_capacity(identifier.len() + 4);
49 if !identifier.contains('.') {
50 push_wrapped(&mut out, identifier, wrap);
51 return Ok(out);
52 }
53 let count = identifier.split('.').count();
54 for (index, segment) in identifier.split('.').enumerate() {
55 if index > 0 {
56 out.push('.');
57 }
58 if segment == "*" && index == count - 1 {
59 out.push('*');
60 } else {
61 push_wrapped(&mut out, segment, wrap);
62 }
63 }
64 Ok(out)
65}
66
67/// Quotes one identifier without treating dots as qualifiers (a column named
68/// `meta.key`, as ClickHouse nested columns are).
69///
70/// PHP: `QuotesIdentifiers::quoteLiteral()`.
71///
72/// ```
73/// use utopia_query::quote_literal;
74///
75/// assert_eq!(quote_literal("meta.key", '`')?, "`meta.key`");
76/// # Ok::<(), utopia_query::Error>(())
77/// ```
78///
79/// ```php
80/// use Utopia\Query\Schema\ClickHouse;
81///
82/// echo (new ClickHouse())->table('t')->string('meta.key')->create()->query, "\n";
83/// ```
84pub fn quote_literal(identifier: &str, wrap: char) -> Result<String> {
85 if identifier == "*" {
86 return Ok("*".into());
87 }
88 reject_control(identifier)?;
89 let mut out = String::with_capacity(identifier.len() + 2);
90 push_wrapped(&mut out, identifier, wrap);
91 Ok(out)
92}