You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@arrow.apache.org by GitBox <gi...@apache.org> on 2022/01/14 17:35:47 UTC

[GitHub] [arrow] zeroshade opened a new pull request #12158: ARROW-3039: [Go] Add support for DictionaryArray

zeroshade opened a new pull request #12158:
URL: https://github.com/apache/arrow/pull/12158


   Also resolves ARROW-5267, ARROW-7286, and ARROW-9378 which all are different pieces of the DictionaryArray support.
   
   This *does not* implement Dictionary support for scalars yet, nor does it yet support concatenating Dictionary Arrays and dictionary unification. Cards will be created to track work for those two pieces of functionality separately.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] brancz commented on pull request #12158: ARROW-3039: [Go] Add support for DictionaryArray

Posted by GitBox <gi...@apache.org>.
brancz commented on pull request #12158:
URL: https://github.com/apache/arrow/pull/12158#issuecomment-1024624600


   Hey! I stumbled on this PR since I was looking for dictionary support, and I was wondering why there wasn't a `StringDictionaryBuilder`, but almost everything else? Or is one just supposed to use the `Dictionary` type directly for that? The other case I have that I'd want to use dictionaries for is Lists, as in a dictionary of common lists seen before, does that even work with Dictionaries? (sorry if the second one is a more general question than about this PR)


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] zeroshade commented on pull request #12158: ARROW-3039: [Go] Add support for DictionaryArray

Posted by GitBox <gi...@apache.org>.
zeroshade commented on pull request #12158:
URL: https://github.com/apache/arrow/pull/12158#issuecomment-1071247615


   @emkornfield Delta and replacement dictionaries are handled at the bottom of the `readDictionary` function by calling `AddDelta` and `AddOrReplace` on the `memo` object, while the `memo` object is used when constructing the record batches with those dictionaries. 
   
   I've added the error case for IPC files to error out on a replacement dictionary. That should cover everything as far as I'm aware for now, and we're passing all the integration tests with dictionaries.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] zeroshade commented on a change in pull request #12158: ARROW-3039: [Go] Add support for DictionaryArray

Posted by GitBox <gi...@apache.org>.
zeroshade commented on a change in pull request #12158:
URL: https://github.com/apache/arrow/pull/12158#discussion_r828201317



##########
File path: go/arrow/array/array_test.go
##########
@@ -95,13 +96,15 @@ func TestMakeFromData(t *testing.T) {
 			}, 0 /* nulls */, 0 /* offset */)},
 		},
 
+		{name: "dictionary", d: &testDataType{arrow.DICTIONARY}, expPanic: true, expError: "arrow/array: no dictionary set in Data for Dictionary array"},
+		{name: "dictionary", d: &arrow.DictionaryType{IndexType: arrow.PrimitiveTypes.Int8, ValueType: &testDataType{arrow.INT64}}, dict: array.NewData(&testDataType{arrow.INT64}, 0 /* length */, make([]*memory.Buffer, 2 /*null bitmap, values*/), nil /* childData */, 0 /* nulls */, 0 /* offset */)},

Review comment:
       no reason not to




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] zeroshade commented on a change in pull request #12158: ARROW-3039: [Go] Add support for DictionaryArray

Posted by GitBox <gi...@apache.org>.
zeroshade commented on a change in pull request #12158:
URL: https://github.com/apache/arrow/pull/12158#discussion_r800700420



##########
File path: go/arrow/array/data.go
##########
@@ -63,6 +64,16 @@ func NewData(dtype arrow.DataType, length int, buffers []*memory.Buffer, childDa
 	}
 }
 
+// NewDataWithDictionary creates a new data object, but also sets the provided dictionary into the data if it's not nil
+func NewDataWithDictionary(dtype arrow.DataType, length int, buffers []*memory.Buffer, childData []arrow.ArrayData, nulls, offset int, dict *Data) *Data {
+	data := NewData(dtype, length, buffers, childData, nulls, offset)

Review comment:
       Is it guaranteed that `childData` should always be empty for Dictionary arrays? Based on the spec, can you have a dictionary of lists where the values of the dictionary are themselves list arrays? If it's guaranteed to always be empty, I'll just remove it from the argument list here.




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] emkornfield commented on a change in pull request #12158: ARROW-3039: [Go] Add support for DictionaryArray

Posted by GitBox <gi...@apache.org>.
emkornfield commented on a change in pull request #12158:
URL: https://github.com/apache/arrow/pull/12158#discussion_r800127882



##########
File path: go/arrow/array/data.go
##########
@@ -63,6 +64,16 @@ func NewData(dtype arrow.DataType, length int, buffers []*memory.Buffer, childDa
 	}
 }
 
+// NewDataWithDictionary creates a new data object, but also sets the provided dictionary into the data if it's not nil
+func NewDataWithDictionary(dtype arrow.DataType, length int, buffers []*memory.Buffer, childData []arrow.ArrayData, nulls, offset int, dict *Data) *Data {
+	data := NewData(dtype, length, buffers, childData, nulls, offset)

Review comment:
       should we check that childData is empty here?




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] emkornfield commented on a change in pull request #12158: ARROW-3039: [Go] Add support for DictionaryArray

Posted by GitBox <gi...@apache.org>.
emkornfield commented on a change in pull request #12158:
URL: https://github.com/apache/arrow/pull/12158#discussion_r800129021



##########
File path: go/arrow/array/dictionary.go
##########
@@ -0,0 +1,1305 @@
+// 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 array
+
+import (
+	"errors"
+	"fmt"
+	"math"
+	"sync/atomic"
+	"unsafe"
+
+	"github.com/apache/arrow/go/v7/arrow"
+	"github.com/apache/arrow/go/v7/arrow/bitutil"
+	"github.com/apache/arrow/go/v7/arrow/decimal128"
+	"github.com/apache/arrow/go/v7/arrow/float16"
+	"github.com/apache/arrow/go/v7/arrow/internal/debug"
+	"github.com/apache/arrow/go/v7/arrow/memory"
+	"github.com/apache/arrow/go/v7/internal/hashing"
+	"github.com/goccy/go-json"
+)
+
+// Dictionary represents the type for dictionary-encoded data with a data
+// dependent dictionary.
+//
+// A dictionary array contains an array of non-negative integers (the "dictionary"
+// indices") along with a data type containing a "dictionary" corresponding to
+// the distinct values represented in the data.
+//
+// For example, the array:
+//
+//      ["foo", "bar", "foo", "bar", "foo", "bar"]
+//
+// with dictionary ["bar", "foo"], would have the representation of:
+//
+//      indices: [1, 0, 1, 0, 1, 0]
+//      dictionary: ["bar", "foo"]
+//
+// The indices in principle may be any integer type.
+type Dictionary struct {
+	array
+
+	indices Interface
+	dict    Interface
+}
+
+// NewDictionaryArray constructs a dictionary array with the provided indices
+// and dictionary using the given type.
+func NewDictionaryArray(typ arrow.DataType, indices, dict Interface) *Dictionary {
+	a := &Dictionary{}
+	a.array.refCount = 1
+	dictdata := NewData(typ, indices.Len(), indices.Data().Buffers(), indices.Data().Children(), indices.NullN(), indices.Data().Offset())
+	dictdata.dictionary = dict.Data().(*Data)
+	dict.Data().Retain()
+
+	defer dictdata.Release()
+	a.setData(dictdata)
+	return a
+}
+
+// checkIndexBounds returns an error if any value in the provided integer
+// arraydata is >= the passed upperlimit or < 0. otherwise nil
+func checkIndexBounds(indices *Data, upperlimit uint64) error {
+	if indices.length == 0 {
+		return nil
+	}
+
+	var maxval uint64
+	switch indices.dtype.ID() {
+	case arrow.UINT8:
+		maxval = math.MaxUint8
+	case arrow.UINT16:
+		maxval = math.MaxUint16
+	case arrow.UINT32:
+		maxval = math.MaxUint32
+	case arrow.UINT64:
+		maxval = math.MaxUint64
+	}
+	isSigned := maxval == 0
+	if !isSigned && upperlimit > maxval {
+		return nil
+	}
+
+	// TODO(mtopol): lift BitSetRunReader from parquet to utils
+	// and use it here for performance improvement.
+	var nullbitmap []byte
+	if indices.buffers[0] != nil {
+		nullbitmap = indices.buffers[0].Bytes()
+	}
+
+	var outOfBounds func(i int) error
+	switch indices.dtype.ID() {
+	case arrow.INT8:
+		data := arrow.Int8Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] < 0 || data[i] >= int8(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.UINT8:
+		data := arrow.Uint8Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] >= uint8(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.INT16:
+		data := arrow.Int16Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] < 0 || data[i] >= int16(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.UINT16:
+		data := arrow.Uint16Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] >= uint16(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.INT32:
+		data := arrow.Int32Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] < 0 || data[i] >= int32(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.UINT32:
+		data := arrow.Uint32Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] >= uint32(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.INT64:
+		data := arrow.Int64Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] < 0 || data[i] >= int64(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.UINT64:
+		data := arrow.Uint64Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] >= upperlimit {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	default:
+		return fmt.Errorf("invalid type for bounds checking: %T", indices.dtype)
+	}
+
+	for i := 0; i < indices.length; i++ {
+		if len(nullbitmap) > 0 && bitutil.BitIsNotSet(nullbitmap, i+indices.offset) {
+			continue
+		}
+
+		if err := outOfBounds(i + indices.offset); err != nil {
+			return err
+		}
+	}
+	return nil
+}
+
+// NewValidatedDictionaryArray constructs a dictionary array from the provided indices
+// and dictionary arrays, while also performing validation checks to ensure correctness
+// such as bounds checking at are usually skipped for performance.
+func NewValidatedDictionaryArray(typ *arrow.DictionaryType, indices, dict Interface) (*Dictionary, error) {
+	if indices.DataType().ID() != typ.IndexType.ID() {
+		return nil, fmt.Errorf("dictionary type index (%T) does not match indices array type (%T)", typ.IndexType, indices.DataType())
+	}
+
+	if !arrow.TypeEqual(typ.ValueType, dict.DataType()) {
+		return nil, fmt.Errorf("dictionary value type (%T) does not match dict array type (%T)", typ.ValueType, dict.DataType())
+	}
+
+	if err := checkIndexBounds(indices.Data().(*Data), uint64(dict.Len())); err != nil {
+		return nil, err
+	}
+
+	return NewDictionaryArray(typ, indices, dict), nil
+}
+
+// NewDictionaryData creates a strongly typed Dictionary array from
+// an ArrayData object with a datatype of arrow.Dictionary and a dictionary
+func NewDictionaryData(data arrow.ArrayData) *Dictionary {
+	a := &Dictionary{}
+	a.refCount = 1
+	a.setData(data.(*Data))
+	return a
+}
+
+func (d *Dictionary) Retain() {
+	atomic.AddInt64(&d.refCount, 1)
+}
+
+func (d *Dictionary) Release() {
+	debug.Assert(atomic.LoadInt64(&d.refCount) > 0, "too many releases")
+
+	if atomic.AddInt64(&d.refCount, -1) == 0 {
+		d.data.Release()
+		d.data, d.nullBitmapBytes = nil, nil
+		d.indices.Release()
+		d.indices = nil
+		if d.dict != nil {
+			d.dict.Release()
+			d.dict = nil
+		}
+	}
+}
+
+func (d *Dictionary) setData(data *Data) {
+	d.array.setData(data)
+
+	if data.dictionary == nil {
+		panic("arrow/array: no dictionary set in Data for Dictionary array")
+	}
+
+	dictType := data.dtype.(*arrow.DictionaryType)
+	debug.Assert(arrow.TypeEqual(dictType.ValueType, data.dictionary.DataType()), "mismatched dictionary value types")
+
+	indexData := NewData(dictType.IndexType, data.length, data.buffers, data.childData, data.nulls, data.offset)
+	defer indexData.Release()
+	d.indices = MakeFromData(indexData)
+}
+
+// Dictionary returns the values array that makes up the dictionary for this
+// array.
+func (d *Dictionary) Dictionary() Interface {
+	if d.dict == nil {
+		d.dict = MakeFromData(d.data.dictionary)
+	}
+	return d.dict
+}
+
+// Indices returns the underlying array of indices as it's own array
+func (d *Dictionary) Indices() Interface {
+	return d.indices
+}
+
+// CanCompareIndices returns true if the dictionary arrays can be compared
+// without having to unify the dictionaries themselves first.
+func (d *Dictionary) CanCompareIndices(other *Dictionary) bool {
+	if !arrow.TypeEqual(d.indices.DataType(), other.indices.DataType()) {
+		return false
+	}
+
+	minlen := int64(min(d.data.dictionary.length, other.data.dictionary.length))
+	return ArraySliceEqual(d.Dictionary(), 0, minlen, other.Dictionary(), 0, minlen)
+}
+
+func (d *Dictionary) String() string {
+	return fmt.Sprintf("{ dictionary: %v\n  indices: %v }", d.Dictionary(), d.Indices())
+}
+
+// GetValueIndex returns the dictionary index for the value at index i of the array.
+// The actual value can be retrieved by using d.Dictionary().(valuetype).Value(d.GetValueIndex(i))
+func (d *Dictionary) GetValueIndex(i int) int {
+	indiceData := d.data.buffers[1].Bytes()
+	// we know the value is non-negative per the spec, so
+	// we can use the unsigned value regardless.
+	switch d.indices.DataType().ID() {
+	case arrow.UINT8, arrow.INT8:
+		return int(uint8(indiceData[d.data.offset+i]))
+	case arrow.UINT16, arrow.INT16:
+		return int(arrow.Uint16Traits.CastFromBytes(indiceData)[d.data.offset+i])
+	case arrow.UINT32, arrow.INT32:
+		return int(arrow.Uint32Traits.CastFromBytes(indiceData)[d.data.offset+i])
+	case arrow.UINT64, arrow.INT64:
+		return int(arrow.Uint64Traits.CastFromBytes(indiceData)[d.data.offset+i])

Review comment:
       unlikely to hit this in practice but doesn't this potentially truncate the index?




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] emkornfield commented on a change in pull request #12158: ARROW-3039: [Go] Add support for DictionaryArray

Posted by GitBox <gi...@apache.org>.
emkornfield commented on a change in pull request #12158:
URL: https://github.com/apache/arrow/pull/12158#discussion_r800129983



##########
File path: go/arrow/ipc/file_reader.go
##########
@@ -157,22 +162,9 @@ func (f *FileReader) readSchema() error {
 			return err
 		}
 
-		id, dict, err := readDictionary(msg.meta, f.fields, f.r)
-		msg.Release()
-		if err != nil {
-			return xerrors.Errorf("arrow/ipc: could not read dictionary %d from file: %w", i, err)
+		if _, err = readDictionary(&f.memo, msg.meta, bytes.NewReader(msg.body.Bytes()), f.mem); err != nil {

Review comment:
       I might have also missed it but is Kind of dictionary used anywhere?




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] brancz commented on pull request #12158: ARROW-3039: [Go] Add support for DictionaryArray

Posted by GitBox <gi...@apache.org>.
brancz commented on pull request #12158:
URL: https://github.com/apache/arrow/pull/12158#issuecomment-1027935601


   That makes sense, thank you for elaborating!


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] emkornfield commented on a change in pull request #12158: ARROW-3039: [Go] Add support for DictionaryArray

Posted by GitBox <gi...@apache.org>.
emkornfield commented on a change in pull request #12158:
URL: https://github.com/apache/arrow/pull/12158#discussion_r800128161



##########
File path: go/arrow/array/dictionary.go
##########
@@ -0,0 +1,1305 @@
+// 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 array
+
+import (
+	"errors"
+	"fmt"
+	"math"
+	"sync/atomic"
+	"unsafe"
+
+	"github.com/apache/arrow/go/v7/arrow"
+	"github.com/apache/arrow/go/v7/arrow/bitutil"
+	"github.com/apache/arrow/go/v7/arrow/decimal128"
+	"github.com/apache/arrow/go/v7/arrow/float16"
+	"github.com/apache/arrow/go/v7/arrow/internal/debug"
+	"github.com/apache/arrow/go/v7/arrow/memory"
+	"github.com/apache/arrow/go/v7/internal/hashing"
+	"github.com/goccy/go-json"
+)
+
+// Dictionary represents the type for dictionary-encoded data with a data
+// dependent dictionary.
+//
+// A dictionary array contains an array of non-negative integers (the "dictionary"
+// indices") along with a data type containing a "dictionary" corresponding to
+// the distinct values represented in the data.
+//
+// For example, the array:
+//
+//      ["foo", "bar", "foo", "bar", "foo", "bar"]
+//
+// with dictionary ["bar", "foo"], would have the representation of:
+//
+//      indices: [1, 0, 1, 0, 1, 0]
+//      dictionary: ["bar", "foo"]
+//
+// The indices in principle may be any integer type.
+type Dictionary struct {
+	array
+
+	indices Interface
+	dict    Interface
+}
+
+// NewDictionaryArray constructs a dictionary array with the provided indices
+// and dictionary using the given type.
+func NewDictionaryArray(typ arrow.DataType, indices, dict Interface) *Dictionary {
+	a := &Dictionary{}
+	a.array.refCount = 1
+	dictdata := NewData(typ, indices.Len(), indices.Data().Buffers(), indices.Data().Children(), indices.NullN(), indices.Data().Offset())
+	dictdata.dictionary = dict.Data().(*Data)
+	dict.Data().Retain()
+
+	defer dictdata.Release()
+	a.setData(dictdata)
+	return a
+}
+
+// checkIndexBounds returns an error if any value in the provided integer
+// arraydata is >= the passed upperlimit or < 0. otherwise nil
+func checkIndexBounds(indices *Data, upperlimit uint64) error {
+	if indices.length == 0 {
+		return nil
+	}
+
+	var maxval uint64
+	switch indices.dtype.ID() {
+	case arrow.UINT8:

Review comment:
       This needs signed cased  also?
   
   From the spec
   
   ```
   Since unsigned integers can be more difficult to work with in some cases (e.g. in the JVM), we recommend preferring signed integers over unsigned integers for representing dictionary indices. Additionally, we recommend avoiding using 64-bit unsigned integer indices unless they are required by an application.
   ```




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] emkornfield commented on a change in pull request #12158: ARROW-3039: [Go] Add support for DictionaryArray

Posted by GitBox <gi...@apache.org>.
emkornfield commented on a change in pull request #12158:
URL: https://github.com/apache/arrow/pull/12158#discussion_r800128243



##########
File path: go/arrow/array/dictionary.go
##########
@@ -0,0 +1,1305 @@
+// 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 array
+
+import (
+	"errors"
+	"fmt"
+	"math"
+	"sync/atomic"
+	"unsafe"
+
+	"github.com/apache/arrow/go/v7/arrow"
+	"github.com/apache/arrow/go/v7/arrow/bitutil"
+	"github.com/apache/arrow/go/v7/arrow/decimal128"
+	"github.com/apache/arrow/go/v7/arrow/float16"
+	"github.com/apache/arrow/go/v7/arrow/internal/debug"
+	"github.com/apache/arrow/go/v7/arrow/memory"
+	"github.com/apache/arrow/go/v7/internal/hashing"
+	"github.com/goccy/go-json"
+)
+
+// Dictionary represents the type for dictionary-encoded data with a data
+// dependent dictionary.
+//
+// A dictionary array contains an array of non-negative integers (the "dictionary"
+// indices") along with a data type containing a "dictionary" corresponding to
+// the distinct values represented in the data.
+//
+// For example, the array:
+//
+//      ["foo", "bar", "foo", "bar", "foo", "bar"]
+//
+// with dictionary ["bar", "foo"], would have the representation of:
+//
+//      indices: [1, 0, 1, 0, 1, 0]
+//      dictionary: ["bar", "foo"]
+//
+// The indices in principle may be any integer type.
+type Dictionary struct {
+	array
+
+	indices Interface
+	dict    Interface
+}
+
+// NewDictionaryArray constructs a dictionary array with the provided indices
+// and dictionary using the given type.
+func NewDictionaryArray(typ arrow.DataType, indices, dict Interface) *Dictionary {
+	a := &Dictionary{}
+	a.array.refCount = 1
+	dictdata := NewData(typ, indices.Len(), indices.Data().Buffers(), indices.Data().Children(), indices.NullN(), indices.Data().Offset())
+	dictdata.dictionary = dict.Data().(*Data)
+	dict.Data().Retain()
+
+	defer dictdata.Release()
+	a.setData(dictdata)
+	return a
+}
+
+// checkIndexBounds returns an error if any value in the provided integer
+// arraydata is >= the passed upperlimit or < 0. otherwise nil
+func checkIndexBounds(indices *Data, upperlimit uint64) error {

Review comment:
       nit: probably will never happen in practice but upperlimit could be awkward here for comparison again int64 in case of overflow (I think I'm OK ignoring it).




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] emkornfield commented on a change in pull request #12158: ARROW-3039: [Go] Add support for DictionaryArray

Posted by GitBox <gi...@apache.org>.
emkornfield commented on a change in pull request #12158:
URL: https://github.com/apache/arrow/pull/12158#discussion_r800129769



##########
File path: go/arrow/ipc/file_reader.go
##########
@@ -157,22 +162,9 @@ func (f *FileReader) readSchema() error {
 			return err
 		}
 
-		id, dict, err := readDictionary(msg.meta, f.fields, f.r)
-		msg.Release()
-		if err != nil {
-			return xerrors.Errorf("arrow/ipc: could not read dictionary %d from file: %w", i, err)
+		if _, err = readDictionary(&f.memo, msg.meta, bytes.NewReader(msg.body.Bytes()), f.mem); err != nil {

Review comment:
       might be worth a comment on why update or delta is ignored? (maybe also validate that it is of the expected type).




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] emkornfield commented on a change in pull request #12158: ARROW-3039: [Go] Add support for DictionaryArray

Posted by GitBox <gi...@apache.org>.
emkornfield commented on a change in pull request #12158:
URL: https://github.com/apache/arrow/pull/12158#discussion_r800127832



##########
File path: go/arrow/array/data.go
##########
@@ -29,13 +29,14 @@ import (
 
 // Data represents the memory and metadata of an Arrow array.
 type Data struct {
-	refCount  int64
-	dtype     arrow.DataType
-	nulls     int
-	offset    int
-	length    int
-	buffers   []*memory.Buffer  // TODO(sgc): should this be an interface?
-	childData []arrow.ArrayData // TODO(sgc): managed by ListArray, StructArray and UnionArray types
+	refCount   int64
+	dtype      arrow.DataType
+	nulls      int
+	offset     int
+	length     int
+	buffers    []*memory.Buffer  // TODO(sgc): should this be an interface?
+	childData  []arrow.ArrayData // TODO(sgc): managed by ListArray, StructArray and UnionArray types
+	dictionary *Data             // only populated for dictionary arrays

Review comment:
       maybe expand the comment  to elaborate that for dictionary arrays buffers will contain nullability and indexes  that reference elements in this variable? (and childdata would be empty)




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] emkornfield commented on a change in pull request #12158: ARROW-3039: [Go] Add support for DictionaryArray

Posted by GitBox <gi...@apache.org>.
emkornfield commented on a change in pull request #12158:
URL: https://github.com/apache/arrow/pull/12158#discussion_r800127568



##########
File path: dev/archery/archery/integration/datagen.py
##########
@@ -1620,24 +1620,20 @@ def _temp_path():
 
         # TODO(ARROW-3039, ARROW-5267): Dictionaries in GO
         generate_dictionary_case()
-        .skip_category('C#')
-        .skip_category('Go'),
+        .skip_category('C#'),

Review comment:
       :)




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] zeroshade commented on pull request #12158: ARROW-3039: [Go] Add support for DictionaryArray

Posted by GitBox <gi...@apache.org>.
zeroshade commented on pull request #12158:
URL: https://github.com/apache/arrow/pull/12158#issuecomment-1025935325


   Hey @brancz The reason for a lack of `StringDictionaryBuilder` is that it's really just a special case of the `BinaryDictionaryBuilder` which can be instantiated with the proper `arrow.DataType` and accepts adding either `[]byte` or `string`. So rather than create a separate `StringDictionaryBuilder` I just rolled it into that. Alternatively I could create a `StringDictionaryBuilder` which is just an alias to the `BinaryDictionaryBuilder` if that might be easier to understand?
   
   As for Lists, in the most technical sense nothing in the Arrow format spec prohibits or prevents using a List array as a dictionary. I just simply didn't implement it yet in this PR as that is not a case covered by the integration tests.
   
   I'd love any feedback on the API from real world usage! I'm still waiting on people looking through and reviewing this and so on, and was aiming to not merge this until after arrow version 7.0.0 gets released anyways. So i'd integrate any feedback you have into this PR. Looking forward to it and thanks for checking this out!


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] brancz edited a comment on pull request #12158: ARROW-3039: [Go] Add support for DictionaryArray

Posted by GitBox <gi...@apache.org>.
brancz edited a comment on pull request #12158:
URL: https://github.com/apache/arrow/pull/12158#issuecomment-1024624600


   Hey! I stumbled on this PR since I was looking for dictionary support, and I was wondering why there wasn't a `StringDictionaryBuilder`, but almost everything else? Or is one just supposed to use the `Dictionary` type directly for that? The other case I have that I'd want to use dictionaries for is Lists, as in a dictionary of common lists seen before, does that even work with Dictionaries? (sorry if the second one is a more general question than about this PR)
   
   Will report on usage of the API once we start trying it out!


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] zeroshade commented on a change in pull request #12158: ARROW-3039: [Go] Add support for DictionaryArray

Posted by GitBox <gi...@apache.org>.
zeroshade commented on a change in pull request #12158:
URL: https://github.com/apache/arrow/pull/12158#discussion_r828298266



##########
File path: go/arrow/array/dictionary.go
##########
@@ -0,0 +1,1305 @@
+// 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 array
+
+import (
+	"errors"
+	"fmt"
+	"math"
+	"sync/atomic"
+	"unsafe"
+
+	"github.com/apache/arrow/go/v7/arrow"
+	"github.com/apache/arrow/go/v7/arrow/bitutil"
+	"github.com/apache/arrow/go/v7/arrow/decimal128"
+	"github.com/apache/arrow/go/v7/arrow/float16"
+	"github.com/apache/arrow/go/v7/arrow/internal/debug"
+	"github.com/apache/arrow/go/v7/arrow/memory"
+	"github.com/apache/arrow/go/v7/internal/hashing"
+	"github.com/goccy/go-json"
+)
+
+// Dictionary represents the type for dictionary-encoded data with a data
+// dependent dictionary.
+//
+// A dictionary array contains an array of non-negative integers (the "dictionary"
+// indices") along with a data type containing a "dictionary" corresponding to
+// the distinct values represented in the data.
+//
+// For example, the array:
+//
+//      ["foo", "bar", "foo", "bar", "foo", "bar"]
+//
+// with dictionary ["bar", "foo"], would have the representation of:
+//
+//      indices: [1, 0, 1, 0, 1, 0]
+//      dictionary: ["bar", "foo"]
+//
+// The indices in principle may be any integer type.
+type Dictionary struct {
+	array
+
+	indices Interface
+	dict    Interface
+}
+
+// NewDictionaryArray constructs a dictionary array with the provided indices
+// and dictionary using the given type.
+func NewDictionaryArray(typ arrow.DataType, indices, dict Interface) *Dictionary {
+	a := &Dictionary{}
+	a.array.refCount = 1
+	dictdata := NewData(typ, indices.Len(), indices.Data().Buffers(), indices.Data().Children(), indices.NullN(), indices.Data().Offset())
+	dictdata.dictionary = dict.Data().(*Data)
+	dict.Data().Retain()
+
+	defer dictdata.Release()
+	a.setData(dictdata)
+	return a
+}
+
+// checkIndexBounds returns an error if any value in the provided integer
+// arraydata is >= the passed upperlimit or < 0. otherwise nil
+func checkIndexBounds(indices *Data, upperlimit uint64) error {
+	if indices.length == 0 {
+		return nil
+	}
+
+	var maxval uint64
+	switch indices.dtype.ID() {
+	case arrow.UINT8:
+		maxval = math.MaxUint8
+	case arrow.UINT16:
+		maxval = math.MaxUint16
+	case arrow.UINT32:
+		maxval = math.MaxUint32
+	case arrow.UINT64:
+		maxval = math.MaxUint64
+	}
+	isSigned := maxval == 0
+	if !isSigned && upperlimit > maxval {
+		return nil
+	}
+
+	// TODO(mtopol): lift BitSetRunReader from parquet to utils
+	// and use it here for performance improvement.
+	var nullbitmap []byte
+	if indices.buffers[0] != nil {
+		nullbitmap = indices.buffers[0].Bytes()
+	}
+
+	var outOfBounds func(i int) error
+	switch indices.dtype.ID() {
+	case arrow.INT8:
+		data := arrow.Int8Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] < 0 || data[i] >= int8(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.UINT8:
+		data := arrow.Uint8Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] >= uint8(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.INT16:
+		data := arrow.Int16Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] < 0 || data[i] >= int16(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.UINT16:
+		data := arrow.Uint16Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] >= uint16(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.INT32:
+		data := arrow.Int32Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] < 0 || data[i] >= int32(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.UINT32:
+		data := arrow.Uint32Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] >= uint32(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.INT64:
+		data := arrow.Int64Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] < 0 || data[i] >= int64(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.UINT64:
+		data := arrow.Uint64Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] >= upperlimit {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	default:
+		return fmt.Errorf("invalid type for bounds checking: %T", indices.dtype)
+	}
+
+	for i := 0; i < indices.length; i++ {
+		if len(nullbitmap) > 0 && bitutil.BitIsNotSet(nullbitmap, i+indices.offset) {
+			continue
+		}
+
+		if err := outOfBounds(i + indices.offset); err != nil {
+			return err
+		}
+	}
+	return nil
+}
+
+// NewValidatedDictionaryArray constructs a dictionary array from the provided indices
+// and dictionary arrays, while also performing validation checks to ensure correctness
+// such as bounds checking at are usually skipped for performance.
+func NewValidatedDictionaryArray(typ *arrow.DictionaryType, indices, dict Interface) (*Dictionary, error) {
+	if indices.DataType().ID() != typ.IndexType.ID() {
+		return nil, fmt.Errorf("dictionary type index (%T) does not match indices array type (%T)", typ.IndexType, indices.DataType())
+	}
+
+	if !arrow.TypeEqual(typ.ValueType, dict.DataType()) {
+		return nil, fmt.Errorf("dictionary value type (%T) does not match dict array type (%T)", typ.ValueType, dict.DataType())
+	}
+
+	if err := checkIndexBounds(indices.Data().(*Data), uint64(dict.Len())); err != nil {
+		return nil, err
+	}
+
+	return NewDictionaryArray(typ, indices, dict), nil
+}
+
+// NewDictionaryData creates a strongly typed Dictionary array from
+// an ArrayData object with a datatype of arrow.Dictionary and a dictionary
+func NewDictionaryData(data arrow.ArrayData) *Dictionary {
+	a := &Dictionary{}
+	a.refCount = 1
+	a.setData(data.(*Data))
+	return a
+}
+
+func (d *Dictionary) Retain() {
+	atomic.AddInt64(&d.refCount, 1)
+}
+
+func (d *Dictionary) Release() {
+	debug.Assert(atomic.LoadInt64(&d.refCount) > 0, "too many releases")
+
+	if atomic.AddInt64(&d.refCount, -1) == 0 {
+		d.data.Release()
+		d.data, d.nullBitmapBytes = nil, nil
+		d.indices.Release()
+		d.indices = nil
+		if d.dict != nil {
+			d.dict.Release()
+			d.dict = nil
+		}
+	}
+}
+
+func (d *Dictionary) setData(data *Data) {
+	d.array.setData(data)
+
+	if data.dictionary == nil {
+		panic("arrow/array: no dictionary set in Data for Dictionary array")
+	}
+
+	dictType := data.dtype.(*arrow.DictionaryType)
+	debug.Assert(arrow.TypeEqual(dictType.ValueType, data.dictionary.DataType()), "mismatched dictionary value types")
+
+	indexData := NewData(dictType.IndexType, data.length, data.buffers, data.childData, data.nulls, data.offset)
+	defer indexData.Release()
+	d.indices = MakeFromData(indexData)
+}
+
+// Dictionary returns the values array that makes up the dictionary for this
+// array.
+func (d *Dictionary) Dictionary() Interface {
+	if d.dict == nil {
+		d.dict = MakeFromData(d.data.dictionary)
+	}
+	return d.dict
+}
+
+// Indices returns the underlying array of indices as it's own array
+func (d *Dictionary) Indices() Interface {
+	return d.indices
+}
+
+// CanCompareIndices returns true if the dictionary arrays can be compared
+// without having to unify the dictionaries themselves first.
+func (d *Dictionary) CanCompareIndices(other *Dictionary) bool {
+	if !arrow.TypeEqual(d.indices.DataType(), other.indices.DataType()) {
+		return false
+	}
+
+	minlen := int64(min(d.data.dictionary.length, other.data.dictionary.length))
+	return ArraySliceEqual(d.Dictionary(), 0, minlen, other.Dictionary(), 0, minlen)
+}
+
+func (d *Dictionary) String() string {
+	return fmt.Sprintf("{ dictionary: %v\n  indices: %v }", d.Dictionary(), d.Indices())
+}
+
+// GetValueIndex returns the dictionary index for the value at index i of the array.
+// The actual value can be retrieved by using d.Dictionary().(valuetype).Value(d.GetValueIndex(i))
+func (d *Dictionary) GetValueIndex(i int) int {
+	indiceData := d.data.buffers[1].Bytes()
+	// we know the value is non-negative per the spec, so
+	// we can use the unsigned value regardless.
+	switch d.indices.DataType().ID() {
+	case arrow.UINT8, arrow.INT8:
+		return int(uint8(indiceData[d.data.offset+i]))
+	case arrow.UINT16, arrow.INT16:
+		return int(arrow.Uint16Traits.CastFromBytes(indiceData)[d.data.offset+i])
+	case arrow.UINT32, arrow.INT32:
+		return int(arrow.Uint32Traits.CastFromBytes(indiceData)[d.data.offset+i])
+	case arrow.UINT64, arrow.INT64:
+		return int(arrow.Uint64Traits.CastFromBytes(indiceData)[d.data.offset+i])

Review comment:
       fair point. On a 64-bit machine if you have uint64 indexes and the value is larger than can fit in an int64 it would truncate. 
   
   On a 32-bit machine this'll truncate for any 64-bit index type and for uint32 indexes that are larger than an int32. I guess I should change this to return a uint64 instead? so that we know we never truncate? What do you think?




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] zeroshade commented on a change in pull request #12158: ARROW-3039: [Go] Add support for DictionaryArray

Posted by GitBox <gi...@apache.org>.
zeroshade commented on a change in pull request #12158:
URL: https://github.com/apache/arrow/pull/12158#discussion_r829393914



##########
File path: go/arrow/array/dictionary.go
##########
@@ -0,0 +1,1305 @@
+// 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 array
+
+import (
+	"errors"
+	"fmt"
+	"math"
+	"sync/atomic"
+	"unsafe"
+
+	"github.com/apache/arrow/go/v7/arrow"
+	"github.com/apache/arrow/go/v7/arrow/bitutil"
+	"github.com/apache/arrow/go/v7/arrow/decimal128"
+	"github.com/apache/arrow/go/v7/arrow/float16"
+	"github.com/apache/arrow/go/v7/arrow/internal/debug"
+	"github.com/apache/arrow/go/v7/arrow/memory"
+	"github.com/apache/arrow/go/v7/internal/hashing"
+	"github.com/goccy/go-json"
+)
+
+// Dictionary represents the type for dictionary-encoded data with a data
+// dependent dictionary.
+//
+// A dictionary array contains an array of non-negative integers (the "dictionary"
+// indices") along with a data type containing a "dictionary" corresponding to
+// the distinct values represented in the data.
+//
+// For example, the array:
+//
+//      ["foo", "bar", "foo", "bar", "foo", "bar"]
+//
+// with dictionary ["bar", "foo"], would have the representation of:
+//
+//      indices: [1, 0, 1, 0, 1, 0]
+//      dictionary: ["bar", "foo"]
+//
+// The indices in principle may be any integer type.
+type Dictionary struct {
+	array
+
+	indices Interface
+	dict    Interface
+}
+
+// NewDictionaryArray constructs a dictionary array with the provided indices
+// and dictionary using the given type.
+func NewDictionaryArray(typ arrow.DataType, indices, dict Interface) *Dictionary {
+	a := &Dictionary{}
+	a.array.refCount = 1
+	dictdata := NewData(typ, indices.Len(), indices.Data().Buffers(), indices.Data().Children(), indices.NullN(), indices.Data().Offset())
+	dictdata.dictionary = dict.Data().(*Data)
+	dict.Data().Retain()
+
+	defer dictdata.Release()
+	a.setData(dictdata)
+	return a
+}
+
+// checkIndexBounds returns an error if any value in the provided integer
+// arraydata is >= the passed upperlimit or < 0. otherwise nil
+func checkIndexBounds(indices *Data, upperlimit uint64) error {
+	if indices.length == 0 {
+		return nil
+	}
+
+	var maxval uint64
+	switch indices.dtype.ID() {
+	case arrow.UINT8:
+		maxval = math.MaxUint8
+	case arrow.UINT16:
+		maxval = math.MaxUint16
+	case arrow.UINT32:
+		maxval = math.MaxUint32
+	case arrow.UINT64:
+		maxval = math.MaxUint64
+	}
+	isSigned := maxval == 0
+	if !isSigned && upperlimit > maxval {
+		return nil
+	}
+
+	// TODO(mtopol): lift BitSetRunReader from parquet to utils
+	// and use it here for performance improvement.
+	var nullbitmap []byte
+	if indices.buffers[0] != nil {
+		nullbitmap = indices.buffers[0].Bytes()
+	}
+
+	var outOfBounds func(i int) error
+	switch indices.dtype.ID() {
+	case arrow.INT8:
+		data := arrow.Int8Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] < 0 || data[i] >= int8(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.UINT8:
+		data := arrow.Uint8Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] >= uint8(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.INT16:
+		data := arrow.Int16Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] < 0 || data[i] >= int16(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.UINT16:
+		data := arrow.Uint16Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] >= uint16(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.INT32:
+		data := arrow.Int32Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] < 0 || data[i] >= int32(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.UINT32:
+		data := arrow.Uint32Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] >= uint32(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.INT64:
+		data := arrow.Int64Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] < 0 || data[i] >= int64(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.UINT64:
+		data := arrow.Uint64Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] >= upperlimit {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	default:
+		return fmt.Errorf("invalid type for bounds checking: %T", indices.dtype)
+	}
+
+	for i := 0; i < indices.length; i++ {
+		if len(nullbitmap) > 0 && bitutil.BitIsNotSet(nullbitmap, i+indices.offset) {
+			continue
+		}
+
+		if err := outOfBounds(i + indices.offset); err != nil {
+			return err
+		}
+	}
+	return nil
+}
+
+// NewValidatedDictionaryArray constructs a dictionary array from the provided indices
+// and dictionary arrays, while also performing validation checks to ensure correctness
+// such as bounds checking at are usually skipped for performance.
+func NewValidatedDictionaryArray(typ *arrow.DictionaryType, indices, dict Interface) (*Dictionary, error) {
+	if indices.DataType().ID() != typ.IndexType.ID() {
+		return nil, fmt.Errorf("dictionary type index (%T) does not match indices array type (%T)", typ.IndexType, indices.DataType())
+	}
+
+	if !arrow.TypeEqual(typ.ValueType, dict.DataType()) {
+		return nil, fmt.Errorf("dictionary value type (%T) does not match dict array type (%T)", typ.ValueType, dict.DataType())
+	}
+
+	if err := checkIndexBounds(indices.Data().(*Data), uint64(dict.Len())); err != nil {
+		return nil, err
+	}
+
+	return NewDictionaryArray(typ, indices, dict), nil
+}
+
+// NewDictionaryData creates a strongly typed Dictionary array from
+// an ArrayData object with a datatype of arrow.Dictionary and a dictionary
+func NewDictionaryData(data arrow.ArrayData) *Dictionary {
+	a := &Dictionary{}
+	a.refCount = 1
+	a.setData(data.(*Data))
+	return a
+}
+
+func (d *Dictionary) Retain() {
+	atomic.AddInt64(&d.refCount, 1)
+}
+
+func (d *Dictionary) Release() {
+	debug.Assert(atomic.LoadInt64(&d.refCount) > 0, "too many releases")
+
+	if atomic.AddInt64(&d.refCount, -1) == 0 {
+		d.data.Release()
+		d.data, d.nullBitmapBytes = nil, nil
+		d.indices.Release()
+		d.indices = nil
+		if d.dict != nil {
+			d.dict.Release()
+			d.dict = nil
+		}
+	}
+}
+
+func (d *Dictionary) setData(data *Data) {
+	d.array.setData(data)
+
+	if data.dictionary == nil {
+		panic("arrow/array: no dictionary set in Data for Dictionary array")
+	}
+
+	dictType := data.dtype.(*arrow.DictionaryType)
+	debug.Assert(arrow.TypeEqual(dictType.ValueType, data.dictionary.DataType()), "mismatched dictionary value types")
+
+	indexData := NewData(dictType.IndexType, data.length, data.buffers, data.childData, data.nulls, data.offset)
+	defer indexData.Release()
+	d.indices = MakeFromData(indexData)
+}
+
+// Dictionary returns the values array that makes up the dictionary for this
+// array.
+func (d *Dictionary) Dictionary() Interface {
+	if d.dict == nil {
+		d.dict = MakeFromData(d.data.dictionary)
+	}
+	return d.dict
+}
+
+// Indices returns the underlying array of indices as it's own array
+func (d *Dictionary) Indices() Interface {
+	return d.indices
+}
+
+// CanCompareIndices returns true if the dictionary arrays can be compared
+// without having to unify the dictionaries themselves first.

Review comment:
       Clarified

##########
File path: go/arrow/array/data.go
##########
@@ -29,13 +29,14 @@ import (
 
 // Data represents the memory and metadata of an Arrow array.
 type Data struct {
-	refCount  int64
-	dtype     arrow.DataType
-	nulls     int
-	offset    int
-	length    int
-	buffers   []*memory.Buffer  // TODO(sgc): should this be an interface?
-	childData []arrow.ArrayData // TODO(sgc): managed by ListArray, StructArray and UnionArray types
+	refCount   int64
+	dtype      arrow.DataType
+	nulls      int
+	offset     int
+	length     int
+	buffers    []*memory.Buffer  // TODO(sgc): should this be an interface?
+	childData  []arrow.ArrayData // TODO(sgc): managed by ListArray, StructArray and UnionArray types
+	dictionary *Data             // only populated for dictionary arrays

Review comment:
       done

##########
File path: go/arrow/array/dictionary.go
##########
@@ -0,0 +1,1305 @@
+// 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 array
+
+import (
+	"errors"
+	"fmt"
+	"math"
+	"sync/atomic"
+	"unsafe"
+
+	"github.com/apache/arrow/go/v7/arrow"
+	"github.com/apache/arrow/go/v7/arrow/bitutil"
+	"github.com/apache/arrow/go/v7/arrow/decimal128"
+	"github.com/apache/arrow/go/v7/arrow/float16"
+	"github.com/apache/arrow/go/v7/arrow/internal/debug"
+	"github.com/apache/arrow/go/v7/arrow/memory"
+	"github.com/apache/arrow/go/v7/internal/hashing"
+	"github.com/goccy/go-json"
+)
+
+// Dictionary represents the type for dictionary-encoded data with a data
+// dependent dictionary.
+//
+// A dictionary array contains an array of non-negative integers (the "dictionary"
+// indices") along with a data type containing a "dictionary" corresponding to
+// the distinct values represented in the data.
+//
+// For example, the array:
+//
+//      ["foo", "bar", "foo", "bar", "foo", "bar"]
+//
+// with dictionary ["bar", "foo"], would have the representation of:
+//
+//      indices: [1, 0, 1, 0, 1, 0]
+//      dictionary: ["bar", "foo"]
+//
+// The indices in principle may be any integer type.
+type Dictionary struct {
+	array
+
+	indices Interface
+	dict    Interface
+}
+
+// NewDictionaryArray constructs a dictionary array with the provided indices
+// and dictionary using the given type.
+func NewDictionaryArray(typ arrow.DataType, indices, dict Interface) *Dictionary {
+	a := &Dictionary{}
+	a.array.refCount = 1
+	dictdata := NewData(typ, indices.Len(), indices.Data().Buffers(), indices.Data().Children(), indices.NullN(), indices.Data().Offset())
+	dictdata.dictionary = dict.Data().(*Data)
+	dict.Data().Retain()
+
+	defer dictdata.Release()
+	a.setData(dictdata)
+	return a
+}
+
+// checkIndexBounds returns an error if any value in the provided integer
+// arraydata is >= the passed upperlimit or < 0. otherwise nil
+func checkIndexBounds(indices *Data, upperlimit uint64) error {
+	if indices.length == 0 {
+		return nil
+	}
+
+	var maxval uint64
+	switch indices.dtype.ID() {
+	case arrow.UINT8:
+		maxval = math.MaxUint8
+	case arrow.UINT16:
+		maxval = math.MaxUint16
+	case arrow.UINT32:
+		maxval = math.MaxUint32
+	case arrow.UINT64:
+		maxval = math.MaxUint64
+	}
+	isSigned := maxval == 0
+	if !isSigned && upperlimit > maxval {
+		return nil
+	}
+
+	// TODO(mtopol): lift BitSetRunReader from parquet to utils

Review comment:
       fixed

##########
File path: go/arrow/array/dictionary.go
##########
@@ -0,0 +1,1305 @@
+// 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 array
+
+import (
+	"errors"
+	"fmt"
+	"math"
+	"sync/atomic"
+	"unsafe"
+
+	"github.com/apache/arrow/go/v7/arrow"
+	"github.com/apache/arrow/go/v7/arrow/bitutil"
+	"github.com/apache/arrow/go/v7/arrow/decimal128"
+	"github.com/apache/arrow/go/v7/arrow/float16"
+	"github.com/apache/arrow/go/v7/arrow/internal/debug"
+	"github.com/apache/arrow/go/v7/arrow/memory"
+	"github.com/apache/arrow/go/v7/internal/hashing"
+	"github.com/goccy/go-json"
+)
+
+// Dictionary represents the type for dictionary-encoded data with a data
+// dependent dictionary.
+//
+// A dictionary array contains an array of non-negative integers (the "dictionary"
+// indices") along with a data type containing a "dictionary" corresponding to
+// the distinct values represented in the data.
+//
+// For example, the array:
+//
+//      ["foo", "bar", "foo", "bar", "foo", "bar"]
+//
+// with dictionary ["bar", "foo"], would have the representation of:
+//
+//      indices: [1, 0, 1, 0, 1, 0]
+//      dictionary: ["bar", "foo"]
+//
+// The indices in principle may be any integer type.
+type Dictionary struct {
+	array
+
+	indices Interface
+	dict    Interface
+}
+
+// NewDictionaryArray constructs a dictionary array with the provided indices
+// and dictionary using the given type.
+func NewDictionaryArray(typ arrow.DataType, indices, dict Interface) *Dictionary {
+	a := &Dictionary{}
+	a.array.refCount = 1
+	dictdata := NewData(typ, indices.Len(), indices.Data().Buffers(), indices.Data().Children(), indices.NullN(), indices.Data().Offset())
+	dictdata.dictionary = dict.Data().(*Data)
+	dict.Data().Retain()
+
+	defer dictdata.Release()
+	a.setData(dictdata)
+	return a
+}
+
+// checkIndexBounds returns an error if any value in the provided integer
+// arraydata is >= the passed upperlimit or < 0. otherwise nil
+func checkIndexBounds(indices *Data, upperlimit uint64) error {
+	if indices.length == 0 {
+		return nil
+	}
+
+	var maxval uint64
+	switch indices.dtype.ID() {
+	case arrow.UINT8:
+		maxval = math.MaxUint8
+	case arrow.UINT16:
+		maxval = math.MaxUint16
+	case arrow.UINT32:
+		maxval = math.MaxUint32
+	case arrow.UINT64:
+		maxval = math.MaxUint64
+	}
+	isSigned := maxval == 0
+	if !isSigned && upperlimit > maxval {
+		return nil
+	}
+
+	// TODO(mtopol): lift BitSetRunReader from parquet to utils
+	// and use it here for performance improvement.
+	var nullbitmap []byte
+	if indices.buffers[0] != nil {
+		nullbitmap = indices.buffers[0].Bytes()
+	}
+
+	var outOfBounds func(i int) error
+	switch indices.dtype.ID() {
+	case arrow.INT8:
+		data := arrow.Int8Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] < 0 || data[i] >= int8(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.UINT8:
+		data := arrow.Uint8Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] >= uint8(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.INT16:
+		data := arrow.Int16Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] < 0 || data[i] >= int16(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.UINT16:
+		data := arrow.Uint16Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] >= uint16(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.INT32:
+		data := arrow.Int32Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] < 0 || data[i] >= int32(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.UINT32:
+		data := arrow.Uint32Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] >= uint32(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.INT64:
+		data := arrow.Int64Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] < 0 || data[i] >= int64(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.UINT64:
+		data := arrow.Uint64Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] >= upperlimit {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	default:
+		return fmt.Errorf("invalid type for bounds checking: %T", indices.dtype)
+	}
+
+	for i := 0; i < indices.length; i++ {
+		if len(nullbitmap) > 0 && bitutil.BitIsNotSet(nullbitmap, i+indices.offset) {
+			continue
+		}
+
+		if err := outOfBounds(i + indices.offset); err != nil {
+			return err
+		}
+	}
+	return nil
+}
+
+// NewValidatedDictionaryArray constructs a dictionary array from the provided indices
+// and dictionary arrays, while also performing validation checks to ensure correctness
+// such as bounds checking at are usually skipped for performance.
+func NewValidatedDictionaryArray(typ *arrow.DictionaryType, indices, dict Interface) (*Dictionary, error) {
+	if indices.DataType().ID() != typ.IndexType.ID() {
+		return nil, fmt.Errorf("dictionary type index (%T) does not match indices array type (%T)", typ.IndexType, indices.DataType())
+	}
+
+	if !arrow.TypeEqual(typ.ValueType, dict.DataType()) {
+		return nil, fmt.Errorf("dictionary value type (%T) does not match dict array type (%T)", typ.ValueType, dict.DataType())
+	}
+
+	if err := checkIndexBounds(indices.Data().(*Data), uint64(dict.Len())); err != nil {
+		return nil, err
+	}
+
+	return NewDictionaryArray(typ, indices, dict), nil
+}
+
+// NewDictionaryData creates a strongly typed Dictionary array from
+// an ArrayData object with a datatype of arrow.Dictionary and a dictionary
+func NewDictionaryData(data arrow.ArrayData) *Dictionary {
+	a := &Dictionary{}
+	a.refCount = 1
+	a.setData(data.(*Data))
+	return a
+}
+
+func (d *Dictionary) Retain() {
+	atomic.AddInt64(&d.refCount, 1)
+}
+
+func (d *Dictionary) Release() {
+	debug.Assert(atomic.LoadInt64(&d.refCount) > 0, "too many releases")
+
+	if atomic.AddInt64(&d.refCount, -1) == 0 {
+		d.data.Release()
+		d.data, d.nullBitmapBytes = nil, nil
+		d.indices.Release()
+		d.indices = nil
+		if d.dict != nil {
+			d.dict.Release()
+			d.dict = nil
+		}
+	}
+}
+
+func (d *Dictionary) setData(data *Data) {
+	d.array.setData(data)
+
+	if data.dictionary == nil {
+		panic("arrow/array: no dictionary set in Data for Dictionary array")
+	}
+
+	dictType := data.dtype.(*arrow.DictionaryType)
+	debug.Assert(arrow.TypeEqual(dictType.ValueType, data.dictionary.DataType()), "mismatched dictionary value types")
+
+	indexData := NewData(dictType.IndexType, data.length, data.buffers, data.childData, data.nulls, data.offset)
+	defer indexData.Release()
+	d.indices = MakeFromData(indexData)
+}
+
+// Dictionary returns the values array that makes up the dictionary for this
+// array.
+func (d *Dictionary) Dictionary() Interface {
+	if d.dict == nil {
+		d.dict = MakeFromData(d.data.dictionary)
+	}
+	return d.dict
+}
+
+// Indices returns the underlying array of indices as it's own array
+func (d *Dictionary) Indices() Interface {
+	return d.indices
+}
+
+// CanCompareIndices returns true if the dictionary arrays can be compared
+// without having to unify the dictionaries themselves first.
+func (d *Dictionary) CanCompareIndices(other *Dictionary) bool {
+	if !arrow.TypeEqual(d.indices.DataType(), other.indices.DataType()) {
+		return false
+	}
+
+	minlen := int64(min(d.data.dictionary.length, other.data.dictionary.length))
+	return ArraySliceEqual(d.Dictionary(), 0, minlen, other.Dictionary(), 0, minlen)
+}
+
+func (d *Dictionary) String() string {
+	return fmt.Sprintf("{ dictionary: %v\n  indices: %v }", d.Dictionary(), d.Indices())
+}
+
+// GetValueIndex returns the dictionary index for the value at index i of the array.
+// The actual value can be retrieved by using d.Dictionary().(valuetype).Value(d.GetValueIndex(i))
+func (d *Dictionary) GetValueIndex(i int) int {
+	indiceData := d.data.buffers[1].Bytes()
+	// we know the value is non-negative per the spec, so
+	// we can use the unsigned value regardless.
+	switch d.indices.DataType().ID() {
+	case arrow.UINT8, arrow.INT8:
+		return int(uint8(indiceData[d.data.offset+i]))
+	case arrow.UINT16, arrow.INT16:
+		return int(arrow.Uint16Traits.CastFromBytes(indiceData)[d.data.offset+i])
+	case arrow.UINT32, arrow.INT32:
+		return int(arrow.Uint32Traits.CastFromBytes(indiceData)[d.data.offset+i])
+	case arrow.UINT64, arrow.INT64:
+		return int(arrow.Uint64Traits.CastFromBytes(indiceData)[d.data.offset+i])
+	}
+	debug.Assert(false, "unreachable dictionary index")
+	return -1
+}
+
+func (d *Dictionary) getOneForMarshal(i int) interface{} {
+	if d.IsNull(i) {
+		return nil
+	}
+	vidx := d.GetValueIndex(i)
+	return d.Dictionary().(arraymarshal).getOneForMarshal(vidx)
+}
+
+func (d *Dictionary) MarshalJSON() ([]byte, error) {
+	vals := make([]interface{}, d.Len())
+	for i := 0; i < d.Len(); i++ {
+		vals[i] = d.getOneForMarshal(i)
+	}
+	return json.Marshal(vals)
+}
+
+func arrayEqualDict(l, r *Dictionary) bool {
+	return ArrayEqual(l.Dictionary(), r.Dictionary()) && ArrayEqual(l.indices, r.indices)
+}
+
+func arrayApproxEqualDict(l, r *Dictionary, opt equalOption) bool {
+	return arrayApproxEqual(l.Dictionary(), r.Dictionary(), opt) && arrayApproxEqual(l.indices, r.indices, opt)
+}
+
+// helper for building the properly typed indices of the dictionary builder
+type indexBuilder struct {
+	Builder
+	Append func(int)
+}
+
+func createIndexBuilder(mem memory.Allocator, dt arrow.FixedWidthDataType) (ret indexBuilder, err error) {
+	ret = indexBuilder{Builder: NewBuilder(mem, dt)}
+	switch dt.ID() {
+	case arrow.INT8:
+		ret.Append = func(idx int) {
+			ret.Builder.(*Int8Builder).Append(int8(idx))
+		}
+	case arrow.UINT8:
+		ret.Append = func(idx int) {
+			ret.Builder.(*Uint8Builder).Append(uint8(idx))
+		}
+	case arrow.INT16:
+		ret.Append = func(idx int) {
+			ret.Builder.(*Int16Builder).Append(int16(idx))
+		}
+	case arrow.UINT16:
+		ret.Append = func(idx int) {
+			ret.Builder.(*Uint16Builder).Append(uint16(idx))
+		}
+	case arrow.INT32:
+		ret.Append = func(idx int) {
+			ret.Builder.(*Int32Builder).Append(int32(idx))
+		}
+	case arrow.UINT32:
+		ret.Append = func(idx int) {
+			ret.Builder.(*Uint32Builder).Append(uint32(idx))
+		}
+	case arrow.INT64:
+		ret.Append = func(idx int) {
+			ret.Builder.(*Int64Builder).Append(int64(idx))
+		}
+	case arrow.UINT64:
+		ret.Append = func(idx int) {
+			ret.Builder.(*Uint64Builder).Append(uint64(idx))
+		}
+	default:
+		debug.Assert(false, "dictionary index type must be integral")
+		err = fmt.Errorf("dictionary index type must be integral, not %s", dt)
+	}
+
+	return
+}
+
+// helper function to construct an appropriately typed memo table based on
+// the value type for the dictionary
+func createMemoTable(mem memory.Allocator, dt arrow.DataType) (ret hashing.MemoTable, err error) {
+	switch dt.ID() {
+	case arrow.INT8:
+		ret = hashing.NewInt8MemoTable(0)
+	case arrow.UINT8:
+		ret = hashing.NewUint8MemoTable(0)
+	case arrow.INT16:
+		ret = hashing.NewInt16MemoTable(0)
+	case arrow.UINT16:
+		ret = hashing.NewUint16MemoTable(0)
+	case arrow.INT32:
+		ret = hashing.NewInt32MemoTable(0)
+	case arrow.UINT32:
+		ret = hashing.NewUint32MemoTable(0)
+	case arrow.INT64:
+		ret = hashing.NewInt64MemoTable(0)
+	case arrow.UINT64:
+		ret = hashing.NewUint64MemoTable(0)
+	case arrow.DURATION, arrow.TIMESTAMP, arrow.DATE64, arrow.TIME64:
+		ret = hashing.NewInt64MemoTable(0)
+	case arrow.TIME32, arrow.DATE32, arrow.INTERVAL_MONTHS:
+		ret = hashing.NewInt32MemoTable(0)
+	case arrow.FLOAT16:
+		ret = hashing.NewUint16MemoTable(0)
+	case arrow.FLOAT32:
+		ret = hashing.NewFloat32MemoTable(0)
+	case arrow.FLOAT64:
+		ret = hashing.NewFloat64MemoTable(0)
+	case arrow.BINARY, arrow.FIXED_SIZE_BINARY, arrow.DECIMAL128, arrow.INTERVAL_DAY_TIME, arrow.INTERVAL_MONTH_DAY_NANO:
+		ret = hashing.NewBinaryMemoTable(0, 0, NewBinaryBuilder(mem, arrow.BinaryTypes.Binary))
+	case arrow.STRING:
+		ret = hashing.NewBinaryMemoTable(0, 0, NewBinaryBuilder(mem, arrow.BinaryTypes.String))
+	case arrow.NULL:
+	default:
+		debug.Assert(false, "unimplemented dictionary value type")
+		err = fmt.Errorf("unimplemented dictionary value type, %s", dt)
+	}
+
+	return
+}
+
+type DictionaryBuilder interface {
+	Builder
+
+	NewDictionaryArray() *Dictionary
+	NewDelta() (indices, delta Interface, err error)
+	AppendArray(Interface) error
+	ResetFull()
+}
+
+type dictionaryBuilder struct {
+	builder
+
+	dt          *arrow.DictionaryType
+	deltaOffset int
+	memoTable   hashing.MemoTable
+	idxBuilder  indexBuilder
+}
+
+func NewDictionaryBuilderWithDict(mem memory.Allocator, dt *arrow.DictionaryType, init Interface) DictionaryBuilder {
+	if init != nil && !arrow.TypeEqual(dt.ValueType, init.DataType()) {
+		panic(fmt.Errorf("arrow/array: cannot initialize dictionary type %T with array of type %T", dt.ValueType, init.DataType()))
+	}
+
+	idxbldr, err := createIndexBuilder(mem, dt.IndexType.(arrow.FixedWidthDataType))
+	if err != nil {
+		panic(fmt.Errorf("arrow/array: unsupported builder for index type of %T", dt))
+	}
+
+	memo, err := createMemoTable(mem, dt.ValueType)
+	if err != nil {
+		panic(fmt.Errorf("arrow/array: unsupported builder for value type of %T", dt))
+	}
+
+	bldr := dictionaryBuilder{
+		builder:    builder{refCount: 1, mem: mem},
+		idxBuilder: idxbldr,
+		memoTable:  memo,
+		dt:         dt,
+	}
+
+	switch dt.ValueType.ID() {
+	case arrow.NULL:
+		ret := &NullDictionaryBuilder{bldr}
+		debug.Assert(init == nil, "arrow/array: doesn't make sense to init a null dictionary")
+		return ret
+	case arrow.UINT8:
+		ret := &Uint8DictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*Uint8)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.INT8:
+		ret := &Int8DictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*Int8)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.UINT16:
+		ret := &Uint16DictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*Uint16)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.INT16:
+		ret := &Int16DictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*Int16)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.UINT32:
+		ret := &Uint32DictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*Uint32)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.INT32:
+		ret := &Int32DictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*Int32)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.UINT64:
+		ret := &Uint64DictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*Uint64)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.INT64:
+		ret := &Int64DictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*Int64)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.FLOAT16:
+		ret := &Float16DictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*Float16)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.FLOAT32:
+		ret := &Float32DictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*Float32)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.FLOAT64:
+		ret := &Float64DictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*Float64)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.STRING:
+		ret := &BinaryDictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertStringDictValues(init.(*String)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.BINARY:
+		ret := &BinaryDictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*Binary)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.FIXED_SIZE_BINARY:
+		ret := &FixedSizeBinaryDictionaryBuilder{
+			bldr, dt.ValueType.(*arrow.FixedSizeBinaryType).ByteWidth,
+		}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*FixedSizeBinary)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.DATE32:
+		ret := &Date32DictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*Date32)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.DATE64:
+		ret := &Date64DictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*Date64)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.TIMESTAMP:
+		ret := &TimestampDictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*Timestamp)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.TIME32:
+		ret := &Time32DictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*Time32)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.TIME64:
+		ret := &Time64DictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*Time64)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.INTERVAL_MONTHS:
+		ret := &MonthIntervalDictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*MonthInterval)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.INTERVAL_DAY_TIME:
+		ret := &DayTimeDictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*DayTimeInterval)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.DECIMAL128:
+		ret := &Decimal128DictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*Decimal128)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.DECIMAL256:
+	case arrow.LIST:
+	case arrow.STRUCT:
+	case arrow.SPARSE_UNION:
+	case arrow.DENSE_UNION:
+	case arrow.DICTIONARY:
+	case arrow.MAP:
+	case arrow.EXTENSION:
+	case arrow.FIXED_SIZE_LIST:
+	case arrow.DURATION:
+		ret := &DurationDictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*Duration)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.LARGE_STRING:
+	case arrow.LARGE_BINARY:
+	case arrow.LARGE_LIST:
+	case arrow.INTERVAL_MONTH_DAY_NANO:
+		ret := &MonthDayNanoDictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*MonthDayNanoInterval)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	}
+
+	panic("arrow/array: unimplemented dictionary key type")
+}
+
+func NewDictionaryBuilder(mem memory.Allocator, dt *arrow.DictionaryType) DictionaryBuilder {
+	return NewDictionaryBuilderWithDict(mem, dt, nil)
+}
+
+func (b *dictionaryBuilder) Release() {
+	debug.Assert(atomic.LoadInt64(&b.refCount) > 0, "too many releases")
+
+	if atomic.AddInt64(&b.refCount, -1) == 0 {
+		b.idxBuilder.Release()
+		b.idxBuilder.Builder = nil
+		if binmemo, ok := b.memoTable.(*hashing.BinaryMemoTable); ok {
+			binmemo.Release()
+		}
+		b.memoTable = nil
+	}
+}
+
+func (b *dictionaryBuilder) AppendNull() {
+	b.length += 1
+	b.nulls += 1
+	b.idxBuilder.AppendNull()
+}
+
+func (b *dictionaryBuilder) Reserve(n int) {
+	b.idxBuilder.Reserve(n)
+}
+
+func (b *dictionaryBuilder) Resize(n int) {
+	b.idxBuilder.Resize(n)
+	b.length = b.idxBuilder.Len()
+}
+
+func (b *dictionaryBuilder) ResetFull() {
+	b.builder.reset()
+	b.idxBuilder.NewArray().Release()
+	b.memoTable.Reset()
+}
+
+func (b *dictionaryBuilder) Cap() int { return b.idxBuilder.Cap() }
+
+// UnmarshalJSON is not yet implemented for dictionary builders and will always error.
+func (b *dictionaryBuilder) UnmarshalJSON([]byte) error {
+	return errors.New("unmarshal json to dictionary not yet implemented")
+}
+
+func (b *dictionaryBuilder) unmarshal(dec *json.Decoder) error {
+	return errors.New("unmarshal json to dictionary not yet implemented")
+}
+
+func (b *dictionaryBuilder) unmarshalOne(dec *json.Decoder) error {
+	return errors.New("unmarshal json to dictionary not yet implemented")
+}
+
+func (b *dictionaryBuilder) NewArray() Interface {
+	return b.NewDictionaryArray()
+}
+
+func (b *dictionaryBuilder) NewDictionaryArray() *Dictionary {
+	a := &Dictionary{}
+	a.refCount = 1
+
+	indices, dict, err := b.newWithDictOffset(0)
+	if err != nil {
+		panic(err)
+	}
+	defer indices.Release()
+
+	indices.dtype = b.dt
+	indices.dictionary = dict
+	a.setData(indices)
+	return a
+}
+
+func (b *dictionaryBuilder) newWithDictOffset(offset int) (indices, dict *Data, err error) {
+	idxarr := b.idxBuilder.NewArray()
+	defer idxarr.Release()
+
+	indices = idxarr.Data().(*Data)
+	indices.Retain()
+
+	dictBuffers := make([]*memory.Buffer, 2)
+
+	dictLength := b.memoTable.Size() - offset
+	dictBuffers[1] = memory.NewResizableBuffer(b.mem)
+	defer dictBuffers[1].Release()
+
+	if bintbl, ok := b.memoTable.(*hashing.BinaryMemoTable); ok {
+		switch b.dt.ValueType.ID() {
+		case arrow.BINARY, arrow.STRING:
+			dictBuffers = append(dictBuffers, memory.NewResizableBuffer(b.mem))
+			defer dictBuffers[2].Release()
+
+			dictBuffers[1].Resize(arrow.Int32SizeBytes * (dictLength + 1))
+			offsets := arrow.Int32Traits.CastFromBytes(dictBuffers[1].Bytes())
+			bintbl.CopyOffsetsSubset(offset, offsets)
+
+			valuesz := offsets[len(offsets)-1] - offsets[0]
+			dictBuffers[2].Resize(int(valuesz))
+			bintbl.CopyValuesSubset(offset, dictBuffers[2].Bytes())
+		default: // fixed size
+			bw := int(bitutil.BytesForBits(int64(b.dt.ValueType.(arrow.FixedWidthDataType).BitWidth())))
+			dictBuffers[1].Resize(dictLength * bw)
+			bintbl.CopyFixedWidthValues(offset, bw, dictBuffers[1].Bytes())
+		}
+	} else {
+		dictBuffers[1].Resize(b.memoTable.TypeTraits().BytesRequired(dictLength))
+		b.memoTable.WriteOutSubset(offset, dictBuffers[1].Bytes())
+	}
+
+	var nullcount int
+	if idx, ok := b.memoTable.GetNull(); ok && idx >= offset {
+		dictBuffers[0] = memory.NewResizableBuffer(b.mem)
+		defer dictBuffers[0].Release()
+
+		nullcount = 1
+
+		dictBuffers[0].Resize(int(bitutil.BytesForBits(int64(dictLength))))
+		memory.Set(dictBuffers[0].Bytes(), 0xFF)
+		bitutil.ClearBit(dictBuffers[0].Bytes(), idx)
+	}
+
+	b.deltaOffset = b.memoTable.Size()
+	dict = NewData(b.dt.ValueType, dictLength, dictBuffers, nil, nullcount, 0)
+	b.reset()
+	return
+}
+
+func (b *dictionaryBuilder) NewDelta() (indices, delta Interface, err error) {

Review comment:
       added

##########
File path: go/arrow/ipc/file_reader.go
##########
@@ -157,22 +162,9 @@ func (f *FileReader) readSchema() error {
 			return err
 		}
 
-		id, dict, err := readDictionary(msg.meta, f.fields, f.r)
-		msg.Release()
-		if err != nil {
-			return xerrors.Errorf("arrow/ipc: could not read dictionary %d from file: %w", i, err)
+		if _, err = readDictionary(&f.memo, msg.meta, bytes.NewReader(msg.body.Bytes()), f.mem); err != nil {

Review comment:
       Good point, i've added the check here so that we error on a replacement since that is not supported for IPC files.
   
   As far as expected type: that is validated inside the `readDictionary` function. We get the expected types from the schema, and read dictionaries using the types as pulled from the memo table populated by the schema. If the type doesn't match, `ctx.loadArray` inside of `readDictionary` will fail with the wrong type.
   
   We don't currently do the stats on the number of dictionaries like the C++ lib does, but it might get added. So usage of the dictionary kind will likely get utilized more than just having the IPC File fail on replacements in a later change.




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] emkornfield commented on pull request #12158: ARROW-3039: [Go] Add support for DictionaryArray

Posted by GitBox <gi...@apache.org>.
emkornfield commented on pull request #12158:
URL: https://github.com/apache/arrow/pull/12158#issuecomment-1057199404


   @zeroshade sorry, I lost track of this, are you waiting for me on this?


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] emkornfield commented on a change in pull request #12158: ARROW-3039: [Go] Add support for DictionaryArray

Posted by GitBox <gi...@apache.org>.
emkornfield commented on a change in pull request #12158:
URL: https://github.com/apache/arrow/pull/12158#discussion_r800129274



##########
File path: go/arrow/array/dictionary.go
##########
@@ -0,0 +1,1305 @@
+// 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 array
+
+import (
+	"errors"
+	"fmt"
+	"math"
+	"sync/atomic"
+	"unsafe"
+
+	"github.com/apache/arrow/go/v7/arrow"
+	"github.com/apache/arrow/go/v7/arrow/bitutil"
+	"github.com/apache/arrow/go/v7/arrow/decimal128"
+	"github.com/apache/arrow/go/v7/arrow/float16"
+	"github.com/apache/arrow/go/v7/arrow/internal/debug"
+	"github.com/apache/arrow/go/v7/arrow/memory"
+	"github.com/apache/arrow/go/v7/internal/hashing"
+	"github.com/goccy/go-json"
+)
+
+// Dictionary represents the type for dictionary-encoded data with a data
+// dependent dictionary.
+//
+// A dictionary array contains an array of non-negative integers (the "dictionary"
+// indices") along with a data type containing a "dictionary" corresponding to
+// the distinct values represented in the data.
+//
+// For example, the array:
+//
+//      ["foo", "bar", "foo", "bar", "foo", "bar"]
+//
+// with dictionary ["bar", "foo"], would have the representation of:
+//
+//      indices: [1, 0, 1, 0, 1, 0]
+//      dictionary: ["bar", "foo"]
+//
+// The indices in principle may be any integer type.
+type Dictionary struct {
+	array
+
+	indices Interface
+	dict    Interface
+}
+
+// NewDictionaryArray constructs a dictionary array with the provided indices
+// and dictionary using the given type.
+func NewDictionaryArray(typ arrow.DataType, indices, dict Interface) *Dictionary {
+	a := &Dictionary{}
+	a.array.refCount = 1
+	dictdata := NewData(typ, indices.Len(), indices.Data().Buffers(), indices.Data().Children(), indices.NullN(), indices.Data().Offset())
+	dictdata.dictionary = dict.Data().(*Data)
+	dict.Data().Retain()
+
+	defer dictdata.Release()
+	a.setData(dictdata)
+	return a
+}
+
+// checkIndexBounds returns an error if any value in the provided integer
+// arraydata is >= the passed upperlimit or < 0. otherwise nil
+func checkIndexBounds(indices *Data, upperlimit uint64) error {
+	if indices.length == 0 {
+		return nil
+	}
+
+	var maxval uint64
+	switch indices.dtype.ID() {
+	case arrow.UINT8:
+		maxval = math.MaxUint8
+	case arrow.UINT16:
+		maxval = math.MaxUint16
+	case arrow.UINT32:
+		maxval = math.MaxUint32
+	case arrow.UINT64:
+		maxval = math.MaxUint64
+	}
+	isSigned := maxval == 0
+	if !isSigned && upperlimit > maxval {
+		return nil
+	}
+
+	// TODO(mtopol): lift BitSetRunReader from parquet to utils
+	// and use it here for performance improvement.
+	var nullbitmap []byte
+	if indices.buffers[0] != nil {
+		nullbitmap = indices.buffers[0].Bytes()
+	}
+
+	var outOfBounds func(i int) error
+	switch indices.dtype.ID() {
+	case arrow.INT8:
+		data := arrow.Int8Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] < 0 || data[i] >= int8(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.UINT8:
+		data := arrow.Uint8Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] >= uint8(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.INT16:
+		data := arrow.Int16Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] < 0 || data[i] >= int16(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.UINT16:
+		data := arrow.Uint16Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] >= uint16(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.INT32:
+		data := arrow.Int32Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] < 0 || data[i] >= int32(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.UINT32:
+		data := arrow.Uint32Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] >= uint32(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.INT64:
+		data := arrow.Int64Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] < 0 || data[i] >= int64(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.UINT64:
+		data := arrow.Uint64Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] >= upperlimit {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	default:
+		return fmt.Errorf("invalid type for bounds checking: %T", indices.dtype)
+	}
+
+	for i := 0; i < indices.length; i++ {
+		if len(nullbitmap) > 0 && bitutil.BitIsNotSet(nullbitmap, i+indices.offset) {
+			continue
+		}
+
+		if err := outOfBounds(i + indices.offset); err != nil {
+			return err
+		}
+	}
+	return nil
+}
+
+// NewValidatedDictionaryArray constructs a dictionary array from the provided indices
+// and dictionary arrays, while also performing validation checks to ensure correctness
+// such as bounds checking at are usually skipped for performance.
+func NewValidatedDictionaryArray(typ *arrow.DictionaryType, indices, dict Interface) (*Dictionary, error) {
+	if indices.DataType().ID() != typ.IndexType.ID() {
+		return nil, fmt.Errorf("dictionary type index (%T) does not match indices array type (%T)", typ.IndexType, indices.DataType())
+	}
+
+	if !arrow.TypeEqual(typ.ValueType, dict.DataType()) {
+		return nil, fmt.Errorf("dictionary value type (%T) does not match dict array type (%T)", typ.ValueType, dict.DataType())
+	}
+
+	if err := checkIndexBounds(indices.Data().(*Data), uint64(dict.Len())); err != nil {
+		return nil, err
+	}
+
+	return NewDictionaryArray(typ, indices, dict), nil
+}
+
+// NewDictionaryData creates a strongly typed Dictionary array from
+// an ArrayData object with a datatype of arrow.Dictionary and a dictionary
+func NewDictionaryData(data arrow.ArrayData) *Dictionary {
+	a := &Dictionary{}
+	a.refCount = 1
+	a.setData(data.(*Data))
+	return a
+}
+
+func (d *Dictionary) Retain() {
+	atomic.AddInt64(&d.refCount, 1)
+}
+
+func (d *Dictionary) Release() {
+	debug.Assert(atomic.LoadInt64(&d.refCount) > 0, "too many releases")
+
+	if atomic.AddInt64(&d.refCount, -1) == 0 {
+		d.data.Release()
+		d.data, d.nullBitmapBytes = nil, nil
+		d.indices.Release()
+		d.indices = nil
+		if d.dict != nil {
+			d.dict.Release()
+			d.dict = nil
+		}
+	}
+}
+
+func (d *Dictionary) setData(data *Data) {
+	d.array.setData(data)
+
+	if data.dictionary == nil {
+		panic("arrow/array: no dictionary set in Data for Dictionary array")
+	}
+
+	dictType := data.dtype.(*arrow.DictionaryType)
+	debug.Assert(arrow.TypeEqual(dictType.ValueType, data.dictionary.DataType()), "mismatched dictionary value types")
+
+	indexData := NewData(dictType.IndexType, data.length, data.buffers, data.childData, data.nulls, data.offset)
+	defer indexData.Release()
+	d.indices = MakeFromData(indexData)
+}
+
+// Dictionary returns the values array that makes up the dictionary for this
+// array.
+func (d *Dictionary) Dictionary() Interface {
+	if d.dict == nil {
+		d.dict = MakeFromData(d.data.dictionary)
+	}
+	return d.dict
+}
+
+// Indices returns the underlying array of indices as it's own array
+func (d *Dictionary) Indices() Interface {
+	return d.indices
+}
+
+// CanCompareIndices returns true if the dictionary arrays can be compared
+// without having to unify the dictionaries themselves first.
+func (d *Dictionary) CanCompareIndices(other *Dictionary) bool {
+	if !arrow.TypeEqual(d.indices.DataType(), other.indices.DataType()) {
+		return false
+	}
+
+	minlen := int64(min(d.data.dictionary.length, other.data.dictionary.length))
+	return ArraySliceEqual(d.Dictionary(), 0, minlen, other.Dictionary(), 0, minlen)
+}
+
+func (d *Dictionary) String() string {
+	return fmt.Sprintf("{ dictionary: %v\n  indices: %v }", d.Dictionary(), d.Indices())
+}
+
+// GetValueIndex returns the dictionary index for the value at index i of the array.
+// The actual value can be retrieved by using d.Dictionary().(valuetype).Value(d.GetValueIndex(i))
+func (d *Dictionary) GetValueIndex(i int) int {
+	indiceData := d.data.buffers[1].Bytes()
+	// we know the value is non-negative per the spec, so
+	// we can use the unsigned value regardless.
+	switch d.indices.DataType().ID() {
+	case arrow.UINT8, arrow.INT8:
+		return int(uint8(indiceData[d.data.offset+i]))
+	case arrow.UINT16, arrow.INT16:
+		return int(arrow.Uint16Traits.CastFromBytes(indiceData)[d.data.offset+i])
+	case arrow.UINT32, arrow.INT32:
+		return int(arrow.Uint32Traits.CastFromBytes(indiceData)[d.data.offset+i])
+	case arrow.UINT64, arrow.INT64:
+		return int(arrow.Uint64Traits.CastFromBytes(indiceData)[d.data.offset+i])
+	}
+	debug.Assert(false, "unreachable dictionary index")
+	return -1
+}
+
+func (d *Dictionary) getOneForMarshal(i int) interface{} {
+	if d.IsNull(i) {
+		return nil
+	}
+	vidx := d.GetValueIndex(i)
+	return d.Dictionary().(arraymarshal).getOneForMarshal(vidx)
+}
+
+func (d *Dictionary) MarshalJSON() ([]byte, error) {
+	vals := make([]interface{}, d.Len())
+	for i := 0; i < d.Len(); i++ {
+		vals[i] = d.getOneForMarshal(i)
+	}
+	return json.Marshal(vals)
+}
+
+func arrayEqualDict(l, r *Dictionary) bool {
+	return ArrayEqual(l.Dictionary(), r.Dictionary()) && ArrayEqual(l.indices, r.indices)
+}
+
+func arrayApproxEqualDict(l, r *Dictionary, opt equalOption) bool {
+	return arrayApproxEqual(l.Dictionary(), r.Dictionary(), opt) && arrayApproxEqual(l.indices, r.indices, opt)
+}
+
+// helper for building the properly typed indices of the dictionary builder
+type indexBuilder struct {
+	Builder
+	Append func(int)
+}
+
+func createIndexBuilder(mem memory.Allocator, dt arrow.FixedWidthDataType) (ret indexBuilder, err error) {
+	ret = indexBuilder{Builder: NewBuilder(mem, dt)}
+	switch dt.ID() {
+	case arrow.INT8:
+		ret.Append = func(idx int) {
+			ret.Builder.(*Int8Builder).Append(int8(idx))
+		}
+	case arrow.UINT8:
+		ret.Append = func(idx int) {
+			ret.Builder.(*Uint8Builder).Append(uint8(idx))
+		}
+	case arrow.INT16:
+		ret.Append = func(idx int) {
+			ret.Builder.(*Int16Builder).Append(int16(idx))
+		}
+	case arrow.UINT16:
+		ret.Append = func(idx int) {
+			ret.Builder.(*Uint16Builder).Append(uint16(idx))
+		}
+	case arrow.INT32:
+		ret.Append = func(idx int) {
+			ret.Builder.(*Int32Builder).Append(int32(idx))
+		}
+	case arrow.UINT32:
+		ret.Append = func(idx int) {
+			ret.Builder.(*Uint32Builder).Append(uint32(idx))
+		}
+	case arrow.INT64:
+		ret.Append = func(idx int) {
+			ret.Builder.(*Int64Builder).Append(int64(idx))
+		}
+	case arrow.UINT64:
+		ret.Append = func(idx int) {
+			ret.Builder.(*Uint64Builder).Append(uint64(idx))
+		}
+	default:
+		debug.Assert(false, "dictionary index type must be integral")
+		err = fmt.Errorf("dictionary index type must be integral, not %s", dt)
+	}
+
+	return
+}
+
+// helper function to construct an appropriately typed memo table based on
+// the value type for the dictionary
+func createMemoTable(mem memory.Allocator, dt arrow.DataType) (ret hashing.MemoTable, err error) {
+	switch dt.ID() {
+	case arrow.INT8:
+		ret = hashing.NewInt8MemoTable(0)
+	case arrow.UINT8:
+		ret = hashing.NewUint8MemoTable(0)
+	case arrow.INT16:
+		ret = hashing.NewInt16MemoTable(0)
+	case arrow.UINT16:
+		ret = hashing.NewUint16MemoTable(0)
+	case arrow.INT32:
+		ret = hashing.NewInt32MemoTable(0)
+	case arrow.UINT32:
+		ret = hashing.NewUint32MemoTable(0)
+	case arrow.INT64:
+		ret = hashing.NewInt64MemoTable(0)
+	case arrow.UINT64:
+		ret = hashing.NewUint64MemoTable(0)
+	case arrow.DURATION, arrow.TIMESTAMP, arrow.DATE64, arrow.TIME64:
+		ret = hashing.NewInt64MemoTable(0)
+	case arrow.TIME32, arrow.DATE32, arrow.INTERVAL_MONTHS:
+		ret = hashing.NewInt32MemoTable(0)
+	case arrow.FLOAT16:
+		ret = hashing.NewUint16MemoTable(0)
+	case arrow.FLOAT32:
+		ret = hashing.NewFloat32MemoTable(0)
+	case arrow.FLOAT64:
+		ret = hashing.NewFloat64MemoTable(0)
+	case arrow.BINARY, arrow.FIXED_SIZE_BINARY, arrow.DECIMAL128, arrow.INTERVAL_DAY_TIME, arrow.INTERVAL_MONTH_DAY_NANO:
+		ret = hashing.NewBinaryMemoTable(0, 0, NewBinaryBuilder(mem, arrow.BinaryTypes.Binary))
+	case arrow.STRING:
+		ret = hashing.NewBinaryMemoTable(0, 0, NewBinaryBuilder(mem, arrow.BinaryTypes.String))
+	case arrow.NULL:
+	default:
+		debug.Assert(false, "unimplemented dictionary value type")
+		err = fmt.Errorf("unimplemented dictionary value type, %s", dt)
+	}
+
+	return
+}
+
+type DictionaryBuilder interface {
+	Builder
+
+	NewDictionaryArray() *Dictionary
+	NewDelta() (indices, delta Interface, err error)
+	AppendArray(Interface) error
+	ResetFull()
+}
+
+type dictionaryBuilder struct {
+	builder
+
+	dt          *arrow.DictionaryType
+	deltaOffset int
+	memoTable   hashing.MemoTable
+	idxBuilder  indexBuilder
+}
+
+func NewDictionaryBuilderWithDict(mem memory.Allocator, dt *arrow.DictionaryType, init Interface) DictionaryBuilder {
+	if init != nil && !arrow.TypeEqual(dt.ValueType, init.DataType()) {
+		panic(fmt.Errorf("arrow/array: cannot initialize dictionary type %T with array of type %T", dt.ValueType, init.DataType()))
+	}
+
+	idxbldr, err := createIndexBuilder(mem, dt.IndexType.(arrow.FixedWidthDataType))
+	if err != nil {
+		panic(fmt.Errorf("arrow/array: unsupported builder for index type of %T", dt))
+	}
+
+	memo, err := createMemoTable(mem, dt.ValueType)
+	if err != nil {
+		panic(fmt.Errorf("arrow/array: unsupported builder for value type of %T", dt))
+	}
+
+	bldr := dictionaryBuilder{
+		builder:    builder{refCount: 1, mem: mem},
+		idxBuilder: idxbldr,
+		memoTable:  memo,
+		dt:         dt,
+	}
+
+	switch dt.ValueType.ID() {
+	case arrow.NULL:
+		ret := &NullDictionaryBuilder{bldr}
+		debug.Assert(init == nil, "arrow/array: doesn't make sense to init a null dictionary")
+		return ret
+	case arrow.UINT8:
+		ret := &Uint8DictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*Uint8)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.INT8:
+		ret := &Int8DictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*Int8)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.UINT16:
+		ret := &Uint16DictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*Uint16)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.INT16:
+		ret := &Int16DictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*Int16)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.UINT32:
+		ret := &Uint32DictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*Uint32)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.INT32:
+		ret := &Int32DictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*Int32)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.UINT64:
+		ret := &Uint64DictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*Uint64)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.INT64:
+		ret := &Int64DictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*Int64)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.FLOAT16:
+		ret := &Float16DictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*Float16)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.FLOAT32:
+		ret := &Float32DictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*Float32)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.FLOAT64:
+		ret := &Float64DictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*Float64)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.STRING:
+		ret := &BinaryDictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertStringDictValues(init.(*String)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.BINARY:
+		ret := &BinaryDictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*Binary)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.FIXED_SIZE_BINARY:
+		ret := &FixedSizeBinaryDictionaryBuilder{
+			bldr, dt.ValueType.(*arrow.FixedSizeBinaryType).ByteWidth,
+		}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*FixedSizeBinary)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.DATE32:
+		ret := &Date32DictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*Date32)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.DATE64:
+		ret := &Date64DictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*Date64)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.TIMESTAMP:
+		ret := &TimestampDictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*Timestamp)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.TIME32:
+		ret := &Time32DictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*Time32)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.TIME64:
+		ret := &Time64DictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*Time64)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.INTERVAL_MONTHS:
+		ret := &MonthIntervalDictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*MonthInterval)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.INTERVAL_DAY_TIME:
+		ret := &DayTimeDictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*DayTimeInterval)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.DECIMAL128:
+		ret := &Decimal128DictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*Decimal128)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.DECIMAL256:
+	case arrow.LIST:
+	case arrow.STRUCT:
+	case arrow.SPARSE_UNION:
+	case arrow.DENSE_UNION:
+	case arrow.DICTIONARY:
+	case arrow.MAP:
+	case arrow.EXTENSION:
+	case arrow.FIXED_SIZE_LIST:
+	case arrow.DURATION:
+		ret := &DurationDictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*Duration)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.LARGE_STRING:
+	case arrow.LARGE_BINARY:
+	case arrow.LARGE_LIST:
+	case arrow.INTERVAL_MONTH_DAY_NANO:
+		ret := &MonthDayNanoDictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*MonthDayNanoInterval)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	}
+
+	panic("arrow/array: unimplemented dictionary key type")
+}
+
+func NewDictionaryBuilder(mem memory.Allocator, dt *arrow.DictionaryType) DictionaryBuilder {
+	return NewDictionaryBuilderWithDict(mem, dt, nil)
+}
+
+func (b *dictionaryBuilder) Release() {
+	debug.Assert(atomic.LoadInt64(&b.refCount) > 0, "too many releases")
+
+	if atomic.AddInt64(&b.refCount, -1) == 0 {
+		b.idxBuilder.Release()
+		b.idxBuilder.Builder = nil
+		if binmemo, ok := b.memoTable.(*hashing.BinaryMemoTable); ok {
+			binmemo.Release()
+		}
+		b.memoTable = nil
+	}
+}
+
+func (b *dictionaryBuilder) AppendNull() {
+	b.length += 1
+	b.nulls += 1
+	b.idxBuilder.AppendNull()
+}
+
+func (b *dictionaryBuilder) Reserve(n int) {
+	b.idxBuilder.Reserve(n)
+}
+
+func (b *dictionaryBuilder) Resize(n int) {
+	b.idxBuilder.Resize(n)
+	b.length = b.idxBuilder.Len()
+}
+
+func (b *dictionaryBuilder) ResetFull() {
+	b.builder.reset()
+	b.idxBuilder.NewArray().Release()
+	b.memoTable.Reset()
+}
+
+func (b *dictionaryBuilder) Cap() int { return b.idxBuilder.Cap() }
+
+// UnmarshalJSON is not yet implemented for dictionary builders and will always error.
+func (b *dictionaryBuilder) UnmarshalJSON([]byte) error {
+	return errors.New("unmarshal json to dictionary not yet implemented")
+}
+
+func (b *dictionaryBuilder) unmarshal(dec *json.Decoder) error {
+	return errors.New("unmarshal json to dictionary not yet implemented")
+}
+
+func (b *dictionaryBuilder) unmarshalOne(dec *json.Decoder) error {
+	return errors.New("unmarshal json to dictionary not yet implemented")
+}
+
+func (b *dictionaryBuilder) NewArray() Interface {
+	return b.NewDictionaryArray()
+}
+
+func (b *dictionaryBuilder) NewDictionaryArray() *Dictionary {
+	a := &Dictionary{}
+	a.refCount = 1
+
+	indices, dict, err := b.newWithDictOffset(0)
+	if err != nil {
+		panic(err)
+	}
+	defer indices.Release()
+
+	indices.dtype = b.dt
+	indices.dictionary = dict
+	a.setData(indices)
+	return a
+}
+
+func (b *dictionaryBuilder) newWithDictOffset(offset int) (indices, dict *Data, err error) {
+	idxarr := b.idxBuilder.NewArray()
+	defer idxarr.Release()
+
+	indices = idxarr.Data().(*Data)
+	indices.Retain()
+
+	dictBuffers := make([]*memory.Buffer, 2)
+
+	dictLength := b.memoTable.Size() - offset
+	dictBuffers[1] = memory.NewResizableBuffer(b.mem)
+	defer dictBuffers[1].Release()
+
+	if bintbl, ok := b.memoTable.(*hashing.BinaryMemoTable); ok {
+		switch b.dt.ValueType.ID() {
+		case arrow.BINARY, arrow.STRING:
+			dictBuffers = append(dictBuffers, memory.NewResizableBuffer(b.mem))
+			defer dictBuffers[2].Release()
+
+			dictBuffers[1].Resize(arrow.Int32SizeBytes * (dictLength + 1))
+			offsets := arrow.Int32Traits.CastFromBytes(dictBuffers[1].Bytes())
+			bintbl.CopyOffsetsSubset(offset, offsets)
+
+			valuesz := offsets[len(offsets)-1] - offsets[0]
+			dictBuffers[2].Resize(int(valuesz))
+			bintbl.CopyValuesSubset(offset, dictBuffers[2].Bytes())
+		default: // fixed size
+			bw := int(bitutil.BytesForBits(int64(b.dt.ValueType.(arrow.FixedWidthDataType).BitWidth())))
+			dictBuffers[1].Resize(dictLength * bw)
+			bintbl.CopyFixedWidthValues(offset, bw, dictBuffers[1].Bytes())
+		}
+	} else {
+		dictBuffers[1].Resize(b.memoTable.TypeTraits().BytesRequired(dictLength))
+		b.memoTable.WriteOutSubset(offset, dictBuffers[1].Bytes())
+	}
+
+	var nullcount int
+	if idx, ok := b.memoTable.GetNull(); ok && idx >= offset {
+		dictBuffers[0] = memory.NewResizableBuffer(b.mem)
+		defer dictBuffers[0].Release()
+
+		nullcount = 1
+
+		dictBuffers[0].Resize(int(bitutil.BytesForBits(int64(dictLength))))
+		memory.Set(dictBuffers[0].Bytes(), 0xFF)
+		bitutil.ClearBit(dictBuffers[0].Bytes(), idx)
+	}
+
+	b.deltaOffset = b.memoTable.Size()
+	dict = NewData(b.dt.ValueType, dictLength, dictBuffers, nil, nullcount, 0)
+	b.reset()
+	return
+}
+
+func (b *dictionaryBuilder) NewDelta() (indices, delta Interface, err error) {

Review comment:
       docs?




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] emkornfield commented on a change in pull request #12158: ARROW-3039: [Go] Add support for DictionaryArray

Posted by GitBox <gi...@apache.org>.
emkornfield commented on a change in pull request #12158:
URL: https://github.com/apache/arrow/pull/12158#discussion_r800128264



##########
File path: go/arrow/array/dictionary.go
##########
@@ -0,0 +1,1305 @@
+// 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 array
+
+import (
+	"errors"
+	"fmt"
+	"math"
+	"sync/atomic"
+	"unsafe"
+
+	"github.com/apache/arrow/go/v7/arrow"
+	"github.com/apache/arrow/go/v7/arrow/bitutil"
+	"github.com/apache/arrow/go/v7/arrow/decimal128"
+	"github.com/apache/arrow/go/v7/arrow/float16"
+	"github.com/apache/arrow/go/v7/arrow/internal/debug"
+	"github.com/apache/arrow/go/v7/arrow/memory"
+	"github.com/apache/arrow/go/v7/internal/hashing"
+	"github.com/goccy/go-json"
+)
+
+// Dictionary represents the type for dictionary-encoded data with a data
+// dependent dictionary.
+//
+// A dictionary array contains an array of non-negative integers (the "dictionary"
+// indices") along with a data type containing a "dictionary" corresponding to
+// the distinct values represented in the data.
+//
+// For example, the array:
+//
+//      ["foo", "bar", "foo", "bar", "foo", "bar"]
+//
+// with dictionary ["bar", "foo"], would have the representation of:
+//
+//      indices: [1, 0, 1, 0, 1, 0]
+//      dictionary: ["bar", "foo"]
+//
+// The indices in principle may be any integer type.
+type Dictionary struct {
+	array
+
+	indices Interface
+	dict    Interface
+}
+
+// NewDictionaryArray constructs a dictionary array with the provided indices
+// and dictionary using the given type.
+func NewDictionaryArray(typ arrow.DataType, indices, dict Interface) *Dictionary {
+	a := &Dictionary{}
+	a.array.refCount = 1
+	dictdata := NewData(typ, indices.Len(), indices.Data().Buffers(), indices.Data().Children(), indices.NullN(), indices.Data().Offset())
+	dictdata.dictionary = dict.Data().(*Data)
+	dict.Data().Retain()
+
+	defer dictdata.Release()
+	a.setData(dictdata)
+	return a
+}
+
+// checkIndexBounds returns an error if any value in the provided integer
+// arraydata is >= the passed upperlimit or < 0. otherwise nil
+func checkIndexBounds(indices *Data, upperlimit uint64) error {
+	if indices.length == 0 {
+		return nil
+	}
+
+	var maxval uint64
+	switch indices.dtype.ID() {
+	case arrow.UINT8:

Review comment:
       I see this is handled below.




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] github-actions[bot] commented on pull request #12158: ARROW-3039: [Go] Add support for DictionaryArray

Posted by GitBox <gi...@apache.org>.
github-actions[bot] commented on pull request #12158:
URL: https://github.com/apache/arrow/pull/12158#issuecomment-1013324342






-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] emkornfield commented on a change in pull request #12158: ARROW-3039: [Go] Add support for DictionaryArray

Posted by GitBox <gi...@apache.org>.
emkornfield commented on a change in pull request #12158:
URL: https://github.com/apache/arrow/pull/12158#discussion_r800127741



##########
File path: go/arrow/array/array_test.go
##########
@@ -95,13 +96,15 @@ func TestMakeFromData(t *testing.T) {
 			}, 0 /* nulls */, 0 /* offset */)},
 		},
 
+		{name: "dictionary", d: &testDataType{arrow.DICTIONARY}, expPanic: true, expError: "arrow/array: no dictionary set in Data for Dictionary array"},
+		{name: "dictionary", d: &arrow.DictionaryType{IndexType: arrow.PrimitiveTypes.Int8, ValueType: &testDataType{arrow.INT64}}, dict: array.NewData(&testDataType{arrow.INT64}, 0 /* length */, make([]*memory.Buffer, 2 /*null bitmap, values*/), nil /* childData */, 0 /* nulls */, 0 /* offset */)},

Review comment:
       does it pay to test more index and value types?




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] zeroshade commented on a change in pull request #12158: ARROW-3039: [Go] Add support for DictionaryArray

Posted by GitBox <gi...@apache.org>.
zeroshade commented on a change in pull request #12158:
URL: https://github.com/apache/arrow/pull/12158#discussion_r829395507



##########
File path: go/arrow/array/dictionary.go
##########
@@ -0,0 +1,1305 @@
+// 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 array
+
+import (
+	"errors"
+	"fmt"
+	"math"
+	"sync/atomic"
+	"unsafe"
+
+	"github.com/apache/arrow/go/v7/arrow"
+	"github.com/apache/arrow/go/v7/arrow/bitutil"
+	"github.com/apache/arrow/go/v7/arrow/decimal128"
+	"github.com/apache/arrow/go/v7/arrow/float16"
+	"github.com/apache/arrow/go/v7/arrow/internal/debug"
+	"github.com/apache/arrow/go/v7/arrow/memory"
+	"github.com/apache/arrow/go/v7/internal/hashing"
+	"github.com/goccy/go-json"
+)
+
+// Dictionary represents the type for dictionary-encoded data with a data
+// dependent dictionary.
+//
+// A dictionary array contains an array of non-negative integers (the "dictionary"
+// indices") along with a data type containing a "dictionary" corresponding to
+// the distinct values represented in the data.
+//
+// For example, the array:
+//
+//      ["foo", "bar", "foo", "bar", "foo", "bar"]
+//
+// with dictionary ["bar", "foo"], would have the representation of:
+//
+//      indices: [1, 0, 1, 0, 1, 0]
+//      dictionary: ["bar", "foo"]
+//
+// The indices in principle may be any integer type.
+type Dictionary struct {
+	array
+
+	indices Interface
+	dict    Interface
+}
+
+// NewDictionaryArray constructs a dictionary array with the provided indices
+// and dictionary using the given type.
+func NewDictionaryArray(typ arrow.DataType, indices, dict Interface) *Dictionary {
+	a := &Dictionary{}
+	a.array.refCount = 1
+	dictdata := NewData(typ, indices.Len(), indices.Data().Buffers(), indices.Data().Children(), indices.NullN(), indices.Data().Offset())
+	dictdata.dictionary = dict.Data().(*Data)
+	dict.Data().Retain()
+
+	defer dictdata.Release()
+	a.setData(dictdata)
+	return a
+}
+
+// checkIndexBounds returns an error if any value in the provided integer
+// arraydata is >= the passed upperlimit or < 0. otherwise nil
+func checkIndexBounds(indices *Data, upperlimit uint64) error {
+	if indices.length == 0 {
+		return nil
+	}
+
+	var maxval uint64
+	switch indices.dtype.ID() {
+	case arrow.UINT8:
+		maxval = math.MaxUint8
+	case arrow.UINT16:
+		maxval = math.MaxUint16
+	case arrow.UINT32:
+		maxval = math.MaxUint32
+	case arrow.UINT64:
+		maxval = math.MaxUint64
+	}
+	isSigned := maxval == 0
+	if !isSigned && upperlimit > maxval {
+		return nil
+	}
+
+	// TODO(mtopol): lift BitSetRunReader from parquet to utils
+	// and use it here for performance improvement.
+	var nullbitmap []byte
+	if indices.buffers[0] != nil {
+		nullbitmap = indices.buffers[0].Bytes()
+	}
+
+	var outOfBounds func(i int) error
+	switch indices.dtype.ID() {
+	case arrow.INT8:
+		data := arrow.Int8Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] < 0 || data[i] >= int8(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.UINT8:
+		data := arrow.Uint8Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] >= uint8(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.INT16:
+		data := arrow.Int16Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] < 0 || data[i] >= int16(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.UINT16:
+		data := arrow.Uint16Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] >= uint16(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.INT32:
+		data := arrow.Int32Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] < 0 || data[i] >= int32(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.UINT32:
+		data := arrow.Uint32Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] >= uint32(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.INT64:
+		data := arrow.Int64Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] < 0 || data[i] >= int64(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.UINT64:
+		data := arrow.Uint64Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] >= upperlimit {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	default:
+		return fmt.Errorf("invalid type for bounds checking: %T", indices.dtype)
+	}
+
+	for i := 0; i < indices.length; i++ {
+		if len(nullbitmap) > 0 && bitutil.BitIsNotSet(nullbitmap, i+indices.offset) {
+			continue
+		}
+
+		if err := outOfBounds(i + indices.offset); err != nil {
+			return err
+		}
+	}
+	return nil
+}
+
+// NewValidatedDictionaryArray constructs a dictionary array from the provided indices
+// and dictionary arrays, while also performing validation checks to ensure correctness
+// such as bounds checking at are usually skipped for performance.
+func NewValidatedDictionaryArray(typ *arrow.DictionaryType, indices, dict Interface) (*Dictionary, error) {
+	if indices.DataType().ID() != typ.IndexType.ID() {
+		return nil, fmt.Errorf("dictionary type index (%T) does not match indices array type (%T)", typ.IndexType, indices.DataType())
+	}
+
+	if !arrow.TypeEqual(typ.ValueType, dict.DataType()) {
+		return nil, fmt.Errorf("dictionary value type (%T) does not match dict array type (%T)", typ.ValueType, dict.DataType())
+	}
+
+	if err := checkIndexBounds(indices.Data().(*Data), uint64(dict.Len())); err != nil {
+		return nil, err
+	}
+
+	return NewDictionaryArray(typ, indices, dict), nil
+}
+
+// NewDictionaryData creates a strongly typed Dictionary array from
+// an ArrayData object with a datatype of arrow.Dictionary and a dictionary
+func NewDictionaryData(data arrow.ArrayData) *Dictionary {
+	a := &Dictionary{}
+	a.refCount = 1
+	a.setData(data.(*Data))
+	return a
+}
+
+func (d *Dictionary) Retain() {
+	atomic.AddInt64(&d.refCount, 1)
+}
+
+func (d *Dictionary) Release() {
+	debug.Assert(atomic.LoadInt64(&d.refCount) > 0, "too many releases")
+
+	if atomic.AddInt64(&d.refCount, -1) == 0 {
+		d.data.Release()
+		d.data, d.nullBitmapBytes = nil, nil
+		d.indices.Release()
+		d.indices = nil
+		if d.dict != nil {
+			d.dict.Release()
+			d.dict = nil
+		}
+	}
+}
+
+func (d *Dictionary) setData(data *Data) {
+	d.array.setData(data)
+
+	if data.dictionary == nil {
+		panic("arrow/array: no dictionary set in Data for Dictionary array")
+	}
+
+	dictType := data.dtype.(*arrow.DictionaryType)
+	debug.Assert(arrow.TypeEqual(dictType.ValueType, data.dictionary.DataType()), "mismatched dictionary value types")
+
+	indexData := NewData(dictType.IndexType, data.length, data.buffers, data.childData, data.nulls, data.offset)
+	defer indexData.Release()
+	d.indices = MakeFromData(indexData)
+}
+
+// Dictionary returns the values array that makes up the dictionary for this
+// array.
+func (d *Dictionary) Dictionary() Interface {
+	if d.dict == nil {
+		d.dict = MakeFromData(d.data.dictionary)
+	}
+	return d.dict
+}
+
+// Indices returns the underlying array of indices as it's own array
+func (d *Dictionary) Indices() Interface {
+	return d.indices
+}
+
+// CanCompareIndices returns true if the dictionary arrays can be compared
+// without having to unify the dictionaries themselves first.
+func (d *Dictionary) CanCompareIndices(other *Dictionary) bool {
+	if !arrow.TypeEqual(d.indices.DataType(), other.indices.DataType()) {
+		return false
+	}
+
+	minlen := int64(min(d.data.dictionary.length, other.data.dictionary.length))
+	return ArraySliceEqual(d.Dictionary(), 0, minlen, other.Dictionary(), 0, minlen)
+}
+
+func (d *Dictionary) String() string {
+	return fmt.Sprintf("{ dictionary: %v\n  indices: %v }", d.Dictionary(), d.Indices())
+}
+
+// GetValueIndex returns the dictionary index for the value at index i of the array.
+// The actual value can be retrieved by using d.Dictionary().(valuetype).Value(d.GetValueIndex(i))
+func (d *Dictionary) GetValueIndex(i int) int {
+	indiceData := d.data.buffers[1].Bytes()
+	// we know the value is non-negative per the spec, so
+	// we can use the unsigned value regardless.
+	switch d.indices.DataType().ID() {
+	case arrow.UINT8, arrow.INT8:
+		return int(uint8(indiceData[d.data.offset+i]))
+	case arrow.UINT16, arrow.INT16:
+		return int(arrow.Uint16Traits.CastFromBytes(indiceData)[d.data.offset+i])
+	case arrow.UINT32, arrow.INT32:
+		return int(arrow.Uint32Traits.CastFromBytes(indiceData)[d.data.offset+i])
+	case arrow.UINT64, arrow.INT64:
+		return int(arrow.Uint64Traits.CastFromBytes(indiceData)[d.data.offset+i])
+	}
+	debug.Assert(false, "unreachable dictionary index")
+	return -1
+}
+
+func (d *Dictionary) getOneForMarshal(i int) interface{} {
+	if d.IsNull(i) {
+		return nil
+	}
+	vidx := d.GetValueIndex(i)
+	return d.Dictionary().(arraymarshal).getOneForMarshal(vidx)
+}
+
+func (d *Dictionary) MarshalJSON() ([]byte, error) {
+	vals := make([]interface{}, d.Len())
+	for i := 0; i < d.Len(); i++ {
+		vals[i] = d.getOneForMarshal(i)
+	}
+	return json.Marshal(vals)
+}
+
+func arrayEqualDict(l, r *Dictionary) bool {
+	return ArrayEqual(l.Dictionary(), r.Dictionary()) && ArrayEqual(l.indices, r.indices)
+}
+
+func arrayApproxEqualDict(l, r *Dictionary, opt equalOption) bool {
+	return arrayApproxEqual(l.Dictionary(), r.Dictionary(), opt) && arrayApproxEqual(l.indices, r.indices, opt)
+}
+
+// helper for building the properly typed indices of the dictionary builder
+type indexBuilder struct {
+	Builder
+	Append func(int)
+}
+
+func createIndexBuilder(mem memory.Allocator, dt arrow.FixedWidthDataType) (ret indexBuilder, err error) {
+	ret = indexBuilder{Builder: NewBuilder(mem, dt)}
+	switch dt.ID() {
+	case arrow.INT8:
+		ret.Append = func(idx int) {
+			ret.Builder.(*Int8Builder).Append(int8(idx))
+		}
+	case arrow.UINT8:
+		ret.Append = func(idx int) {
+			ret.Builder.(*Uint8Builder).Append(uint8(idx))
+		}
+	case arrow.INT16:
+		ret.Append = func(idx int) {
+			ret.Builder.(*Int16Builder).Append(int16(idx))
+		}
+	case arrow.UINT16:
+		ret.Append = func(idx int) {
+			ret.Builder.(*Uint16Builder).Append(uint16(idx))
+		}
+	case arrow.INT32:
+		ret.Append = func(idx int) {
+			ret.Builder.(*Int32Builder).Append(int32(idx))
+		}
+	case arrow.UINT32:
+		ret.Append = func(idx int) {
+			ret.Builder.(*Uint32Builder).Append(uint32(idx))
+		}
+	case arrow.INT64:
+		ret.Append = func(idx int) {
+			ret.Builder.(*Int64Builder).Append(int64(idx))
+		}
+	case arrow.UINT64:
+		ret.Append = func(idx int) {
+			ret.Builder.(*Uint64Builder).Append(uint64(idx))
+		}
+	default:
+		debug.Assert(false, "dictionary index type must be integral")
+		err = fmt.Errorf("dictionary index type must be integral, not %s", dt)
+	}
+
+	return
+}
+
+// helper function to construct an appropriately typed memo table based on
+// the value type for the dictionary
+func createMemoTable(mem memory.Allocator, dt arrow.DataType) (ret hashing.MemoTable, err error) {
+	switch dt.ID() {
+	case arrow.INT8:
+		ret = hashing.NewInt8MemoTable(0)
+	case arrow.UINT8:
+		ret = hashing.NewUint8MemoTable(0)
+	case arrow.INT16:
+		ret = hashing.NewInt16MemoTable(0)
+	case arrow.UINT16:
+		ret = hashing.NewUint16MemoTable(0)
+	case arrow.INT32:
+		ret = hashing.NewInt32MemoTable(0)
+	case arrow.UINT32:
+		ret = hashing.NewUint32MemoTable(0)
+	case arrow.INT64:
+		ret = hashing.NewInt64MemoTable(0)
+	case arrow.UINT64:
+		ret = hashing.NewUint64MemoTable(0)
+	case arrow.DURATION, arrow.TIMESTAMP, arrow.DATE64, arrow.TIME64:
+		ret = hashing.NewInt64MemoTable(0)
+	case arrow.TIME32, arrow.DATE32, arrow.INTERVAL_MONTHS:
+		ret = hashing.NewInt32MemoTable(0)
+	case arrow.FLOAT16:
+		ret = hashing.NewUint16MemoTable(0)
+	case arrow.FLOAT32:
+		ret = hashing.NewFloat32MemoTable(0)
+	case arrow.FLOAT64:
+		ret = hashing.NewFloat64MemoTable(0)
+	case arrow.BINARY, arrow.FIXED_SIZE_BINARY, arrow.DECIMAL128, arrow.INTERVAL_DAY_TIME, arrow.INTERVAL_MONTH_DAY_NANO:
+		ret = hashing.NewBinaryMemoTable(0, 0, NewBinaryBuilder(mem, arrow.BinaryTypes.Binary))
+	case arrow.STRING:
+		ret = hashing.NewBinaryMemoTable(0, 0, NewBinaryBuilder(mem, arrow.BinaryTypes.String))
+	case arrow.NULL:
+	default:
+		debug.Assert(false, "unimplemented dictionary value type")
+		err = fmt.Errorf("unimplemented dictionary value type, %s", dt)
+	}
+
+	return
+}
+
+type DictionaryBuilder interface {
+	Builder
+
+	NewDictionaryArray() *Dictionary
+	NewDelta() (indices, delta Interface, err error)
+	AppendArray(Interface) error
+	ResetFull()
+}
+
+type dictionaryBuilder struct {
+	builder
+
+	dt          *arrow.DictionaryType
+	deltaOffset int
+	memoTable   hashing.MemoTable
+	idxBuilder  indexBuilder
+}
+
+func NewDictionaryBuilderWithDict(mem memory.Allocator, dt *arrow.DictionaryType, init Interface) DictionaryBuilder {
+	if init != nil && !arrow.TypeEqual(dt.ValueType, init.DataType()) {
+		panic(fmt.Errorf("arrow/array: cannot initialize dictionary type %T with array of type %T", dt.ValueType, init.DataType()))
+	}
+
+	idxbldr, err := createIndexBuilder(mem, dt.IndexType.(arrow.FixedWidthDataType))
+	if err != nil {
+		panic(fmt.Errorf("arrow/array: unsupported builder for index type of %T", dt))
+	}
+
+	memo, err := createMemoTable(mem, dt.ValueType)
+	if err != nil {
+		panic(fmt.Errorf("arrow/array: unsupported builder for value type of %T", dt))
+	}
+
+	bldr := dictionaryBuilder{
+		builder:    builder{refCount: 1, mem: mem},
+		idxBuilder: idxbldr,
+		memoTable:  memo,
+		dt:         dt,
+	}
+
+	switch dt.ValueType.ID() {
+	case arrow.NULL:
+		ret := &NullDictionaryBuilder{bldr}
+		debug.Assert(init == nil, "arrow/array: doesn't make sense to init a null dictionary")
+		return ret
+	case arrow.UINT8:
+		ret := &Uint8DictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*Uint8)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.INT8:
+		ret := &Int8DictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*Int8)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.UINT16:
+		ret := &Uint16DictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*Uint16)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.INT16:
+		ret := &Int16DictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*Int16)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.UINT32:
+		ret := &Uint32DictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*Uint32)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.INT32:
+		ret := &Int32DictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*Int32)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.UINT64:
+		ret := &Uint64DictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*Uint64)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.INT64:
+		ret := &Int64DictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*Int64)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.FLOAT16:
+		ret := &Float16DictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*Float16)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.FLOAT32:
+		ret := &Float32DictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*Float32)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.FLOAT64:
+		ret := &Float64DictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*Float64)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.STRING:
+		ret := &BinaryDictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertStringDictValues(init.(*String)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.BINARY:
+		ret := &BinaryDictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*Binary)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.FIXED_SIZE_BINARY:
+		ret := &FixedSizeBinaryDictionaryBuilder{
+			bldr, dt.ValueType.(*arrow.FixedSizeBinaryType).ByteWidth,
+		}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*FixedSizeBinary)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.DATE32:
+		ret := &Date32DictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*Date32)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.DATE64:
+		ret := &Date64DictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*Date64)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.TIMESTAMP:
+		ret := &TimestampDictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*Timestamp)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.TIME32:
+		ret := &Time32DictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*Time32)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.TIME64:
+		ret := &Time64DictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*Time64)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.INTERVAL_MONTHS:
+		ret := &MonthIntervalDictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*MonthInterval)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.INTERVAL_DAY_TIME:
+		ret := &DayTimeDictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*DayTimeInterval)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.DECIMAL128:
+		ret := &Decimal128DictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*Decimal128)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.DECIMAL256:
+	case arrow.LIST:
+	case arrow.STRUCT:
+	case arrow.SPARSE_UNION:
+	case arrow.DENSE_UNION:
+	case arrow.DICTIONARY:
+	case arrow.MAP:
+	case arrow.EXTENSION:
+	case arrow.FIXED_SIZE_LIST:
+	case arrow.DURATION:
+		ret := &DurationDictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*Duration)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.LARGE_STRING:
+	case arrow.LARGE_BINARY:
+	case arrow.LARGE_LIST:
+	case arrow.INTERVAL_MONTH_DAY_NANO:
+		ret := &MonthDayNanoDictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*MonthDayNanoInterval)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	}
+
+	panic("arrow/array: unimplemented dictionary key type")
+}
+
+func NewDictionaryBuilder(mem memory.Allocator, dt *arrow.DictionaryType) DictionaryBuilder {
+	return NewDictionaryBuilderWithDict(mem, dt, nil)
+}
+
+func (b *dictionaryBuilder) Release() {
+	debug.Assert(atomic.LoadInt64(&b.refCount) > 0, "too many releases")
+
+	if atomic.AddInt64(&b.refCount, -1) == 0 {
+		b.idxBuilder.Release()
+		b.idxBuilder.Builder = nil
+		if binmemo, ok := b.memoTable.(*hashing.BinaryMemoTable); ok {
+			binmemo.Release()
+		}
+		b.memoTable = nil
+	}
+}
+
+func (b *dictionaryBuilder) AppendNull() {
+	b.length += 1
+	b.nulls += 1
+	b.idxBuilder.AppendNull()
+}
+
+func (b *dictionaryBuilder) Reserve(n int) {
+	b.idxBuilder.Reserve(n)
+}
+
+func (b *dictionaryBuilder) Resize(n int) {
+	b.idxBuilder.Resize(n)
+	b.length = b.idxBuilder.Len()
+}
+
+func (b *dictionaryBuilder) ResetFull() {
+	b.builder.reset()
+	b.idxBuilder.NewArray().Release()
+	b.memoTable.Reset()
+}
+
+func (b *dictionaryBuilder) Cap() int { return b.idxBuilder.Cap() }
+
+// UnmarshalJSON is not yet implemented for dictionary builders and will always error.
+func (b *dictionaryBuilder) UnmarshalJSON([]byte) error {
+	return errors.New("unmarshal json to dictionary not yet implemented")
+}
+
+func (b *dictionaryBuilder) unmarshal(dec *json.Decoder) error {
+	return errors.New("unmarshal json to dictionary not yet implemented")
+}
+
+func (b *dictionaryBuilder) unmarshalOne(dec *json.Decoder) error {
+	return errors.New("unmarshal json to dictionary not yet implemented")
+}
+
+func (b *dictionaryBuilder) NewArray() Interface {
+	return b.NewDictionaryArray()
+}
+
+func (b *dictionaryBuilder) NewDictionaryArray() *Dictionary {
+	a := &Dictionary{}
+	a.refCount = 1
+
+	indices, dict, err := b.newWithDictOffset(0)
+	if err != nil {
+		panic(err)
+	}
+	defer indices.Release()
+
+	indices.dtype = b.dt
+	indices.dictionary = dict
+	a.setData(indices)
+	return a
+}
+
+func (b *dictionaryBuilder) newWithDictOffset(offset int) (indices, dict *Data, err error) {
+	idxarr := b.idxBuilder.NewArray()
+	defer idxarr.Release()
+
+	indices = idxarr.Data().(*Data)
+	indices.Retain()
+
+	dictBuffers := make([]*memory.Buffer, 2)
+
+	dictLength := b.memoTable.Size() - offset
+	dictBuffers[1] = memory.NewResizableBuffer(b.mem)
+	defer dictBuffers[1].Release()
+
+	if bintbl, ok := b.memoTable.(*hashing.BinaryMemoTable); ok {
+		switch b.dt.ValueType.ID() {
+		case arrow.BINARY, arrow.STRING:
+			dictBuffers = append(dictBuffers, memory.NewResizableBuffer(b.mem))
+			defer dictBuffers[2].Release()
+
+			dictBuffers[1].Resize(arrow.Int32SizeBytes * (dictLength + 1))
+			offsets := arrow.Int32Traits.CastFromBytes(dictBuffers[1].Bytes())
+			bintbl.CopyOffsetsSubset(offset, offsets)
+
+			valuesz := offsets[len(offsets)-1] - offsets[0]
+			dictBuffers[2].Resize(int(valuesz))
+			bintbl.CopyValuesSubset(offset, dictBuffers[2].Bytes())
+		default: // fixed size
+			bw := int(bitutil.BytesForBits(int64(b.dt.ValueType.(arrow.FixedWidthDataType).BitWidth())))
+			dictBuffers[1].Resize(dictLength * bw)
+			bintbl.CopyFixedWidthValues(offset, bw, dictBuffers[1].Bytes())
+		}
+	} else {
+		dictBuffers[1].Resize(b.memoTable.TypeTraits().BytesRequired(dictLength))
+		b.memoTable.WriteOutSubset(offset, dictBuffers[1].Bytes())
+	}
+
+	var nullcount int
+	if idx, ok := b.memoTable.GetNull(); ok && idx >= offset {
+		dictBuffers[0] = memory.NewResizableBuffer(b.mem)
+		defer dictBuffers[0].Release()
+
+		nullcount = 1
+
+		dictBuffers[0].Resize(int(bitutil.BytesForBits(int64(dictLength))))
+		memory.Set(dictBuffers[0].Bytes(), 0xFF)
+		bitutil.ClearBit(dictBuffers[0].Bytes(), idx)
+	}
+
+	b.deltaOffset = b.memoTable.Size()
+	dict = NewData(b.dt.ValueType, dictLength, dictBuffers, nil, nullcount, 0)
+	b.reset()
+	return
+}
+
+func (b *dictionaryBuilder) NewDelta() (indices, delta Interface, err error) {

Review comment:
       added




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] zeroshade commented on pull request #12158: ARROW-3039: [Go] Add support for DictionaryArray

Posted by GitBox <gi...@apache.org>.
zeroshade commented on pull request #12158:
URL: https://github.com/apache/arrow/pull/12158#issuecomment-1082511124


   rebased from master to resolve conflict.
   
   bump @emkornfield for review :smile:


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] zeroshade commented on a change in pull request #12158: ARROW-3039: [Go] Add support for DictionaryArray

Posted by GitBox <gi...@apache.org>.
zeroshade commented on a change in pull request #12158:
URL: https://github.com/apache/arrow/pull/12158#discussion_r800703148



##########
File path: go/arrow/array/dictionary.go
##########
@@ -0,0 +1,1305 @@
+// 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 array
+
+import (
+	"errors"
+	"fmt"
+	"math"
+	"sync/atomic"
+	"unsafe"
+
+	"github.com/apache/arrow/go/v7/arrow"
+	"github.com/apache/arrow/go/v7/arrow/bitutil"
+	"github.com/apache/arrow/go/v7/arrow/decimal128"
+	"github.com/apache/arrow/go/v7/arrow/float16"
+	"github.com/apache/arrow/go/v7/arrow/internal/debug"
+	"github.com/apache/arrow/go/v7/arrow/memory"
+	"github.com/apache/arrow/go/v7/internal/hashing"
+	"github.com/goccy/go-json"
+)
+
+// Dictionary represents the type for dictionary-encoded data with a data
+// dependent dictionary.
+//
+// A dictionary array contains an array of non-negative integers (the "dictionary"
+// indices") along with a data type containing a "dictionary" corresponding to
+// the distinct values represented in the data.
+//
+// For example, the array:
+//
+//      ["foo", "bar", "foo", "bar", "foo", "bar"]
+//
+// with dictionary ["bar", "foo"], would have the representation of:
+//
+//      indices: [1, 0, 1, 0, 1, 0]
+//      dictionary: ["bar", "foo"]
+//
+// The indices in principle may be any integer type.
+type Dictionary struct {
+	array
+
+	indices Interface
+	dict    Interface
+}
+
+// NewDictionaryArray constructs a dictionary array with the provided indices
+// and dictionary using the given type.
+func NewDictionaryArray(typ arrow.DataType, indices, dict Interface) *Dictionary {
+	a := &Dictionary{}
+	a.array.refCount = 1
+	dictdata := NewData(typ, indices.Len(), indices.Data().Buffers(), indices.Data().Children(), indices.NullN(), indices.Data().Offset())
+	dictdata.dictionary = dict.Data().(*Data)
+	dict.Data().Retain()
+
+	defer dictdata.Release()
+	a.setData(dictdata)
+	return a
+}
+
+// checkIndexBounds returns an error if any value in the provided integer
+// arraydata is >= the passed upperlimit or < 0. otherwise nil
+func checkIndexBounds(indices *Data, upperlimit uint64) error {
+	if indices.length == 0 {
+		return nil
+	}
+
+	var maxval uint64
+	switch indices.dtype.ID() {
+	case arrow.UINT8:
+		maxval = math.MaxUint8
+	case arrow.UINT16:
+		maxval = math.MaxUint16
+	case arrow.UINT32:
+		maxval = math.MaxUint32
+	case arrow.UINT64:
+		maxval = math.MaxUint64
+	}
+	isSigned := maxval == 0
+	if !isSigned && upperlimit > maxval {
+		return nil
+	}
+
+	// TODO(mtopol): lift BitSetRunReader from parquet to utils
+	// and use it here for performance improvement.
+	var nullbitmap []byte
+	if indices.buffers[0] != nil {
+		nullbitmap = indices.buffers[0].Bytes()
+	}
+
+	var outOfBounds func(i int) error
+	switch indices.dtype.ID() {
+	case arrow.INT8:
+		data := arrow.Int8Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] < 0 || data[i] >= int8(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.UINT8:
+		data := arrow.Uint8Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] >= uint8(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.INT16:
+		data := arrow.Int16Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] < 0 || data[i] >= int16(upperlimit) {

Review comment:
       yea, the function to do that natively with SIMD is in the Parquet implemention's native code currently. That's still a good idea for me to lift that into the shared utilities and use that here.




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] zeroshade commented on pull request #12158: ARROW-3039: [Go] Add support for DictionaryArray

Posted by GitBox <gi...@apache.org>.
zeroshade commented on pull request #12158:
URL: https://github.com/apache/arrow/pull/12158#issuecomment-1057211719


   @emkornfield Nope, i'm not waiting for you on this, i was on vacation for a week and then ended up in the hospital with pneumonia. I just haven't had a chance to get back to this to address the comments and fixes. I am gonna try to do so later this week / early next week. I'll tag you in a comment when I'm ready for another lookover by you.
   
   Sorry for the confusion.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] zeroshade commented on a change in pull request #12158: ARROW-3039: [Go] Add support for DictionaryArray

Posted by GitBox <gi...@apache.org>.
zeroshade commented on a change in pull request #12158:
URL: https://github.com/apache/arrow/pull/12158#discussion_r829417887



##########
File path: go/arrow/ipc/file_reader.go
##########
@@ -157,22 +162,9 @@ func (f *FileReader) readSchema() error {
 			return err
 		}
 
-		id, dict, err := readDictionary(msg.meta, f.fields, f.r)
-		msg.Release()
-		if err != nil {
-			return xerrors.Errorf("arrow/ipc: could not read dictionary %d from file: %w", i, err)
+		if _, err = readDictionary(&f.memo, msg.meta, bytes.NewReader(msg.body.Bytes()), f.mem); err != nil {

Review comment:
       Good point, i've added the check here so that we error on a replacement since that is not supported for IPC files.
   
   As far as expected type: that is validated inside the `readDictionary` function. We get the expected types from the schema, and read dictionaries using the types as pulled from the memo table populated by the schema. If the type doesn't match, `ctx.loadArray` inside of `readDictionary` will fail with the wrong type.
   
   We don't currently do the stats on the number of dictionaries like the C++ lib does, but it might get added. So usage of the dictionary kind will likely get utilized more than just having the IPC File fail on replacements in a later change.




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] zeroshade commented on a change in pull request #12158: ARROW-3039: [Go] Add support for DictionaryArray

Posted by GitBox <gi...@apache.org>.
zeroshade commented on a change in pull request #12158:
URL: https://github.com/apache/arrow/pull/12158#discussion_r829393914



##########
File path: go/arrow/array/dictionary.go
##########
@@ -0,0 +1,1305 @@
+// 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 array
+
+import (
+	"errors"
+	"fmt"
+	"math"
+	"sync/atomic"
+	"unsafe"
+
+	"github.com/apache/arrow/go/v7/arrow"
+	"github.com/apache/arrow/go/v7/arrow/bitutil"
+	"github.com/apache/arrow/go/v7/arrow/decimal128"
+	"github.com/apache/arrow/go/v7/arrow/float16"
+	"github.com/apache/arrow/go/v7/arrow/internal/debug"
+	"github.com/apache/arrow/go/v7/arrow/memory"
+	"github.com/apache/arrow/go/v7/internal/hashing"
+	"github.com/goccy/go-json"
+)
+
+// Dictionary represents the type for dictionary-encoded data with a data
+// dependent dictionary.
+//
+// A dictionary array contains an array of non-negative integers (the "dictionary"
+// indices") along with a data type containing a "dictionary" corresponding to
+// the distinct values represented in the data.
+//
+// For example, the array:
+//
+//      ["foo", "bar", "foo", "bar", "foo", "bar"]
+//
+// with dictionary ["bar", "foo"], would have the representation of:
+//
+//      indices: [1, 0, 1, 0, 1, 0]
+//      dictionary: ["bar", "foo"]
+//
+// The indices in principle may be any integer type.
+type Dictionary struct {
+	array
+
+	indices Interface
+	dict    Interface
+}
+
+// NewDictionaryArray constructs a dictionary array with the provided indices
+// and dictionary using the given type.
+func NewDictionaryArray(typ arrow.DataType, indices, dict Interface) *Dictionary {
+	a := &Dictionary{}
+	a.array.refCount = 1
+	dictdata := NewData(typ, indices.Len(), indices.Data().Buffers(), indices.Data().Children(), indices.NullN(), indices.Data().Offset())
+	dictdata.dictionary = dict.Data().(*Data)
+	dict.Data().Retain()
+
+	defer dictdata.Release()
+	a.setData(dictdata)
+	return a
+}
+
+// checkIndexBounds returns an error if any value in the provided integer
+// arraydata is >= the passed upperlimit or < 0. otherwise nil
+func checkIndexBounds(indices *Data, upperlimit uint64) error {
+	if indices.length == 0 {
+		return nil
+	}
+
+	var maxval uint64
+	switch indices.dtype.ID() {
+	case arrow.UINT8:
+		maxval = math.MaxUint8
+	case arrow.UINT16:
+		maxval = math.MaxUint16
+	case arrow.UINT32:
+		maxval = math.MaxUint32
+	case arrow.UINT64:
+		maxval = math.MaxUint64
+	}
+	isSigned := maxval == 0
+	if !isSigned && upperlimit > maxval {
+		return nil
+	}
+
+	// TODO(mtopol): lift BitSetRunReader from parquet to utils
+	// and use it here for performance improvement.
+	var nullbitmap []byte
+	if indices.buffers[0] != nil {
+		nullbitmap = indices.buffers[0].Bytes()
+	}
+
+	var outOfBounds func(i int) error
+	switch indices.dtype.ID() {
+	case arrow.INT8:
+		data := arrow.Int8Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] < 0 || data[i] >= int8(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.UINT8:
+		data := arrow.Uint8Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] >= uint8(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.INT16:
+		data := arrow.Int16Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] < 0 || data[i] >= int16(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.UINT16:
+		data := arrow.Uint16Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] >= uint16(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.INT32:
+		data := arrow.Int32Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] < 0 || data[i] >= int32(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.UINT32:
+		data := arrow.Uint32Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] >= uint32(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.INT64:
+		data := arrow.Int64Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] < 0 || data[i] >= int64(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.UINT64:
+		data := arrow.Uint64Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] >= upperlimit {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	default:
+		return fmt.Errorf("invalid type for bounds checking: %T", indices.dtype)
+	}
+
+	for i := 0; i < indices.length; i++ {
+		if len(nullbitmap) > 0 && bitutil.BitIsNotSet(nullbitmap, i+indices.offset) {
+			continue
+		}
+
+		if err := outOfBounds(i + indices.offset); err != nil {
+			return err
+		}
+	}
+	return nil
+}
+
+// NewValidatedDictionaryArray constructs a dictionary array from the provided indices
+// and dictionary arrays, while also performing validation checks to ensure correctness
+// such as bounds checking at are usually skipped for performance.
+func NewValidatedDictionaryArray(typ *arrow.DictionaryType, indices, dict Interface) (*Dictionary, error) {
+	if indices.DataType().ID() != typ.IndexType.ID() {
+		return nil, fmt.Errorf("dictionary type index (%T) does not match indices array type (%T)", typ.IndexType, indices.DataType())
+	}
+
+	if !arrow.TypeEqual(typ.ValueType, dict.DataType()) {
+		return nil, fmt.Errorf("dictionary value type (%T) does not match dict array type (%T)", typ.ValueType, dict.DataType())
+	}
+
+	if err := checkIndexBounds(indices.Data().(*Data), uint64(dict.Len())); err != nil {
+		return nil, err
+	}
+
+	return NewDictionaryArray(typ, indices, dict), nil
+}
+
+// NewDictionaryData creates a strongly typed Dictionary array from
+// an ArrayData object with a datatype of arrow.Dictionary and a dictionary
+func NewDictionaryData(data arrow.ArrayData) *Dictionary {
+	a := &Dictionary{}
+	a.refCount = 1
+	a.setData(data.(*Data))
+	return a
+}
+
+func (d *Dictionary) Retain() {
+	atomic.AddInt64(&d.refCount, 1)
+}
+
+func (d *Dictionary) Release() {
+	debug.Assert(atomic.LoadInt64(&d.refCount) > 0, "too many releases")
+
+	if atomic.AddInt64(&d.refCount, -1) == 0 {
+		d.data.Release()
+		d.data, d.nullBitmapBytes = nil, nil
+		d.indices.Release()
+		d.indices = nil
+		if d.dict != nil {
+			d.dict.Release()
+			d.dict = nil
+		}
+	}
+}
+
+func (d *Dictionary) setData(data *Data) {
+	d.array.setData(data)
+
+	if data.dictionary == nil {
+		panic("arrow/array: no dictionary set in Data for Dictionary array")
+	}
+
+	dictType := data.dtype.(*arrow.DictionaryType)
+	debug.Assert(arrow.TypeEqual(dictType.ValueType, data.dictionary.DataType()), "mismatched dictionary value types")
+
+	indexData := NewData(dictType.IndexType, data.length, data.buffers, data.childData, data.nulls, data.offset)
+	defer indexData.Release()
+	d.indices = MakeFromData(indexData)
+}
+
+// Dictionary returns the values array that makes up the dictionary for this
+// array.
+func (d *Dictionary) Dictionary() Interface {
+	if d.dict == nil {
+		d.dict = MakeFromData(d.data.dictionary)
+	}
+	return d.dict
+}
+
+// Indices returns the underlying array of indices as it's own array
+func (d *Dictionary) Indices() Interface {
+	return d.indices
+}
+
+// CanCompareIndices returns true if the dictionary arrays can be compared
+// without having to unify the dictionaries themselves first.

Review comment:
       Clarified

##########
File path: go/arrow/array/data.go
##########
@@ -29,13 +29,14 @@ import (
 
 // Data represents the memory and metadata of an Arrow array.
 type Data struct {
-	refCount  int64
-	dtype     arrow.DataType
-	nulls     int
-	offset    int
-	length    int
-	buffers   []*memory.Buffer  // TODO(sgc): should this be an interface?
-	childData []arrow.ArrayData // TODO(sgc): managed by ListArray, StructArray and UnionArray types
+	refCount   int64
+	dtype      arrow.DataType
+	nulls      int
+	offset     int
+	length     int
+	buffers    []*memory.Buffer  // TODO(sgc): should this be an interface?
+	childData  []arrow.ArrayData // TODO(sgc): managed by ListArray, StructArray and UnionArray types
+	dictionary *Data             // only populated for dictionary arrays

Review comment:
       done




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] zeroshade commented on pull request #12158: ARROW-3039: [Go] Add support for DictionaryArray

Posted by GitBox <gi...@apache.org>.
zeroshade commented on pull request #12158:
URL: https://github.com/apache/arrow/pull/12158#issuecomment-1074178252


   @emkornfield This is ready for a re-review now! Thanks!


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] zeroshade commented on a change in pull request #12158: ARROW-3039: [Go] Add support for DictionaryArray

Posted by GitBox <gi...@apache.org>.
zeroshade commented on a change in pull request #12158:
URL: https://github.com/apache/arrow/pull/12158#discussion_r829394426



##########
File path: go/arrow/array/dictionary.go
##########
@@ -0,0 +1,1305 @@
+// 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 array
+
+import (
+	"errors"
+	"fmt"
+	"math"
+	"sync/atomic"
+	"unsafe"
+
+	"github.com/apache/arrow/go/v7/arrow"
+	"github.com/apache/arrow/go/v7/arrow/bitutil"
+	"github.com/apache/arrow/go/v7/arrow/decimal128"
+	"github.com/apache/arrow/go/v7/arrow/float16"
+	"github.com/apache/arrow/go/v7/arrow/internal/debug"
+	"github.com/apache/arrow/go/v7/arrow/memory"
+	"github.com/apache/arrow/go/v7/internal/hashing"
+	"github.com/goccy/go-json"
+)
+
+// Dictionary represents the type for dictionary-encoded data with a data
+// dependent dictionary.
+//
+// A dictionary array contains an array of non-negative integers (the "dictionary"
+// indices") along with a data type containing a "dictionary" corresponding to
+// the distinct values represented in the data.
+//
+// For example, the array:
+//
+//      ["foo", "bar", "foo", "bar", "foo", "bar"]
+//
+// with dictionary ["bar", "foo"], would have the representation of:
+//
+//      indices: [1, 0, 1, 0, 1, 0]
+//      dictionary: ["bar", "foo"]
+//
+// The indices in principle may be any integer type.
+type Dictionary struct {
+	array
+
+	indices Interface
+	dict    Interface
+}
+
+// NewDictionaryArray constructs a dictionary array with the provided indices
+// and dictionary using the given type.
+func NewDictionaryArray(typ arrow.DataType, indices, dict Interface) *Dictionary {
+	a := &Dictionary{}
+	a.array.refCount = 1
+	dictdata := NewData(typ, indices.Len(), indices.Data().Buffers(), indices.Data().Children(), indices.NullN(), indices.Data().Offset())
+	dictdata.dictionary = dict.Data().(*Data)
+	dict.Data().Retain()
+
+	defer dictdata.Release()
+	a.setData(dictdata)
+	return a
+}
+
+// checkIndexBounds returns an error if any value in the provided integer
+// arraydata is >= the passed upperlimit or < 0. otherwise nil
+func checkIndexBounds(indices *Data, upperlimit uint64) error {
+	if indices.length == 0 {
+		return nil
+	}
+
+	var maxval uint64
+	switch indices.dtype.ID() {
+	case arrow.UINT8:
+		maxval = math.MaxUint8
+	case arrow.UINT16:
+		maxval = math.MaxUint16
+	case arrow.UINT32:
+		maxval = math.MaxUint32
+	case arrow.UINT64:
+		maxval = math.MaxUint64
+	}
+	isSigned := maxval == 0
+	if !isSigned && upperlimit > maxval {
+		return nil
+	}
+
+	// TODO(mtopol): lift BitSetRunReader from parquet to utils

Review comment:
       fixed




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] zeroshade commented on a change in pull request #12158: ARROW-3039: [Go] Add support for DictionaryArray

Posted by GitBox <gi...@apache.org>.
zeroshade commented on a change in pull request #12158:
URL: https://github.com/apache/arrow/pull/12158#discussion_r828299627



##########
File path: go/arrow/array/dictionary.go
##########
@@ -0,0 +1,1305 @@
+// 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 array
+
+import (
+	"errors"
+	"fmt"
+	"math"
+	"sync/atomic"
+	"unsafe"
+
+	"github.com/apache/arrow/go/v7/arrow"
+	"github.com/apache/arrow/go/v7/arrow/bitutil"
+	"github.com/apache/arrow/go/v7/arrow/decimal128"
+	"github.com/apache/arrow/go/v7/arrow/float16"
+	"github.com/apache/arrow/go/v7/arrow/internal/debug"
+	"github.com/apache/arrow/go/v7/arrow/memory"
+	"github.com/apache/arrow/go/v7/internal/hashing"
+	"github.com/goccy/go-json"
+)
+
+// Dictionary represents the type for dictionary-encoded data with a data
+// dependent dictionary.
+//
+// A dictionary array contains an array of non-negative integers (the "dictionary"
+// indices") along with a data type containing a "dictionary" corresponding to
+// the distinct values represented in the data.
+//
+// For example, the array:
+//
+//      ["foo", "bar", "foo", "bar", "foo", "bar"]
+//
+// with dictionary ["bar", "foo"], would have the representation of:
+//
+//      indices: [1, 0, 1, 0, 1, 0]
+//      dictionary: ["bar", "foo"]
+//
+// The indices in principle may be any integer type.
+type Dictionary struct {
+	array
+
+	indices Interface
+	dict    Interface
+}
+
+// NewDictionaryArray constructs a dictionary array with the provided indices
+// and dictionary using the given type.
+func NewDictionaryArray(typ arrow.DataType, indices, dict Interface) *Dictionary {
+	a := &Dictionary{}
+	a.array.refCount = 1
+	dictdata := NewData(typ, indices.Len(), indices.Data().Buffers(), indices.Data().Children(), indices.NullN(), indices.Data().Offset())
+	dictdata.dictionary = dict.Data().(*Data)
+	dict.Data().Retain()
+
+	defer dictdata.Release()
+	a.setData(dictdata)
+	return a
+}
+
+// checkIndexBounds returns an error if any value in the provided integer
+// arraydata is >= the passed upperlimit or < 0. otherwise nil
+func checkIndexBounds(indices *Data, upperlimit uint64) error {
+	if indices.length == 0 {
+		return nil
+	}
+
+	var maxval uint64
+	switch indices.dtype.ID() {
+	case arrow.UINT8:
+		maxval = math.MaxUint8
+	case arrow.UINT16:
+		maxval = math.MaxUint16
+	case arrow.UINT32:
+		maxval = math.MaxUint32
+	case arrow.UINT64:
+		maxval = math.MaxUint64
+	}
+	isSigned := maxval == 0
+	if !isSigned && upperlimit > maxval {
+		return nil
+	}
+
+	// TODO(mtopol): lift BitSetRunReader from parquet to utils
+	// and use it here for performance improvement.
+	var nullbitmap []byte
+	if indices.buffers[0] != nil {
+		nullbitmap = indices.buffers[0].Bytes()
+	}
+
+	var outOfBounds func(i int) error
+	switch indices.dtype.ID() {
+	case arrow.INT8:
+		data := arrow.Int8Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] < 0 || data[i] >= int8(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.UINT8:
+		data := arrow.Uint8Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] >= uint8(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.INT16:
+		data := arrow.Int16Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] < 0 || data[i] >= int16(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.UINT16:
+		data := arrow.Uint16Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] >= uint16(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.INT32:
+		data := arrow.Int32Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] < 0 || data[i] >= int32(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.UINT32:
+		data := arrow.Uint32Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] >= uint32(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.INT64:
+		data := arrow.Int64Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] < 0 || data[i] >= int64(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.UINT64:
+		data := arrow.Uint64Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] >= upperlimit {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	default:
+		return fmt.Errorf("invalid type for bounds checking: %T", indices.dtype)
+	}
+
+	for i := 0; i < indices.length; i++ {
+		if len(nullbitmap) > 0 && bitutil.BitIsNotSet(nullbitmap, i+indices.offset) {
+			continue
+		}
+
+		if err := outOfBounds(i + indices.offset); err != nil {
+			return err
+		}
+	}
+	return nil
+}
+
+// NewValidatedDictionaryArray constructs a dictionary array from the provided indices
+// and dictionary arrays, while also performing validation checks to ensure correctness
+// such as bounds checking at are usually skipped for performance.
+func NewValidatedDictionaryArray(typ *arrow.DictionaryType, indices, dict Interface) (*Dictionary, error) {
+	if indices.DataType().ID() != typ.IndexType.ID() {
+		return nil, fmt.Errorf("dictionary type index (%T) does not match indices array type (%T)", typ.IndexType, indices.DataType())
+	}
+
+	if !arrow.TypeEqual(typ.ValueType, dict.DataType()) {
+		return nil, fmt.Errorf("dictionary value type (%T) does not match dict array type (%T)", typ.ValueType, dict.DataType())
+	}
+
+	if err := checkIndexBounds(indices.Data().(*Data), uint64(dict.Len())); err != nil {
+		return nil, err
+	}
+
+	return NewDictionaryArray(typ, indices, dict), nil
+}
+
+// NewDictionaryData creates a strongly typed Dictionary array from
+// an ArrayData object with a datatype of arrow.Dictionary and a dictionary
+func NewDictionaryData(data arrow.ArrayData) *Dictionary {
+	a := &Dictionary{}
+	a.refCount = 1
+	a.setData(data.(*Data))
+	return a
+}
+
+func (d *Dictionary) Retain() {
+	atomic.AddInt64(&d.refCount, 1)
+}
+
+func (d *Dictionary) Release() {
+	debug.Assert(atomic.LoadInt64(&d.refCount) > 0, "too many releases")
+
+	if atomic.AddInt64(&d.refCount, -1) == 0 {
+		d.data.Release()
+		d.data, d.nullBitmapBytes = nil, nil
+		d.indices.Release()
+		d.indices = nil
+		if d.dict != nil {
+			d.dict.Release()
+			d.dict = nil
+		}
+	}
+}
+
+func (d *Dictionary) setData(data *Data) {
+	d.array.setData(data)
+
+	if data.dictionary == nil {
+		panic("arrow/array: no dictionary set in Data for Dictionary array")
+	}
+
+	dictType := data.dtype.(*arrow.DictionaryType)
+	debug.Assert(arrow.TypeEqual(dictType.ValueType, data.dictionary.DataType()), "mismatched dictionary value types")
+
+	indexData := NewData(dictType.IndexType, data.length, data.buffers, data.childData, data.nulls, data.offset)
+	defer indexData.Release()
+	d.indices = MakeFromData(indexData)
+}
+
+// Dictionary returns the values array that makes up the dictionary for this
+// array.
+func (d *Dictionary) Dictionary() Interface {
+	if d.dict == nil {
+		d.dict = MakeFromData(d.data.dictionary)
+	}
+	return d.dict
+}
+
+// Indices returns the underlying array of indices as it's own array
+func (d *Dictionary) Indices() Interface {
+	return d.indices
+}
+
+// CanCompareIndices returns true if the dictionary arrays can be compared
+// without having to unify the dictionaries themselves first.
+func (d *Dictionary) CanCompareIndices(other *Dictionary) bool {
+	if !arrow.TypeEqual(d.indices.DataType(), other.indices.DataType()) {
+		return false
+	}
+
+	minlen := int64(min(d.data.dictionary.length, other.data.dictionary.length))
+	return ArraySliceEqual(d.Dictionary(), 0, minlen, other.Dictionary(), 0, minlen)
+}
+
+func (d *Dictionary) String() string {
+	return fmt.Sprintf("{ dictionary: %v\n  indices: %v }", d.Dictionary(), d.Indices())
+}
+
+// GetValueIndex returns the dictionary index for the value at index i of the array.
+// The actual value can be retrieved by using d.Dictionary().(valuetype).Value(d.GetValueIndex(i))
+func (d *Dictionary) GetValueIndex(i int) int {
+	indiceData := d.data.buffers[1].Bytes()
+	// we know the value is non-negative per the spec, so
+	// we can use the unsigned value regardless.
+	switch d.indices.DataType().ID() {
+	case arrow.UINT8, arrow.INT8:
+		return int(uint8(indiceData[d.data.offset+i]))
+	case arrow.UINT16, arrow.INT16:
+		return int(arrow.Uint16Traits.CastFromBytes(indiceData)[d.data.offset+i])
+	case arrow.UINT32, arrow.INT32:
+		return int(arrow.Uint32Traits.CastFromBytes(indiceData)[d.data.offset+i])
+	case arrow.UINT64, arrow.INT64:
+		return int(arrow.Uint64Traits.CastFromBytes(indiceData)[d.data.offset+i])
+	}
+	debug.Assert(false, "unreachable dictionary index")
+	return -1
+}
+
+func (d *Dictionary) getOneForMarshal(i int) interface{} {
+	if d.IsNull(i) {
+		return nil
+	}
+	vidx := d.GetValueIndex(i)
+	return d.Dictionary().(arraymarshal).getOneForMarshal(vidx)
+}
+
+func (d *Dictionary) MarshalJSON() ([]byte, error) {
+	vals := make([]interface{}, d.Len())
+	for i := 0; i < d.Len(); i++ {
+		vals[i] = d.getOneForMarshal(i)
+	}
+	return json.Marshal(vals)
+}
+
+func arrayEqualDict(l, r *Dictionary) bool {
+	return ArrayEqual(l.Dictionary(), r.Dictionary()) && ArrayEqual(l.indices, r.indices)
+}
+
+func arrayApproxEqualDict(l, r *Dictionary, opt equalOption) bool {
+	return arrayApproxEqual(l.Dictionary(), r.Dictionary(), opt) && arrayApproxEqual(l.indices, r.indices, opt)
+}
+
+// helper for building the properly typed indices of the dictionary builder
+type indexBuilder struct {
+	Builder
+	Append func(int)
+}
+
+func createIndexBuilder(mem memory.Allocator, dt arrow.FixedWidthDataType) (ret indexBuilder, err error) {
+	ret = indexBuilder{Builder: NewBuilder(mem, dt)}
+	switch dt.ID() {
+	case arrow.INT8:
+		ret.Append = func(idx int) {
+			ret.Builder.(*Int8Builder).Append(int8(idx))
+		}
+	case arrow.UINT8:
+		ret.Append = func(idx int) {
+			ret.Builder.(*Uint8Builder).Append(uint8(idx))
+		}
+	case arrow.INT16:
+		ret.Append = func(idx int) {
+			ret.Builder.(*Int16Builder).Append(int16(idx))
+		}
+	case arrow.UINT16:
+		ret.Append = func(idx int) {
+			ret.Builder.(*Uint16Builder).Append(uint16(idx))
+		}
+	case arrow.INT32:
+		ret.Append = func(idx int) {
+			ret.Builder.(*Int32Builder).Append(int32(idx))
+		}
+	case arrow.UINT32:
+		ret.Append = func(idx int) {
+			ret.Builder.(*Uint32Builder).Append(uint32(idx))
+		}
+	case arrow.INT64:
+		ret.Append = func(idx int) {
+			ret.Builder.(*Int64Builder).Append(int64(idx))
+		}
+	case arrow.UINT64:
+		ret.Append = func(idx int) {
+			ret.Builder.(*Uint64Builder).Append(uint64(idx))
+		}
+	default:
+		debug.Assert(false, "dictionary index type must be integral")
+		err = fmt.Errorf("dictionary index type must be integral, not %s", dt)
+	}
+
+	return
+}
+
+// helper function to construct an appropriately typed memo table based on
+// the value type for the dictionary
+func createMemoTable(mem memory.Allocator, dt arrow.DataType) (ret hashing.MemoTable, err error) {
+	switch dt.ID() {
+	case arrow.INT8:
+		ret = hashing.NewInt8MemoTable(0)
+	case arrow.UINT8:
+		ret = hashing.NewUint8MemoTable(0)
+	case arrow.INT16:
+		ret = hashing.NewInt16MemoTable(0)
+	case arrow.UINT16:
+		ret = hashing.NewUint16MemoTable(0)
+	case arrow.INT32:
+		ret = hashing.NewInt32MemoTable(0)
+	case arrow.UINT32:
+		ret = hashing.NewUint32MemoTable(0)
+	case arrow.INT64:
+		ret = hashing.NewInt64MemoTable(0)
+	case arrow.UINT64:
+		ret = hashing.NewUint64MemoTable(0)
+	case arrow.DURATION, arrow.TIMESTAMP, arrow.DATE64, arrow.TIME64:
+		ret = hashing.NewInt64MemoTable(0)
+	case arrow.TIME32, arrow.DATE32, arrow.INTERVAL_MONTHS:
+		ret = hashing.NewInt32MemoTable(0)
+	case arrow.FLOAT16:
+		ret = hashing.NewUint16MemoTable(0)
+	case arrow.FLOAT32:
+		ret = hashing.NewFloat32MemoTable(0)
+	case arrow.FLOAT64:
+		ret = hashing.NewFloat64MemoTable(0)
+	case arrow.BINARY, arrow.FIXED_SIZE_BINARY, arrow.DECIMAL128, arrow.INTERVAL_DAY_TIME, arrow.INTERVAL_MONTH_DAY_NANO:
+		ret = hashing.NewBinaryMemoTable(0, 0, NewBinaryBuilder(mem, arrow.BinaryTypes.Binary))
+	case arrow.STRING:
+		ret = hashing.NewBinaryMemoTable(0, 0, NewBinaryBuilder(mem, arrow.BinaryTypes.String))
+	case arrow.NULL:
+	default:
+		debug.Assert(false, "unimplemented dictionary value type")
+		err = fmt.Errorf("unimplemented dictionary value type, %s", dt)
+	}
+
+	return
+}
+
+type DictionaryBuilder interface {
+	Builder
+
+	NewDictionaryArray() *Dictionary
+	NewDelta() (indices, delta Interface, err error)
+	AppendArray(Interface) error
+	ResetFull()
+}
+
+type dictionaryBuilder struct {
+	builder
+
+	dt          *arrow.DictionaryType
+	deltaOffset int
+	memoTable   hashing.MemoTable
+	idxBuilder  indexBuilder
+}
+
+func NewDictionaryBuilderWithDict(mem memory.Allocator, dt *arrow.DictionaryType, init Interface) DictionaryBuilder {
+	if init != nil && !arrow.TypeEqual(dt.ValueType, init.DataType()) {
+		panic(fmt.Errorf("arrow/array: cannot initialize dictionary type %T with array of type %T", dt.ValueType, init.DataType()))
+	}
+
+	idxbldr, err := createIndexBuilder(mem, dt.IndexType.(arrow.FixedWidthDataType))
+	if err != nil {
+		panic(fmt.Errorf("arrow/array: unsupported builder for index type of %T", dt))
+	}
+
+	memo, err := createMemoTable(mem, dt.ValueType)
+	if err != nil {
+		panic(fmt.Errorf("arrow/array: unsupported builder for value type of %T", dt))
+	}
+
+	bldr := dictionaryBuilder{
+		builder:    builder{refCount: 1, mem: mem},
+		idxBuilder: idxbldr,
+		memoTable:  memo,
+		dt:         dt,
+	}
+
+	switch dt.ValueType.ID() {
+	case arrow.NULL:
+		ret := &NullDictionaryBuilder{bldr}
+		debug.Assert(init == nil, "arrow/array: doesn't make sense to init a null dictionary")
+		return ret
+	case arrow.UINT8:
+		ret := &Uint8DictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*Uint8)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.INT8:
+		ret := &Int8DictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*Int8)); err != nil {
+				panic(err)

Review comment:
       The alternative would be to change the function signature to return `(DictionaryBuilder, error)` but all of the other functions to construct a NewBuilder currently would panic if they ran into an error and don't return `(Builder, error)` so I was following the existing pattern.




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] emkornfield commented on a change in pull request #12158: ARROW-3039: [Go] Add support for DictionaryArray

Posted by GitBox <gi...@apache.org>.
emkornfield commented on a change in pull request #12158:
URL: https://github.com/apache/arrow/pull/12158#discussion_r800129147



##########
File path: go/arrow/array/dictionary.go
##########
@@ -0,0 +1,1305 @@
+// 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 array
+
+import (
+	"errors"
+	"fmt"
+	"math"
+	"sync/atomic"
+	"unsafe"
+
+	"github.com/apache/arrow/go/v7/arrow"
+	"github.com/apache/arrow/go/v7/arrow/bitutil"
+	"github.com/apache/arrow/go/v7/arrow/decimal128"
+	"github.com/apache/arrow/go/v7/arrow/float16"
+	"github.com/apache/arrow/go/v7/arrow/internal/debug"
+	"github.com/apache/arrow/go/v7/arrow/memory"
+	"github.com/apache/arrow/go/v7/internal/hashing"
+	"github.com/goccy/go-json"
+)
+
+// Dictionary represents the type for dictionary-encoded data with a data
+// dependent dictionary.
+//
+// A dictionary array contains an array of non-negative integers (the "dictionary"
+// indices") along with a data type containing a "dictionary" corresponding to
+// the distinct values represented in the data.
+//
+// For example, the array:
+//
+//      ["foo", "bar", "foo", "bar", "foo", "bar"]
+//
+// with dictionary ["bar", "foo"], would have the representation of:
+//
+//      indices: [1, 0, 1, 0, 1, 0]
+//      dictionary: ["bar", "foo"]
+//
+// The indices in principle may be any integer type.
+type Dictionary struct {
+	array
+
+	indices Interface
+	dict    Interface
+}
+
+// NewDictionaryArray constructs a dictionary array with the provided indices
+// and dictionary using the given type.
+func NewDictionaryArray(typ arrow.DataType, indices, dict Interface) *Dictionary {
+	a := &Dictionary{}
+	a.array.refCount = 1
+	dictdata := NewData(typ, indices.Len(), indices.Data().Buffers(), indices.Data().Children(), indices.NullN(), indices.Data().Offset())
+	dictdata.dictionary = dict.Data().(*Data)
+	dict.Data().Retain()
+
+	defer dictdata.Release()
+	a.setData(dictdata)
+	return a
+}
+
+// checkIndexBounds returns an error if any value in the provided integer
+// arraydata is >= the passed upperlimit or < 0. otherwise nil
+func checkIndexBounds(indices *Data, upperlimit uint64) error {
+	if indices.length == 0 {
+		return nil
+	}
+
+	var maxval uint64
+	switch indices.dtype.ID() {
+	case arrow.UINT8:
+		maxval = math.MaxUint8
+	case arrow.UINT16:
+		maxval = math.MaxUint16
+	case arrow.UINT32:
+		maxval = math.MaxUint32
+	case arrow.UINT64:
+		maxval = math.MaxUint64
+	}
+	isSigned := maxval == 0
+	if !isSigned && upperlimit > maxval {
+		return nil
+	}
+
+	// TODO(mtopol): lift BitSetRunReader from parquet to utils
+	// and use it here for performance improvement.
+	var nullbitmap []byte
+	if indices.buffers[0] != nil {
+		nullbitmap = indices.buffers[0].Bytes()
+	}
+
+	var outOfBounds func(i int) error
+	switch indices.dtype.ID() {
+	case arrow.INT8:
+		data := arrow.Int8Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] < 0 || data[i] >= int8(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.UINT8:
+		data := arrow.Uint8Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] >= uint8(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.INT16:
+		data := arrow.Int16Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] < 0 || data[i] >= int16(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.UINT16:
+		data := arrow.Uint16Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] >= uint16(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.INT32:
+		data := arrow.Int32Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] < 0 || data[i] >= int32(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.UINT32:
+		data := arrow.Uint32Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] >= uint32(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.INT64:
+		data := arrow.Int64Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] < 0 || data[i] >= int64(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.UINT64:
+		data := arrow.Uint64Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] >= upperlimit {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	default:
+		return fmt.Errorf("invalid type for bounds checking: %T", indices.dtype)
+	}
+
+	for i := 0; i < indices.length; i++ {
+		if len(nullbitmap) > 0 && bitutil.BitIsNotSet(nullbitmap, i+indices.offset) {
+			continue
+		}
+
+		if err := outOfBounds(i + indices.offset); err != nil {
+			return err
+		}
+	}
+	return nil
+}
+
+// NewValidatedDictionaryArray constructs a dictionary array from the provided indices
+// and dictionary arrays, while also performing validation checks to ensure correctness
+// such as bounds checking at are usually skipped for performance.
+func NewValidatedDictionaryArray(typ *arrow.DictionaryType, indices, dict Interface) (*Dictionary, error) {
+	if indices.DataType().ID() != typ.IndexType.ID() {
+		return nil, fmt.Errorf("dictionary type index (%T) does not match indices array type (%T)", typ.IndexType, indices.DataType())
+	}
+
+	if !arrow.TypeEqual(typ.ValueType, dict.DataType()) {
+		return nil, fmt.Errorf("dictionary value type (%T) does not match dict array type (%T)", typ.ValueType, dict.DataType())
+	}
+
+	if err := checkIndexBounds(indices.Data().(*Data), uint64(dict.Len())); err != nil {
+		return nil, err
+	}
+
+	return NewDictionaryArray(typ, indices, dict), nil
+}
+
+// NewDictionaryData creates a strongly typed Dictionary array from
+// an ArrayData object with a datatype of arrow.Dictionary and a dictionary
+func NewDictionaryData(data arrow.ArrayData) *Dictionary {
+	a := &Dictionary{}
+	a.refCount = 1
+	a.setData(data.(*Data))
+	return a
+}
+
+func (d *Dictionary) Retain() {
+	atomic.AddInt64(&d.refCount, 1)
+}
+
+func (d *Dictionary) Release() {
+	debug.Assert(atomic.LoadInt64(&d.refCount) > 0, "too many releases")
+
+	if atomic.AddInt64(&d.refCount, -1) == 0 {
+		d.data.Release()
+		d.data, d.nullBitmapBytes = nil, nil
+		d.indices.Release()
+		d.indices = nil
+		if d.dict != nil {
+			d.dict.Release()
+			d.dict = nil
+		}
+	}
+}
+
+func (d *Dictionary) setData(data *Data) {
+	d.array.setData(data)
+
+	if data.dictionary == nil {
+		panic("arrow/array: no dictionary set in Data for Dictionary array")
+	}
+
+	dictType := data.dtype.(*arrow.DictionaryType)
+	debug.Assert(arrow.TypeEqual(dictType.ValueType, data.dictionary.DataType()), "mismatched dictionary value types")
+
+	indexData := NewData(dictType.IndexType, data.length, data.buffers, data.childData, data.nulls, data.offset)
+	defer indexData.Release()
+	d.indices = MakeFromData(indexData)
+}
+
+// Dictionary returns the values array that makes up the dictionary for this
+// array.
+func (d *Dictionary) Dictionary() Interface {
+	if d.dict == nil {
+		d.dict = MakeFromData(d.data.dictionary)
+	}
+	return d.dict
+}
+
+// Indices returns the underlying array of indices as it's own array
+func (d *Dictionary) Indices() Interface {
+	return d.indices
+}
+
+// CanCompareIndices returns true if the dictionary arrays can be compared
+// without having to unify the dictionaries themselves first.
+func (d *Dictionary) CanCompareIndices(other *Dictionary) bool {
+	if !arrow.TypeEqual(d.indices.DataType(), other.indices.DataType()) {
+		return false
+	}
+
+	minlen := int64(min(d.data.dictionary.length, other.data.dictionary.length))
+	return ArraySliceEqual(d.Dictionary(), 0, minlen, other.Dictionary(), 0, minlen)
+}
+
+func (d *Dictionary) String() string {
+	return fmt.Sprintf("{ dictionary: %v\n  indices: %v }", d.Dictionary(), d.Indices())
+}
+
+// GetValueIndex returns the dictionary index for the value at index i of the array.
+// The actual value can be retrieved by using d.Dictionary().(valuetype).Value(d.GetValueIndex(i))
+func (d *Dictionary) GetValueIndex(i int) int {
+	indiceData := d.data.buffers[1].Bytes()
+	// we know the value is non-negative per the spec, so
+	// we can use the unsigned value regardless.
+	switch d.indices.DataType().ID() {
+	case arrow.UINT8, arrow.INT8:
+		return int(uint8(indiceData[d.data.offset+i]))
+	case arrow.UINT16, arrow.INT16:
+		return int(arrow.Uint16Traits.CastFromBytes(indiceData)[d.data.offset+i])
+	case arrow.UINT32, arrow.INT32:
+		return int(arrow.Uint32Traits.CastFromBytes(indiceData)[d.data.offset+i])
+	case arrow.UINT64, arrow.INT64:
+		return int(arrow.Uint64Traits.CastFromBytes(indiceData)[d.data.offset+i])
+	}
+	debug.Assert(false, "unreachable dictionary index")
+	return -1
+}
+
+func (d *Dictionary) getOneForMarshal(i int) interface{} {
+	if d.IsNull(i) {
+		return nil
+	}
+	vidx := d.GetValueIndex(i)
+	return d.Dictionary().(arraymarshal).getOneForMarshal(vidx)
+}
+
+func (d *Dictionary) MarshalJSON() ([]byte, error) {
+	vals := make([]interface{}, d.Len())
+	for i := 0; i < d.Len(); i++ {
+		vals[i] = d.getOneForMarshal(i)
+	}
+	return json.Marshal(vals)
+}
+
+func arrayEqualDict(l, r *Dictionary) bool {
+	return ArrayEqual(l.Dictionary(), r.Dictionary()) && ArrayEqual(l.indices, r.indices)
+}
+
+func arrayApproxEqualDict(l, r *Dictionary, opt equalOption) bool {
+	return arrayApproxEqual(l.Dictionary(), r.Dictionary(), opt) && arrayApproxEqual(l.indices, r.indices, opt)
+}
+
+// helper for building the properly typed indices of the dictionary builder
+type indexBuilder struct {
+	Builder
+	Append func(int)
+}
+
+func createIndexBuilder(mem memory.Allocator, dt arrow.FixedWidthDataType) (ret indexBuilder, err error) {
+	ret = indexBuilder{Builder: NewBuilder(mem, dt)}
+	switch dt.ID() {
+	case arrow.INT8:
+		ret.Append = func(idx int) {
+			ret.Builder.(*Int8Builder).Append(int8(idx))
+		}
+	case arrow.UINT8:
+		ret.Append = func(idx int) {
+			ret.Builder.(*Uint8Builder).Append(uint8(idx))
+		}
+	case arrow.INT16:
+		ret.Append = func(idx int) {
+			ret.Builder.(*Int16Builder).Append(int16(idx))
+		}
+	case arrow.UINT16:
+		ret.Append = func(idx int) {
+			ret.Builder.(*Uint16Builder).Append(uint16(idx))
+		}
+	case arrow.INT32:
+		ret.Append = func(idx int) {
+			ret.Builder.(*Int32Builder).Append(int32(idx))
+		}
+	case arrow.UINT32:
+		ret.Append = func(idx int) {
+			ret.Builder.(*Uint32Builder).Append(uint32(idx))
+		}
+	case arrow.INT64:
+		ret.Append = func(idx int) {
+			ret.Builder.(*Int64Builder).Append(int64(idx))
+		}
+	case arrow.UINT64:
+		ret.Append = func(idx int) {
+			ret.Builder.(*Uint64Builder).Append(uint64(idx))
+		}
+	default:
+		debug.Assert(false, "dictionary index type must be integral")
+		err = fmt.Errorf("dictionary index type must be integral, not %s", dt)
+	}
+
+	return
+}
+
+// helper function to construct an appropriately typed memo table based on
+// the value type for the dictionary
+func createMemoTable(mem memory.Allocator, dt arrow.DataType) (ret hashing.MemoTable, err error) {
+	switch dt.ID() {
+	case arrow.INT8:
+		ret = hashing.NewInt8MemoTable(0)
+	case arrow.UINT8:
+		ret = hashing.NewUint8MemoTable(0)
+	case arrow.INT16:
+		ret = hashing.NewInt16MemoTable(0)
+	case arrow.UINT16:
+		ret = hashing.NewUint16MemoTable(0)
+	case arrow.INT32:
+		ret = hashing.NewInt32MemoTable(0)
+	case arrow.UINT32:
+		ret = hashing.NewUint32MemoTable(0)
+	case arrow.INT64:
+		ret = hashing.NewInt64MemoTable(0)
+	case arrow.UINT64:
+		ret = hashing.NewUint64MemoTable(0)
+	case arrow.DURATION, arrow.TIMESTAMP, arrow.DATE64, arrow.TIME64:
+		ret = hashing.NewInt64MemoTable(0)
+	case arrow.TIME32, arrow.DATE32, arrow.INTERVAL_MONTHS:
+		ret = hashing.NewInt32MemoTable(0)
+	case arrow.FLOAT16:
+		ret = hashing.NewUint16MemoTable(0)
+	case arrow.FLOAT32:
+		ret = hashing.NewFloat32MemoTable(0)
+	case arrow.FLOAT64:
+		ret = hashing.NewFloat64MemoTable(0)
+	case arrow.BINARY, arrow.FIXED_SIZE_BINARY, arrow.DECIMAL128, arrow.INTERVAL_DAY_TIME, arrow.INTERVAL_MONTH_DAY_NANO:
+		ret = hashing.NewBinaryMemoTable(0, 0, NewBinaryBuilder(mem, arrow.BinaryTypes.Binary))
+	case arrow.STRING:
+		ret = hashing.NewBinaryMemoTable(0, 0, NewBinaryBuilder(mem, arrow.BinaryTypes.String))
+	case arrow.NULL:
+	default:
+		debug.Assert(false, "unimplemented dictionary value type")
+		err = fmt.Errorf("unimplemented dictionary value type, %s", dt)
+	}
+
+	return
+}
+
+type DictionaryBuilder interface {
+	Builder
+
+	NewDictionaryArray() *Dictionary
+	NewDelta() (indices, delta Interface, err error)
+	AppendArray(Interface) error
+	ResetFull()
+}
+
+type dictionaryBuilder struct {
+	builder
+
+	dt          *arrow.DictionaryType
+	deltaOffset int
+	memoTable   hashing.MemoTable
+	idxBuilder  indexBuilder
+}
+
+func NewDictionaryBuilderWithDict(mem memory.Allocator, dt *arrow.DictionaryType, init Interface) DictionaryBuilder {
+	if init != nil && !arrow.TypeEqual(dt.ValueType, init.DataType()) {
+		panic(fmt.Errorf("arrow/array: cannot initialize dictionary type %T with array of type %T", dt.ValueType, init.DataType()))
+	}
+
+	idxbldr, err := createIndexBuilder(mem, dt.IndexType.(arrow.FixedWidthDataType))
+	if err != nil {
+		panic(fmt.Errorf("arrow/array: unsupported builder for index type of %T", dt))
+	}
+
+	memo, err := createMemoTable(mem, dt.ValueType)
+	if err != nil {
+		panic(fmt.Errorf("arrow/array: unsupported builder for value type of %T", dt))
+	}
+
+	bldr := dictionaryBuilder{
+		builder:    builder{refCount: 1, mem: mem},
+		idxBuilder: idxbldr,
+		memoTable:  memo,
+		dt:         dt,
+	}
+
+	switch dt.ValueType.ID() {
+	case arrow.NULL:
+		ret := &NullDictionaryBuilder{bldr}
+		debug.Assert(init == nil, "arrow/array: doesn't make sense to init a null dictionary")
+		return ret
+	case arrow.UINT8:
+		ret := &Uint8DictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*Uint8)); err != nil {
+				panic(err)
+			}
+		}
+		return ret
+	case arrow.INT8:
+		ret := &Int8DictionaryBuilder{bldr}
+		if init != nil {
+			if err = ret.InsertDictValues(init.(*Int8)); err != nil {
+				panic(err)

Review comment:
       why is panic the right thing here?




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] emkornfield commented on a change in pull request #12158: ARROW-3039: [Go] Add support for DictionaryArray

Posted by GitBox <gi...@apache.org>.
emkornfield commented on a change in pull request #12158:
URL: https://github.com/apache/arrow/pull/12158#discussion_r800127967



##########
File path: go/arrow/array/dictionary.go
##########
@@ -0,0 +1,1305 @@
+// 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 array
+
+import (
+	"errors"
+	"fmt"
+	"math"
+	"sync/atomic"
+	"unsafe"
+
+	"github.com/apache/arrow/go/v7/arrow"
+	"github.com/apache/arrow/go/v7/arrow/bitutil"
+	"github.com/apache/arrow/go/v7/arrow/decimal128"
+	"github.com/apache/arrow/go/v7/arrow/float16"
+	"github.com/apache/arrow/go/v7/arrow/internal/debug"
+	"github.com/apache/arrow/go/v7/arrow/memory"
+	"github.com/apache/arrow/go/v7/internal/hashing"
+	"github.com/goccy/go-json"
+)
+
+// Dictionary represents the type for dictionary-encoded data with a data

Review comment:
       Thank you for the nice docs!




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] emkornfield commented on a change in pull request #12158: ARROW-3039: [Go] Add support for DictionaryArray

Posted by GitBox <gi...@apache.org>.
emkornfield commented on a change in pull request #12158:
URL: https://github.com/apache/arrow/pull/12158#discussion_r800128811



##########
File path: go/arrow/array/dictionary.go
##########
@@ -0,0 +1,1305 @@
+// 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 array
+
+import (
+	"errors"
+	"fmt"
+	"math"
+	"sync/atomic"
+	"unsafe"
+
+	"github.com/apache/arrow/go/v7/arrow"
+	"github.com/apache/arrow/go/v7/arrow/bitutil"
+	"github.com/apache/arrow/go/v7/arrow/decimal128"
+	"github.com/apache/arrow/go/v7/arrow/float16"
+	"github.com/apache/arrow/go/v7/arrow/internal/debug"
+	"github.com/apache/arrow/go/v7/arrow/memory"
+	"github.com/apache/arrow/go/v7/internal/hashing"
+	"github.com/goccy/go-json"
+)
+
+// Dictionary represents the type for dictionary-encoded data with a data
+// dependent dictionary.
+//
+// A dictionary array contains an array of non-negative integers (the "dictionary"
+// indices") along with a data type containing a "dictionary" corresponding to
+// the distinct values represented in the data.
+//
+// For example, the array:
+//
+//      ["foo", "bar", "foo", "bar", "foo", "bar"]
+//
+// with dictionary ["bar", "foo"], would have the representation of:
+//
+//      indices: [1, 0, 1, 0, 1, 0]
+//      dictionary: ["bar", "foo"]
+//
+// The indices in principle may be any integer type.
+type Dictionary struct {
+	array
+
+	indices Interface
+	dict    Interface
+}
+
+// NewDictionaryArray constructs a dictionary array with the provided indices
+// and dictionary using the given type.
+func NewDictionaryArray(typ arrow.DataType, indices, dict Interface) *Dictionary {
+	a := &Dictionary{}
+	a.array.refCount = 1
+	dictdata := NewData(typ, indices.Len(), indices.Data().Buffers(), indices.Data().Children(), indices.NullN(), indices.Data().Offset())
+	dictdata.dictionary = dict.Data().(*Data)
+	dict.Data().Retain()
+
+	defer dictdata.Release()
+	a.setData(dictdata)
+	return a
+}
+
+// checkIndexBounds returns an error if any value in the provided integer
+// arraydata is >= the passed upperlimit or < 0. otherwise nil
+func checkIndexBounds(indices *Data, upperlimit uint64) error {
+	if indices.length == 0 {
+		return nil
+	}
+
+	var maxval uint64
+	switch indices.dtype.ID() {
+	case arrow.UINT8:
+		maxval = math.MaxUint8
+	case arrow.UINT16:
+		maxval = math.MaxUint16
+	case arrow.UINT32:
+		maxval = math.MaxUint32
+	case arrow.UINT64:
+		maxval = math.MaxUint64
+	}
+	isSigned := maxval == 0
+	if !isSigned && upperlimit > maxval {
+		return nil
+	}
+
+	// TODO(mtopol): lift BitSetRunReader from parquet to utils
+	// and use it here for performance improvement.
+	var nullbitmap []byte
+	if indices.buffers[0] != nil {
+		nullbitmap = indices.buffers[0].Bytes()
+	}
+
+	var outOfBounds func(i int) error
+	switch indices.dtype.ID() {
+	case arrow.INT8:
+		data := arrow.Int8Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] < 0 || data[i] >= int8(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.UINT8:
+		data := arrow.Uint8Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] >= uint8(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.INT16:
+		data := arrow.Int16Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] < 0 || data[i] >= int16(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.UINT16:
+		data := arrow.Uint16Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] >= uint16(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.INT32:
+		data := arrow.Int32Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] < 0 || data[i] >= int32(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.UINT32:
+		data := arrow.Uint32Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] >= uint32(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.INT64:
+		data := arrow.Int64Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] < 0 || data[i] >= int64(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.UINT64:
+		data := arrow.Uint64Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] >= upperlimit {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	default:
+		return fmt.Errorf("invalid type for bounds checking: %T", indices.dtype)
+	}
+
+	for i := 0; i < indices.length; i++ {
+		if len(nullbitmap) > 0 && bitutil.BitIsNotSet(nullbitmap, i+indices.offset) {
+			continue
+		}
+
+		if err := outOfBounds(i + indices.offset); err != nil {
+			return err
+		}
+	}
+	return nil
+}
+
+// NewValidatedDictionaryArray constructs a dictionary array from the provided indices
+// and dictionary arrays, while also performing validation checks to ensure correctness
+// such as bounds checking at are usually skipped for performance.
+func NewValidatedDictionaryArray(typ *arrow.DictionaryType, indices, dict Interface) (*Dictionary, error) {
+	if indices.DataType().ID() != typ.IndexType.ID() {
+		return nil, fmt.Errorf("dictionary type index (%T) does not match indices array type (%T)", typ.IndexType, indices.DataType())
+	}
+
+	if !arrow.TypeEqual(typ.ValueType, dict.DataType()) {
+		return nil, fmt.Errorf("dictionary value type (%T) does not match dict array type (%T)", typ.ValueType, dict.DataType())
+	}
+
+	if err := checkIndexBounds(indices.Data().(*Data), uint64(dict.Len())); err != nil {
+		return nil, err
+	}
+
+	return NewDictionaryArray(typ, indices, dict), nil
+}
+
+// NewDictionaryData creates a strongly typed Dictionary array from
+// an ArrayData object with a datatype of arrow.Dictionary and a dictionary
+func NewDictionaryData(data arrow.ArrayData) *Dictionary {
+	a := &Dictionary{}
+	a.refCount = 1
+	a.setData(data.(*Data))
+	return a
+}
+
+func (d *Dictionary) Retain() {
+	atomic.AddInt64(&d.refCount, 1)
+}
+
+func (d *Dictionary) Release() {
+	debug.Assert(atomic.LoadInt64(&d.refCount) > 0, "too many releases")
+
+	if atomic.AddInt64(&d.refCount, -1) == 0 {
+		d.data.Release()
+		d.data, d.nullBitmapBytes = nil, nil
+		d.indices.Release()
+		d.indices = nil
+		if d.dict != nil {
+			d.dict.Release()
+			d.dict = nil
+		}
+	}
+}
+
+func (d *Dictionary) setData(data *Data) {
+	d.array.setData(data)
+
+	if data.dictionary == nil {
+		panic("arrow/array: no dictionary set in Data for Dictionary array")
+	}
+
+	dictType := data.dtype.(*arrow.DictionaryType)
+	debug.Assert(arrow.TypeEqual(dictType.ValueType, data.dictionary.DataType()), "mismatched dictionary value types")
+
+	indexData := NewData(dictType.IndexType, data.length, data.buffers, data.childData, data.nulls, data.offset)
+	defer indexData.Release()
+	d.indices = MakeFromData(indexData)
+}
+
+// Dictionary returns the values array that makes up the dictionary for this
+// array.
+func (d *Dictionary) Dictionary() Interface {
+	if d.dict == nil {
+		d.dict = MakeFromData(d.data.dictionary)
+	}
+	return d.dict
+}
+
+// Indices returns the underlying array of indices as it's own array
+func (d *Dictionary) Indices() Interface {
+	return d.indices
+}
+
+// CanCompareIndices returns true if the dictionary arrays can be compared
+// without having to unify the dictionaries themselves first.

Review comment:
       might want to clarify that index types also need to be equal




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] emkornfield commented on a change in pull request #12158: ARROW-3039: [Go] Add support for DictionaryArray

Posted by GitBox <gi...@apache.org>.
emkornfield commented on a change in pull request #12158:
URL: https://github.com/apache/arrow/pull/12158#discussion_r800128658



##########
File path: go/arrow/array/dictionary.go
##########
@@ -0,0 +1,1305 @@
+// 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 array
+
+import (
+	"errors"
+	"fmt"
+	"math"
+	"sync/atomic"
+	"unsafe"
+
+	"github.com/apache/arrow/go/v7/arrow"
+	"github.com/apache/arrow/go/v7/arrow/bitutil"
+	"github.com/apache/arrow/go/v7/arrow/decimal128"
+	"github.com/apache/arrow/go/v7/arrow/float16"
+	"github.com/apache/arrow/go/v7/arrow/internal/debug"
+	"github.com/apache/arrow/go/v7/arrow/memory"
+	"github.com/apache/arrow/go/v7/internal/hashing"
+	"github.com/goccy/go-json"
+)
+
+// Dictionary represents the type for dictionary-encoded data with a data
+// dependent dictionary.
+//
+// A dictionary array contains an array of non-negative integers (the "dictionary"
+// indices") along with a data type containing a "dictionary" corresponding to
+// the distinct values represented in the data.
+//
+// For example, the array:
+//
+//      ["foo", "bar", "foo", "bar", "foo", "bar"]
+//
+// with dictionary ["bar", "foo"], would have the representation of:
+//
+//      indices: [1, 0, 1, 0, 1, 0]
+//      dictionary: ["bar", "foo"]
+//
+// The indices in principle may be any integer type.
+type Dictionary struct {
+	array
+
+	indices Interface
+	dict    Interface
+}
+
+// NewDictionaryArray constructs a dictionary array with the provided indices
+// and dictionary using the given type.
+func NewDictionaryArray(typ arrow.DataType, indices, dict Interface) *Dictionary {
+	a := &Dictionary{}
+	a.array.refCount = 1
+	dictdata := NewData(typ, indices.Len(), indices.Data().Buffers(), indices.Data().Children(), indices.NullN(), indices.Data().Offset())
+	dictdata.dictionary = dict.Data().(*Data)
+	dict.Data().Retain()
+
+	defer dictdata.Release()
+	a.setData(dictdata)
+	return a
+}
+
+// checkIndexBounds returns an error if any value in the provided integer
+// arraydata is >= the passed upperlimit or < 0. otherwise nil
+func checkIndexBounds(indices *Data, upperlimit uint64) error {
+	if indices.length == 0 {
+		return nil
+	}
+
+	var maxval uint64
+	switch indices.dtype.ID() {
+	case arrow.UINT8:
+		maxval = math.MaxUint8
+	case arrow.UINT16:
+		maxval = math.MaxUint16
+	case arrow.UINT32:
+		maxval = math.MaxUint32
+	case arrow.UINT64:
+		maxval = math.MaxUint64
+	}
+	isSigned := maxval == 0
+	if !isSigned && upperlimit > maxval {
+		return nil
+	}
+
+	// TODO(mtopol): lift BitSetRunReader from parquet to utils
+	// and use it here for performance improvement.
+	var nullbitmap []byte
+	if indices.buffers[0] != nil {
+		nullbitmap = indices.buffers[0].Bytes()
+	}
+
+	var outOfBounds func(i int) error
+	switch indices.dtype.ID() {
+	case arrow.INT8:
+		data := arrow.Int8Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] < 0 || data[i] >= int8(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.UINT8:
+		data := arrow.Uint8Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] >= uint8(upperlimit) {
+				return fmt.Errorf("index %d out of bounds", data[i])
+			}
+			return nil
+		}
+	case arrow.INT16:
+		data := arrow.Int16Traits.CastFromBytes(indices.buffers[1].Bytes())
+		outOfBounds = func(i int) error {
+			if data[i] < 0 || data[i] >= int16(upperlimit) {

Review comment:
       not sure if you care about perf here and what the SIMD version story is in Go but in C++ the compiler can use SIMD to take the min and max over the entire data array first.  Then checking the bounds of that min and max against 0 and upper bound.  (Not sure if the function to do this ended up in the parquet implementation native code).  The down-side is the error message has to be less precise (you can't can provide index without reiterating over the array but most arrays will be valid anyways).




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] emkornfield commented on a change in pull request #12158: ARROW-3039: [Go] Add support for DictionaryArray

Posted by GitBox <gi...@apache.org>.
emkornfield commented on a change in pull request #12158:
URL: https://github.com/apache/arrow/pull/12158#discussion_r800128445



##########
File path: go/arrow/array/dictionary.go
##########
@@ -0,0 +1,1305 @@
+// 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 array
+
+import (
+	"errors"
+	"fmt"
+	"math"
+	"sync/atomic"
+	"unsafe"
+
+	"github.com/apache/arrow/go/v7/arrow"
+	"github.com/apache/arrow/go/v7/arrow/bitutil"
+	"github.com/apache/arrow/go/v7/arrow/decimal128"
+	"github.com/apache/arrow/go/v7/arrow/float16"
+	"github.com/apache/arrow/go/v7/arrow/internal/debug"
+	"github.com/apache/arrow/go/v7/arrow/memory"
+	"github.com/apache/arrow/go/v7/internal/hashing"
+	"github.com/goccy/go-json"
+)
+
+// Dictionary represents the type for dictionary-encoded data with a data
+// dependent dictionary.
+//
+// A dictionary array contains an array of non-negative integers (the "dictionary"
+// indices") along with a data type containing a "dictionary" corresponding to
+// the distinct values represented in the data.
+//
+// For example, the array:
+//
+//      ["foo", "bar", "foo", "bar", "foo", "bar"]
+//
+// with dictionary ["bar", "foo"], would have the representation of:
+//
+//      indices: [1, 0, 1, 0, 1, 0]
+//      dictionary: ["bar", "foo"]
+//
+// The indices in principle may be any integer type.
+type Dictionary struct {
+	array
+
+	indices Interface
+	dict    Interface
+}
+
+// NewDictionaryArray constructs a dictionary array with the provided indices
+// and dictionary using the given type.
+func NewDictionaryArray(typ arrow.DataType, indices, dict Interface) *Dictionary {
+	a := &Dictionary{}
+	a.array.refCount = 1
+	dictdata := NewData(typ, indices.Len(), indices.Data().Buffers(), indices.Data().Children(), indices.NullN(), indices.Data().Offset())
+	dictdata.dictionary = dict.Data().(*Data)
+	dict.Data().Retain()
+
+	defer dictdata.Release()
+	a.setData(dictdata)
+	return a
+}
+
+// checkIndexBounds returns an error if any value in the provided integer
+// arraydata is >= the passed upperlimit or < 0. otherwise nil
+func checkIndexBounds(indices *Data, upperlimit uint64) error {
+	if indices.length == 0 {
+		return nil
+	}
+
+	var maxval uint64
+	switch indices.dtype.ID() {
+	case arrow.UINT8:
+		maxval = math.MaxUint8
+	case arrow.UINT16:
+		maxval = math.MaxUint16
+	case arrow.UINT32:
+		maxval = math.MaxUint32
+	case arrow.UINT64:
+		maxval = math.MaxUint64
+	}
+	isSigned := maxval == 0
+	if !isSigned && upperlimit > maxval {

Review comment:
       couldn't this check be applied to signed values as well?




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] emkornfield commented on a change in pull request #12158: ARROW-3039: [Go] Add support for DictionaryArray

Posted by GitBox <gi...@apache.org>.
emkornfield commented on a change in pull request #12158:
URL: https://github.com/apache/arrow/pull/12158#discussion_r800128349



##########
File path: go/arrow/array/dictionary.go
##########
@@ -0,0 +1,1305 @@
+// 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 array
+
+import (
+	"errors"
+	"fmt"
+	"math"
+	"sync/atomic"
+	"unsafe"
+
+	"github.com/apache/arrow/go/v7/arrow"
+	"github.com/apache/arrow/go/v7/arrow/bitutil"
+	"github.com/apache/arrow/go/v7/arrow/decimal128"
+	"github.com/apache/arrow/go/v7/arrow/float16"
+	"github.com/apache/arrow/go/v7/arrow/internal/debug"
+	"github.com/apache/arrow/go/v7/arrow/memory"
+	"github.com/apache/arrow/go/v7/internal/hashing"
+	"github.com/goccy/go-json"
+)
+
+// Dictionary represents the type for dictionary-encoded data with a data
+// dependent dictionary.
+//
+// A dictionary array contains an array of non-negative integers (the "dictionary"
+// indices") along with a data type containing a "dictionary" corresponding to
+// the distinct values represented in the data.
+//
+// For example, the array:
+//
+//      ["foo", "bar", "foo", "bar", "foo", "bar"]
+//
+// with dictionary ["bar", "foo"], would have the representation of:
+//
+//      indices: [1, 0, 1, 0, 1, 0]
+//      dictionary: ["bar", "foo"]
+//
+// The indices in principle may be any integer type.
+type Dictionary struct {
+	array
+
+	indices Interface
+	dict    Interface
+}
+
+// NewDictionaryArray constructs a dictionary array with the provided indices
+// and dictionary using the given type.
+func NewDictionaryArray(typ arrow.DataType, indices, dict Interface) *Dictionary {
+	a := &Dictionary{}
+	a.array.refCount = 1
+	dictdata := NewData(typ, indices.Len(), indices.Data().Buffers(), indices.Data().Children(), indices.NullN(), indices.Data().Offset())
+	dictdata.dictionary = dict.Data().(*Data)
+	dict.Data().Retain()
+
+	defer dictdata.Release()
+	a.setData(dictdata)
+	return a
+}
+
+// checkIndexBounds returns an error if any value in the provided integer
+// arraydata is >= the passed upperlimit or < 0. otherwise nil
+func checkIndexBounds(indices *Data, upperlimit uint64) error {
+	if indices.length == 0 {
+		return nil
+	}
+
+	var maxval uint64
+	switch indices.dtype.ID() {
+	case arrow.UINT8:
+		maxval = math.MaxUint8
+	case arrow.UINT16:
+		maxval = math.MaxUint16
+	case arrow.UINT32:
+		maxval = math.MaxUint32
+	case arrow.UINT64:
+		maxval = math.MaxUint64
+	}
+	isSigned := maxval == 0
+	if !isSigned && upperlimit > maxval {
+		return nil
+	}
+
+	// TODO(mtopol): lift BitSetRunReader from parquet to utils

Review comment:
       TODOs with links to JIRAs instead of contributors would be appreciated. 




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] emkornfield commented on pull request #12158: ARROW-3039: [Go] Add support for DictionaryArray

Posted by GitBox <gi...@apache.org>.
emkornfield commented on pull request #12158:
URL: https://github.com/apache/arrow/pull/12158#issuecomment-1057212930


   @zeroshade sorry to hear that.  Glad you are on the mend.  I figured I'd check in since I'm usually the bottleneck :)


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] zeroshade commented on pull request #12158: ARROW-3039: [Go] Add support for DictionaryArray

Posted by GitBox <gi...@apache.org>.
zeroshade commented on pull request #12158:
URL: https://github.com/apache/arrow/pull/12158#issuecomment-1071247615


   @emkornfield Delta and replacement dictionaries are handled at the bottom of the `readDictionary` function by calling `AddDelta` and `AddOrReplace` on the `memo` object, while the `memo` object is used when constructing the record batches with those dictionaries. 
   
   I've added the error case for IPC files to error out on a replacement dictionary. That should cover everything as far as I'm aware for now, and we're passing all the integration tests with dictionaries.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] zeroshade commented on a change in pull request #12158: ARROW-3039: [Go] Add support for DictionaryArray

Posted by GitBox <gi...@apache.org>.
zeroshade commented on a change in pull request #12158:
URL: https://github.com/apache/arrow/pull/12158#discussion_r828204207



##########
File path: go/arrow/array/data.go
##########
@@ -63,6 +64,16 @@ func NewData(dtype arrow.DataType, length int, buffers []*memory.Buffer, childDa
 	}
 }
 
+// NewDataWithDictionary creates a new data object, but also sets the provided dictionary into the data if it's not nil
+func NewDataWithDictionary(dtype arrow.DataType, length int, buffers []*memory.Buffer, childData []arrow.ArrayData, nulls, offset int, dict *Data) *Data {
+	data := NewData(dtype, length, buffers, childData, nulls, offset)

Review comment:
       also, we'd only verify that childData is empty *iff* dict is non-nil.
   
   @emkornfield do you know the answer to whether or not `childData` should *always* be empty for a dictionary array?




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [arrow] zeroshade commented on a change in pull request #12158: ARROW-3039: [Go] Add support for DictionaryArray

Posted by GitBox <gi...@apache.org>.
zeroshade commented on a change in pull request #12158:
URL: https://github.com/apache/arrow/pull/12158#discussion_r828247238



##########
File path: go/arrow/array/dictionary.go
##########
@@ -0,0 +1,1305 @@
+// 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 array
+
+import (
+	"errors"
+	"fmt"
+	"math"
+	"sync/atomic"
+	"unsafe"
+
+	"github.com/apache/arrow/go/v7/arrow"
+	"github.com/apache/arrow/go/v7/arrow/bitutil"
+	"github.com/apache/arrow/go/v7/arrow/decimal128"
+	"github.com/apache/arrow/go/v7/arrow/float16"
+	"github.com/apache/arrow/go/v7/arrow/internal/debug"
+	"github.com/apache/arrow/go/v7/arrow/memory"
+	"github.com/apache/arrow/go/v7/internal/hashing"
+	"github.com/goccy/go-json"
+)
+
+// Dictionary represents the type for dictionary-encoded data with a data
+// dependent dictionary.
+//
+// A dictionary array contains an array of non-negative integers (the "dictionary"
+// indices") along with a data type containing a "dictionary" corresponding to
+// the distinct values represented in the data.
+//
+// For example, the array:
+//
+//      ["foo", "bar", "foo", "bar", "foo", "bar"]
+//
+// with dictionary ["bar", "foo"], would have the representation of:
+//
+//      indices: [1, 0, 1, 0, 1, 0]
+//      dictionary: ["bar", "foo"]
+//
+// The indices in principle may be any integer type.
+type Dictionary struct {
+	array
+
+	indices Interface
+	dict    Interface
+}
+
+// NewDictionaryArray constructs a dictionary array with the provided indices
+// and dictionary using the given type.
+func NewDictionaryArray(typ arrow.DataType, indices, dict Interface) *Dictionary {
+	a := &Dictionary{}
+	a.array.refCount = 1
+	dictdata := NewData(typ, indices.Len(), indices.Data().Buffers(), indices.Data().Children(), indices.NullN(), indices.Data().Offset())
+	dictdata.dictionary = dict.Data().(*Data)
+	dict.Data().Retain()
+
+	defer dictdata.Release()
+	a.setData(dictdata)
+	return a
+}
+
+// checkIndexBounds returns an error if any value in the provided integer
+// arraydata is >= the passed upperlimit or < 0. otherwise nil
+func checkIndexBounds(indices *Data, upperlimit uint64) error {
+	if indices.length == 0 {
+		return nil
+	}
+
+	var maxval uint64
+	switch indices.dtype.ID() {
+	case arrow.UINT8:
+		maxval = math.MaxUint8
+	case arrow.UINT16:
+		maxval = math.MaxUint16
+	case arrow.UINT32:
+		maxval = math.MaxUint32
+	case arrow.UINT64:
+		maxval = math.MaxUint64
+	}
+	isSigned := maxval == 0
+	if !isSigned && upperlimit > maxval {

Review comment:
       I've added a comment there as to why we except signed values from this check, but basically:
   
   For unsigned integers, if `upperlimit > maxval` there's no need to bounds check at all, but for signed integers the value could still be < 0, so we still need to do the bounds check to confirm.




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org