-
Notifications
You must be signed in to change notification settings - Fork 227
/
Copy pathschema.py
1591 lines (1238 loc) · 59.3 KB
/
schema.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.
# pylint: disable=W0511
from __future__ import annotations
import itertools
from abc import ABC, abstractmethod
from dataclasses import dataclass
from functools import cached_property, partial, singledispatch
from typing import (
Any,
Callable,
Dict,
Generic,
List,
Literal,
Optional,
Set,
Tuple,
TypeVar,
Union,
)
from pydantic import Field, PrivateAttr, model_validator
from pyiceberg.exceptions import ResolveError
from pyiceberg.typedef import EMPTY_DICT, IcebergBaseModel, StructProtocol
from pyiceberg.types import (
BinaryType,
BooleanType,
DateType,
DecimalType,
DoubleType,
FixedType,
FloatType,
IcebergType,
IntegerType,
ListType,
LongType,
MapType,
NestedField,
PrimitiveType,
StringType,
StructType,
TimestampType,
TimestamptzType,
TimeType,
UUIDType,
)
T = TypeVar("T")
P = TypeVar("P")
INITIAL_SCHEMA_ID = 0
class Schema(IcebergBaseModel):
"""A table Schema.
Example:
>>> from pyiceberg import schema
>>> from pyiceberg import types
"""
type: Literal["struct"] = "struct"
fields: Tuple[NestedField, ...] = Field(default_factory=tuple)
schema_id: int = Field(alias="schema-id", default=INITIAL_SCHEMA_ID)
identifier_field_ids: List[int] = Field(alias="identifier-field-ids", default_factory=list)
_name_to_id: Dict[str, int] = PrivateAttr()
def __init__(self, *fields: NestedField, **data: Any):
if fields:
data["fields"] = fields
super().__init__(**data)
self._name_to_id = index_by_name(self)
def __str__(self) -> str:
"""Return the string representation of the Schema class."""
return "table {\n" + "\n".join([" " + str(field) for field in self.columns]) + "\n}"
def __repr__(self) -> str:
"""Return the string representation of the Schema class."""
return f"Schema({', '.join(repr(column) for column in self.columns)}, schema_id={self.schema_id}, identifier_field_ids={self.identifier_field_ids})"
def __len__(self) -> int:
"""Return the length of an instance of the Literal class."""
return len(self.fields)
def __eq__(self, other: Any) -> bool:
"""Return the equality of two instances of the Schema class."""
if not other:
return False
if not isinstance(other, Schema):
return False
if len(self.columns) != len(other.columns):
return False
identifier_field_ids_is_equal = self.identifier_field_ids == other.identifier_field_ids
schema_is_equal = all(lhs == rhs for lhs, rhs in zip(self.columns, other.columns))
return identifier_field_ids_is_equal and schema_is_equal
@model_validator(mode="after")
def check_schema(self) -> Schema:
if self.identifier_field_ids:
for field_id in self.identifier_field_ids:
self._validate_identifier_field(field_id)
return self
@property
def columns(self) -> Tuple[NestedField, ...]:
"""A tuple of the top-level fields."""
return self.fields
@cached_property
def _lazy_id_to_field(self) -> Dict[int, NestedField]:
"""Return an index of field ID to NestedField instance.
This is calculated once when called for the first time. Subsequent calls to this method will use a cached index.
"""
return index_by_id(self)
@cached_property
def _lazy_id_to_parent(self) -> Dict[int, int]:
"""Returns an index of field ID to parent field IDs.
This is calculated once when called for the first time. Subsequent calls to this method will use a cached index.
"""
return _index_parents(self)
@cached_property
def _lazy_name_to_id_lower(self) -> Dict[str, int]:
"""Return an index of lower-case field names to field IDs.
This is calculated once when called for the first time. Subsequent calls to this method will use a cached index.
"""
return {name.lower(): field_id for name, field_id in self._name_to_id.items()}
@cached_property
def _lazy_id_to_name(self) -> Dict[int, str]:
"""Return an index of field ID to full name.
This is calculated once when called for the first time. Subsequent calls to this method will use a cached index.
"""
return index_name_by_id(self)
@cached_property
def _lazy_id_to_accessor(self) -> Dict[int, Accessor]:
"""Return an index of field ID to accessor.
This is calculated once when called for the first time. Subsequent calls to this method will use a cached index.
"""
return build_position_accessors(self)
def as_struct(self) -> StructType:
"""Return the schema as a struct."""
return StructType(*self.fields)
def find_field(self, name_or_id: Union[str, int], case_sensitive: bool = True) -> NestedField:
"""Find a field using a field name or field ID.
Args:
name_or_id (Union[str, int]): Either a field name or a field ID.
case_sensitive (bool, optional): Whether to perform a case-sensitive lookup using a field name. Defaults to True.
Raises:
ValueError: When the value cannot be found.
Returns:
NestedField: The matched NestedField.
"""
if isinstance(name_or_id, int):
if name_or_id not in self._lazy_id_to_field:
raise ValueError(f"Could not find field with id: {name_or_id}")
return self._lazy_id_to_field[name_or_id]
if case_sensitive:
field_id = self._name_to_id.get(name_or_id)
else:
field_id = self._lazy_name_to_id_lower.get(name_or_id.lower())
if field_id is None:
raise ValueError(f"Could not find field with name {name_or_id}, case_sensitive={case_sensitive}")
return self._lazy_id_to_field[field_id]
def find_type(self, name_or_id: Union[str, int], case_sensitive: bool = True) -> IcebergType:
"""Find a field type using a field name or field ID.
Args:
name_or_id (Union[str, int]): Either a field name or a field ID.
case_sensitive (bool, optional): Whether to perform a case-sensitive lookup using a field name. Defaults to True.
Returns:
NestedField: The type of the matched NestedField.
"""
field = self.find_field(name_or_id=name_or_id, case_sensitive=case_sensitive)
if not field:
raise ValueError(f"Could not find field with name or id {name_or_id}, case_sensitive={case_sensitive}")
return field.field_type
@property
def highest_field_id(self) -> int:
return max(self._lazy_id_to_name.keys(), default=0)
def find_column_name(self, column_id: int) -> Optional[str]:
"""Find a column name given a column ID.
Args:
column_id (int): The ID of the column.
Returns:
str: The column name (or None if the column ID cannot be found).
"""
return self._lazy_id_to_name.get(column_id)
@property
def column_names(self) -> List[str]:
"""
Return a list of all the column names, including nested fields.
Excludes short names.
Returns:
List[str]: The column names.
"""
return list(self._lazy_id_to_name.values())
def accessor_for_field(self, field_id: int) -> Accessor:
"""Find a schema position accessor given a field ID.
Args:
field_id (int): The ID of the field.
Raises:
ValueError: When the value cannot be found.
Returns:
Accessor: An accessor for the given field ID.
"""
if field_id not in self._lazy_id_to_accessor:
raise ValueError(f"Could not find accessor for field with id: {field_id}")
return self._lazy_id_to_accessor[field_id]
def identifier_field_names(self) -> Set[str]:
"""Return the names of the identifier fields.
Returns:
Set of names of the identifier fields
"""
ids = set()
for field_id in self.identifier_field_ids:
column_name = self.find_column_name(field_id)
if column_name is None:
raise ValueError(f"Could not find identifier column id: {field_id}")
ids.add(column_name)
return ids
def select(self, *names: str, case_sensitive: bool = True) -> Schema:
"""Return a new schema instance pruned to a subset of columns.
Args:
names (List[str]): A list of column names.
case_sensitive (bool, optional): Whether to perform a case-sensitive lookup for each column name. Defaults to True.
Returns:
Schema: A new schema with pruned columns.
Raises:
ValueError: If a column is selected that doesn't exist.
"""
try:
if case_sensitive:
ids = {self._name_to_id[name] for name in names}
else:
ids = {self._lazy_name_to_id_lower[name.lower()] for name in names}
except KeyError as e:
raise ValueError(f"Could not find column: {e}") from e
return prune_columns(self, ids)
@property
def field_ids(self) -> Set[int]:
"""Return the IDs of the current schema."""
return set(self._name_to_id.values())
def _validate_identifier_field(self, field_id: int) -> None:
"""Validate that the field with the given ID is a valid identifier field.
Args:
field_id: The ID of the field to validate.
Raises:
ValueError: If the field is not valid.
"""
field = self.find_field(field_id)
if not field.field_type.is_primitive:
raise ValueError(f"Identifier field {field_id} invalid: not a primitive type field")
if not field.required:
raise ValueError(f"Identifier field {field_id} invalid: not a required field")
if isinstance(field.field_type, (DoubleType, FloatType)):
raise ValueError(f"Identifier field {field_id} invalid: must not be float or double field")
# Check whether the nested field is in a chain of required struct fields
# Exploring from root for better error message for list and map types
parent_id = self._lazy_id_to_parent.get(field.field_id)
fields: List[int] = []
while parent_id is not None:
fields.append(parent_id)
parent_id = self._lazy_id_to_parent.get(parent_id)
while fields:
parent = self.find_field(fields.pop())
if not parent.field_type.is_struct:
raise ValueError(f"Cannot add field {field.name} as an identifier field: must not be nested in {parent}")
if not parent.required:
raise ValueError(
f"Cannot add field {field.name} as an identifier field: must not be nested in an optional field {parent}"
)
class SchemaVisitor(Generic[T], ABC):
def before_field(self, field: NestedField) -> None:
"""Override this method to perform an action immediately before visiting a field."""
def after_field(self, field: NestedField) -> None:
"""Override this method to perform an action immediately after visiting a field."""
def before_list_element(self, element: NestedField) -> None:
"""Override this method to perform an action immediately before visiting an element within a ListType."""
self.before_field(element)
def after_list_element(self, element: NestedField) -> None:
"""Override this method to perform an action immediately after visiting an element within a ListType."""
self.after_field(element)
def before_map_key(self, key: NestedField) -> None:
"""Override this method to perform an action immediately before visiting a key within a MapType."""
self.before_field(key)
def after_map_key(self, key: NestedField) -> None:
"""Override this method to perform an action immediately after visiting a key within a MapType."""
self.after_field(key)
def before_map_value(self, value: NestedField) -> None:
"""Override this method to perform an action immediately before visiting a value within a MapType."""
self.before_field(value)
def after_map_value(self, value: NestedField) -> None:
"""Override this method to perform an action immediately after visiting a value within a MapType."""
self.after_field(value)
@abstractmethod
def schema(self, schema: Schema, struct_result: T) -> T:
"""Visit a Schema."""
@abstractmethod
def struct(self, struct: StructType, field_results: List[T]) -> T:
"""Visit a StructType."""
@abstractmethod
def field(self, field: NestedField, field_result: T) -> T:
"""Visit a NestedField."""
@abstractmethod
def list(self, list_type: ListType, element_result: T) -> T:
"""Visit a ListType."""
@abstractmethod
def map(self, map_type: MapType, key_result: T, value_result: T) -> T:
"""Visit a MapType."""
@abstractmethod
def primitive(self, primitive: PrimitiveType) -> T:
"""Visit a PrimitiveType."""
class PreOrderSchemaVisitor(Generic[T], ABC):
@abstractmethod
def schema(self, schema: Schema, struct_result: Callable[[], T]) -> T:
"""Visit a Schema."""
@abstractmethod
def struct(self, struct: StructType, field_results: List[Callable[[], T]]) -> T:
"""Visit a StructType."""
@abstractmethod
def field(self, field: NestedField, field_result: Callable[[], T]) -> T:
"""Visit a NestedField."""
@abstractmethod
def list(self, list_type: ListType, element_result: Callable[[], T]) -> T:
"""Visit a ListType."""
@abstractmethod
def map(self, map_type: MapType, key_result: Callable[[], T], value_result: Callable[[], T]) -> T:
"""Visit a MapType."""
@abstractmethod
def primitive(self, primitive: PrimitiveType) -> T:
"""Visit a PrimitiveType."""
class SchemaWithPartnerVisitor(Generic[P, T], ABC):
def before_field(self, field: NestedField, field_partner: Optional[P]) -> None:
"""Override this method to perform an action immediately before visiting a field."""
def after_field(self, field: NestedField, field_partner: Optional[P]) -> None:
"""Override this method to perform an action immediately after visiting a field."""
def before_list_element(self, element: NestedField, element_partner: Optional[P]) -> None:
"""Override this method to perform an action immediately before visiting an element within a ListType."""
self.before_field(element, element_partner)
def after_list_element(self, element: NestedField, element_partner: Optional[P]) -> None:
"""Override this method to perform an action immediately after visiting an element within a ListType."""
self.after_field(element, element_partner)
def before_map_key(self, key: NestedField, key_partner: Optional[P]) -> None:
"""Override this method to perform an action immediately before visiting a key within a MapType."""
self.before_field(key, key_partner)
def after_map_key(self, key: NestedField, key_partner: Optional[P]) -> None:
"""Override this method to perform an action immediately after visiting a key within a MapType."""
self.after_field(key, key_partner)
def before_map_value(self, value: NestedField, value_partner: Optional[P]) -> None:
"""Override this method to perform an action immediately before visiting a value within a MapType."""
self.before_field(value, value_partner)
def after_map_value(self, value: NestedField, value_partner: Optional[P]) -> None:
"""Override this method to perform an action immediately after visiting a value within a MapType."""
self.after_field(value, value_partner)
@abstractmethod
def schema(self, schema: Schema, schema_partner: Optional[P], struct_result: T) -> T:
"""Visit a schema with a partner."""
@abstractmethod
def struct(self, struct: StructType, struct_partner: Optional[P], field_results: List[T]) -> T:
"""Visit a struct type with a partner."""
@abstractmethod
def field(self, field: NestedField, field_partner: Optional[P], field_result: T) -> T:
"""Visit a nested field with a partner."""
@abstractmethod
def list(self, list_type: ListType, list_partner: Optional[P], element_result: T) -> T:
"""Visit a list type with a partner."""
@abstractmethod
def map(self, map_type: MapType, map_partner: Optional[P], key_result: T, value_result: T) -> T:
"""Visit a map type with a partner."""
@abstractmethod
def primitive(self, primitive: PrimitiveType, primitive_partner: Optional[P]) -> T:
"""Visit a primitive type with a partner."""
class PrimitiveWithPartnerVisitor(SchemaWithPartnerVisitor[P, T]):
def primitive(self, primitive: PrimitiveType, primitive_partner: Optional[P]) -> T:
"""Visit a PrimitiveType."""
if isinstance(primitive, BooleanType):
return self.visit_boolean(primitive, primitive_partner)
elif isinstance(primitive, IntegerType):
return self.visit_integer(primitive, primitive_partner)
elif isinstance(primitive, LongType):
return self.visit_long(primitive, primitive_partner)
elif isinstance(primitive, FloatType):
return self.visit_float(primitive, primitive_partner)
elif isinstance(primitive, DoubleType):
return self.visit_double(primitive, primitive_partner)
elif isinstance(primitive, DecimalType):
return self.visit_decimal(primitive, primitive_partner)
elif isinstance(primitive, DateType):
return self.visit_date(primitive, primitive_partner)
elif isinstance(primitive, TimeType):
return self.visit_time(primitive, primitive_partner)
elif isinstance(primitive, TimestampType):
return self.visit_timestamp(primitive, primitive_partner)
elif isinstance(primitive, TimestamptzType):
return self.visit_timestamptz(primitive, primitive_partner)
elif isinstance(primitive, StringType):
return self.visit_string(primitive, primitive_partner)
elif isinstance(primitive, UUIDType):
return self.visit_uuid(primitive, primitive_partner)
elif isinstance(primitive, FixedType):
return self.visit_fixed(primitive, primitive_partner)
elif isinstance(primitive, BinaryType):
return self.visit_binary(primitive, primitive_partner)
else:
raise ValueError(f"Unknown type: {primitive}")
@abstractmethod
def visit_boolean(self, boolean_type: BooleanType, partner: Optional[P]) -> T:
"""Visit a BooleanType."""
@abstractmethod
def visit_integer(self, integer_type: IntegerType, partner: Optional[P]) -> T:
"""Visit a IntegerType."""
@abstractmethod
def visit_long(self, long_type: LongType, partner: Optional[P]) -> T:
"""Visit a LongType."""
@abstractmethod
def visit_float(self, float_type: FloatType, partner: Optional[P]) -> T:
"""Visit a FloatType."""
@abstractmethod
def visit_double(self, double_type: DoubleType, partner: Optional[P]) -> T:
"""Visit a DoubleType."""
@abstractmethod
def visit_decimal(self, decimal_type: DecimalType, partner: Optional[P]) -> T:
"""Visit a DecimalType."""
@abstractmethod
def visit_date(self, date_type: DateType, partner: Optional[P]) -> T:
"""Visit a DecimalType."""
@abstractmethod
def visit_time(self, time_type: TimeType, partner: Optional[P]) -> T:
"""Visit a DecimalType."""
@abstractmethod
def visit_timestamp(self, timestamp_type: TimestampType, partner: Optional[P]) -> T:
"""Visit a TimestampType."""
@abstractmethod
def visit_timestamptz(self, timestamptz_type: TimestamptzType, partner: Optional[P]) -> T:
"""Visit a TimestamptzType."""
@abstractmethod
def visit_string(self, string_type: StringType, partner: Optional[P]) -> T:
"""Visit a StringType."""
@abstractmethod
def visit_uuid(self, uuid_type: UUIDType, partner: Optional[P]) -> T:
"""Visit a UUIDType."""
@abstractmethod
def visit_fixed(self, fixed_type: FixedType, partner: Optional[P]) -> T:
"""Visit a FixedType."""
@abstractmethod
def visit_binary(self, binary_type: BinaryType, partner: Optional[P]) -> T:
"""Visit a BinaryType."""
class PartnerAccessor(Generic[P], ABC):
@abstractmethod
def schema_partner(self, partner: Optional[P]) -> Optional[P]:
"""Return the equivalent of the schema as a struct."""
@abstractmethod
def field_partner(self, partner_struct: Optional[P], field_id: int, field_name: str) -> Optional[P]:
"""Return the equivalent struct field by name or id in the partner struct."""
@abstractmethod
def list_element_partner(self, partner_list: Optional[P]) -> Optional[P]:
"""Return the equivalent list element in the partner list."""
@abstractmethod
def map_key_partner(self, partner_map: Optional[P]) -> Optional[P]:
"""Return the equivalent map key in the partner map."""
@abstractmethod
def map_value_partner(self, partner_map: Optional[P]) -> Optional[P]:
"""Return the equivalent map value in the partner map."""
@singledispatch
def visit_with_partner(
schema_or_type: Union[Schema, IcebergType], partner: P, visitor: SchemaWithPartnerVisitor[T, P], accessor: PartnerAccessor[P]
) -> T:
raise ValueError(f"Unsupported type: {schema_or_type}")
@visit_with_partner.register(Schema)
def _(schema: Schema, partner: P, visitor: SchemaWithPartnerVisitor[P, T], accessor: PartnerAccessor[P]) -> T:
struct_partner = accessor.schema_partner(partner)
return visitor.schema(schema, partner, visit_with_partner(schema.as_struct(), struct_partner, visitor, accessor)) # type: ignore
@visit_with_partner.register(StructType)
def _(struct: StructType, partner: P, visitor: SchemaWithPartnerVisitor[P, T], accessor: PartnerAccessor[P]) -> T:
field_results = []
for field in struct.fields:
field_partner = accessor.field_partner(partner, field.field_id, field.name)
visitor.before_field(field, field_partner)
try:
field_result = visit_with_partner(field.field_type, field_partner, visitor, accessor) # type: ignore
field_results.append(visitor.field(field, field_partner, field_result))
finally:
visitor.after_field(field, field_partner)
return visitor.struct(struct, partner, field_results)
@visit_with_partner.register(ListType)
def _(list_type: ListType, partner: P, visitor: SchemaWithPartnerVisitor[P, T], accessor: PartnerAccessor[P]) -> T:
element_partner = accessor.list_element_partner(partner)
visitor.before_list_element(list_type.element_field, element_partner)
try:
element_result = visit_with_partner(list_type.element_type, element_partner, visitor, accessor) # type: ignore
finally:
visitor.after_list_element(list_type.element_field, element_partner)
return visitor.list(list_type, partner, element_result)
@visit_with_partner.register(MapType)
def _(map_type: MapType, partner: P, visitor: SchemaWithPartnerVisitor[P, T], accessor: PartnerAccessor[P]) -> T:
key_partner = accessor.map_key_partner(partner)
visitor.before_map_key(map_type.key_field, key_partner)
try:
key_result = visit_with_partner(map_type.key_type, key_partner, visitor, accessor) # type: ignore
finally:
visitor.after_map_key(map_type.key_field, key_partner)
value_partner = accessor.map_value_partner(partner)
visitor.before_map_value(map_type.value_field, value_partner)
try:
value_result = visit_with_partner(map_type.value_type, value_partner, visitor, accessor) # type: ignore
finally:
visitor.after_map_value(map_type.value_field, value_partner)
return visitor.map(map_type, partner, key_result, value_result)
@visit_with_partner.register(PrimitiveType)
def _(primitive: PrimitiveType, partner: P, visitor: SchemaWithPartnerVisitor[P, T], _: PartnerAccessor[P]) -> T:
return visitor.primitive(primitive, partner)
class SchemaVisitorPerPrimitiveType(SchemaVisitor[T], ABC):
def primitive(self, primitive: PrimitiveType) -> T:
"""Visit a PrimitiveType."""
if isinstance(primitive, FixedType):
return self.visit_fixed(primitive)
elif isinstance(primitive, DecimalType):
return self.visit_decimal(primitive)
elif isinstance(primitive, BooleanType):
return self.visit_boolean(primitive)
elif isinstance(primitive, IntegerType):
return self.visit_integer(primitive)
elif isinstance(primitive, LongType):
return self.visit_long(primitive)
elif isinstance(primitive, FloatType):
return self.visit_float(primitive)
elif isinstance(primitive, DoubleType):
return self.visit_double(primitive)
elif isinstance(primitive, DateType):
return self.visit_date(primitive)
elif isinstance(primitive, TimeType):
return self.visit_time(primitive)
elif isinstance(primitive, TimestampType):
return self.visit_timestamp(primitive)
elif isinstance(primitive, TimestamptzType):
return self.visit_timestamptz(primitive)
elif isinstance(primitive, StringType):
return self.visit_string(primitive)
elif isinstance(primitive, UUIDType):
return self.visit_uuid(primitive)
elif isinstance(primitive, BinaryType):
return self.visit_binary(primitive)
else:
raise ValueError(f"Unknown type: {primitive}")
@abstractmethod
def visit_fixed(self, fixed_type: FixedType) -> T:
"""Visit a FixedType."""
@abstractmethod
def visit_decimal(self, decimal_type: DecimalType) -> T:
"""Visit a DecimalType."""
@abstractmethod
def visit_boolean(self, boolean_type: BooleanType) -> T:
"""Visit a BooleanType."""
@abstractmethod
def visit_integer(self, integer_type: IntegerType) -> T:
"""Visit a IntegerType."""
@abstractmethod
def visit_long(self, long_type: LongType) -> T:
"""Visit a LongType."""
@abstractmethod
def visit_float(self, float_type: FloatType) -> T:
"""Visit a FloatType."""
@abstractmethod
def visit_double(self, double_type: DoubleType) -> T:
"""Visit a DoubleType."""
@abstractmethod
def visit_date(self, date_type: DateType) -> T:
"""Visit a DecimalType."""
@abstractmethod
def visit_time(self, time_type: TimeType) -> T:
"""Visit a DecimalType."""
@abstractmethod
def visit_timestamp(self, timestamp_type: TimestampType) -> T:
"""Visit a TimestampType."""
@abstractmethod
def visit_timestamptz(self, timestamptz_type: TimestamptzType) -> T:
"""Visit a TimestamptzType."""
@abstractmethod
def visit_string(self, string_type: StringType) -> T:
"""Visit a StringType."""
@abstractmethod
def visit_uuid(self, uuid_type: UUIDType) -> T:
"""Visit a UUIDType."""
@abstractmethod
def visit_binary(self, binary_type: BinaryType) -> T:
"""Visit a BinaryType."""
@dataclass(init=True, eq=True, frozen=True)
class Accessor:
"""An accessor for a specific position in a container that implements the StructProtocol."""
position: int
inner: Optional[Accessor] = None
def __str__(self) -> str:
"""Return the string representation of the Accessor class."""
return f"Accessor(position={self.position},inner={self.inner})"
def __repr__(self) -> str:
"""Return the string representation of the Accessor class."""
return self.__str__()
def get(self, container: StructProtocol) -> Any:
"""Return the value at self.position in `container`.
Args:
container (StructProtocol): A container to access at position `self.position`.
Returns:
Any: The value at position `self.position` in the container.
"""
pos = self.position
val = container[pos]
inner = self
while inner.inner:
inner = inner.inner
val = val[inner.position]
return val
@singledispatch
def visit(obj: Union[Schema, IcebergType], visitor: SchemaVisitor[T]) -> T:
"""Apply a schema visitor to any point within a schema.
The function traverses the schema in post-order fashion.
Args:
obj (Union[Schema, IcebergType]): An instance of a Schema or an IcebergType.
visitor (SchemaVisitor[T]): An instance of an implementation of the generic SchemaVisitor base class.
Raises:
NotImplementedError: If attempting to visit an unrecognized object type.
"""
raise NotImplementedError(f"Cannot visit non-type: {obj}")
@visit.register(Schema)
def _(obj: Schema, visitor: SchemaVisitor[T]) -> T:
"""Visit a Schema with a concrete SchemaVisitor."""
return visitor.schema(obj, visit(obj.as_struct(), visitor))
@visit.register(StructType)
def _(obj: StructType, visitor: SchemaVisitor[T]) -> T:
"""Visit a StructType with a concrete SchemaVisitor."""
results = []
for field in obj.fields:
visitor.before_field(field)
result = visit(field.field_type, visitor)
visitor.after_field(field)
results.append(visitor.field(field, result))
return visitor.struct(obj, results)
@visit.register(ListType)
def _(obj: ListType, visitor: SchemaVisitor[T]) -> T:
"""Visit a ListType with a concrete SchemaVisitor."""
visitor.before_list_element(obj.element_field)
result = visit(obj.element_type, visitor)
visitor.after_list_element(obj.element_field)
return visitor.list(obj, result)
@visit.register(MapType)
def _(obj: MapType, visitor: SchemaVisitor[T]) -> T:
"""Visit a MapType with a concrete SchemaVisitor."""
visitor.before_map_key(obj.key_field)
key_result = visit(obj.key_type, visitor)
visitor.after_map_key(obj.key_field)
visitor.before_map_value(obj.value_field)
value_result = visit(obj.value_type, visitor)
visitor.after_map_value(obj.value_field)
return visitor.map(obj, key_result, value_result)
@visit.register(PrimitiveType)
def _(obj: PrimitiveType, visitor: SchemaVisitor[T]) -> T:
"""Visit a PrimitiveType with a concrete SchemaVisitor."""
return visitor.primitive(obj)
@singledispatch
def pre_order_visit(obj: Union[Schema, IcebergType], visitor: PreOrderSchemaVisitor[T]) -> T:
"""Apply a schema visitor to any point within a schema.
The function traverses the schema in pre-order fashion. This is a slimmed down version
compared to the post-order traversal (missing before and after methods), mostly
because we don't use the pre-order traversal much.
Args:
obj (Union[Schema, IcebergType]): An instance of a Schema or an IcebergType.
visitor (PreOrderSchemaVisitor[T]): An instance of an implementation of the generic PreOrderSchemaVisitor base class.
Raises:
NotImplementedError: If attempting to visit an unrecognized object type.
"""
raise NotImplementedError(f"Cannot visit non-type: {obj}")
@pre_order_visit.register(Schema)
def _(obj: Schema, visitor: PreOrderSchemaVisitor[T]) -> T:
"""Visit a Schema with a concrete PreOrderSchemaVisitor."""
return visitor.schema(obj, lambda: pre_order_visit(obj.as_struct(), visitor))
@pre_order_visit.register(StructType)
def _(obj: StructType, visitor: PreOrderSchemaVisitor[T]) -> T:
"""Visit a StructType with a concrete PreOrderSchemaVisitor."""
return visitor.struct(
obj,
[
partial(
lambda field: visitor.field(field, partial(lambda field: pre_order_visit(field.field_type, visitor), field)),
field,
)
for field in obj.fields
],
)
@pre_order_visit.register(ListType)
def _(obj: ListType, visitor: PreOrderSchemaVisitor[T]) -> T:
"""Visit a ListType with a concrete PreOrderSchemaVisitor."""
return visitor.list(obj, lambda: pre_order_visit(obj.element_type, visitor))
@pre_order_visit.register(MapType)
def _(obj: MapType, visitor: PreOrderSchemaVisitor[T]) -> T:
"""Visit a MapType with a concrete PreOrderSchemaVisitor."""
return visitor.map(obj, lambda: pre_order_visit(obj.key_type, visitor), lambda: pre_order_visit(obj.value_type, visitor))
@pre_order_visit.register(PrimitiveType)
def _(obj: PrimitiveType, visitor: PreOrderSchemaVisitor[T]) -> T:
"""Visit a PrimitiveType with a concrete PreOrderSchemaVisitor."""
return visitor.primitive(obj)
class _IndexById(SchemaVisitor[Dict[int, NestedField]]):
"""A schema visitor for generating a field ID to NestedField index."""
def __init__(self) -> None:
self._index: Dict[int, NestedField] = {}
def schema(self, schema: Schema, struct_result: Dict[int, NestedField]) -> Dict[int, NestedField]:
return self._index
def struct(self, struct: StructType, field_results: List[Dict[int, NestedField]]) -> Dict[int, NestedField]:
return self._index
def field(self, field: NestedField, field_result: Dict[int, NestedField]) -> Dict[int, NestedField]:
"""Add the field ID to the index."""
self._index[field.field_id] = field
return self._index
def list(self, list_type: ListType, element_result: Dict[int, NestedField]) -> Dict[int, NestedField]:
"""Add the list element ID to the index."""
self._index[list_type.element_field.field_id] = list_type.element_field
return self._index
def map(
self, map_type: MapType, key_result: Dict[int, NestedField], value_result: Dict[int, NestedField]
) -> Dict[int, NestedField]:
"""Add the key ID and value ID as individual items in the index."""
self._index[map_type.key_field.field_id] = map_type.key_field
self._index[map_type.value_field.field_id] = map_type.value_field
return self._index
def primitive(self, primitive: PrimitiveType) -> Dict[int, NestedField]:
return self._index
def index_by_id(schema_or_type: Union[Schema, IcebergType]) -> Dict[int, NestedField]:
"""Generate an index of field IDs to NestedField instances.
Args:
schema_or_type (Union[Schema, IcebergType]): A schema or type to index.
Returns:
Dict[int, NestedField]: An index of field IDs to NestedField instances.
"""
return visit(schema_or_type, _IndexById())
class _IndexParents(SchemaVisitor[Dict[int, int]]):
def __init__(self) -> None:
self.id_to_parent: Dict[int, int] = {}
self.id_stack: List[int] = []
def before_field(self, field: NestedField) -> None:
self.id_stack.append(field.field_id)
def after_field(self, field: NestedField) -> None:
self.id_stack.pop()
def schema(self, schema: Schema, struct_result: Dict[int, int]) -> Dict[int, int]:
return self.id_to_parent
def struct(self, struct: StructType, field_results: List[Dict[int, int]]) -> Dict[int, int]:
for field in struct.fields:
parent_id = self.id_stack[-1] if self.id_stack else None
if parent_id is not None:
# fields in the root struct are not added
self.id_to_parent[field.field_id] = parent_id
return self.id_to_parent
def field(self, field: NestedField, field_result: Dict[int, int]) -> Dict[int, int]:
return self.id_to_parent
def list(self, list_type: ListType, element_result: Dict[int, int]) -> Dict[int, int]:
self.id_to_parent[list_type.element_id] = self.id_stack[-1]
return self.id_to_parent
def map(self, map_type: MapType, key_result: Dict[int, int], value_result: Dict[int, int]) -> Dict[int, int]:
self.id_to_parent[map_type.key_id] = self.id_stack[-1]
self.id_to_parent[map_type.value_id] = self.id_stack[-1]
return self.id_to_parent
def primitive(self, primitive: PrimitiveType) -> Dict[int, int]:
return self.id_to_parent
def _index_parents(schema_or_type: Union[Schema, IcebergType]) -> Dict[int, int]:
"""Generate an index of field IDs to their parent field IDs.
Args:
schema_or_type (Union[Schema, IcebergType]): A schema or type to index.
Returns:
Dict[int, int]: An index of field IDs to their parent field IDs.
"""