-
Notifications
You must be signed in to change notification settings - Fork 67
/
Copy pathschema.go
1719 lines (1503 loc) · 47.3 KB
/
schema.go
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
package dynparquet
import (
"bytes"
"errors"
"fmt"
"io"
"regexp"
"slices"
"sort"
"strings"
"sync"
"text/tabwriter"
"github.com/parquet-go/parquet-go"
"github.com/parquet-go/parquet-go/compress"
"github.com/parquet-go/parquet-go/encoding"
"github.com/parquet-go/parquet-go/format"
"google.golang.org/protobuf/proto"
schemapb "github.com/polarsignals/frostdb/gen/proto/go/frostdb/schema/v1alpha1"
schemav2pb "github.com/polarsignals/frostdb/gen/proto/go/frostdb/schema/v1alpha2"
)
const (
// The size of the column indicies in parquet files.
ColumnIndexSize = 16
)
// ColumnDefinition describes a column in a dynamic parquet schema.
type ColumnDefinition struct {
Name string
StorageLayout parquet.Node
Dynamic bool
PreHash bool
}
// SortingColumn describes a column to sort by in a dynamic parquet schema.
type SortingColumn interface {
parquet.SortingColumn
ColumnName() string
}
// Ascending constructs a SortingColumn value which dictates to sort by the column in ascending order.
func Ascending(column string) SortingColumn { return ascending{name: column, path: []string{column}} }
// Descending constructs a SortingColumn value which dictates to sort by the column in descending order.
func Descending(column string) SortingColumn { return descending{name: column, path: []string{column}} }
// NullsFirst wraps the SortingColumn passed as argument so that it instructs
// the row group to place null values first in the column.
func NullsFirst(sortingColumn SortingColumn) SortingColumn { return nullsFirst{sortingColumn} }
type ascending struct {
name string
path []string
}
func (asc ascending) String() string { return "ascending(" + asc.name + ")" }
func (asc ascending) ColumnName() string { return asc.name }
func (asc ascending) Path() []string { return asc.path }
func (asc ascending) Descending() bool { return false }
func (asc ascending) NullsFirst() bool { return false }
type descending struct {
name string
path []string
}
func (desc descending) String() string { return "descending(" + desc.name + ")" }
func (desc descending) ColumnName() string { return desc.name }
func (desc descending) Path() []string { return desc.path }
func (desc descending) Descending() bool { return true }
func (desc descending) NullsFirst() bool { return false }
type nullsFirst struct{ SortingColumn }
func (nf nullsFirst) String() string { return fmt.Sprintf("nulls_first+%s", nf.SortingColumn) }
func (nf nullsFirst) NullsFirst() bool { return true }
func makeDynamicSortingColumn(dynamicColumnName string, sortingColumn SortingColumn) SortingColumn {
fullName := sortingColumn.ColumnName() + "." + dynamicColumnName
return dynamicSortingColumn{
SortingColumn: sortingColumn,
dynamicColumnName: dynamicColumnName,
fullName: fullName,
path: []string{fullName},
}
}
// dynamicSortingColumn is a SortingColumn which is a dynamic column.
type dynamicSortingColumn struct {
SortingColumn
dynamicColumnName string
fullName string
path []string
}
func (dyn dynamicSortingColumn) String() string {
return fmt.Sprintf("dynamic(%s, %v)", dyn.dynamicColumnName, dyn.SortingColumn)
}
func (dyn dynamicSortingColumn) ColumnName() string {
return dyn.fullName
}
func (dyn dynamicSortingColumn) Path() []string { return dyn.path }
// Schema is a dynamic parquet schema. It extends a parquet schema with the
// ability that any column definition that is dynamic will have columns
// dynamically created as their column name is seen for the first time.
type Schema struct {
def proto.Message
columns []ColumnDefinition
columnIndexes map[string]int
sortingColumns []SortingColumn
dynamicColumns []int
UniquePrimaryIndex bool
writers *sync.Map
buffers *sync.Map
sortingSchemas *sync.Map
parquetSchemas *sync.Map
}
// FindDynamicColumnForConcreteColumn returns a column definition for the
// column passed. So "labels.label1" would return the column definition for the
// dynamic column "labels" if it exists.
func (s *Schema) FindDynamicColumnForConcreteColumn(column string) (ColumnDefinition, bool) {
periodPosition := 0
foundPeriod := false
for i, c := range column {
if c != '.' {
continue
}
if foundPeriod {
// Can't have more than one period.
return ColumnDefinition{}, false
}
foundPeriod = true
periodPosition = i
}
if !foundPeriod {
return ColumnDefinition{}, false
}
return s.FindDynamicColumn(column[:periodPosition])
}
// FindDynamicColumn returns a dynamic column definition for the column passed.
func (s *Schema) FindDynamicColumn(dynamicColumnName string) (ColumnDefinition, bool) {
idx, ok := s.columnIndexes[dynamicColumnName]
if !ok {
return ColumnDefinition{}, false
}
colDef := s.columns[idx]
// Note: This is different from the FindColumn function.
if !colDef.Dynamic {
return ColumnDefinition{}, false
}
return colDef, true
}
// FindColumn returns a column definition for the column passed.
func (s *Schema) FindColumn(column string) (ColumnDefinition, bool) {
idx, ok := s.columnIndexes[column]
if !ok {
return ColumnDefinition{}, false
}
colDef := s.columns[idx]
// Note: This is different from the FindDynamicColumn function.
if colDef.Dynamic {
return ColumnDefinition{}, false
}
return colDef, true
}
func findLeavesFromNode(node *schemav2pb.Node) []ColumnDefinition {
switch n := node.Type.(type) {
case *schemav2pb.Node_Leaf:
ret, err := storageLayoutToParquetNode(&v2storageLayoutWrapper{n.Leaf.StorageLayout})
if err != nil {
panic("sheisse")
}
return []ColumnDefinition{
{
Name: n.Leaf.Name,
StorageLayout: ret,
Dynamic: false, // TODO(can we get rid of dynamic cols): do we need dynamic columns to be separate?
},
}
case *schemav2pb.Node_Group:
columns := make([]ColumnDefinition, 0, len(n.Group.Nodes))
for _, g := range n.Group.Nodes {
columns = append(columns, findLeavesFromNode(g)...)
}
return columns
default:
panic(fmt.Sprintf("unknown node type: %v", n))
}
}
func ParquetSchemaFromV2Definition(def *schemav2pb.Schema) *parquet.Schema {
root := parquet.Group{}
for _, node := range def.Root.Nodes {
root[nameFromNodeDef(node)] = nodeFromDefinition(node)
}
return parquet.NewSchema(def.Root.Name, root)
}
func nodeFromDefinition(node *schemav2pb.Node) parquet.Node {
switch n := node.Type.(type) {
case *schemav2pb.Node_Leaf:
ret, err := storageLayoutToParquetNode(&v2storageLayoutWrapper{n.Leaf.StorageLayout})
if err != nil {
panic("sheisse")
}
return ret
case *schemav2pb.Node_Group:
group := parquet.Group{}
for _, g := range n.Group.Nodes {
group[nameFromNodeDef(g)] = nodeFromDefinition(g)
}
var node parquet.Node
node = group
if n.Group.Nullable {
node = parquet.Optional(node)
}
if n.Group.Repeated {
node = parquet.Repeated(node)
}
return node
default:
panic(fmt.Sprintf("unknown node type: %v", n))
}
}
func nameFromNodeDef(node *schemav2pb.Node) string {
switch n := node.Type.(type) {
case *schemav2pb.Node_Leaf:
return n.Leaf.Name
case *schemav2pb.Node_Group:
return n.Group.Name
default:
panic(fmt.Sprintf("unknown node type: %v", n))
}
}
func SchemaFromDefinition(msg proto.Message) (*Schema, error) {
var (
columns []ColumnDefinition
sortingColumns []SortingColumn
uniquePrimaryIndex bool
)
switch def := msg.(type) {
case *schemapb.Schema:
columns = make([]ColumnDefinition, 0, len(def.Columns))
for _, col := range def.Columns {
layout, err := storageLayoutToParquetNode(&v1storageLayoutWrapper{col.StorageLayout})
if err != nil {
return nil, err
}
columns = append(columns, ColumnDefinition{
Name: col.Name,
StorageLayout: layout,
Dynamic: col.Dynamic,
PreHash: col.Prehash,
})
}
sortingColumns = make([]SortingColumn, 0, len(def.SortingColumns))
for _, col := range def.SortingColumns {
var sortingColumn SortingColumn
switch col.Direction {
case schemapb.SortingColumn_DIRECTION_ASCENDING:
sortingColumn = Ascending(col.Name)
case schemapb.SortingColumn_DIRECTION_DESCENDING:
sortingColumn = Descending(col.Name)
default:
return nil, fmt.Errorf("unknown sorting direction %q, only \"ascending\", \"descending\" are valid choices", col.Direction)
}
if col.NullsFirst {
sortingColumn = NullsFirst(sortingColumn)
}
sortingColumns = append(sortingColumns, sortingColumn)
}
uniquePrimaryIndex = def.UniquePrimaryIndex
case *schemav2pb.Schema:
columns = []ColumnDefinition{}
for _, node := range def.Root.Nodes {
columns = append(columns, findLeavesFromNode(node)...)
}
sortingColumns = make([]SortingColumn, 0, len(def.SortingColumns))
for _, col := range def.SortingColumns {
var sortingColumn SortingColumn
switch col.Direction {
case schemav2pb.SortingColumn_DIRECTION_ASCENDING:
sortingColumn = Ascending(col.Path)
case schemav2pb.SortingColumn_DIRECTION_DESCENDING:
sortingColumn = Descending(col.Path)
default:
return nil, fmt.Errorf("unknown sorting direction %q, only \"ascending\", \"descending\" are valid choices", col.Direction)
}
if col.NullsFirst {
sortingColumn = NullsFirst(sortingColumn)
}
sortingColumns = append(sortingColumns, sortingColumn)
}
uniquePrimaryIndex = def.UniquePrimaryIndex
}
return newSchema(msg, columns, sortingColumns, uniquePrimaryIndex), nil
}
// DefinitionFromParquetFile converts a parquet file into a schemapb.Schema.
func DefinitionFromParquetFile(file *parquet.File) (*schemapb.Schema, error) {
schema := file.Schema()
buf, err := NewSerializedBuffer(file)
if err != nil {
return nil, err
}
dyncols := buf.DynamicColumns()
found := map[string]struct{}{}
columns := []*schemapb.Column{}
metadata := file.Metadata()
sortingCols := []*schemapb.SortingColumn{}
foundSortingCols := map[string]struct{}{}
for _, rg := range metadata.RowGroups {
// Extract the sorting column information
for _, sc := range rg.SortingColumns {
name := rg.Columns[sc.ColumnIdx].MetaData.PathInSchema[0]
isDynamic := false
split := strings.Split(name, ".")
colName := split[0]
if len(split) > 1 && len(dyncols[colName]) != 0 {
isDynamic = true
}
if isDynamic {
name = colName
}
// we need a set to filter out duplicates
if _, ok := foundSortingCols[name]; ok {
continue
}
foundSortingCols[name] = struct{}{}
direction := schemapb.SortingColumn_DIRECTION_ASCENDING
if sc.Descending {
direction = schemapb.SortingColumn_DIRECTION_DESCENDING
}
sortingCols = append(sortingCols, &schemapb.SortingColumn{
Name: name,
Direction: direction,
NullsFirst: sc.NullsFirst,
})
}
for _, col := range rg.Columns {
name := col.MetaData.PathInSchema[0] // we only support flat schemas
// Check if the column is optional
nullable := false
for _, node := range schema.Fields() {
if node.Name() == name {
nullable = node.Optional()
}
}
isDynamic := false
split := strings.Split(name, ".")
colName := split[0]
if len(split) > 1 && len(dyncols[colName]) != 0 {
isDynamic = true
}
// Mark the dynamic column as being found
if _, ok := found[colName]; ok {
continue
}
found[colName] = struct{}{}
columns = append(columns, &schemapb.Column{
Name: split[0],
StorageLayout: parquetColumnMetaDataToStorageLayout(col.MetaData, nullable),
Dynamic: isDynamic,
})
}
}
return &schemapb.Schema{
Name: schema.Name(),
Columns: columns,
SortingColumns: sortingCols,
}, nil
}
// SchemaFromParquetFile converts a parquet file into a dnyparquet.Schema.
func SchemaFromParquetFile(file *parquet.File) (*Schema, error) {
def, err := DefinitionFromParquetFile(file)
if err != nil {
return nil, err
}
return SchemaFromDefinition(def)
}
func parquetColumnMetaDataToStorageLayout(metadata format.ColumnMetaData, nullable bool) *schemapb.StorageLayout {
layout := &schemapb.StorageLayout{
Nullable: nullable,
}
switch metadata.Encoding[len(metadata.Encoding)-1] {
case format.RLEDictionary:
layout.Encoding = schemapb.StorageLayout_ENCODING_RLE_DICTIONARY
case format.DeltaBinaryPacked:
layout.Encoding = schemapb.StorageLayout_ENCODING_DELTA_BINARY_PACKED
}
switch metadata.Codec {
case format.Snappy:
layout.Compression = schemapb.StorageLayout_COMPRESSION_SNAPPY
case format.Gzip:
layout.Compression = schemapb.StorageLayout_COMPRESSION_GZIP
case format.Brotli:
layout.Compression = schemapb.StorageLayout_COMPRESSION_BROTLI
case format.Lz4Raw:
layout.Compression = schemapb.StorageLayout_COMPRESSION_LZ4_RAW
case format.Zstd:
layout.Compression = schemapb.StorageLayout_COMPRESSION_ZSTD
}
switch metadata.Type {
case format.ByteArray:
layout.Type = schemapb.StorageLayout_TYPE_STRING
case format.Int64:
layout.Type = schemapb.StorageLayout_TYPE_INT64
case format.Double:
layout.Type = schemapb.StorageLayout_TYPE_DOUBLE
case format.Boolean:
layout.Type = schemapb.StorageLayout_TYPE_BOOL
}
return layout
}
type StorageLayout interface {
GetTypeInt32() int32
GetRepeated() bool
GetNullable() bool
GetEncodingInt32() int32
GetCompressionInt32() int32
}
type v1storageLayoutWrapper struct {
*schemapb.StorageLayout
}
func (s *v1storageLayoutWrapper) GetRepeated() bool {
return s.Repeated
}
func (s *v1storageLayoutWrapper) GetTypeInt32() int32 {
return int32(s.StorageLayout.GetType())
}
func (s *v1storageLayoutWrapper) GetEncodingInt32() int32 {
return int32(s.StorageLayout.GetEncoding())
}
func (s *v1storageLayoutWrapper) GetCompressionInt32() int32 {
return int32(s.StorageLayout.GetCompression())
}
type v2storageLayoutWrapper struct {
*schemav2pb.StorageLayout
}
func (s *v2storageLayoutWrapper) GetTypeInt32() int32 {
return int32(s.StorageLayout.GetType())
}
func (s *v2storageLayoutWrapper) GetEncodingInt32() int32 {
return int32(s.StorageLayout.GetEncoding())
}
func (s *v2storageLayoutWrapper) GetCompressionInt32() int32 {
return int32(s.StorageLayout.GetCompression())
}
func StorageLayoutWrapper(_ *schemav2pb.StorageLayout) StorageLayout {
return nil
}
func storageLayoutToParquetNode(l StorageLayout) (parquet.Node, error) {
var node parquet.Node
switch l.GetTypeInt32() {
case int32(schemapb.StorageLayout_TYPE_STRING):
node = parquet.String()
case int32(schemapb.StorageLayout_TYPE_INT64):
node = parquet.Int(64)
case int32(schemapb.StorageLayout_TYPE_DOUBLE):
node = parquet.Leaf(parquet.DoubleType)
case int32(schemapb.StorageLayout_TYPE_BOOL):
node = parquet.Leaf(parquet.BooleanType)
case int32(schemapb.StorageLayout_TYPE_INT32):
node = parquet.Int(32)
case int32(schemapb.StorageLayout_TYPE_UINT64):
node = parquet.Uint(64)
default:
return nil, fmt.Errorf("unknown storage layout type: %v", l.GetTypeInt32())
}
if l.GetNullable() {
node = parquet.Optional(node)
}
if l.GetEncodingInt32() != int32(schemapb.StorageLayout_ENCODING_PLAIN_UNSPECIFIED) {
enc, err := encodingFromDefinition(l.GetEncodingInt32())
if err != nil {
return nil, err
}
node = parquet.Encoded(node, enc)
}
if l.GetCompressionInt32() != int32(schemapb.StorageLayout_COMPRESSION_NONE_UNSPECIFIED) {
comp, err := compressionFromDefinition(l.GetCompressionInt32())
if err != nil {
return nil, err
}
node = parquet.Compressed(node, comp)
}
if l.GetRepeated() {
node = parquet.Repeated(node)
}
return node, nil
}
func encodingFromDefinition(enc int32) (encoding.Encoding, error) {
switch enc {
case int32(schemapb.StorageLayout_ENCODING_RLE_DICTIONARY):
return &parquet.RLEDictionary, nil
case int32(schemapb.StorageLayout_ENCODING_DELTA_BINARY_PACKED):
return &parquet.DeltaBinaryPacked, nil
case int32(schemapb.StorageLayout_ENCODING_DELTA_BYTE_ARRAY):
return &parquet.DeltaByteArray, nil
case int32(schemapb.StorageLayout_ENCODING_DELTA_LENGTH_BYTE_ARRAY):
return &parquet.DeltaLengthByteArray, nil
default:
return nil, fmt.Errorf("unknown encoding: %v", enc)
}
}
func compressionFromDefinition(comp int32) (compress.Codec, error) {
switch comp {
case int32(schemapb.StorageLayout_COMPRESSION_SNAPPY):
return &parquet.Snappy, nil
case int32(schemapb.StorageLayout_COMPRESSION_GZIP):
return &parquet.Gzip, nil
case int32(schemapb.StorageLayout_COMPRESSION_BROTLI):
return &parquet.Brotli, nil
case int32(schemapb.StorageLayout_COMPRESSION_LZ4_RAW):
return &parquet.Lz4Raw, nil
case int32(schemapb.StorageLayout_COMPRESSION_ZSTD):
return &parquet.Zstd, nil
default:
return nil, fmt.Errorf("unknown compression: %v", comp)
}
}
// NewSchema creates a new dynamic parquet schema with the given name, column
// definitions and sorting columns. The order of the sorting columns is
// important as it determines the order in which data is written to a file or
// laid out in memory.
func newSchema(
def proto.Message,
columns []ColumnDefinition,
sortingColumns []SortingColumn,
uniquePrimaryIndex bool,
) *Schema {
sort.Slice(columns, func(i, j int) bool {
return columns[i].Name < columns[j].Name
})
columnIndexes := make(map[string]int, len(columns))
for i, col := range columns {
columnIndexes[col.Name] = i
}
s := &Schema{
def: def,
columns: columns,
sortingColumns: sortingColumns,
columnIndexes: columnIndexes,
writers: &sync.Map{},
buffers: &sync.Map{},
sortingSchemas: &sync.Map{},
parquetSchemas: &sync.Map{},
UniquePrimaryIndex: uniquePrimaryIndex,
}
for i, col := range columns {
if col.Dynamic {
s.dynamicColumns = append(s.dynamicColumns, i)
}
}
return s
}
func (s *Schema) Name() string {
switch sc := s.def.(type) {
case *schemapb.Schema:
return sc.GetName()
case *schemav2pb.Schema:
return sc.Root.GetName()
default:
panic("unknown schema version")
}
}
func (s *Schema) Definition() proto.Message {
return s.def
}
func (s *Schema) ColumnByName(name string) (ColumnDefinition, bool) {
i, ok := s.columnIndexes[name]
if !ok {
return ColumnDefinition{}, false
}
return s.columns[i], true
}
func (s *Schema) Columns() []ColumnDefinition {
return s.columns
}
func (s *Schema) SortingColumns() []SortingColumn {
sCols := make([]SortingColumn, len(s.sortingColumns))
copy(sCols, s.sortingColumns)
return sCols
}
func (s *Schema) ColumnDefinitionsForSortingColumns() []ColumnDefinition {
sCols := make([]ColumnDefinition, len(s.sortingColumns))
for i, col := range s.sortingColumns {
sCols[i] = s.columns[s.columnIndexes[col.ColumnName()]]
}
return sCols
}
func (s *Schema) ParquetSchema() *parquet.Schema {
switch schema := s.def.(type) {
case *schemav2pb.Schema:
return ParquetSchemaFromV2Definition(schema)
case *schemapb.Schema:
g := parquet.Group{}
for _, col := range s.columns {
g[col.Name] = col.StorageLayout
}
return parquet.NewSchema(s.Name(), g)
default:
panic(fmt.Sprintf("unknown schema version %T", schema))
}
}
// dynamicParquetSchema returns the parquet schema for the dynamic schema with the
// concrete dynamic column names given in the argument.
func (s Schema) dynamicParquetSchema(dynamicColumns map[string][]string) (*parquet.Schema, error) {
switch def := s.def.(type) {
case *schemav2pb.Schema:
return ParquetSchemaFromV2Definition(def), nil
case *schemapb.Schema:
g := parquet.Group{}
for _, col := range s.columns {
if col.Dynamic {
dyn := dynamicColumnsFor(col.Name, dynamicColumns)
for _, name := range dyn {
g[col.Name+"."+name] = col.StorageLayout
if col.PreHash {
g[HashedColumnName(col.Name+"."+name)] = parquet.Int(64) // TODO(thor): Do we need compression etc. here?
}
}
continue
}
g[col.Name] = col.StorageLayout
if col.PreHash {
g[HashedColumnName(col.Name)] = parquet.Int(64) // TODO(thor): Do we need compression etc. here?
}
}
return parquet.NewSchema(s.Name(), g), nil
default:
return nil, fmt.Errorf("unsupported schema definition version")
}
}
// parquetSortingSchema returns the parquet schema of just the sorting columns
// with the concrete dynamic column names given in the argument.
func (s Schema) parquetSortingSchema(
dynamicColumns map[string][]string,
) (
*parquet.Schema,
error,
) {
g := parquet.Group{}
for _, col := range s.sortingColumns {
colName := col.ColumnName()
col := s.columns[s.columnIndexes[colName]]
if !col.Dynamic {
g[colName] = col.StorageLayout
continue
}
dyn := dynamicColumnsFor(col.Name, dynamicColumns)
for _, name := range dyn {
g[colName+"."+name] = col.StorageLayout
}
}
return parquet.NewSchema(s.Name(), g), nil
}
// ParquetSortingColumns returns the parquet sorting columns for the dynamic
// sorting columns with the concrete dynamic column names given in the
// argument.
func (s Schema) ParquetSortingColumns(
dynamicColumns map[string][]string,
) []parquet.SortingColumn {
cols := make([]parquet.SortingColumn, 0, len(s.sortingColumns))
for _, col := range s.sortingColumns {
colName := col.ColumnName()
if !s.columns[s.columnIndexes[colName]].Dynamic {
cols = append(cols, col)
continue
}
dyn := dynamicColumnsFor(colName, dynamicColumns)
for _, name := range dyn {
cols = append(cols, makeDynamicSortingColumn(name, col))
}
}
return cols
}
// dynamicColumnsFor returns the concrete dynamic column names for the given dynamic column name.
func dynamicColumnsFor(column string, dynamicColumns map[string][]string) []string {
return dynamicColumns[column]
}
// Buffer represents an batch of rows with a concrete set of dynamic column
// names representing how its parquet schema was created off of a dynamic
// parquet schema.
type Buffer struct {
buffer *parquet.Buffer
dynamicColumns map[string][]string
fields []parquet.Field
}
func (b *Buffer) Reset() {
b.buffer.Reset()
}
func (b *Buffer) Size() int64 {
return b.buffer.Size()
}
func (b *Buffer) String() string {
return prettyRowGroup(b)
}
// DynamicRowGroup is a parquet.RowGroup that can describe the concrete dynamic
// columns.
type DynamicRowGroup interface {
parquet.RowGroup
fmt.Stringer
// DynamicColumns returns the concrete dynamic column names that were used
// create its concrete parquet schema with a dynamic parquet schema.
DynamicColumns() map[string][]string
// DynamicRows return an iterator over the rows in the row group.
DynamicRows() DynamicRowReader
}
type prettyWriter struct {
*tabwriter.Writer
cellWidth int
b *bytes.Buffer
}
func newPrettyWriter() prettyWriter {
const (
tabWidth = 15
minWidth = tabWidth
padding = 2
padChar = ' '
noFlags = 0
)
w := prettyWriter{
cellWidth: tabWidth,
b: bytes.NewBuffer(nil),
}
w.Writer = tabwriter.NewWriter(w.b, minWidth, tabWidth, padding, padChar, noFlags)
return w
}
func (w prettyWriter) String() string {
return w.b.String()
}
func (w prettyWriter) truncateString(s string) string {
const ellipses = "..."
if len(s) > w.cellWidth {
return s[:w.cellWidth-len(ellipses)] + ellipses
}
return s
}
func (w prettyWriter) writePrettyRowGroup(rg DynamicRowGroup) {
rows := rg.Rows()
defer rows.Close()
// Print sorting schema.
for _, col := range rg.SortingColumns() {
_, _ = w.Write([]byte(w.truncateString(fmt.Sprintf("%v", col.Path())) + "\t"))
}
_, _ = w.Write([]byte("\n"))
rBuf := make([]parquet.Row, rg.NumRows())
for {
n, err := rows.ReadRows(rBuf)
for _, row := range rBuf[:n] {
// Print only sorting columns.
for _, col := range rg.SortingColumns() {
leaf, ok := rg.Schema().Lookup(col.Path()...)
if !ok {
panic(fmt.Sprintf("sorting column not found: %v", col.Path()))
}
_, _ = w.Write([]byte(w.truncateString(row[leaf.ColumnIndex].String()) + "\t"))
}
_, _ = w.Write([]byte("\n"))
}
if err != nil {
if errors.Is(err, io.EOF) {
break
}
panic(err)
}
}
}
func prettyRowGroup(rg DynamicRowGroup) string {
w := newPrettyWriter()
w.writePrettyRowGroup(rg)
_ = w.Flush()
return w.String()
}
// DynamicRowReader is an iterator over the rows in a DynamicRowGroup.
type DynamicRowReader interface {
parquet.RowSeeker
ReadRows(*DynamicRows) (int, error)
Close() error
}
type dynamicRowGroupReader struct {
schema *parquet.Schema
dynamicColumns map[string][]string
rows parquet.Rows
fields []parquet.Field
}
func newDynamicRowGroupReader(rg DynamicRowGroup, fields []parquet.Field) *dynamicRowGroupReader {
return &dynamicRowGroupReader{
schema: rg.Schema(),
dynamicColumns: rg.DynamicColumns(),
rows: rg.Rows(),
fields: fields,
}
}
func (r *dynamicRowGroupReader) SeekToRow(i int64) error {
return r.rows.SeekToRow(i)
}
// ReadRows implements the DynamicRows interface.
func (r *dynamicRowGroupReader) ReadRows(rows *DynamicRows) (int, error) {
if rows.DynamicColumns == nil {
rows.DynamicColumns = r.dynamicColumns
}
if rows.Schema == nil {
rows.Schema = r.schema
}
if rows.fields == nil {
rows.fields = r.fields
}
n, err := r.rows.ReadRows(rows.Rows)
if err == io.EOF {
rows.Rows = rows.Rows[:n]
return n, io.EOF
}
if err != nil {
return n, fmt.Errorf("read row: %w", err)
}
rows.Rows = rows.Rows[:n]
return n, nil
}
func (r *dynamicRowGroupReader) Close() error {
return r.rows.Close()
}
// ColumnChunks returns the list of parquet.ColumnChunk for the given index.
// It contains all the pages associated with this row group's column.
// Implements the parquet.RowGroup interface.
func (b *Buffer) ColumnChunks() []parquet.ColumnChunk {
return b.buffer.ColumnChunks()
}
// NumRows returns the number of rows in the buffer. Implements the
// parquet.RowGroup interface.
func (b *Buffer) NumRows() int64 {
return b.buffer.NumRows()
}
func (b *Buffer) Sort() {
sort.Sort(b.buffer)
}
func (b *Buffer) Clone() (*Buffer, error) {
buf := parquet.NewBuffer(
b.buffer.Schema(),
parquet.SortingRowGroupConfig(
parquet.SortingColumns(b.buffer.SortingColumns()...),
),
)
rows := b.buffer.Rows()
defer rows.Close()
for {
rowBuf := make([]parquet.Row, 64)
n, err := rows.ReadRows(rowBuf)
if err == io.EOF && n == 0 {
break
}
if err != nil && err != io.EOF {
return nil, err
}
rowBuf = rowBuf[:n]
_, err = buf.WriteRows(rowBuf)
if err != nil {
return nil, err
}
if err == io.EOF {
break
}
}
return &Buffer{
buffer: buf,
dynamicColumns: b.dynamicColumns,
fields: b.fields,
}, nil
}
// Schema returns the concrete parquet.Schema of the buffer. Implements the
// parquet.RowGroup interface.
func (b *Buffer) Schema() *parquet.Schema {
return b.buffer.Schema()
}
// SortingColumns returns the concrete slice of parquet.SortingColumns of the
// buffer. Implements the parquet.RowGroup interface.
func (b *Buffer) SortingColumns() []parquet.SortingColumn {
return b.buffer.SortingColumns()
}
// DynamicColumns returns the concrete dynamic column names of the buffer. It
// implements the DynamicRowGroup interface.
func (b *Buffer) DynamicColumns() map[string][]string {
return b.dynamicColumns
}
// WriteRow writes a single row to the buffer.