forked from apache/iceberg-python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtransforms.py
1067 lines (814 loc) · 37.3 KB
/
transforms.py
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
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# 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.
import base64
import struct
from abc import ABC, abstractmethod
from enum import IntEnum
from functools import singledispatch
from typing import TYPE_CHECKING, Any, Callable, Generic, Optional, TypeVar
from typing import Literal as LiteralType
from uuid import UUID
import mmh3
from pydantic import Field, PositiveInt, PrivateAttr
from pyiceberg.expressions import (
BoundEqualTo,
BoundGreaterThan,
BoundGreaterThanOrEqual,
BoundIn,
BoundLessThan,
BoundLessThanOrEqual,
BoundLiteralPredicate,
BoundNotEqualTo,
BoundNotIn,
BoundNotStartsWith,
BoundPredicate,
BoundSetPredicate,
BoundStartsWith,
BoundTerm,
BoundUnaryPredicate,
EqualTo,
GreaterThan,
GreaterThanOrEqual,
LessThan,
LessThanOrEqual,
NotEqualTo,
NotStartsWith,
Reference,
StartsWith,
UnboundPredicate,
)
from pyiceberg.expressions.literals import (
DateLiteral,
DecimalLiteral,
Literal,
LongLiteral,
TimestampLiteral,
literal,
)
from pyiceberg.typedef import IcebergRootModel, L
from pyiceberg.types import (
BinaryType,
DateType,
DecimalType,
FixedType,
IcebergType,
IntegerType,
LongType,
StringType,
TimestampType,
TimestamptzType,
TimeType,
UUIDType,
)
from pyiceberg.utils import datetime
from pyiceberg.utils.decimal import decimal_to_bytes, truncate_decimal
from pyiceberg.utils.parsing import ParseNumberFromBrackets
from pyiceberg.utils.singleton import Singleton
if TYPE_CHECKING:
import pyarrow as pa
S = TypeVar("S")
T = TypeVar("T")
IDENTITY = "identity"
VOID = "void"
BUCKET = "bucket"
TRUNCATE = "truncate"
YEAR = "year"
MONTH = "month"
DAY = "day"
HOUR = "hour"
BUCKET_PARSER = ParseNumberFromBrackets(BUCKET)
TRUNCATE_PARSER = ParseNumberFromBrackets(TRUNCATE)
def _transform_literal(func: Callable[[L], L], lit: Literal[L]) -> Literal[L]:
"""Small helper to upwrap the value from the literal, and wrap it again."""
return literal(func(lit.value))
def parse_transform(v: Any) -> Any:
if isinstance(v, str):
if v == IDENTITY:
return IdentityTransform()
elif v == VOID:
return VoidTransform()
elif v.startswith(BUCKET):
return BucketTransform(num_buckets=BUCKET_PARSER.match(v))
elif v.startswith(TRUNCATE):
return TruncateTransform(width=TRUNCATE_PARSER.match(v))
elif v == YEAR:
return YearTransform()
elif v == MONTH:
return MonthTransform()
elif v == DAY:
return DayTransform()
elif v == HOUR:
return HourTransform()
else:
return UnknownTransform(transform=v)
return v
class Transform(IcebergRootModel[str], ABC, Generic[S, T]):
"""Transform base class for concrete transforms.
A base class to transform values and project predicates on partition values.
This class is not used directly. Instead, use one of module method to create the child classes.
"""
root: str = Field()
@abstractmethod
def transform(self, source: IcebergType) -> Callable[[Optional[S]], Optional[T]]: ...
@abstractmethod
def can_transform(self, source: IcebergType) -> bool:
return False
@abstractmethod
def result_type(self, source: IcebergType) -> IcebergType:
"""Return the `IcebergType` produced by this transform given a source type.
This method defines both the physical and display representation of the partition field.
The physical representation must conform to the Iceberg spec. The display representation
can deviate from the spec, such as by transforming the value into a more human-readable format.
"""
...
@abstractmethod
def project(self, name: str, pred: BoundPredicate[L]) -> Optional[UnboundPredicate[Any]]: ...
@abstractmethod
def strict_project(self, name: str, pred: BoundPredicate[Any]) -> Optional[UnboundPredicate[Any]]: ...
@property
def preserves_order(self) -> bool:
return False
def satisfies_order_of(self, other: Any) -> bool:
return self == other
def to_human_string(self, _: IcebergType, value: Optional[S]) -> str:
return str(value) if value is not None else "null"
@property
def dedup_name(self) -> str:
return self.__str__()
def __str__(self) -> str:
"""Return the string representation of the Transform class."""
return self.root
def __eq__(self, other: Any) -> bool:
"""Return the equality of two instances of the Transform class."""
if isinstance(other, Transform):
return self.root == other.root
return False
@property
def supports_pyarrow_transform(self) -> bool:
return False
@abstractmethod
def pyarrow_transform(self, source: IcebergType) -> "Callable[[pa.Array], pa.Array]": ...
class BucketTransform(Transform[S, int]):
"""Base Transform class to transform a value into a bucket partition value.
Transforms are parameterized by a number of buckets. Bucket partition transforms use a 32-bit
hash of the source value to produce a positive value by mod the bucket number.
Args:
num_buckets (int): The number of buckets.
"""
root: str = Field()
_num_buckets: PositiveInt = PrivateAttr()
def __init__(self, num_buckets: int, **data: Any) -> None:
self._num_buckets = num_buckets
super().__init__(f"bucket[{num_buckets}]", **data)
@property
def num_buckets(self) -> int:
return self._num_buckets
def hash(self, value: S) -> int:
raise NotImplementedError()
def apply(self, value: Optional[S]) -> Optional[int]:
return (self.hash(value) & IntegerType.max) % self._num_buckets if value else None
def result_type(self, source: IcebergType) -> IcebergType:
return IntegerType()
def project(self, name: str, pred: BoundPredicate[L]) -> Optional[UnboundPredicate[Any]]:
transformer = self.transform(pred.term.ref().field.field_type)
if isinstance(pred.term, BoundTransform):
return _project_transform_predicate(self, name, pred)
elif isinstance(pred, BoundUnaryPredicate):
return pred.as_unbound(Reference(name))
elif isinstance(pred, BoundEqualTo):
return pred.as_unbound(Reference(name), _transform_literal(transformer, pred.literal))
elif isinstance(pred, BoundIn): # NotIn can't be projected
return pred.as_unbound(Reference(name), {_transform_literal(transformer, literal) for literal in pred.literals})
else:
# - Comparison predicates can't be projected, notEq can't be projected
# - Small ranges can be projected:
# For example, (x > 0) and (x < 3) can be turned into in({1, 2}) and projected.
return None
def strict_project(self, name: str, pred: BoundPredicate[Any]) -> Optional[UnboundPredicate[Any]]:
transformer = self.transform(pred.term.ref().field.field_type)
if isinstance(pred.term, BoundTransform):
return _project_transform_predicate(self, name, pred)
elif isinstance(pred, BoundUnaryPredicate):
return pred.as_unbound(Reference(name))
elif isinstance(pred, BoundNotEqualTo):
return pred.as_unbound(Reference(name), _transform_literal(transformer, pred.literal))
elif isinstance(pred, BoundNotIn):
return pred.as_unbound(Reference(name), {_transform_literal(transformer, literal) for literal in pred.literals})
else:
# no strict projection for comparison or equality
return None
def can_transform(self, source: IcebergType) -> bool:
return isinstance(
source,
(
IntegerType,
DateType,
LongType,
TimeType,
TimestampType,
TimestamptzType,
DecimalType,
StringType,
FixedType,
BinaryType,
UUIDType,
),
)
def transform(self, source: IcebergType, bucket: bool = True) -> Callable[[Optional[Any]], Optional[int]]:
if isinstance(source, (IntegerType, LongType, DateType, TimeType, TimestampType, TimestamptzType)):
def hash_func(v: Any) -> int:
return mmh3.hash(struct.pack("<q", v))
elif isinstance(source, DecimalType):
def hash_func(v: Any) -> int:
return mmh3.hash(decimal_to_bytes(v))
elif isinstance(source, (StringType, FixedType, BinaryType)):
def hash_func(v: Any) -> int:
return mmh3.hash(v)
elif isinstance(source, UUIDType):
def hash_func(v: Any) -> int:
if isinstance(v, UUID):
return mmh3.hash(v.bytes)
return mmh3.hash(v)
else:
raise ValueError(f"Unknown type {source}")
if bucket:
return lambda v: (hash_func(v) & IntegerType.max) % self._num_buckets if v is not None else None
return hash_func
def __repr__(self) -> str:
"""Return the string representation of the BucketTransform class."""
return f"BucketTransform(num_buckets={self._num_buckets})"
def pyarrow_transform(self, source: IcebergType) -> "Callable[[pa.Array], pa.Array]":
raise NotImplementedError()
class TimeResolution(IntEnum):
YEAR = 6
MONTH = 5
WEEK = 4
DAY = 3
HOUR = 2
MINUTE = 1
SECOND = 0
class TimeTransform(Transform[S, int], Generic[S], Singleton):
@property
@abstractmethod
def granularity(self) -> TimeResolution: ...
def satisfies_order_of(self, other: Transform[S, T]) -> bool:
return self.granularity <= other.granularity if hasattr(other, "granularity") else False
def result_type(self, source: IcebergType) -> IntegerType:
return IntegerType()
@abstractmethod
def transform(self, source: IcebergType) -> Callable[[Optional[Any]], Optional[int]]: ...
def project(self, name: str, pred: BoundPredicate[L]) -> Optional[UnboundPredicate[Any]]:
transformer = self.transform(pred.term.ref().field.field_type)
if isinstance(pred.term, BoundTransform):
return _project_transform_predicate(self, name, pred)
elif isinstance(pred, BoundUnaryPredicate):
return pred.as_unbound(Reference(name))
elif isinstance(pred, BoundLiteralPredicate):
return _truncate_number(name, pred, transformer)
elif isinstance(pred, BoundIn): # NotIn can't be projected
return _set_apply_transform(name, pred, transformer)
else:
return None
def strict_project(self, name: str, pred: BoundPredicate[Any]) -> Optional[UnboundPredicate[Any]]:
transformer = self.transform(pred.term.ref().field.field_type)
if isinstance(pred.term, BoundTransform):
return _project_transform_predicate(self, name, pred)
elif isinstance(pred, BoundUnaryPredicate):
return pred.as_unbound(Reference(name))
elif isinstance(pred, BoundLiteralPredicate):
return _truncate_number_strict(name, pred, transformer)
elif isinstance(pred, BoundNotIn):
return _set_apply_transform(name, pred, transformer)
else:
return None
@property
def dedup_name(self) -> str:
return "time"
@property
def preserves_order(self) -> bool:
return True
@property
def supports_pyarrow_transform(self) -> bool:
return True
class YearTransform(TimeTransform[S]):
"""Transforms a datetime value into a year value.
Example:
>>> transform = YearTransform()
>>> transform.transform(TimestampType())(1512151975038194)
47
"""
root: LiteralType["year"] = Field(default="year") # noqa: F821
def transform(self, source: IcebergType) -> Callable[[Optional[S]], Optional[int]]:
if isinstance(source, DateType):
def year_func(v: Any) -> int:
return datetime.days_to_years(v)
elif isinstance(source, (TimestampType, TimestamptzType)):
def year_func(v: Any) -> int:
return datetime.micros_to_years(v)
else:
raise ValueError(f"Cannot apply year transform for type: {source}")
return lambda v: year_func(v) if v is not None else None
def can_transform(self, source: IcebergType) -> bool:
return isinstance(source, (DateType, TimestampType, TimestamptzType))
@property
def granularity(self) -> TimeResolution:
return TimeResolution.YEAR
def to_human_string(self, _: IcebergType, value: Optional[S]) -> str:
return datetime.to_human_year(value) if isinstance(value, int) else "null"
def __repr__(self) -> str:
"""Return the string representation of the YearTransform class."""
return "YearTransform()"
def pyarrow_transform(self, source: IcebergType) -> "Callable[[pa.Array], pa.Array]":
import pyarrow as pa
import pyarrow.compute as pc
if isinstance(source, DateType):
epoch = datetime.EPOCH_DATE
elif isinstance(source, TimestampType):
epoch = datetime.EPOCH_TIMESTAMP
elif isinstance(source, TimestamptzType):
epoch = datetime.EPOCH_TIMESTAMPTZ
else:
raise ValueError(f"Cannot apply year transform for type: {source}")
return lambda v: pc.years_between(pa.scalar(epoch), v) if v is not None else None
class MonthTransform(TimeTransform[S]):
"""Transforms a datetime value into a month value.
Example:
>>> transform = MonthTransform()
>>> transform.transform(DateType())(17501)
575
"""
root: LiteralType["month"] = Field(default="month") # noqa: F821
def transform(self, source: IcebergType) -> Callable[[Optional[S]], Optional[int]]:
if isinstance(source, DateType):
def month_func(v: Any) -> int:
return datetime.days_to_months(v)
elif isinstance(source, (TimestampType, TimestamptzType)):
def month_func(v: Any) -> int:
return datetime.micros_to_months(v)
else:
raise ValueError(f"Cannot apply month transform for type: {source}")
return lambda v: month_func(v) if v is not None else None
def can_transform(self, source: IcebergType) -> bool:
return isinstance(source, (DateType, TimestampType, TimestamptzType))
@property
def granularity(self) -> TimeResolution:
return TimeResolution.MONTH
def to_human_string(self, _: IcebergType, value: Optional[S]) -> str:
return datetime.to_human_month(value) if isinstance(value, int) else "null"
def __repr__(self) -> str:
"""Return the string representation of the MonthTransform class."""
return "MonthTransform()"
def pyarrow_transform(self, source: IcebergType) -> "Callable[[pa.Array], pa.Array]":
import pyarrow as pa
import pyarrow.compute as pc
if isinstance(source, DateType):
epoch = datetime.EPOCH_DATE
elif isinstance(source, TimestampType):
epoch = datetime.EPOCH_TIMESTAMP
elif isinstance(source, TimestamptzType):
epoch = datetime.EPOCH_TIMESTAMPTZ
else:
raise ValueError(f"Cannot apply month transform for type: {source}")
def month_func(v: pa.Array) -> pa.Array:
return pc.add(
pc.multiply(pc.years_between(pa.scalar(epoch), v), pa.scalar(12)),
pc.add(pc.month(v), pa.scalar(-1)),
)
return lambda v: month_func(v) if v is not None else None
class DayTransform(TimeTransform[S]):
"""Transforms a datetime value into a day value.
Example:
>>> transform = DayTransform()
>>> transform.transform(DateType())(17501)
17501
"""
root: LiteralType["day"] = Field(default="day") # noqa: F821
def transform(self, source: IcebergType) -> Callable[[Optional[S]], Optional[int]]:
if isinstance(source, DateType):
def day_func(v: Any) -> int:
return v
elif isinstance(source, (TimestampType, TimestamptzType)):
def day_func(v: Any) -> int:
return datetime.micros_to_days(v)
else:
raise ValueError(f"Cannot apply day transform for type: {source}")
return lambda v: day_func(v) if v is not None else None
def can_transform(self, source: IcebergType) -> bool:
return isinstance(source, (DateType, TimestampType, TimestamptzType))
def result_type(self, source: IcebergType) -> IcebergType:
"""Return the result type of a day transform.
The physical representation conforms to the Iceberg spec as DateType is internally converted to int.
The DateType returned here provides a more human-readable way to display the partition field.
"""
return DateType()
@property
def granularity(self) -> TimeResolution:
return TimeResolution.DAY
def to_human_string(self, _: IcebergType, value: Optional[S]) -> str:
return datetime.to_human_day(value) if isinstance(value, int) else "null"
def __repr__(self) -> str:
"""Return the string representation of the DayTransform class."""
return "DayTransform()"
def pyarrow_transform(self, source: IcebergType) -> "Callable[[pa.Array], pa.Array]":
import pyarrow as pa
import pyarrow.compute as pc
if isinstance(source, DateType):
epoch = datetime.EPOCH_DATE
elif isinstance(source, TimestampType):
epoch = datetime.EPOCH_TIMESTAMP
elif isinstance(source, TimestamptzType):
epoch = datetime.EPOCH_TIMESTAMPTZ
else:
raise ValueError(f"Cannot apply day transform for type: {source}")
return lambda v: pc.days_between(pa.scalar(epoch), v) if v is not None else None
class HourTransform(TimeTransform[S]):
"""Transforms a datetime value into a hour value.
Example:
>>> transform = HourTransform()
>>> transform.transform(TimestampType())(1512151975038194)
420042
"""
root: LiteralType["hour"] = Field(default="hour") # noqa: F821
def transform(self, source: IcebergType) -> Callable[[Optional[S]], Optional[int]]:
if isinstance(source, (TimestampType, TimestamptzType)):
def hour_func(v: Any) -> int:
return datetime.micros_to_hours(v)
else:
raise ValueError(f"Cannot apply hour transform for type: {source}")
return lambda v: hour_func(v) if v is not None else None
def can_transform(self, source: IcebergType) -> bool:
return isinstance(source, (TimestampType, TimestamptzType))
@property
def granularity(self) -> TimeResolution:
return TimeResolution.HOUR
def to_human_string(self, _: IcebergType, value: Optional[S]) -> str:
return datetime.to_human_hour(value) if isinstance(value, int) else "null"
def __repr__(self) -> str:
"""Return the string representation of the HourTransform class."""
return "HourTransform()"
def pyarrow_transform(self, source: IcebergType) -> "Callable[[pa.Array], pa.Array]":
import pyarrow as pa
import pyarrow.compute as pc
if isinstance(source, TimestampType):
epoch = datetime.EPOCH_TIMESTAMP
elif isinstance(source, TimestamptzType):
epoch = datetime.EPOCH_TIMESTAMPTZ
else:
raise ValueError(f"Cannot apply hour transform for type: {source}")
return lambda v: pc.hours_between(pa.scalar(epoch), v) if v is not None else None
def _base64encode(buffer: bytes) -> str:
"""Convert bytes to base64 string."""
return base64.b64encode(buffer).decode("ISO-8859-1")
class IdentityTransform(Transform[S, S]):
"""Transforms a value into itself.
Example:
>>> transform = IdentityTransform()
>>> transform.transform(StringType())('hello-world')
'hello-world'
"""
root: LiteralType["identity"] = Field(default="identity") # noqa: F821
def __init__(self) -> None:
super().__init__("identity")
def transform(self, source: IcebergType) -> Callable[[Optional[S]], Optional[S]]:
return lambda v: v
def can_transform(self, source: IcebergType) -> bool:
return source.is_primitive
def result_type(self, source: IcebergType) -> IcebergType:
return source
def project(self, name: str, pred: BoundPredicate[L]) -> Optional[UnboundPredicate[Any]]:
if isinstance(pred.term, BoundTransform):
return _project_transform_predicate(self, name, pred)
elif isinstance(pred, BoundUnaryPredicate):
return pred.as_unbound(Reference(name))
elif isinstance(pred, BoundLiteralPredicate):
return pred.as_unbound(Reference(name), pred.literal)
elif isinstance(pred, BoundSetPredicate):
return pred.as_unbound(Reference(name), pred.literals)
else:
return None
def strict_project(self, name: str, pred: BoundPredicate[Any]) -> Optional[UnboundPredicate[Any]]:
if isinstance(pred, BoundUnaryPredicate):
return pred.as_unbound(Reference(name))
elif isinstance(pred, BoundLiteralPredicate):
return pred.as_unbound(Reference(name), pred.literal)
elif isinstance(pred, BoundSetPredicate):
return pred.as_unbound(Reference(name), pred.literals)
else:
return None
@property
def preserves_order(self) -> bool:
return True
def satisfies_order_of(self, other: Transform[S, T]) -> bool:
"""Ordering by value is the same as long as the other preserves order."""
return other.preserves_order
def to_human_string(self, source_type: IcebergType, value: Optional[S]) -> str:
return _human_string(value, source_type) if value is not None else "null"
def __str__(self) -> str:
"""Return the string representation of the IdentityTransform class."""
return "identity"
def __repr__(self) -> str:
"""Return the string representation of the IdentityTransform class."""
return "IdentityTransform()"
def pyarrow_transform(self, source: IcebergType) -> "Callable[[pa.Array], pa.Array]":
return lambda v: v
@property
def supports_pyarrow_transform(self) -> bool:
return True
class TruncateTransform(Transform[S, S]):
"""A transform for truncating a value to a specified width.
Args:
width (int): The truncate width, should be positive.
Raises:
ValueError: If a type is provided that is incompatible with a Truncate transform.
"""
root: str = Field()
_source_type: IcebergType = PrivateAttr()
_width: PositiveInt = PrivateAttr()
def __init__(self, width: int, **data: Any):
super().__init__(root=f"truncate[{width}]", **data)
self._width = width
def can_transform(self, source: IcebergType) -> bool:
return isinstance(source, (IntegerType, LongType, StringType, BinaryType, DecimalType))
def result_type(self, source: IcebergType) -> IcebergType:
return source
@property
def preserves_order(self) -> bool:
return True
@property
def source_type(self) -> IcebergType:
return self._source_type
def project(self, name: str, pred: BoundPredicate[L]) -> Optional[UnboundPredicate[Any]]:
field_type = pred.term.ref().field.field_type
if isinstance(pred.term, BoundTransform):
return _project_transform_predicate(self, name, pred)
if isinstance(pred, BoundUnaryPredicate):
return pred.as_unbound(Reference(name))
elif isinstance(pred, BoundIn):
return _set_apply_transform(name, pred, self.transform(field_type))
elif isinstance(field_type, (IntegerType, LongType, DecimalType)):
if isinstance(pred, BoundLiteralPredicate):
return _truncate_number(name, pred, self.transform(field_type))
elif isinstance(field_type, (BinaryType, StringType)):
if isinstance(pred, BoundLiteralPredicate):
return _truncate_array(name, pred, self.transform(field_type))
return None
def strict_project(self, name: str, pred: BoundPredicate[Any]) -> Optional[UnboundPredicate[Any]]:
field_type = pred.term.ref().field.field_type
if isinstance(pred.term, BoundTransform):
return _project_transform_predicate(self, name, pred)
if isinstance(field_type, (IntegerType, LongType, DecimalType)):
if isinstance(pred, BoundUnaryPredicate):
return pred.as_unbound(Reference(name))
elif isinstance(pred, BoundLiteralPredicate):
return _truncate_number_strict(name, pred, self.transform(field_type))
elif isinstance(pred, BoundNotIn):
return _set_apply_transform(name, pred, self.transform(field_type))
else:
return None
if isinstance(pred, BoundLiteralPredicate):
if isinstance(pred, BoundStartsWith):
literal_width = len(pred.literal.value)
if literal_width < self.width:
return pred.as_unbound(name, pred.literal.value)
elif literal_width == self.width:
return EqualTo(name, pred.literal.value)
else:
return None
elif isinstance(pred, BoundNotStartsWith):
literal_width = len(pred.literal.value)
if literal_width < self.width:
return pred.as_unbound(name, pred.literal.value)
elif literal_width == self.width:
return NotEqualTo(name, pred.literal.value)
else:
return pred.as_unbound(name, self.transform(field_type)(pred.literal.value))
else:
# ProjectionUtil.truncateArrayStrict(name, pred, this);
return _truncate_array_strict(name, pred, self.transform(field_type))
elif isinstance(pred, BoundNotIn):
return _set_apply_transform(name, pred, self.transform(field_type))
else:
return None
@property
def width(self) -> int:
return self._width
def transform(self, source: IcebergType) -> Callable[[Optional[S]], Optional[S]]:
if isinstance(source, (IntegerType, LongType)):
def truncate_func(v: Any) -> Any:
return v - v % self._width
elif isinstance(source, (StringType, BinaryType)):
def truncate_func(v: Any) -> Any:
return v[0 : min(self._width, len(v))]
elif isinstance(source, DecimalType):
def truncate_func(v: Any) -> Any:
return truncate_decimal(v, self._width)
else:
raise ValueError(f"Cannot truncate for type: {source}")
return lambda v: truncate_func(v) if v is not None else None
def satisfies_order_of(self, other: Transform[S, T]) -> bool:
if self == other:
return True
elif (
isinstance(self.source_type, StringType)
and isinstance(other, TruncateTransform)
and isinstance(other.source_type, StringType)
):
return self.width >= other.width
return False
def to_human_string(self, _: IcebergType, value: Optional[S]) -> str:
if value is None:
return "null"
elif isinstance(value, bytes):
return _base64encode(value)
else:
return str(value)
def __repr__(self) -> str:
"""Return the string representation of the TruncateTransform class."""
return f"TruncateTransform(width={self._width})"
def pyarrow_transform(self, source: IcebergType) -> "Callable[[pa.Array], pa.Array]":
raise NotImplementedError()
@singledispatch
def _human_string(value: Any, _type: IcebergType) -> str:
return str(value)
@_human_string.register(bytes)
def _(value: bytes, _type: IcebergType) -> str:
return _base64encode(value)
@_human_string.register(int)
def _(value: int, _type: IcebergType) -> str:
return _int_to_human_string(_type, value)
@_human_string.register(bool)
def _(value: bool, _type: IcebergType) -> str:
return str(value).lower()
@singledispatch
def _int_to_human_string(_type: IcebergType, value: int) -> str:
return str(value)
@_int_to_human_string.register(DateType)
def _(_type: IcebergType, value: int) -> str:
return datetime.to_human_day(value)
@_int_to_human_string.register(TimeType)
def _(_type: IcebergType, value: int) -> str:
return datetime.to_human_time(value)
@_int_to_human_string.register(TimestampType)
def _(_type: IcebergType, value: int) -> str:
return datetime.to_human_timestamp(value)
@_int_to_human_string.register(TimestamptzType)
def _(_type: IcebergType, value: int) -> str:
return datetime.to_human_timestamptz(value)
class UnknownTransform(Transform[S, T]):
"""A transform that represents when an unknown transform is provided.
Args:
transform (str): A string name of a transform.
Keyword Args:
source_type (IcebergType): An Iceberg `Type`.
"""
root: LiteralType["unknown"] = Field(default="unknown") # noqa: F821
_transform: str = PrivateAttr()
def __init__(self, transform: str, **data: Any):
super().__init__(**data)
self._transform = transform
def transform(self, source: IcebergType) -> Callable[[Optional[S]], Optional[T]]:
raise AttributeError(f"Cannot apply unsupported transform: {self}")
def can_transform(self, source: IcebergType) -> bool:
return False
def result_type(self, source: IcebergType) -> StringType:
return StringType()
def project(self, name: str, pred: BoundPredicate[L]) -> Optional[UnboundPredicate[Any]]:
return None
def strict_project(self, name: str, pred: BoundPredicate[Any]) -> Optional[UnboundPredicate[Any]]:
return None
def __repr__(self) -> str:
"""Return the string representation of the UnknownTransform class."""
return f"UnknownTransform(transform={repr(self._transform)})"
def pyarrow_transform(self, source: IcebergType) -> "Callable[[pa.Array], pa.Array]":
raise NotImplementedError()
class VoidTransform(Transform[S, None], Singleton):
"""A transform that always returns None."""
root: str = "void"
def transform(self, source: IcebergType) -> Callable[[Optional[S]], Optional[T]]:
return lambda v: None
def can_transform(self, _: IcebergType) -> bool:
return True
def result_type(self, source: IcebergType) -> IcebergType:
return source
def project(self, name: str, pred: BoundPredicate[L]) -> Optional[UnboundPredicate[Any]]:
return None
def strict_project(self, name: str, pred: BoundPredicate[L]) -> Optional[UnboundPredicate[Any]]:
return None
def to_human_string(self, _: IcebergType, value: Optional[S]) -> str:
return "null"
def __repr__(self) -> str:
"""Return the string representation of the VoidTransform class."""
return "VoidTransform()"
def pyarrow_transform(self, source: IcebergType) -> "Callable[[pa.Array], pa.Array]":
raise NotImplementedError()
def _truncate_number(
name: str, pred: BoundLiteralPredicate[L], transform: Callable[[Optional[L]], Optional[L]]
) -> Optional[UnboundPredicate[Any]]:
boundary = pred.literal
if not isinstance(boundary, (LongLiteral, DecimalLiteral, DateLiteral, TimestampLiteral)):
raise ValueError(f"Expected a numeric literal, got: {type(boundary)}")
if isinstance(pred, BoundLessThan):
return LessThanOrEqual(Reference(name), _transform_literal(transform, boundary.decrement())) # type: ignore
elif isinstance(pred, BoundLessThanOrEqual):
return LessThanOrEqual(Reference(name), _transform_literal(transform, boundary))
elif isinstance(pred, BoundGreaterThan):
return GreaterThanOrEqual(Reference(name), _transform_literal(transform, boundary.increment())) # type: ignore
elif isinstance(pred, BoundGreaterThanOrEqual):
return GreaterThanOrEqual(Reference(name), _transform_literal(transform, boundary))
elif isinstance(pred, BoundEqualTo):
return EqualTo(Reference(name), _transform_literal(transform, boundary))
else:
return None
def _truncate_number_strict(
name: str, pred: BoundLiteralPredicate[L], transform: Callable[[Optional[L]], Optional[L]]
) -> Optional[UnboundPredicate[Any]]:
boundary = pred.literal
if not isinstance(boundary, (LongLiteral, DecimalLiteral, DateLiteral, TimestampLiteral)):
raise ValueError(f"Expected a numeric literal, got: {type(boundary)}")
if isinstance(pred, BoundLessThan):
return LessThan(Reference(name), _transform_literal(transform, boundary))
elif isinstance(pred, BoundLessThanOrEqual):
return LessThan(Reference(name), _transform_literal(transform, boundary.increment())) # type: ignore
elif isinstance(pred, BoundGreaterThan):
return GreaterThan(Reference(name), _transform_literal(transform, boundary))
elif isinstance(pred, BoundGreaterThanOrEqual):
return GreaterThan(Reference(name), _transform_literal(transform, boundary.decrement())) # type: ignore
elif isinstance(pred, BoundNotEqualTo):
return EqualTo(Reference(name), _transform_literal(transform, boundary))
elif isinstance(pred, BoundEqualTo):
# there is no predicate that guarantees equality because adjacent longs transform to the
# same value
return None
else:
return None
def _truncate_array_strict(
name: str, pred: BoundLiteralPredicate[L], transform: Callable[[Optional[L]], Optional[L]]
) -> Optional[UnboundPredicate[Any]]:
boundary = pred.literal