hamelin_lib 0.21.6

Core library for Hamelin query language
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
//! Aggregate functions

use std::any::TypeId;
use std::sync::Arc;

use anyhow::bail;

use crate::func::def::{
    FunctionDef, ParameterBinding, ParameterBindingProvider, Parameters, SpecialPosition,
};
use crate::tree::ast::expression::{Expression, ExpressionKind, IntLiteral};
use crate::tree::ast::identifier::SimpleIdentifier;
use crate::tree::ast::ops::UnaryPrefixOp;
use crate::tree::typed_ast::expression::TypedExpression;
use crate::types::array::Array;
use crate::types::map::Map;
use crate::types::matcher::{
    numeric_or_interval_matcher, AnyMatcher, BaseMatcher, ExactMatcher, MapKeyMatcher,
    NumericMatcher, OrMatcher,
};
use crate::types::struct_type::Struct;
use crate::types::{Type, BOOLEAN, DOUBLE, INT, INTERVAL, STRING, TIMESTAMP, VARIANT};

/// count() - Count all rows (COUNT(*)).
#[derive(Default, Clone)]
pub struct CountStar;

impl FunctionDef for CountStar {
    fn name(&self) -> &'static str {
        "count"
    }

    fn return_type(&self, _bindings: &dyn ParameterBindingProvider) -> anyhow::Result<Type> {
        Ok(INT)
    }

    fn type_id(&self) -> TypeId {
        TypeId::of::<Self>()
    }

    fn special_position(&self) -> Option<SpecialPosition> {
        Some(SpecialPosition::Agg)
    }
}

/// count(x) - Count non-null values.
#[derive(Default, Clone)]
pub struct CountAny;

impl FunctionDef for CountAny {
    fn name(&self) -> &'static str {
        "count"
    }

    fn parameters(&self) -> Parameters {
        Parameters::new().with("x", AnyMatcher::default())
    }

    fn return_type(&self, _bindings: &dyn ParameterBindingProvider) -> anyhow::Result<Type> {
        Ok(INT)
    }

    fn type_id(&self) -> TypeId {
        TypeId::of::<Self>()
    }

    fn special_position(&self) -> Option<SpecialPosition> {
        Some(SpecialPosition::Agg)
    }
}

/// count_distinct(x) - Count distinct non-null values.
#[derive(Default, Clone)]
pub struct CountDistinct;

impl FunctionDef for CountDistinct {
    fn name(&self) -> &'static str {
        "count_distinct"
    }

    fn parameters(&self) -> Parameters {
        Parameters::new().with("x", AnyMatcher::default())
    }

    fn return_type(&self, _bindings: &dyn ParameterBindingProvider) -> anyhow::Result<Type> {
        Ok(INT)
    }

    fn type_id(&self) -> TypeId {
        TypeId::of::<Self>()
    }

    fn special_position(&self) -> Option<SpecialPosition> {
        Some(SpecialPosition::Agg)
    }
}

/// approx_distinct(x) - Approximate count distinct.
#[derive(Default, Clone)]
pub struct ApproxDistinct;

impl FunctionDef for ApproxDistinct {
    fn name(&self) -> &'static str {
        "approx_distinct"
    }

    fn parameters(&self) -> Parameters {
        Parameters::new().with("x", AnyMatcher::default())
    }

    fn return_type(&self, _bindings: &dyn ParameterBindingProvider) -> anyhow::Result<Type> {
        Ok(INT)
    }

    fn type_id(&self) -> TypeId {
        TypeId::of::<Self>()
    }

    fn special_position(&self) -> Option<SpecialPosition> {
        Some(SpecialPosition::Agg)
    }
}

/// approx_top_k(value, k, max_items_tracked) - Approximate most frequent values.
#[derive(Default, Clone)]
pub struct ApproxTopK;

impl ApproxTopK {
    /// Default number of items returned.
    pub const DEFAULT_K: i64 = 5;
    /// Default candidate capacity.
    pub const DEFAULT_MAX_ITEMS_TRACKED: i64 = 10_000;
    /// Largest supported `k` value.
    pub const MAX_K: i64 = 100_000;
    /// Largest supported candidate capacity.
    pub const MAX_ITEMS_TRACKED: i64 = 100_000;

    /// Validate semantic arguments and convert them to runtime sizes.
    pub fn validate_config(k: i64, max_items_tracked: i64) -> anyhow::Result<(usize, usize)> {
        if k <= 0 {
            bail!("approx_top_k: k must be greater than 0, got {k}");
        }
        if k > Self::MAX_K {
            bail!(
                "approx_top_k: k must be less than or equal to {}, got {k}",
                Self::MAX_K
            );
        }
        if max_items_tracked < k {
            bail!(
                "approx_top_k: max_items_tracked must be greater than or equal to k ({k}), got {max_items_tracked}"
            );
        }
        if max_items_tracked > Self::MAX_ITEMS_TRACKED {
            bail!(
                "approx_top_k: max_items_tracked must be less than or equal to {}, got {max_items_tracked}",
                Self::MAX_ITEMS_TRACKED
            );
        }

        let k = usize::try_from(k)
            .map_err(|_| anyhow::anyhow!("approx_top_k: k does not fit this platform"))?;
        let max_items_tracked = usize::try_from(max_items_tracked).map_err(|_| {
            anyhow::anyhow!("approx_top_k: max_items_tracked does not fit this platform")
        })?;

        Ok((k, max_items_tracked))
    }

    fn integer_literal(name: &str, expression: &Expression) -> anyhow::Result<i64> {
        match &expression.kind {
            ExpressionKind::IntLiteral(IntLiteral { int }) => Ok(*int),
            ExpressionKind::UnaryPrefixOperator(operator) => {
                let ExpressionKind::IntLiteral(IntLiteral { int }) = &operator.operand.kind else {
                    bail!("approx_top_k: {name} must be an integer literal");
                };
                match operator.operator {
                    UnaryPrefixOp::Plus => Ok(*int),
                    UnaryPrefixOp::Minus => int.checked_neg().ok_or_else(|| {
                        anyhow::anyhow!("approx_top_k: {name} integer literal is out of range")
                    }),
                    _ => bail!("approx_top_k: {name} must be an integer literal"),
                }
            }
            _ => bail!("approx_top_k: {name} must be an integer literal"),
        }
    }
}

impl FunctionDef for ApproxTopK {
    fn name(&self) -> &'static str {
        "approx_top_k"
    }

    fn parameters(&self) -> Parameters {
        Parameters::new()
            .with("value", BaseMatcher)
            .with_default(
                "k",
                ExactMatcher::of(INT),
                Expression::from_kind(IntLiteral {
                    int: Self::DEFAULT_K,
                }),
            )
            .with_default(
                "max_items_tracked",
                ExactMatcher::of(INT),
                Expression::from_kind(IntLiteral {
                    int: Self::DEFAULT_MAX_ITEMS_TRACKED,
                }),
            )
    }

    fn refine_binding(
        &self,
        binding: ParameterBinding<Arc<TypedExpression>>,
    ) -> anyhow::Result<ParameterBinding<Arc<TypedExpression>>> {
        let k = Self::integer_literal("k", binding.get_by_name("k")?.ast.as_ref())?;
        let max_items_tracked = Self::integer_literal(
            "max_items_tracked",
            binding.get_by_name("max_items_tracked")?.ast.as_ref(),
        )?;
        Self::validate_config(k, max_items_tracked)?;
        Ok(binding)
    }

    fn return_type(&self, bindings: &dyn ParameterBindingProvider) -> anyhow::Result<Type> {
        let item_type = bindings.get_by_name("value")?.typ().clone();
        let result = Struct::new([
            (SimpleIdentifier::new("item"), item_type),
            (SimpleIdentifier::new("count"), INT),
        ]);
        Ok(Array::new(result.into()).into())
    }

    fn type_id(&self) -> TypeId {
        TypeId::of::<Self>()
    }

    fn special_position(&self) -> Option<SpecialPosition> {
        Some(SpecialPosition::Agg)
    }

    fn manages_window_clause(&self) -> bool {
        true
    }
}

/// count_if(condition) - Count rows where condition is true.
#[derive(Default, Clone)]
pub struct CountIf;

impl FunctionDef for CountIf {
    fn name(&self) -> &'static str {
        "count_if"
    }

    fn parameters(&self) -> Parameters {
        Parameters::new().with("condition", ExactMatcher::of(BOOLEAN))
    }

    fn return_type(&self, _bindings: &dyn ParameterBindingProvider) -> anyhow::Result<Type> {
        Ok(INT)
    }

    fn type_id(&self) -> TypeId {
        TypeId::of::<Self>()
    }

    fn special_position(&self) -> Option<SpecialPosition> {
        Some(SpecialPosition::Agg)
    }
}

/// sum(x) - Sum of numeric values.
#[derive(Default, Clone)]
pub struct Sum;

impl FunctionDef for Sum {
    fn name(&self) -> &'static str {
        "sum"
    }

    fn parameters(&self) -> Parameters {
        Parameters::new().with("x", numeric_or_interval_matcher())
    }

    fn return_type(&self, bindings: &dyn ParameterBindingProvider) -> anyhow::Result<Type> {
        // Return type matches input type
        Ok(bindings.get_by_index(0)?.typ().clone())
    }

    fn type_id(&self) -> TypeId {
        TypeId::of::<Self>()
    }

    fn special_position(&self) -> Option<SpecialPosition> {
        Some(SpecialPosition::Agg)
    }
}

/// avg(x) - Average of numeric values.
#[derive(Default, Clone)]
pub struct Avg;

impl FunctionDef for Avg {
    fn name(&self) -> &'static str {
        "avg"
    }

    fn parameters(&self) -> Parameters {
        Parameters::new().with("x", numeric_or_interval_matcher())
    }

    fn return_type(&self, bindings: &dyn ParameterBindingProvider) -> anyhow::Result<Type> {
        match bindings.get_by_index(0)?.typ() {
            Type::Int => Ok(DOUBLE),
            other => Ok(other.clone()),
        }
    }

    fn type_id(&self) -> TypeId {
        TypeId::of::<Self>()
    }

    fn special_position(&self) -> Option<SpecialPosition> {
        Some(SpecialPosition::Agg)
    }
}

/// stddev(x) - Standard deviation of numeric values.
#[derive(Default, Clone)]
pub struct Stddev;

impl FunctionDef for Stddev {
    fn name(&self) -> &'static str {
        "stddev"
    }

    fn parameters(&self) -> Parameters {
        Parameters::new().with("x", NumericMatcher::default())
    }

    fn return_type(&self, _bindings: &dyn ParameterBindingProvider) -> anyhow::Result<Type> {
        Ok(DOUBLE)
    }

    fn type_id(&self) -> TypeId {
        TypeId::of::<Self>()
    }

    fn special_position(&self) -> Option<SpecialPosition> {
        Some(SpecialPosition::Agg)
    }
}

/// approx_percentile(x, percentile) - Approximate percentile.
#[derive(Default, Clone)]
pub struct ApproxPercentile;

impl FunctionDef for ApproxPercentile {
    fn name(&self) -> &'static str {
        "approx_percentile"
    }

    fn parameters(&self) -> Parameters {
        Parameters::new()
            .with("x", NumericMatcher::default())
            .with("percentile", NumericMatcher::default())
    }

    fn return_type(&self, bindings: &dyn ParameterBindingProvider) -> anyhow::Result<Type> {
        match bindings.get_by_name("x")?.typ() {
            Type::Int => Ok(INT.into()),
            _ => Ok(DOUBLE.clone()),
        }
    }

    fn type_id(&self) -> TypeId {
        TypeId::of::<Self>()
    }

    fn special_position(&self) -> Option<SpecialPosition> {
        Some(SpecialPosition::Agg)
    }
}

/// min(x) - Minimum value (aggregate).
#[derive(Default, Clone)]
pub struct AggMin;

impl FunctionDef for AggMin {
    fn name(&self) -> &'static str {
        "min"
    }

    fn parameters(&self) -> Parameters {
        Parameters::new().with(
            "x",
            OrMatcher::default()
                .with(NumericMatcher::default())
                .with(ExactMatcher::of(STRING))
                .with(ExactMatcher::of(TIMESTAMP))
                .with(ExactMatcher::of(INTERVAL)),
        )
    }

    fn return_type(&self, bindings: &dyn ParameterBindingProvider) -> anyhow::Result<Type> {
        Ok(bindings.get_by_index(0)?.typ().clone())
    }

    fn type_id(&self) -> TypeId {
        TypeId::of::<Self>()
    }

    fn special_position(&self) -> Option<SpecialPosition> {
        Some(SpecialPosition::Agg)
    }
}

/// max(x) - Maximum value (aggregate).
#[derive(Default, Clone)]
pub struct AggMax;

impl FunctionDef for AggMax {
    fn name(&self) -> &'static str {
        "max"
    }

    fn parameters(&self) -> Parameters {
        Parameters::new().with(
            "x",
            OrMatcher::default()
                .with(NumericMatcher::default())
                .with(ExactMatcher::of(STRING))
                .with(ExactMatcher::of(TIMESTAMP))
                .with(ExactMatcher::of(INTERVAL)),
        )
    }

    fn return_type(&self, bindings: &dyn ParameterBindingProvider) -> anyhow::Result<Type> {
        Ok(bindings.get_by_index(0)?.typ().clone())
    }

    fn type_id(&self) -> TypeId {
        TypeId::of::<Self>()
    }

    fn special_position(&self) -> Option<SpecialPosition> {
        Some(SpecialPosition::Agg)
    }
}

/// any_value(x) - Return any value from the group.
#[derive(Default, Clone)]
pub struct AnyValue;

impl FunctionDef for AnyValue {
    fn name(&self) -> &'static str {
        "any_value"
    }

    fn parameters(&self) -> Parameters {
        Parameters::new().with("x", AnyMatcher::default())
    }

    fn return_type(&self, bindings: &dyn ParameterBindingProvider) -> anyhow::Result<Type> {
        Ok(bindings.get_by_index(0)?.typ().clone())
    }

    fn type_id(&self) -> TypeId {
        TypeId::of::<Self>()
    }

    fn special_position(&self) -> Option<SpecialPosition> {
        Some(SpecialPosition::Agg)
    }
}

/// schema_of_variant_agg(value) - Infer and merge the Hamelin types of Variant values.
#[derive(Default, Clone)]
pub struct SchemaOfVariantAgg;

impl FunctionDef for SchemaOfVariantAgg {
    fn name(&self) -> &'static str {
        "schema_of_variant_agg"
    }

    fn parameters(&self) -> Parameters {
        Parameters::new().with("value", ExactMatcher::of(VARIANT))
    }

    fn return_type(&self, _bindings: &dyn ParameterBindingProvider) -> anyhow::Result<Type> {
        Ok(STRING)
    }

    fn type_id(&self) -> TypeId {
        TypeId::of::<Self>()
    }

    fn special_position(&self) -> Option<SpecialPosition> {
        Some(SpecialPosition::Agg)
    }
}

/// array_agg(x) - Aggregate values into an array.
#[derive(Default, Clone)]
pub struct ArrayAgg;

impl FunctionDef for ArrayAgg {
    fn name(&self) -> &'static str {
        "array_agg"
    }

    fn parameters(&self) -> Parameters {
        Parameters::new().with("x", AnyMatcher::default())
    }

    fn return_type(&self, bindings: &dyn ParameterBindingProvider) -> anyhow::Result<Type> {
        Ok(Array::new(bindings.get_by_index(0)?.typ().clone()).into())
    }

    fn type_id(&self) -> TypeId {
        TypeId::of::<Self>()
    }

    fn special_position(&self) -> Option<SpecialPosition> {
        Some(SpecialPosition::Agg)
    }

    fn sortable_input(&self) -> bool {
        true
    }
}

/// set_agg(x) - Aggregate distinct values into an array.
#[derive(Default, Clone)]
pub struct SetAgg;

impl FunctionDef for SetAgg {
    fn name(&self) -> &'static str {
        "set_agg"
    }

    fn parameters(&self) -> Parameters {
        Parameters::new().with("x", AnyMatcher::default())
    }

    fn return_type(&self, bindings: &dyn ParameterBindingProvider) -> anyhow::Result<Type> {
        Ok(Array::new(bindings.get_by_index(0)?.typ().clone()).into())
    }

    fn type_id(&self) -> TypeId {
        TypeId::of::<Self>()
    }

    fn special_position(&self) -> Option<SpecialPosition> {
        Some(SpecialPosition::Agg)
    }
}

/// map_agg(key, value) - Aggregate key-value pairs into a map.
#[derive(Default, Clone)]
pub struct MapAgg;

impl FunctionDef for MapAgg {
    fn name(&self) -> &'static str {
        "map_agg"
    }

    fn parameters(&self) -> Parameters {
        Parameters::new()
            .with("key", MapKeyMatcher::default())
            .with("value", AnyMatcher::default())
    }

    fn return_type(&self, bindings: &dyn ParameterBindingProvider) -> anyhow::Result<Type> {
        let key = bindings.get_by_index(0)?.typ().clone();
        let value = bindings.get_by_index(1)?.typ().clone();
        Ok(Map::new(key, value).into())
    }

    fn type_id(&self) -> TypeId {
        TypeId::of::<Self>()
    }

    fn special_position(&self) -> Option<SpecialPosition> {
        Some(SpecialPosition::Agg)
    }

    fn sortable_input(&self) -> bool {
        true
    }
}

/// multimap_agg(key, value) - Aggregate key-value pairs into a multimap.
#[derive(Default, Clone)]
pub struct MultimapAgg;

impl FunctionDef for MultimapAgg {
    fn name(&self) -> &'static str {
        "multimap_agg"
    }

    fn parameters(&self) -> Parameters {
        Parameters::new()
            .with("key", MapKeyMatcher::default())
            .with("value", AnyMatcher::default())
    }

    fn return_type(&self, bindings: &dyn ParameterBindingProvider) -> anyhow::Result<Type> {
        let key = bindings.get_by_index(0)?.typ().clone();
        let value = bindings.get_by_index(1)?.typ().clone();
        Ok(Map::new(key, Array::new(value).into()).into())
    }

    fn type_id(&self) -> TypeId {
        TypeId::of::<Self>()
    }

    fn special_position(&self) -> Option<SpecialPosition> {
        Some(SpecialPosition::Agg)
    }

    fn sortable_input(&self) -> bool {
        true
    }
}

/// any(x) - Aggregate boolean OR (any true).
#[derive(Default, Clone)]
pub struct AggAny;

impl FunctionDef for AggAny {
    fn name(&self) -> &'static str {
        "any"
    }

    fn parameters(&self) -> Parameters {
        Parameters::new().with("x", ExactMatcher::of(BOOLEAN))
    }

    fn return_type(&self, _bindings: &dyn ParameterBindingProvider) -> anyhow::Result<Type> {
        Ok(BOOLEAN)
    }

    fn type_id(&self) -> TypeId {
        TypeId::of::<Self>()
    }

    fn special_position(&self) -> Option<SpecialPosition> {
        Some(SpecialPosition::Agg)
    }
}

/// all(x) - Aggregate boolean AND (all true).
#[derive(Default, Clone)]
pub struct AggAll;

impl FunctionDef for AggAll {
    fn name(&self) -> &'static str {
        "all"
    }

    fn parameters(&self) -> Parameters {
        Parameters::new().with("x", ExactMatcher::of(BOOLEAN))
    }

    fn return_type(&self, _bindings: &dyn ParameterBindingProvider) -> anyhow::Result<Type> {
        Ok(BOOLEAN)
    }

    fn type_id(&self) -> TypeId {
        TypeId::of::<Self>()
    }

    fn special_position(&self) -> Option<SpecialPosition> {
        Some(SpecialPosition::Agg)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tree::ast::ParseWithErrors;

    fn typed_expression(source: &str) -> Arc<TypedExpression> {
        let expression = Expression::parse_result(source).expect("expression must parse");
        expression.into()
    }

    #[test]
    fn approx_top_k_validation_preserves_unary_plus_arguments() {
        let value = typed_expression("'value'");
        let k = typed_expression("+3");
        let max_items_tracked = typed_expression("+1000");
        let binding = ParameterBinding::from_named([
            ("value".to_string(), value),
            ("k".to_string(), k.clone()),
            ("max_items_tracked".to_string(), max_items_tracked.clone()),
        ]);

        let validated = ApproxTopK
            .refine_binding(binding)
            .expect("valid configuration must pass validation");

        assert!(Arc::ptr_eq(validated.get_by_name("k").unwrap(), &k));
        assert!(Arc::ptr_eq(
            validated.get_by_name("max_items_tracked").unwrap(),
            &max_items_tracked
        ));
    }
}