mool 0.2.0

A source-first Rust database toolkit for typed SQL queries, migrations, and model metadata
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
//! Table, CTE, and subquery sources and projected source columns.
use std::fmt;
use std::hash::{Hash, Hasher};
use std::marker::PhantomData;
use std::ops::Deref;
use std::sync::Arc;

use super::expr::{ColumnRef, Expr, ExprNode, IntoExpr, IntoSourceColumn, OrderExpr, Predicate};
use super::handles::{ColumnOwner, Table};
use super::render::SelectModel;
use super::scope::QueryScope;
use super::traits::{IntoSourceMeta, IntoTableSource, Projectable};
use super::validate::{source_key, table_name};

/// Typed common table expression source.
pub struct Cte<T>
where
    T: Projectable,
{
    pub(super) data: Arc<CteData>,
    pub(super) columns: <T as Projectable>::Columns,
    pub(super) _marker: PhantomData<fn() -> T>,
}

/// Typed subquery source.
pub struct Subquery<T>
where
    T: Projectable,
{
    pub(super) data: Arc<SubqueryData>,
    pub(super) columns: <T as Projectable>::Columns,
    pub(super) _marker: PhantomData<fn() -> T>,
}

#[doc(hidden)]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct SourceColumnRef {
    pub(super) source: Source,
    pub(super) owner: Option<Source>,
    pub(super) name: Arc<str>,
}

/// Typed projected output column generated from a CTE or subquery row shape.
pub struct ProjectedColumn<T> {
    pub(super) data: Arc<SourceColumnData>,
    _marker: PhantomData<fn() -> T>,
}

/// One-column projection picked from a CTE or subquery source.
pub struct Picked<T> {
    pub(super) data: Arc<PickedData>,
    pub(super) _marker: PhantomData<fn() -> T>,
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub(super) struct PickedData {
    pub(super) source: Source,
    pub(super) column: SourceColumnRef,
}

/// Source handle passed to generated projection metadata.
#[derive(Clone)]
pub struct ProjectionSource {
    pub(super) source: Source,
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub(super) struct SourceColumnData {
    pub(super) source: Source,
    pub(super) name: Arc<str>,
}

#[derive(Clone)]
pub enum Source {
    #[doc(hidden)]
    Table(Table),
    #[doc(hidden)]
    Cte(CteSource),
    #[doc(hidden)]
    Subquery(SubquerySource),
}

#[derive(Clone)]
pub struct CteSource {
    pub(super) data: Arc<CteData>,
}

#[derive(Clone)]
pub struct SubquerySource {
    pub(super) data: Arc<SubqueryData>,
}

pub(super) struct CteData {
    pub(super) name: Arc<str>,
    pub(super) scope: QueryScope,
    pub(super) model: SelectModel,
    pub(super) slice: Option<(usize, usize)>,
    pub(super) columns: Vec<String>,
}

pub(super) struct SubqueryData {
    pub(super) name: Arc<str>,
    pub(super) scope: QueryScope,
    pub(super) model: SelectModel,
    pub(super) slice: Option<(usize, usize)>,
    pub(super) columns: Vec<String>,
}

pub(super) struct SelectSource {
    pub(super) model: SelectModel,
    pub(super) slice: Option<(usize, usize)>,
    pub(super) columns: Vec<String>,
}

/// Typed query source kind exposed through [`SourceMeta`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SourceKind {
    /// A concrete database table source.
    Table,
    /// A common table expression source.
    Cte,
    /// An inline subquery source.
    Subquery,
}

/// Read-only typed query source metadata.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SourceMeta {
    kind: SourceKind,
    name: String,
    schema: Option<String>,
    writable_columns: Vec<String>,
    output_columns: Vec<String>,
}

impl fmt::Debug for Source {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Source::Table(table) => f.debug_tuple("Table").field(table).finish(),
            Source::Cte(cte) => f.debug_tuple("Cte").field(&cte.data.name).finish(),
            Source::Subquery(subquery) => f
                .debug_tuple("Subquery")
                .field(&subquery.data.name)
                .finish(),
        }
    }
}

impl PartialEq for Source {
    fn eq(&self, other: &Self) -> bool {
        source_key(self) == source_key(other)
    }
}

impl Eq for Source {}

impl Hash for Source {
    fn hash<H: Hasher>(&self, state: &mut H) {
        source_key(self).hash(state);
    }
}

impl Source {
    fn column_owner(&self) -> ColumnOwner {
        match self {
            Source::Table(table) => ColumnOwner::Root(table.clone()),
            Source::Cte(cte) => ColumnOwner::Source(cte.data.name.clone()),
            Source::Subquery(subquery) => ColumnOwner::Source(subquery.data.name.clone()),
        }
    }
}

impl fmt::Debug for CteSource {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("CteSource").field(&self.data.name).finish()
    }
}

impl PartialEq for CteSource {
    fn eq(&self, other: &Self) -> bool {
        self.data.name == other.data.name
    }
}

impl Eq for CteSource {}

impl Hash for CteSource {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.data.name.hash(state);
    }
}

impl fmt::Debug for SubquerySource {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("SubquerySource")
            .field(&self.data.name)
            .finish()
    }
}

impl PartialEq for SubquerySource {
    fn eq(&self, other: &Self) -> bool {
        self.data.name == other.data.name
    }
}

impl Eq for SubquerySource {}

impl Hash for SubquerySource {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.data.name.hash(state);
    }
}

impl<T> Clone for Cte<T>
where
    T: Projectable,
{
    fn clone(&self) -> Self {
        Self {
            data: self.data.clone(),
            columns: self.columns.clone(),
            _marker: PhantomData,
        }
    }
}

impl<T> fmt::Debug for Cte<T>
where
    T: Projectable,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("Cte").field(&self.data.name).finish()
    }
}

impl<T> Clone for Subquery<T>
where
    T: Projectable,
{
    fn clone(&self) -> Self {
        Self {
            data: self.data.clone(),
            columns: self.columns.clone(),
            _marker: PhantomData,
        }
    }
}

impl<T> fmt::Debug for Subquery<T>
where
    T: Projectable,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("Subquery").field(&self.data.name).finish()
    }
}

impl<T> Clone for ProjectedColumn<T> {
    fn clone(&self) -> Self {
        Self {
            data: self.data.clone(),
            _marker: PhantomData,
        }
    }
}

impl<T> fmt::Debug for ProjectedColumn<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ProjectedColumn")
            .field("source", &self.data.source)
            .field("name", &self.data.name)
            .finish()
    }
}

impl<T> PartialEq for ProjectedColumn<T> {
    fn eq(&self, other: &Self) -> bool {
        self.data == other.data
    }
}

impl<T> Eq for ProjectedColumn<T> {}

impl<T> Hash for ProjectedColumn<T> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.data.hash(state);
    }
}

impl<T> Clone for Picked<T> {
    fn clone(&self) -> Self {
        Self {
            data: self.data.clone(),
            _marker: PhantomData,
        }
    }
}

impl<T> fmt::Debug for Picked<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Picked")
            .field("source", &self.data.source)
            .field("column", &self.data.column)
            .finish()
    }
}

impl fmt::Debug for ProjectionSource {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("ProjectionSource")
            .field(&self.source)
            .finish()
    }
}

impl<T> Cte<T>
where
    T: Projectable,
{
    /// Returns typed projected columns for this CTE row shape.
    pub fn cols(&self) -> <T as Projectable>::Columns {
        self.columns.clone()
    }

    /// Picks one projected column from this CTE for an expression such as `IN`.
    pub fn pick<U>(&self, col: &ProjectedColumn<U>) -> Picked<U> {
        Picked::new(Source::Cte(self.as_source()), col.clone())
    }

    pub(super) fn as_source(&self) -> CteSource {
        CteSource {
            data: self.data.clone(),
        }
    }
}

impl<T> Subquery<T>
where
    T: Projectable,
{
    /// Returns typed projected columns for this subquery row shape.
    pub fn cols(&self) -> <T as Projectable>::Columns {
        self.columns.clone()
    }

    /// Picks one projected column from this subquery for an expression such as `IN`.
    pub fn pick<U>(&self, col: &ProjectedColumn<U>) -> Picked<U> {
        Picked::new(Source::Subquery(self.as_source()), col.clone())
    }

    pub(super) fn as_source(&self) -> SubquerySource {
        SubquerySource {
            data: self.data.clone(),
        }
    }
}

impl SourceMeta {
    pub(super) fn table(table: &Table) -> Self {
        let writable_columns = match table.data.columns.as_deref() {
            Some(columns) => columns.to_vec(),
            None => Vec::new(),
        };
        Self {
            kind: SourceKind::Table,
            name: table.data.name.to_string(),
            schema: table.data.schema.as_deref().map(str::to_string),
            writable_columns,
            output_columns: Vec::new(),
        }
    }

    pub(super) fn cte(source: &CteSource) -> Self {
        Self {
            kind: SourceKind::Cte,
            name: source.data.name.to_string(),
            schema: None,
            writable_columns: Vec::new(),
            output_columns: source.data.columns.clone(),
        }
    }

    pub(super) fn subquery(source: &SubquerySource) -> Self {
        Self {
            kind: SourceKind::Subquery,
            name: source.data.name.to_string(),
            schema: None,
            writable_columns: Vec::new(),
            output_columns: source.data.columns.clone(),
        }
    }

    /// Returns the source kind.
    pub fn kind(&self) -> SourceKind {
        self.kind
    }

    /// Returns the source name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Returns the schema name for table sources when one exists.
    pub fn schema(&self) -> Option<&str> {
        self.schema.as_deref()
    }

    /// Returns the schema-qualified source name when a schema exists.
    pub fn qualified_name(&self) -> String {
        table_name(self.schema(), &self.name)
    }

    /// Returns known writable column names for table sources.
    pub fn writable_columns(&self) -> &[String] {
        &self.writable_columns
    }

    /// Returns projected output column names for CTE and subquery sources.
    pub fn output_columns(&self) -> &[String] {
        &self.output_columns
    }
}

impl<T> Deref for Cte<T>
where
    T: Projectable,
{
    type Target = <T as Projectable>::Columns;

    fn deref(&self) -> &Self::Target {
        &self.columns
    }
}

impl<T> Deref for Subquery<T>
where
    T: Projectable,
{
    type Target = <T as Projectable>::Columns;

    fn deref(&self) -> &Self::Target {
        &self.columns
    }
}

impl<T> ProjectedColumn<T> {
    fn new(source: Source, name: &'static str) -> Self {
        Self {
            data: Arc::new(SourceColumnData {
                source,
                name: Arc::from(name),
            }),
            _marker: PhantomData,
        }
    }

    /// Equality predicate.
    pub fn eq<R>(&self, rhs: R) -> Predicate
    where
        R: IntoExpr<T>,
    {
        self.compare("=", rhs)
    }

    /// Inequality predicate.
    pub fn ne<R>(&self, rhs: R) -> Predicate
    where
        R: IntoExpr<T>,
    {
        self.compare("!=", rhs)
    }

    /// Less-than predicate.
    pub fn lt<R>(&self, rhs: R) -> Predicate
    where
        R: IntoExpr<T>,
    {
        self.compare("<", rhs)
    }

    /// Less-than-or-equal predicate.
    pub fn lte<R>(&self, rhs: R) -> Predicate
    where
        R: IntoExpr<T>,
    {
        self.compare("<=", rhs)
    }

    /// Greater-than predicate.
    pub fn gt<R>(&self, rhs: R) -> Predicate
    where
        R: IntoExpr<T>,
    {
        self.compare(">", rhs)
    }

    /// Greater-than-or-equal predicate.
    pub fn gte<R>(&self, rhs: R) -> Predicate
    where
        R: IntoExpr<T>,
    {
        self.compare(">=", rhs)
    }

    /// Ascending order expression.
    pub fn asc(&self) -> OrderExpr {
        self.expr().asc()
    }

    /// Descending order expression.
    pub fn desc(&self) -> OrderExpr {
        self.expr().desc()
    }

    fn compare<R>(&self, op: &'static str, rhs: R) -> Predicate
    where
        R: IntoExpr<T>,
    {
        Predicate::new(ExprNode::Binary {
            left: Box::new(self.expr().node),
            op,
            right: Box::new(rhs.into_expr().node),
        })
    }

    fn expr(&self) -> Expr<T> {
        Expr::new(ExprNode::Column(ColumnRef {
            owner: self.data.source.column_owner(),
            name: self.data.name.clone(),
        }))
    }
}

impl ProjectedColumn<String> {
    /// SQL LIKE predicate for text source columns.
    pub fn like<R>(&self, rhs: R) -> Predicate
    where
        R: IntoExpr<String>,
    {
        self.compare("LIKE", rhs)
    }

    /// SQL ILIKE predicate for text source columns.
    pub fn ilike<R>(&self, rhs: R) -> Predicate
    where
        R: IntoExpr<String>,
    {
        self.compare("ILIKE", rhs)
    }
}

impl<T> IntoExpr<T> for ProjectedColumn<T> {
    fn into_expr(self) -> Expr<T> {
        self.expr()
    }
}

impl<T> IntoExpr<T> for &ProjectedColumn<T> {
    fn into_expr(self) -> Expr<T> {
        self.expr()
    }
}

impl<T> Picked<T> {
    pub(super) fn new(source: Source, col: ProjectedColumn<T>) -> Self {
        Self {
            data: Arc::new(PickedData {
                source: source.clone(),
                column: SourceColumnRef {
                    source,
                    owner: Some(col.data.source.clone()),
                    name: col.data.name.clone(),
                },
            }),
            _marker: PhantomData,
        }
    }
}

impl ProjectionSource {
    pub(super) fn new(source: Source) -> Self {
        Self { source }
    }

    /// Returns a projected output column for generated source column structs.
    pub fn col<T>(&self, name: &'static str) -> ProjectedColumn<T> {
        ProjectedColumn::new(self.source.clone(), name)
    }
}

impl<T> IntoSourceColumn<T> for Picked<T> {
    fn into_source_column(self) -> SourceColumnRef {
        self.data.column.clone()
    }
}

impl<T> IntoSourceColumn<T> for &Picked<T> {
    fn into_source_column(self) -> SourceColumnRef {
        self.data.column.clone()
    }
}

impl<T> IntoTableSource for Cte<T>
where
    T: Projectable,
{
    fn into_table_source(self) -> Source {
        Source::Cte(self.as_source())
    }
}

impl<T> IntoTableSource for &Cte<T>
where
    T: Projectable,
{
    fn into_table_source(self) -> Source {
        Source::Cte(self.as_source())
    }
}

impl<T> IntoTableSource for Subquery<T>
where
    T: Projectable,
{
    fn into_table_source(self) -> Source {
        Source::Subquery(self.as_source())
    }
}

impl<T> IntoTableSource for &Subquery<T>
where
    T: Projectable,
{
    fn into_table_source(self) -> Source {
        Source::Subquery(self.as_source())
    }
}

impl<T> IntoSourceMeta for Cte<T>
where
    T: Projectable,
{
    fn source_meta(&self) -> SourceMeta {
        SourceMeta::cte(&self.as_source())
    }
}

impl<T> IntoSourceMeta for &Cte<T>
where
    T: Projectable,
{
    fn source_meta(&self) -> SourceMeta {
        SourceMeta::cte(&self.as_source())
    }
}

impl<T> IntoSourceMeta for Subquery<T>
where
    T: Projectable,
{
    fn source_meta(&self) -> SourceMeta {
        SourceMeta::subquery(&self.as_source())
    }
}

impl<T> IntoSourceMeta for &Subquery<T>
where
    T: Projectable,
{
    fn source_meta(&self) -> SourceMeta {
        SourceMeta::subquery(&self.as_source())
    }
}