icepick 0.4.1

Experimental Rust client for Apache Iceberg with WASM support for AWS S3 Tables and Cloudflare R2
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
//! Predicate expressions for filtering Iceberg tables
use crate::spec::PrimitiveType;
use std::fmt;

/// A scalar value for comparison (Bool, Int, Long, Float, Double, String, Date, Timestamp, Binary)
#[derive(Debug, Clone, PartialEq)]
pub enum Datum {
    Bool(bool),
    Int(i32),
    Long(i64),
    Float(f32),
    Double(f64),
    String(String),
    Date(i32),
    Timestamp(i64),
    Binary(Vec<u8>),
}

impl Datum {
    /// Decode a datum from Iceberg binary representation
    ///
    /// This decodes raw bytes into a Datum based on the primitive type.
    /// Used for reading partition values and column bounds from manifest files.
    pub fn from_bytes(bytes: &[u8], prim_type: &PrimitiveType) -> Option<Self> {
        match prim_type {
            PrimitiveType::Boolean => {
                if bytes.is_empty() {
                    return None;
                }
                Some(Datum::Bool(bytes[0] != 0))
            }
            PrimitiveType::Int => {
                let arr: [u8; 4] = bytes.get(..4)?.try_into().ok()?;
                Some(Datum::Int(i32::from_le_bytes(arr)))
            }
            PrimitiveType::Long => {
                let arr: [u8; 8] = bytes.get(..8)?.try_into().ok()?;
                Some(Datum::Long(i64::from_le_bytes(arr)))
            }
            PrimitiveType::Float => {
                let arr: [u8; 4] = bytes.get(..4)?.try_into().ok()?;
                Some(Datum::Float(f32::from_le_bytes(arr)))
            }
            PrimitiveType::Double => {
                let arr: [u8; 8] = bytes.get(..8)?.try_into().ok()?;
                Some(Datum::Double(f64::from_le_bytes(arr)))
            }
            PrimitiveType::Date => {
                let arr: [u8; 4] = bytes.get(..4)?.try_into().ok()?;
                Some(Datum::Date(i32::from_le_bytes(arr)))
            }
            PrimitiveType::Time | PrimitiveType::Timestamp | PrimitiveType::Timestamptz => {
                let arr: [u8; 8] = bytes.get(..8)?.try_into().ok()?;
                Some(Datum::Timestamp(i64::from_le_bytes(arr)))
            }
            PrimitiveType::String | PrimitiveType::Uuid => {
                String::from_utf8(bytes.to_vec()).ok().map(Datum::String)
            }
            PrimitiveType::Binary | PrimitiveType::Fixed(_) => Some(Datum::Binary(bytes.to_vec())),
            PrimitiveType::Decimal { .. } => {
                // Decimal requires precision/scale handling, skip for now
                None
            }
        }
    }

    /// Check if this datum can be compared with another
    pub fn is_comparable_to(&self, other: &Datum) -> bool {
        use Datum::*;
        matches!(
            (self, other),
            (Bool(_), Bool(_))
                | (Int(_), Int(_))
                | (Int(_), Long(_))
                | (Long(_), Int(_))
                | (Long(_), Long(_))
                | (Float(_), Float(_))
                | (Float(_), Double(_))
                | (Double(_), Float(_))
                | (Double(_), Double(_))
                | (String(_), String(_))
                | (Date(_), Date(_))
                | (Timestamp(_), Timestamp(_))
                | (Binary(_), Binary(_))
        )
    }

    /// Compare two datums, returning ordering if comparable
    pub fn compare(&self, other: &Datum) -> Option<std::cmp::Ordering> {
        use Datum::*;

        match (self, other) {
            (Bool(a), Bool(b)) => Some(a.cmp(b)),
            (Int(a), Int(b)) => Some(a.cmp(b)),
            (Int(a), Long(b)) => Some((*a as i64).cmp(b)),
            (Long(a), Int(b)) => Some(a.cmp(&(*b as i64))),
            (Long(a), Long(b)) => Some(a.cmp(b)),
            (Float(a), Float(b)) => a.partial_cmp(b),
            (Float(a), Double(b)) => (*a as f64).partial_cmp(b),
            (Double(a), Float(b)) => a.partial_cmp(&(*b as f64)),
            (Double(a), Double(b)) => a.partial_cmp(b),
            (String(a), String(b)) => Some(a.cmp(b)),
            (Date(a), Date(b)) => Some(a.cmp(b)),
            (Timestamp(a), Timestamp(b)) => Some(a.cmp(b)),
            (Binary(a), Binary(b)) => Some(a.cmp(b)),
            _ => None,
        }
    }
}

impl fmt::Display for Datum {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Datum::Bool(v) => write!(f, "{}", v),
            Datum::Int(v) => write!(f, "{}", v),
            Datum::Long(v) => write!(f, "{}", v),
            Datum::Float(v) => write!(f, "{}", v),
            Datum::Double(v) => write!(f, "{}", v),
            Datum::String(v) => write!(f, "'{}'", v),
            Datum::Date(v) => write!(f, "DATE({})", v),
            Datum::Timestamp(v) => write!(f, "TIMESTAMP({})", v),
            Datum::Binary(v) => write!(f, "BINARY({} bytes)", v.len()),
        }
    }
}

// Convenience From implementations
macro_rules! impl_from_for_datum {
    ($t:ty, $variant:ident) => {
        impl From<$t> for Datum {
            fn from(v: $t) -> Self {
                Datum::$variant(v)
            }
        }
    };
}
impl_from_for_datum!(bool, Bool);
impl_from_for_datum!(i32, Int);
impl_from_for_datum!(i64, Long);
impl_from_for_datum!(f32, Float);
impl_from_for_datum!(f64, Double);
impl_from_for_datum!(String, String);
impl From<&str> for Datum {
    fn from(v: &str) -> Self {
        Datum::String(v.to_string())
    }
}

/// Binary comparison operators (Eq, NotEq, Lt, LtEq, Gt, GtEq)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ComparisonOp {
    Eq,
    NotEq,
    Lt,
    LtEq,
    Gt,
    GtEq,
}

impl ComparisonOp {
    /// Evaluate the operator on an ordering result
    pub fn evaluate(&self, ordering: std::cmp::Ordering) -> bool {
        use std::cmp::Ordering;
        matches!(
            (self, ordering),
            (ComparisonOp::Eq, Ordering::Equal)
                | (ComparisonOp::NotEq, Ordering::Less | Ordering::Greater)
                | (ComparisonOp::Lt, Ordering::Less)
                | (ComparisonOp::LtEq, Ordering::Less | Ordering::Equal)
                | (ComparisonOp::Gt, Ordering::Greater)
                | (ComparisonOp::GtEq, Ordering::Greater | Ordering::Equal)
        )
    }

    /// Get the negation of this operator
    pub fn negate(&self) -> Self {
        match self {
            ComparisonOp::Eq => ComparisonOp::NotEq,
            ComparisonOp::NotEq => ComparisonOp::Eq,
            ComparisonOp::Lt => ComparisonOp::GtEq,
            ComparisonOp::LtEq => ComparisonOp::Gt,
            ComparisonOp::Gt => ComparisonOp::LtEq,
            ComparisonOp::GtEq => ComparisonOp::Lt,
        }
    }
}

impl fmt::Display for ComparisonOp {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ComparisonOp::Eq => write!(f, "="),
            ComparisonOp::NotEq => write!(f, "!="),
            ComparisonOp::Lt => write!(f, "<"),
            ComparisonOp::LtEq => write!(f, "<="),
            ComparisonOp::Gt => write!(f, ">"),
            ComparisonOp::GtEq => write!(f, ">="),
        }
    }
}

/// A reference to a column
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum ColumnRef {
    /// Reference by column name
    Named(String),
    /// Reference by field ID
    Id(i32),
}

impl ColumnRef {
    /// Create a named column reference with validation
    ///
    /// # Errors
    ///
    /// Returns `Error::InvalidInput` if the name is empty.
    ///
    /// # Examples
    ///
    /// ```
    /// use icepick::expr::ColumnRef;
    ///
    /// let col = ColumnRef::named("age").unwrap();
    /// assert_eq!(col.name(), Some("age"));
    ///
    /// let empty = ColumnRef::named("");
    /// assert!(empty.is_err());
    /// ```
    pub fn named(name: impl Into<String>) -> crate::error::Result<Self> {
        let name_str = name.into();
        if name_str.is_empty() {
            return Err(crate::error::Error::invalid_input(
                "Column name cannot be empty",
            ));
        }
        Ok(ColumnRef::Named(name_str))
    }

    /// Create a column reference by field ID with validation
    ///
    /// # Errors
    ///
    /// Returns `Error::InvalidInput` if the ID is not positive (must be > 0).
    /// Field IDs in the Iceberg spec must be positive integers.
    ///
    /// # Examples
    ///
    /// ```
    /// use icepick::expr::ColumnRef;
    ///
    /// let col = ColumnRef::id(42).unwrap();
    ///
    /// let negative = ColumnRef::id(-1);
    /// assert!(negative.is_err());
    ///
    /// let zero = ColumnRef::id(0);
    /// assert!(zero.is_err());
    /// ```
    pub fn id(id: i32) -> crate::error::Result<Self> {
        if id <= 0 {
            return Err(crate::error::Error::invalid_input(format!(
                "Field ID must be positive, got {}",
                id
            )));
        }
        Ok(ColumnRef::Id(id))
    }

    /// Get the column name if this is a named reference
    pub fn name(&self) -> Option<&str> {
        match self {
            ColumnRef::Named(n) => Some(n),
            ColumnRef::Id(_) => None,
        }
    }
}

impl fmt::Display for ColumnRef {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ColumnRef::Named(n) => write!(f, "{}", n),
            ColumnRef::Id(id) => write!(f, "#{}", id),
        }
    }
}

impl From<String> for ColumnRef {
    /// Convert a String to a ColumnRef::Named variant
    ///
    /// # Panics
    ///
    /// This conversion does not validate the input. Empty strings will create
    /// invalid column references. Use `ColumnRef::named()` for validated construction.
    fn from(v: String) -> Self {
        ColumnRef::Named(v)
    }
}

impl From<&str> for ColumnRef {
    /// Convert a string slice to a ColumnRef::Named variant
    ///
    /// # Panics
    ///
    /// This conversion does not validate the input. Empty strings will create
    /// invalid column references. Use `ColumnRef::named()` for validated construction.
    fn from(v: &str) -> Self {
        ColumnRef::Named(v.to_string())
    }
}

impl From<i32> for ColumnRef {
    /// Convert an i32 to a ColumnRef::Id variant
    ///
    /// # Panics
    ///
    /// This conversion does not validate the input. Non-positive IDs will create
    /// invalid column references. Use `ColumnRef::id()` for validated construction.
    fn from(v: i32) -> Self {
        ColumnRef::Id(v)
    }
}

/// Predicate expression for filtering (AlwaysTrue, AlwaysFalse, Comparison, IsNull, IsNotNull, In, And, Or, Not)
#[derive(Debug, Clone, PartialEq)]
pub enum Predicate {
    AlwaysTrue,
    AlwaysFalse,
    Comparison {
        column: ColumnRef,
        op: ComparisonOp,
        value: Datum,
    },
    IsNull(ColumnRef),
    IsNotNull(ColumnRef),
    In {
        column: ColumnRef,
        values: Vec<Datum>,
    },
    And(Vec<Predicate>),
    Or(Vec<Predicate>),
    Not(Box<Predicate>),
}

impl Predicate {
    /// Create an AND of multiple predicates
    pub fn and(predicates: impl IntoIterator<Item = Predicate>) -> Self {
        let preds: Vec<_> = predicates.into_iter().collect();
        if preds.is_empty() {
            Predicate::AlwaysTrue
        } else if preds.len() == 1 {
            preds.into_iter().next().unwrap()
        } else {
            Predicate::And(preds)
        }
    }

    /// Create an OR of multiple predicates
    pub fn or(predicates: impl IntoIterator<Item = Predicate>) -> Self {
        let preds: Vec<_> = predicates.into_iter().collect();
        if preds.is_empty() {
            Predicate::AlwaysFalse
        } else if preds.len() == 1 {
            preds.into_iter().next().unwrap()
        } else {
            Predicate::Or(preds)
        }
    }

    /// Create a NOT predicate (negation)
    pub fn negate(predicate: Predicate) -> Self {
        match predicate {
            Predicate::AlwaysTrue => Predicate::AlwaysFalse,
            Predicate::AlwaysFalse => Predicate::AlwaysTrue,
            Predicate::Not(inner) => *inner,
            other => Predicate::Not(Box::new(other)),
        }
    }

    /// Create an equality comparison
    pub fn eq(column: impl Into<ColumnRef>, value: impl Into<Datum>) -> Self {
        Predicate::Comparison {
            column: column.into(),
            op: ComparisonOp::Eq,
            value: value.into(),
        }
    }

    /// Create a not-equal comparison
    pub fn not_eq(column: impl Into<ColumnRef>, value: impl Into<Datum>) -> Self {
        Predicate::Comparison {
            column: column.into(),
            op: ComparisonOp::NotEq,
            value: value.into(),
        }
    }

    /// Create a less-than comparison
    pub fn lt(column: impl Into<ColumnRef>, value: impl Into<Datum>) -> Self {
        Predicate::Comparison {
            column: column.into(),
            op: ComparisonOp::Lt,
            value: value.into(),
        }
    }

    /// Create a less-than-or-equal comparison
    pub fn lt_eq(column: impl Into<ColumnRef>, value: impl Into<Datum>) -> Self {
        Predicate::Comparison {
            column: column.into(),
            op: ComparisonOp::LtEq,
            value: value.into(),
        }
    }

    /// Create a greater-than comparison
    pub fn gt(column: impl Into<ColumnRef>, value: impl Into<Datum>) -> Self {
        Predicate::Comparison {
            column: column.into(),
            op: ComparisonOp::Gt,
            value: value.into(),
        }
    }

    /// Create a greater-than-or-equal comparison
    pub fn gt_eq(column: impl Into<ColumnRef>, value: impl Into<Datum>) -> Self {
        Predicate::Comparison {
            column: column.into(),
            op: ComparisonOp::GtEq,
            value: value.into(),
        }
    }

    /// Create an IS NULL predicate
    pub fn is_null(column: impl Into<ColumnRef>) -> Self {
        Predicate::IsNull(column.into())
    }

    /// Create an IS NOT NULL predicate
    pub fn is_not_null(column: impl Into<ColumnRef>) -> Self {
        Predicate::IsNotNull(column.into())
    }

    /// Create an IN predicate
    pub fn is_in(column: impl Into<ColumnRef>, values: impl IntoIterator<Item = Datum>) -> Self {
        Predicate::In {
            column: column.into(),
            values: values.into_iter().collect(),
        }
    }

    /// Check if this predicate is always true
    pub fn is_always_true(&self) -> bool {
        matches!(self, Predicate::AlwaysTrue)
    }

    /// Check if this predicate is always false
    pub fn is_always_false(&self) -> bool {
        matches!(self, Predicate::AlwaysFalse)
    }

    /// Get all column references in this predicate
    pub fn columns(&self) -> Vec<&ColumnRef> {
        match self {
            Predicate::AlwaysTrue | Predicate::AlwaysFalse => vec![],
            Predicate::Comparison { column, .. } => vec![column],
            Predicate::IsNull(column) | Predicate::IsNotNull(column) => vec![column],
            Predicate::In { column, .. } => vec![column],
            Predicate::And(preds) | Predicate::Or(preds) => {
                preds.iter().flat_map(|p| p.columns()).collect()
            }
            Predicate::Not(pred) => pred.columns(),
        }
    }
}

impl fmt::Display for Predicate {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Predicate::AlwaysTrue => write!(f, "TRUE"),
            Predicate::AlwaysFalse => write!(f, "FALSE"),
            Predicate::Comparison { column, op, value } => {
                write!(f, "{} {} {}", column, op, value)
            }
            Predicate::IsNull(column) => write!(f, "{} IS NULL", column),
            Predicate::IsNotNull(column) => write!(f, "{} IS NOT NULL", column),
            Predicate::In { column, values } => {
                write!(f, "{} IN (", column)?;
                for (i, v) in values.iter().enumerate() {
                    if i > 0 {
                        write!(f, ", ")?;
                    }
                    write!(f, "{}", v)?;
                }
                write!(f, ")")
            }
            Predicate::And(preds) => {
                write!(f, "(")?;
                for (i, p) in preds.iter().enumerate() {
                    if i > 0 {
                        write!(f, " AND ")?;
                    }
                    write!(f, "{}", p)?;
                }
                write!(f, ")")
            }
            Predicate::Or(preds) => {
                write!(f, "(")?;
                for (i, p) in preds.iter().enumerate() {
                    if i > 0 {
                        write!(f, " OR ")?;
                    }
                    write!(f, "{}", p)?;
                }
                write!(f, ")")
            }
            Predicate::Not(pred) => write!(f, "NOT {}", pred),
        }
    }
}

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

    #[test]
    fn test_datum_comparison() {
        assert_eq!(
            Datum::Int(5).compare(&Datum::Int(10)),
            Some(std::cmp::Ordering::Less)
        );
        assert_eq!(
            Datum::Int(10).compare(&Datum::Long(5)),
            Some(std::cmp::Ordering::Greater)
        );
        assert_eq!(
            Datum::String("abc".into()).compare(&Datum::String("def".into())),
            Some(std::cmp::Ordering::Less)
        );
        // Incompatible types
        assert_eq!(Datum::Int(5).compare(&Datum::String("5".into())), None);
    }

    #[test]
    fn test_predicate_builders() {
        let p = Predicate::eq("name", "Alice");
        assert!(matches!(
            p,
            Predicate::Comparison {
                op: ComparisonOp::Eq,
                ..
            }
        ));

        let p = Predicate::and([Predicate::gt("age", 18), Predicate::lt("age", 65)]);
        assert!(matches!(p, Predicate::And(_)));
    }

    #[test]
    fn test_predicate_display() {
        let p = Predicate::and([
            Predicate::eq("status", "active"),
            Predicate::gt_eq("age", 21),
        ]);
        assert_eq!(p.to_string(), "(status = 'active' AND age >= 21)");
    }

    #[test]
    fn test_not_simplification() {
        assert!(matches!(
            Predicate::negate(Predicate::AlwaysTrue),
            Predicate::AlwaysFalse
        ));
        assert!(matches!(
            Predicate::negate(Predicate::AlwaysFalse),
            Predicate::AlwaysTrue
        ));

        // Double negation
        let p = Predicate::negate(Predicate::negate(Predicate::eq("x", 1)));
        assert!(matches!(p, Predicate::Comparison { .. }));
    }

    #[test]
    fn test_columns() {
        let p = Predicate::and([
            Predicate::eq("name", "test"),
            Predicate::gt("age", 18),
            Predicate::is_not_null("email"),
        ]);
        let cols = p.columns();
        assert_eq!(cols.len(), 3);
    }

    #[test]
    fn test_column_ref_named_validation() {
        // Valid name should succeed
        let col = ColumnRef::named("age");
        assert!(col.is_ok());
        assert_eq!(col.unwrap().name(), Some("age"));

        // Empty string should fail
        let empty = ColumnRef::named("");
        assert!(empty.is_err());
        assert!(empty
            .unwrap_err()
            .to_string()
            .contains("Column name cannot be empty"));

        // Empty String should also fail
        let empty_string = ColumnRef::named(String::new());
        assert!(empty_string.is_err());
    }

    #[test]
    fn test_column_ref_id_validation() {
        // Valid positive ID should succeed
        let col = ColumnRef::id(1);
        assert!(col.is_ok());
        assert!(matches!(col.unwrap(), ColumnRef::Id(1)));

        let col42 = ColumnRef::id(42);
        assert!(col42.is_ok());
        assert!(matches!(col42.unwrap(), ColumnRef::Id(42)));

        // Zero should fail
        let zero = ColumnRef::id(0);
        assert!(zero.is_err());
        assert!(zero.unwrap_err().to_string().contains("must be positive"));

        // Negative IDs should fail
        let negative = ColumnRef::id(-1);
        assert!(negative.is_err());
        assert!(negative
            .unwrap_err()
            .to_string()
            .contains("must be positive"));

        let very_negative = ColumnRef::id(-999);
        assert!(very_negative.is_err());
        assert!(very_negative
            .unwrap_err()
            .to_string()
            .contains("must be positive"));
    }

    #[test]
    fn test_column_ref_from_impls_no_validation() {
        // From impls should still work but don't validate
        // These document the unsafe behavior

        // String conversion - allows empty (but creates invalid ref)
        let _col_from_str: ColumnRef = "valid_name".into();
        let _empty_from_str: ColumnRef = "".into(); // Invalid but allowed

        // i32 conversion - allows negative (but creates invalid ref)
        let _col_from_i32: ColumnRef = 42.into();
        let _negative_from_i32: ColumnRef = (-1).into(); // Invalid but allowed
        let _zero_from_i32: ColumnRef = 0.into(); // Invalid but allowed
    }
}