Last active
March 11, 2024 19:53
-
-
Save jquiterio/ef31f8640ebe2960a8fd3a0bcccd9689 to your computer and use it in GitHub Desktop.
JSONMap definition for gorm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ( | |
"database/sql/driver" | |
"encoding/json" | |
"errors" | |
"fmt" | |
"gorm.io/gorm" | |
"gorm.io/gorm/schema" | |
) | |
// JSONMap defiend JSON data type, need to implements driver.Valuer, sql.Scanner interface | |
type JSONMap map[string]interface{} | |
// Value return json value, implement driver.Valuer interface | |
func (m JSONMap) Value() (driver.Value, error) { | |
if m == nil { | |
return nil, nil | |
} | |
ba, err := m.MarshalJSON() | |
return string(ba), err | |
} | |
// Scan scan value into Jsonb, implements sql.Scanner interface | |
func (m *JSONMap) Scan(val interface{}) error { | |
var ba []byte | |
switch v := val.(type) { | |
case []byte: | |
ba = v | |
case string: | |
ba = []byte(v) | |
default: | |
return errors.New(fmt.Sprint("Failed to unmarshal JSONB value:", val)) | |
} | |
t := map[string]interface{}{} | |
err := json.Unmarshal(ba, &t) | |
*m = JSONMap(t) | |
return err | |
} | |
// MarshalJSON to output non base64 encoded []byte | |
func (m JSONMap) MarshalJSON() ([]byte, error) { | |
if m == nil { | |
return []byte("null"), nil | |
} | |
t := (map[string]interface{})(m) | |
return json.Marshal(t) | |
} | |
// UnmarshalJSON to deserialize []byte | |
func (m *JSONMap) UnmarshalJSON(b []byte) error { | |
t := map[string]interface{}{} | |
err := json.Unmarshal(b, &t) | |
*m = JSONMap(t) | |
return err | |
} | |
// GormDataType gorm common data type | |
func (m JSONMap) GormDataType() string { | |
return "jsonmap" | |
} | |
// GormDBDataType gorm db data type | |
func (JSONMap) GormDBDataType(db *gorm.DB, field *schema.Field) string { | |
switch db.Dialector.Name() { | |
case "sqlite": | |
return "JSON" | |
case "mysql": | |
return "JSON" | |
case "postgres": | |
return "JSONB" | |
} | |
return "" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment