Skip to main content

sql_builder/backend/
mod.rs

1//! Translating the SQL AST into engine-specific SQL statements.
2
3use crate::*;
4use std::borrow::Cow;
5
6mod mysql;
7
8mod postgres;
9
10mod sqlite;
11
12pub use mysql::*;
13
14pub use postgres::*;
15
16pub use sqlite::*;
17
18mod bound_sql;
19mod dialect;
20mod json_path;
21mod query_builder;
22mod table_ref_builder;
23
24pub use self::dialect::{
25    ArrayOperator, BoundPart, BoundPiece, BoundSql, JsonContainment, JsonExistence, MATCH_NOTHING,
26    SqlDialect,
27};
28pub use self::json_path::{JsonPathStep, is_plain_identifier, json_path_text, parse_json_path};
29pub use self::query_builder::*;
30pub use self::table_ref_builder::*;
31
32pub trait QuotedBuilder {
33    /// The type of quote the builder uses.
34    fn quote(&self) -> Quote;
35
36    /// To prepare iden and write to SQL.
37    fn prepare_iden(&self, iden: &DynIden, sql: &mut impl SqlWriter) {
38        let quote = self.quote();
39        match &iden.0 {
40            Cow::Borrowed(name) => {
41                sql.write_char(quote.left()).unwrap();
42                sql.write_str(name).unwrap();
43                sql.write_char(quote.right()).unwrap();
44            }
45            Cow::Owned(name) => write_identifier(sql, quote, name),
46        }
47    }
48}
49
50/// Writes `name` between `quote`s, doubling every closing quote inside it.
51pub(crate) fn write_identifier(out: &mut impl Write, quote: Quote, name: &str) {
52    out.write_char(quote.left()).unwrap();
53    for ch in name.chars() {
54        if ch == quote.right() {
55            out.write_char(ch).unwrap();
56        }
57        out.write_char(ch).unwrap();
58    }
59    out.write_char(quote.right()).unwrap();
60}
61
62pub trait EscapeBuilder {
63    /// Return if string literal needs to be escaped
64    fn needs_escape(&self, s: &str) -> bool {
65        s.chars().any(|c| {
66            matches!(
67                c,
68                '\r' | '\n' | '\x1a' | '\x09' | '\x08' | '\0' | '\'' | '"' | '\\'
69            )
70        })
71    }
72
73    /// Escape a SQL string literal
74    fn escape_string(&self, string: &str) -> String {
75        let mut escaped = String::with_capacity(string.len() + 8);
76        self.write_escaped(&mut escaped, string);
77        escaped
78    }
79
80    fn write_escaped(&self, buffer: &mut impl Write, string: &str) {
81        for c in string.chars() {
82            match c {
83                '\\' => buffer.write_str("\\\\"),
84                '"' => buffer.write_str("\\\""),
85                '\'' => buffer.write_str("\\'"),
86                '\0' => buffer.write_str("\\0"),
87                '\x08' => buffer.write_str("\\b"),
88                '\x09' => buffer.write_str("\\t"),
89                '\x1a' => buffer.write_str("\\z"),
90                '\n' => buffer.write_str("\\n"),
91                '\r' => buffer.write_str("\\r"),
92                _ => buffer.write_char(c),
93            }
94            .unwrap()
95        }
96    }
97}
98
99pub trait PrecedenceDecider {
100    // This method decides which precedence relations should lead to dropped parentheses.
101    // There will be more fine grained precedence relations than the ones represented here,
102    // but dropping parentheses due to these relations can be confusing for readers.
103    fn inner_expr_well_known_greater_precedence(&self, inner: &Expr, outer_oper: &Oper) -> bool {
104        common_inner_expr_well_known_greater_precedence(inner, outer_oper)
105    }
106}
107
108pub trait OperLeftAssocDecider {
109    // This method decides if the left associativity of an operator should lead to dropped parentheses.
110    // Not all known left associative operators are necessarily included here,
111    // as dropping them may in some cases be confusing to readers.
112    fn well_known_left_associative(&self, op: &BinOper) -> bool {
113        common_well_known_left_associative(op)
114    }
115}
116
117#[derive(Debug, PartialEq)]
118pub enum Oper {
119    UnOper(UnOper),
120    BinOper(BinOper),
121}
122
123impl From<UnOper> for Oper {
124    fn from(value: UnOper) -> Self {
125        Oper::UnOper(value)
126    }
127}
128
129impl From<BinOper> for Oper {
130    fn from(value: BinOper) -> Self {
131        Oper::BinOper(value)
132    }
133}
134
135impl Oper {
136    pub(crate) fn is_logical(&self) -> bool {
137        matches!(
138            self,
139            Oper::UnOper(UnOper::Not) | Oper::BinOper(BinOper::And) | Oper::BinOper(BinOper::Or)
140        )
141    }
142
143    pub(crate) fn is_between(&self) -> bool {
144        matches!(
145            self,
146            Oper::BinOper(BinOper::Between) | Oper::BinOper(BinOper::NotBetween)
147        )
148    }
149
150    pub(crate) fn is_like(&self) -> bool {
151        matches!(
152            self,
153            Oper::BinOper(BinOper::Like) | Oper::BinOper(BinOper::NotLike)
154        )
155    }
156
157    pub(crate) fn is_in(&self) -> bool {
158        matches!(
159            self,
160            Oper::BinOper(BinOper::In) | Oper::BinOper(BinOper::NotIn)
161        )
162    }
163
164    pub(crate) fn is_is(&self) -> bool {
165        matches!(
166            self,
167            Oper::BinOper(BinOper::Is) | Oper::BinOper(BinOper::IsNot)
168        )
169    }
170
171    pub(crate) fn is_shift(&self) -> bool {
172        matches!(
173            self,
174            Oper::BinOper(BinOper::LShift) | Oper::BinOper(BinOper::RShift)
175        )
176    }
177
178    pub(crate) fn is_arithmetic(&self) -> bool {
179        match self {
180            Oper::BinOper(b) => {
181                matches!(
182                    b,
183                    BinOper::Mul | BinOper::Div | BinOper::Mod | BinOper::Add | BinOper::Sub
184                )
185            }
186            _ => false,
187        }
188    }
189
190    pub(crate) fn is_comparison(&self) -> bool {
191        match self {
192            Oper::BinOper(b) => {
193                matches!(
194                    b,
195                    BinOper::SmallerThan
196                        | BinOper::SmallerThanOrEqual
197                        | BinOper::Equal
198                        | BinOper::GreaterThanOrEqual
199                        | BinOper::GreaterThan
200                        | BinOper::NotEqual
201                )
202            }
203            _ => false,
204        }
205    }
206}