2019-08-20 15:38:40 +00:00
|
|
|
package sqlite
|
|
|
|
|
|
|
|
import (
|
|
|
|
"database/sql/driver"
|
|
|
|
"encoding/json"
|
|
|
|
"errors"
|
|
|
|
"reflect"
|
|
|
|
)
|
|
|
|
|
|
|
|
// JSONBlob type for marshaling/unmarshaling inner type to json.
|
|
|
|
type JSONBlob struct {
|
|
|
|
Data interface{}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Scan implements interface.
|
|
|
|
func (blob *JSONBlob) Scan(value interface{}) error {
|
|
|
|
dataVal := reflect.ValueOf(blob.Data)
|
|
|
|
if value == nil || dataVal.Kind() == reflect.Ptr && dataVal.IsNil() {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
bytes, ok := value.([]byte)
|
|
|
|
if !ok {
|
|
|
|
return errors.New("not a byte slice")
|
|
|
|
}
|
|
|
|
if len(bytes) == 0 {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
err := json.Unmarshal(bytes, blob.Data)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Value implements interface.
|
|
|
|
func (blob *JSONBlob) Value() (driver.Value, error) {
|
|
|
|
dataVal := reflect.ValueOf(blob.Data)
|
2022-03-23 18:47:00 +00:00
|
|
|
if (blob.Data == nil) || (dataVal.Kind() == reflect.Ptr && dataVal.IsNil()) {
|
2019-08-20 15:38:40 +00:00
|
|
|
return nil, nil
|
|
|
|
}
|
2022-03-23 18:47:00 +00:00
|
|
|
|
|
|
|
switch dataVal.Kind() {
|
|
|
|
case reflect.Slice, reflect.Array, reflect.Map:
|
|
|
|
if dataVal.Len() == 0 {
|
|
|
|
return nil, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-08-20 15:38:40 +00:00
|
|
|
return json.Marshal(blob.Data)
|
|
|
|
}
|