pqb 0.1.0

A PostgreSQL Query Builder
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
// Copyright 2025 FastLabs Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! SQL expressions.
//!
//! [`Expr`] is an arbitrary, dynamically-typed SQL expression. It can be used in select fields,
//! where clauses and many other places.

use std::borrow::Cow;

use crate::func::FunctionCall;
use crate::func::write_function_call;
use crate::query::Select;
use crate::query::write_select;
use crate::types::ColumnName;
use crate::types::ColumnRef;
use crate::types::IntoColumnRef;
use crate::types::IntoIden;
use crate::types::write_iden;
use crate::types::write_table_name;
use crate::value::Value;
use crate::writer::SqlWriter;

/// SQL keywords.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
#[expect(missing_docs)]
pub enum Keyword {
    Null,
    CurrentTimestamp,
}

/// An arbitrary, dynamically-typed SQL expression.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
#[expect(missing_docs)]
pub enum Expr {
    Column(ColumnRef),
    Asterisk,
    Keyword(Keyword),
    Tuple(Vec<Expr>),
    Value(Value),
    Unary(UnaryOp, Box<Expr>),
    Binary(Box<Expr>, BinaryOp, Box<Expr>),
    FunctionCall(FunctionCall),
    SubQuery(Option<SubQueryOp>, Box<Select>),
    Custom(Cow<'static, str>),
}

/// # Expression constructors
impl Expr {
    /// Express a [`Value`], returning a [`Expr`].
    pub fn value<T>(value: T) -> Expr
    where
        T: Into<Value>,
    {
        Expr::Value(value.into())
    }

    /// Express the target column, returning a [`Expr`].
    pub fn column<T>(col: T) -> Self
    where
        T: IntoColumnRef,
    {
        Expr::Column(col.into_column_ref())
    }

    /// Express the asterisk (*) without table prefix.
    pub fn asterisk() -> Self {
        Expr::Asterisk
    }

    /// Wraps tuple of `Expr`, can be used for tuple comparison.
    pub fn tuple<I>(exprs: I) -> Self
    where
        I: IntoIterator<Item = Self>,
    {
        Expr::Tuple(exprs.into_iter().collect())
    }

    /// Express a custom SQL expression.
    pub fn custom<T>(expr: T) -> Self
    where
        T: Into<Cow<'static, str>>,
    {
        Expr::Custom(expr.into())
    }

    /// Keyword `CURRENT_TIMESTAMP`.
    pub fn current_timestamp() -> Self {
        Expr::Keyword(Keyword::CurrentTimestamp)
    }
}

/// # Expression combinators
impl Expr {
    /// Create a MAX() function call.
    pub fn max(self) -> Self {
        Expr::FunctionCall(FunctionCall::max(self))
    }

    /// Create a MIN() function call.
    pub fn min(self) -> Self {
        Expr::FunctionCall(FunctionCall::min(self))
    }

    /// Create a SUM() function call.
    pub fn sum(self) -> Self {
        Expr::FunctionCall(FunctionCall::sum(self))
    }

    /// Create an AVG() function call.
    pub fn avg(self) -> Self {
        Expr::FunctionCall(FunctionCall::avg(self))
    }

    /// Create a COUNT() function call.
    pub fn count(self) -> Self {
        Expr::FunctionCall(FunctionCall::count(self))
    }

    /// Check if the expression is NULL.
    pub fn is_null(self) -> Self {
        self.binary(BinaryOp::Is, Expr::Keyword(Keyword::Null))
    }

    /// Check if the expression is NOT NULL.
    pub fn is_not_null(self) -> Self {
        self.binary(BinaryOp::IsNot, Expr::Keyword(Keyword::Null))
    }

    /// Check if the expression is between two values.
    pub fn between<A, B>(self, a: A, b: B) -> Self
    where
        A: Into<Expr>,
        B: Into<Expr>,
    {
        self.binary(
            BinaryOp::Between,
            Expr::Binary(Box::new(a.into()), BinaryOp::And, Box::new(b.into())),
        )
    }

    /// Check if the expression is not between two values.
    pub fn not_between<A, B>(self, a: A, b: B) -> Self
    where
        A: Into<Expr>,
        B: Into<Expr>,
    {
        self.binary(
            BinaryOp::NotBetween,
            Expr::Binary(Box::new(a.into()), BinaryOp::And, Box::new(b.into())),
        )
    }

    /// Pattern matching with LIKE.
    pub fn like<R>(self, pattern: R) -> Self
    where
        R: Into<Expr>,
    {
        self.binary(BinaryOp::Like, pattern)
    }

    /// Add a value.
    #[expect(clippy::should_implement_trait)]
    pub fn add<R>(self, rhs: R) -> Self
    where
        R: Into<Expr>,
    {
        self.binary(BinaryOp::Add, rhs)
    }

    /// Subtract a value.
    #[expect(clippy::should_implement_trait)]
    pub fn sub<R>(self, rhs: R) -> Self
    where
        R: Into<Expr>,
    {
        self.binary(BinaryOp::Sub, rhs)
    }

    /// Multiply by a value.
    #[expect(clippy::should_implement_trait)]
    pub fn mul<R>(self, rhs: R) -> Self
    where
        R: Into<Expr>,
    {
        self.binary(BinaryOp::Mul, rhs)
    }

    /// Divide by a value.
    #[expect(clippy::should_implement_trait)]
    pub fn div<R>(self, rhs: R) -> Self
    where
        R: Into<Expr>,
    {
        self.binary(BinaryOp::Div, rhs)
    }

    /// Replace NULL with the specified value using COALESCE.
    pub fn if_null<V>(self, value: V) -> Self
    where
        V: Into<Expr>,
    {
        Expr::FunctionCall(FunctionCall::coalesce(self, value))
    }

    /// Greater than (`>`).
    pub fn gt<R>(self, right: R) -> Self
    where
        R: Into<Expr>,
    {
        self.binary(BinaryOp::GreaterThan, right)
    }

    /// Greater than or equal (`>=`).
    pub fn gte<R>(self, right: R) -> Self
    where
        R: Into<Expr>,
    {
        self.binary(BinaryOp::GreaterThanOrEqual, right)
    }

    /// Less than (`<`).
    pub fn lt<R>(self, right: R) -> Self
    where
        R: Into<Expr>,
    {
        self.binary(BinaryOp::LessThan, right)
    }

    /// Less than or equal (`<=`).
    pub fn lte<R>(self, right: R) -> Self
    where
        R: Into<Expr>,
    {
        self.binary(BinaryOp::LessThanOrEqual, right)
    }

    /// Create any binary operation.
    pub fn binary<R>(self, op: BinaryOp, rhs: R) -> Self
    where
        R: Into<Expr>,
    {
        Expr::Binary(Box::new(self), op, Box::new(rhs.into()))
    }

    /// Express a logical `AND` operation.
    pub fn and<R>(self, right: R) -> Expr
    where
        R: Into<Expr>,
    {
        self.binary(BinaryOp::And, right)
    }

    /// Express a logical `OR` operation.
    pub fn or<R>(self, right: R) -> Expr
    where
        R: Into<Expr>,
    {
        self.binary(BinaryOp::Or, right)
    }

    /// Express an equal (`=`) expression.
    pub fn eq<R>(self, right: R) -> Expr
    where
        R: Into<Expr>,
    {
        self.binary(BinaryOp::Equal, right)
    }

    /// Express a not equal (`<>`) expression.
    pub fn ne<R>(self, right: R) -> Expr
    where
        R: Into<Expr>,
    {
        self.binary(BinaryOp::NotEqual, right)
    }

    /// Express a `IS` expression.
    pub fn is<R>(self, right: R) -> Expr
    where
        R: Into<Expr>,
    {
        self.binary(BinaryOp::Is, right)
    }

    /// Express a `IS NOT` expression.
    pub fn is_not<R>(self, right: R) -> Expr
    where
        R: Into<Expr>,
    {
        self.binary(BinaryOp::IsNot, right)
    }

    /// Express a `IN` expression.
    pub fn is_in<V, I>(self, v: I) -> Expr
    where
        V: Into<Expr>,
        I: IntoIterator<Item = V>,
    {
        self.binary(
            BinaryOp::In,
            Expr::Tuple(v.into_iter().map(|v| v.into()).collect()),
        )
    }

    /// Express a `NOT IN` expression.
    pub fn is_not_in<V, I>(self, v: I) -> Expr
    where
        V: Into<Expr>,
        I: IntoIterator<Item = V>,
    {
        self.binary(
            BinaryOp::NotIn,
            Expr::Tuple(v.into_iter().map(|v| v.into()).collect()),
        )
    }

    /// Express a `IN` subquery expression.
    pub fn in_subquery(self, query: Select) -> Expr {
        self.binary(BinaryOp::In, Expr::SubQuery(None, Box::new(query)))
    }

    /// Express a `IN` expression with tuple values.
    pub fn in_tuples<T, I>(self, tuples: I) -> Expr
    where
        T: IntoIterator<Item = Expr>,
        I: IntoIterator<Item = T>,
    {
        self.binary(
            BinaryOp::In,
            Expr::Tuple(
                tuples
                    .into_iter()
                    .map(|t| Expr::Tuple(t.into_iter().collect()))
                    .collect(),
            ),
        )
    }

    /// Apply any unary operator to the expression.
    pub fn unary(self, op: UnaryOp) -> Expr {
        Expr::Unary(op, Box::new(self))
    }

    /// Negates an expression with `NOT`.
    #[expect(clippy::should_implement_trait)]
    pub fn not(self) -> Expr {
        self.unary(UnaryOp::Not)
    }

    /// Call `CAST` function with a custom type.
    pub fn cast_as<N>(self, ty: N) -> Expr
    where
        N: IntoIden,
    {
        Expr::FunctionCall(FunctionCall::cast_as(self, ty))
    }
}

/// SubQuery operators
#[derive(Debug, Copy, Clone, PartialEq)]
#[non_exhaustive]
#[expect(missing_docs)]
pub enum SubQueryOp {
    Exists,
    Any,
    Some,
    All,
}

/// Unary operators.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
#[expect(missing_docs)]
pub enum UnaryOp {
    Not,
}

/// Binary operators.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
#[expect(missing_docs)]
pub enum BinaryOp {
    And,
    Or,
    As,
    Equal,
    NotEqual,
    Between,
    NotBetween,
    Like,
    NotLike,
    Is,
    IsNot,
    In,
    NotIn,
    LShift,
    RShift,
    Add,
    Sub,
    Mul,
    Div,
    Mod,
    LessThan,
    LessThanOrEqual,
    GreaterThan,
    GreaterThanOrEqual,
}

impl Expr {
    pub(crate) fn from_conditions(conditions: Vec<Expr>) -> Option<Expr> {
        conditions
            .into_iter()
            .reduce(|lhs, rhs| lhs.binary(BinaryOp::And, rhs))
    }
}

impl From<Keyword> for Expr {
    fn from(k: Keyword) -> Self {
        Expr::Keyword(k)
    }
}

impl<T> From<T> for Expr
where
    T: Into<Value>,
{
    fn from(v: T) -> Self {
        Expr::Value(v.into())
    }
}

pub(crate) fn write_expr<W: SqlWriter>(w: &mut W, expr: &Expr) {
    match expr {
        Expr::Column(col) => write_column_ref(w, col),
        Expr::Asterisk => w.push_char('*'),
        Expr::Keyword(keyword) => w.push_str(match keyword {
            Keyword::Null => "NULL",
            Keyword::CurrentTimestamp => "CURRENT_TIMESTAMP",
        }),
        Expr::Tuple(exprs) => write_tuple(w, exprs),
        Expr::Value(value) => w.push_param(value.clone()),
        Expr::Unary(unary, expr) => write_unary_expr(w, unary, expr),
        Expr::Binary(lhs, op, rhs) => match (op, &**rhs) {
            (BinaryOp::In, Expr::Tuple(t)) if t.is_empty() => {
                // 1 = 2 is always false <=> IN () is always false
                write_binary_expr(w, &Expr::value(1), &BinaryOp::Equal, &Expr::value(2))
            }
            (BinaryOp::NotIn, Expr::Tuple(t)) if t.is_empty() => {
                // 1 = 1 is always true <=> NOT IN () is always true
                write_binary_expr(w, &Expr::value(1), &BinaryOp::Equal, &Expr::value(1))
            }
            _ => write_binary_expr(w, lhs, op, rhs),
        },
        Expr::FunctionCall(call) => write_function_call(w, call),
        Expr::SubQuery(op, query) => {
            if let Some(op) = op {
                w.push_str(match op {
                    SubQueryOp::Exists => "EXISTS",
                    SubQueryOp::Any => "ANY",
                    SubQueryOp::Some => "SOME",
                    SubQueryOp::All => "ALL",
                });
            }
            w.push_char('(');
            write_select(w, query);
            w.push_char(')');
        }
        Expr::Custom(expr) => w.push_str(expr),
    }
}

fn write_unary_expr<W: SqlWriter>(w: &mut W, op: &UnaryOp, expr: &Expr) {
    write_unary_op(w, op);
    w.push_char(' ');

    let mut paren = true;
    paren &= !well_known_no_parentheses(expr);
    paren &= !well_known_high_precedence(expr, &Operator::Unary(*op));
    if paren {
        w.push_char('(');
    }
    write_expr(w, expr);
    if paren {
        w.push_char(')');
    }
}

fn write_unary_op<W: SqlWriter>(w: &mut W, op: &UnaryOp) {
    w.push_str(match op {
        UnaryOp::Not => "NOT",
    })
}

fn write_binary_expr<W: SqlWriter>(w: &mut W, lhs: &Expr, op: &BinaryOp, rhs: &Expr) {
    let binop = Operator::Binary(*op);

    let mut left_paren = true;
    left_paren &= !well_known_no_parentheses(lhs);
    left_paren &= !well_known_high_precedence(lhs, &binop);
    // left associativity allow us to drop the left parentheses
    if left_paren
        && let Expr::Binary(_, inner_op, _) = lhs
        && inner_op == op
        && well_known_left_associative(op)
    {
        left_paren = false;
    }
    if left_paren {
        w.push_char('(');
    }
    write_expr(w, lhs);
    if left_paren {
        w.push_char(')');
    }

    w.push_char(' ');
    write_binary_op(w, op);
    w.push_char(' ');

    let mut right_paren = true;
    right_paren &= !well_known_no_parentheses(rhs);
    right_paren &= !well_known_high_precedence(rhs, &binop);
    // workaround represent trinary op between as nested binary ops
    if right_paren
        && binop.is_between()
        && let Expr::Binary(_, BinaryOp::And, _) = rhs
    {
        right_paren = false;
    }
    // workaround custom representation of casting AS datatype
    if right_paren && (op == &BinaryOp::As) && matches!(rhs, Expr::Custom(_)) {
        right_paren = false;
    }
    if right_paren {
        w.push_char('(');
    }
    write_expr(w, rhs);
    if right_paren {
        w.push_char(')');
    }
}

fn write_binary_op<W: SqlWriter>(w: &mut W, op: &BinaryOp) {
    w.push_str(match op {
        BinaryOp::And => "AND",
        BinaryOp::Or => "OR",
        BinaryOp::As => "AS",
        BinaryOp::Like => "LIKE",
        BinaryOp::NotLike => "NOT LIKE",
        BinaryOp::Is => "IS",
        BinaryOp::IsNot => "IS NOT",
        BinaryOp::In => "IN",
        BinaryOp::NotIn => "NOT IN",
        BinaryOp::Between => "BETWEEN",
        BinaryOp::NotBetween => "NOT BETWEEN",
        BinaryOp::Equal => "=",
        BinaryOp::NotEqual => "<>",
        BinaryOp::LessThan => "<",
        BinaryOp::LessThanOrEqual => "<=",
        BinaryOp::GreaterThan => ">",
        BinaryOp::GreaterThanOrEqual => ">=",
        BinaryOp::Add => "+",
        BinaryOp::Sub => "-",
        BinaryOp::Mul => "*",
        BinaryOp::Div => "/",
        BinaryOp::Mod => "%",
        BinaryOp::LShift => "<<",
        BinaryOp::RShift => ">>",
    })
}

fn write_tuple<W: SqlWriter>(w: &mut W, exprs: &[Expr]) {
    w.push_char('(');
    for (i, expr) in exprs.iter().enumerate() {
        if i != 0 {
            w.push_str(", ");
        }
        write_expr(w, expr);
    }
    w.push_char(')');
}

fn write_column_ref<W: SqlWriter>(w: &mut W, col: &ColumnRef) {
    match col {
        ColumnRef::Column(ColumnName(table_name, column)) => {
            if let Some(table_name) = table_name {
                write_table_name(w, table_name);
                w.push_char('.');
            }
            write_iden(w, column);
        }
        ColumnRef::Asterisk(table_name) => {
            if let Some(table_name) = table_name {
                write_table_name(w, table_name);
                w.push_char('.');
            }
            w.push_char('*');
        }
    }
}

fn well_known_no_parentheses(expr: &Expr) -> bool {
    matches!(
        expr,
        Expr::Column(_)
            | Expr::Tuple(_)
            | Expr::Value(_)
            | Expr::Asterisk
            | Expr::Keyword(_)
            | Expr::FunctionCall(_)
            | Expr::SubQuery(_, _)
    )
}

fn well_known_left_associative(op: &BinaryOp) -> bool {
    matches!(
        op,
        BinaryOp::And
            | BinaryOp::Or
            | BinaryOp::Add
            | BinaryOp::Sub
            | BinaryOp::Mul
            | BinaryOp::Div
    )
}

fn well_known_high_precedence(expr: &Expr, outer_op: &Operator) -> bool {
    let inner_op = if let Expr::Binary(_, op, _) = expr {
        Operator::Binary(*op)
    } else {
        return false;
    };

    if inner_op.is_arithmetic() || inner_op.is_shift() {
        return outer_op.is_comparison()
            || outer_op.is_between()
            || outer_op.is_in()
            || outer_op.is_like()
            || outer_op.is_logical();
    }

    if inner_op.is_comparison() || inner_op.is_in() || inner_op.is_like() || inner_op.is_is() {
        return outer_op.is_logical();
    }

    false
}

enum Operator {
    Unary(UnaryOp),
    Binary(BinaryOp),
}

impl Operator {
    fn is_logical(&self) -> bool {
        matches!(
            self,
            Operator::Unary(UnaryOp::Not)
                | Operator::Binary(BinaryOp::And)
                | Operator::Binary(BinaryOp::Or)
        )
    }

    fn is_between(&self) -> bool {
        matches!(
            self,
            Operator::Binary(BinaryOp::Between) | Operator::Binary(BinaryOp::NotBetween)
        )
    }

    fn is_like(&self) -> bool {
        matches!(
            self,
            Operator::Binary(BinaryOp::Like) | Operator::Binary(BinaryOp::NotLike)
        )
    }

    fn is_in(&self) -> bool {
        matches!(
            self,
            Operator::Binary(BinaryOp::In) | Operator::Binary(BinaryOp::NotIn)
        )
    }

    fn is_is(&self) -> bool {
        matches!(
            self,
            Operator::Binary(BinaryOp::Is) | Operator::Binary(BinaryOp::IsNot)
        )
    }

    fn is_shift(&self) -> bool {
        matches!(
            self,
            Operator::Binary(BinaryOp::LShift) | Operator::Binary(BinaryOp::RShift)
        )
    }

    fn is_arithmetic(&self) -> bool {
        match self {
            Operator::Binary(b) => {
                matches!(
                    b,
                    BinaryOp::Mul | BinaryOp::Div | BinaryOp::Mod | BinaryOp::Add | BinaryOp::Sub
                )
            }
            _ => false,
        }
    }

    fn is_comparison(&self) -> bool {
        match self {
            Operator::Binary(b) => {
                matches!(
                    b,
                    BinaryOp::LessThan
                        | BinaryOp::LessThanOrEqual
                        | BinaryOp::Equal
                        | BinaryOp::GreaterThanOrEqual
                        | BinaryOp::GreaterThan
                        | BinaryOp::NotEqual
                )
            }
            _ => false,
        }
    }
}