GORM fournit quelques interfaces qui permettent aux utilisateurs de définir des types de données personnalisés bien pris en charge pour GORM, prend json comme exemple
Implémenter de type de données personnalisées
Scanner / Valuer
The customized data type has to implement the Scanner and Valuer interfaces, so GORM knowns to how to receive/save it into the database
For example:
type JSON json.RawMessage |
There are many third party packages implement the Scanner
/Valuer
interface, which can be used with GORM together, for example:
import ( |
GormDataTypeInterface
GORM will read column’s database type from tag type
, if not found, will check if the struct implemented interface GormDBDataTypeInterface
or GormDataTypeInterface
and will use its result as data type
type GormDataTypeInterface interface { |
The result of GormDataType
will be used as the general data type and can be obtained from schema.Field
‘s field DataType
, which might be helpful when writing plugins or hooks for example:
func (JSON) GormDataType() string { |
GormDBDataType
usually returns the right data type for current driver when migrating, for example:
func (JSON) GormDBDataType(db *gorm.DB, field *schema.Field) string { |
If the struct hasn’t implemented the GormDBDataTypeInterface
or GormDataTypeInterface
interface, GORM will guess its data type from the struct’s first field, for example, will use string
for NullString
type NullString struct { |
GormValuerInterface
GORM provides a GormValuerInterface
interface, which can allow to create/update from SQL Expr or value based on context, for example:
// GORM Valuer interface |
Create/Update from SQL Expr
type Location struct { |
You can also create/update with SQL Expr from map, checkout Create From SQL Expr and Update with SQL Expression for details
Value based on Context
If you want to create or update a value depends on current context, you can also implements the GormValuerInterface
interface, for example:
type EncryptedString struct { |
Clause Expression
If you want to build some query helpers, you can make a struct that implements the clause.Expression
interface:
type Expression interface { |
Checkout JSON and SQL Builder for details, the following is an example of usage:
// Generates SQL with clause Expression |
Customized Data Types Collections
We created a Github repo for customized data types collections https://github.com/go-gorm/datatypes, pull request welcome ;)