Skip to content

Commit

Permalink
Merge pull request #2228 from jackc/fix-xml-decode-value
Browse files Browse the repository at this point in the history
XMLCodec: fix DecodeValue to return a []byte
  • Loading branch information
jackc authored Jan 25, 2025
2 parents 5f33ee5 + 03f08ab commit 2d21a2b
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 1 deletion.
20 changes: 19 additions & 1 deletion pgtype/pgtype_default.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,25 @@ func initDefaultMap() {
defaultMap.RegisterType(&Type{Name: "varchar", OID: VarcharOID, Codec: TextCodec{}})
defaultMap.RegisterType(&Type{Name: "xid", OID: XIDOID, Codec: Uint32Codec{}})
defaultMap.RegisterType(&Type{Name: "xid8", OID: XID8OID, Codec: Uint64Codec{}})
defaultMap.RegisterType(&Type{Name: "xml", OID: XMLOID, Codec: &XMLCodec{Marshal: xml.Marshal, Unmarshal: xml.Unmarshal}})
defaultMap.RegisterType(&Type{Name: "xml", OID: XMLOID, Codec: &XMLCodec{
Marshal: xml.Marshal,
// xml.Unmarshal does not support unmarshalling into *any. However, XMLCodec.DecodeValue calls Unmarshal with a
// *any. Wrap xml.Marshal with a function that copies the data into a new byte slice in this case. Not implementing
// directly in XMLCodec.DecodeValue to allow for the unlikely possibility that someone uses an alternative XML
// unmarshaler that does support unmarshalling into *any.
//
// https://github.com/jackc/pgx/issues/2227
// https://github.com/jackc/pgx/pull/2228
Unmarshal: func(data []byte, v any) error {
if v, ok := v.(*any); ok {
dstBuf := make([]byte, len(data))
copy(dstBuf, data)
*v = dstBuf
return nil
}
return xml.Unmarshal(data, v)
},
}})

// Range types
defaultMap.RegisterType(&Type{Name: "daterange", OID: DaterangeOID, Codec: &RangeCodec{ElementType: defaultMap.oidToType[DateOID]}})
Expand Down
29 changes: 29 additions & 0 deletions pgtype/xml_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,3 +97,32 @@ func TestXMLCodecPointerToPointerToString(t *testing.T) {
require.Nil(t, s)
})
}

func TestXMLCodecDecodeValue(t *testing.T) {
skipCockroachDB(t, "CockroachDB does not support XML.")
defaultConnTestRunner.RunTest(context.Background(), t, func(ctx context.Context, _ testing.TB, conn *pgx.Conn) {
for _, tt := range []struct {
sql string
expected any
}{
{
sql: `select '<foo>bar</foo>'::xml`,
expected: []byte("<foo>bar</foo>"),
},
} {
t.Run(tt.sql, func(t *testing.T) {
rows, err := conn.Query(ctx, tt.sql)
require.NoError(t, err)

for rows.Next() {
values, err := rows.Values()
require.NoError(t, err)
require.Len(t, values, 1)
require.Equal(t, tt.expected, values[0])
}

require.NoError(t, rows.Err())
})
}
})
}

0 comments on commit 2d21a2b

Please sign in to comment.