halo-sqlbuilder 1.0.0

Composable SQL builder and argument collector
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
//! Cond: helpers to build WHERE clause expressions.

use crate::args::Args;
use crate::flavor::Flavor;
use crate::macros::{IntoStrings, collect_into_strings};
use crate::modifiers::{Arg, Builder};
use crate::string_builder::{StringBuilder, filter_empty_strings};
use std::cell::RefCell;
use std::rc::Rc;

const MIN_INDEX_BASE: usize = 256;

pub type ArgsRef = Rc<RefCell<Args>>;

/// Cond provides helper methods for conditional expressions.
#[derive(Debug, Clone)]
pub struct Cond {
    pub(crate) args: ArgsRef,
}

impl Cond {
    /// Create an independent Cond; uses a larger index_base to avoid accidental recursion.
    pub fn new() -> Self {
        let a = Args {
            index_base: MIN_INDEX_BASE,
            ..Args::default()
        };
        Self {
            args: Rc::new(RefCell::new(a)),
        }
    }

    pub(crate) fn with_args(args: ArgsRef) -> Self {
        Self { args }
    }

    /// Var: store a value into Args and return the `$n` placeholder.
    pub fn var(&self, value: impl Into<Arg>) -> String {
        self.args.borrow_mut().add(value)
    }

    fn expr_builder(&self, f: impl Fn(Flavor, &[Arg]) -> (String, Vec<Arg>) + 'static) -> String {
        self.var(Arg::Builder(Box::new(CondDynBuilder::new(f))))
    }

    pub fn equal(&self, field: &str, value: impl Into<Arg>) -> String {
        if field.is_empty() {
            return String::new();
        }
        let field = field.to_string();
        let value: Arg = value.into();
        self.expr_builder(move |flavor, initial| {
            let mut a = Args {
                flavor,
                ..Args::default()
            };
            let v = a.add(value.clone());
            let fmt = format!("{field} = {v}");
            a.compile_with_flavor(&fmt, flavor, initial)
        })
    }
    pub fn e(&self, field: &str, value: impl Into<Arg>) -> String {
        self.equal(field, value)
    }
    pub fn eq(&self, field: &str, value: impl Into<Arg>) -> String {
        self.equal(field, value)
    }

    pub fn not_equal(&self, field: &str, value: impl Into<Arg>) -> String {
        if field.is_empty() {
            return String::new();
        }
        let field = field.to_string();
        let value: Arg = value.into();
        self.expr_builder(move |flavor, initial| {
            let mut a = Args {
                flavor,
                ..Args::default()
            };
            let v = a.add(value.clone());
            let fmt = format!("{field} <> {v}");
            a.compile_with_flavor(&fmt, flavor, initial)
        })
    }
    pub fn ne(&self, field: &str, value: impl Into<Arg>) -> String {
        self.not_equal(field, value)
    }
    pub fn neq(&self, field: &str, value: impl Into<Arg>) -> String {
        self.not_equal(field, value)
    }

    pub fn greater_than(&self, field: &str, value: impl Into<Arg>) -> String {
        if field.is_empty() {
            return String::new();
        }
        let field = field.to_string();
        let value: Arg = value.into();
        self.expr_builder(move |flavor, initial| {
            let mut a = Args {
                flavor,
                ..Args::default()
            };
            let v = a.add(value.clone());
            let fmt = format!("{field} > {v}");
            a.compile_with_flavor(&fmt, flavor, initial)
        })
    }
    pub fn g(&self, field: &str, value: impl Into<Arg>) -> String {
        self.greater_than(field, value)
    }
    pub fn gt(&self, field: &str, value: impl Into<Arg>) -> String {
        self.greater_than(field, value)
    }

    pub fn greater_equal_than(&self, field: &str, value: impl Into<Arg>) -> String {
        if field.is_empty() {
            return String::new();
        }
        let field = field.to_string();
        let value: Arg = value.into();
        self.expr_builder(move |flavor, initial| {
            let mut a = Args {
                flavor,
                ..Args::default()
            };
            let v = a.add(value.clone());
            let fmt = format!("{field} >= {v}");
            a.compile_with_flavor(&fmt, flavor, initial)
        })
    }
    pub fn ge(&self, field: &str, value: impl Into<Arg>) -> String {
        self.greater_equal_than(field, value)
    }
    pub fn gte(&self, field: &str, value: impl Into<Arg>) -> String {
        self.greater_equal_than(field, value)
    }

    pub fn less_than(&self, field: &str, value: impl Into<Arg>) -> String {
        if field.is_empty() {
            return String::new();
        }
        let field = field.to_string();
        let value: Arg = value.into();
        self.expr_builder(move |flavor, initial| {
            let mut a = Args {
                flavor,
                ..Args::default()
            };
            let v = a.add(value.clone());
            let fmt = format!("{field} < {v}");
            a.compile_with_flavor(&fmt, flavor, initial)
        })
    }
    pub fn l(&self, field: &str, value: impl Into<Arg>) -> String {
        self.less_than(field, value)
    }
    pub fn lt(&self, field: &str, value: impl Into<Arg>) -> String {
        self.less_than(field, value)
    }

    pub fn less_equal_than(&self, field: &str, value: impl Into<Arg>) -> String {
        if field.is_empty() {
            return String::new();
        }
        let field = field.to_string();
        let value: Arg = value.into();
        self.expr_builder(move |flavor, initial| {
            let mut a = Args {
                flavor,
                ..Args::default()
            };
            let v = a.add(value.clone());
            let fmt = format!("{field} <= {v}");
            a.compile_with_flavor(&fmt, flavor, initial)
        })
    }
    pub fn le(&self, field: &str, value: impl Into<Arg>) -> String {
        self.less_equal_than(field, value)
    }
    pub fn lte(&self, field: &str, value: impl Into<Arg>) -> String {
        self.less_equal_than(field, value)
    }

    pub fn like(&self, field: &str, value: impl Into<Arg>) -> String {
        if field.is_empty() {
            return String::new();
        }
        let field = field.to_string();
        let value: Arg = value.into();
        self.expr_builder(move |flavor, initial| {
            let mut a = Args {
                flavor,
                ..Args::default()
            };
            let v = a.add(value.clone());
            let fmt = format!("{field} LIKE {v}");
            a.compile_with_flavor(&fmt, flavor, initial)
        })
    }

    pub fn ilike(&self, field: &str, value: impl Into<Arg>) -> String {
        if field.is_empty() {
            return String::new();
        }

        let field = field.to_string();
        let value: Arg = value.into();

        // Choose ILIKE or LOWER(...) LIKE LOWER(...) based on flavor
        let b = CondDynBuilder::new(move |flavor, initial| {
            let mut a = Args {
                flavor,
                ..Args::default()
            };
            let v = a.add(value.clone());
            let fmt = match flavor {
                Flavor::PostgreSQL | Flavor::SQLite => format!("{} ILIKE {v}", field),
                _ => format!("LOWER({}) LIKE LOWER({v})", field),
            };
            a.compile_with_flavor(&fmt, flavor, initial)
        });
        self.var(Arg::Builder(Box::new(b)))
    }

    pub fn not_like(&self, field: &str, value: impl Into<Arg>) -> String {
        if field.is_empty() {
            return String::new();
        }
        let field = field.to_string();
        let value: Arg = value.into();
        self.expr_builder(move |flavor, initial| {
            let mut a = Args {
                flavor,
                ..Args::default()
            };
            let v = a.add(value.clone());
            let fmt = format!("{field} NOT LIKE {v}");
            a.compile_with_flavor(&fmt, flavor, initial)
        })
    }

    pub fn not_ilike(&self, field: &str, value: impl Into<Arg>) -> String {
        if field.is_empty() {
            return String::new();
        }

        let field = field.to_string();
        let value: Arg = value.into();

        let b = CondDynBuilder::new(move |flavor, initial| {
            let mut a = Args {
                flavor,
                ..Args::default()
            };
            let v = a.add(value.clone());
            let fmt = match flavor {
                Flavor::PostgreSQL | Flavor::SQLite => format!("{} NOT ILIKE {v}", field),
                _ => format!("LOWER({}) NOT LIKE LOWER({v})", field),
            };
            a.compile_with_flavor(&fmt, flavor, initial)
        });
        self.var(Arg::Builder(Box::new(b)))
    }

    pub fn is_null(&self, field: &str) -> String {
        if field.is_empty() {
            return String::new();
        }
        let field = field.to_string();
        self.expr_builder(move |_flavor, initial| (format!("{field} IS NULL"), initial.to_vec()))
    }

    pub fn is_not_null(&self, field: &str) -> String {
        if field.is_empty() {
            return String::new();
        }
        let field = field.to_string();
        self.expr_builder(move |_flavor, initial| {
            (format!("{field} IS NOT NULL"), initial.to_vec())
        })
    }

    pub fn between(&self, field: &str, lower: impl Into<Arg>, upper: impl Into<Arg>) -> String {
        if field.is_empty() {
            return String::new();
        }
        let field = field.to_string();
        let lower: Arg = lower.into();
        let upper: Arg = upper.into();
        self.expr_builder(move |flavor, initial| {
            let mut a = Args {
                flavor,
                ..Args::default()
            };
            let l = a.add(lower.clone());
            let u = a.add(upper.clone());
            let fmt = format!("{field} BETWEEN {l} AND {u}");
            a.compile_with_flavor(&fmt, flavor, initial)
        })
    }

    pub fn not_between(&self, field: &str, lower: impl Into<Arg>, upper: impl Into<Arg>) -> String {
        if field.is_empty() {
            return String::new();
        }
        let field = field.to_string();
        let lower: Arg = lower.into();
        let upper: Arg = upper.into();
        self.expr_builder(move |flavor, initial| {
            let mut a = Args {
                flavor,
                ..Args::default()
            };
            let l = a.add(lower.clone());
            let u = a.add(upper.clone());
            let fmt = format!("{field} NOT BETWEEN {l} AND {u}");
            a.compile_with_flavor(&fmt, flavor, initial)
        })
    }

    pub fn in_(&self, field: &str, values: impl IntoIterator<Item = impl Into<Arg>>) -> String {
        if field.is_empty() {
            return String::new();
        }
        let values: Vec<Arg> = values.into_iter().map(|v| v.into()).collect();
        if values.is_empty() {
            return "0 = 1".to_string();
        }
        let field = field.to_string();
        self.expr_builder(move |flavor, initial| {
            let mut a = Args {
                flavor,
                ..Args::default()
            };
            let vals: Vec<String> = values.iter().cloned().map(|v| a.add(v)).collect();
            let fmt = format!("{field} IN ({})", vals.join(", "));
            a.compile_with_flavor(&fmt, flavor, initial)
        })
    }

    pub fn not_in(&self, field: &str, values: impl IntoIterator<Item = impl Into<Arg>>) -> String {
        if field.is_empty() {
            return String::new();
        }
        let values: Vec<Arg> = values.into_iter().map(|v| v.into()).collect();
        if values.is_empty() {
            return "0 = 0".to_string();
        }
        let field = field.to_string();
        self.expr_builder(move |flavor, initial| {
            let mut a = Args {
                flavor,
                ..Args::default()
            };
            let vals: Vec<String> = values.iter().cloned().map(|v| a.add(v)).collect();
            let fmt = format!("{field} NOT IN ({})", vals.join(", "));
            a.compile_with_flavor(&fmt, flavor, initial)
        })
    }

    pub fn or<T>(&self, exprs: T) -> String
    where
        T: IntoStrings,
    {
        let exprs = filter_empty_strings(collect_into_strings(exprs));
        if exprs.is_empty() {
            return String::new();
        }
        let mut buf = StringBuilder::new();
        buf.write_str("(");
        buf.write_strings(&exprs, " OR ");
        buf.write_str(")");
        buf.into_string()
    }

    pub fn and<T>(&self, exprs: T) -> String
    where
        T: IntoStrings,
    {
        let exprs = filter_empty_strings(collect_into_strings(exprs));
        if exprs.is_empty() {
            return String::new();
        }
        let mut buf = StringBuilder::new();
        buf.write_str("(");
        buf.write_strings(&exprs, " AND ");
        buf.write_str(")");
        buf.into_string()
    }

    pub fn not(&self, expr: impl Into<String>) -> String {
        let expr = expr.into();
        if expr.is_empty() {
            return String::new();
        }
        format!("NOT {expr}")
    }

    pub fn exists(&self, subquery: impl Into<Arg>) -> String {
        let subquery: Arg = subquery.into();
        self.expr_builder(move |flavor, initial| {
            let mut a = Args {
                flavor,
                ..Args::default()
            };
            let v = a.add(subquery.clone());
            let fmt = format!("EXISTS ({v})");
            a.compile_with_flavor(&fmt, flavor, initial)
        })
    }

    pub fn not_exists(&self, subquery: impl Into<Arg>) -> String {
        let subquery: Arg = subquery.into();
        self.expr_builder(move |flavor, initial| {
            let mut a = Args {
                flavor,
                ..Args::default()
            };
            let v = a.add(subquery.clone());
            let fmt = format!("NOT EXISTS ({v})");
            a.compile_with_flavor(&fmt, flavor, initial)
        })
    }

    pub fn any(
        &self,
        field: &str,
        op: &str,
        values: impl IntoIterator<Item = impl Into<Arg>>,
    ) -> String {
        if field.is_empty() || op.is_empty() {
            return String::new();
        }
        let values: Vec<Arg> = values.into_iter().map(|v| v.into()).collect();
        if values.is_empty() {
            return "0 = 1".to_string();
        }
        let field = field.to_string();
        let op = op.to_string();
        self.expr_builder(move |flavor, initial| {
            let mut a = Args {
                flavor,
                ..Args::default()
            };
            let vals: Vec<String> = values.iter().cloned().map(|v| a.add(v)).collect();
            let fmt = format!("{field} {op} ANY ({})", vals.join(", "));
            a.compile_with_flavor(&fmt, flavor, initial)
        })
    }

    pub fn all(
        &self,
        field: &str,
        op: &str,
        values: impl IntoIterator<Item = impl Into<Arg>>,
    ) -> String {
        if field.is_empty() || op.is_empty() {
            return String::new();
        }
        let values: Vec<Arg> = values.into_iter().map(|v| v.into()).collect();
        if values.is_empty() {
            return "0 = 1".to_string();
        }
        let field = field.to_string();
        let op = op.to_string();
        self.expr_builder(move |flavor, initial| {
            let mut a = Args {
                flavor,
                ..Args::default()
            };
            let vals: Vec<String> = values.iter().cloned().map(|v| a.add(v)).collect();
            let fmt = format!("{field} {op} ALL ({})", vals.join(", "));
            a.compile_with_flavor(&fmt, flavor, initial)
        })
    }

    pub fn some(
        &self,
        field: &str,
        op: &str,
        values: impl IntoIterator<Item = impl Into<Arg>>,
    ) -> String {
        if field.is_empty() || op.is_empty() {
            return String::new();
        }
        let values: Vec<Arg> = values.into_iter().map(|v| v.into()).collect();
        if values.is_empty() {
            return "0 = 1".to_string();
        }
        let field = field.to_string();
        let op = op.to_string();
        self.expr_builder(move |flavor, initial| {
            let mut a = Args {
                flavor,
                ..Args::default()
            };
            let vals: Vec<String> = values.iter().cloned().map(|v| a.add(v)).collect();
            let fmt = format!("{field} {op} SOME ({})", vals.join(", "));
            a.compile_with_flavor(&fmt, flavor, initial)
        })
    }

    pub fn is_distinct_from(&self, field: &str, value: impl Into<Arg>) -> String {
        if field.is_empty() {
            return String::new();
        }

        let field = field.to_string();
        let value: Arg = value.into();

        let b = CondDynBuilder::new(move |flavor, initial| {
            let mut a = Args {
                flavor,
                ..Args::default()
            };
            let fmt = match flavor {
                Flavor::PostgreSQL | Flavor::SQLite | Flavor::SQLServer => {
                    let v = a.add(value.clone());
                    format!("{field} IS DISTINCT FROM {v}")
                }
                Flavor::MySQL => {
                    let v = a.add(value.clone());
                    format!("NOT {field} <=> {v}")
                }
                _ => {
                    // CASE
                    //     WHEN field IS NULL AND value IS NULL THEN 0
                    //     WHEN field IS NOT NULL AND value IS NOT NULL AND field = value THEN 0
                    //     ELSE 1
                    // END = 1
                    let v1 = a.add(value.clone());
                    let v2 = a.add(value.clone());
                    let v3 = a.add(value.clone());
                    format!(
                        "CASE WHEN {field} IS NULL AND {v1} IS NULL THEN 0 WHEN {field} IS NOT NULL AND {v2} IS NOT NULL AND {field} = {v3} THEN 0 ELSE 1 END = 1"
                    )
                }
            };
            a.compile_with_flavor(&fmt, flavor, initial)
        });
        self.var(Arg::Builder(Box::new(b)))
    }

    pub fn is_not_distinct_from(&self, field: &str, value: impl Into<Arg>) -> String {
        if field.is_empty() {
            return String::new();
        }

        let field = field.to_string();
        let value: Arg = value.into();

        let b = CondDynBuilder::new(move |flavor, initial| {
            let mut a = Args {
                flavor,
                ..Args::default()
            };
            let fmt = match flavor {
                Flavor::PostgreSQL | Flavor::SQLite | Flavor::SQLServer => {
                    let v = a.add(value.clone());
                    format!("{field} IS NOT DISTINCT FROM {v}")
                }
                Flavor::MySQL => {
                    let v = a.add(value.clone());
                    format!("{field} <=> {v}")
                }
                _ => {
                    // CASE
                    //     WHEN field IS NULL AND value IS NULL THEN 1
                    //     WHEN field IS NOT NULL AND value IS NOT NULL AND field = value THEN 1
                    //     ELSE 0
                    // END = 1
                    let v1 = a.add(value.clone());
                    let v2 = a.add(value.clone());
                    let v3 = a.add(value.clone());
                    format!(
                        "CASE WHEN {field} IS NULL AND {v1} IS NULL THEN 1 WHEN {field} IS NOT NULL AND {v2} IS NOT NULL AND {field} = {v3} THEN 1 ELSE 0 END = 1"
                    )
                }
            };
            a.compile_with_flavor(&fmt, flavor, initial)
        });
        self.var(Arg::Builder(Box::new(b)))
    }
}

/// Internal helper for flavor-dependent conditional expressions.
#[derive(Clone)]
struct CondDynBuilder {
    f: Rc<CondBuildFn>,
}

type CondBuildFn = dyn Fn(Flavor, &[Arg]) -> (String, Vec<Arg>);

impl CondDynBuilder {
    fn new(f: impl Fn(Flavor, &[Arg]) -> (String, Vec<Arg>) + 'static) -> Self {
        Self { f: Rc::new(f) }
    }
}

impl Default for Cond {
    fn default() -> Self {
        Self::new()
    }
}

impl Builder for CondDynBuilder {
    fn build_with_flavor(&self, flavor: Flavor, initial_arg: &[Arg]) -> (String, Vec<Arg>) {
        (self.f)(flavor, initial_arg)
    }

    fn flavor(&self) -> Flavor {
        Flavor::default()
    }
}