解析数据库字段时增加对字符串和字节的支持

This commit is contained in:
gouguoyin 2024-11-25 01:05:42 +08:00
parent 05f128d5c0
commit 2397dc4ddf
2 changed files with 35 additions and 14 deletions

View File

@ -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.

View File

@ -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) {