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                // doubled, not `\'`: MySQL reads `''` the same with
86                // NO_BACKSLASH_ESCAPES, where `\'` would end the literal
87                '\'' => buffer.write_str("''"),
88                '\0' => buffer.write_str("\\0"),
89                '\x08' => buffer.write_str("\\b"),
90                '\x09' => buffer.write_str("\\t"),
91                '\x1a' => buffer.write_str("\\z"),
92                '\n' => buffer.write_str("\\n"),
93                '\r' => buffer.write_str("\\r"),
94                _ => buffer.write_char(c),
95            }
96            .unwrap()
97        }
98    }
99}
100
101pub trait PrecedenceDecider {
102    // This method decides which precedence relations should lead to dropped parentheses.
103    // There will be more fine grained precedence relations than the ones represented here,
104    // but dropping parentheses due to these relations can be confusing for readers.
105    fn inner_expr_well_known_greater_precedence(&self, inner: &Expr, outer_oper: &Oper) -> bool {
106        common_inner_expr_well_known_greater_precedence(inner, outer_oper)
107    }
108}
109
110pub trait OperLeftAssocDecider {
111    // This method decides if the left associativity of an operator should lead to dropped parentheses.
112    // Not all known left associative operators are necessarily included here,
113    // as dropping them may in some cases be confusing to readers.
114    fn well_known_left_associative(&self, op: &BinOper) -> bool {
115        common_well_known_left_associative(op)
116    }
117}
118
119#[derive(Debug, PartialEq)]
120pub enum Oper {
121    UnOper(UnOper),
122    BinOper(BinOper),
123}
124
125impl From<UnOper> for Oper {
126    fn from(value: UnOper) -> Self {
127        Oper::UnOper(value)
128    }
129}
130
131impl From<BinOper> for Oper {
132    fn from(value: BinOper) -> Self {
133        Oper::BinOper(value)
134    }
135}
136
137impl Oper {
138    pub(crate) fn is_logical(&self) -> bool {
139        matches!(
140            self,
141            Oper::UnOper(UnOper::Not) | Oper::BinOper(BinOper::And) | Oper::BinOper(BinOper::Or)
142        )
143    }
144
145    pub(crate) fn is_between(&self) -> bool {
146        matches!(
147            self,
148            Oper::BinOper(BinOper::Between) | Oper::BinOper(BinOper::NotBetween)
149        )
150    }
151
152    pub(crate) fn is_like(&self) -> bool {
153        matches!(
154            self,
155            Oper::BinOper(BinOper::Like) | Oper::BinOper(BinOper::NotLike)
156        )
157    }
158
159    pub(crate) fn is_in(&self) -> bool {
160        matches!(
161            self,
162            Oper::BinOper(BinOper::In) | Oper::BinOper(BinOper::NotIn)
163        )
164    }
165
166    pub(crate) fn is_is(&self) -> bool {
167        matches!(
168            self,
169            Oper::BinOper(BinOper::Is) | Oper::BinOper(BinOper::IsNot)
170        )
171    }
172
173    pub(crate) fn is_shift(&self) -> bool {
174        matches!(
175            self,
176            Oper::BinOper(BinOper::LShift) | Oper::BinOper(BinOper::RShift)
177        )
178    }
179
180    pub(crate) fn is_arithmetic(&self) -> bool {
181        match self {
182            Oper::BinOper(b) => {
183                matches!(
184                    b,
185                    BinOper::Mul | BinOper::Div | BinOper::Mod | BinOper::Add | BinOper::Sub
186                )
187            }
188            _ => false,
189        }
190    }
191
192    pub(crate) fn is_comparison(&self) -> bool {
193        match self {
194            Oper::BinOper(b) => {
195                matches!(
196                    b,
197                    BinOper::SmallerThan
198                        | BinOper::SmallerThanOrEqual
199                        | BinOper::Equal
200                        | BinOper::GreaterThanOrEqual
201                        | BinOper::GreaterThan
202                        | BinOper::NotEqual
203                )
204            }
205            _ => false,
206        }
207    }
208}