drizzle-core 0.4.0

A type-safe SQL query builder for Rust
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
//! Typed derived-table projections.
//!
//! A [`Derived`] value is a complete SELECT used as a named source
//! (`(SELECT ...) AS "name"`) in another query's FROM or JOIN. It exposes
//! only the columns the SELECT returns, as typed [`DerivedField`]s. Dialect
//! builders create one with `.alias(name)` after checking the query is
//! complete.

use core::marker::PhantomData;

use crate::expr::{AllScalar, Expr, HasAggStatus, Scalar};
use crate::row::{
    ExprValueType, GroupByIdentity, HasSelectModel, IntoGroupBy, IntoSelectTarget, Scoped,
    SelectCols, SelectStar,
};
use crate::{Cons, Nil, SQL, SQLColumnInfo, SQLParam, SQLSchemaType, SQLTable, Tag, ToSQL, Token};

mod private {
    pub trait Projection {}
    pub trait Selection<'a, V: crate::SQLParam, Schema, Table> {}
    pub trait Output {}
}

/// A complete SELECT used as a named source in another query:
/// `(SELECT ...) AS "name"`.
///
/// Create one with a SELECT builder's `.alias(name)`, where `name` is a
/// [`Tag`] value. Read its columns through [`fields`](Self::fields). Columns
/// of a derived table resolve against its alias, so the scope check treats
/// it like an aliased table.
pub struct Derived<'a, V: SQLParam, Name, Projection, Query> {
    query: Query,
    marker: PhantomData<(&'a (), V, Name, Projection)>,
}

impl<'a, V, Name, Projection, Query> Derived<'a, V, Name, Projection, Query>
where
    V: SQLParam,
    Name: Tag,
    Projection: DerivedProjection<Name>,
{
    /// Creates a derived source without checking its query.
    ///
    /// # Safety
    ///
    /// `query` must select exactly the columns described by `Projection`, in
    /// the same order, and must already satisfy the dialect builder's
    /// aggregate rules. Its scope is checked where the derived source is
    /// used, through `Query`'s [`ExprSources`](crate::expr::ExprSources).
    #[doc(hidden)]
    #[track_caller]
    pub unsafe fn new_unchecked(query: Query) -> Self {
        Projection::validate();
        Self {
            query,
            marker: PhantomData,
        }
    }

    /// Returns the underlying query.
    pub const fn query(&self) -> &Query {
        &self.query
    }

    /// Returns the underlying query by value.
    pub fn into_query(self) -> Query {
        self.query
    }

    /// Returns the typed columns of this source, each rendered as
    /// `"name"."column"`.
    pub fn fields(&self) -> Projection::Fields
    where
        Name: Tag,
        Projection: DerivedProjection<Name>,
    {
        Projection::fields()
    }
}

impl<'a, V: SQLParam, Name, Projection, Query: Clone> Clone
    for Derived<'a, V, Name, Projection, Query>
{
    fn clone(&self) -> Self {
        Self {
            query: self.query.clone(),
            marker: PhantomData,
        }
    }
}

impl<'a, V, Name, Projection, Query> ToSQL<'a, V> for Derived<'a, V, Name, Projection, Query>
where
    V: SQLParam,
    Name: Tag,
    Query: ToSQL<'a, V>,
{
    fn to_sql(&self) -> SQL<'a, V> {
        self.query
            .to_sql()
            .parens()
            .push(Token::AS)
            .append(SQL::table(crate::TableRef::sql(Name::NAME, &[])))
    }

    fn into_sql(self) -> SQL<'a, V> {
        self.query
            .into_sql()
            .parens()
            .push(Token::AS)
            .append(SQL::table(crate::TableRef::sql(Name::NAME, &[])))
    }
}

// A derived source is looked up in scope by its alias name.
impl<V: SQLParam, Name, Projection, Query: crate::expr::ExprSources> crate::scope::ScopeEntry
    for Derived<'_, V, Name, Projection, Query>
{
    type Key = crate::scope::AliasKey<Name>;
    type Nullable = crate::expr::NonNull;
    type Sources = Query::Sources;
}

impl<'a, V, Name, Projection, Query> HasSelectModel for Derived<'a, V, Name, Projection, Query>
where
    V: SQLParam,
    Name: Tag,
    Projection: DerivedProjection<Name>,
{
    type SelectModel = Projection::Row;

    const COLUMN_COUNT: usize = Projection::COLUMN_COUNT;
}

/// Maps a SELECT projection to the fields and row exposed by a derived source.
#[doc(hidden)]
pub trait DerivedProjection<Name: Tag>: private::Projection {
    /// The typed columns returned by [`Derived::fields`].
    type Fields;
    /// The row type of `SELECT *` from the derived source.
    type Row;

    /// Number of columns.
    const COLUMN_COUNT: usize;

    /// Checks the projection at construction time.
    ///
    /// # Panics
    ///
    /// Implementations panic when two columns share an output name.
    fn validate() {}

    /// Builds the typed columns.
    fn fields() -> Self::Fields;
}

/// Select markers whose query can become a derived source.
///
/// The single-table `SELECT *` implementation deliberately matches only an
/// exact one-table scope. After a join, `SELECT *` contains more columns and
/// cannot soundly expose the last joined table as its complete projection.
#[doc(hidden)]
pub trait DerivedSelection<'a, V: SQLParam, Schema, Table>:
    private::Selection<'a, V, Schema, Table>
{
    type Projection;
}

impl<'a, V, Schema, Table, Used> DerivedSelection<'a, V, Schema, Table>
    for Scoped<SelectStar, Cons<Table, Nil>, Used>
where
    V: SQLParam + 'a,
    Schema: SQLSchemaType,
    Table: SQLTable<'a, Schema, V>,
{
    type Projection = TableProjection<'a, V, Schema, Table>;
}

impl<'a, V, Schema, Table, Used> private::Selection<'a, V, Schema, Table>
    for Scoped<SelectStar, Cons<Table, Nil>, Used>
where
    V: SQLParam + 'a,
    Schema: SQLSchemaType,
    Table: SQLTable<'a, Schema, V>,
{
}

impl<'a, V, Schema, Name, Projection, Query, Used>
    DerivedSelection<'a, V, Schema, Derived<'a, V, Name, Projection, Query>>
    for Scoped<SelectStar, Cons<Derived<'a, V, Name, Projection, Query>, Nil>, Used>
where
    V: SQLParam,
    Name: Tag,
    Projection: DerivedProjection<Name>,
{
    type Projection = Projection;
}

impl<'a, V, Schema, Name, Projection, Query, Used>
    private::Selection<'a, V, Schema, Derived<'a, V, Name, Projection, Query>>
    for Scoped<SelectStar, Cons<Derived<'a, V, Name, Projection, Query>, Nil>, Used>
where
    V: SQLParam,
    Name: Tag,
    Projection: DerivedProjection<Name>,
{
}

impl<'a, V, Schema, Table, Columns, Scope, Used> DerivedSelection<'a, V, Schema, Table>
    for Scoped<SelectCols<Columns>, Scope, Used>
where
    V: SQLParam,
{
    type Projection = Self;
}

impl<'a, V, Schema, Table, Columns, Scope, Used> private::Selection<'a, V, Schema, Table>
    for Scoped<SelectCols<Columns>, Scope, Used>
where
    V: SQLParam,
{
}

impl<Name, Marker, Scope, Used> DerivedProjection<Name> for Scoped<Marker, Scope, Used>
where
    Name: Tag,
    Marker: DerivedProjection<Name>,
{
    type Fields = Marker::Fields;
    type Row = Marker::Row;

    const COLUMN_COUNT: usize = Marker::COLUMN_COUNT;

    fn validate() {
        Marker::validate();
    }

    fn fields() -> Self::Fields {
        Marker::fields()
    }
}

impl<Marker, Scope, Used> private::Projection for Scoped<Marker, Scope, Used> where
    Marker: private::Projection
{
}

/// Projection marker used when a dialect has proven that `SELECT *` comes from
/// one base table.
#[doc(hidden)]
pub struct TableProjection<'a, V: SQLParam, Schema, Table>(PhantomData<(&'a (), V, Schema, Table)>);

impl<V: SQLParam, Schema, Table> private::Projection for TableProjection<'_, V, Schema, Table> {}

impl<'a, V, Schema, Name, Table> DerivedProjection<Name> for TableProjection<'a, V, Schema, Table>
where
    V: SQLParam + 'a,
    Schema: SQLSchemaType,
    Name: Tag + 'static,
    Table: SQLTable<'a, Schema, V> + HasSelectModel,
    Table::Aliased<Name>: HasSelectModel<SelectModel = Table::SelectModel>,
{
    type Fields = Table::Aliased<Name>;
    type Row = Table::SelectModel;

    const COLUMN_COUNT: usize = Table::COLUMN_COUNT;

    fn fields() -> Self::Fields {
        Table::alias::<Name>()
    }
}

/// A column of a derived source named `Name`, rendered as
/// `"name"."output"`.
///
/// `Output` is the selected expression (a column or a named expression),
/// which supplies the output name, SQL type and nullability.
pub struct DerivedField<Name, Output>(PhantomData<(Name, Output)>);

impl<Name, Output> Copy for DerivedField<Name, Output> {}

impl<Name, Output> Clone for DerivedField<Name, Output> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<Name, Output> Default for DerivedField<Name, Output> {
    fn default() -> Self {
        Self(PhantomData)
    }
}

impl<'a, V, Name, Output> ToSQL<'a, V> for DerivedField<Name, Output>
where
    V: SQLParam,
    Name: Tag,
    Output: ProjectionOutput,
{
    fn to_sql(&self) -> SQL<'a, V> {
        SQL::ident(Name::NAME)
            .push(Token::DOT)
            .append(SQL::ident(Output::output_name()))
    }
}

impl<'a, V, Name, Output> Expr<'a, V> for DerivedField<Name, Output>
where
    V: SQLParam + 'a,
    Name: Tag,
    Output: ProjectionOutput + Expr<'a, V>,
{
    type SQLType = Output::SQLType;
    type Nullable = Output::Nullable;
    type Aggregate = Scalar;
}

impl<Name, Output> ExprValueType for DerivedField<Name, Output>
where
    Name: Tag,
    Output: ProjectionOutput + ExprValueType,
{
    type ValueType = Output::ValueType;
}

impl<Name, Output> IntoSelectTarget for DerivedField<Name, Output>
where
    Name: Tag,
    Output: ProjectionOutput + ExprValueType,
{
    type Marker = SelectCols<(Self,)>;
}

impl<Name, Output> HasAggStatus for DerivedField<Name, Output>
where
    Name: Tag,
    Output: ProjectionOutput,
{
    type Status = AllScalar;
}

impl<Name, Output> GroupByIdentity for DerivedField<Name, Output>
where
    Name: Tag,
    Output: ProjectionOutput,
{
    type Identity = Self;
}

impl<'a, V, Name, Output, Projection, Query>
    crate::traits::ColumnOf<Derived<'a, V, Name, Projection, Query>> for DerivedField<Name, Output>
where
    V: SQLParam,
{
}

// A derived field reads the derived source named `Name`.
impl<Name, Output> crate::expr::ExprSources for DerivedField<Name, Output> {
    type Sources = crate::scope::Src<crate::scope::AliasKey<Name>>;
}

impl<'a, V, Name, Output> IntoGroupBy<'a, V> for DerivedField<Name, Output>
where
    V: SQLParam + 'a,
    Name: Tag,
    Output: ProjectionOutput,
{
    type Columns = Cons<Self, Nil>;
}

/// Supplies the static output name for one SELECT expression.
#[doc(hidden)]
pub trait ProjectionOutput: private::Output {
    /// The column's name in the derived table.
    fn output_name() -> &'static str;
}

impl<Column> private::Output for Column where Column: SQLColumnInfo + Default {}

impl<Column> ProjectionOutput for Column
where
    Column: SQLColumnInfo + Default,
{
    fn output_name() -> &'static str {
        Column::default().name()
    }
}

impl<E, Name> ProjectionOutput for crate::expr::NamedExpr<E, Name>
where
    Name: Tag,
{
    fn output_name() -> &'static str {
        Name::NAME
    }
}

impl<E, Name> private::Output for crate::expr::NamedExpr<E, Name> where Name: Tag {}

impl<Name, Output> ProjectionOutput for DerivedField<Name, Output>
where
    Name: Tag,
    Output: ProjectionOutput,
{
    fn output_name() -> &'static str {
        Output::output_name()
    }
}

impl<Name, Output> private::Output for DerivedField<Name, Output>
where
    Name: Tag,
    Output: ProjectionOutput,
{
}

macro_rules! impl_derived_projection_tuple {
    ($($output:ident),+; $($_index:tt),+) => {
        impl<Name, $($output),+> DerivedProjection<Name> for SelectCols<($($output,)+)>
        where
            Name: Tag,
            $($output: ProjectionOutput + ExprValueType,)+
        {
            type Fields = ($(DerivedField<Name, $output>,)+);
            type Row = ($(<$output as ExprValueType>::ValueType,)+);

            const COLUMN_COUNT: usize = impl_derived_projection_tuple!(@count $($output),+);

            fn validate() {
                let names = [$(<$output as ProjectionOutput>::output_name(),)+];
                let mut left = 0;
                while left < names.len() {
                    let mut right = left + 1;
                    while right < names.len() {
                        assert!(
                            names[left] != names[right],
                            "derived projection contains duplicate output name `{}`; name one expression with `.named::<Tag>()`",
                            names[left],
                        );
                        right += 1;
                    }
                    left += 1;
                }
            }

            fn fields() -> Self::Fields {
                ($(DerivedField::<Name, $output>::default(),)+)
            }
        }

        impl<$($output),+> private::Projection for SelectCols<($($output,)+)>
        where
            $($output: ProjectionOutput + ExprValueType,)+
        {
        }
    };
    (@count $head:ident $(,$tail:ident)*) => {
        1usize $(+ { let _ = stringify!($tail); 1usize })*
    };
}

with_col_sizes_8!(impl_derived_projection_tuple);

#[cfg(any(
    feature = "col16",
    feature = "col32",
    feature = "col64",
    feature = "col128",
    feature = "col200"
))]
with_col_sizes_16!(impl_derived_projection_tuple);

#[cfg(any(
    feature = "col32",
    feature = "col64",
    feature = "col128",
    feature = "col200"
))]
with_col_sizes_32!(impl_derived_projection_tuple);

#[cfg(any(feature = "col64", feature = "col128", feature = "col200"))]
with_col_sizes_64!(impl_derived_projection_tuple);

#[cfg(any(feature = "col128", feature = "col200"))]
with_col_sizes_128!(impl_derived_projection_tuple);

#[cfg(feature = "col200")]
with_col_sizes_200!(impl_derived_projection_tuple);

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{Dialect, SQLiteDialect};

    #[derive(Clone, Debug)]
    struct TestParam;

    impl SQLParam for TestParam {
        const DIALECT: Dialect = Dialect::SQLite;
        type DialectMarker = SQLiteDialect;
    }

    struct Alias;

    impl Tag for Alias {
        const NAME: &'static str = "alias";
    }

    struct First;
    struct Second;

    impl private::Output for First {}
    impl private::Output for Second {}

    impl ProjectionOutput for First {
        fn output_name() -> &'static str {
            "duplicate"
        }
    }

    impl ProjectionOutput for Second {
        fn output_name() -> &'static str {
            "duplicate"
        }
    }

    impl ExprValueType for First {
        type ValueType = i32;
    }

    impl ExprValueType for Second {
        type ValueType = i32;
    }

    #[test]
    #[should_panic(expected = "duplicate output name")]
    fn duplicate_projection_names_are_rejected() {
        let _: Derived<'_, TestParam, Alias, SelectCols<(First, Second)>, ()> =
            // SAFETY: This test exercises projection-name validation before
            // the query is ever rendered or decoded.
            unsafe { Derived::new_unchecked(()) };
    }
}