Skip to main content

tank_core/expression/
expression.rs

1use crate::{
2    AnyQuery, AsValue, ExpressionVisitor, FixedDecimal, GenericSqlWriter, Interval, OpPrecedence,
3    Operand, Value,
4    writer::{Context, SqlWriter},
5};
6use rust_decimal::Decimal;
7use std::{borrow::Cow, mem, sync::Arc};
8use time::UtcDateTime;
9use uuid::Uuid;
10
11/// Fragment that represents an AST that can be written in a SQL query.
12pub trait Expression: OpPrecedence {
13    /// Generates the SQL representation of this expression.
14    fn write_query(&self, writer: &dyn SqlWriter, context: &mut Context, out: &mut AnyQuery);
15
16    /// Traverses the expression with a visitor.
17    ///
18    /// Returns `true` if the visitor matched this node.
19    fn accept_visitor(
20        &self,
21        _matcher: &mut dyn ExpressionVisitor,
22        _writer: &dyn SqlWriter,
23        _context: &mut Context,
24        _out: &mut AnyQuery,
25    ) -> bool {
26        false
27    }
28
29    /// Renders the expression as a string suitable for use as an identifier.
30    fn as_identifier(&self, context: &mut Context) -> String {
31        let mut out = AnyQuery::new(String::new());
32        let writer = GenericSqlWriter::new();
33        self.write_query(&writer, context, &mut out);
34        mem::take(out.buffer())
35    }
36}
37
38impl Expression for () {
39    fn write_query(&self, _writer: &dyn SqlWriter, _context: &mut Context, _out: &mut AnyQuery) {}
40}
41
42impl<T: Expression> Expression for &T {
43    fn write_query(&self, writer: &dyn SqlWriter, context: &mut Context, out: &mut AnyQuery) {
44        (*self).write_query(writer, context, out);
45    }
46    fn accept_visitor(
47        &self,
48        matcher: &mut dyn ExpressionVisitor,
49        writer: &dyn SqlWriter,
50        context: &mut Context,
51        out: &mut AnyQuery,
52    ) -> bool {
53        (*self).accept_visitor(matcher, writer, context, out)
54    }
55    fn as_identifier(&self, context: &mut Context) -> String {
56        (*self).as_identifier(context)
57    }
58}
59
60impl Expression for &dyn Expression {
61    fn write_query(&self, writer: &dyn SqlWriter, context: &mut Context, out: &mut AnyQuery) {
62        (*self).write_query(writer, context, out);
63    }
64    fn accept_visitor(
65        &self,
66        matcher: &mut dyn ExpressionVisitor,
67        writer: &dyn SqlWriter,
68        context: &mut Context,
69        out: &mut AnyQuery,
70    ) -> bool {
71        (*self).accept_visitor(matcher, writer, context, out)
72    }
73    fn as_identifier(&self, context: &mut Context) -> String {
74        (*self).as_identifier(context)
75    }
76}
77
78impl Expression for bool {
79    fn write_query(&self, writer: &dyn SqlWriter, context: &mut Context, out: &mut AnyQuery) {
80        writer.write_bool(context, out, *self);
81    }
82    fn accept_visitor(
83        &self,
84        matcher: &mut dyn ExpressionVisitor,
85        writer: &dyn SqlWriter,
86        context: &mut Context,
87        out: &mut AnyQuery,
88    ) -> bool {
89        matcher.visit_operand(writer, context, out, &Operand::LitBool(*self))
90    }
91}
92
93impl<const W: u8, const S: u8> Expression for FixedDecimal<W, S> {
94    fn write_query(&self, writer: &dyn SqlWriter, context: &mut Context, out: &mut AnyQuery) {
95        writer.write_value(context, out, &(*self).as_value());
96    }
97    fn accept_visitor(
98        &self,
99        matcher: &mut dyn ExpressionVisitor,
100        writer: &dyn SqlWriter,
101        context: &mut Context,
102        out: &mut AnyQuery,
103    ) -> bool {
104        matcher.visit_operand(writer, context, out, &Operand::Variable((*self).as_value()))
105    }
106}
107
108impl Expression for &'_ str {
109    fn write_query(&self, writer: &dyn SqlWriter, context: &mut Context, out: &mut AnyQuery) {
110        writer.write_string(context, out, self);
111    }
112    fn accept_visitor(
113        &self,
114        matcher: &mut dyn ExpressionVisitor,
115        writer: &dyn SqlWriter,
116        context: &mut Context,
117        out: &mut AnyQuery,
118    ) -> bool {
119        matcher.visit_operand(writer, context, out, &Operand::LitStr(*self))
120    }
121}
122
123impl Expression for String {
124    fn write_query(&self, writer: &dyn SqlWriter, context: &mut Context, out: &mut AnyQuery) {
125        writer.write_string(context, out, self);
126    }
127    fn accept_visitor(
128        &self,
129        matcher: &mut dyn ExpressionVisitor,
130        writer: &dyn SqlWriter,
131        context: &mut Context,
132        out: &mut AnyQuery,
133    ) -> bool {
134        matcher.visit_operand(writer, context, out, &Operand::LitStr(self))
135    }
136}
137
138impl Expression for Cow<'_, str> {
139    fn write_query(&self, writer: &dyn SqlWriter, context: &mut Context, out: &mut AnyQuery) {
140        writer.write_string(context, out, self.as_ref());
141    }
142    fn accept_visitor(
143        &self,
144        matcher: &mut dyn ExpressionVisitor,
145        writer: &dyn SqlWriter,
146        context: &mut Context,
147        out: &mut AnyQuery,
148    ) -> bool {
149        matcher.visit_operand(writer, context, out, &Operand::LitStr(self))
150    }
151}
152
153impl Expression for Box<[u8]> {
154    fn write_query(&self, writer: &dyn SqlWriter, context: &mut Context, out: &mut AnyQuery) {
155        writer.write_value(context, out, &Value::Blob(Some(Cow::Borrowed(self))));
156    }
157    fn accept_visitor(
158        &self,
159        matcher: &mut dyn ExpressionVisitor,
160        writer: &dyn SqlWriter,
161        context: &mut Context,
162        out: &mut AnyQuery,
163    ) -> bool {
164        let value = Value::Blob(Some(Cow::Borrowed(self)));
165        matcher.visit_operand(writer, context, out, &Operand::Variable(value))
166    }
167}
168
169impl Expression for Value<'_> {
170    fn write_query(&self, writer: &dyn SqlWriter, context: &mut Context, out: &mut AnyQuery) {
171        writer.write_value(context, out, self);
172    }
173    fn accept_visitor(
174        &self,
175        matcher: &mut dyn ExpressionVisitor,
176        writer: &dyn SqlWriter,
177        context: &mut Context,
178        out: &mut AnyQuery,
179    ) -> bool {
180        matcher.visit_operand(writer, context, out, &Operand::Value(self))
181    }
182}
183
184impl Expression for Cow<'_, Value<'_>> {
185    fn write_query(&self, writer: &dyn SqlWriter, context: &mut Context, out: &mut AnyQuery) {
186        writer.write_value(context, out, self);
187    }
188    fn accept_visitor(
189        &self,
190        matcher: &mut dyn ExpressionVisitor,
191        writer: &dyn SqlWriter,
192        context: &mut Context,
193        out: &mut AnyQuery,
194    ) -> bool {
195        matcher.visit_operand(writer, context, out, &Operand::Value(self))
196    }
197}
198
199impl Expression for serde_json::Value {
200    fn write_query(&self, writer: &dyn SqlWriter, context: &mut Context, out: &mut AnyQuery) {
201        writer.write_value(context, out, &Value::Json(Some(self.clone())));
202    }
203    fn accept_visitor(
204        &self,
205        matcher: &mut dyn ExpressionVisitor,
206        writer: &dyn SqlWriter,
207        context: &mut Context,
208        out: &mut AnyQuery,
209    ) -> bool {
210        let value = Value::Json(Some(self.clone()));
211        matcher.visit_operand(writer, context, out, &Operand::Variable(value))
212    }
213}
214
215impl Expression for UtcDateTime {
216    fn write_query(&self, writer: &dyn SqlWriter, context: &mut Context, out: &mut AnyQuery) {
217        writer.write_value(
218            context,
219            out,
220            &Value::Timestamp(Some(time::PrimitiveDateTime::new(self.date(), self.time()))),
221        );
222    }
223    fn accept_visitor(
224        &self,
225        matcher: &mut dyn ExpressionVisitor,
226        writer: &dyn SqlWriter,
227        context: &mut Context,
228        out: &mut AnyQuery,
229    ) -> bool {
230        let value = Value::Timestamp(Some(time::PrimitiveDateTime::new(self.date(), self.time())));
231        matcher.visit_operand(writer, context, out, &Operand::Variable(value))
232    }
233}
234
235impl<T: AsValue + Expression> Expression for Option<T> {
236    fn write_query(&self, writer: &dyn SqlWriter, context: &mut Context, out: &mut AnyQuery) {
237        match self {
238            Some(v) => v.write_query(writer, context, out),
239            None => writer.write_value(context, out, &T::as_empty_value()),
240        }
241    }
242    fn accept_visitor(
243        &self,
244        matcher: &mut dyn ExpressionVisitor,
245        writer: &dyn SqlWriter,
246        context: &mut Context,
247        out: &mut AnyQuery,
248    ) -> bool {
249        match self {
250            Some(v) => v.accept_visitor(matcher, writer, context, out),
251            None => matcher.visit_operand(
252                writer,
253                context,
254                out,
255                &Operand::Variable(T::as_empty_value()),
256            ),
257        }
258    }
259}
260
261impl<T: Expression> Expression for Box<T> {
262    fn write_query(&self, writer: &dyn SqlWriter, context: &mut Context, out: &mut AnyQuery) {
263        (**self).write_query(writer, context, out);
264    }
265    fn accept_visitor(
266        &self,
267        matcher: &mut dyn ExpressionVisitor,
268        writer: &dyn SqlWriter,
269        context: &mut Context,
270        out: &mut AnyQuery,
271    ) -> bool {
272        (**self).accept_visitor(matcher, writer, context, out)
273    }
274}
275
276impl<T: Expression> Expression for Arc<T> {
277    fn write_query(&self, writer: &dyn SqlWriter, context: &mut Context, out: &mut AnyQuery) {
278        (**self).write_query(writer, context, out);
279    }
280    fn accept_visitor(
281        &self,
282        matcher: &mut dyn ExpressionVisitor,
283        writer: &dyn SqlWriter,
284        context: &mut Context,
285        out: &mut AnyQuery,
286    ) -> bool {
287        (**self).accept_visitor(matcher, writer, context, out)
288    }
289}
290
291macro_rules! impl_expression {
292    ($($T:ty),* $(,)?) => {$(
293        impl OpPrecedence for $T {
294            fn precedence(&self, _: &dyn SqlWriter) -> i32 { 0 }
295        }
296        impl Expression for $T {
297            fn write_query(
298                &self,
299                writer: &dyn SqlWriter,
300                context: &mut Context,
301                out: &mut AnyQuery,
302            ) {
303                writer.write_value(context, out, &(*self).as_value());
304            }
305            fn accept_visitor(
306                &self,
307                matcher: &mut dyn ExpressionVisitor,
308                writer: &dyn SqlWriter,
309                context: &mut Context,
310                out: &mut AnyQuery,
311            ) -> bool {
312                matcher.visit_operand(writer, context, out, &Operand::Variable((*self).as_value()))
313            }
314        }
315    )*};
316}
317
318impl_expression!(
319    i8,
320    i16,
321    i32,
322    i64,
323    i128,
324    isize,
325    u8,
326    u16,
327    u32,
328    u64,
329    u128,
330    usize,
331    f32,
332    f64,
333    char,
334    Uuid,
335    Decimal,
336    Interval,
337    std::time::Duration,
338    time::Duration,
339    time::Date,
340    time::Time,
341    time::PrimitiveDateTime,
342    time::OffsetDateTime,
343);
344
345#[cfg(feature = "chrono")]
346impl_expression!(
347    chrono::NaiveDate,
348    chrono::NaiveTime,
349    chrono::NaiveDateTime,
350    chrono::DateTime<chrono::FixedOffset>,
351);
352
353impl<'a, T: Expression> From<&'a T> for &'a dyn Expression {
354    fn from(value: &'a T) -> Self {
355        value as &'a dyn Expression
356    }
357}