Skip to content

Commit

Permalink
Add support for string and []byte when parsing database data
Browse files Browse the repository at this point in the history
  • Loading branch information
gouguoyin committed Nov 24, 2024
1 parent 9707d88 commit 8636334
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 14 deletions.
31 changes: 21 additions & 10 deletions database.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
if c.Error != nil {
return failedScanError(src)
}
return fmt.Errorf("can not convert %v to carbon", v)
return nil
}

// Value the interface providing the Value method for package database/sql/driver.
Expand Down
18 changes: 14 additions & 4 deletions database_unit_test.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package carbon

import (
"fmt"
"testing"
"time"

Expand All @@ -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) {
Expand Down

0 comments on commit 8636334

Please sign in to comment.