hamelin_lib 0.16.2

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
use crate::tree::ast::identifier::SimpleIdentifier;
use crate::types::Type;
use std::fmt::{Debug, Display, Formatter};
use std::sync::Arc;

use super::UNKNOWN;

pub trait Matcher: Display + Debug {
    fn matches(&self, other: &Type) -> bool;
}

#[derive(Debug)]
pub struct ExactMatcher {
    pub ty: Type,
}

impl ExactMatcher {
    pub fn of(ty: Type) -> Self {
        Self { ty }
    }
}

impl Display for ExactMatcher {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.ty)
    }
}

impl Matcher for ExactMatcher {
    fn matches(&self, other: &Type) -> bool {
        self.ty == *other || UNKNOWN == *other
    }
}

#[derive(Debug, Default)]
pub struct AnyMatcher;

impl Display for AnyMatcher {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "any")
    }
}

impl Matcher for AnyMatcher {
    fn matches(&self, _other: &Type) -> bool {
        true
    }
}

#[derive(Debug, Default)]
pub struct OrMatcher {
    pub matchers: Vec<Arc<dyn Matcher + Send + Sync>>,
}

impl Display for OrMatcher {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "({})",
            self.matchers
                .iter()
                .map(|m| m.to_string())
                .collect::<Vec<_>>()
                .join(" | ")
        )
    }
}

impl OrMatcher {
    pub fn with<M: Matcher + Send + Sync + 'static>(mut self, matcher: M) -> Self {
        self.matchers.push(Arc::new(matcher));
        self
    }
}

impl Matcher for OrMatcher {
    fn matches(&self, other: &Type) -> bool {
        self.matchers.iter().any(|m| m.matches(other))
    }
}

#[derive(Debug, Default)]
pub struct NumericMatcher;

impl Display for NumericMatcher {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "numeric")
    }
}

impl Matcher for NumericMatcher {
    fn matches(&self, other: &Type) -> bool {
        match other {
            Type::Binary => false,
            Type::Boolean => false,
            Type::Interval => false,
            Type::CalendarInterval => false,
            Type::Int => true,
            Type::Double => true,
            Type::Rows => true,
            Type::String => false,
            Type::Timestamp => false,
            Type::Unknown => true,
            Type::Decimal(_) => true,
            Type::Array(_) => false,
            Type::Function(_) => false,
            Type::Map(_) => false,
            Type::Tuple(_) => false,
            Type::Variant => false,
            Type::Range(_) | Type::RangeInclusive(_) => false,
            Type::Struct(_) => false,
        }
    }
}

#[derive(Debug, Default)]
pub struct IntervalMatcher;

impl Display for IntervalMatcher {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "interval")
    }
}

impl Matcher for IntervalMatcher {
    fn matches(&self, other: &Type) -> bool {
        match other {
            Type::Interval => true,
            Type::CalendarInterval => true,
            Type::Unknown => true,
            _ => false,
        }
    }
}

#[derive(Debug, Default)]
pub struct BaseMatcher;

impl Display for BaseMatcher {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "any base")
    }
}

impl Matcher for BaseMatcher {
    fn matches(&self, other: &Type) -> bool {
        match other {
            Type::Binary => true,
            Type::Boolean => true,
            Type::Interval => true,
            Type::CalendarInterval => true,
            Type::Int => true,
            Type::Double => true,
            Type::Rows => false,
            Type::String => true,
            Type::Timestamp => true,
            Type::Unknown => true,
            Type::Decimal(_) => true,
            Type::Array(_) => false,
            Type::Function(_) => false,
            Type::Map(_) => false,
            Type::Tuple(_) => false,
            Type::Variant => false,
            Type::Range(_) | Type::RangeInclusive(_) => false,
            Type::Struct(_) => false,
        }
    }
}

/// Like `BaseMatcher` but excludes `Double` — floating-point equality is
/// unreliable so floats are not allowed as map keys.
#[derive(Debug, Default)]
pub struct MapKeyMatcher;

impl Display for MapKeyMatcher {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "any base (excluding float)")
    }
}

impl Matcher for MapKeyMatcher {
    fn matches(&self, other: &Type) -> bool {
        match other {
            Type::Double => false,
            _ => BaseMatcher.matches(other),
        }
    }
}

#[derive(Debug)]
pub struct ArrayMatcher {
    pub matcher: Arc<dyn Matcher + Send + Sync>,
}

impl ArrayMatcher {
    pub fn of<M: Matcher + Send + Sync + 'static>(matcher: M) -> Self {
        Self {
            matcher: Arc::new(matcher),
        }
    }
}

impl Default for ArrayMatcher {
    fn default() -> Self {
        Self {
            matcher: Arc::new(AnyMatcher),
        }
    }
}

impl Display for ArrayMatcher {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "array({})", self.matcher)
    }
}

impl Matcher for ArrayMatcher {
    fn matches(&self, other: &Type) -> bool {
        matches!(other, Type::Array(a) if self.matcher.matches(a.element_type.as_ref()))
    }
}

#[derive(Debug)]
pub struct MapMatcher {
    pub key: Arc<dyn Matcher + Send + Sync>,
    pub value: Arc<dyn Matcher + Send + Sync>,
}

impl MapMatcher {
    pub fn of<KM: Matcher + Send + Sync + 'static, VM: Matcher + Send + Sync + 'static>(
        key: KM,
        value: VM,
    ) -> Self {
        Self {
            key: Arc::new(key),
            value: Arc::new(value),
        }
    }
}

impl Default for MapMatcher {
    fn default() -> Self {
        Self {
            key: Arc::new(AnyMatcher),
            value: Arc::new(AnyMatcher),
        }
    }
}

impl Display for MapMatcher {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "map({}, {})", self.key, self.value)
    }
}

impl Matcher for MapMatcher {
    fn matches(&self, other: &Type) -> bool {
        matches!(
            other,
            Type::Map(m)
                if self.key.matches(m.key_type.as_ref()) && self.value.matches(m.value_type.as_ref())
        )
    }
}

#[derive(Default, Debug)]
pub struct StructMatcher {
    pub matchers: Vec<(SimpleIdentifier, Arc<dyn Matcher + Send + Sync>)>,
}
impl StructMatcher {
    pub fn with<M: Matcher + Send + Sync + 'static>(
        mut self,
        name: SimpleIdentifier,
        matcher: M,
    ) -> Self {
        self.matchers.push((name, Arc::new(matcher)));
        self
    }
}

impl Display for StructMatcher {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{{")?;
        let matchers_length = self.matchers.len();
        for (i, (name, matcher)) in self.matchers.iter().enumerate() {
            write!(f, "{}", name)?;
            write!(f, ": ")?;
            write!(f, "{}", matcher)?;
            if i != matchers_length - 1 {
                write!(f, ", ")?;
            }
        }
        write!(f, "}}")
    }
}

impl Matcher for StructMatcher {
    fn matches(&self, other: &Type) -> bool {
        matches!(other, Type::Struct(s) if {
            self.matchers.iter().all(|(name, matcher)| {
                s.lookup(name).map_or(false, |ty| matcher.matches(ty))
            })
        })
    }
}

#[derive(Debug)]
pub struct TupleMatcher {
    pub matchers: Vec<Arc<dyn Matcher + Send + Sync>>,
}

impl TupleMatcher {
    pub fn of<L, R>(left: L, right: R) -> Self
    where
        L: Matcher + Send + Sync + 'static,
        R: Matcher + Send + Sync + 'static,
    {
        Self {
            matchers: vec![Arc::new(left), Arc::new(right)],
        }
    }

    pub fn with<M: Matcher + Send + Sync + 'static>(mut self, matcher: M) -> Self {
        self.matchers.push(Arc::new(matcher));
        self
    }
}

impl Display for TupleMatcher {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        if self.matchers.len() == 2 {
            write!(f, "{}: {}", self.matchers[0], self.matchers[1])
        } else {
            write!(f, "(")?;
            let matchers_length = self.matchers.len();
            for (i, matcher) in self.matchers.iter().enumerate() {
                write!(f, "{}", matcher)?;
                if i != matchers_length - 1 {
                    write!(f, ", ")?;
                }
            }
            write!(f, ")")
        }
    }
}

impl Matcher for TupleMatcher {
    fn matches(&self, other: &Type) -> bool {
        let inner = match other {
            Type::Tuple(t) => t,
            _ => return false,
        };
        inner.elements.len() == self.matchers.len()
            && self
                .matchers
                .iter()
                .zip(inner.elements.iter())
                .all(|(matcher, ty)| matcher.matches(ty))
    }
}

#[derive(Debug)]
pub struct RangeMatcher {
    pub matcher: Arc<dyn Matcher + Send + Sync>,
}

impl RangeMatcher {
    pub fn of<M: Matcher + Send + Sync + 'static>(matcher: M) -> Self {
        Self {
            matcher: Arc::new(matcher),
        }
    }
}

impl Default for RangeMatcher {
    fn default() -> Self {
        Self {
            matcher: Arc::new(AnyMatcher),
        }
    }
}

impl Display for RangeMatcher {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "range({})", self.matcher)
    }
}

impl Matcher for RangeMatcher {
    fn matches(&self, other: &Type) -> bool {
        matches!(other, Type::Range(r) | Type::RangeInclusive(r) if self.matcher.matches(r.of.as_ref()))
    }
}

#[derive(Debug)]
pub struct UnboundedTupleMatcher {
    pub matcher: Arc<dyn Matcher + Send + Sync>,
}

impl UnboundedTupleMatcher {
    pub fn of<M: Matcher + Send + Sync + 'static>(matcher: M) -> Self {
        Self {
            matcher: Arc::new(matcher),
        }
    }
}

impl Default for UnboundedTupleMatcher {
    fn default() -> Self {
        Self {
            matcher: Arc::new(AnyMatcher),
        }
    }
}

impl Display for UnboundedTupleMatcher {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "({}..)", self.matcher)
    }
}

impl Matcher for UnboundedTupleMatcher {
    fn matches(&self, other: &Type) -> bool {
        matches!(other, Type::Tuple(r) if r.elements.iter().all(|t| self.matcher.matches(t)))
    }
}