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
//! Partition predicate evaluation for file filtering
//!
//! This module provides functions to evaluate predicates against partition values
//! to determine if a file might contain matching rows.

use super::date::{
    days_to_year, days_to_year_month, parse_date_to_days, parse_date_year, parse_date_year_month,
};
use crate::expr::{ColumnRef, ComparisonOp, Datum, Predicate};
use crate::spec::{PartitionField, PartitionSpec, Schema, Type};
use std::collections::HashMap;

/// Iceberg partition transforms
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Transform {
    /// Identity transform (value unchanged)
    Identity,
    /// Year transform for date/timestamp
    Year,
    /// Month transform for date/timestamp
    Month,
    /// Day transform for date/timestamp
    Day,
    /// Hour transform for timestamp
    Hour,
    /// Bucket hash transform
    Bucket(u32),
    /// Truncate transform
    Truncate(u32),
    /// Void transform (always null)
    Void,
}

impl Transform {
    /// Parse a transform string from Iceberg metadata
    pub fn parse(s: &str) -> Option<Self> {
        let s = s.to_lowercase();
        if s == "identity" {
            return Some(Transform::Identity);
        }
        if s == "year" {
            return Some(Transform::Year);
        }
        if s == "month" {
            return Some(Transform::Month);
        }
        if s == "day" {
            return Some(Transform::Day);
        }
        if s == "hour" {
            return Some(Transform::Hour);
        }
        if s == "void" {
            return Some(Transform::Void);
        }
        if let Some(n) = s.strip_prefix("bucket[").and_then(|s| s.strip_suffix(']')) {
            if let Ok(num) = n.parse::<u32>() {
                // Validate width > 0 to prevent division by zero
                if num > 0 {
                    return Some(Transform::Bucket(num));
                }
            }
        }
        if let Some(n) = s
            .strip_prefix("truncate[")
            .and_then(|s| s.strip_suffix(']'))
        {
            if let Ok(num) = n.parse::<u32>() {
                // Validate width > 0 to prevent division by zero
                if num > 0 {
                    return Some(Transform::Truncate(num));
                }
            }
        }
        None
    }
}

/// Information about how a source column maps to a partition field
#[derive(Debug, Clone)]
pub struct PartitionMapping {
    /// Source column field ID
    pub source_id: i32,
    /// Partition field ID (used as key in partition values map)
    pub partition_field_id: i32,
    /// Transform applied to source column
    pub transform: Transform,
}

/// Build a mapping from source column IDs to partition fields
pub fn build_partition_mapping(spec: &PartitionSpec) -> Vec<PartitionMapping> {
    spec.fields()
        .iter()
        .filter_map(|f| {
            let transform = Transform::parse(f.transform())?;
            Some(PartitionMapping {
                source_id: f.source_id(),
                partition_field_id: f.field_id(),
                transform,
            })
        })
        .collect()
}

/// Resolve a column reference to a field ID using the schema
pub fn resolve_column_id(col: &ColumnRef, schema: &Schema) -> Option<i32> {
    match col {
        ColumnRef::Id(id) => Some(*id),
        ColumnRef::Named(name) => schema.as_struct().field_by_name(name).map(|f| f.id()),
    }
}

/// Project a predicate to partition columns
///
/// Returns a new predicate that can be evaluated against partition values.
/// If a column in the predicate is not a partition column, it is replaced with AlwaysTrue.
pub fn project_to_partition(
    predicate: &Predicate,
    schema: &Schema,
    spec: &PartitionSpec,
) -> Predicate {
    let mapping = build_partition_mapping(spec);

    project_predicate_impl(predicate, schema, &mapping)
}

fn project_predicate_impl(
    predicate: &Predicate,
    schema: &Schema,
    mapping: &[PartitionMapping],
) -> Predicate {
    match predicate {
        Predicate::AlwaysTrue => Predicate::AlwaysTrue,
        Predicate::AlwaysFalse => Predicate::AlwaysFalse,

        Predicate::Comparison { column, op, value } => {
            if let Some(field_id) = resolve_column_id(column, schema) {
                // Find partition mapping for this source column
                if let Some(pm) = mapping.iter().find(|m| m.source_id == field_id) {
                    // Transform the value based on the partition transform
                    if let Some(transformed_value) =
                        transform_value_for_partition(value, pm.transform)
                    {
                        // For non-identity transforms, some operations can't be pushed down
                        let can_push = match pm.transform {
                            Transform::Identity => true,
                            Transform::Year | Transform::Month | Transform::Day => {
                                // Range predicates can be pushed for temporal transforms
                                // but need careful handling of boundaries
                                matches!(
                                    op,
                                    ComparisonOp::Eq | ComparisonOp::Lt | ComparisonOp::GtEq
                                )
                            }
                            Transform::Hour => matches!(op, ComparisonOp::Eq),
                            Transform::Bucket(_) => matches!(op, ComparisonOp::Eq),
                            Transform::Truncate(_) => matches!(op, ComparisonOp::Eq),
                            Transform::Void => false,
                        };

                        if can_push {
                            // partition_field_id comes from Iceberg metadata and should be valid
                            // If it's invalid, this indicates corrupted metadata
                            let column = ColumnRef::id(pm.partition_field_id)
                                .expect("partition field ID from metadata should be positive");
                            return Predicate::Comparison {
                                column,
                                op: *op,
                                value: transformed_value,
                            };
                        }
                    }
                }
            }
            // Cannot project to partition - return true (file might contain matches)
            Predicate::AlwaysTrue
        }

        Predicate::IsNull(column) => {
            if let Some(field_id) = resolve_column_id(column, schema) {
                if let Some(pm) = mapping.iter().find(|m| m.source_id == field_id) {
                    // IS NULL can always be pushed to partition
                    let col = ColumnRef::id(pm.partition_field_id)
                        .expect("partition field ID from metadata should be positive");
                    return Predicate::IsNull(col);
                }
            }
            Predicate::AlwaysTrue
        }

        Predicate::IsNotNull(column) => {
            if let Some(field_id) = resolve_column_id(column, schema) {
                if let Some(pm) = mapping.iter().find(|m| m.source_id == field_id) {
                    let col = ColumnRef::id(pm.partition_field_id)
                        .expect("partition field ID from metadata should be positive");
                    return Predicate::IsNotNull(col);
                }
            }
            Predicate::AlwaysTrue
        }

        Predicate::In { column, values } => {
            if let Some(field_id) = resolve_column_id(column, schema) {
                if let Some(pm) = mapping.iter().find(|m| m.source_id == field_id) {
                    // Only identity transform supports IN pushdown reliably
                    if pm.transform == Transform::Identity {
                        let col = ColumnRef::id(pm.partition_field_id)
                            .expect("partition field ID from metadata should be positive");
                        return Predicate::In {
                            column: col,
                            values: values.clone(),
                        };
                    }
                }
            }
            Predicate::AlwaysTrue
        }

        Predicate::And(preds) => {
            let projected: Vec<_> = preds
                .iter()
                .map(|p| project_predicate_impl(p, schema, mapping))
                .collect();
            Predicate::and(projected)
        }

        Predicate::Or(preds) => {
            let projected: Vec<_> = preds
                .iter()
                .map(|p| project_predicate_impl(p, schema, mapping))
                .collect();
            // If any branch is always true, the whole OR is always true
            if projected.iter().any(|p| p.is_always_true()) {
                Predicate::AlwaysTrue
            } else {
                Predicate::or(projected)
            }
        }

        Predicate::Not(_) => {
            // NOT is tricky for partition pruning - we can't simply negate
            // because partition values might not uniquely identify rows
            Predicate::AlwaysTrue
        }
    }
}

/// Transform a datum value based on the partition transform
fn transform_value_for_partition(value: &Datum, transform: Transform) -> Option<Datum> {
    match transform {
        Transform::Identity => Some(value.clone()),

        Transform::Year => match value {
            // Date: days since epoch -> year
            Datum::Date(days) => {
                let year = days_to_year(*days);
                Some(Datum::Int(year))
            }
            // Timestamp: microseconds since epoch -> year
            Datum::Timestamp(micros) => {
                let days = (*micros / 86_400_000_000) as i32;
                let year = days_to_year(days);
                Some(Datum::Int(year))
            }
            // String date like "2024-01-15"
            Datum::String(s) => parse_date_year(s).map(Datum::Int),
            _ => None,
        },

        Transform::Month => match value {
            Datum::Date(days) => {
                let (year, month) = days_to_year_month(*days);
                // Use checked arithmetic to prevent overflow for extreme year values
                year.checked_mul(12)
                    .and_then(|v| v.checked_add(month - 1))
                    .map(Datum::Int)
            }
            Datum::Timestamp(micros) => {
                let days = (*micros / 86_400_000_000) as i32;
                let (year, month) = days_to_year_month(days);
                // Use checked arithmetic to prevent overflow for extreme year values
                year.checked_mul(12)
                    .and_then(|v| v.checked_add(month - 1))
                    .map(Datum::Int)
            }
            Datum::String(s) => parse_date_year_month(s).and_then(|(year, month)| {
                // Use checked arithmetic to prevent overflow for extreme year values
                year.checked_mul(12)
                    .and_then(|v| v.checked_add(month - 1))
                    .map(Datum::Int)
            }),
            _ => None,
        },

        Transform::Day => match value {
            Datum::Date(days) => Some(Datum::Int(*days)),
            Datum::Timestamp(micros) => {
                let days = (*micros / 86_400_000_000) as i32;
                Some(Datum::Int(days))
            }
            Datum::String(s) => parse_date_to_days(s).map(Datum::Int),
            _ => None,
        },

        Transform::Hour => match value {
            Datum::Timestamp(micros) => {
                let hours = (*micros / 3_600_000_000) as i32;
                Some(Datum::Int(hours))
            }
            _ => None,
        },

        Transform::Bucket(_) => {
            // Bucket transform requires computing hash of the value
            // For simplicity, we don't transform - predicate will be AlwaysTrue
            None
        }

        Transform::Truncate(width) => {
            // Safety guard: width must be > 0 to prevent division by zero
            if width == 0 {
                return None;
            }
            match value {
                Datum::Int(v) => Some(Datum::Int((v / width as i32) * width as i32)),
                Datum::Long(v) => Some(Datum::Long((v / width as i64) * width as i64)),
                Datum::String(s) => {
                    let truncated: String = s.chars().take(width as usize).collect();
                    Some(Datum::String(truncated))
                }
                _ => None,
            }
        }

        Transform::Void => None,
    }
}

/// Evaluate a projected predicate against partition values
///
/// Returns true if the partition MIGHT contain matching rows.
/// Returns false only if we can definitively prove no matches exist.
pub fn evaluate_partition(
    predicate: &Predicate,
    partition_values: &HashMap<i32, Vec<u8>>,
    partition_fields: &[PartitionField],
    schema: &Schema,
) -> bool {
    match predicate {
        Predicate::AlwaysTrue => true,
        Predicate::AlwaysFalse => false,

        Predicate::Comparison { column, op, value } => {
            let field_id = match column {
                ColumnRef::Id(id) => *id,
                ColumnRef::Named(_) => return true, // Can't evaluate named refs against partition
            };

            // Find the partition field to get its type
            let field_type = partition_fields
                .iter()
                .find(|f| f.field_id() == field_id)
                .and_then(|pf| {
                    // Get source field type from schema
                    schema.as_struct().field_by_id(pf.source_id())
                })
                .map(|f| f.field_type());

            // Get partition value bytes
            let Some(bytes) = partition_values.get(&field_id) else {
                // No value means null partition - only match IS NULL predicates
                return true;
            };

            // Decode and compare
            if let Some(partition_datum) = decode_partition_value(bytes, field_type) {
                if let Some(ordering) = partition_datum.compare(value) {
                    return op.evaluate(ordering);
                }
            }

            // Can't evaluate - assume might match
            true
        }

        Predicate::IsNull(column) => {
            let field_id = match column {
                ColumnRef::Id(id) => *id,
                ColumnRef::Named(_) => return true,
            };

            // Partition is null if not in the map
            !partition_values.contains_key(&field_id)
        }

        Predicate::IsNotNull(column) => {
            let field_id = match column {
                ColumnRef::Id(id) => *id,
                ColumnRef::Named(_) => return true,
            };

            partition_values.contains_key(&field_id)
        }

        Predicate::In { column, values } => {
            let field_id = match column {
                ColumnRef::Id(id) => *id,
                ColumnRef::Named(_) => return true,
            };

            let field_type = partition_fields
                .iter()
                .find(|f| f.field_id() == field_id)
                .and_then(|pf| schema.as_struct().field_by_id(pf.source_id()))
                .map(|f| f.field_type());

            let Some(bytes) = partition_values.get(&field_id) else {
                return true;
            };

            if let Some(partition_datum) = decode_partition_value(bytes, field_type) {
                // Check if partition value is in the set
                for v in values {
                    if partition_datum.compare(v) == Some(std::cmp::Ordering::Equal) {
                        return true;
                    }
                }
                return false;
            }

            true
        }

        Predicate::And(preds) => preds
            .iter()
            .all(|p| evaluate_partition(p, partition_values, partition_fields, schema)),

        Predicate::Or(preds) => preds
            .iter()
            .any(|p| evaluate_partition(p, partition_values, partition_fields, schema)),

        Predicate::Not(inner) => {
            !evaluate_partition(inner, partition_values, partition_fields, schema)
        }
    }
}

/// Decode raw bytes to a Datum based on the field type
fn decode_partition_value(bytes: &[u8], field_type: Option<&Type>) -> Option<Datum> {
    let typ = field_type?;

    match typ {
        Type::Primitive(prim) => Datum::from_bytes(bytes, prim),
        _ => None,
    }
}

#[cfg(test)]
mod tests {
    use super::super::date::year_to_days;
    use super::*;
    use crate::PrimitiveType;

    #[test]
    fn test_transform_parse() {
        assert_eq!(Transform::parse("identity"), Some(Transform::Identity));
        assert_eq!(Transform::parse("Identity"), Some(Transform::Identity));
        assert_eq!(Transform::parse("year"), Some(Transform::Year));
        assert_eq!(Transform::parse("bucket[16]"), Some(Transform::Bucket(16)));
        assert_eq!(
            Transform::parse("truncate[100]"),
            Some(Transform::Truncate(100))
        );
        assert_eq!(Transform::parse("void"), Some(Transform::Void));
    }

    #[test]
    fn test_days_to_year() {
        // 1970-01-01 is day 0
        assert_eq!(days_to_year(0), 1970);
        // 2024-01-01 is approximately day 19724
        let days_2024 = year_to_days(2024);
        assert_eq!(days_to_year(days_2024), 2024);
    }

    #[test]
    fn test_parse_date_to_days() {
        let days = parse_date_to_days("2024-01-15").unwrap();
        let (year, month) = days_to_year_month(days);
        assert_eq!(year, 2024);
        assert_eq!(month, 1);
    }

    #[test]
    fn test_decode_primitive() {
        // Int
        let bytes = 42i32.to_le_bytes().to_vec();
        assert_eq!(
            Datum::from_bytes(&bytes, &PrimitiveType::Int),
            Some(Datum::Int(42))
        );

        // String
        let bytes = b"hello".to_vec();
        assert_eq!(
            Datum::from_bytes(&bytes, &PrimitiveType::String),
            Some(Datum::String("hello".to_string()))
        );
    }

    #[test]
    fn test_transform_parse_zero_width_rejection() {
        // bucket[0] should be rejected
        assert_eq!(Transform::parse("bucket[0]"), None);

        // truncate[0] should be rejected
        assert_eq!(Transform::parse("truncate[0]"), None);

        // Valid widths should still work
        assert_eq!(Transform::parse("bucket[1]"), Some(Transform::Bucket(1)));
        assert_eq!(
            Transform::parse("truncate[1]"),
            Some(Transform::Truncate(1))
        );
        assert_eq!(
            Transform::parse("bucket[100]"),
            Some(Transform::Bucket(100))
        );
        assert_eq!(
            Transform::parse("truncate[100]"),
            Some(Transform::Truncate(100))
        );
    }

    #[test]
    fn test_transform_parse_malformed_input() {
        // Non-numeric values should be rejected
        assert_eq!(Transform::parse("bucket[abc]"), None);
        assert_eq!(Transform::parse("truncate[xyz]"), None);
        assert_eq!(Transform::parse("bucket[not_a_number]"), None);

        // Missing brackets or malformed syntax
        assert_eq!(Transform::parse("bucket"), None);
        assert_eq!(Transform::parse("truncate"), None);
        assert_eq!(Transform::parse("bucket[10"), None);
        assert_eq!(Transform::parse("truncate10]"), None);
    }

    #[test]
    fn test_truncate_transform_zero_width_safety() {
        // Even if a zero-width transform somehow exists (shouldn't happen after parser fix),
        // the transform function should handle it safely
        let value = Datum::Int(100);
        let result = transform_value_for_partition(&value, Transform::Truncate(0));
        assert_eq!(result, None);

        let value = Datum::Long(1000);
        let result = transform_value_for_partition(&value, Transform::Truncate(0));
        assert_eq!(result, None);
    }

    #[test]
    fn test_truncate_transform_valid_widths() {
        // Test that valid widths still work correctly
        let value = Datum::Int(123);
        let result = transform_value_for_partition(&value, Transform::Truncate(10));
        assert_eq!(result, Some(Datum::Int(120)));

        let value = Datum::Long(456);
        let result = transform_value_for_partition(&value, Transform::Truncate(100));
        assert_eq!(result, Some(Datum::Long(400)));

        let value = Datum::String("hello world".to_string());
        let result = transform_value_for_partition(&value, Transform::Truncate(5));
        assert_eq!(result, Some(Datum::String("hello".to_string())));
    }
}