自訂資料類型

GORM 提供少數介面,讓使用者可以為 GORM 定義良好支援的自訂資料類型,以 json 為例

實作自訂資料類型

Scanner / Valuer

自訂資料類型必須實作 ScannerValuer 介面,這樣 GORM 才知道如何接收/儲存資料到資料庫中

例如

type JSON json.RawMessage

// Scan scan value into Jsonb, implements sql.Scanner interface
func (j *JSON) Scan(value interface{}) error {
bytes, ok := value.([]byte)
if !ok {
return errors.New(fmt.Sprint("Failed to unmarshal JSONB value:", value))
}

result := json.RawMessage{}
err := json.Unmarshal(bytes, &result)
*j = JSON(result)
return err
}

// Value return json value, implement driver.Valuer interface
func (j JSON) Value() (driver.Value, error) {
if len(j) == 0 {
return nil, nil
}
return json.RawMessage(j).MarshalJSON()
}

有許多第三方套件實作 Scanner/Valuer 介面,可以與 GORM 搭配使用,例如

import (
"github.com/google/uuid"
"github.com/lib/pq"
)

type Post struct {
ID uuid.UUID `gorm:"type:uuid;default:uuid_generate_v4()"`
Title string
Tags pq.StringArray `gorm:"type:text[]"`
}

GormDataTypeInterface

GORM 會從 標籤 type 讀取欄位的資料庫類型,如果找不到,會檢查結構是否實作介面 GormDBDataTypeInterfaceGormDataTypeInterface,並會使用其結果作為資料類型

type GormDataTypeInterface interface {
GormDataType() string
}

type GormDBDataTypeInterface interface {
GormDBDataType(*gorm.DB, *schema.Field) string
}

GormDataType 的結果會用作一般資料類型,而且可以從 schema.Field 的欄位 DataType 取得,這在 撰寫外掛程式hook 時可能會很有用

func (JSON) GormDataType() string {
return "json"
}

type User struct {
Attrs JSON
}

func (user User) BeforeCreate(tx *gorm.DB) {
field := tx.Statement.Schema.LookUpField("Attrs")
if field.DataType == "json" {
// do something
}
}

GormDBDataType 通常會在遷移時傳回目前驅動程式的正確資料類型,例如

func (JSON) GormDBDataType(db *gorm.DB, field *schema.Field) string {
// use field.Tag, field.TagSettings gets field's tags
// checkout https://github.com/go-gorm/gorm/blob/master/schema/field.go for all options

// returns different database type based on driver name
switch db.Dialector.Name() {
case "mysql", "sqlite":
return "JSON"
case "postgres":
return "JSONB"
}
return ""
}

如果結構未實作 GormDBDataTypeInterfaceGormDataTypeInterface 介面,GORM 會從結構的第一個欄位猜測其資料類型,例如,會對 NullString 使用 string

type NullString struct {
String string // use the first field's data type
Valid bool
}

type User struct {
Name NullString // data type will be string
}

GormValuerInterface

GORM 提供了一個 GormValuerInterface 介面,它允許根據 SQL Expr 或基於上下文的 value 來建立/更新,例如

// GORM Valuer interface
type GormValuerInterface interface {
GormValue(ctx context.Context, db *gorm.DB) clause.Expr
}

建立/更新自 SQL Expr

type Location struct {
X, Y int
}

func (loc Location) GormDataType() string {
return "geometry"
}

func (loc Location) GormValue(ctx context.Context, db *gorm.DB) clause.Expr {
return clause.Expr{
SQL: "ST_PointFromText(?)",
Vars: []interface{}{fmt.Sprintf("POINT(%d %d)", loc.X, loc.Y)},
}
}

// Scan implements the sql.Scanner interface
func (loc *Location) Scan(v interface{}) error {
// Scan a value into struct from database driver
}

type User struct {
ID int
Name string
Location Location
}

db.Create(&User{
Name: "jinzhu",
Location: Location{X: 100, Y: 100},
})
// INSERT INTO `users` (`name`,`point`) VALUES ("jinzhu",ST_PointFromText("POINT(100 100)"))

db.Model(&User{ID: 1}).Updates(User{
Name: "jinzhu",
Location: Location{X: 100, Y: 100},
})
// UPDATE `user_with_points` SET `name`="jinzhu",`location`=ST_PointFromText("POINT(100 100)") WHERE `id` = 1

您也可以使用來自 map 的 SQL Expr 來建立/更新,請查看 從 SQL Expr 建立使用 SQL 表達式更新 以取得詳細資訊

基於上下文的 值

如果您想要建立或更新一個取決於當前上下文的 value,您也可以實作 GormValuerInterface 介面,例如

type EncryptedString struct {
Value string
}

func (es EncryptedString) GormValue(ctx context.Context, db *gorm.DB) (expr clause.Expr) {
if encryptionKey, ok := ctx.Value("TenantEncryptionKey").(string); ok {
return clause.Expr{SQL: "?", Vars: []interface{}{Encrypt(es.Value, encryptionKey)}}
} else {
db.AddError(errors.New("invalid encryption key"))
}

return
}

子句表達式

如果您想要建立一些查詢輔助程式,您可以建立一個實作 clause.Expression 介面的結構

type Expression interface {
Build(builder Builder)
}

請查看 JSONSQL Builder 以取得詳細資訊,以下是使用範例

// Generates SQL with clause Expression
db.Find(&user, datatypes.JSONQuery("attributes").HasKey("role"))
db.Find(&user, datatypes.JSONQuery("attributes").HasKey("orgs", "orga"))

// MySQL
// SELECT * FROM `users` WHERE JSON_EXTRACT(`attributes`, '$.role') IS NOT NULL
// SELECT * FROM `users` WHERE JSON_EXTRACT(`attributes`, '$.orgs.orga') IS NOT NULL

// PostgreSQL
// SELECT * FROM "user" WHERE "attributes"::jsonb ? 'role'
// SELECT * FROM "user" WHERE "attributes"::jsonb -> 'orgs' ? 'orga'

db.Find(&user, datatypes.JSONQuery("attributes").Equals("jinzhu", "name"))
// MySQL
// SELECT * FROM `user` WHERE JSON_EXTRACT(`attributes`, '$.name') = "jinzhu"

// PostgreSQL
// SELECT * FROM "user" WHERE json_extract_path_text("attributes"::json,'name') = 'jinzhu'

自訂資料類型集合

我們為自訂資料類型集合建立了一個 Github repo https://github.com/go-gorm/datatypes,歡迎提出 pull request ;)

白金贊助商

黃金贊助商

白金贊助商

黃金贊助商