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
|
// 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 schema provides types and functions for manipulating and building parquet
// file schemas.
//
// Some of the utilities provided include building a schema using Struct Tags
// on a struct type, getting Column Paths from a node, and dealing with the
// converted and logical types for Parquet.
//
// Logical types specify ways to interpret the primitive types allowing the
// number of primitive types to be smaller and reuse efficient encodings.
// For instance a "string" is just a ByteArray column with a UTF-8 annotation
// or "String Logical Type".
//
// For more information about Logical and Converted Types, check:
// https://github.com/apache/parquet-format/blob/master/LogicalTypes.md
package schema
import (
"fmt"
"io"
"strings"
"github.com/apache/arrow/go/v6/parquet"
format "github.com/apache/arrow/go/v6/parquet/internal/gen-go/parquet"
"golang.org/x/xerrors"
)
// Schema is the container for the converted Parquet schema with a computed
// information from the schema analysis needed for file reading
//
// * Column index to Node
//
// * Max repetition / definition levels for each primitive node
//
// The ColumnDescriptor objects produced by this class can be used to assist in
// the reconstruction of fully materialized data structures from the
// repetition-definition level encoding of nested data
type Schema struct {
root Node
leaves []*Column
nodeToLeaf map[*PrimitiveNode]int
leafToBase map[int]Node
leafToIndex strIntMultimap
}
// FromParquet converts a slice of thrift Schema Elements to the correct node type
func FromParquet(elems []*format.SchemaElement) (Node, error) {
if len(elems) == 0 {
return nil, xerrors.New("parquet: empty schema (no root)")
}
if elems[0].GetNumChildren() == 0 {
if len(elems) > 1 {
return nil, xerrors.New("parquet: schema had multiple nodes but root had no children")
}
// parquet file with no columns
return GroupNodeFromThrift(elems[0], []Node{})
}
// We don't check that the root node is repeated since this is not
// consistently set by implementations
var (
pos = 0
nextNode func() (Node, error)
)
nextNode = func() (Node, error) {
if pos == len(elems) {
return nil, xerrors.New("parquet: malformed schema: not enough elements")
}
elem := elems[pos]
pos++
if elem.GetNumChildren() == 0 {
return PrimitiveNodeFromThrift(elem)
}
fields := make([]Node, 0, elem.GetNumChildren())
for i := 0; i < int(elem.GetNumChildren()); i++ {
n, err := nextNode()
if err != nil {
return nil, err
}
fields = append(fields, n)
}
return GroupNodeFromThrift(elem, fields)
}
return nextNode()
}
// Root returns the group node that is the root of this schema
func (s *Schema) Root() *GroupNode {
return s.root.(*GroupNode)
}
// NumColumns returns the number of leaf nodes that are the actual primitive
// columns in this schema.
func (s *Schema) NumColumns() int {
return len(s.leaves)
}
// Equals returns true as long as the leaf columns are equal, doesn't take
// into account the groups and only checks whether the schemas are compatible
// at the physical storage level.
func (s *Schema) Equals(rhs *Schema) bool {
if s.NumColumns() != rhs.NumColumns() {
return false
}
for idx, c := range s.leaves {
if !c.Equals(rhs.Column(idx)) {
return false
}
}
return true
}
func (s *Schema) buildTree(n Node, maxDefLvl, maxRepLvl int16, base Node) {
switch n.RepetitionType() {
case parquet.Repetitions.Repeated:
maxRepLvl++
fallthrough
case parquet.Repetitions.Optional:
maxDefLvl++
}
switch n := n.(type) {
case *GroupNode:
for _, f := range n.fields {
s.buildTree(f, maxDefLvl, maxRepLvl, base)
}
case *PrimitiveNode:
s.nodeToLeaf[n] = len(s.leaves)
s.leaves = append(s.leaves, NewColumn(n, maxDefLvl, maxRepLvl))
s.leafToBase[len(s.leaves)-1] = base
s.leafToIndex.Add(n.Path(), len(s.leaves)-1)
}
}
// Column returns the (0-indexed) column of the provided index.
func (s *Schema) Column(i int) *Column {
return s.leaves[i]
}
// ColumnIndexByName looks up the column by it's full dot separated
// node path. If there are multiple columns that match, it returns the first one.
//
// Returns -1 if not found.
func (s *Schema) ColumnIndexByName(nodePath string) int {
if search, ok := s.leafToIndex[nodePath]; ok {
return search[0]
}
return -1
}
// ColumnIndexByNode returns the index of the column represented by this node.
//
// Returns -1 if not found.
func (s *Schema) ColumnIndexByNode(n Node) int {
if search, ok := s.leafToIndex[n.Path()]; ok {
for _, idx := range search {
if n == s.Column(idx).SchemaNode() {
return idx
}
}
}
return -1
}
// ColumnRoot returns the root node of a given column if it is under a
// nested group node, providing that root group node.
func (s *Schema) ColumnRoot(i int) Node {
return s.leafToBase[i]
}
// HasRepeatedFields returns true if any node in the schema has a repeated field type.
func (s *Schema) HasRepeatedFields() bool {
return s.root.(*GroupNode).HasRepeatedFields()
}
// UpdateColumnOrders must get a slice that is the same length as the number of leaf columns
// and is used to update the schema metadata Column Orders. len(orders) must equal s.NumColumns()
func (s *Schema) UpdateColumnOrders(orders []parquet.ColumnOrder) error {
if len(orders) != s.NumColumns() {
return xerrors.New("parquet: malformed schema: not enough ColumnOrder values")
}
visitor := schemaColumnOrderUpdater{orders, 0}
s.root.Visit(&visitor)
return nil
}
// NewSchema constructs a new Schema object from a root group node.
//
// Any fields with a field-id of -1 will be given an appropriate field number based on their order.
func NewSchema(root *GroupNode) *Schema {
s := &Schema{
root,
make([]*Column, 0),
make(map[*PrimitiveNode]int),
make(map[int]Node),
make(strIntMultimap),
}
for _, f := range root.fields {
s.buildTree(f, 0, 0, f)
}
return s
}
type schemaColumnOrderUpdater struct {
colOrders []parquet.ColumnOrder
leafCount int
}
func (s *schemaColumnOrderUpdater) VisitPre(n Node) bool {
if n.Type() == Primitive {
leaf := n.(*PrimitiveNode)
leaf.ColumnOrder = s.colOrders[s.leafCount]
s.leafCount++
}
return true
}
func (s *schemaColumnOrderUpdater) VisitPost(Node) {}
type toThriftVisitor struct {
elements []*format.SchemaElement
}
func (t *toThriftVisitor) VisitPre(n Node) bool {
t.elements = append(t.elements, n.toThrift())
return true
}
func (t *toThriftVisitor) VisitPost(Node) {}
// ToThrift converts a GroupNode to a slice of SchemaElements which is used
// for thrift serialization.
func ToThrift(schema *GroupNode) []*format.SchemaElement {
t := &toThriftVisitor{make([]*format.SchemaElement, 0)}
schema.Visit(t)
return t.elements
}
type schemaPrinter struct {
w io.Writer
indent int
indentWidth int
}
func (s *schemaPrinter) VisitPre(n Node) bool {
fmt.Fprint(s.w, strings.Repeat(" ", s.indent))
if n.Type() == Group {
g := n.(*GroupNode)
fmt.Fprintf(s.w, "%s group field_id=%d %s", g.RepetitionType(), g.FieldID(), g.Name())
_, invalid := g.logicalType.(UnknownLogicalType)
_, none := g.logicalType.(NoLogicalType)
if g.logicalType != nil && !invalid && !none {
fmt.Fprintf(s.w, " (%s)", g.logicalType)
} else if g.convertedType != ConvertedTypes.None {
fmt.Fprintf(s.w, " (%s)", g.convertedType)
}
fmt.Fprintln(s.w, " {")
s.indent += s.indentWidth
} else {
p := n.(*PrimitiveNode)
fmt.Fprintf(s.w, "%s %s field_id=%d %s", p.RepetitionType(), strings.ToLower(p.PhysicalType().String()), p.FieldID(), p.Name())
_, invalid := p.logicalType.(UnknownLogicalType)
_, none := p.logicalType.(NoLogicalType)
if p.logicalType != nil && !invalid && !none {
fmt.Fprintf(s.w, " (%s)", p.logicalType)
} else if p.convertedType == ConvertedTypes.Decimal {
fmt.Fprintf(s.w, " (%s(%d,%d))", p.convertedType, p.DecimalMetadata().Precision, p.DecimalMetadata().Scale)
} else if p.convertedType != ConvertedTypes.None {
fmt.Fprintf(s.w, " (%s)", p.convertedType)
}
fmt.Fprintln(s.w, ";")
}
return true
}
func (s *schemaPrinter) VisitPost(n Node) {
if n.Type() == Group {
s.indent -= s.indentWidth
fmt.Fprint(s.w, strings.Repeat(" ", s.indent))
fmt.Fprintln(s.w, "}")
}
}
// PrintSchema writes a string representation of the tree to w using the indent
// width provided.
func PrintSchema(n Node, w io.Writer, indentWidth int) {
n.Visit(&schemaPrinter{w, 0, indentWidth})
}
type strIntMultimap map[string][]int
func (f strIntMultimap) Add(key string, val int) bool {
if _, ok := f[key]; !ok {
f[key] = []int{val}
return false
}
f[key] = append(f[key], val)
return true
}
|