Add database/sql support to pgtype
This commit is contained in:
@@ -1,7 +1,9 @@
|
||||
package pgtype
|
||||
|
||||
import (
|
||||
"database/sql/driver"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
)
|
||||
|
||||
@@ -11,6 +13,11 @@ type Json struct {
|
||||
}
|
||||
|
||||
func (dst *Json) Set(src interface{}) error {
|
||||
if src == nil {
|
||||
*dst = Json{Status: Null}
|
||||
return nil
|
||||
}
|
||||
|
||||
switch value := src.(type) {
|
||||
case string:
|
||||
*dst = Json{Bytes: []byte(value), Status: Present}
|
||||
@@ -116,3 +123,32 @@ func (src Json) EncodeText(ci *ConnInfo, w io.Writer) (bool, error) {
|
||||
func (src Json) EncodeBinary(ci *ConnInfo, w io.Writer) (bool, error) {
|
||||
return src.EncodeText(ci, w)
|
||||
}
|
||||
|
||||
// Scan implements the database/sql Scanner interface.
|
||||
func (dst *Json) Scan(src interface{}) error {
|
||||
if src == nil {
|
||||
*dst = Json{Status: Null}
|
||||
return nil
|
||||
}
|
||||
|
||||
switch src := src.(type) {
|
||||
case string:
|
||||
return dst.DecodeText(nil, []byte(src))
|
||||
case []byte:
|
||||
return dst.DecodeText(nil, src)
|
||||
}
|
||||
|
||||
return fmt.Errorf("cannot scan %T", src)
|
||||
}
|
||||
|
||||
// Value implements the database/sql/driver Valuer interface.
|
||||
func (src Json) Value() (driver.Value, error) {
|
||||
switch src.Status {
|
||||
case Present:
|
||||
return src.Bytes, nil
|
||||
case Null:
|
||||
return nil, nil
|
||||
default:
|
||||
return nil, errUndefined
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user