forked from segmentio/parquet-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
node.go
483 lines (396 loc) · 12.6 KB
/
node.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
package parquet
import (
"reflect"
"sort"
"unicode"
"unicode/utf8"
"github.com/segmentio/parquet-go/compress"
"github.com/segmentio/parquet-go/deprecated"
"github.com/segmentio/parquet-go/encoding"
"github.com/segmentio/parquet-go/format"
)
// Node values represent nodes of a parquet schema.
//
// Nodes carry the type of values, as well as properties like whether the values
// are optional or repeat. Nodes with one or more children represent parquet
// groups and therefore do not have a logical type.
//
// Nodes are immutable values and therefore safe to use concurrently from
// multiple goroutines.
type Node interface {
// Returns a human-readable representation of the parquet node.
String() string
// For leaf nodes, returns the type of values of the parquet column.
//
// Calling this method on non-leaf nodes will panic.
Type() Type
// Returns whether the parquet column is optional.
Optional() bool
// Returns whether the parquet column is repeated.
Repeated() bool
// Returns whether the parquet column is required.
Required() bool
// Returns true if this a leaf node.
Leaf() bool
// Returns a mapping of the node's fields.
//
// As an optimization, the same slices may be returned by multiple calls to
// this method, programs must treat the returned values as immutable.
//
// This method returns an empty mapping when called on leaf nodes.
Fields() []Field
// Returns the encoding used by the node.
//
// The method may return nil to indicate that no specific encoding was
// configured on the node, in which case a default encoding might be used.
Encoding() encoding.Encoding
// Returns compression codec used by the node.
//
// The method may return nil to indicate that no specific compression codec
// was configured on the node, in which case a default compression might be
// used.
Compression() compress.Codec
// Returns the Go type that best represents the parquet node.
//
// For leaf nodes, this will be one of bool, int32, int64, deprecated.Int96,
// float32, float64, string, []byte, or [N]byte.
//
// For groups, the method returns a struct type.
//
// If the method is called on a repeated node, the method returns a slice of
// the underlying type.
//
// For optional nodes, the method returns a pointer of the underlying type.
//
// For nodes that were constructed from Go values (e.g. using SchemaOf), the
// method returns the original Go type.
GoType() reflect.Type
}
// Field instances represent fields of a parquet node, which associate a node to
// their name in their parent node.
type Field interface {
Node
// Returns the name of this field in its parent node.
Name() string
// Given a reference to the Go value matching the structure of the parent
// node, returns the Go value of the field.
Value(base reflect.Value) reflect.Value
}
// Encoded wraps the node passed as argument to use the given encoding.
//
// The function panics if it is called on a non-leaf node, or if the
// encoding does not support the node type.
func Encoded(node Node, encoding encoding.Encoding) Node {
if !node.Leaf() {
panic("cannot add encoding to a non-leaf node")
}
if encoding != nil {
kind := node.Type().Kind()
if !canEncode(encoding, kind) {
panic("cannot apply " + encoding.Encoding().String() + " to node of type " + kind.String())
}
}
return &encodedNode{
Node: node,
encoding: encoding,
}
}
type encodedNode struct {
Node
encoding encoding.Encoding
}
func (n *encodedNode) Encoding() encoding.Encoding {
return n.encoding
}
// Compressed wraps the node passed as argument to use the given compression
// codec.
//
// If the codec is nil, the node's compression is left unchanged.
//
// The function panics if it is called on a non-leaf node.
func Compressed(node Node, codec compress.Codec) Node {
if !node.Leaf() {
panic("cannot add compression codec to a non-leaf node")
}
return &compressedNode{
Node: node,
codec: codec,
}
}
type compressedNode struct {
Node
codec compress.Codec
}
func (n *compressedNode) Compression() compress.Codec {
return n.codec
}
// Optional wraps the given node to make it optional.
func Optional(node Node) Node { return &optionalNode{node} }
type optionalNode struct{ Node }
func (opt *optionalNode) Optional() bool { return true }
func (opt *optionalNode) Repeated() bool { return false }
func (opt *optionalNode) Required() bool { return false }
func (opt *optionalNode) GoType() reflect.Type { return reflect.PtrTo(opt.Node.GoType()) }
// Repeated wraps the given node to make it repeated.
func Repeated(node Node) Node { return &repeatedNode{node} }
type repeatedNode struct{ Node }
func (rep *repeatedNode) Optional() bool { return false }
func (rep *repeatedNode) Repeated() bool { return true }
func (rep *repeatedNode) Required() bool { return false }
func (rep *repeatedNode) GoType() reflect.Type { return reflect.SliceOf(rep.Node.GoType()) }
// Required wraps the given node to make it required.
func Required(node Node) Node { return &requiredNode{node} }
type requiredNode struct{ Node }
func (req *requiredNode) Optional() bool { return false }
func (req *requiredNode) Repeated() bool { return false }
func (req *requiredNode) Required() bool { return true }
func (req *requiredNode) GoType() reflect.Type { return req.Node.GoType() }
type node struct{}
// Leaf returns a leaf node of the given type.
func Leaf(typ Type) Node {
return &leafNode{typ: typ}
}
type leafNode struct{ typ Type }
func (n *leafNode) String() string { return sprint("", n) }
func (n *leafNode) Type() Type { return n.typ }
func (n *leafNode) Optional() bool { return false }
func (n *leafNode) Repeated() bool { return false }
func (n *leafNode) Required() bool { return true }
func (n *leafNode) Leaf() bool { return true }
func (n *leafNode) Fields() []Field { return nil }
func (n *leafNode) Encoding() encoding.Encoding { return nil }
func (n *leafNode) Compression() compress.Codec { return nil }
func (n *leafNode) GoType() reflect.Type { return goTypeOfLeaf(n) }
var repetitionTypes = [...]format.FieldRepetitionType{
0: format.Required,
1: format.Optional,
2: format.Repeated,
}
func fieldRepetitionTypePtrOf(node Node) *format.FieldRepetitionType {
switch {
case node.Required():
return &repetitionTypes[format.Required]
case node.Optional():
return &repetitionTypes[format.Optional]
case node.Repeated():
return &repetitionTypes[format.Repeated]
default:
return nil
}
}
func fieldRepetitionTypeOf(node Node) format.FieldRepetitionType {
switch {
case node.Optional():
return format.Optional
case node.Repeated():
return format.Repeated
default:
return format.Required
}
}
type Group map[string]Node
func (g Group) String() string { return sprint("", g) }
func (g Group) Type() Type { return groupType{} }
func (g Group) Optional() bool { return false }
func (g Group) Repeated() bool { return false }
func (g Group) Required() bool { return true }
func (g Group) Leaf() bool { return false }
func (g Group) Fields() []Field {
groupFields := make([]groupField, 0, len(g))
for name, node := range g {
groupFields = append(groupFields, groupField{
Node: node,
name: name,
})
}
sort.Slice(groupFields, func(i, j int) bool {
return groupFields[i].name < groupFields[j].name
})
fields := make([]Field, len(groupFields))
for i := range groupFields {
fields[i] = &groupFields[i]
}
return fields
}
func (g Group) Encoding() encoding.Encoding { return nil }
func (g Group) Compression() compress.Codec { return nil }
func (g Group) GoType() reflect.Type { return goTypeOfGroup(g) }
type groupField struct {
Node
name string
}
func (f *groupField) Name() string { return f.name }
func (f *groupField) Value(base reflect.Value) reflect.Value {
return base.MapIndex(reflect.ValueOf(&f.name).Elem())
}
func goTypeOf(node Node) reflect.Type {
switch {
case node.Optional():
return goTypeOfOptional(node)
case node.Repeated():
return goTypeOfRepeated(node)
default:
return goTypeOfRequired(node)
}
}
func goTypeOfOptional(node Node) reflect.Type {
return reflect.PtrTo(goTypeOfRequired(node))
}
func goTypeOfRepeated(node Node) reflect.Type {
return reflect.SliceOf(goTypeOfRequired(node))
}
func goTypeOfRequired(node Node) reflect.Type {
if node.Leaf() {
return goTypeOfLeaf(node)
} else {
return goTypeOfGroup(node)
}
}
func goTypeOfLeaf(node Node) reflect.Type {
t := node.Type()
if convertibleType, ok := t.(interface{ GoType() reflect.Type }); ok {
return convertibleType.GoType()
}
switch t.Kind() {
case Boolean:
return reflect.TypeOf(false)
case Int32:
return reflect.TypeOf(int32(0))
case Int64:
return reflect.TypeOf(int64(0))
case Int96:
return reflect.TypeOf(deprecated.Int96{})
case Float:
return reflect.TypeOf(float32(0))
case Double:
return reflect.TypeOf(float64(0))
case ByteArray:
return reflect.TypeOf(([]byte)(nil))
case FixedLenByteArray:
return reflect.ArrayOf(t.Length(), reflect.TypeOf(byte(0)))
default:
panic("BUG: parquet type returned an unsupported kind")
}
}
func goTypeOfGroup(node Node) reflect.Type {
fields := node.Fields()
structFields := make([]reflect.StructField, len(fields))
for i, field := range fields {
structFields[i].Name = exportedStructFieldName(field.Name())
structFields[i].Type = field.GoType()
// TODO: can we reconstruct a struct tag that would be valid if a value
// of this type were passed to SchemaOf?
}
return reflect.StructOf(structFields)
}
func exportedStructFieldName(name string) string {
firstRune, size := utf8.DecodeRuneInString(name)
return string([]rune{unicode.ToUpper(firstRune)}) + name[size:]
}
func isList(node Node) bool {
logicalType := node.Type().LogicalType()
return logicalType != nil && logicalType.List != nil
}
func isMap(node Node) bool {
logicalType := node.Type().LogicalType()
return logicalType != nil && logicalType.Map != nil
}
func numLeafColumnsOf(node Node) int16 {
return makeColumnIndex(numLeafColumns(node, 0))
}
func numLeafColumns(node Node, columnIndex int) int {
if node.Leaf() {
return columnIndex + 1
}
for _, field := range node.Fields() {
columnIndex = numLeafColumns(field, columnIndex)
}
return columnIndex
}
func listElementOf(node Node) Node {
if !node.Leaf() {
if list := childByName(node, "list"); list != nil {
if elem := childByName(list, "element"); elem != nil {
return elem
}
}
}
panic("node with logical type LIST is not composed of a repeated .list.element")
}
func mapKeyValueOf(node Node) Node {
if !node.Leaf() && (node.Required() || node.Optional()) {
if keyValue := childByName(node, "key_value"); keyValue != nil && !keyValue.Leaf() && keyValue.Repeated() {
k := childByName(keyValue, "key")
v := childByName(keyValue, "value")
if k != nil && v != nil && k.Required() {
return keyValue
}
}
}
panic("node with logical type MAP is not composed of a repeated .key_value group with key and value fields")
}
func encodingOf(node Node) encoding.Encoding {
encoding := node.Encoding()
// The parquet-format documentation states that the
// DELTA_LENGTH_BYTE_ARRAY is always preferred to PLAIN when
// encoding BYTE_ARRAY values. We apply it as a default if
// none were explicitly specified, which gives the application
// the opportunity to override this behavior if needed.
//
// https://github.com/apache/parquet-format/blob/master/Encodings.md#delta-length-byte-array-delta_length_byte_array--6
if node.Type().Kind() == ByteArray && encoding == nil {
encoding = &DeltaLengthByteArray
}
if encoding == nil {
encoding = &Plain
}
return encoding
}
func forEachNodeOf(name string, node Node, do func(string, Node)) {
do(name, node)
for _, f := range node.Fields() {
forEachNodeOf(f.Name(), f, do)
}
}
func childByName(node Node, name string) Node {
for _, f := range node.Fields() {
if f.Name() == name {
return f
}
}
return nil
}
func nodesAreEqual(node1, node2 Node) bool {
if node1.Leaf() {
return node2.Leaf() && leafNodesAreEqual(node1, node2)
} else {
return !node2.Leaf() && groupNodesAreEqual(node1, node2)
}
}
func typesAreEqual(node1, node2 Node) bool {
return node1.Type().Kind() == node2.Type().Kind()
}
func repetitionsAreEqual(node1, node2 Node) bool {
return node1.Optional() == node2.Optional() && node1.Repeated() == node2.Repeated()
}
func leafNodesAreEqual(node1, node2 Node) bool {
return typesAreEqual(node1, node2) && repetitionsAreEqual(node1, node2)
}
func groupNodesAreEqual(node1, node2 Node) bool {
fields1 := node1.Fields()
fields2 := node2.Fields()
if len(fields1) != len(fields2) {
return false
}
for i := range fields1 {
f1 := fields1[i]
f2 := fields2[i]
if f1.Name() != f2.Name() {
return false
}
if !nodesAreEqual(f1, f2) {
return false
}
}
return true
}