Merge pull request #454 from regeda/macaddr-array

macaddr array is introduced
pull/455/head
Jack Christensen 2018-09-01 22:46:13 -04:00 committed by GitHub
commit e44f0f24c4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 407 additions and 0 deletions

301
pgtype/macaddr_array.go Normal file
View File

@ -0,0 +1,301 @@
package pgtype
import (
"database/sql/driver"
"encoding/binary"
"net"
"github.com/jackc/pgx/pgio"
"github.com/pkg/errors"
)
type MacaddrArray struct {
Elements []Macaddr
Dimensions []ArrayDimension
Status Status
}
func (dst *MacaddrArray) Set(src interface{}) error {
// untyped nil and typed nil interfaces are different
if src == nil {
*dst = MacaddrArray{Status: Null}
return nil
}
switch value := src.(type) {
case []net.HardwareAddr:
if value == nil {
*dst = MacaddrArray{Status: Null}
} else if len(value) == 0 {
*dst = MacaddrArray{Status: Present}
} else {
elements := make([]Macaddr, len(value))
for i := range value {
if err := elements[i].Set(value[i]); err != nil {
return err
}
}
*dst = MacaddrArray{
Elements: elements,
Dimensions: []ArrayDimension{{Length: int32(len(elements)), LowerBound: 1}},
Status: Present,
}
}
default:
if originalSrc, ok := underlyingSliceType(src); ok {
return dst.Set(originalSrc)
}
return errors.Errorf("cannot convert %v to MacaddrArray", value)
}
return nil
}
func (dst *MacaddrArray) Get() interface{} {
switch dst.Status {
case Present:
return dst
case Null:
return nil
default:
return dst.Status
}
}
func (src *MacaddrArray) AssignTo(dst interface{}) error {
switch src.Status {
case Present:
switch v := dst.(type) {
case *[]net.HardwareAddr:
*v = make([]net.HardwareAddr, len(src.Elements))
for i := range src.Elements {
if err := src.Elements[i].AssignTo(&((*v)[i])); err != nil {
return err
}
}
return nil
default:
if nextDst, retry := GetAssignToDstType(dst); retry {
return src.AssignTo(nextDst)
}
}
case Null:
return NullAssignTo(dst)
}
return errors.Errorf("cannot decode %#v into %T", src, dst)
}
func (dst *MacaddrArray) DecodeText(ci *ConnInfo, src []byte) error {
if src == nil {
*dst = MacaddrArray{Status: Null}
return nil
}
uta, err := ParseUntypedTextArray(string(src))
if err != nil {
return err
}
var elements []Macaddr
if len(uta.Elements) > 0 {
elements = make([]Macaddr, len(uta.Elements))
for i, s := range uta.Elements {
var elem Macaddr
var elemSrc []byte
if s != "NULL" {
elemSrc = []byte(s)
}
err = elem.DecodeText(ci, elemSrc)
if err != nil {
return err
}
elements[i] = elem
}
}
*dst = MacaddrArray{Elements: elements, Dimensions: uta.Dimensions, Status: Present}
return nil
}
func (dst *MacaddrArray) DecodeBinary(ci *ConnInfo, src []byte) error {
if src == nil {
*dst = MacaddrArray{Status: Null}
return nil
}
var arrayHeader ArrayHeader
rp, err := arrayHeader.DecodeBinary(ci, src)
if err != nil {
return err
}
if len(arrayHeader.Dimensions) == 0 {
*dst = MacaddrArray{Dimensions: arrayHeader.Dimensions, Status: Present}
return nil
}
elementCount := arrayHeader.Dimensions[0].Length
for _, d := range arrayHeader.Dimensions[1:] {
elementCount *= d.Length
}
elements := make([]Macaddr, elementCount)
for i := range elements {
elemLen := int(int32(binary.BigEndian.Uint32(src[rp:])))
rp += 4
var elemSrc []byte
if elemLen >= 0 {
elemSrc = src[rp : rp+elemLen]
rp += elemLen
}
err = elements[i].DecodeBinary(ci, elemSrc)
if err != nil {
return err
}
}
*dst = MacaddrArray{Elements: elements, Dimensions: arrayHeader.Dimensions, Status: Present}
return nil
}
func (src *MacaddrArray) EncodeText(ci *ConnInfo, buf []byte) ([]byte, error) {
switch src.Status {
case Null:
return nil, nil
case Undefined:
return nil, errUndefined
}
if len(src.Dimensions) == 0 {
return append(buf, '{', '}'), nil
}
buf = EncodeTextArrayDimensions(buf, src.Dimensions)
// dimElemCounts is the multiples of elements that each array lies on. For
// example, a single dimension array of length 4 would have a dimElemCounts of
// [4]. A multi-dimensional array of lengths [3,5,2] would have a
// dimElemCounts of [30,10,2]. This is used to simplify when to render a '{'
// or '}'.
dimElemCounts := make([]int, len(src.Dimensions))
dimElemCounts[len(src.Dimensions)-1] = int(src.Dimensions[len(src.Dimensions)-1].Length)
for i := len(src.Dimensions) - 2; i > -1; i-- {
dimElemCounts[i] = int(src.Dimensions[i].Length) * dimElemCounts[i+1]
}
inElemBuf := make([]byte, 0, 32)
for i, elem := range src.Elements {
if i > 0 {
buf = append(buf, ',')
}
for _, dec := range dimElemCounts {
if i%dec == 0 {
buf = append(buf, '{')
}
}
elemBuf, err := elem.EncodeText(ci, inElemBuf)
if err != nil {
return nil, err
}
if elemBuf == nil {
buf = append(buf, `NULL`...)
} else {
buf = append(buf, QuoteArrayElementIfNeeded(string(elemBuf))...)
}
for _, dec := range dimElemCounts {
if (i+1)%dec == 0 {
buf = append(buf, '}')
}
}
}
return buf, nil
}
func (src *MacaddrArray) EncodeBinary(ci *ConnInfo, buf []byte) ([]byte, error) {
switch src.Status {
case Null:
return nil, nil
case Undefined:
return nil, errUndefined
}
arrayHeader := ArrayHeader{
Dimensions: src.Dimensions,
}
if dt, ok := ci.DataTypeForName("macaddr"); ok {
arrayHeader.ElementOID = int32(dt.OID)
} else {
return nil, errors.Errorf("unable to find oid for type name %v", "macaddr")
}
for i := range src.Elements {
if src.Elements[i].Status == Null {
arrayHeader.ContainsNull = true
break
}
}
buf = arrayHeader.EncodeBinary(ci, buf)
for i := range src.Elements {
sp := len(buf)
buf = pgio.AppendInt32(buf, -1)
elemBuf, err := src.Elements[i].EncodeBinary(ci, buf)
if err != nil {
return nil, err
}
if elemBuf != nil {
buf = elemBuf
pgio.SetInt32(buf[sp:], int32(len(buf[sp:])-4))
}
}
return buf, nil
}
// Scan implements the database/sql Scanner interface.
func (dst *MacaddrArray) Scan(src interface{}) error {
if src == nil {
return dst.DecodeText(nil, nil)
}
switch src := src.(type) {
case string:
return dst.DecodeText(nil, []byte(src))
case []byte:
srcCopy := make([]byte, len(src))
copy(srcCopy, src)
return dst.DecodeText(nil, srcCopy)
}
return errors.Errorf("cannot scan %T", src)
}
// Value implements the database/sql/driver Valuer interface.
func (src *MacaddrArray) Value() (driver.Value, error) {
buf, err := src.EncodeText(nil, nil)
if err != nil {
return nil, err
}
if buf == nil {
return nil, nil
}
return string(buf), nil
}

View File

@ -0,0 +1,105 @@
package pgtype_test
import (
"net"
"reflect"
"testing"
"github.com/jackc/pgx/pgtype"
"github.com/jackc/pgx/pgtype/testutil"
)
func TestMacaddrArrayTranscode(t *testing.T) {
testutil.TestSuccessfulTranscode(t, "macaddr[]", []interface{}{
&pgtype.MacaddrArray{
Elements: nil,
Dimensions: nil,
Status: pgtype.Present,
},
&pgtype.MacaddrArray{
Elements: []pgtype.Macaddr{
{Addr: mustParseMacaddr(t, "01:23:45:67:89:ab"), Status: pgtype.Present},
{Status: pgtype.Null},
},
Dimensions: []pgtype.ArrayDimension{{Length: 2, LowerBound: 1}},
Status: pgtype.Present,
},
&pgtype.MacaddrArray{Status: pgtype.Null},
})
}
func TestMacaddrArraySet(t *testing.T) {
successfulTests := []struct {
source interface{}
result pgtype.MacaddrArray
}{
{
source: []net.HardwareAddr{mustParseMacaddr(t, "01:23:45:67:89:ab")},
result: pgtype.MacaddrArray{
Elements: []pgtype.Macaddr{{Addr: mustParseMacaddr(t, "01:23:45:67:89:ab"), Status: pgtype.Present}},
Dimensions: []pgtype.ArrayDimension{{LowerBound: 1, Length: 1}},
Status: pgtype.Present},
},
{
source: (([]net.HardwareAddr)(nil)),
result: pgtype.MacaddrArray{Status: pgtype.Null},
},
}
for i, tt := range successfulTests {
var r pgtype.MacaddrArray
err := r.Set(tt.source)
if err != nil {
t.Errorf("%d: %v", i, err)
}
if !reflect.DeepEqual(r, tt.result) {
t.Errorf("%d: expected %v to convert to %v, but it was %v", i, tt.source, tt.result, r)
}
}
}
func TestMacaddrArrayAssignTo(t *testing.T) {
var macaddrSlice []net.HardwareAddr
simpleTests := []struct {
src pgtype.MacaddrArray
dst interface{}
expected interface{}
}{
{
src: pgtype.MacaddrArray{
Elements: []pgtype.Macaddr{{Addr: mustParseMacaddr(t, "01:23:45:67:89:ab"), Status: pgtype.Present}},
Dimensions: []pgtype.ArrayDimension{{LowerBound: 1, Length: 1}},
Status: pgtype.Present,
},
dst: &macaddrSlice,
expected: []net.HardwareAddr{mustParseMacaddr(t, "01:23:45:67:89:ab")},
},
{
src: pgtype.MacaddrArray{
Elements: []pgtype.Macaddr{{Status: pgtype.Null}},
Dimensions: []pgtype.ArrayDimension{{LowerBound: 1, Length: 1}},
Status: pgtype.Present,
},
dst: &macaddrSlice,
expected: []net.HardwareAddr{nil},
},
{
src: pgtype.MacaddrArray{Status: pgtype.Null},
dst: &macaddrSlice,
expected: (([]net.HardwareAddr)(nil)),
},
}
for i, tt := range simpleTests {
err := tt.src.AssignTo(tt.dst)
if err != nil {
t.Errorf("%d: %v", i, err)
}
if dst := reflect.ValueOf(tt.dst).Elem().Interface(); !reflect.DeepEqual(dst, tt.expected) {
t.Errorf("%d: expected %v to assign %v, but result was %v", i, tt.src, tt.expected, dst)
}
}
}

View File

@ -8,6 +8,7 @@ erb pgtype_array_type=TimestampArray pgtype_element_type=Timestamp go_array_type
erb pgtype_array_type=Float4Array pgtype_element_type=Float4 go_array_types=[]float32 element_type_name=float4 text_null=NULL binary_format=true typed_array.go.erb > float4_array.go
erb pgtype_array_type=Float8Array pgtype_element_type=Float8 go_array_types=[]float64 element_type_name=float8 text_null=NULL binary_format=true typed_array.go.erb > float8_array.go
erb pgtype_array_type=InetArray pgtype_element_type=Inet go_array_types=[]*net.IPNet,[]net.IP element_type_name=inet text_null=NULL binary_format=true typed_array.go.erb > inet_array.go
erb pgtype_array_type=MacaddrArray pgtype_element_type=Macaddr go_array_types=[]net.HardwareAddr element_type_name=macaddr text_null=NULL binary_format=true typed_array.go.erb > macaddr_array.go
erb pgtype_array_type=CIDRArray pgtype_element_type=CIDR go_array_types=[]*net.IPNet,[]net.IP element_type_name=cidr text_null=NULL binary_format=true typed_array.go.erb > cidr_array.go
erb pgtype_array_type=TextArray pgtype_element_type=Text go_array_types=[]string element_type_name=text text_null='"NULL"' binary_format=true typed_array.go.erb > text_array.go
erb pgtype_array_type=VarcharArray pgtype_element_type=Varchar go_array_types=[]string element_type_name=varchar text_null='"NULL"' binary_format=true typed_array.go.erb > varchar_array.go