forked from pingcap/br
/
parquet_parser.go
370 lines (331 loc) · 8.96 KB
/
parquet_parser.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
package mydump
import (
"bytes"
"context"
"fmt"
"io"
"reflect"
"strings"
"time"
"github.com/pingcap/errors"
"github.com/pingcap/tidb/types"
"github.com/xitongsys/parquet-go/parquet"
preader "github.com/xitongsys/parquet-go/reader"
"github.com/xitongsys/parquet-go/source"
"go.uber.org/zap"
"github.com/pingcap/br/pkg/lightning/log"
"github.com/pingcap/br/pkg/storage"
)
const (
batchReadRowSize = 32
// if a parquet if small than this threshold, parquet will load the whole file in a byte slice to
// optimize the read performance
smallParquetFileThreshold = 256 * 1024 * 1024
)
type ParquetParser struct {
Reader *preader.ParquetReader
columns []string
columnMetas []*parquet.SchemaElement
rows []interface{}
readRows int64
curStart int64
curIndex int
lastRow Row
logger log.Logger
}
// readerWrapper is a used for implement `source.ParquetFile`
type readerWrapper struct {
ReadSeekCloser
store storage.ExternalStorage
ctx context.Context
// current file path
path string
}
func (r *readerWrapper) Write(p []byte) (n int, err error) {
return 0, errors.New("unsupported operation")
}
func (r *readerWrapper) Open(name string) (source.ParquetFile, error) {
if len(name) == 0 {
name = r.path
}
reader, err := r.store.Open(r.ctx, name)
if err != nil {
return nil, errors.Trace(err)
}
return &readerWrapper{
ReadSeekCloser: reader,
store: r.store,
ctx: r.ctx,
path: name,
}, nil
}
func (r *readerWrapper) Create(name string) (source.ParquetFile, error) {
return nil, errors.New("unsupported operation")
}
// bytesReaderWrapper is a wrapper of bytes.Reader used for implement `source.ParquetFile`
type bytesReaderWrapper struct {
*bytes.Reader
rawBytes []byte
// current file path
path string
}
func (r *bytesReaderWrapper) Close() error {
return nil
}
func (r *bytesReaderWrapper) Create(name string) (source.ParquetFile, error) {
return nil, errors.New("unsupported operation")
}
func (r *bytesReaderWrapper) Write(p []byte) (n int, err error) {
return 0, errors.New("unsupported operation")
}
func (r *bytesReaderWrapper) Open(name string) (source.ParquetFile, error) {
if len(name) > 0 && name != r.path {
panic(fmt.Sprintf("Open with a different name is not supported! current: '%s', new: '%s'", r.path, name))
}
return &bytesReaderWrapper{
Reader: bytes.NewReader(r.rawBytes),
rawBytes: r.rawBytes,
path: r.path,
}, nil
}
func OpenParquetReader(
ctx context.Context,
store storage.ExternalStorage,
path string,
size int64,
) (source.ParquetFile, error) {
if size <= smallParquetFileThreshold {
fileBytes, err := store.ReadFile(ctx, path)
if err != nil {
return nil, err
}
return &bytesReaderWrapper{
Reader: bytes.NewReader(fileBytes),
rawBytes: fileBytes,
path: path,
}, nil
}
r, err := store.Open(ctx, path)
if err != nil {
return nil, err
}
return &readerWrapper{
ReadSeekCloser: r,
store: store,
ctx: ctx,
path: path,
}, nil
}
// a special func to fetch parquet file row count fast.
func ReadParquetFileRowCount(
ctx context.Context,
store storage.ExternalStorage,
r storage.ReadSeekCloser,
path string,
) (int64, error) {
wrapper := &readerWrapper{
ReadSeekCloser: r,
store: store,
ctx: ctx,
path: path,
}
var err error
res := new(preader.ParquetReader)
res.NP = 1
res.PFile = wrapper
if err = res.ReadFooter(); err != nil {
return 0, err
}
numRows := res.Footer.NumRows
if err = wrapper.Close(); err != nil {
return 0, err
}
return numRows, nil
}
func NewParquetParser(
ctx context.Context,
store storage.ExternalStorage,
r storage.ReadSeekCloser,
path string,
) (*ParquetParser, error) {
// check to avoid wrapping twice
wrapper, ok := r.(source.ParquetFile)
if !ok {
wrapper = &readerWrapper{
ReadSeekCloser: r,
store: store,
ctx: ctx,
path: path,
}
}
// FIXME: need to bench what the best value for the concurrent reader number
reader, err := preader.NewParquetReader(wrapper, nil, 2)
if err != nil {
return nil, errors.Trace(err)
}
columns := make([]string, 0, len(reader.Footer.Schema)-1)
columnMetas := make([]*parquet.SchemaElement, 0, len(reader.Footer.Schema)-1)
for _, c := range reader.SchemaHandler.SchemaElements {
if c.GetNumChildren() == 0 {
// NOTE: the SchemaElement.Name is capitalized, SchemaHandler.Infos.ExName is the raw column name
// though in this context, there is no difference between these two fields
columns = append(columns, strings.ToLower(c.Name))
columnMetas = append(columnMetas, c)
}
}
return &ParquetParser{
Reader: reader,
columns: columns,
columnMetas: columnMetas,
logger: log.L(),
}, nil
}
// Pos returns the currently row number of the parquet file
func (pp *ParquetParser) Pos() (pos int64, rowID int64) {
return pp.curStart + int64(pp.curIndex), pp.lastRow.RowID
}
func (pp *ParquetParser) SetPos(pos int64, rowID int64) error {
if pos < pp.curStart {
panic("don't support seek back yet")
}
pp.lastRow.RowID = rowID
if pos < pp.curStart+int64(len(pp.rows)) {
pp.curIndex = int(pos - pp.curStart)
pp.readRows = pos
return nil
}
if pos > pp.curStart+int64(len(pp.rows)) {
if err := pp.Reader.SkipRows(pos - pp.curStart - int64(len(pp.rows))); err != nil {
return errors.Trace(err)
}
}
pp.curStart = pos
pp.readRows = pos
pp.curIndex = 0
if len(pp.rows) > 0 {
pp.rows = pp.rows[:0]
}
return nil
}
func (pp *ParquetParser) Close() error {
pp.Reader.ReadStop()
return pp.Reader.PFile.Close()
}
func (pp *ParquetParser) ReadRow() error {
pp.lastRow.RowID++
if pp.curIndex >= len(pp.rows) {
if pp.readRows >= pp.Reader.GetNumRows() {
return io.EOF
}
count := batchReadRowSize
if pp.Reader.GetNumRows()-pp.readRows < int64(count) {
count = int(pp.Reader.GetNumRows() - pp.readRows)
}
var err error
pp.rows, err = pp.Reader.ReadByNumber(count)
if err != nil {
return errors.Trace(err)
}
pp.curStart = pp.readRows
pp.readRows += int64(len(pp.rows))
pp.curIndex = 0
}
row := pp.rows[pp.curIndex]
pp.curIndex++
v := reflect.ValueOf(row)
length := v.NumField()
if cap(pp.lastRow.Row) < length {
pp.lastRow.Row = make([]types.Datum, length)
} else {
pp.lastRow.Row = pp.lastRow.Row[:length]
}
for i := 0; i < length; i++ {
setDatumValue(&pp.lastRow.Row[i], v.Field(i), pp.columnMetas[i])
}
return nil
}
// convert a parquet value to Datum
//
// See: https://github.com/apache/parquet-format/blob/master/LogicalTypes.md
func setDatumValue(d *types.Datum, v reflect.Value, meta *parquet.SchemaElement) {
switch v.Kind() {
case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
d.SetUint64(v.Uint())
case reflect.Int8, reflect.Int16:
d.SetInt64(v.Int())
case reflect.Int32, reflect.Int64:
setDatumByInt(d, v.Int(), meta)
case reflect.String:
d.SetString(v.String(), "")
case reflect.Float32, reflect.Float64:
d.SetFloat64(v.Float())
case reflect.Ptr:
if v.IsNil() {
d.SetNull()
} else {
setDatumValue(d, v.Elem(), meta)
}
default:
log.L().Fatal("unknown value", zap.Stringer("kind", v.Kind()),
zap.String("type", v.Type().Name()), zap.Reflect("value", v.Interface()))
}
}
// when the value type is int32/int64, convert to value to target logical type in tidb
func setDatumByInt(d *types.Datum, v int64, meta *parquet.SchemaElement) {
if meta.ConvertedType == nil {
d.SetInt64(v)
return
}
switch *meta.ConvertedType {
// decimal
case parquet.ConvertedType_DECIMAL:
minLen := *meta.Scale + 1
if v < 0 {
minLen++
}
val := fmt.Sprintf("%0*d", minLen, v)
dotIndex := len(val) - int(*meta.Scale)
d.SetString(val[:dotIndex]+"."+val[dotIndex:], "")
case parquet.ConvertedType_DATE:
dateStr := time.Unix(v*86400, 0).Format("2006-01-02")
d.SetString(dateStr, "")
// convert all timestamp types (datetime/timestamp) to string
case parquet.ConvertedType_TIMESTAMP_MICROS:
dateStr := time.Unix(v/1e6, (v%1e6)*1e3).Format("2006-01-02 15:04:05.999")
d.SetString(dateStr, "")
case parquet.ConvertedType_TIMESTAMP_MILLIS:
dateStr := time.Unix(v/1e3, (v%1e3)*1e6).Format("2006-01-02 15:04:05.999")
d.SetString(dateStr, "")
// covert time types to string
case parquet.ConvertedType_TIME_MILLIS, parquet.ConvertedType_TIME_MICROS:
if *meta.ConvertedType == parquet.ConvertedType_TIME_MICROS {
v /= 1e3
}
millis := v % 1e3
v /= 1e3
sec := v % 60
v /= 60
min := v % 60
v /= 60
d.SetString(fmt.Sprintf("%d:%d:%d.%3d", v, min, sec, millis), "")
default:
d.SetInt64(v)
}
}
func (pp *ParquetParser) LastRow() Row {
return pp.lastRow
}
func (pp *ParquetParser) RecycleRow(row Row) {
}
// Columns returns the _lower-case_ column names corresponding to values in
// the LastRow.
func (pp *ParquetParser) Columns() []string {
return pp.columns
}
// SetColumns set restored column names to parser
func (pp *ParquetParser) SetColumns(cols []string) {
// just do nothing
}
func (pp *ParquetParser) SetLogger(l log.Logger) {
pp.logger = l
}