-
Notifications
You must be signed in to change notification settings - Fork 0
/
types.go
48 lines (40 loc) · 945 Bytes
/
types.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package sqljson
import (
"database/sql/driver"
"encoding/json"
"errors"
"fmt"
"reflect"
)
type JSON[T any] struct {
Item T
}
func From[T any](input T) JSON[T] {
return JSON[T]{Item: input}
}
func (j *JSON[T]) Scan(value interface{}) error {
bytes, ok := value.([]byte)
if !ok {
return errors.New(fmt.Sprint("Failed to unmarshal JSONB value:", value))
}
return json.Unmarshal(bytes, &j.Item)
}
func (j JSON[T]) Value() (driver.Value, error) {
itemValue := reflect.ValueOf(j.Item)
switch itemValue.Kind() {
case reflect.Chan, reflect.Func, reflect.Map, reflect.Pointer, reflect.UnsafePointer, reflect.Interface, reflect.Slice:
if itemValue.IsNil() {
return nil, nil
}
}
return json.Marshal(j.Item)
}
func (j JSON[T]) MarshalJSON() ([]byte, error) {
return json.Marshal(j.Item)
}
func (j *JSON[T]) UnmarshalJSON(data []byte) error {
var out JSON[T]
err := json.Unmarshal(data, &out.Item)
*j = out
return err
}