39 lines
877 B
Go
39 lines
877 B
Go
|
|
// Package orm define database data struct
|
||
|
|
package orm
|
||
|
|
|
||
|
|
import (
|
||
|
|
"database/sql/driver"
|
||
|
|
"encoding/json"
|
||
|
|
"errors"
|
||
|
|
)
|
||
|
|
|
||
|
|
// JSONMap define struct of implements the sql.Scanner and driver.Valuer interfaces for handling JSONB fields
|
||
|
|
type JSONMap map[string]any
|
||
|
|
|
||
|
|
// Value define func to convert the JSONMap to driver.Value([]byte) for writing to the database
|
||
|
|
func (j JSONMap) Value() (driver.Value, error) {
|
||
|
|
if j == nil {
|
||
|
|
return nil, nil
|
||
|
|
}
|
||
|
|
return json.Marshal(j)
|
||
|
|
}
|
||
|
|
|
||
|
|
// Scan define to scanned values([]bytes) in the database and parsed into a JSONMap for data retrieval
|
||
|
|
func (j *JSONMap) Scan(value any) error {
|
||
|
|
if value == nil {
|
||
|
|
*j = nil
|
||
|
|
return nil
|
||
|
|
}
|
||
|
|
|
||
|
|
var source []byte
|
||
|
|
switch v := value.(type) {
|
||
|
|
case []byte:
|
||
|
|
source = v
|
||
|
|
case string:
|
||
|
|
source = []byte(v)
|
||
|
|
default:
|
||
|
|
return errors.New("unsupported data type for JSONMap Scan")
|
||
|
|
}
|
||
|
|
return json.Unmarshal(source, j)
|
||
|
|
}
|