forked from fraugster/parquet-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
chunk_writer.go
332 lines (288 loc) · 9.52 KB
/
chunk_writer.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
package goparquet
import (
"bytes"
"context"
"fmt"
"math"
"sort"
"github.com/infosum/parquet-go/parquet"
)
func getBooleanValuesEncoder(pageEncoding parquet.Encoding) (valuesEncoder, error) {
switch pageEncoding {
case parquet.Encoding_PLAIN:
return &booleanPlainEncoder{}, nil
case parquet.Encoding_RLE:
return &booleanRLEEncoder{}, nil
default:
return nil, fmt.Errorf("unsupported encoding %s for boolean", pageEncoding)
}
}
func getByteArrayValuesEncoder(pageEncoding parquet.Encoding, dictValues []interface{}) (valuesEncoder, error) {
switch pageEncoding {
case parquet.Encoding_PLAIN:
return &byteArrayPlainEncoder{}, nil
case parquet.Encoding_DELTA_LENGTH_BYTE_ARRAY:
return &byteArrayDeltaLengthEncoder{}, nil
case parquet.Encoding_DELTA_BYTE_ARRAY:
return &byteArrayDeltaEncoder{}, nil
default:
return nil, fmt.Errorf("unsupported encoding %s for binary", pageEncoding)
}
}
func getFixedLenByteArrayValuesEncoder(pageEncoding parquet.Encoding, len int, dictValues []interface{}) (valuesEncoder, error) {
switch pageEncoding {
case parquet.Encoding_PLAIN:
return &byteArrayPlainEncoder{length: len}, nil
case parquet.Encoding_DELTA_BYTE_ARRAY:
return &byteArrayDeltaEncoder{}, nil
default:
return nil, fmt.Errorf("unsupported encoding %s for fixed_len_byte_array(%d)", pageEncoding, len)
}
}
func getInt32ValuesEncoder(pageEncoding parquet.Encoding, typ *parquet.SchemaElement, dictValues []interface{}) (valuesEncoder, error) {
switch pageEncoding {
case parquet.Encoding_PLAIN:
return &int32PlainEncoder{}, nil
case parquet.Encoding_DELTA_BINARY_PACKED:
return &int32DeltaBPEncoder{
deltaBitPackEncoder32: deltaBitPackEncoder32{
blockSize: 128,
miniBlockCount: 4,
},
}, nil
default:
return nil, fmt.Errorf("unsupported encoding %s for int32", pageEncoding)
}
}
func getInt64ValuesEncoder(pageEncoding parquet.Encoding, typ *parquet.SchemaElement, dictValues []interface{}) (valuesEncoder, error) {
switch pageEncoding {
case parquet.Encoding_PLAIN:
return &int64PlainEncoder{}, nil
case parquet.Encoding_DELTA_BINARY_PACKED:
return &int64DeltaBPEncoder{
deltaBitPackEncoder64: deltaBitPackEncoder64{
blockSize: 128,
miniBlockCount: 4,
},
}, nil
default:
return nil, fmt.Errorf("unsupported encoding %s for int64", pageEncoding)
}
}
func getValuesEncoder(pageEncoding parquet.Encoding, typ *parquet.SchemaElement, dictValues []interface{}) (valuesEncoder, error) {
// Change the deprecated value
if pageEncoding == parquet.Encoding_PLAIN_DICTIONARY {
pageEncoding = parquet.Encoding_RLE_DICTIONARY
}
switch *typ.Type {
case parquet.Type_BOOLEAN:
return getBooleanValuesEncoder(pageEncoding)
case parquet.Type_BYTE_ARRAY:
return getByteArrayValuesEncoder(pageEncoding, dictValues)
case parquet.Type_FIXED_LEN_BYTE_ARRAY:
if typ.TypeLength == nil {
return nil, fmt.Errorf("type %s with nil type len", typ.Type)
}
return getFixedLenByteArrayValuesEncoder(pageEncoding, int(*typ.TypeLength), dictValues)
case parquet.Type_FLOAT:
switch pageEncoding {
case parquet.Encoding_PLAIN:
return &floatPlainEncoder{}, nil
}
case parquet.Type_DOUBLE:
switch pageEncoding {
case parquet.Encoding_PLAIN:
return &doublePlainEncoder{}, nil
}
case parquet.Type_INT32:
return getInt32ValuesEncoder(pageEncoding, typ, dictValues)
case parquet.Type_INT64:
return getInt64ValuesEncoder(pageEncoding, typ, dictValues)
case parquet.Type_INT96:
switch pageEncoding {
case parquet.Encoding_PLAIN:
return &int96PlainEncoder{}, nil
}
default:
return nil, fmt.Errorf("unsupported type: %s", typ.Type)
}
return nil, fmt.Errorf("unsupported encoding %s for %s type", pageEncoding, typ.Type)
}
func getDictValuesEncoder(typ *parquet.SchemaElement) (valuesEncoder, error) {
switch *typ.Type {
case parquet.Type_BYTE_ARRAY:
return &byteArrayPlainEncoder{}, nil
case parquet.Type_FIXED_LEN_BYTE_ARRAY:
if typ.TypeLength == nil {
return nil, fmt.Errorf("type %s with nil type len", typ)
}
return &byteArrayPlainEncoder{length: int(*typ.TypeLength)}, nil
case parquet.Type_FLOAT:
return &floatPlainEncoder{}, nil
case parquet.Type_DOUBLE:
return &doublePlainEncoder{}, nil
case parquet.Type_INT32:
return &int32PlainEncoder{}, nil
case parquet.Type_INT64:
return &int64PlainEncoder{}, nil
case parquet.Type_INT96:
return &int96PlainEncoder{}, nil
}
return nil, fmt.Errorf("type %s is not supported for dict value encoder", typ)
}
func writeChunk(ctx context.Context, w writePos, sch *schema, col *Column, codec parquet.CompressionCodec, pageFn newDataPageFunc, kvMetaData map[string]string) (*parquet.ColumnChunk, error) {
pos := w.Pos() // Save the position before writing data
chunkOffset := pos
var (
dictPageOffset *int64
// NOTE :
// This is documentation on these two field :
// - TotalUncompressedSize: total byte size of all uncompressed pages in this column chunk (including the headers) *
// - TotalCompressedSize: total byte size of all compressed pages in this column chunk (including the headers) *
// the including header part is confusing. for uncompressed size, we can use the position, but for the compressed
// the only value we have doesn't contain the header
totalComp int64
totalUnComp int64
)
// flush final data page before writing dictionary page (if applicable) and all data pages.
if err := col.data.flushPage(sch, true); err != nil {
return nil, err
}
dictValues := []interface{}{}
indices := map[interface{}]int32{}
useDict := true
if *col.Type() == parquet.Type_BOOLEAN { // never ever use dictionary encoding on booleans.
useDict = false
}
if !col.data.useDictionary() {
useDict = false
}
if useDict {
outerLoop:
for _, page := range col.data.dataPages {
if page.stats.DistinctCount != nil && *page.stats.DistinctCount > math.MaxInt16 {
useDict = false
break outerLoop
}
for _, v := range page.values {
k := mapKey(v)
if idx, ok := indices[k]; !ok {
idx = int32(len(dictValues))
indices[k] = idx
dictValues = append(dictValues, v)
page.indexList = append(page.indexList, idx)
if len(dictValues) > math.MaxInt16 {
useDict = false
break outerLoop
}
} else {
page.indexList = append(page.indexList, idx)
}
}
}
}
if useDict {
tmp := pos // make a copy, do not use the pos here
dictPageOffset = &tmp
dict := &dictPageWriter{}
if err := dict.init(sch, col, codec, dictValues); err != nil {
return nil, err
}
compSize, unCompSize, err := dict.write(ctx, w)
if err != nil {
return nil, err
}
totalComp = w.Pos() - pos
// Header size plus the rLevel and dLevel size
headerSize := totalComp - int64(compSize)
totalUnComp = int64(unCompSize) + headerSize
pos = w.Pos() // Move position for data pos
}
var (
compSize, unCompSize int
numValues, nullValues int64
)
for _, page := range col.data.dataPages {
pw := pageFn(useDict, dictValues, page, sch.enableCRC)
if err := pw.init(col, codec); err != nil {
return nil, err
}
var buf bytes.Buffer
compressed, uncompressed, err := pw.write(ctx, &buf)
if err != nil {
return nil, err
}
compSize += compressed
unCompSize += uncompressed
numValues += page.numValues
nullValues += page.nullValues
if _, err := w.Write(buf.Bytes()); err != nil {
return nil, err
}
}
col.data.dataPages = nil
totalComp += w.Pos() - pos
// Header size plus the rLevel and dLevel size
headerSize := totalComp - int64(compSize)
totalUnComp += int64(unCompSize) + headerSize
encodings := make([]parquet.Encoding, 0, 3)
encodings = append(encodings,
parquet.Encoding_RLE,
col.data.encoding(),
)
if useDict {
encodings[1] = parquet.Encoding_PLAIN // In dictionary we use PLAIN for the data, not the column encoding
encodings = append(encodings, parquet.Encoding_RLE_DICTIONARY)
}
keyValueMetaData := make([]*parquet.KeyValue, 0, len(kvMetaData))
for k, v := range kvMetaData {
value := v
keyValueMetaData = append(keyValueMetaData, &parquet.KeyValue{Key: k, Value: &value})
}
sort.Slice(keyValueMetaData, func(i, j int) bool {
return keyValueMetaData[i].Key < keyValueMetaData[j].Key
})
distinctCount := int64(len(dictValues))
stats := &parquet.Statistics{
MinValue: col.data.getStats().minValue(),
MaxValue: col.data.getStats().maxValue(),
NullCount: &nullValues,
DistinctCount: &distinctCount,
}
ch := &parquet.ColumnChunk{
FilePath: nil, // No support for external
FileOffset: chunkOffset,
MetaData: &parquet.ColumnMetaData{
Type: col.data.parquetType(),
Encodings: encodings,
PathInSchema: col.path,
Codec: codec,
NumValues: numValues + nullValues,
TotalUncompressedSize: totalUnComp,
TotalCompressedSize: totalComp,
KeyValueMetadata: keyValueMetaData,
DataPageOffset: pos,
IndexPageOffset: nil,
DictionaryPageOffset: dictPageOffset,
Statistics: stats,
EncodingStats: nil,
},
OffsetIndexOffset: nil,
OffsetIndexLength: nil,
ColumnIndexOffset: nil,
ColumnIndexLength: nil,
}
return ch, nil
}
func writeRowGroup(ctx context.Context, w writePos, sch *schema, codec parquet.CompressionCodec, pageFn newDataPageFunc, h *flushRowGroupOptionHandle) ([]*parquet.ColumnChunk, error) {
dataCols := sch.Columns()
var res = make([]*parquet.ColumnChunk, 0, len(dataCols))
for _, ci := range dataCols {
ch, err := writeChunk(ctx, w, sch, ci, codec, pageFn, h.getMetaData(ci.Path()))
if err != nil {
return nil, err
}
res = append(res, ch)
}
return res, nil
}