common: add database/sql support for Hash and Address (#15541)

This commit is contained in:
Vincent Serpoul
2018-07-24 21:15:07 +08:00
committed by Felix Lange
parent d96ba77113
commit 2909f6d7a2
2 changed files with 219 additions and 2 deletions

View File

@ -17,6 +17,7 @@
package common
import (
"database/sql/driver"
"encoding/hex"
"encoding/json"
"fmt"
@ -31,7 +32,9 @@ import (
// Lengths of hashes and addresses in bytes.
const (
HashLength = 32
// HashLength is the expected length of the hash
HashLength = 32
// AddressLength is the expected length of the adddress
AddressLength = 20
)
@ -120,6 +123,24 @@ func (h Hash) Generate(rand *rand.Rand, size int) reflect.Value {
return reflect.ValueOf(h)
}
// Scan implements Scanner for database/sql.
func (h *Hash) Scan(src interface{}) error {
srcB, ok := src.([]byte)
if !ok {
return fmt.Errorf("can't scan %T into Hash", src)
}
if len(srcB) != HashLength {
return fmt.Errorf("can't scan []byte of len %d into Hash, want %d", len(srcB), HashLength)
}
copy(h[:], srcB)
return nil
}
// Value implements valuer for database/sql.
func (h Hash) Value() (driver.Value, error) {
return h[:], nil
}
// UnprefixedHash allows marshaling a Hash without 0x prefix.
type UnprefixedHash Hash
@ -229,6 +250,24 @@ func (a *Address) UnmarshalJSON(input []byte) error {
return hexutil.UnmarshalFixedJSON(addressT, input, a[:])
}
// Scan implements Scanner for database/sql.
func (a *Address) Scan(src interface{}) error {
srcB, ok := src.([]byte)
if !ok {
return fmt.Errorf("can't scan %T into Address", src)
}
if len(srcB) != AddressLength {
return fmt.Errorf("can't scan []byte of len %d into Address, want %d", len(srcB), AddressLength)
}
copy(a[:], srcB)
return nil
}
// Value implements valuer for database/sql.
func (a Address) Value() (driver.Value, error) {
return a[:], nil
}
// UnprefixedAddress allows marshaling an Address without 0x prefix.
type UnprefixedAddress Address