fluss-rs 1.0.0

The official rust client of Apache Fluss
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
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

//! Predicates for server-side filter pushdown on log scans.
//!
//! ```rust
//! use fluss::predicate::col;
//!
//! let p = col("age").gt(30i64).and(col("name").starts_with("A"));
//! ```
//!
//! The server prunes whole Arrow batches by their statistics, so a filtered scan
//! returns a superset of the matching records and callers must still filter
//! exactly. The protocol has no negation node; negate with [`ColumnRef::ne`] and
//! [`ColumnRef::not_in`].
//!
//! Setting a predicate on a scan is only supported on log scans over tables
//! with the ARROW log format.

mod pb;

pub(crate) use pb::to_pb_predicate;

use crate::row::{Decimal, TimestampLtz, TimestampNtz};

/// Comparison applied by a [`Predicate::Leaf`] to one column.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum LeafFunction {
    Equal,
    NotEqual,
    LessThan,
    LessOrEqual,
    GreaterThan,
    GreaterOrEqual,
    IsNull,
    IsNotNull,
    StartsWith,
    Contains,
    EndsWith,
    In,
    NotIn,
}

/// Boolean connective applied by a [`Predicate::Compound`] to its children.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum CompoundFunction {
    And,
    Or,
}

/// A constant compared against a column, coerced to the column's declared type
/// when the predicate is bound to a schema. [`Literal::Date`] holds epoch days
/// and [`Literal::Time`] milliseconds of day, as Fluss encodes them internally.
#[derive(Debug, Clone, PartialEq)]
pub enum Literal {
    Null,
    Bool(bool),
    Int8(i8),
    Int16(i16),
    Int32(i32),
    Int64(i64),
    Float32(f32),
    Float64(f64),
    String(String),
    Bytes(Vec<u8>),
    Decimal(Decimal),
    Date(i32),
    Time(i32),
    TimestampNtz(TimestampNtz),
    TimestampLtz(TimestampLtz),
}

macro_rules! impl_from_literal {
    ($($ty:ty => $variant:ident),* $(,)?) => {
        $(
            impl From<$ty> for Literal {
                fn from(value: $ty) -> Self {
                    Literal::$variant(value.into())
                }
            }
        )*
    };
}

impl_from_literal! {
    bool => Bool,
    i8 => Int8,
    i16 => Int16,
    i32 => Int32,
    i64 => Int64,
    f32 => Float32,
    f64 => Float64,
    String => String,
    Decimal => Decimal,
    TimestampNtz => TimestampNtz,
    TimestampLtz => TimestampLtz,
}

impl From<&str> for Literal {
    fn from(value: &str) -> Self {
        Literal::String(value.to_string())
    }
}

impl From<Vec<u8>> for Literal {
    fn from(value: Vec<u8>) -> Self {
        Literal::Bytes(value)
    }
}

impl From<&[u8]> for Literal {
    fn from(value: &[u8]) -> Self {
        Literal::Bytes(value.to_vec())
    }
}

impl<T: Into<Literal>> From<Option<T>> for Literal {
    fn from(value: Option<T>) -> Self {
        match value {
            Some(v) => v.into(),
            None => Literal::Null,
        }
    }
}

/// A filter expression pushed down to the server for a log scan, built with
/// [`col`]. Column names and literal types are checked when it is attached to a
/// scan, not here.
#[derive(Debug, Clone, PartialEq)]
pub enum Predicate {
    /// A comparison against a single column.
    Leaf {
        field: String,
        function: LeafFunction,
        /// Empty for `IS [NOT] NULL`, one element for the comparisons, one or
        /// more for `IN`/`NOT IN`.
        literals: Vec<Literal>,
    },
    /// A boolean combination of child predicates.
    Compound {
        function: CompoundFunction,
        children: Vec<Predicate>,
    },
}

impl Predicate {
    /// Returns a predicate matching rows matched by both `self` and `other`.
    pub fn and(self, other: Predicate) -> Predicate {
        self.combine(CompoundFunction::And, other)
    }

    /// Returns a predicate matching rows matched by either `self` or `other`.
    pub fn or(self, other: Predicate) -> Predicate {
        self.combine(CompoundFunction::Or, other)
    }

    /// Combines all `predicates` with `AND`, or returns `None` if empty.
    pub fn and_all(predicates: impl IntoIterator<Item = Predicate>) -> Option<Predicate> {
        Self::combine_all(CompoundFunction::And, predicates)
    }

    /// Combines all `predicates` with `OR`, or returns `None` if empty.
    pub fn or_all(predicates: impl IntoIterator<Item = Predicate>) -> Option<Predicate> {
        Self::combine_all(CompoundFunction::Or, predicates)
    }

    /// Flattens into an existing node of the same function so that chained
    /// combinators produce one n-ary node instead of a left-leaning tree.
    fn combine(self, function: CompoundFunction, other: Predicate) -> Predicate {
        match self {
            // Same kind of node: absorb `other` as one more child.
            Predicate::Compound {
                function: existing,
                mut children,
            } if existing == function => {
                children.push(other);
                Predicate::Compound { function, children }
            }
            // A leaf, or a node of the other kind: both operands become children.
            lhs => Predicate::Compound {
                function,
                children: vec![lhs, other],
            },
        }
    }

    fn combine_all(
        function: CompoundFunction,
        predicates: impl IntoIterator<Item = Predicate>,
    ) -> Option<Predicate> {
        predicates
            .into_iter()
            .reduce(|acc, next| acc.combine(function, next))
    }
}

/// Starts a predicate on the column named `name`, which is validated only once
/// the predicate is attached to a scan.
pub fn col(name: impl Into<String>) -> ColumnRef {
    ColumnRef { name: name.into() }
}

/// A column reference awaiting a comparison, produced by [`col`].
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ColumnRef {
    name: String,
}

// The `is_*` builders consume `self` and return a predicate, like every other
// combinator here, rather than asking a question about the column.
#[allow(clippy::wrong_self_convention)]
impl ColumnRef {
    /// Name of the referenced column.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// `column = value`.
    pub fn eq(self, value: impl Into<Literal>) -> Predicate {
        self.binary(LeafFunction::Equal, value)
    }

    /// `column <> value`.
    pub fn ne(self, value: impl Into<Literal>) -> Predicate {
        self.binary(LeafFunction::NotEqual, value)
    }

    /// `column < value`.
    pub fn lt(self, value: impl Into<Literal>) -> Predicate {
        self.binary(LeafFunction::LessThan, value)
    }

    /// `column <= value`.
    pub fn le(self, value: impl Into<Literal>) -> Predicate {
        self.binary(LeafFunction::LessOrEqual, value)
    }

    /// `column > value`.
    pub fn gt(self, value: impl Into<Literal>) -> Predicate {
        self.binary(LeafFunction::GreaterThan, value)
    }

    /// `column >= value`.
    pub fn ge(self, value: impl Into<Literal>) -> Predicate {
        self.binary(LeafFunction::GreaterOrEqual, value)
    }

    /// `column IS NULL`.
    pub fn is_null(self) -> Predicate {
        self.leaf(LeafFunction::IsNull, vec![])
    }

    /// `column IS NOT NULL`.
    pub fn is_not_null(self) -> Predicate {
        self.leaf(LeafFunction::IsNotNull, vec![])
    }

    /// `column IN (values...)`. An empty `values` matches nothing.
    pub fn is_in<V: Into<Literal>>(self, values: impl IntoIterator<Item = V>) -> Predicate {
        self.leaf(
            LeafFunction::In,
            values.into_iter().map(Into::into).collect(),
        )
    }

    /// `column NOT IN (values...)`. An empty `values` matches everything.
    pub fn not_in<V: Into<Literal>>(self, values: impl IntoIterator<Item = V>) -> Predicate {
        self.leaf(
            LeafFunction::NotIn,
            values.into_iter().map(Into::into).collect(),
        )
    }

    /// `column LIKE 'prefix%'`, for character-string columns.
    pub fn starts_with(self, prefix: impl Into<String>) -> Predicate {
        self.binary(LeafFunction::StartsWith, prefix.into())
    }

    /// `column LIKE '%suffix'`, for character-string columns.
    pub fn ends_with(self, suffix: impl Into<String>) -> Predicate {
        self.binary(LeafFunction::EndsWith, suffix.into())
    }

    /// `column LIKE '%infix%'`, for character-string columns.
    pub fn contains(self, infix: impl Into<String>) -> Predicate {
        self.binary(LeafFunction::Contains, infix.into())
    }

    fn binary(self, function: LeafFunction, value: impl Into<Literal>) -> Predicate {
        self.leaf(function, vec![value.into()])
    }

    fn leaf(self, function: LeafFunction, literals: Vec<Literal>) -> Predicate {
        Predicate::Leaf {
            field: self.name,
            function,
            literals,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn leaf(field: &str, function: LeafFunction, literals: Vec<Literal>) -> Predicate {
        Predicate::Leaf {
            field: field.to_string(),
            function,
            literals,
        }
    }

    #[test]
    fn builds_leaf_predicates() {
        assert_eq!(
            col("age").gt(30i64),
            leaf("age", LeafFunction::GreaterThan, vec![Literal::Int64(30)])
        );
        assert_eq!(
            col("name").starts_with("A"),
            leaf(
                "name",
                LeafFunction::StartsWith,
                vec![Literal::String("A".to_string())]
            )
        );
        assert_eq!(
            col("deleted_at").is_null(),
            leaf("deleted_at", LeafFunction::IsNull, vec![])
        );
        assert_eq!(
            col("region").is_in(vec!["eu", "us"]),
            leaf(
                "region",
                LeafFunction::In,
                vec![
                    Literal::String("eu".to_string()),
                    Literal::String("us".to_string())
                ]
            )
        );
    }

    #[test]
    fn converts_rust_values_to_literals() {
        assert_eq!(Literal::from(true), Literal::Bool(true));
        assert_eq!(Literal::from(7i8), Literal::Int8(7));
        assert_eq!(Literal::from(7i32), Literal::Int32(7));
        assert_eq!(Literal::from(1.5f64), Literal::Float64(1.5));
        assert_eq!(
            Literal::from("hi".to_string()),
            Literal::String("hi".to_string())
        );
        assert_eq!(
            Literal::from(vec![1u8, 2].as_slice()),
            Literal::Bytes(vec![1, 2])
        );
        assert_eq!(Literal::from(None::<i32>), Literal::Null);
        assert_eq!(Literal::from(Some(3i32)), Literal::Int32(3));
    }

    #[test]
    fn chained_combinators_produce_one_n_ary_node() {
        let predicate = col("a")
            .eq(1i32)
            .and(col("b").eq(2i32))
            .and(col("c").eq(3i32));

        assert_eq!(
            predicate,
            Predicate::Compound {
                function: CompoundFunction::And,
                children: vec![
                    leaf("a", LeafFunction::Equal, vec![Literal::Int32(1)]),
                    leaf("b", LeafFunction::Equal, vec![Literal::Int32(2)]),
                    leaf("c", LeafFunction::Equal, vec![Literal::Int32(3)]),
                ],
            }
        );
    }

    #[test]
    fn mixed_combinators_stay_nested() {
        let predicate = col("a")
            .eq(1i32)
            .and(col("b").eq(2i32))
            .or(col("c").eq(3i32));

        assert_eq!(
            predicate,
            Predicate::Compound {
                function: CompoundFunction::Or,
                children: vec![
                    Predicate::Compound {
                        function: CompoundFunction::And,
                        children: vec![
                            leaf("a", LeafFunction::Equal, vec![Literal::Int32(1)]),
                            leaf("b", LeafFunction::Equal, vec![Literal::Int32(2)]),
                        ],
                    },
                    leaf("c", LeafFunction::Equal, vec![Literal::Int32(3)]),
                ],
            }
        );
    }

    #[test]
    fn combine_all_folds_and_handles_empty_input() {
        assert_eq!(Predicate::and_all(Vec::new()), None);
        assert_eq!(
            Predicate::or_all(vec![col("a").eq(1i32)]),
            Some(col("a").eq(1i32))
        );

        let folded = Predicate::and_all(vec![col("a").eq(1i32), col("b").eq(2i32)]).unwrap();
        assert_eq!(folded, col("a").eq(1i32).and(col("b").eq(2i32)));
    }
}