drizzle-core 0.1.12

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
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
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
//! Type-safe aggregate functions.
//!
//! These functions return expressions marked as aggregates, which can be used
//! to enforce GROUP BY rules at compile time.
//!
//! # Type Safety
//!
//! - `sum`, `avg`: Require `Numeric` types (Int, `BigInt`, Float, Double)
//! - `count`: Works with any type
//! - `min`, `max`: Work with any type (ordered types in SQL)

use crate::dialect::DialectTypes;
use crate::sql::SQL;
use crate::traits::SQLParam;
use crate::types::{Array, Numeric};
use crate::{PostgresDialect, SQLiteDialect};
use drizzle_types::postgres::types::{
    Boolean as PgBoolean, Float4, Float8, Int2, Int4, Int8, Numeric as PgNumeric,
};
use drizzle_types::sqlite::types::{
    Integer as SqliteInteger, Numeric as SqliteNumeric, Real as SqliteReal,
};

use super::{Agg, Expr, NonNull, Null, SQLExpr, Scalar};

// =============================================================================
// Dialect Aggregate Policy
// =============================================================================

/// Dialect-specific aggregate output mapping.
///
/// Keeps aggregate output typing in one place so all aggregate functions
/// follow the same per-dialect policy.
#[diagnostic::on_unimplemented(
    message = "no aggregate policy for `{Self}` on this dialect",
    label = "aggregate result type is not defined for this SQL type/dialect"
)]
pub trait AggregatePolicy<D>: Numeric {
    type Sum: crate::types::DataType;
    type Avg: crate::types::DataType;
}

#[diagnostic::on_unimplemented(
    message = "no statistical aggregate policy for `{Self}` on this dialect",
    label = "stddev/variance result type is not defined for this SQL type/dialect"
)]
pub trait StatisticalAggregatePolicy<D>: Numeric {
    type StddevPop: crate::types::DataType;
    type StddevSamp: crate::types::DataType;
    type VarPop: crate::types::DataType;
    type VarSamp: crate::types::DataType;
}

#[diagnostic::on_unimplemented(
    message = "boolean aggregates are not supported for `{Self}` on this dialect",
    label = "use a boolean expression with a dialect that supports BOOL_AND/BOOL_OR"
)]
pub trait BooleanAggregatePolicy<D>: crate::types::DataType {}

#[diagnostic::on_unimplemented(
    message = "this aggregate is not available for this dialect",
    label = "use a dialect-specific alternative"
)]
pub trait PostgresAggregateSupport {}

#[diagnostic::on_unimplemented(
    message = "this aggregate is not available for this dialect",
    label = "use a dialect-specific alternative"
)]
pub trait SQLiteAggregateSupport {}

#[diagnostic::on_unimplemented(
    message = "no COUNT return type defined for this dialect",
    label = "COUNT result type is not configured for this dialect marker"
)]
pub trait CountPolicy {
    /// The integer type returned by COUNT (e.g. Integer on `SQLite`, Int8 on `PostgreSQL`).
    type Count: crate::types::DataType;
}

mod count_arg_private {
    use super::SQLParam;

    pub trait Sealed<'a, V: SQLParam> {}

    impl<'a, V: SQLParam> Sealed<'a, V> for () {}

    impl<'a, V, E> Sealed<'a, V> for E
    where
        V: SQLParam + 'a,
        E: crate::traits::ToSQL<'a, V> + crate::row::ExprValueType,
    {
    }
}

/// Argument accepted by [`count`].
///
/// This trait is sealed and exists only to support `count(())` for `COUNT(*)`
/// and `count(expr)` for `COUNT(expr)` without making `()` a general SQL
/// expression.
#[doc(hidden)]
pub trait CountArg<'a, V: SQLParam>: count_arg_private::Sealed<'a, V> {
    fn count_sql(self) -> SQL<'a, V>;
}

impl<'a, V: SQLParam + 'a> CountArg<'a, V> for () {
    fn count_sql(self) -> SQL<'a, V> {
        SQL::raw("COUNT(*)")
    }
}

impl<'a, V, E> CountArg<'a, V> for E
where
    V: SQLParam + 'a,
    E: crate::traits::ToSQL<'a, V> + crate::row::ExprValueType,
{
    fn count_sql(self) -> SQL<'a, V> {
        SQL::func("COUNT", self.into_sql().parens_if_subquery())
    }
}

impl CountPolicy for SQLiteDialect {
    type Count = drizzle_types::sqlite::types::Integer;
}

impl CountPolicy for PostgresDialect {
    type Count = drizzle_types::postgres::types::Int8;
}

#[diagnostic::on_unimplemented(
    message = "no floating-point return type defined for this dialect",
    label = "PERCENT_RANK/CUME_DIST result type is not configured for this dialect marker"
)]
pub trait FloatPolicy {
    /// The floating-point type returned by distribution window functions
    /// like `PERCENT_RANK` and `CUME_DIST` (Real on `SQLite`, Float8 on `PostgreSQL`).
    type Float: crate::types::DataType;
}

impl FloatPolicy for SQLiteDialect {
    type Float = drizzle_types::sqlite::types::Real;
}

impl FloatPolicy for PostgresDialect {
    type Float = drizzle_types::postgres::types::Float8;
}

impl AggregatePolicy<SQLiteDialect> for SqliteInteger {
    type Sum = Self;
    type Avg = SqliteReal;
}
impl AggregatePolicy<SQLiteDialect> for SqliteReal {
    type Sum = Self;
    type Avg = Self;
}
impl AggregatePolicy<SQLiteDialect> for SqliteNumeric {
    type Sum = Self;
    type Avg = SqliteReal;
}
impl AggregatePolicy<SQLiteDialect> for drizzle_types::sqlite::types::Any {
    type Sum = Self;
    type Avg = SqliteReal;
}

impl StatisticalAggregatePolicy<PostgresDialect> for Int2 {
    type StddevPop = Float8;
    type StddevSamp = Float8;
    type VarPop = Float8;
    type VarSamp = Float8;
}
impl StatisticalAggregatePolicy<PostgresDialect> for Int4 {
    type StddevPop = Float8;
    type StddevSamp = Float8;
    type VarPop = Float8;
    type VarSamp = Float8;
}
impl StatisticalAggregatePolicy<PostgresDialect> for Int8 {
    type StddevPop = Float8;
    type StddevSamp = Float8;
    type VarPop = Float8;
    type VarSamp = Float8;
}
impl StatisticalAggregatePolicy<PostgresDialect> for Float4 {
    type StddevPop = Float8;
    type StddevSamp = Float8;
    type VarPop = Float8;
    type VarSamp = Float8;
}
impl StatisticalAggregatePolicy<PostgresDialect> for Float8 {
    type StddevPop = Self;
    type StddevSamp = Self;
    type VarPop = Self;
    type VarSamp = Self;
}
impl StatisticalAggregatePolicy<PostgresDialect> for PgNumeric {
    type StddevPop = Float8;
    type StddevSamp = Float8;
    type VarPop = Float8;
    type VarSamp = Float8;
}

impl BooleanAggregatePolicy<PostgresDialect> for PgBoolean {}

impl PostgresAggregateSupport for PostgresDialect {}
impl SQLiteAggregateSupport for SQLiteDialect {}

impl AggregatePolicy<PostgresDialect> for Int2 {
    type Sum = Int8;
    type Avg = Float8;
}
impl AggregatePolicy<PostgresDialect> for Int4 {
    type Sum = Int8;
    type Avg = Float8;
}
impl AggregatePolicy<PostgresDialect> for Int8 {
    type Sum = Self;
    type Avg = Float8;
}
impl AggregatePolicy<PostgresDialect> for Float4 {
    type Sum = Float8;
    type Avg = Float8;
}
impl AggregatePolicy<PostgresDialect> for Float8 {
    type Sum = Self;
    type Avg = Self;
}
impl AggregatePolicy<PostgresDialect> for PgNumeric {
    type Sum = Self;
    type Avg = Self;
}

// =============================================================================
// COUNT
// =============================================================================

/// COUNT aggregate.
///
/// Pass `()` for `COUNT(*)`, or a column/expression for `COUNT(expr)`.
///
/// Returns a `BigInt`, `NonNull` (count is never NULL), Aggregate expression.
///
/// # Example
///
/// ```rust
/// # let _ = r####"
/// use drizzle_core::expr::count;
///
/// let all_rows = count(());
/// // Generates: COUNT(*)
///
/// let email_count = count(users.email);
/// // Generates: COUNT("users"."email")
/// # "####;
/// ```
pub fn count<'a, V, A>(
    arg: A,
) -> SQLExpr<'a, V, <V::DialectMarker as CountPolicy>::Count, NonNull, Agg>
where
    V: SQLParam + 'a,
    V::DialectMarker: CountPolicy,
    A: CountArg<'a, V>,
{
    SQLExpr::new(arg.count_sql())
}

/// COUNT(DISTINCT expr) - counts distinct non-null values.
///
/// Returns a `BigInt`, `NonNull`, Aggregate expression.
/// Works with any expression type.
pub fn count_distinct<'a, V, E>(
    expr: E,
) -> SQLExpr<'a, V, <V::DialectMarker as CountPolicy>::Count, NonNull, Agg>
where
    V: SQLParam + 'a,
    V::DialectMarker: CountPolicy,
    E: Expr<'a, V>,
{
    SQLExpr::new(SQL::func(
        "COUNT",
        SQL::raw("DISTINCT").append(expr.into_expr_sql()),
    ))
}

// =============================================================================
// SUM
// =============================================================================

/// SUM(expr) - sums numeric values.
///
/// Requires the expression to be `Numeric` (Int, `BigInt`, Float, Double).
/// Result type is dialect-aware.
/// Returns a nullable expression (empty set returns NULL).
///
/// # Type Safety
///
/// ```rust
/// # let _ = r####"
/// // ✅ OK: Numeric column
/// sum(orders.amount);
/// // SQLite: same width for integer sums
/// // PostgreSQL: Int/SmallInt promote to BigInt
///
/// // ❌ Compile error: Text is not Numeric
/// sum(users.name);
/// # "####;
/// ```
pub fn sum<'a, V, E>(
    expr: E,
) -> SQLExpr<'a, V, <E::SQLType as AggregatePolicy<V::DialectMarker>>::Sum, Null, Agg>
where
    V: SQLParam + 'a,
    E: Expr<'a, V>,
    E::SQLType: AggregatePolicy<V::DialectMarker>,
{
    SQLExpr::new(SQL::func("SUM", expr.into_expr_sql()))
}

/// SUM(DISTINCT expr) - sums distinct numeric values.
///
/// Requires the expression to be `Numeric`.
/// Result type is dialect-aware.
pub fn sum_distinct<'a, V, E>(
    expr: E,
) -> SQLExpr<'a, V, <E::SQLType as AggregatePolicy<V::DialectMarker>>::Sum, Null, Agg>
where
    V: SQLParam + 'a,
    E: Expr<'a, V>,
    E::SQLType: AggregatePolicy<V::DialectMarker>,
{
    SQLExpr::new(SQL::func(
        "SUM",
        SQL::raw("DISTINCT").append(expr.into_expr_sql()),
    ))
}

// =============================================================================
// AVG
// =============================================================================

/// AVG(expr) - calculates average of numeric values.
///
/// Requires the expression to be `Numeric`.
/// Always returns Double (SQL standard behavior), nullable.
///
/// # Type Safety
///
/// ```rust
/// # let _ = r####"
/// // ✅ OK: Numeric column
/// avg(products.price);
///
/// // ❌ Compile error: Text is not Numeric
/// avg(users.name);
/// # "####;
/// ```
pub fn avg<'a, V, E>(
    expr: E,
) -> SQLExpr<'a, V, <E::SQLType as AggregatePolicy<V::DialectMarker>>::Avg, Null, Agg>
where
    V: SQLParam + 'a,
    E: Expr<'a, V>,
    E::SQLType: AggregatePolicy<V::DialectMarker>,
{
    SQLExpr::new(SQL::func("AVG", expr.into_expr_sql()))
}

/// AVG(DISTINCT expr) - calculates average of distinct numeric values.
///
/// Requires the expression to be `Numeric`.
pub fn avg_distinct<'a, V, E>(
    expr: E,
) -> SQLExpr<'a, V, <E::SQLType as AggregatePolicy<V::DialectMarker>>::Avg, Null, Agg>
where
    V: SQLParam + 'a,
    E: Expr<'a, V>,
    E::SQLType: AggregatePolicy<V::DialectMarker>,
{
    SQLExpr::new(SQL::func(
        "AVG",
        SQL::raw("DISTINCT").append(expr.into_expr_sql()),
    ))
}

// =============================================================================
// MIN / MAX
// =============================================================================

/// MIN(expr) - finds minimum value.
///
/// Works with any expression type (ordered types in SQL).
/// Preserves the input expression's SQL type.
/// Result is nullable (empty set returns NULL).
///
/// # Example
///
/// ```rust
/// # let _ = r####"
/// use drizzle_core::expr::min;
///
/// let cheapest = min(products.price);
/// // Generates: MIN("products"."price")
/// // Returns the same SQL type as products.price
/// # "####;
/// ```
pub fn min<'a, V, E>(expr: E) -> SQLExpr<'a, V, E::SQLType, Null, Agg>
where
    V: SQLParam + 'a,
    E: Expr<'a, V>,
{
    SQLExpr::new(SQL::func("MIN", expr.into_expr_sql()))
}

/// MAX(expr) - finds maximum value.
///
/// Works with any expression type (ordered types in SQL).
/// Preserves the input expression's SQL type.
/// Result is nullable (empty set returns NULL).
///
/// # Example
///
/// ```rust
/// # let _ = r####"
/// use drizzle_core::expr::max;
///
/// let most_expensive = max(products.price);
/// // Generates: MAX("products"."price")
/// // Returns the same SQL type as products.price
/// # "####;
/// ```
pub fn max<'a, V, E>(expr: E) -> SQLExpr<'a, V, E::SQLType, Null, Agg>
where
    V: SQLParam + 'a,
    E: Expr<'a, V>,
{
    SQLExpr::new(SQL::func("MAX", expr.into_expr_sql()))
}

// =============================================================================
// STATISTICAL FUNCTIONS
// =============================================================================

/// `STDDEV_POP` - population standard deviation.
///
/// Calculates the population standard deviation of numeric values.
/// Requires the expression to be `Numeric`.
/// Returns Double, nullable (empty set returns NULL).
///
/// Note: This function is available in `PostgreSQL`. `SQLite` does not have it built-in.
///
/// # Example
///
/// ```rust
/// # let _ = r####"
/// use drizzle_core::expr::stddev_pop;
///
/// let deviation = stddev_pop(measurements.value);
/// // Generates: STDDEV_POP("measurements"."value")
/// # "####;
/// ```
pub fn stddev_pop<'a, V, E>(
    expr: E,
) -> SQLExpr<
    'a,
    V,
    <E::SQLType as StatisticalAggregatePolicy<V::DialectMarker>>::StddevPop,
    Null,
    Agg,
>
where
    V: SQLParam + 'a,
    E: Expr<'a, V>,
    E::SQLType: StatisticalAggregatePolicy<V::DialectMarker>,
{
    SQLExpr::new(SQL::func("STDDEV_POP", expr.into_expr_sql()))
}

/// `STDDEV_SAMP` / STDDEV - sample standard deviation.
///
/// Calculates the sample standard deviation of numeric values.
/// Requires the expression to be `Numeric`.
/// Returns Double, nullable (empty set returns NULL).
///
/// Note: This function is available in `PostgreSQL`. `SQLite` does not have it built-in.
///
/// # Example
///
/// ```rust
/// # let _ = r####"
/// use drizzle_core::expr::stddev_samp;
///
/// let deviation = stddev_samp(measurements.value);
/// // Generates: STDDEV_SAMP("measurements"."value")
/// # "####;
/// ```
pub fn stddev_samp<'a, V, E>(
    expr: E,
) -> SQLExpr<
    'a,
    V,
    <E::SQLType as StatisticalAggregatePolicy<V::DialectMarker>>::StddevSamp,
    Null,
    Agg,
>
where
    V: SQLParam + 'a,
    E: Expr<'a, V>,
    E::SQLType: StatisticalAggregatePolicy<V::DialectMarker>,
{
    SQLExpr::new(SQL::func("STDDEV_SAMP", expr.into_expr_sql()))
}

/// `VAR_POP` - population variance.
///
/// Calculates the population variance of numeric values.
/// Requires the expression to be `Numeric`.
/// Returns Double, nullable (empty set returns NULL).
///
/// Note: This function is available in `PostgreSQL`. `SQLite` does not have it built-in.
///
/// # Example
///
/// ```rust
/// # let _ = r####"
/// use drizzle_core::expr::var_pop;
///
/// let variance = var_pop(measurements.value);
/// // Generates: VAR_POP("measurements"."value")
/// # "####;
/// ```
pub fn var_pop<'a, V, E>(
    expr: E,
) -> SQLExpr<'a, V, <E::SQLType as StatisticalAggregatePolicy<V::DialectMarker>>::VarPop, Null, Agg>
where
    V: SQLParam + 'a,
    E: Expr<'a, V>,
    E::SQLType: StatisticalAggregatePolicy<V::DialectMarker>,
{
    SQLExpr::new(SQL::func("VAR_POP", expr.into_expr_sql()))
}

/// `VAR_SAMP` / VARIANCE - sample variance.
///
/// Calculates the sample variance of numeric values.
/// Requires the expression to be `Numeric`.
/// Returns Double, nullable (empty set returns NULL).
///
/// Note: This function is available in `PostgreSQL`. `SQLite` does not have it built-in.
///
/// # Example
///
/// ```rust
/// # let _ = r####"
/// use drizzle_core::expr::var_samp;
///
/// let variance = var_samp(measurements.value);
/// // Generates: VAR_SAMP("measurements"."value")
/// # "####;
/// ```
pub fn var_samp<'a, V, E>(
    expr: E,
) -> SQLExpr<'a, V, <E::SQLType as StatisticalAggregatePolicy<V::DialectMarker>>::VarSamp, Null, Agg>
where
    V: SQLParam + 'a,
    E: Expr<'a, V>,
    E::SQLType: StatisticalAggregatePolicy<V::DialectMarker>,
{
    SQLExpr::new(SQL::func("VAR_SAMP", expr.into_expr_sql()))
}

/// VARIANCE - `PostgreSQL` alias for sample variance (`VAR_SAMP`).
pub fn variance<'a, V, E>(
    expr: E,
) -> SQLExpr<'a, V, <E::SQLType as StatisticalAggregatePolicy<V::DialectMarker>>::VarSamp, Null, Agg>
where
    V: SQLParam + 'a,
    E: Expr<'a, V>,
    E::SQLType: StatisticalAggregatePolicy<V::DialectMarker>,
{
    SQLExpr::new(SQL::func("VARIANCE", expr.into_expr_sql()))
}

/// `BOOL_AND` - true if all non-null inputs are true (`PostgreSQL`).
pub fn bool_and<'a, V, E>(
    expr: E,
) -> SQLExpr<'a, V, <V::DialectMarker as DialectTypes>::Bool, Null, Agg>
where
    V: SQLParam + 'a,
    V::DialectMarker: PostgresAggregateSupport,
    E: Expr<'a, V>,
    E::SQLType: BooleanAggregatePolicy<V::DialectMarker>,
{
    SQLExpr::new(SQL::func("BOOL_AND", expr.into_expr_sql()))
}

/// `BOOL_OR` - true if any non-null input is true (`PostgreSQL`).
pub fn bool_or<'a, V, E>(
    expr: E,
) -> SQLExpr<'a, V, <V::DialectMarker as DialectTypes>::Bool, Null, Agg>
where
    V: SQLParam + 'a,
    V::DialectMarker: PostgresAggregateSupport,
    E: Expr<'a, V>,
    E::SQLType: BooleanAggregatePolicy<V::DialectMarker>,
{
    SQLExpr::new(SQL::func("BOOL_OR", expr.into_expr_sql()))
}

/// `JSON_AGG` - aggregates values into a JSON array (`PostgreSQL`).
pub fn json_agg<'a, V, E>(
    expr: E,
) -> SQLExpr<'a, V, <V::DialectMarker as DialectTypes>::Json, Null, Agg>
where
    V: SQLParam + 'a,
    V::DialectMarker: PostgresAggregateSupport,
    E: Expr<'a, V>,
{
    SQLExpr::new(SQL::func("JSON_AGG", expr.into_expr_sql()))
}

/// `JSONB_AGG` - aggregates values into a JSONB array (`PostgreSQL`).
pub fn jsonb_agg<'a, V, E>(
    expr: E,
) -> SQLExpr<'a, V, <V::DialectMarker as DialectTypes>::Jsonb, Null, Agg>
where
    V: SQLParam + 'a,
    V::DialectMarker: PostgresAggregateSupport,
    E: Expr<'a, V>,
{
    SQLExpr::new(SQL::func("JSONB_AGG", expr.into_expr_sql()))
}

/// `ARRAY_AGG` - aggregates values into a SQL array (`PostgreSQL`).
pub fn array_agg<'a, V, E>(expr: E) -> SQLExpr<'a, V, Array<E::SQLType>, Null, Agg>
where
    V: SQLParam + 'a,
    V::DialectMarker: PostgresAggregateSupport,
    E: Expr<'a, V>,
{
    SQLExpr::new(SQL::func("ARRAY_AGG", expr.into_expr_sql()))
}

// =============================================================================
// TOTAL (SQLite)
// =============================================================================

/// TOTAL - sums numeric values, returning 0.0 for empty sets (`SQLite`).
///
/// Unlike `SUM`, which returns NULL for an empty result set,
/// `TOTAL` always returns a floating-point value (0.0 for empty sets).
///
/// # Example
///
/// ```rust
/// # let _ = r####"
/// use drizzle_core::expr::total;
///
/// // SELECT TOTAL(orders.amount)
/// let total_amount = total(orders.amount);
/// # "####;
/// ```
pub fn total<'a, V, E>(
    expr: E,
) -> SQLExpr<'a, V, <V::DialectMarker as DialectTypes>::Double, NonNull, Agg>
where
    V: SQLParam + 'a,
    V::DialectMarker: SQLiteAggregateSupport,
    E: Expr<'a, V>,
    E::SQLType: Numeric,
{
    SQLExpr::new(SQL::func("TOTAL", expr.into_expr_sql()))
}

// =============================================================================
// GROUP_CONCAT / STRING_AGG
// =============================================================================

/// `GROUP_CONCAT` - concatenates values into a string (`SQLite`).
///
/// Returns Text type, nullable.
pub fn group_concat<'a, V, E>(
    expr: E,
) -> SQLExpr<'a, V, <V::DialectMarker as DialectTypes>::Text, Null, Agg>
where
    V: SQLParam + 'a,
    V::DialectMarker: SQLiteAggregateSupport,
    E: Expr<'a, V>,
    E::SQLType: crate::types::Textual,
{
    SQLExpr::new(SQL::func("GROUP_CONCAT", expr.into_expr_sql()))
}

/// `STRING_AGG` - concatenates text values using a delimiter (`PostgreSQL`).
pub fn string_agg<'a, V, E, D>(
    expr: E,
    delimiter: D,
) -> SQLExpr<'a, V, <V::DialectMarker as DialectTypes>::Text, Null, Agg>
where
    V: SQLParam + 'a,
    V::DialectMarker: PostgresAggregateSupport,
    E: Expr<'a, V>,
    E::SQLType: crate::types::Textual,
    D: Expr<'a, V>,
    D::SQLType: crate::types::Textual,
{
    SQLExpr::new(SQL::func(
        "STRING_AGG",
        expr.into_expr_sql()
            .push(crate::Token::COMMA)
            .append(delimiter.into_expr_sql()),
    ))
}

// =============================================================================
// PostgreSQL Aggregate Functions
// =============================================================================

/// EVERY - true if all non-null inputs are true (`PostgreSQL`).
///
/// SQL standard alias for `BOOL_AND`.
///
/// # Example
///
/// ```rust
/// # let _ = r####"
/// use drizzle_core::expr::every;
///
/// // SELECT EVERY(orders.is_paid)
/// let all_paid = every(orders.is_paid);
/// # "####;
/// ```
pub fn every<'a, V, E>(
    expr: E,
) -> SQLExpr<'a, V, <V::DialectMarker as DialectTypes>::Bool, Null, Agg>
where
    V: SQLParam + 'a,
    V::DialectMarker: PostgresAggregateSupport,
    E: Expr<'a, V>,
    E::SQLType: BooleanAggregatePolicy<V::DialectMarker>,
{
    SQLExpr::new(SQL::func("EVERY", expr.into_expr_sql()))
}

/// `JSON_OBJECT_AGG` - aggregates key/value pairs into a JSON object (`PostgreSQL`).
///
/// # Example
///
/// ```rust
/// # let _ = r####"
/// use drizzle_core::expr::json_object_agg;
///
/// // SELECT JSON_OBJECT_AGG(settings.key, settings.value)
/// let obj = json_object_agg(settings.key, settings.value);
/// # "####;
/// ```
pub fn json_object_agg<'a, V, K, Val>(
    key: K,
    value: Val,
) -> SQLExpr<'a, V, <V::DialectMarker as DialectTypes>::Json, Null, Agg>
where
    V: SQLParam + 'a,
    V::DialectMarker: PostgresAggregateSupport,
    K: Expr<'a, V>,
    Val: Expr<'a, V>,
{
    SQLExpr::new(SQL::func(
        "JSON_OBJECT_AGG",
        key.into_expr_sql()
            .push(crate::Token::COMMA)
            .append(value.into_expr_sql()),
    ))
}

/// `JSONB_OBJECT_AGG` - aggregates key/value pairs into a JSONB object (`PostgreSQL`).
///
/// # Example
///
/// ```rust
/// # let _ = r####"
/// use drizzle_core::expr::jsonb_object_agg;
///
/// // SELECT JSONB_OBJECT_AGG(settings.key, settings.value)
/// let obj = jsonb_object_agg(settings.key, settings.value);
/// # "####;
/// ```
pub fn jsonb_object_agg<'a, V, K, Val>(
    key: K,
    value: Val,
) -> SQLExpr<'a, V, <V::DialectMarker as DialectTypes>::Jsonb, Null, Agg>
where
    V: SQLParam + 'a,
    V::DialectMarker: PostgresAggregateSupport,
    K: Expr<'a, V>,
    Val: Expr<'a, V>,
{
    SQLExpr::new(SQL::func(
        "JSONB_OBJECT_AGG",
        key.into_expr_sql()
            .push(crate::Token::COMMA)
            .append(value.into_expr_sql()),
    ))
}

// =============================================================================
// Distinct Wrapper
// =============================================================================

/// DISTINCT - marks an expression as DISTINCT.
///
/// Typically used inside aggregate functions.
pub fn distinct<'a, V, E>(expr: E) -> SQLExpr<'a, V, E::SQLType, E::Nullable, Scalar>
where
    V: SQLParam + 'a,
    E: Expr<'a, V>,
{
    SQLExpr::new(SQL::raw("DISTINCT").append(expr.into_expr_sql()))
}