Repository navigation
Expand file tree
/
Copy pathtransforms.go
More file actions
1565 lines (1321 loc) · 38.9 KB
/
Copy pathtransforms.go
File metadata and controls
1565 lines (1321 loc) · 38.9 KB
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.
package iceberg
import (
"encoding"
"encoding/base64"
"encoding/binary"
"fmt"
"math"
"math/big"
"strconv"
"strings"
"time"
"unicode/utf8"
"unsafe"
"github.com/apache/arrow-go/v18/arrow/decimal128"
"github.com/apache/iceberg-go/internal"
"github.com/google/uuid"
"github.com/twmb/murmur3"
)
// ParseTransform takes the string representation of a transform as
// defined in the iceberg spec, and produces the appropriate Transform
// object. Strings that don't name a known transform yield an
// UnknownTransform rather than an error, so that v3 tables using transforms
// this implementation doesn't recognize can still be read. This mirrors Java's
// Transforms.fromString: only a bucket/truncate whose width parses as a number
// but is out of range (e.g. bucket[0]) is an error; anything else that doesn't
// match the width pattern, like bucket[-1], is an unknown transform.
func ParseTransform(s string) (Transform, error) {
if s == "" {
return nil, fmt.Errorf("%w: empty transform", ErrInvalidTransform)
}
if transform, ok := parseSimpleTransform(s); ok {
return transform, nil
}
if n, matched := parseTransformWidth(s, "bucket["); matched {
if n == 0 {
return nil, fmt.Errorf("%w: %s", ErrInvalidTransform, s)
}
return BucketTransform{NumBuckets: n}, nil
}
if n, matched := parseTransformWidth(s, "truncate["); matched {
if n == 0 {
return nil, fmt.Errorf("%w: %s", ErrInvalidTransform, s)
}
return TruncateTransform{Width: n}, nil
}
if hasASCIICaseDifference(s) {
if transform, ok := parseSimpleTransformFold(s); ok {
return transform, nil
}
if n, matched := parseTransformWidthFold(s, "bucket["); matched {
if n == 0 {
return nil, fmt.Errorf("%w: %s", ErrInvalidTransform, s)
}
return BucketTransform{NumBuckets: n}, nil
}
if n, matched := parseTransformWidthFold(s, "truncate["); matched {
if n == 0 {
return nil, fmt.Errorf("%w: %s", ErrInvalidTransform, s)
}
return TruncateTransform{Width: n}, nil
}
}
// Unknown transform: v3 readers must load these and ignore them when
// filtering instead of failing. Keep the original string, case and all, so it
// round-trips; Equals stays byte-for-byte, matching Java's UnknownTransform.
return UnknownTransform{name: s}, nil
}
func hasASCIICaseDifference(s string) bool {
for i := range s {
if s[i] >= 'A' && s[i] <= 'Z' {
return true
}
}
return false
}
func parseSimpleTransformFold(s string) (Transform, bool) {
switch {
case strings.EqualFold(s, "identity"):
return IdentityTransform{}, true
case strings.EqualFold(s, "void"):
return VoidTransform{}, true
case strings.EqualFold(s, "year"):
return YearTransform{}, true
case strings.EqualFold(s, "month"):
return MonthTransform{}, true
case strings.EqualFold(s, "day"):
return DayTransform{}, true
case strings.EqualFold(s, "hour"):
return HourTransform{}, true
default:
return nil, false
}
}
func parseSimpleTransform(s string) (Transform, bool) {
switch s {
case "identity":
return IdentityTransform{}, true
case "void":
return VoidTransform{}, true
case "year":
return YearTransform{}, true
case "month":
return MonthTransform{}, true
case "day":
return DayTransform{}, true
case "hour":
return HourTransform{}, true
default:
return nil, false
}
}
func parseTransformWidth(s, prefix string) (int, bool) {
if !strings.HasPrefix(s, prefix) || len(s) <= len(prefix)+1 || s[len(s)-1] != ']' {
return 0, false
}
width := s[len(prefix) : len(s)-1]
for i := range width {
if width[i] < '0' || width[i] > '9' {
return 0, false
}
}
n, err := strconv.Atoi(width)
if err != nil || n <= 0 || n > math.MaxInt32 {
return 0, true
}
return n, true
}
func parseTransformWidthFold(s, prefix string) (int, bool) {
if !hasPrefixFold(s, prefix) || len(s) <= len(prefix)+1 || s[len(s)-1] != ']' {
return 0, false
}
width := s[len(prefix) : len(s)-1]
for i := range width {
if width[i] < '0' || width[i] > '9' {
return 0, false
}
}
n, err := strconv.Atoi(width)
if err != nil || n <= 0 || n > math.MaxInt32 {
return 0, true
}
return n, true
}
func hasPrefixFold(s, prefix string) bool {
if len(s) < len(prefix) {
return false
}
for i := range prefix {
got := s[i]
if got >= 'A' && got <= 'Z' {
got += 'a' - 'A'
}
if got != prefix[i] {
return false
}
}
return true
}
// Transform is an interface for the various Transformation types
// in partition specs. Currently, they do not yet provide actual
// transformation functions or implementation. That will come later as
// data reading gets implemented.
type Transform interface {
fmt.Stringer
encoding.TextMarshaler
CanTransform(t Type) bool
ResultType(t Type) Type
PreservesOrder() bool
Equals(Transform) bool
Apply(Optional[Literal]) Optional[Literal]
Project(name string, pred BoundPredicate) (UnboundPredicate, error)
ToHumanStrType(typ Type, val any) string
// Deprecated: ToHumanStr cannot recover source-type information; use ToHumanStrType instead.
ToHumanStr(any) string
}
// IdentityTransform uses the identity function, performing no transformation
// but instead partitioning on the value itself.
type IdentityTransform struct{}
func (t IdentityTransform) MarshalText() ([]byte, error) {
return []byte(t.String()), nil
}
func (IdentityTransform) String() string { return "identity" }
func (IdentityTransform) CanTransform(t Type) bool {
switch t.(type) {
case GeometryType, GeographyType, VariantType:
return false
}
_, ok := t.(PrimitiveType)
return ok
}
func (IdentityTransform) ResultType(t Type) Type { return t }
func (IdentityTransform) PreservesOrder() bool { return true }
func (IdentityTransform) Equals(other Transform) bool {
switch rhs := other.(type) {
case IdentityTransform:
return true
case *IdentityTransform:
return rhs != nil
default:
return false
}
}
func (IdentityTransform) Apply(value Optional[Literal]) Optional[Literal] {
return value
}
func (IdentityTransform) ToHumanStr(val any) string {
switch v := val.(type) {
case nil:
return "null"
case string:
return v
case []byte:
return base64.StdEncoding.EncodeToString(v)
case bool:
return strconv.FormatBool(v)
case Date:
return v.ToTime().Format("2006-01-02")
case Time:
return v.ToTime().Format("15:04:05.999999")
case Timestamp:
return v.ToTime().Format("2006-01-02T15:04:05.999999")
case TimestampNano:
return v.ToTime().Format("2006-01-02T15:04:05.999999999")
default:
return fmt.Sprintf("%v", v)
}
}
// ToHumanStrType is the type-aware form invoked by PartitionToPath.
// It appends "+00:00" for TimestampTz/TimestampTzNs — information the value-only ToHumanStr(any) cannot recover by design
func (t IdentityTransform) ToHumanStrType(typ Type, val any) string {
if val == nil {
return "null"
}
switch typ.(type) {
case TimestampType:
if v, ok := val.(Timestamp); ok {
return v.ToTime().Format("2006-01-02T15:04:05.999999")
}
case TimestampTzType:
if v, ok := val.(Timestamp); ok {
return v.ToTime().Format("2006-01-02T15:04:05.999999") + "+00:00"
}
case TimestampNsType:
if v, ok := val.(TimestampNano); ok {
return v.ToTime().Format("2006-01-02T15:04:05.999999999")
}
case TimestampTzNsType:
if v, ok := val.(TimestampNano); ok {
return v.ToTime().Format("2006-01-02T15:04:05.999999999") + "+00:00"
}
}
return t.ToHumanStr(val)
}
func (t IdentityTransform) Project(name string, pred BoundPredicate) (UnboundPredicate, error) {
if _, ok := pred.Term().(*BoundTransform); ok {
return projectTransformPredicate(t, name, pred)
}
switch p := pred.(type) {
case BoundUnaryPredicate:
return p.AsUnbound(Reference(name)), nil
case BoundLiteralPredicate:
return p.AsUnbound(Reference(name), p.Literal()), nil
case BoundSetPredicate:
return p.AsUnbound(Reference(name), boundSetLiteralsForVisit(p).Members()), nil
}
return nil, nil
}
// VoidTransform is a transformation that always returns nil.
type VoidTransform struct{}
func (t VoidTransform) MarshalText() ([]byte, error) {
return []byte(t.String()), nil
}
func (VoidTransform) String() string { return "void" }
func (VoidTransform) CanTransform(Type) bool { return true }
func (VoidTransform) ResultType(t Type) Type { return t }
func (VoidTransform) PreservesOrder() bool { return false }
func (VoidTransform) Equals(other Transform) bool {
switch rhs := other.(type) {
case VoidTransform:
return true
case *VoidTransform:
return rhs != nil
default:
return false
}
}
func (VoidTransform) Apply(value Optional[Literal]) Optional[Literal] {
return Optional[Literal]{}
}
func (VoidTransform) ToHumanStr(any) string { return "null" }
func (VoidTransform) ToHumanStrType(Type, any) string { return "null" }
func (VoidTransform) Project(string, BoundPredicate) (UnboundPredicate, error) {
return nil, nil
}
// UnknownTransform is a placeholder for a partition or sort transform that
// this implementation doesn't recognize. The v3 spec requires readers to load
// tables that use unknown transforms and to ignore those fields when
// filtering; writers must not commit a partition spec that uses one.
type UnknownTransform struct {
name string
}
// MarshalText rejects the zero value. UnknownTransform{} is a legal composite
// literal outside this package, and an empty name would serialize to
// "transform": "" -- metadata that can't be read back.
func (t UnknownTransform) MarshalText() ([]byte, error) {
if t.name == "" {
return nil, fmt.Errorf("%w: unknown transform has no name", ErrInvalidTransform)
}
return []byte(t.name), nil
}
func (t UnknownTransform) String() string { return t.name }
// CanTransform always returns true: compatibility with a source type is
// unverifiable for an unknown transform, not verified. Callers such as
// SortOrder.CheckCompatibility therefore accept any source type here.
func (UnknownTransform) CanTransform(Type) bool { return true }
// ResultType is unknown, so report string, matching the Java reference.
func (UnknownTransform) ResultType(Type) Type { return StringType{} }
func (UnknownTransform) PreservesOrder() bool { return false }
func (t UnknownTransform) Equals(other Transform) bool {
switch rhs := other.(type) {
case UnknownTransform:
return t.name == rhs.name
case *UnknownTransform:
return rhs != nil && t.name == rhs.name
default:
return false
}
}
// Apply can't be evaluated for an unknown transform.
func (UnknownTransform) Apply(Optional[Literal]) Optional[Literal] {
return Optional[Literal]{}
}
// ToHumanStr renders the value, not the transform name. Java's
// Transform#toHumanString default does the same and UnknownTransform doesn't
// override it. Returning the name would be constant for a spec field, which
// collapses distinct partitions into one PartitionToPath key.
func (UnknownTransform) ToHumanStr(val any) string {
return IdentityTransform{}.ToHumanStr(val)
}
func (UnknownTransform) ToHumanStrType(typ Type, val any) string {
return IdentityTransform{}.ToHumanStrType(typ, val)
}
// Project returns nil so scans don't prune on an unknown partition field.
func (UnknownTransform) Project(string, BoundPredicate) (UnboundPredicate, error) {
return nil, nil
}
// BucketTransform transforms values into a bucket partition value. It is
// 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.
type BucketTransform struct {
NumBuckets int
}
func (t BucketTransform) MarshalText() ([]byte, error) {
if err := t.validateNumBuckets(); err != nil {
return nil, err
}
return []byte(t.String()), nil
}
func (t BucketTransform) String() string { return fmt.Sprintf("bucket[%d]", t.NumBuckets) }
func (t BucketTransform) validateNumBuckets() error {
if t.NumBuckets <= 0 {
return fmt.Errorf("%w: bucket transform requires numBuckets > 0", ErrInvalidArgument)
}
if t.NumBuckets > math.MaxInt32 {
return fmt.Errorf("%w: bucket transform requires numBuckets <= %d", ErrInvalidArgument, math.MaxInt32)
}
return nil
}
func (BucketTransform) CanTransform(t Type) bool {
switch t.(type) {
case Int32Type,
DateType,
Int64Type,
TimeType,
TimestampNsType,
TimestampType,
TimestampTzNsType,
TimestampTzType,
DecimalType,
StringType,
FixedType,
BinaryType,
UUIDType:
return true
default:
return false
}
}
func (BucketTransform) ResultType(Type) Type { return PrimitiveTypes.Int32 }
func (BucketTransform) PreservesOrder() bool { return false }
func hashHelperInt[T ~int32 | ~int64](v any) uint32 {
var (
val = uint64(v.(T))
buf [8]byte
b = buf[:]
)
binary.LittleEndian.PutUint64(b, val)
return murmur3.Sum32(b)
}
func hashTimestampNano(v any) uint32 {
micros := internal.FloorDiv(int64(v.(TimestampNano)), int64(time.Microsecond))
return hashHelperInt[int64](micros)
}
func hashDecimal(v Decimal) uint32 {
// Decimal bucket transforms hash the minimum two's-complement
// big-endian representation of the unscaled value. Keep the full
// decimal128 value on the stack and trim only redundant sign bytes.
var buf [16]byte
binary.BigEndian.PutUint64(buf[:8], uint64(v.Val.HighBits()))
binary.BigEndian.PutUint64(buf[8:], v.Val.LowBits())
start := 0
if v.Val.Sign() >= 0 {
for start < len(buf)-1 && buf[start] == 0 && buf[start+1]&0x80 == 0 {
start++
}
} else {
for start < len(buf)-1 && buf[start] == 0xff && buf[start+1]&0x80 != 0 {
start++
}
}
return murmur3.Sum32(buf[start:])
}
func (t BucketTransform) Equals(other Transform) bool {
switch rhs := other.(type) {
case BucketTransform:
return t.NumBuckets == rhs.NumBuckets
case *BucketTransform:
return rhs != nil && t.NumBuckets == rhs.NumBuckets
default:
return false
}
}
func (t BucketTransform) Apply(value Optional[Literal]) Optional[Literal] {
if !value.Valid {
return Optional[Literal]{}
}
if err := t.validateNumBuckets(); err != nil {
return Optional[Literal]{}
}
var hash uint32
switch v := value.Val.(type) {
case TypedLiteral[[]byte]:
hash = murmur3.Sum32(v.Value())
case StringLiteral:
hash = murmur3.Sum32(unsafe.Slice(unsafe.StringData(string(v)), len(v)))
case UUIDLiteral:
hash = murmur3.Sum32(v[:])
case DecimalLiteral:
hash = hashDecimal(Decimal(v))
case Int32Literal:
hash = hashHelperInt[int64](int64(v))
case Int64Literal:
hash = hashHelperInt[int64](int64(v))
case DateLiteral:
hash = hashHelperInt[int64](int64(v))
case TimeLiteral:
hash = hashHelperInt[int64](int64(v))
case TimestampLiteral:
hash = hashHelperInt[int64](int64(v))
case TimestampNsLiteral:
hash = hashTimestampNano(TimestampNano(v))
default:
return Optional[Literal]{}
}
return Optional[Literal]{
Valid: true,
Val: Int32Literal((int32(hash) & math.MaxInt32) % int32(t.NumBuckets)),
}
}
func (t BucketTransform) Transformer(src Type) func(any) Optional[int32] {
if err := t.validateNumBuckets(); err != nil {
return func(_ any) Optional[int32] {
return Optional[int32]{}
}
}
var h func(any) uint32
switch src.(type) {
case Int32Type:
h = hashHelperInt[int32]
case DateType:
h = hashHelperInt[Date]
case Int64Type:
h = hashHelperInt[int64]
case TimeType:
h = hashHelperInt[Time]
case TimestampType:
h = hashHelperInt[Timestamp]
case TimestampTzType:
h = hashHelperInt[Timestamp]
case TimestampNsType, TimestampTzNsType:
h = hashTimestampNano
case DecimalType:
h = func(v any) uint32 {
return hashDecimal(v.(Decimal))
}
case StringType, FixedType, BinaryType:
h = func(v any) uint32 {
if v, ok := v.([]byte); ok {
return murmur3.Sum32(v)
}
str := v.(string)
return murmur3.Sum32(unsafe.Slice(unsafe.StringData(str), len(str)))
}
case UUIDType:
h = func(v any) uint32 {
if v, ok := v.([]byte); ok {
return murmur3.Sum32(v)
}
u := v.(uuid.UUID)
return murmur3.Sum32(u[:])
}
}
return func(v any) Optional[int32] {
if v == nil || h == nil {
return Optional[int32]{}
}
return Optional[int32]{
Valid: true,
Val: int32((int32(h(v)) & math.MaxInt32) % int32(t.NumBuckets)),
}
}
}
func (BucketTransform) ToHumanStr(val any) string {
if val == nil {
return "null"
}
return fmt.Sprintf("%v", val)
}
func (t BucketTransform) ToHumanStrType(_ Type, val any) string {
return t.ToHumanStr(val)
}
func (t BucketTransform) Project(name string, pred BoundPredicate) (UnboundPredicate, error) {
if err := t.validateNumBuckets(); err != nil {
return nil, err
}
if _, ok := pred.Term().(*BoundTransform); ok {
return projectTransformPredicate(t, name, pred)
}
if !t.CanTransform(pred.Term().Type()) {
return nil, nil
}
transformer := t.Transformer(pred.Term().Type())
switch p := pred.(type) {
case BoundUnaryPredicate:
return p.AsUnbound(Reference(name)), nil
case BoundLiteralPredicate:
if p.Op() != OpEQ {
break
}
return p.AsUnbound(Reference(name), transformLiteral(transformer, p.Literal())), nil
case BoundSetPredicate:
if p.Op() != OpIn {
break
}
return setApplyTransform(name, p, transformer), nil
}
return nil, nil
}
// TruncateTransform is a transformation for truncating a value to a specified width.
type TruncateTransform struct {
Width int
}
func (t TruncateTransform) MarshalText() ([]byte, error) {
if err := t.validateWidth(); err != nil {
return nil, err
}
return []byte(t.String()), nil
}
func (t TruncateTransform) String() string { return fmt.Sprintf("truncate[%d]", t.Width) }
func (t TruncateTransform) validateWidth() error {
if t.Width <= 0 {
return fmt.Errorf("%w: truncate transform requires width > 0", ErrInvalidArgument)
}
if t.Width > math.MaxInt32 {
return fmt.Errorf("%w: truncate transform requires width <= %d", ErrInvalidArgument, math.MaxInt32)
}
return nil
}
func (TruncateTransform) CanTransform(t Type) bool {
switch t.(type) {
case Int32Type,
Int64Type,
StringType,
BinaryType,
DecimalType:
return true
default:
return false
}
}
func (TruncateTransform) ResultType(t Type) Type { return t }
func (TruncateTransform) PreservesOrder() bool { return true }
func (t TruncateTransform) Equals(other Transform) bool {
switch rhs := other.(type) {
case TruncateTransform:
return t.Width == rhs.Width
case *TruncateTransform:
return rhs != nil && t.Width == rhs.Width
default:
return false
}
}
func (t TruncateTransform) Transformer(src Type) (func(any) any, error) {
if err := t.validateWidth(); err != nil {
return nil, err
}
switch src.(type) {
case Int32Type:
return func(v any) any {
if v == nil {
return nil
}
val := v.(int32)
width := int32(t.Width)
remainder := val % width
if remainder < 0 {
remainder += width
}
return val - remainder
}, nil
case Int64Type:
return func(v any) any {
if v == nil {
return nil
}
val := v.(int64)
width := int64(t.Width)
remainder := val % width
if remainder < 0 {
remainder += width
}
return val - remainder
}, nil
case StringType:
return func(v any) any {
str, ok := v.(string)
if !ok {
return nil
}
return truncateString(str, t.Width)
}, nil
case BinaryType:
return func(v any) any {
b, ok := v.([]byte)
if !ok {
return nil
}
return b[:min(len(b), t.Width)]
}, nil
case DecimalType:
bigWidth := big.NewInt(int64(t.Width))
return func(v any) any {
if v == nil {
return nil
}
val := v.(Decimal)
unscaled := val.Val.BigInt()
// big.Int.Mod already gives a non-negative remainder for positive widths.
applied := (&big.Int{}).Mod(unscaled, bigWidth)
val.Val = decimal128.FromBigInt(unscaled.Sub(unscaled, applied))
return val
}, nil
}
return nil, fmt.Errorf("%w: cannot truncate for type %s",
ErrInvalidArgument, src)
}
// truncateString truncates by UTF-8 code points without allocating.
// Strings shorter than the width in bytes need no scan. ASCII prefixes
// can be sliced directly, while other prefixes still use rune boundaries.
func truncateString(s string, width int) string {
if width >= len(s) {
return s
}
idx := 0
for idx < width && s[idx] < utf8.RuneSelf {
idx++
}
if idx == width {
return s[:idx]
}
width -= idx
for offset := range s[idx:] {
if width == 0 {
return s[:idx+offset]
}
width--
}
return s
}
func (t TruncateTransform) Apply(value Optional[Literal]) (out Optional[Literal]) {
if !value.Valid {
return out
}
fn, err := t.Transformer(value.Val.Type())
if err != nil {
return out
}
out.Valid = true
switch v := value.Val.(type) {
case Int32Literal:
out.Val = Int32Literal(fn(int32(v)).(int32))
case Int64Literal:
out.Val = Int64Literal(fn(int64(v)).(int64))
case DecimalLiteral:
out.Val = DecimalLiteral(fn(Decimal(v)).(Decimal))
case StringLiteral:
out.Val = StringLiteral(fn(string(v)).(string))
case BinaryLiteral:
out.Val = BinaryLiteral(fn([]byte(v)).([]byte))
}
return out
}
func (TruncateTransform) ToHumanStr(val any) string {
switch v := val.(type) {
case nil:
return "null"
case []byte:
return base64.StdEncoding.EncodeToString(v)
default:
return fmt.Sprintf("%v", v)
}
}
func (t TruncateTransform) ToHumanStrType(_ Type, val any) string {
return t.ToHumanStr(val)
}
func (t TruncateTransform) Project(name string, pred BoundPredicate) (UnboundPredicate, error) {
if err := t.validateWidth(); err != nil {
return nil, err
}
if _, ok := pred.Term().(*BoundTransform); ok {
return projectTransformPredicate(t, name, pred)
}
fieldType := pred.Term().Ref().Field().Type
transformer, err := t.Transformer(fieldType)
if err != nil {
return nil, err
}
switch p := pred.(type) {
case BoundUnaryPredicate:
return p.AsUnbound(Reference(name)), nil
case BoundSetPredicate:
if p.Op() != OpIn {
break
}
switch fieldType.(type) {
case Int32Type:
return setApplyTransform(name, p, wrapTransformFn[int32](transformer)), nil
case Int64Type:
return setApplyTransform(name, p, wrapTransformFn[int64](transformer)), nil
case DecimalType:
return setApplyTransform(name, p, wrapTransformFn[Decimal](transformer)), nil
case StringType:
return setApplyTransform(name, p, wrapTransformFn[string](transformer)), nil
case BinaryType:
return setApplyTransform(name, p, wrapTransformFn[[]byte](transformer)), nil
}
case BoundLiteralPredicate:
// notStartsWith is only projectable when the prefix fits within the
// truncation width. If the prefix is longer, the truncated partition
// value may itself satisfy the predicate, so projecting the truncated
// prefix would incorrectly prune matching files.
if p.Op() == OpNotStartsWith {
l := literalLen(p.Literal())
switch {
case l < 0:
return nil, nil
case l < t.Width:
return LiteralPredicate(OpNotStartsWith, Reference(name), p.Literal()), nil
case l == t.Width:
return LiteralPredicate(OpNEQ, Reference(name), p.Literal()), nil
}
return nil, nil
}
switch fieldType.(type) {
case Int32Type:
return truncateNumber(name, p, wrapTransformFn[int32](transformer))
case Int64Type:
return truncateNumber(name, p, wrapTransformFn[int64](transformer))
case DecimalType:
return truncateNumber(name, p, wrapTransformFn[Decimal](transformer))
case StringType:
return truncateArray(name, p, wrapTransformFn[string](transformer))
case BinaryType:
return truncateArray(name, p, wrapTransformFn[[]byte](transformer))
}
}
return nil, nil
}
var epochTM = time.Unix(0, 0).UTC()
type TimeTransform interface {
Transform
Transformer(Type) (func(any) Optional[int32], error)
}
func canTransformTime(t TimeTransform, sourceType Type) bool {
switch sourceType.(type) {
case DateType, TimestampType, TimestampTzType, TimestampNsType, TimestampTzNsType:
return true
default:
return false
}
}
func projectTimeTransform(t TimeTransform, name string, pred BoundPredicate) (UnboundPredicate, error) {
if _, ok := pred.Term().(*BoundTransform); ok {
return projectTransformPredicate(t, name, pred)
}
transformer, err := t.Transformer(pred.Term().Ref().Type())
if err != nil {
return nil, err
}
switch p := pred.(type) {
case BoundUnaryPredicate:
return p.AsUnbound(Reference(name)), nil
case BoundLiteralPredicate:
return truncateNumber(name, p, transformer)
case BoundSetPredicate:
if p.Op() != OpIn {
break
}
return setApplyTransform(name, p, transformer), nil
}
return nil, nil
}
// YearTransform transforms a datetime value into a year value.
type YearTransform struct{}
func (t YearTransform) MarshalText() ([]byte, error) {
return []byte(t.String()), nil
}
func (YearTransform) String() string { return "year" }
func (t YearTransform) CanTransform(sourceType Type) bool { return canTransformTime(t, sourceType) }