mirror of
https://gitee.com/dromara/carbon.git
synced 2024-11-29 18:57:37 +08:00
解析数据库字段时增加对字符串和字节的支持
This commit is contained in:
parent
05f128d5c0
commit
2397dc4ddf
31
database.go
31
database.go
@ -2,22 +2,33 @@ package carbon
|
||||
|
||||
import (
|
||||
"database/sql/driver"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
// returns a failed scan error.
|
||||
// 失败的扫描错误
|
||||
var failedScanError = func(src interface{}) error {
|
||||
return errors.New(fmt.Sprintf("failed to scan value: %v", src))
|
||||
}
|
||||
|
||||
// Scan an interface used by Scan in package database/sql for Scanning value from database to local golang variable.
|
||||
func (c *Carbon) Scan(v interface{}) error {
|
||||
if value, ok := v.(time.Time); ok {
|
||||
loc, err := getLocationByTimezone(defaultTimezone)
|
||||
if c.loc != nil {
|
||||
loc = c.loc
|
||||
}
|
||||
*c = CreateFromStdTime(value)
|
||||
c.loc, c.Error = loc, err
|
||||
return nil
|
||||
func (c *Carbon) Scan(src interface{}) error {
|
||||
switch v := src.(type) {
|
||||
case []byte:
|
||||
*c = Parse(string(v))
|
||||
case string:
|
||||
*c = Parse(v)
|
||||
case time.Time:
|
||||
*c = CreateFromStdTime(v)
|
||||
default:
|
||||
return failedScanError(src)
|
||||
}
|
||||
return fmt.Errorf("can not convert %v to carbon", v)
|
||||
if c.Error != nil {
|
||||
return failedScanError(src)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Value the interface providing the Value method for package database/sql/driver.
|
||||
|
@ -1,7 +1,6 @@
|
||||
package carbon
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@ -23,9 +22,20 @@ func TestCarbon_Value(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestError_Scan(t *testing.T) {
|
||||
c, v := NewCarbon(), "xxx"
|
||||
err := c.Scan(v)
|
||||
assert.Equal(t, err, fmt.Errorf("can not convert %v to carbon", v))
|
||||
c := NewCarbon()
|
||||
str, bytes, time, dt := "xxx", []byte("xxx"), time.Now(), DateTime{}
|
||||
|
||||
err1 := c.Scan(str)
|
||||
assert.Equal(t, err1, failedScanError(str))
|
||||
|
||||
err2 := c.Scan(bytes)
|
||||
assert.Equal(t, err2, failedScanError(bytes))
|
||||
|
||||
err3 := c.Scan(time)
|
||||
assert.Equal(t, err3, nil)
|
||||
|
||||
err4 := c.Scan(dt)
|
||||
assert.Equal(t, err4, failedScanError(dt))
|
||||
}
|
||||
|
||||
func TestError_Value(t *testing.T) {
|
||||
|
Loading…
Reference in New Issue
Block a user