Adding json type for mssql dialect, similar to postgres.Jsonb

This commit is contained in:
Louis Brauer 2018-06-07 00:54:24 +02:00
parent 82eb9f8a5b
commit 1aca53985b

View File

@ -1,6 +1,9 @@
package mssql package mssql
import ( import (
"database/sql/driver"
"encoding/json"
"errors"
"fmt" "fmt"
"reflect" "reflect"
"strconv" "strconv"
@ -201,3 +204,25 @@ func currentDatabaseAndTable(dialect gorm.Dialect, tableName string) (string, st
} }
return dialect.CurrentDatabase(), tableName return dialect.CurrentDatabase(), tableName
} }
type Json struct {
json.RawMessage
}
// Value get value of Jsonb
func (j Json) Value() (driver.Value, error) {
if len(j.RawMessage) == 0 {
return nil, nil
}
return j.MarshalJSON()
}
// Scan scan value into Json
func (j *Json) Scan(value interface{}) error {
str, ok := value.(string)
if !ok {
return errors.New(fmt.Sprint("Failed to unmarshal JSONB value (strcast):", value))
}
bytes := []byte(str)
return json.Unmarshal(bytes, j)
}