2
0

Convert polygon to Codec

This commit is contained in:
Jack Christensen
2022-01-18 12:04:17 -06:00
parent 11d96fb928
commit abd7e98f31
3 changed files with 223 additions and 219 deletions
+1 -1
View File
@@ -326,7 +326,7 @@ func NewConnInfo() *ConnInfo {
ci.RegisterDataType(DataType{Name: "oid", OID: OIDOID, Codec: Uint32Codec{}}) ci.RegisterDataType(DataType{Name: "oid", OID: OIDOID, Codec: Uint32Codec{}})
ci.RegisterDataType(DataType{Name: "path", OID: PathOID, Codec: PathCodec{}}) ci.RegisterDataType(DataType{Name: "path", OID: PathOID, Codec: PathCodec{}})
ci.RegisterDataType(DataType{Name: "point", OID: PointOID, Codec: PointCodec{}}) ci.RegisterDataType(DataType{Name: "point", OID: PointOID, Codec: PointCodec{}})
ci.RegisterDataType(DataType{Value: &Polygon{}, Name: "polygon", OID: PolygonOID}) ci.RegisterDataType(DataType{Name: "polygon", OID: PolygonOID, Codec: PolygonCodec{}})
// ci.RegisterDataType(DataType{Value: &Record{}, Name: "record", OID: RecordOID}) // ci.RegisterDataType(DataType{Value: &Record{}, Name: "record", OID: RecordOID})
ci.RegisterDataType(DataType{Name: "text", OID: TextOID, Codec: TextCodec{}}) ci.RegisterDataType(DataType{Name: "text", OID: TextOID, Codec: TextCodec{}})
ci.RegisterDataType(DataType{Value: &TID{}, Name: "tid", OID: TIDOID}) ci.RegisterDataType(DataType{Value: &TID{}, Name: "tid", OID: TIDOID})
+180 -142
View File
@@ -11,81 +11,195 @@ import (
"github.com/jackc/pgio" "github.com/jackc/pgio"
) )
type PolygonScanner interface {
ScanPolygon(v Polygon) error
}
type PolygonValuer interface {
PolygonValue() (Polygon, error)
}
type Polygon struct { type Polygon struct {
P []Vec2 P []Vec2
Valid bool Valid bool
} }
// Set converts src to dest. func (p *Polygon) ScanPolygon(v Polygon) error {
// *p = v
// src can be nil, string, []float64, and []pgtype.Vec2.
//
// If src is string the format must be ((x1,y1),(x2,y2),...,(xn,yn)).
// Important that there are no spaces in it.
func (dst *Polygon) Set(src interface{}) error {
if src == nil {
dst.Valid = false
return nil
}
err := fmt.Errorf("cannot convert %v to Polygon", src)
var p *Polygon
switch value := src.(type) {
case string:
p, err = stringToPolygon(value)
case []Vec2:
p = &Polygon{Valid: true, P: value}
err = nil
case []float64:
p, err = float64ToPolygon(value)
default:
return err
}
if err != nil {
return err
}
*dst = *p
return nil return nil
} }
func stringToPolygon(src string) (*Polygon, error) { func (p Polygon) PolygonValue() (Polygon, error) {
p := &Polygon{}
err := p.DecodeText(nil, []byte(src))
return p, err
}
func float64ToPolygon(src []float64) (*Polygon, error) {
p := &Polygon{}
if len(src) == 0 {
return p, nil
}
if len(src)%2 != 0 {
return p, fmt.Errorf("invalid length for polygon: %v", len(src))
}
p.Valid = true
p.P = make([]Vec2, 0)
for i := 0; i < len(src); i += 2 {
p.P = append(p.P, Vec2{X: src[i], Y: src[i+1]})
}
return p, nil return p, nil
} }
func (dst Polygon) Get() interface{} { // Scan implements the database/sql Scanner interface.
if !dst.Valid { func (p *Polygon) Scan(src interface{}) error {
if src == nil {
*p = Polygon{}
return nil return nil
} }
return dst
switch src := src.(type) {
case string:
return scanPlanTextAnyToPolygonScanner{}.Scan(nil, 0, TextFormatCode, []byte(src), p)
}
return fmt.Errorf("cannot scan %T", src)
} }
func (src *Polygon) AssignTo(dst interface{}) error { // Value implements the database/sql/driver Valuer interface.
return fmt.Errorf("cannot assign %v to %T", src, dst) func (p Polygon) Value() (driver.Value, error) {
if !p.Valid {
return nil, nil
}
buf, err := PolygonCodec{}.PlanEncode(nil, 0, TextFormatCode, p).Encode(p, nil)
if err != nil {
return nil, err
}
return string(buf), err
} }
func (dst *Polygon) DecodeText(ci *ConnInfo, src []byte) error { type PolygonCodec struct{}
if src == nil {
*dst = Polygon{} func (PolygonCodec) FormatSupported(format int16) bool {
return format == TextFormatCode || format == BinaryFormatCode
}
func (PolygonCodec) PreferredFormat() int16 {
return BinaryFormatCode
}
func (PolygonCodec) PlanEncode(ci *ConnInfo, oid uint32, format int16, value interface{}) EncodePlan {
if _, ok := value.(PolygonValuer); !ok {
return nil return nil
} }
switch format {
case BinaryFormatCode:
return encodePlanPolygonCodecBinary{}
case TextFormatCode:
return encodePlanPolygonCodecText{}
}
return nil
}
type encodePlanPolygonCodecBinary struct{}
func (encodePlanPolygonCodecBinary) Encode(value interface{}, buf []byte) (newBuf []byte, err error) {
polygon, err := value.(PolygonValuer).PolygonValue()
if err != nil {
return nil, err
}
if !polygon.Valid {
return nil, nil
}
buf = pgio.AppendInt32(buf, int32(len(polygon.P)))
for _, p := range polygon.P {
buf = pgio.AppendUint64(buf, math.Float64bits(p.X))
buf = pgio.AppendUint64(buf, math.Float64bits(p.Y))
}
return buf, nil
}
type encodePlanPolygonCodecText struct{}
func (encodePlanPolygonCodecText) Encode(value interface{}, buf []byte) (newBuf []byte, err error) {
polygon, err := value.(PolygonValuer).PolygonValue()
if err != nil {
return nil, err
}
if !polygon.Valid {
return nil, nil
}
buf = append(buf, '(')
for i, p := range polygon.P {
if i > 0 {
buf = append(buf, ',')
}
buf = append(buf, fmt.Sprintf(`(%s,%s)`,
strconv.FormatFloat(p.X, 'f', -1, 64),
strconv.FormatFloat(p.Y, 'f', -1, 64),
)...)
}
buf = append(buf, ')')
return buf, nil
}
func (PolygonCodec) PlanScan(ci *ConnInfo, oid uint32, format int16, target interface{}, actualTarget bool) ScanPlan {
switch format {
case BinaryFormatCode:
switch target.(type) {
case PolygonScanner:
return scanPlanBinaryPolygonToPolygonScanner{}
}
case TextFormatCode:
switch target.(type) {
case PolygonScanner:
return scanPlanTextAnyToPolygonScanner{}
}
}
return nil
}
type scanPlanBinaryPolygonToPolygonScanner struct{}
func (scanPlanBinaryPolygonToPolygonScanner) Scan(ci *ConnInfo, oid uint32, formatCode int16, src []byte, dst interface{}) error {
scanner := (dst).(PolygonScanner)
if src == nil {
return scanner.ScanPolygon(Polygon{})
}
if len(src) < 5 {
return fmt.Errorf("invalid length for polygon: %v", len(src))
}
pointCount := int(binary.BigEndian.Uint32(src))
rp := 4
if 4+pointCount*16 != len(src) {
return fmt.Errorf("invalid length for Polygon with %d points: %v", pointCount, len(src))
}
points := make([]Vec2, pointCount)
for i := 0; i < len(points); i++ {
x := binary.BigEndian.Uint64(src[rp:])
rp += 8
y := binary.BigEndian.Uint64(src[rp:])
rp += 8
points[i] = Vec2{math.Float64frombits(x), math.Float64frombits(y)}
}
return scanner.ScanPolygon(Polygon{
P: points,
Valid: true,
})
}
type scanPlanTextAnyToPolygonScanner struct{}
func (scanPlanTextAnyToPolygonScanner) Scan(ci *ConnInfo, oid uint32, formatCode int16, src []byte, dst interface{}) error {
scanner := (dst).(PolygonScanner)
if src == nil {
return scanner.ScanPolygon(Polygon{})
}
if len(src) < 7 { if len(src) < 7 {
return fmt.Errorf("invalid length for Polygon: %v", len(src)) return fmt.Errorf("invalid length for Polygon: %v", len(src))
} }
@@ -118,98 +232,22 @@ func (dst *Polygon) DecodeText(ci *ConnInfo, src []byte) error {
} }
} }
*dst = Polygon{P: points, Valid: true} return scanner.ScanPolygon(Polygon{P: points, Valid: true})
return nil
} }
func (dst *Polygon) DecodeBinary(ci *ConnInfo, src []byte) error { func (c PolygonCodec) DecodeDatabaseSQLValue(ci *ConnInfo, oid uint32, format int16, src []byte) (driver.Value, error) {
return codecDecodeToTextFormat(c, ci, oid, format, src)
}
func (c PolygonCodec) DecodeValue(ci *ConnInfo, oid uint32, format int16, src []byte) (interface{}, error) {
if src == nil { if src == nil {
*dst = Polygon{}
return nil
}
if len(src) < 5 {
return fmt.Errorf("invalid length for Polygon: %v", len(src))
}
pointCount := int(binary.BigEndian.Uint32(src))
rp := 4
if 4+pointCount*16 != len(src) {
return fmt.Errorf("invalid length for Polygon with %d points: %v", pointCount, len(src))
}
points := make([]Vec2, pointCount)
for i := 0; i < len(points); i++ {
x := binary.BigEndian.Uint64(src[rp:])
rp += 8
y := binary.BigEndian.Uint64(src[rp:])
rp += 8
points[i] = Vec2{math.Float64frombits(x), math.Float64frombits(y)}
}
*dst = Polygon{
P: points,
Valid: true,
}
return nil
}
func (src Polygon) EncodeText(ci *ConnInfo, buf []byte) ([]byte, error) {
if !src.Valid {
return nil, nil return nil, nil
} }
buf = append(buf, '(') var polygon Polygon
err := codecScan(c, ci, oid, format, src, &polygon)
for i, p := range src.P { if err != nil {
if i > 0 { return nil, err
buf = append(buf, ',')
}
buf = append(buf, fmt.Sprintf(`(%s,%s)`,
strconv.FormatFloat(p.X, 'f', -1, 64),
strconv.FormatFloat(p.Y, 'f', -1, 64),
)...)
} }
return polygon, nil
return append(buf, ')'), nil
}
func (src Polygon) EncodeBinary(ci *ConnInfo, buf []byte) ([]byte, error) {
if !src.Valid {
return nil, nil
}
buf = pgio.AppendInt32(buf, int32(len(src.P)))
for _, p := range src.P {
buf = pgio.AppendUint64(buf, math.Float64bits(p.X))
buf = pgio.AppendUint64(buf, math.Float64bits(p.Y))
}
return buf, nil
}
// Scan implements the database/sql Scanner interface.
func (dst *Polygon) Scan(src interface{}) error {
if src == nil {
*dst = Polygon{}
return 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 fmt.Errorf("cannot scan %T", src)
}
// Value implements the database/sql/driver Valuer interface.
func (src Polygon) Value() (driver.Value, error) {
return EncodeValueText(src)
} }
+42 -76
View File
@@ -4,86 +4,52 @@ import (
"testing" "testing"
"github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgtype"
"github.com/jackc/pgx/v5/pgtype/testutil"
) )
func TestPolygonTranscode(t *testing.T) { func isExpectedEqPolygon(a interface{}) func(interface{}) bool {
testutil.TestSuccessfulTranscode(t, "polygon", []interface{}{ return func(v interface{}) bool {
&pgtype.Polygon{ ap := a.(pgtype.Polygon)
P: []pgtype.Vec2{{3.14, 1.678901234}, {7.1, 5.234}, {5.0, 3.234}}, vp := v.(pgtype.Polygon)
Valid: true,
}, if !(ap.Valid == vp.Valid && len(ap.P) == len(vp.P)) {
&pgtype.Polygon{ return false
P: []pgtype.Vec2{{3.14, -1.678}, {7.1, -5.234}, {23.1, 9.34}}, }
Valid: true,
}, for i := range ap.P {
&pgtype.Polygon{}, if ap.P[i] != vp.P[i] {
}) return false
}
}
return true
}
} }
func TestPolygon_Set(t *testing.T) { func TestPolygonTranscode(t *testing.T) {
tests := []struct { testPgxCodec(t, "polygon", []PgxTranscodeTestCase{
name string
arg interface{}
valid bool
wantErr bool
}{
{ {
name: "string", pgtype.Polygon{
arg: "((3.14,1.678901234),(7.1,5.234),(5.0,3.234))", P: []pgtype.Vec2{{3.14, 1.678901234}, {7.1, 5.234}, {5.0, 3.234}},
valid: true, Valid: true,
wantErr: false, },
}, { new(pgtype.Polygon),
name: "[]float64", isExpectedEqPolygon(pgtype.Polygon{
arg: []float64{1, 2, 3.45, 6.78, 1.23, 4.567, 8.9, 1.0}, P: []pgtype.Vec2{{3.14, 1.678901234}, {7.1, 5.234}, {5.0, 3.234}},
valid: true, Valid: true,
wantErr: false, }),
}, {
name: "[]Vec2",
arg: []pgtype.Vec2{{1, 2}, {2.3, 4.5}, {6.78, 9.123}},
valid: true,
wantErr: false,
}, {
name: "null",
arg: nil,
valid: false,
wantErr: false,
}, {
name: "invalid_string_1",
arg: "((3.14,1.678901234),(7.1,5.234),(5.0,3.234x))",
valid: false,
wantErr: true,
}, {
name: "invalid_string_2",
arg: "(3,4)",
valid: false,
wantErr: true,
}, {
name: "invalid_[]float64",
arg: []float64{1, 2, 3.45, 6.78, 1.23, 4.567, 8.9},
valid: false,
wantErr: true,
}, {
name: "invalid_type",
arg: []int{1, 2, 3, 6},
valid: false,
wantErr: true,
}, {
name: "empty_[]float64",
arg: []float64{},
valid: false,
wantErr: false,
}, },
} {
for _, tt := range tests { pgtype.Polygon{
t.Run(tt.name, func(t *testing.T) { P: []pgtype.Vec2{{3.14, -1.678}, {7.1, -5.234}, {23.1, 9.34}},
dst := &pgtype.Polygon{} Valid: true,
if err := dst.Set(tt.arg); (err != nil) != tt.wantErr { },
t.Errorf("Set() error = %v, wantErr %v", err, tt.wantErr) new(pgtype.Polygon),
} isExpectedEqPolygon(pgtype.Polygon{
if dst.Valid != tt.valid { P: []pgtype.Vec2{{3.14, -1.678}, {7.1, -5.234}, {23.1, 9.34}},
t.Errorf("Expected valid: %v; got: %v", tt.valid, dst.Valid) Valid: true,
} }),
}) },
} {pgtype.Polygon{}, new(pgtype.Polygon), isExpectedEqPolygon(pgtype.Polygon{})},
{nil, new(pgtype.Polygon), isExpectedEqPolygon(pgtype.Polygon{})},
})
} }