1use crate::BindValue;
8use std::{any::Any, fmt, sync::Arc};
9
10#[derive(Clone, Debug, PartialEq, Eq)]
14pub enum ColumnType {
15 Simple,
16 Composite(String),
17 Array(Box<ColumnType>),
18}
19
20#[derive(Clone, Debug, PartialEq, Eq)]
22pub struct ColumnExpr {
23 pub table: Option<String>,
24 pub name: String,
25 pub ty: ColumnType,
26}
27
28impl ColumnExpr {
29 pub fn new(name: impl Into<String>) -> Self {
31 Self {
32 table: None,
33 name: name.into(),
34 ty: ColumnType::Simple,
35 }
36 }
37
38 pub fn with_table(table: impl Into<String>, name: impl Into<String>) -> Self {
40 Self {
41 table: Some(table.into()),
42 name: name.into(),
43 ty: ColumnType::Simple,
44 }
45 }
46
47 pub fn composite(name: impl Into<String>, composite_type: impl Into<String>) -> Self {
49 Self {
50 table: None,
51 name: name.into(),
52 ty: ColumnType::Composite(composite_type.into()),
53 }
54 }
55}
56
57#[derive(Clone, Debug, PartialEq)]
61pub enum ValueExpr {
62 Bind(BindValue),
63 Column(ColumnExpr),
64 Tuple(Vec<BindValue>), }
66
67impl<V: Into<BindValue>> From<V> for ValueExpr {
68 fn from(v: V) -> Self {
69 ValueExpr::Bind(v.into())
70 }
71}
72
73#[derive(Clone, Copy, Debug, PartialEq, Eq)]
77pub enum CmpOp {
78 Eq,
79 Ne,
80 Gt,
81 Ge,
82 Lt,
83 Le,
84 Like,
85 ILike,
86 In,
87 NotIn,
88}
89
90impl CmpOp {
91 #[inline]
93 pub fn to_sql(self) -> &'static str {
94 match self {
95 CmpOp::Eq => "=",
96 CmpOp::Ne => "<>",
97 CmpOp::Gt => ">",
98 CmpOp::Ge => ">=",
99 CmpOp::Lt => "<",
100 CmpOp::Le => "<=",
101 CmpOp::Like => "LIKE",
102 CmpOp::ILike => "ILIKE",
103 CmpOp::In => "IN",
104 CmpOp::NotIn => "NOT IN",
105 }
106 }
107}
108
109#[derive(Clone, Debug, PartialEq)]
113pub struct ComparisonExpr {
114 pub left: ColumnExpr,
115 pub op: CmpOp,
116 pub right: ValueExpr,
117}
118
119#[derive(Clone, Copy, Debug, PartialEq, Eq)]
121pub enum NullCheckKind {
122 IsNull,
123 IsNotNull,
124}
125
126#[derive(Clone, Debug, PartialEq)]
128pub struct NullCheckExpr {
129 pub column: ColumnExpr,
130 pub kind: NullCheckKind,
131}
132
133pub trait ExtBoolExpr: fmt::Debug + Send + Sync + 'static {
137 fn write_sql(&self, out: &mut String, binds: &mut Vec<BindValue>);
139
140 fn as_any(&self) -> &dyn Any
142 where
143 Self: Sized,
144 {
145 self
146 }
147
148 fn precedence(&self) -> u8 {
150 5 }
152}
153
154#[derive(Clone, Debug)]
158pub enum BoolExpr {
159 Comparison(ComparisonExpr),
161 NullCheck(NullCheckExpr),
162 And(Box<BoolExpr>, Box<BoolExpr>),
163 Or(Box<BoolExpr>, Box<BoolExpr>),
164 Not(Box<BoolExpr>),
165 Parens(Box<BoolExpr>),
166 Literal(bool),
167
168 Custom(Arc<dyn ExtBoolExpr>),
170}
171
172impl BoolExpr {
173 #[inline]
175 pub fn and(self, rhs: BoolExpr) -> Self {
176 BoolExpr::And(Box::new(self), Box::new(rhs))
177 }
178
179 #[inline]
181 pub fn or(self, rhs: BoolExpr) -> Self {
182 BoolExpr::Or(Box::new(self), Box::new(rhs))
183 }
184
185 #[inline]
187 pub fn not(self) -> Self {
188 BoolExpr::Not(Box::new(self))
189 }
190
191 #[inline]
193 pub fn grouped(self) -> Self {
194 BoolExpr::Parens(Box::new(self))
195 }
196}
197
198pub trait ColumnOps: Sized {
202 fn is_null(self) -> BoolExpr;
204
205 fn not_null(self) -> BoolExpr;
207}
208
209pub trait CompareOps: Sized {
211 fn eq<V: Into<BindValue>>(self, v: V) -> BoolExpr;
213
214 fn ne<V: Into<BindValue>>(self, v: V) -> BoolExpr;
216
217 fn gt<V: Into<BindValue>>(self, v: V) -> BoolExpr;
219
220 fn ge<V: Into<BindValue>>(self, v: V) -> BoolExpr;
222
223 fn lt<V: Into<BindValue>>(self, v: V) -> BoolExpr;
225
226 fn le<V: Into<BindValue>>(self, v: V) -> BoolExpr;
228
229 fn like<V: Into<BindValue>>(self, v: V) -> BoolExpr;
231
232 fn ilike<V: Into<BindValue>>(self, v: V) -> BoolExpr;
234
235 fn is_in<V: Into<BindValue>>(self, values: impl IntoIterator<Item = V>) -> BoolExpr;
237
238 fn not_in<V: Into<BindValue>>(self, values: impl IntoIterator<Item = V>) -> BoolExpr;
240}
241
242impl ColumnOps for ColumnExpr {
244 #[inline]
245 fn is_null(self) -> BoolExpr {
246 BoolExpr::NullCheck(NullCheckExpr {
247 column: self,
248 kind: NullCheckKind::IsNull,
249 })
250 }
251
252 #[inline]
253 fn not_null(self) -> BoolExpr {
254 BoolExpr::NullCheck(NullCheckExpr {
255 column: self,
256 kind: NullCheckKind::IsNotNull,
257 })
258 }
259}
260
261impl CompareOps for ColumnExpr {
263 #[inline]
264 fn eq<V: Into<BindValue>>(self, v: V) -> BoolExpr {
265 BoolExpr::Comparison(ComparisonExpr {
266 left: self,
267 op: CmpOp::Eq,
268 right: ValueExpr::from(v),
269 })
270 }
271
272 #[inline]
273 fn ne<V: Into<BindValue>>(self, v: V) -> BoolExpr {
274 BoolExpr::Comparison(ComparisonExpr {
275 left: self,
276 op: CmpOp::Ne,
277 right: ValueExpr::from(v),
278 })
279 }
280
281 #[inline]
282 fn gt<V: Into<BindValue>>(self, v: V) -> BoolExpr {
283 BoolExpr::Comparison(ComparisonExpr {
284 left: self,
285 op: CmpOp::Gt,
286 right: ValueExpr::from(v),
287 })
288 }
289
290 #[inline]
291 fn ge<V: Into<BindValue>>(self, v: V) -> BoolExpr {
292 BoolExpr::Comparison(ComparisonExpr {
293 left: self,
294 op: CmpOp::Ge,
295 right: ValueExpr::from(v),
296 })
297 }
298
299 #[inline]
300 fn lt<V: Into<BindValue>>(self, v: V) -> BoolExpr {
301 BoolExpr::Comparison(ComparisonExpr {
302 left: self,
303 op: CmpOp::Lt,
304 right: ValueExpr::from(v),
305 })
306 }
307
308 #[inline]
309 fn le<V: Into<BindValue>>(self, v: V) -> BoolExpr {
310 BoolExpr::Comparison(ComparisonExpr {
311 left: self,
312 op: CmpOp::Le,
313 right: ValueExpr::from(v),
314 })
315 }
316
317 #[inline]
318 fn like<V: Into<BindValue>>(self, v: V) -> BoolExpr {
319 BoolExpr::Comparison(ComparisonExpr {
320 left: self,
321 op: CmpOp::Like,
322 right: ValueExpr::from(v),
323 })
324 }
325
326 #[inline]
327 fn ilike<V: Into<BindValue>>(self, v: V) -> BoolExpr {
328 BoolExpr::Comparison(ComparisonExpr {
329 left: self,
330 op: CmpOp::ILike,
331 right: ValueExpr::from(v),
332 })
333 }
334
335 #[inline]
336 fn is_in<V: Into<BindValue>>(self, values: impl IntoIterator<Item = V>) -> BoolExpr {
337 let vals: Vec<BindValue> = values.into_iter().map(Into::into).collect();
338 BoolExpr::Comparison(ComparisonExpr {
339 left: self,
340 op: CmpOp::In,
341 right: ValueExpr::Tuple(vals),
342 })
343 }
344
345 #[inline]
346 fn not_in<V: Into<BindValue>>(self, values: impl IntoIterator<Item = V>) -> BoolExpr {
347 let vals: Vec<BindValue> = values.into_iter().map(Into::into).collect();
348 BoolExpr::Comparison(ComparisonExpr {
349 left: self,
350 op: CmpOp::NotIn,
351 right: ValueExpr::Tuple(vals),
352 })
353 }
354}
355
356pub trait ToSql {
360 fn write_sql(&self, out: &mut String, binds: &mut Vec<BindValue>);
362}
363
364impl ToSql for ColumnExpr {
365 #[inline]
366 fn write_sql(&self, out: &mut String, _binds: &mut Vec<BindValue>) {
367 if let Some(ref table) = self.table {
368 out.push('"');
369 out.push_str(table);
370 out.push_str("\".");
371 }
372 out.push('"');
373 out.push_str(&self.name);
374 out.push('"');
375 }
376}
377
378impl ToSql for ComparisonExpr {
379 #[inline]
380 fn write_sql(&self, out: &mut String, binds: &mut Vec<BindValue>) {
381 self.left.write_sql(out, binds);
382 out.push(' ');
383 out.push_str(self.op.to_sql());
384 out.push(' ');
385
386 match &self.right {
387 ValueExpr::Bind(v) => {
388 out.push('?');
389 binds.push(v.clone());
390 }
391 ValueExpr::Column(c) => {
392 c.write_sql(out, binds);
393 }
394 ValueExpr::Tuple(vals) => {
395 out.push('(');
396 for (i, v) in vals.iter().enumerate() {
397 if i > 0 {
398 out.push_str(", ");
399 }
400 out.push('?');
401 binds.push(v.clone());
402 }
403 out.push(')');
404 }
405 }
406 }
407}
408
409impl ToSql for NullCheckExpr {
410 #[inline]
411 fn write_sql(&self, out: &mut String, binds: &mut Vec<BindValue>) {
412 self.column.write_sql(out, binds);
413 match self.kind {
414 NullCheckKind::IsNull => out.push_str(" IS NULL"),
415 NullCheckKind::IsNotNull => out.push_str(" IS NOT NULL"),
416 }
417 }
418}
419
420impl ToSql for BoolExpr {
421 #[inline]
422 fn write_sql(&self, out: &mut String, binds: &mut Vec<BindValue>) {
423 match self {
424 BoolExpr::Comparison(c) => c.write_sql(out, binds),
425 BoolExpr::NullCheck(n) => n.write_sql(out, binds),
426 BoolExpr::And(left, right) => {
427 left.write_sql(out, binds);
428 out.push_str(" AND ");
429 right.write_sql(out, binds);
430 }
431 BoolExpr::Or(left, right) => {
432 left.write_sql(out, binds);
433 out.push_str(" OR ");
434 right.write_sql(out, binds);
435 }
436 BoolExpr::Not(expr) => {
437 out.push_str("NOT ");
438 expr.write_sql(out, binds);
439 }
440 BoolExpr::Parens(expr) => {
441 out.push('(');
442 expr.write_sql(out, binds);
443 out.push(')');
444 }
445 BoolExpr::Literal(true) => out.push_str("TRUE"),
446 BoolExpr::Literal(false) => out.push_str("FALSE"),
447 BoolExpr::Custom(ext) => ext.write_sql(out, binds),
448 }
449 }
450}
451
452impl fmt::Display for BoolExpr {
454 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
455 let mut sql = String::new();
456 let mut binds = Vec::new();
457 self.write_sql(&mut sql, &mut binds);
458 write!(f, "{} -- binds: {:?}", sql, binds)
459 }
460}
461
462pub fn col(name: impl Into<String>) -> ColumnExpr {
466 ColumnExpr::new(name)
467}
468
469pub fn table_col(table: impl Into<String>, name: impl Into<String>) -> ColumnExpr {
471 ColumnExpr::with_table(table, name)
472}
473
474pub fn literal(value: bool) -> BoolExpr {
476 BoolExpr::Literal(value)
477}
478
479#[cfg(test)]
482mod tests {
483 use super::*;
484
485 #[test]
486 fn test_column_operations() {
487 let email = col("email");
489 let age = col("age");
490
491 let expr = email.not_null().and(age.gt(18));
493
494 let mut sql = String::new();
495 let mut binds = vec![];
496 expr.write_sql(&mut sql, &mut binds);
497
498 assert_eq!(sql, r#""email" IS NOT NULL AND "age" > ?"#);
499 assert_eq!(binds, vec![BindValue::Int4(18)]);
500 }
501
502 #[test]
503 fn test_complex_expression() {
504 let expr = table_col("users", "email")
505 .not_null()
506 .and(table_col("users", "age").ge(21))
507 .or(table_col("users", "verified").eq(true))
508 .grouped();
509
510 let mut sql = String::new();
511 let mut binds = vec![];
512 expr.write_sql(&mut sql, &mut binds);
513
514 assert_eq!(
515 sql,
516 r#"("users"."email" IS NOT NULL AND "users"."age" >= ? OR "users"."verified" = ?)"#
517 );
518 assert_eq!(binds, vec![BindValue::Int4(21), BindValue::Bool(true)]);
519 }
520
521 #[test]
522 fn test_in_list() {
523 let expr = col("status").is_in(["active", "pending", "approved"]);
524
525 let mut sql = String::new();
526 let mut binds = vec![];
527 expr.write_sql(&mut sql, &mut binds);
528
529 assert_eq!(sql, r#""status" IN (?, ?, ?)"#);
530 assert_eq!(
531 binds,
532 vec![
533 BindValue::Text("active".to_string()),
534 BindValue::Text("pending".to_string()),
535 BindValue::Text("approved".to_string()),
536 ]
537 );
538 }
539
540 #[test]
541 fn test_not_expression() {
542 let expr = col("active").eq(false).not();
543
544 let mut sql = String::new();
545 let mut binds = vec![];
546 expr.write_sql(&mut sql, &mut binds);
547
548 assert_eq!(sql, r#"NOT "active" = ?"#);
549 assert_eq!(binds, vec![BindValue::Bool(false)]);
550 }
551
552 #[derive(Debug)]
554 struct GeoWithinExpr {
555 geom_col: ColumnExpr,
556 region_wkt: String,
557 }
558
559 impl ExtBoolExpr for GeoWithinExpr {
560 fn write_sql(&self, out: &mut String, binds: &mut Vec<BindValue>) {
561 out.push_str("ST_Within(");
562 self.geom_col.write_sql(out, binds);
563 out.push_str(", ST_GeomFromText(?))");
564 binds.push(BindValue::Text(self.region_wkt.clone()));
565 }
566 }
567
568 fn geo_within(geom_col: ColumnExpr, region_wkt: impl Into<String>) -> BoolExpr {
569 BoolExpr::Custom(Arc::new(GeoWithinExpr {
570 geom_col,
571 region_wkt: region_wkt.into(),
572 }))
573 }
574
575 #[test]
576 fn test_plugin_expression() {
577 let expr = geo_within(col("location"), "POLYGON((0 0, 1 0, 1 1, 0 1, 0 0))")
578 .and(col("active").eq(true));
579
580 let mut sql = String::new();
581 let mut binds = vec![];
582 expr.write_sql(&mut sql, &mut binds);
583
584 assert_eq!(
585 sql,
586 r#"ST_Within("location", ST_GeomFromText(?)) AND "active" = ?"#
587 );
588 assert_eq!(
589 binds,
590 vec![
591 BindValue::Text("POLYGON((0 0, 1 0, 1 1, 0 1, 0 0))".to_string()),
592 BindValue::Bool(true),
593 ]
594 );
595 }
596}