This is an automated email from the ASF dual-hosted git repository.
zeroshade pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/arrow-go.git
The following commit(s) were added to refs/heads/main by this push:
new 38527b3c fix(arrow/avro): read nested, nullable, and logical types;
reject recursive schemas (#1692)
38527b3c is described below
commit 38527b3c9d3947f7ee6155211f064b42e4477e3b
Author: Travis Bischel <[email protected]>
AuthorDate: Fri Nov 27 10:07:20 2026 -0700
fix(arrow/avro): read nested, nullable, and logical types; reject recursive
schemas (#1692)
Fixes for the OCF reader, most of them for reads that broke when
arrow/avro switched from hamba/avro to twmb/avro in #830:
* The loader looked up each value by a path of keys written for the
shapes hamba/avro decoded. With twmb/avro, a ["null", record] field and
a record two or more levels inside an array or map read as nulls, values
after a null record shifted, a record field named "value" or "item" lost
its nested fields, an array of maps panicked and crashed the process,
and maps of maps, arrays of arrays, and maps of arrays returned errors
or dropped values. The loader is now recursive appenders: each list,
map, and struct builder appends its own items, keys and values, or
fields. All of these read correctly.
* A record that contains itself, such as a Node with a ["null","Node"]
field, recursed until the Go stack overflowed, a fatal error that
recover cannot catch, including for a schema read from an untrusted file
header. The conversion now returns an error that names the record. An
Arrow schema cannot describe a recursive type, so such a file still
cannot be read; reading it would need the conversion to cut the
recursion at a fixed depth or to store the recursive field as binary or
JSON, which this does not do.
* A field of Avro type "null" crashed the process. It now reads as an
Arrow null column.
* An unknown logical type, or one on an underlying type the spec does
not allow, such as time-millis on a long or uuid on a fixed(4), failed
the read. Such a field now reads as its underlying type, as the spec
says and as twmb/avro decodes it.
* A field-level logicalType, as in
{"name":"f","type":"long","logicalType":"timestamp-millis"}, which
Confluent's code generator and most Debezium sources write, failed the
read, because twmb/avro lifts it onto the type and the conversion did
not. The conversion now applies it the same way.
* A big-decimal field (Avro 1.12) failed the whole file with "field with
nil DataType". It now reads as a string column of each value's exact
decimal text. A value written as 1.50 reads as "1.5", because twmb/avro
does not keep the scale each value was written with.
* A record with a dotted name, such as "x.A", could not be referenced by
its short name from inside its namespace.
Existing readers may notice:
* uuid on bytes reads as a Binary column instead of a UUID column, which
failed for any value that was not 16 bytes.
* A field-level uuid on a string reads as a UUID column instead of a
string column.
* A WithSchemaEdit that gives a field a type its data does not have
returns an error. Before, an edit to an array wrapped each value in a
one-element list, an edit to a record read nulls, and an edit to a map
crashed the process or returned no rows.
* Fields that read as null before, such as ["null", record] fields, read
their values.
Each fix has rows in TestOCFReaderValues or the schema tests that fail
without it.
---
arrow/avro/reader_test.go | 166 +++++++++++-----
arrow/avro/reader_types.go | 480 ++++++++++-----------------------------------
arrow/avro/schema.go | 89 ++++++++-
arrow/avro/schema_test.go | 53 +++--
4 files changed, 348 insertions(+), 440 deletions(-)
diff --git a/arrow/avro/reader_test.go b/arrow/avro/reader_test.go
index d3c25fdf..35a69326 100644
--- a/arrow/avro/reader_test.go
+++ b/arrow/avro/reader_test.go
@@ -21,6 +21,7 @@ import (
"encoding/json"
"errors"
"fmt"
+ "math/big"
"os"
"path/filepath"
"testing"
@@ -143,7 +144,7 @@ func TestReader(t *testing.T) {
},
{
Name: "uuidField",
- Type: arrow.BinaryTypes.String,
+ Type: extensions.NewUUIDType(),
},
{
Name: "fixedUuidField",
@@ -251,53 +252,127 @@ func TestReader(t *testing.T) {
}
}
-// A nullable logical timestamp must decode to a value rather than a null: the
-// union branch carries the logical type, so the reader has to honour it on the
-// branch and not just on a bare long.
-
-// TestOCFReaderBytesValues exercises avro `bytes` fields, both plain and as a
-// ["null","bytes"] union.
-func TestOCFReaderBytesValues(t *testing.T) {
- schema := `{
- "type": "record",
- "name": "rec",
- "fields": [
- {"name": "plain", "type": "bytes"},
- {"name": "nullable", "type": ["null", "bytes"]}
- ]
- }`
+// TestOCFReaderValues writes one row per entry in rows to a record whose only
+// field, f, has the Avro type typ, and compares the column that NewOCFReader
+// reads back with want as JSON. Field-level attributes of f, such as a
+// field-level logicalType, follow the type in typ.
+func TestOCFReaderValues(t *testing.T) {
+ const rec =
`{"type":"record","name":"R","fields":[{"name":"x","type":"int"}]}`
+ const listAndMap =
`{"type":"record","name":"P","fields":[{"name":"l","type":{"type":"array","items":"int"}},{"name":"m","type":{"type":"map","values":"int"}}]}`
payload := []byte{0x00, 0x01, 0xfe, 0xff}
+ x := func(v int32) map[string]any { return map[string]any{"x": v} }
+ lm := map[string]any{"l": []any{int32(1)}, "m": map[string]any{"a":
int32(2)}}
+ ts := time.UnixMilli(1_700_000_000_123).UTC()
+ tsMicros := time.UnixMicro(1_700_000_000_123_456).UTC()
+ const bigDecimal = `{"type":"bytes","logicalType":"big-decimal"}`
+ manyDigits, _ :=
new(big.Rat).SetString("12345678901234567890.0000000001")
+ tests := []struct {
+ name string
+ typ string
+ rows []any
+ want string
+ }{
+ {"null", `"null"`, []any{nil, nil}, `[null,null]`},
+ {"bytes", `"bytes"`, []any{payload, []byte{}},
`["AAH+/w==",""]`},
+ {"nullable bytes", `["null","bytes"]`,
[]any{map[string]any{"bytes": payload}, nil}, `["AAH+/w==",null]`},
+ {"nullable record", `["null",` + rec + `]`, []any{x(7), nil,
x(8)}, `[{"x":7},null,{"x":8}]`},
+ {"array of nullable records with a null",
`{"type":"array","items":["null",` + rec + `]}`, []any{[]any{x(7), nil, x(8)}},
`[[{"x":7},null,{"x":8}]]`},
+ {"null record of a record",
`["null",{"type":"record","name":"P","fields":[{"name":"r","type":` + rec +
`}]}]`,
+ []any{nil, map[string]any{"r": x(9)}},
`[null,{"r":{"x":9}}]`},
+ {"null record of an array and a map", `["null",` + listAndMap +
`]`,
+ []any{nil, lm},
`[null,{"l":[1],"m":[{"key":"a","value":2}]}]`},
+ {"array of nullable records of an array and a map with a null",
`{"type":"array","items":["null",` + listAndMap + `]}`,
+ []any{[]any{nil, lm}},
`[[null,{"l":[1],"m":[{"key":"a","value":2}]}]]`},
+ {"map of nullable records with a null",
`{"type":"map","values":["null",` + rec + `]}`,
+ []any{map[string]any{"a": nil}, map[string]any{"b":
x(8)}}, `[[{"key":"a","value":null}],[{"key":"b","value":{"x":8}}]]`},
+ {"nullable record in a nullable record",
`["null",{"type":"record","name":"P","fields":[{"name":"r","type":["null",` +
rec + `]}]}]`,
+ []any{map[string]any{"r": x(5)}, map[string]any{"r":
nil}}, `[{"r":{"x":5}},{"r":null}]`},
+ {"record in an array of records",
`{"type":"array","items":{"type":"record","name":"P","fields":[{"name":"r","type":`
+ rec + `}]}}`,
+ []any{[]any{map[string]any{"r": x(9)}}},
`[[{"r":{"x":9}}]]`},
+ {"record in a map of records",
`{"type":"map","values":{"type":"record","name":"P","fields":[{"name":"r","type":`
+ rec + `}]}}`,
+ []any{map[string]any{"a": map[string]any{"r": x(9)}}},
`[[{"key":"a","value":{"r":{"x":9}}}]]`},
+ {"record field named value",
`{"type":"record","name":"P","fields":[{"name":"value","type":` + rec + `}]}`,
+ []any{map[string]any{"value": x(9)}},
`[{"value":{"x":9}}]`},
+ {"record field named item in an array",
`{"type":"array","items":{"type":"record","name":"P","fields":[{"name":"item","type":`
+ rec + `}]}}`,
+ []any{[]any{map[string]any{"item": x(9)}}},
`[[{"item":{"x":9}}]]`},
+ {"array of maps",
`{"type":"array","items":{"type":"map","values":"long"}}`,
+ []any{[]any{map[string]any{"a": int64(1)},
map[string]any{"b": int64(2)}}},
`[[[{"key":"a","value":1}],[{"key":"b","value":2}]]]`},
+ {"map of maps",
`{"type":"map","values":{"type":"map","values":"long"}}`,
+ []any{map[string]any{"c": map[string]any{"d":
int64(3)}}}, `[[{"key":"c","value":[{"key":"d","value":3}]}]]`},
+ {"array of arrays of maps",
`{"type":"array","items":{"type":"array","items":{"type":"map","values":"long"}}}`,
+ []any{[]any{[]any{map[string]any{"e": int64(4)}},
[]any{}}}, `[[[[{"key":"e","value":4}]],[]]]`},
+ {"map of arrays",
`{"type":"map","values":{"type":"array","items":"int"}}`,
+ []any{map[string]any{"a": []any{int32(1), int32(2)}},
map[string]any{"b": []any{}}},
`[[{"key":"a","value":[1,2]}],[{"key":"b","value":[]}]]`},
+ {"map of arrays of records",
`{"type":"map","values":{"type":"array","items":` + rec + `}}`,
+ []any{map[string]any{"a": []any{x(1), x(2)}}},
`[[{"key":"a","value":[{"x":1},{"x":2}]}]]`},
+ {"map of arrays of maps",
`{"type":"map","values":{"type":"array","items":{"type":"map","values":"int"}}}`,
+ []any{map[string]any{"a": []any{map[string]any{"b":
int32(1)}}}}, `[[{"key":"a","value":[[{"key":"b","value":1}]]}]]`},
+ {"map of arrays of arrays",
`{"type":"map","values":{"type":"array","items":{"type":"array","items":"int"}}}`,
+ []any{map[string]any{"a": []any{[]any{int32(1)},
[]any{}}}}, `[[{"key":"a","value":[[1],[]]}]]`},
+ {"unknown logical type",
`{"type":"string","logicalType":"foo"}`, []any{"s"}, `["s"]`},
+ {"decimal on int",
`{"type":"int","logicalType":"decimal","precision":4,"scale":2}`,
[]any{int32(5)}, `[5]`},
+ {"uuid on bytes", `{"type":"bytes","logicalType":"uuid"}`,
[]any{[]byte("0123456789abcdef")}, `["MDEyMzQ1Njc4OWFiY2RlZg=="]`},
+ {"uuid on fixed(4)",
`{"type":"fixed","name":"F","size":4,"logicalType":"uuid"}`, []any{[4]byte{1,
2, 3, 4}}, `["AQIDBA=="]`},
+ {"time-millis on long",
`{"type":"long","logicalType":"time-millis"}`, []any{int64(5)}, `[5]`},
+ {"timestamp-millis on int",
`{"type":"int","logicalType":"timestamp-millis"}`, []any{int32(5)}, `[5]`},
+ {"duration on fixed(10)",
`{"type":"fixed","name":"D","size":10,"logicalType":"duration"}`,
[]any{[10]byte{1}}, `["AQAAAAAAAAAAAA=="]`},
+ {"field-level timestamp-millis on long",
`"long","logicalType":"timestamp-millis"`, []any{ts},
`["2023-11-14T22:13:20.123Z"]`},
+ {"field-level decimal on bytes",
`"bytes","logicalType":"decimal","precision":4,"scale":2`,
[]any{big.NewRat(1234, 100)}, `["12.34"]`},
+ {"field-level timestamp-millis on a nullable long",
`["null","long"],"logicalType":"timestamp-millis"`, []any{ts, nil},
`["2023-11-14T22:13:20.123Z",null]`},
+ {"logical type in the type wins over the field",
`{"type":"long","logicalType":"timestamp-micros"},"logicalType":"timestamp-millis"`,
+ []any{tsMicros}, `["2023-11-14T22:13:20.123456Z"]`},
+ {"field-level scale fills the type's decimal",
`{"type":"bytes","logicalType":"decimal","precision":6},"logicalType":"decimal","scale":2`,
+ []any{big.NewRat(1234, 100)}, `["12.34"]`},
+ {"field-level logical type that does not fit",
`"int","logicalType":"timestamp-millis"`, []any{int32(5)}, `[5]`},
+ {"big-decimal", bigDecimal, []any{big.NewRat(1234, 100),
big.NewRat(-15, 10), big.NewRat(42, 1), new(big.Rat), manyDigits},
+
`["12.34","-1.5","42","0","12345678901234567890.0000000001"]`},
+ {"nullable big-decimal", `["null",` + bigDecimal + `]`,
[]any{big.NewRat(3, 2), nil}, `["1.5",null]`},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ rows := make([]any, len(tt.rows))
+ for i, row := range tt.rows {
+ rows[i] = map[string]any{"f": row}
+ }
+ schema :=
`{"type":"record","name":"rec","fields":[{"name":"f","type":` + tt.typ + `}]}`
+ ar, err := NewOCFReader(bytes.NewReader(writeOCF(t,
schema, rows...)), WithChunk(-1))
+ require.NoError(t, err)
+ defer ar.Close()
- var buf bytes.Buffer
- avroSchema, err := avro.Parse(schema)
- assert.NoError(t, err)
- enc, err := ocf.NewWriter(&buf, avroSchema)
- assert.NoError(t, err)
- assert.NoError(t, enc.Encode(map[string]any{
- "plain": payload,
- "nullable": map[string]any{"bytes": payload},
- }))
- assert.NoError(t, enc.Encode(map[string]any{
- "plain": []byte{},
- "nullable": nil,
- }))
- assert.NoError(t, enc.Close())
-
- ar, err := NewOCFReader(bytes.NewReader(buf.Bytes()), WithChunk(-1))
- assert.NoError(t, err)
- defer ar.Close()
-
- assert.True(t, ar.Next())
- assert.NoError(t, ar.Err())
- rec := ar.RecordBatch()
+ require.True(t, ar.Next(), "%v", ar.Err())
+ got, err := json.Marshal(ar.RecordBatch().Column(0))
+ require.NoError(t, err)
+ assert.JSONEq(t, tt.want, string(got))
+ })
+ }
+}
- plain := rec.Column(0).(*array.Binary)
- assert.Equal(t, payload, plain.Value(0))
- assert.Equal(t, []byte{}, plain.Value(1))
+// A schema edit can give a field a type that the data in the file does not
+// have. The reader must return an error for such a value.
+func TestOCFReaderSchemaEditMismatch(t *testing.T) {
+ fixture := writeOCF(t,
`{"type":"record","name":"rec","fields":[{"name":"f","type":"int"},{"name":"g","type":"int"}]}`,
+ map[string]any{"f": int32(1), "g": int32(2)})
+ tests := []struct {
+ name string
+ typ string
+ wantErr string
+ }{
+ {"array", `{"type":"array","items":"int"}`, "unsupported value
of type int32 for List column"},
+ {"map", `{"type":"map","values":"int"}`, "unsupported value of
type int32 for Map column"},
+ {"record",
`{"type":"record","name":"R","fields":[{"name":"x","type":"int"}]}`,
"unsupported value of type int32 for Struct column"},
+ {"null", `"null"`, "unsupported value of type int32 for Null
column"},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ ar, err := NewOCFReader(bytes.NewReader(fixture),
WithChunk(-1),
+ WithSchemaEdit("set", "fields.0.type",
json.RawMessage(tt.typ)))
+ require.NoError(t, err)
+ defer ar.Close()
- nullable := rec.Column(1).(*array.Binary)
- assert.Equal(t, payload, nullable.Value(0))
- assert.True(t, nullable.IsNull(1))
+ require.False(t, ar.Next())
+ require.ErrorContains(t, ar.Err(), tt.wantErr)
+ })
+ }
}
func TestOCFReaderCloseUnblocksFullQueues(t *testing.T) {
@@ -405,6 +480,9 @@ func TestOCFReaderReuseDiscardsPartialBuilderState(t
*testing.T) {
mem.AssertSize(t, 0)
}
+// A nullable logical timestamp must decode to a value rather than a null: the
+// union branch carries the logical type, so the reader has to honour it on the
+// branch and not just on a bare long.
func TestOCFReaderNullableTimestamps(t *testing.T) {
tests := []struct {
logicalType string
diff --git a/arrow/avro/reader_types.go b/arrow/avro/reader_types.go
index 6cfd49f6..6781930b 100644
--- a/arrow/avro/reader_types.go
+++ b/arrow/avro/reader_types.go
@@ -21,6 +21,7 @@ import (
"fmt"
"math/big"
"reflect"
+ "strings"
"time"
"github.com/apache/arrow-go/v18/arrow"
@@ -33,258 +34,29 @@ import (
)
type dataLoader struct {
- idx, depth int32
- list *fieldPos
- item *fieldPos
- mapField *fieldPos
- mapKey *fieldPos
- mapValue *fieldPos
- fields []*fieldPos
- children []*dataLoader
+ fields []*fieldPos
}
var (
ErrNullStructData = errors.New("null struct data")
)
-func newDataLoader() *dataLoader { return &dataLoader{idx: 0, depth: 0} }
-
-// drawTree takes the tree of field builders produced by mapFieldBuilders()
-// and produces another tree structure and aggregates fields whose values can
-// be retrieved from a `map[string]any` into a slice of builders, and creates
a hierarchy to
-// deal with nested types (lists and maps).
-func (d *dataLoader) drawTree(field *fieldPos) {
- for _, f := range field.children() {
- if f.isList || f.isMap {
- if f.isList {
- c := d.newListChild(f)
- if !f.childrens[0].isList {
- c.item = f.childrens[0]
- c.drawTree(f.childrens[0])
- } else {
- c.drawTree(f.childrens[0].childrens[0])
- }
- }
- if f.isMap {
- c := d.newMapChild(f)
- if
!arrow.IsNested(f.childrens[1].builder.Type().ID()) {
- c.mapKey = f.childrens[0]
- c.mapValue = f.childrens[1]
- } else {
- c.mapKey = f.childrens[0]
- m := c.newChild()
- m.mapValue = f.childrens[1]
- m.drawTree(f.childrens[1])
- }
- }
- } else {
- d.fields = append(d.fields, f)
- if len(f.children()) > 0 {
- d.drawTree(f)
- }
- }
- }
-}
+func newDataLoader() *dataLoader { return &dataLoader{} }
-// loadDatum loads decoded Avro data to the schema fields' builder functions.
-// Since array.StructBuilder.AppendNull() will recursively append null to all
of the
-// struct's fields, in the case of nil being passed to a struct's builderFunc
it will
-// return a ErrNullStructData error to signal that all its sub-fields can be
skipped.
-func (d *dataLoader) loadDatum(data any) error {
- if d.list == nil && d.mapField == nil {
- if d.mapValue != nil {
- if err := appendValue(d.mapValue, data); err != nil {
- return err
- }
- }
- var NullParent *fieldPos
- for _, f := range d.fields {
- if f.parent == NullParent {
- continue
- }
- if d.mapValue == nil {
- err := f.appendFunc(f.getValue(data))
- if err != nil {
- if err == ErrNullStructData {
- NullParent = f
- continue
- }
- return err
- }
- } else {
- switch dt := data.(type) {
- case nil:
- err := f.appendFunc(dt)
- if err != nil {
- if err == ErrNullStructData {
- NullParent = f
- continue
- }
- return err
- }
- case []any:
- if len(d.children) < 1 {
- for _, e := range dt {
- err := f.appendFunc(e)
- if err != nil {
- if err ==
ErrNullStructData {
-
NullParent = f
- continue
- }
- return err
- }
- }
- } else {
- for _, e := range dt {
- if err :=
d.children[0].loadDatum(e); err != nil {
- return err
- }
- }
- }
- case map[string]any:
- err := f.appendFunc(f.getValue(dt))
- if err != nil {
- if err == ErrNullStructData {
- NullParent = f
- continue
- }
- return err
- }
- }
+// drawTree keeps the top-level fields of the tree of field builders produced
+// by mapFieldBuilders(). The appendFunc of a list, map, or struct field
appends
+// the items, keys and values, or fields under it.
+func (d *dataLoader) drawTree(field *fieldPos) { d.fields = field.childrens }
- }
- }
- for _, c := range d.children {
- if c.list != nil {
- if err := c.loadDatum(c.list.getValue(data));
err != nil {
- return err
- }
- }
- if c.mapField != nil {
- switch dt := data.(type) {
- case nil:
- if err := c.loadDatum(dt); err != nil {
- return err
- }
- case map[string]any:
- if err :=
c.loadDatum(c.mapField.getValue(dt)); err != nil {
- return err
- }
- default:
- if err :=
c.loadDatum(c.mapField.getValue(data)); err != nil {
- return err
- }
- }
- }
- }
- } else {
- if d.list != nil {
- switch dt := data.(type) {
- case nil:
- if err := appendValue(d.list, dt); err != nil {
- return err
- }
- case []any:
- if err := appendValue(d.list, dt); err != nil {
- return err
- }
- for _, e := range dt {
- if d.item != nil {
- if err := appendValue(d.item,
e); err != nil {
- return err
- }
- }
- var NullParent *fieldPos
- for _, f := range d.fields {
- if f.parent == NullParent {
- continue
- }
- err :=
f.appendFunc(f.getValue(e))
- if err != nil {
- if err ==
ErrNullStructData {
- NullParent = f
- continue
- }
- return err
- }
- }
- for _, c := range d.children {
- if c.list != nil {
- if err :=
c.loadDatum(c.list.getValue(e)); err != nil {
- return err
- }
- }
- if c.mapField != nil {
- if err :=
c.loadDatum(c.mapField.getValue(e)); err != nil {
- return err
- }
- }
- }
- }
- case map[string]any:
- if err := appendValue(d.list, dt["array"]); err
!= nil {
- return err
- }
- for _, e := range dt["array"].([]any) {
- if d.item != nil {
- if err := appendValue(d.item,
e); err != nil {
- return err
- }
- }
- var NullParent *fieldPos
- for _, f := range d.fields {
- if f.parent == NullParent {
- continue
- }
- err :=
f.appendFunc(f.getValue(e))
- if err != nil {
- if err ==
ErrNullStructData {
- NullParent = f
- continue
- }
- return err
- }
- }
- for _, c := range d.children {
- if err :=
c.loadDatum(c.list.getValue(e)); err != nil {
- return err
- }
- }
- }
- default:
- if err := appendValue(d.list, data); err != nil
{
- return err
- }
- if err := appendValue(d.item, dt); err != nil {
- return err
- }
- }
- }
- if d.mapField != nil {
- switch dt := data.(type) {
- case nil:
- if err := appendValue(d.mapField, dt); err !=
nil {
- return err
- }
- case map[string]any:
- if err := appendValue(d.mapField, dt); err !=
nil {
- return err
- }
- for k, v := range dt {
- if err := appendValue(d.mapKey, k); err
!= nil {
- return err
- }
- if d.mapValue != nil {
- if err :=
appendValue(d.mapValue, v); err != nil {
- return err
- }
- } else {
- if err :=
d.children[0].loadDatum(v); err != nil {
- return err
- }
- }
- }
- }
+// loadDatum appends each top-level field of a decoded Avro record.
+func (d *dataLoader) loadDatum(data any) error {
+ record, ok := data.(map[string]any)
+ if !ok {
+ return fmt.Errorf("avro: unsupported value of type %T for a
record", data)
+ }
+ for _, f := range d.fields {
+ if err := appendValue(f, record[f.fieldName]); err != nil {
+ return err
}
}
return nil
@@ -302,128 +74,18 @@ func appendValue(f *fieldPos, data any) error {
return nil
}
-func (d *dataLoader) newChild() *dataLoader {
- var child = &dataLoader{
- depth: d.depth + 1,
- }
- d.children = append(d.children, child)
- return child
-}
-
-func (d *dataLoader) newListChild(list *fieldPos) *dataLoader {
- var child = &dataLoader{
- list: list,
- item: list.childrens[0],
- depth: d.depth + 1,
- }
- d.children = append(d.children, child)
- return child
-}
-
-func (d *dataLoader) newMapChild(mapField *fieldPos) *dataLoader {
- var child = &dataLoader{
- mapField: mapField,
- depth: d.depth + 1,
- }
- d.children = append(d.children, child)
- return child
-}
-
type fieldPos struct {
- parent *fieldPos
- fieldName string
- builder array.Builder
- path []string
- isList bool
- isItem bool
- isStruct bool
- isMap bool
- typeName string
- appendFunc func(val interface{}) error
- metadatas arrow.Metadata
- childrens []*fieldPos
- index, depth int32
+ fieldName string
+ appendFunc func(val interface{}) error
+ childrens []*fieldPos
}
-func newFieldPos() *fieldPos { return &fieldPos{index: -1} }
-
-func (f *fieldPos) children() []*fieldPos { return f.childrens }
+func newFieldPos() *fieldPos { return &fieldPos{} }
-func (f *fieldPos) newChild(childName string, childBuilder array.Builder, meta
arrow.Metadata) *fieldPos {
- var child = fieldPos{
- parent: f,
- fieldName: childName,
- builder: childBuilder,
- metadatas: meta,
- index: int32(len(f.childrens)),
- depth: f.depth + 1,
- }
- if f.isList {
- child.isItem = true
- }
- child.path = child.buildNamePath()
- f.childrens = append(f.childrens, &child)
- return &child
-}
-
-func (f *fieldPos) buildNamePath() []string {
- var path []string
- var listPath []string
- cur := f
- for i := f.depth - 1; i >= 0; i-- {
- if cur.typeName == "" {
- path = append([]string{cur.fieldName}, path...)
- } else {
- path = append([]string{cur.fieldName, cur.typeName},
path...)
- }
- if !cur.parent.isMap {
- cur = cur.parent
- }
- }
- if f.parent.parent != nil && f.parent.parent.isList {
- for i := len(path) - 1; i >= 0; i-- {
- if path[i] != "item" {
- listPath = append([]string{path[i]},
listPath...)
- } else {
- return listPath
- }
- }
- }
- if f.parent != nil && f.parent.fieldName == "value" {
- for i := len(path) - 1; i >= 0; i-- {
- if path[i] != "value" {
- listPath = append([]string{path[i]},
listPath...)
- } else {
- return listPath
- }
- }
- }
- return path
-}
-
-// NamePath returns a slice of keys making up the path to the field
-func (f *fieldPos) namePath() []string { return f.path }
-
-// GetValue retrieves the value from the map[string]any
-// by following the field's key path
-func (f *fieldPos) getValue(m any) any {
- if _, ok := m.(map[string]any); !ok {
- return m
- }
- for _, key := range f.namePath() {
- valueMap, ok := m.(map[string]any)
- if !ok {
- if key == "item" {
- return m
- }
- return nil
- }
- m, ok = valueMap[key]
- if !ok {
- return nil
- }
- }
- return m
+func (f *fieldPos) newChild(childName string) *fieldPos {
+ child := &fieldPos{fieldName: childName}
+ f.childrens = append(f.childrens, child)
+ return child
}
// Avro data is loaded to Arrow arrays using the following type mapping:
@@ -440,12 +102,21 @@ func (f *fieldPos) getValue(m any) any {
// array []interface{} List
// enum string
Dictionary
// fixed []byte
FixedSizeBinary
-// map and record map[string]any Struct
+// map map[string]any Map
+// record map[string]any Struct
//
// mapFieldBuilders builds a tree of field builders matching the Arrow schema
func mapFieldBuilders(b array.Builder, field arrow.Field, parent *fieldPos) {
- f := parent.newChild(field.Name, b, field.Metadata)
+ f := parent.newChild(field.Name)
switch bt := b.(type) {
+ case *array.NullBuilder:
+ f.appendFunc = func(data interface{}) error {
+ if data != nil {
+ return fmt.Errorf("avro: unsupported value of
type %T for Null column", data)
+ }
+ bt.AppendNull()
+ return nil
+ }
case *array.BinaryBuilder:
f.appendFunc = func(data interface{}) error {
return appendBinaryData(bt, data)
@@ -512,8 +183,8 @@ func mapFieldBuilders(b array.Builder, field arrow.Field,
parent *fieldPos) {
}
case *array.LargeListBuilder:
vb := bt.ValueBuilder()
- f.isList = true
mapFieldBuilders(vb,
field.Type.(*arrow.LargeListType).ElemField(), f)
+ item := f.childrens[0]
f.appendFunc = func(data interface{}) error {
switch dt := data.(type) {
case nil:
@@ -524,15 +195,20 @@ func mapFieldBuilders(b array.Builder, field arrow.Field,
parent *fieldPos) {
} else {
bt.Append(true)
}
+ for _, e := range dt {
+ if err := appendValue(item, e); err !=
nil {
+ return err
+ }
+ }
default:
- bt.Append(true)
+ return fmt.Errorf("avro: unsupported value of
type %T for LargeList column", data)
}
return nil
}
case *array.ListBuilder:
vb := bt.ValueBuilder()
- f.isList = true
mapFieldBuilders(vb, field.Type.(*arrow.ListType).ElemField(),
f)
+ item := f.childrens[0]
f.appendFunc = func(data interface{}) error {
switch dt := data.(type) {
case nil:
@@ -543,24 +219,38 @@ func mapFieldBuilders(b array.Builder, field arrow.Field,
parent *fieldPos) {
} else {
bt.Append(true)
}
+ for _, e := range dt {
+ if err := appendValue(item, e); err !=
nil {
+ return err
+ }
+ }
default:
- bt.Append(true)
+ return fmt.Errorf("avro: unsupported value of
type %T for List column", data)
}
return nil
}
case *array.MapBuilder:
- // has metadata for objects in values
- f.isMap = true
kb := bt.KeyBuilder()
ib := bt.ItemBuilder()
mapFieldBuilders(kb, field.Type.(*arrow.MapType).KeyField(), f)
mapFieldBuilders(ib, field.Type.(*arrow.MapType).ItemField(), f)
+ key, value := f.childrens[0], f.childrens[1]
f.appendFunc = func(data interface{}) error {
- switch data.(type) {
+ switch dt := data.(type) {
case nil:
bt.AppendNull()
- default:
+ case map[string]any:
bt.Append(true)
+ for k, v := range dt {
+ if err := appendValue(key, k); err !=
nil {
+ return err
+ }
+ if err := appendValue(value, v); err !=
nil {
+ return err
+ }
+ }
+ default:
+ return fmt.Errorf("avro: unsupported value of
type %T for Map column", data)
}
return nil
}
@@ -573,20 +263,25 @@ func mapFieldBuilders(b array.Builder, field arrow.Field,
parent *fieldPos) {
return appendStringData(bt, data)
}
case *array.StructBuilder:
- // has metadata for Avro Union named types
- f.typeName, _ = field.Metadata.GetValue("typeName")
- f.isStruct = true
// create children
for i, p := range field.Type.(*arrow.StructType).Fields() {
mapFieldBuilders(bt.FieldBuilder(i), p, f)
}
f.appendFunc = func(data interface{}) error {
- switch data.(type) {
+ switch dt := data.(type) {
case nil:
+ // AppendNull appends a null to every field
under the struct.
bt.AppendNull()
return ErrNullStructData
- default:
+ case map[string]any:
bt.Append(true)
+ for _, c := range f.childrens {
+ if err := appendValue(c,
dt[c.fieldName]); err != nil {
+ return err
+ }
+ }
+ default:
+ return fmt.Errorf("avro: unsupported value of
type %T for Struct column", data)
}
return nil
}
@@ -602,6 +297,10 @@ func mapFieldBuilders(b array.Builder, field arrow.Field,
parent *fieldPos) {
f.appendFunc = func(data interface{}) error {
return appendTimestampData(bt, data)
}
+ default:
+ f.appendFunc = func(interface{}) error {
+ return fmt.Errorf("avro: unsupported Arrow type %s for
column %q", field.Type, field.Name)
+ }
}
}
@@ -808,12 +507,39 @@ func appendStringData(b *array.StringBuilder, data
interface{}) error {
b.AppendNull()
case string:
b.Append(dt)
+ case *big.Rat:
+ // A big-decimal value arrives as a *big.Rat.
+ s, ok := decimalText(dt)
+ if !ok {
+ return fmt.Errorf("avro: value %s has no exact decimal
text for String column", dt.RatString())
+ }
+ b.Append(s)
default:
return fmt.Errorf("avro: unsupported value of type %T for
String column", data)
}
return nil
}
+// decimalText returns the decimal text of r with the fewest digits after the
+// point that represent r exactly. It returns false when no decimal text is
+// exact, which is when r's reduced denominator has a prime factor other than
+// 2 and 5.
+func decimalText(r *big.Rat) (string, bool) {
+ d := new(big.Int).Set(r.Denom())
+ twos := d.TrailingZeroBits()
+ d.Rsh(d, twos)
+ digits := int(twos)
+ if d.BitLen() > 1 {
+ // d must be a power of 5, which in base 5 is a 1 followed by
zeros.
+ s := d.Text(5)
+ if s[0] != '1' || strings.TrimRight(s[1:], "0") != "" {
+ return "", false
+ }
+ digits = max(digits, len(s)-1)
+ }
+ return r.FloatString(digits), true
+}
+
func appendTime32Data(b *array.Time32Builder, data interface{}) error {
switch dt := data.(type) {
case nil:
diff --git a/arrow/avro/schema.go b/arrow/avro/schema.go
index 96508df6..1f2fccdd 100644
--- a/arrow/avro/schema.go
+++ b/arrow/avro/schema.go
@@ -21,7 +21,9 @@ import (
"encoding/json"
"fmt"
"math"
+ "slices"
"strconv"
+ "strings"
"github.com/apache/arrow-go/v18/arrow"
"github.com/apache/arrow-go/v18/arrow/decimal128"
@@ -110,10 +112,12 @@ func (node *schemaNode) rememberNamed(s avro.SchemaNode) {
full = s.Namespace + "." + s.Name
}
node.namedCache[full] = s
- if existing, ok := node.bareToFull[s.Name]; ok && existing != full {
- node.ambiguousBare[s.Name] = struct{}{}
+ // A dotted name such as "x.A" is a full name, and its short name is
"A".
+ short := s.Name[strings.LastIndexByte(s.Name, '.')+1:]
+ if existing, ok := node.bareToFull[short]; ok && existing != full {
+ node.ambiguousBare[short] = struct{}{}
} else {
- node.bareToFull[s.Name] = full
+ node.bareToFull[short] = full
}
}
@@ -278,10 +282,60 @@ func arrowSchemafromAvro(n *schemaNode) {
}
}
+// liftFieldLogical returns the type of the record field f with a field-level
+// logicalType moved onto it, as twmb/avro does before it decodes the field.
The
+// logical type moves onto the type, or onto the first non-null branch of a
+// union, and a logical type already on that type wins. Where the logical type
+// in effect is decimal, the field's precision and scale fill in the ones the
+// type does not have. isLogicalSchemaType then ignores a logical type that
does
+// not fit, as twmb/avro does.
+func liftFieldLogical(f avro.SchemaField) avro.SchemaNode {
+ t := f.Type
+ logical, _ := f.Props["logicalType"].(string)
+ if logical == "" {
+ return t
+ }
+ target := &t
+ if t.Type == "union" {
+ t.Branches = slices.Clone(t.Branches)
+ target = nil
+ for i := range t.Branches {
+ if t.Branches[i].Type != "null" {
+ target = &t.Branches[i]
+ break
+ }
+ }
+ if target == nil {
+ return t
+ }
+ }
+ if target.LogicalType == "" {
+ target.LogicalType = logical
+ }
+ if target.LogicalType == "decimal" {
+ if p, ok := f.Props["precision"].(int64); ok &&
target.Precision == 0 {
+ target.Precision = int(p)
+ }
+ if s, ok := f.Props["scale"].(int64); ok && target.Scale == 0 {
+ target.Scale = int(s)
+ }
+ }
+ return t
+}
+
// iterate record Fields
func iterateFields(n *schemaNode) {
+ // An Arrow schema cannot represent a record that contains itself, so
reject
+ // a record that is also one of its enclosing records. The top
schemaNode has
+ // no parent and repeats the root record, so the walk stops before it.
+ for p := n.parent; p != nil && p.parent != nil; p = p.parent {
+ if p.node.Type == "record" && p.node.Name == n.node.Name &&
p.node.Namespace == n.node.Namespace {
+ name, _ := isNamedSchema(n.node)
+ panic(fmt.Errorf("recursive avro record %q at %s: arrow
schemas cannot represent recursive types", name, n.schemaPath()))
+ }
+ }
for _, f := range n.node.Fields {
- ft := n.resolveRef(f.Type, f.Name)
+ ft := n.resolveRef(liftFieldLogical(f), f.Name)
switch ft.Type {
// Avro "array" field type
case "array":
@@ -402,8 +456,27 @@ func nullableBranch(s avro.SchemaNode) (avro.SchemaNode,
bool) {
return *nonNull, true
}
+// isLogicalSchemaType reports whether s has a logical type that applies to its
+// underlying type. The Avro spec has a reader ignore an unknown logical type,
+// and one on an underlying type or size that the logical type does not allow.
+// twmb/avro then decodes the underlying type, so we convert that type instead.
func isLogicalSchemaType(s avro.SchemaNode) bool {
- return s.LogicalType != ""
+ switch s.LogicalType {
+ case "decimal":
+ return s.Type == "bytes" || s.Type == "fixed"
+ case "big-decimal":
+ return s.Type == "bytes"
+ case "uuid":
+ return s.Type == "string" || s.Type == "fixed" && s.Size == 16
+ case "date", "time-millis":
+ return s.Type == "int"
+ case "time-micros", "timestamp-millis", "timestamp-micros",
"timestamp-nanos",
+ "local-timestamp-millis", "local-timestamp-micros",
"local-timestamp-nanos":
+ return s.Type == "long"
+ case "duration":
+ return s.Type == "fixed" && s.Size == 12
+ }
+ return false
}
func isNamedSchema(s avro.SchemaNode) (string, bool) {
@@ -548,6 +621,12 @@ func avroLogicalToArrowField(n *schemaNode) {
// stores a number in days, and the third stores a number in
milliseconds.
case "duration":
dt = arrow.FixedWidthTypes.MonthDayNanoInterval
+
+ // The big-decimal logical type annotates Avro bytes, and each value
carries
+ // its own scale, which no Arrow decimal type has. We read each value
as its
+ // exact decimal text.
+ case "big-decimal":
+ dt = arrow.BinaryTypes.String
}
n.arrowField = buildArrowField(n, dt, arrow.Metadata{})
}
diff --git a/arrow/avro/schema_test.go b/arrow/avro/schema_test.go
index 8b208a34..7c687614 100644
--- a/arrow/avro/schema_test.go
+++ b/arrow/avro/schema_test.go
@@ -19,6 +19,7 @@ package avro
import (
"errors"
"fmt"
+ "slices"
"strings"
"testing"
@@ -129,7 +130,7 @@ func TestSchemaStringEqual(t *testing.T) {
},
{
Name: "uuidField",
- Type: arrow.BinaryTypes.String,
+ Type: extensions.NewUUIDType(),
},
{
Name: "fixedUuidField",
@@ -237,7 +238,8 @@ func
TestArrowSchemaFromAvro_Deprecated_PreservesLogicalTypesOnFixed(t *testing.
// OCF requires a record at the top level. Non-record roots are rejected by our
// own guard, while a record with an empty name is rejected earlier by the avro
// parser; both must surface an error rather than produce a degenerate schema.
-func TestArrowSchemaFromAvroJSON_RejectsInvalidRoot(t *testing.T) {
+// A record that contains itself has no Arrow equivalent and is rejected too.
+func TestArrowSchemaFromAvroJSON_RejectsInvalidSchema(t *testing.T) {
tests := []struct {
name string
schemaJSON string
@@ -247,6 +249,9 @@ func TestArrowSchemaFromAvroJSON_RejectsInvalidRoot(t
*testing.T) {
{name: "string root", schemaJSON: `"string"`, wantErr: "must be
a record"},
{name: "array root", schemaJSON:
`{"type":"array","items":"int"}`, wantErr: "must be a record"},
{name: "empty record name", schemaJSON:
`{"type":"record","name":"","fields":[{"name":"x","type":"int"}]}`, wantParse:
true},
+ {name: "recursive record", schemaJSON:
`{"type":"record","name":"Node","fields":[{"name":"next","type":["null","Node"]}]}`,
wantErr: `recursive avro record "Node"`},
+ {name: "recursive nested record", schemaJSON:
`{"type":"record","name":"Root","fields":[{"name":"tree","type":{"type":"record","name":"Tree","namespace":"ns","fields":[{"name":"children","type":{"type":"array","items":"Tree"}}]}}]}`,
wantErr: `recursive avro record "ns.Tree"`},
+ {name: "mutually recursive records", schemaJSON:
`{"type":"record","name":"A","fields":[{"name":"b","type":["null",{"type":"record","name":"B","fields":[{"name":"a","type":["null","A"]}]}]}]}`,
wantErr: `recursive avro record "A"`},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
@@ -291,20 +296,40 @@ func
TestArrowSchemaFromAvroJSON_RejectsInvalidDecimalPrecision(t *testing.T) {
}
}
-// A named record referenced again by name resolves back to the same
definition.
+// A named record referenced again by name resolves back to the same
definition,
+// and a record inside another record with the same short name converts.
func TestArrowSchemaFromAvroJSON_ReusedNamedReference(t *testing.T) {
- const schemaJSON = `{"type":"record","name":"Root","fields":[
-
{"name":"a","type":{"type":"record","name":"Foo","fields":[{"name":"x","type":"int"}]}},
- {"name":"b","type":"Foo"}]}`
- s, err := ArrowSchemaFromAvroJSON(schemaJSON)
- if err != nil {
- t.Fatalf("ArrowSchemaFromAvroJSON: %v", err)
- }
- if s.NumFields() != 2 {
- t.Fatalf("got %d fields, want 2", s.NumFields())
+ tests := []struct {
+ name string
+ schemaJSON string
+ want []string // the Arrow type of each top-level field
+ }{
+ {"reference in a sibling field",
`{"type":"record","name":"Root","fields":[
+
{"name":"a","type":{"type":"record","name":"Foo","fields":[{"name":"x","type":"int"}]}},
+ {"name":"b","type":"Foo"}]}`, []string{"struct<x:
int32>", "struct<x: int32>"}},
+ {"same short name in another namespace inside",
`{"type":"record","name":"R","fields":[
+
{"name":"a","type":{"type":"record","name":"A","namespace":"x","fields":[
+
{"name":"b","type":{"type":"record","name":"A","namespace":"y","fields":[{"name":"y","type":"int"}]}}]}}]}`,
+ []string{"struct<b: struct<y: int32>>"}},
+ {"short reference to a dotted name",
`{"type":"record","name":"R","fields":[
+
{"name":"a","type":{"type":"record","name":"x.A","fields":[{"name":"v","type":"int"}]}},
+
{"name":"b","type":{"type":"record","name":"B","namespace":"x","fields":[{"name":"c","type":"A"}]}}]}`,
+ []string{"struct<v: int32>", "struct<c: struct<v:
int32>>"}},
}
- if a, b := s.Field(0).Type.String(), s.Field(1).Type.String(); a != b {
- t.Fatalf("reused reference resolved to a different type:\n a =
%s\n b = %s", a, b)
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ s, err := ArrowSchemaFromAvroJSON(tt.schemaJSON)
+ if err != nil {
+ t.Fatalf("ArrowSchemaFromAvroJSON: %v", err)
+ }
+ var got []string
+ for _, f := range s.Fields() {
+ got = append(got, f.Type.String())
+ }
+ if !slices.Equal(got, tt.want) {
+ t.Fatalf("field types:\n got = %q\nwant = %q",
got, tt.want)
+ }
+ })
}
}