Detect erroneous JSON(B) encoding

JSON(B) automatically marshals any value. Avoid marshalling values of
pgtype.JSON and pgtype.JSONB. The caller certainly meant to call on a
pointer.

See https://github.com/jackc/pgx/issues/350 for discussion.

refs #350
This commit is contained in:
Jack Christensen 2017-11-04 19:09:24 -05:00
parent 425fbe1c88
commit f6d37536c4

View File

@ -33,6 +33,15 @@ func (dst *JSON) Set(src interface{}) error {
} else {
*dst = JSON{Bytes: value, Status: Present}
}
// Encode* methods are defined on *JSON. If JSON is passed directly then the
// struct itself would be encoded instead of Bytes. This is clearly a footgun
// so detect and return an error. See https://github.com/jackc/pgx/issues/350.
case JSON:
return errors.New("use pointer to pgtype.JSON instead of value")
// Same as above but for JSONB (because they share implementation)
case JSONB:
return errors.New("use pointer to pgtype.JSONB instead of value")
default:
buf, err := json.Marshal(value)
if err != nil {