Skip to main content

no_mistakes_postgres_sql/
sql_names.rs

1pub fn parts(raw: &str) -> Vec<String> {
2    let mut parts = Vec::new();
3    let mut part = String::new();
4    let mut quoted = false;
5    let mut chars = raw.trim().chars().peekable();
6    while let Some(character) = chars.next() {
7        if character == '"' {
8            part.push(character);
9            if quoted && chars.peek() == Some(&'"') {
10                part.push(chars.next().unwrap());
11            } else {
12                quoted = !quoted;
13            }
14        } else if character == '.' && !quoted {
15            parts.push(part.trim().to_string());
16            part.clear();
17        } else {
18            part.push(character);
19        }
20    }
21    parts.push(part.trim().to_string());
22    parts
23}
24
25pub fn normalize_identifier(identifier: &str) -> String {
26    let part = parts(identifier).pop().unwrap_or_default();
27    if part.starts_with('"') && part.ends_with('"') && part.len() >= 2 {
28        part[1..part.len() - 1].replace("\"\"", "\"")
29    } else {
30        part.to_ascii_lowercase()
31    }
32}
33
34/// The parts of a SQL table name with their quoting removed: `other."Users"` is
35/// `["other", "Users"]`, and `"audit.log"` is one part.
36pub fn decoded_parts(name: &str) -> Vec<String> {
37    parts(name)
38        .iter()
39        .map(|part| normalize_identifier(part))
40        .collect()
41}
42
43pub fn normalize_table_name(table: &str) -> String {
44    parts(table)
45        .iter()
46        .map(|part| {
47            let value = normalize_identifier(part);
48            if value.contains(['.', '"']) {
49                format!("\"{}\"", value.replace('"', "\"\""))
50            } else {
51                value
52            }
53        })
54        .collect::<Vec<_>>()
55        .join(".")
56}
57
58/// The column name when an index key expression is a bare (possibly quoted) identifier.
59pub fn plain_column(expression: &str) -> Option<String> {
60    let text = expression.trim();
61    let bare = text
62        .chars()
63        .next()
64        .is_some_and(|first| first.is_ascii_alphabetic() || first == '_')
65        && text
66            .chars()
67            .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$');
68    let quoted = text.len() >= 2
69        && text.starts_with('"')
70        && text.ends_with('"')
71        && !text[1..text.len() - 1].replace("\"\"", "").contains('"');
72    (bare || quoted).then(|| normalize_identifier(text))
73}