vortex-expr 0.54.0

Vortex Expressions
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
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright the Vortex contributors

//! Vortex's expression language.
//!
//! All expressions are serializable, and own their own wire format.
//!
//! The implementation takes inspiration from [Postgres] and [Apache Datafusion].
//!
//! [Postgres]: https://www.postgresql.org/docs/current/sql-expressions.html
//! [Apache Datafusion]: https://github.com/apache/datafusion/tree/5fac581efbaffd0e6a9edf931182517524526afd/datafusion/expr

use std::any::Any;
use std::fmt::{Debug, Display, Formatter};
use std::hash::{Hash, Hasher};
use std::sync::Arc;

use dyn_hash::DynHash;
pub use exprs::*;
pub mod aliases;
mod analysis;
#[cfg(feature = "arbitrary")]
pub mod arbitrary;
pub mod dyn_traits;
mod encoding;
mod exprs;
mod field;
pub mod forms;
pub mod proto;
pub mod pruning;
mod registry;
mod scope;
mod scope_vars;
pub mod transform;
pub mod traversal;
mod vtable;

pub use analysis::*;
pub use between::*;
pub use binary::*;
pub use cast::*;
pub use concat::*;
pub use encoding::*;
pub use get_item::*;
pub use is_null::*;
pub use like::*;
pub use list_contains::*;
pub use literal::*;
pub use merge::*;
pub use not::*;
pub use operators::*;
pub use pack::*;
pub use registry::*;
pub use root::*;
pub use scope::*;
pub use scope_vars::*;
pub use select::*;
use vortex_array::operator::OperatorRef;
use vortex_array::{Array, ArrayRef, SerializeMetadata};
use vortex_dtype::{DType, FieldName, FieldPath};
use vortex_error::{VortexExpect, VortexResult, VortexUnwrap, vortex_bail};
use vortex_utils::aliases::hash_set::HashSet;
pub use vtable::*;

pub mod display;

use crate::display::{DisplayAs, DisplayFormat};
use crate::dyn_traits::DynEq;
use crate::traversal::{NodeExt, ReferenceCollector};

pub trait IntoExpr {
    /// Convert this type into an expression reference.
    fn into_expr(self) -> ExprRef;
}

pub type ExprRef = Arc<dyn VortexExpr>;

/// Represents logical operation on [`ArrayRef`]s
pub trait VortexExpr:
    'static + Send + Sync + Debug + DisplayAs + DynEq + DynHash + AnalysisExpr + private::Sealed
{
    /// Convert expression reference to reference of [`Any`] type
    fn as_any(&self) -> &dyn Any;

    /// Convert the expression to an [`ExprRef`].
    fn to_expr(&self) -> ExprRef;

    /// Return the encoding of the expression.
    fn encoding(&self) -> ExprEncodingRef;

    /// Serialize the metadata of this expression into a bytes vector.
    ///
    /// Returns `None` if the expression does not support serialization.
    fn metadata(&self) -> Option<Vec<u8>> {
        None
    }

    /// Compute result of expression on given batch producing a new batch
    ///
    /// "Unchecked" means that this function lacks a debug assertion that the returned array matches
    /// the [VortexExpr::return_dtype] method. Use instead the
    /// [`VortexExpr::evaluate`](./trait.VortexExpr.html#method.evaluate).
    /// function which includes such an assertion.
    fn unchecked_evaluate(&self, ctx: &Scope) -> VortexResult<ArrayRef>;

    /// Returns the children of this expression.
    fn children(&self) -> Vec<&ExprRef>;

    /// Returns a new instance of this expression with the children replaced.
    fn with_children(self: Arc<Self>, children: Vec<ExprRef>) -> VortexResult<ExprRef>;

    /// Compute the type of the array returned by
    /// [`VortexExpr::evaluate`](./trait.VortexExpr.html#method.evaluate).
    fn return_dtype(&self, scope: &DType) -> VortexResult<DType>;

    fn operator(&self, scope: &OperatorRef) -> VortexResult<Option<OperatorRef>>;
}

dyn_hash::hash_trait_object!(VortexExpr);

impl PartialEq for dyn VortexExpr {
    fn eq(&self, other: &Self) -> bool {
        self.dyn_eq(other.as_any())
    }
}

impl Eq for dyn VortexExpr {}

impl dyn VortexExpr + '_ {
    pub fn id(&self) -> ExprId {
        self.encoding().id()
    }

    pub fn is<V: VTable>(&self) -> bool {
        self.as_opt::<V>().is_some()
    }

    pub fn as_<V: VTable>(&self) -> &V::Expr {
        self.as_opt::<V>()
            .vortex_expect("Expr is not of the expected type")
    }

    pub fn as_opt<V: VTable>(&self) -> Option<&V::Expr> {
        VortexExpr::as_any(self)
            .downcast_ref::<ExprAdapter<V>>()
            .map(|e| &e.0)
    }

    /// Compute result of expression on given batch producing a new batch
    pub fn evaluate(&self, scope: &Scope) -> VortexResult<ArrayRef> {
        let result = self.unchecked_evaluate(scope)?;
        assert_eq!(
            result.dtype(),
            &self.return_dtype(scope.dtype())?,
            "Expression {} returned dtype {} but declared return_dtype of {}",
            &self,
            result.dtype(),
            self.return_dtype(scope.dtype())?,
        );
        Ok(result)
    }

    /// Display the expression as a formatted tree structure.
    ///
    /// This provides a hierarchical view of the expression that shows the relationships
    /// between parent and child expressions, making complex nested expressions easier
    /// to understand and debug.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use vortex_dtype::{DType, Nullability, PType};
    /// # use vortex_expr::{and, cast, eq, get_item, gt, lit, not, root, select, IntoExpr, LikeExpr};
    /// // Build a complex nested expression
    /// let complex_expr = select(
    ///     ["result"],
    ///     and(
    ///         not(eq(get_item("status", root()), lit("inactive"))),
    ///         and(
    ///             LikeExpr::new(get_item("name", root()), lit("%admin%"), false, false).into_expr(),
    ///             gt(
    ///                 cast(get_item("score", root()), DType::Primitive(PType::F64, Nullability::NonNullable)),
    ///                 lit(75.0)
    ///             )
    ///         )
    ///     )
    /// );
    ///
    /// println!("{}", complex_expr.display_tree());
    /// ```
    ///
    /// This produces output like:
    ///
    /// ```text
    /// Select(include): {result}
    /// └── Binary(and)
    ///     ├── lhs: Not
    ///     │   └── Binary(=)
    ///     │       ├── lhs: GetItem(status)
    ///     │       │   └── Root
    ///     │       └── rhs: Literal(value: "inactive", dtype: utf8)
    ///     └── rhs: Binary(and)
    ///         ├── lhs: Like
    ///         │   ├── child: GetItem(name)
    ///         │   │   └── Root
    ///         │   └── pattern: Literal(value: "%admin%", dtype: utf8)
    ///         └── rhs: Binary(>)
    ///             ├── lhs: Cast(target: f64)
    ///             │   └── GetItem(score)
    ///             │       └── Root
    ///             └── rhs: Literal(value: 75f64, dtype: f64)
    /// ```
    pub fn display_tree(&self) -> impl Display {
        display::DisplayTreeExpr(self)
    }
}

impl Display for dyn VortexExpr + '_ {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        DisplayAs::fmt_as(self, DisplayFormat::Compact, f)
    }
}

pub trait VortexExprExt {
    /// Accumulate all field references from this expression and its children in a set
    fn field_references(&self) -> HashSet<FieldName>;
}

impl VortexExprExt for ExprRef {
    fn field_references(&self) -> HashSet<FieldName> {
        let mut collector = ReferenceCollector::new();
        // The collector is infallible, so we can unwrap the result
        self.accept(&mut collector).vortex_unwrap();
        collector.into_fields()
    }
}

#[derive(Clone)]
#[repr(transparent)]
pub struct ExprAdapter<V: VTable>(V::Expr);

impl<V: VTable> VortexExpr for ExprAdapter<V> {
    fn as_any(&self) -> &dyn Any {
        self
    }

    fn to_expr(&self) -> ExprRef {
        Arc::new(ExprAdapter::<V>(self.0.clone()))
    }

    fn encoding(&self) -> ExprEncodingRef {
        V::encoding(&self.0)
    }

    fn metadata(&self) -> Option<Vec<u8>> {
        V::metadata(&self.0).map(|m| m.serialize())
    }

    fn unchecked_evaluate(&self, ctx: &Scope) -> VortexResult<ArrayRef> {
        V::evaluate(&self.0, ctx)
    }

    fn children(&self) -> Vec<&ExprRef> {
        V::children(&self.0)
    }

    fn with_children(self: Arc<Self>, children: Vec<ExprRef>) -> VortexResult<ExprRef> {
        if self.children().len() != children.len() {
            vortex_bail!(
                "Expected {} children, got {}",
                self.children().len(),
                children.len()
            );
        }
        Ok(V::with_children(&self.0, children)?.to_expr())
    }

    fn return_dtype(&self, scope: &DType) -> VortexResult<DType> {
        V::return_dtype(&self.0, scope)
    }

    fn operator(&self, scope: &OperatorRef) -> VortexResult<Option<OperatorRef>> {
        V::operator(&self.0, scope)
    }
}

impl<V: VTable> Debug for ExprAdapter<V> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        Debug::fmt(&self.0, f)
    }
}

impl<V: VTable> Display for ExprAdapter<V> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        DisplayAs::fmt_as(&self.0, DisplayFormat::Compact, f)
    }
}

impl<V: VTable> DisplayAs for ExprAdapter<V> {
    fn fmt_as(&self, df: DisplayFormat, f: &mut Formatter) -> std::fmt::Result {
        DisplayAs::fmt_as(&self.0, df, f)
    }

    fn child_names(&self) -> Option<Vec<String>> {
        DisplayAs::child_names(&self.0)
    }
}

impl<V: VTable> PartialEq for ExprAdapter<V> {
    fn eq(&self, other: &Self) -> bool {
        PartialEq::eq(&self.0, &other.0)
    }
}

impl<V: VTable> Eq for ExprAdapter<V> {}

impl<V: VTable> Hash for ExprAdapter<V> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        Hash::hash(&self.0, state);
    }
}

impl<V: VTable> AnalysisExpr for ExprAdapter<V> {
    fn stat_falsification(&self, catalog: &mut dyn StatsCatalog) -> Option<ExprRef> {
        <V::Expr as AnalysisExpr>::stat_falsification(&self.0, catalog)
    }

    fn max(&self, catalog: &mut dyn StatsCatalog) -> Option<ExprRef> {
        <V::Expr as AnalysisExpr>::max(&self.0, catalog)
    }

    fn min(&self, catalog: &mut dyn StatsCatalog) -> Option<ExprRef> {
        <V::Expr as AnalysisExpr>::min(&self.0, catalog)
    }

    fn nan_count(&self, catalog: &mut dyn StatsCatalog) -> Option<ExprRef> {
        <V::Expr as AnalysisExpr>::nan_count(&self.0, catalog)
    }

    fn field_path(&self) -> Option<FieldPath> {
        <V::Expr as AnalysisExpr>::field_path(&self.0)
    }
}

mod private {
    use super::*;

    pub trait Sealed {}

    impl<V: VTable> Sealed for ExprAdapter<V> {}
}

/// Splits top level and operations into separate expressions.
pub fn split_conjunction(expr: &ExprRef) -> Vec<ExprRef> {
    let mut conjunctions = vec![];
    split_inner(expr, &mut conjunctions);
    conjunctions
}

fn split_inner(expr: &ExprRef, exprs: &mut Vec<ExprRef>) {
    match expr.as_opt::<BinaryVTable>() {
        Some(bexp) if bexp.op() == Operator::And => {
            split_inner(bexp.lhs(), exprs);
            split_inner(bexp.rhs(), exprs);
        }
        Some(_) | None => {
            exprs.push(expr.clone());
        }
    }
}

/// An expression wrapper that performs pointer equality.
#[derive(Clone)]
pub struct ExactExpr(pub ExprRef);

impl PartialEq for ExactExpr {
    fn eq(&self, other: &Self) -> bool {
        Arc::ptr_eq(&self.0, &other.0)
    }
}

impl Eq for ExactExpr {}

impl Hash for ExactExpr {
    fn hash<H: Hasher>(&self, state: &mut H) {
        Arc::as_ptr(&self.0).hash(state)
    }
}

#[cfg(feature = "test-harness")]
pub mod test_harness {
    use vortex_dtype::{DType, Nullability, PType, StructFields};

    pub fn struct_dtype() -> DType {
        DType::Struct(
            StructFields::new(
                ["a", "col1", "col2", "bool1", "bool2"].into(),
                vec![
                    DType::Primitive(PType::I32, Nullability::NonNullable),
                    DType::Primitive(PType::U16, Nullability::Nullable),
                    DType::Primitive(PType::U16, Nullability::Nullable),
                    DType::Bool(Nullability::NonNullable),
                    DType::Bool(Nullability::NonNullable),
                ],
            ),
            Nullability::NonNullable,
        )
    }
}

#[cfg(test)]
mod tests {
    use vortex_dtype::{DType, FieldNames, Nullability, PType, StructFields};
    use vortex_scalar::Scalar;

    use super::*;

    #[test]
    fn basic_expr_split_test() {
        let lhs = get_item("col1", root());
        let rhs = lit(1);
        let expr = eq(lhs, rhs);
        let conjunction = split_conjunction(&expr);
        assert_eq!(conjunction.len(), 1);
    }

    #[test]
    fn basic_conjunction_split_test() {
        let lhs = get_item("col1", root());
        let rhs = lit(1);
        let expr = and(lhs, rhs);
        let conjunction = split_conjunction(&expr);
        assert_eq!(conjunction.len(), 2, "Conjunction is {conjunction:?}");
    }

    #[test]
    fn expr_display() {
        assert_eq!(col("a").to_string(), "$.a");
        assert_eq!(root().to_string(), "$");

        let col1: Arc<dyn VortexExpr> = col("col1");
        let col2: Arc<dyn VortexExpr> = col("col2");
        assert_eq!(
            and(col1.clone(), col2.clone()).to_string(),
            "($.col1 and $.col2)"
        );
        assert_eq!(
            or(col1.clone(), col2.clone()).to_string(),
            "($.col1 or $.col2)"
        );
        assert_eq!(
            eq(col1.clone(), col2.clone()).to_string(),
            "($.col1 = $.col2)"
        );
        assert_eq!(
            not_eq(col1.clone(), col2.clone()).to_string(),
            "($.col1 != $.col2)"
        );
        assert_eq!(
            gt(col1.clone(), col2.clone()).to_string(),
            "($.col1 > $.col2)"
        );
        assert_eq!(
            gt_eq(col1.clone(), col2.clone()).to_string(),
            "($.col1 >= $.col2)"
        );
        assert_eq!(
            lt(col1.clone(), col2.clone()).to_string(),
            "($.col1 < $.col2)"
        );
        assert_eq!(
            lt_eq(col1.clone(), col2.clone()).to_string(),
            "($.col1 <= $.col2)"
        );

        assert_eq!(
            or(
                lt(col1.clone(), col2.clone()),
                not_eq(col1.clone(), col2.clone()),
            )
            .to_string(),
            "(($.col1 < $.col2) or ($.col1 != $.col2))"
        );

        assert_eq!(not(col1.clone()).to_string(), "(!$.col1)");

        assert_eq!(
            select(vec![FieldName::from("col1")], root()).to_string(),
            "${col1}"
        );
        assert_eq!(
            select(
                vec![FieldName::from("col1"), FieldName::from("col2")],
                root()
            )
            .to_string(),
            "${col1, col2}"
        );
        assert_eq!(
            select_exclude(
                vec![FieldName::from("col1"), FieldName::from("col2")],
                root()
            )
            .to_string(),
            "$~{col1, col2}"
        );

        assert_eq!(lit(Scalar::from(0u8)).to_string(), "0u8");
        assert_eq!(lit(Scalar::from(0.0f32)).to_string(), "0f32");
        assert_eq!(
            lit(Scalar::from(i64::MAX)).to_string(),
            "9223372036854775807i64"
        );
        assert_eq!(lit(Scalar::from(true)).to_string(), "true");
        assert_eq!(
            lit(Scalar::null(DType::Bool(Nullability::Nullable))).to_string(),
            "null"
        );

        assert_eq!(
            lit(Scalar::struct_(
                DType::Struct(
                    StructFields::new(
                        FieldNames::from(["dog", "cat"]),
                        vec![
                            DType::Primitive(PType::U32, Nullability::NonNullable),
                            DType::Utf8(Nullability::NonNullable)
                        ],
                    ),
                    Nullability::NonNullable
                ),
                vec![Scalar::from(32_u32), Scalar::from("rufus".to_string())]
            ))
            .to_string(),
            "{dog: 32u32, cat: \"rufus\"}"
        );
    }
}