/
dict.go
398 lines (339 loc) · 9.31 KB
/
dict.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
// 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 dictutils
import (
"errors"
"fmt"
"hash/maphash"
"github.com/apache/arrow/go/v8/arrow"
"github.com/apache/arrow/go/v8/arrow/array"
"github.com/apache/arrow/go/v8/arrow/memory"
)
type Kind int8
const (
KindNew Kind = iota
KindDelta
KindReplacement
)
type FieldPos struct {
parent *FieldPos
index, depth int32
}
func NewFieldPos() FieldPos { return FieldPos{index: -1} }
func (f *FieldPos) Child(index int32) FieldPos {
return FieldPos{parent: f, index: index, depth: f.depth + 1}
}
func (f *FieldPos) Path() []int32 {
path := make([]int32, f.depth)
cur := f
for i := f.depth - 1; i >= 0; i-- {
path[i] = int32(cur.index)
cur = cur.parent
}
return path
}
type Mapper struct {
pathToID map[uint64]int64
hasher maphash.Hash
}
func (d *Mapper) NumDicts() int {
unique := make(map[int64]bool)
for _, id := range d.pathToID {
unique[id] = true
}
return len(unique)
}
func (d *Mapper) AddField(id int64, fieldPath []int32) error {
d.hasher.Write(arrow.Int32Traits.CastToBytes(fieldPath))
defer d.hasher.Reset()
sum := d.hasher.Sum64()
if _, ok := d.pathToID[sum]; ok {
return errors.New("field already mapped to id")
}
d.pathToID[sum] = id
return nil
}
func (d *Mapper) GetFieldID(fieldPath []int32) (int64, error) {
d.hasher.Write(arrow.Int32Traits.CastToBytes(fieldPath))
defer d.hasher.Reset()
id, ok := d.pathToID[d.hasher.Sum64()]
if !ok {
return -1, errors.New("arrow/ipc: dictionary field not found")
}
return id, nil
}
func (d *Mapper) NumFields() int {
return len(d.pathToID)
}
func (d *Mapper) InsertPath(pos FieldPos) {
id := len(d.pathToID)
d.hasher.Write(arrow.Int32Traits.CastToBytes(pos.Path()))
d.pathToID[d.hasher.Sum64()] = int64(id)
d.hasher.Reset()
}
func (d *Mapper) ImportField(pos FieldPos, field *arrow.Field) {
dt := field.Type
if dt.ID() == arrow.EXTENSION {
dt = dt.(arrow.ExtensionType).StorageType()
}
if dt.ID() == arrow.DICTIONARY {
d.InsertPath(pos)
// import nested dicts
if nested, ok := dt.(*arrow.DictionaryType).ValueType.(arrow.NestedType); ok {
d.ImportFields(pos, nested.Fields())
}
return
}
if nested, ok := dt.(arrow.NestedType); ok {
d.ImportFields(pos, nested.Fields())
}
}
func (d *Mapper) ImportFields(pos FieldPos, fields []arrow.Field) {
for i := range fields {
d.ImportField(pos.Child(int32(i)), &fields[i])
}
}
func (d *Mapper) ImportSchema(schema *arrow.Schema) {
d.pathToID = make(map[uint64]int64)
d.ImportFields(NewFieldPos(), schema.Fields())
}
func hasUnresolvedNestedDict(data arrow.ArrayData) bool {
d := data.(*array.Data)
if d.DataType().ID() == arrow.DICTIONARY {
if d.Dictionary().(*array.Data) == nil {
return true
}
if hasUnresolvedNestedDict(d.Dictionary()) {
return true
}
}
for _, c := range d.Children() {
if hasUnresolvedNestedDict(c) {
return true
}
}
return false
}
type dictpair struct {
ID int64
Dict arrow.Array
}
type dictCollector struct {
dictionaries []dictpair
mapper *Mapper
}
func (d *dictCollector) visitChildren(pos FieldPos, typ arrow.DataType, arr arrow.Array) error {
for i, c := range arr.Data().Children() {
child := array.MakeFromData(c)
defer child.Release()
if err := d.visit(pos.Child(int32(i)), child); err != nil {
return err
}
}
return nil
}
func (d *dictCollector) visit(pos FieldPos, arr arrow.Array) error {
dt := arr.DataType()
if dt.ID() == arrow.EXTENSION {
dt = dt.(arrow.ExtensionType).StorageType()
arr = arr.(array.ExtensionArray).Storage()
}
if dt.ID() == arrow.DICTIONARY {
dictarr := arr.(*array.Dictionary)
dict := dictarr.Dictionary()
// traverse the dictionary to first gather any nested dictionaries
// so they appear in the output before their respective parents
dictType := dt.(*arrow.DictionaryType)
d.visitChildren(pos, dictType.ValueType, dict)
id, err := d.mapper.GetFieldID(pos.Path())
if err != nil {
return err
}
dict.Retain()
d.dictionaries = append(d.dictionaries, dictpair{ID: id, Dict: dict})
return nil
}
return d.visitChildren(pos, dt, arr)
}
func (d *dictCollector) collect(batch arrow.Record) error {
var (
pos = NewFieldPos()
schema = batch.Schema()
)
d.dictionaries = make([]dictpair, 0, d.mapper.NumFields())
for i := range schema.Fields() {
if err := d.visit(pos.Child(int32(i)), batch.Column(i)); err != nil {
return err
}
}
return nil
}
type dictMap map[int64][]arrow.ArrayData
type dictTypeMap map[int64]arrow.DataType
type Memo struct {
Mapper Mapper
dict2id map[arrow.ArrayData]int64
id2type dictTypeMap
id2dict dictMap // map of dictionary ID to dictionary array
}
func NewMemo() Memo {
return Memo{
dict2id: make(map[arrow.ArrayData]int64),
id2dict: make(dictMap),
id2type: make(dictTypeMap),
Mapper: Mapper{
pathToID: make(map[uint64]int64),
},
}
}
func (memo *Memo) Len() int { return len(memo.id2dict) }
func (memo *Memo) Clear() {
for id, v := range memo.id2dict {
delete(memo.id2dict, id)
for _, d := range v {
delete(memo.dict2id, d)
d.Release()
}
}
}
func (memo *Memo) reify(id int64, mem memory.Allocator) (arrow.ArrayData, error) {
v, ok := memo.id2dict[id]
if !ok {
return nil, fmt.Errorf("arrow/ipc: no dictionaries found for id=%d", id)
}
if len(v) == 1 {
return v[0], nil
}
// there are deltas we need to concatenate them with the first dictionary
toCombine := make([]arrow.Array, 0, len(v))
// NOTE: at this point the dictionary data may not be trusted. it needs to
// be validated as concatenation can crash on invalid or corrupted data.
for _, data := range v {
if hasUnresolvedNestedDict(data) {
return nil, fmt.Errorf("arrow/ipc: delta dict with unresolved nested dictionary not implemented")
}
arr := array.MakeFromData(data)
defer arr.Release()
toCombine = append(toCombine, arr)
defer data.Release()
}
combined, err := array.Concatenate(toCombine, mem)
if err != nil {
return nil, err
}
defer combined.Release()
combined.Data().Retain()
memo.id2dict[id] = []arrow.ArrayData{combined.Data()}
return combined.Data(), nil
}
func (memo *Memo) Dict(id int64, mem memory.Allocator) (arrow.ArrayData, error) {
return memo.reify(id, mem)
}
func (memo *Memo) AddType(id int64, typ arrow.DataType) error {
if existing, dup := memo.id2type[id]; dup && !arrow.TypeEqual(existing, typ) {
return fmt.Errorf("arrow/ipc: conflicting dictionary types for id %d", id)
}
memo.id2type[id] = typ
return nil
}
func (memo *Memo) Type(id int64) (arrow.DataType, bool) {
t, ok := memo.id2type[id]
return t, ok
}
// func (memo *dictMemo) ID(v arrow.Array) int64 {
// id, ok := memo.dict2id[v]
// if ok {
// return id
// }
// v.Retain()
// id = int64(len(memo.dict2id))
// memo.dict2id[v] = id
// memo.id2dict[id] = v
// return id
// }
func (memo Memo) HasDict(v arrow.ArrayData) bool {
_, ok := memo.dict2id[v]
return ok
}
func (memo Memo) HasID(id int64) bool {
_, ok := memo.id2dict[id]
return ok
}
func (memo *Memo) Add(id int64, v arrow.ArrayData) {
if _, dup := memo.id2dict[id]; dup {
panic(fmt.Errorf("arrow/ipc: duplicate id=%d", id))
}
v.Retain()
memo.id2dict[id] = []arrow.ArrayData{v}
memo.dict2id[v] = id
}
func (memo *Memo) AddDelta(id int64, v arrow.ArrayData) {
d, ok := memo.id2dict[id]
if !ok {
panic(fmt.Errorf("arrow/ipc: adding delta to non-existing id=%d", id))
}
v.Retain()
memo.id2dict[id] = append(d, v)
}
func (memo *Memo) AddOrReplace(id int64, v arrow.ArrayData) bool {
d, ok := memo.id2dict[id]
if ok {
d = append(d, v)
} else {
d = []arrow.ArrayData{v}
}
v.Retain()
memo.id2dict[id] = d
return !ok
}
func CollectDictionaries(batch arrow.Record, mapper *Mapper) (out []dictpair, err error) {
collector := dictCollector{mapper: mapper}
err = collector.collect(batch)
out = collector.dictionaries
return
}
func ResolveFieldDict(memo *Memo, data arrow.ArrayData, pos FieldPos, mem memory.Allocator) error {
typ := data.DataType()
if typ.ID() == arrow.EXTENSION {
typ = typ.(arrow.ExtensionType).StorageType()
}
if typ.ID() == arrow.DICTIONARY {
id, err := memo.Mapper.GetFieldID(pos.Path())
if err != nil {
return err
}
dictData, err := memo.Dict(id, mem)
if err != nil {
return err
}
data.(*array.Data).SetDictionary(dictData)
if err := ResolveFieldDict(memo, dictData, pos, mem); err != nil {
return err
}
}
return ResolveDictionaries(memo, data.Children(), pos, mem)
}
func ResolveDictionaries(memo *Memo, cols []arrow.ArrayData, parentPos FieldPos, mem memory.Allocator) error {
for i, c := range cols {
if c == nil {
continue
}
if err := ResolveFieldDict(memo, c, parentPos.Child(int32(i)), mem); err != nil {
return err
}
}
return nil
}