schema
v1.31.2
Documentation
pkg.go.dev ↗Package schema provides the Schema struct and related functions for parsing and managing database schemas in GORM.
Constants
DefaultAutoIncrementIncrement
const DefaultAutoIncrementIncrement int64 = 1
Variables
TimeReflectType (3 declarations)
var (
TimeReflectType = reflect.TypeOf(time.Time{})
TimePtrReflectType = reflect.TypeOf(&time.Time{})
ByteReflectType = reflect.TypeOf(uint8(0))
)
special types' reflect type
ErrUnsupportedDataType
var ErrUnsupportedDataType = errors.New("unsupported data type")
ErrUnsupportedDataType unsupported data type
Functions
GetIdentityFieldValuesMap
func GetIdentityFieldValuesMap(ctx context.Context, reflectValue reflect.Value, fields []*Field) (map[string][]reflect.Value, [][]interface{})
GetIdentityFieldValuesMap get identity map from fields
GetIdentityFieldValuesMapFromValues
func GetIdentityFieldValuesMapFromValues(ctx context.Context, values []interface{}, fields []*Field) (map[string][]reflect.Value, [][]interface{})
GetIdentityFieldValuesMapFromValues get identity map from fields
GetRelationsValues
func GetRelationsValues(ctx context.Context, reflectValue reflect.Value, rels []*Relationship) (reflectResults reflect.Value)
GetRelationsValues get relations's values from a reflect value
ParseTagSetting
func ParseTagSetting(str string, sep string) map[string]string
RegisterSerializer
func RegisterSerializer(name string, serializer SerializerInterface)
RegisterSerializer register serializer
ToQueryValues
func ToQueryValues(table string, foreignKeys []string, foreignValues [][]interface{}) (interface{}, []interface{})
ToQueryValues to query values
Types
CheckConstraint
type CheckConstraint struct {
Name string
Constraint string // length(phone) >= 10
*Field
}
CheckConstraint.Build
func (chk *CheckConstraint) Build() (sql string, vars []interface{})
CheckConstraint.GetName
func (chk *CheckConstraint) GetName() string
Constraint
type Constraint struct {
Name string
Field *Field
Schema *Schema
ForeignKeys []*Field
ReferenceSchema *Schema
References []*Field
OnDelete string
OnUpdate string
}
Constraint is ForeignKey Constraint
Constraint.Build
func (constraint *Constraint) Build() (sql string, vars []interface{})
Constraint.GetName
func (constraint *Constraint) GetName() string
ConstraintInterface
type ConstraintInterface interface {
GetName() string
Build() (sql string, vars []interface{})
}
ConstraintInterface database constraint interface
CreateClausesInterface
type CreateClausesInterface interface {
CreateClauses(*Field) []clause.Interface
}
CreateClausesInterface create clauses interface
DataType
type DataType string
DataType GORM data type
Bool (7 declarations)
const ( Bool DataType = "bool" Int DataType = "int" Uint DataType = "uint" Float DataType = "float" String DataType = "string" Time DataType = "time" Bytes DataType = "bytes" )
GORM fields types
DeleteClausesInterface
type DeleteClausesInterface interface {
DeleteClauses(*Field) []clause.Interface
}
DeleteClausesInterface delete clauses interface
Field
type Field struct {
Name string
DBName string
BindNames []string
EmbeddedBindNames []string
DataType DataType
GORMDataType DataType
PrimaryKey bool
AutoIncrement bool
AutoIncrementIncrement int64
Creatable bool
Updatable bool
Readable bool
AutoCreateTime TimeType
AutoUpdateTime TimeType
HasDefaultValue bool
DefaultValue string
DefaultValueInterface interface{}
NotNull bool
Unique bool
Comment string
Size int
Precision int
Scale int
IgnoreMigration bool
FieldType reflect.Type
IndirectFieldType reflect.Type
StructField reflect.StructField
Tag reflect.StructTag
TagSettings map[string]string
Schema *Schema
EmbeddedSchema *Schema
OwnerSchema *Schema
ReflectValueOf func(context.Context, reflect.Value) reflect.Value
ValueOf func(context.Context, reflect.Value) (value interface{}, zero bool)
Set func(context.Context, reflect.Value, interface{}) error
Serializer SerializerInterface
NewValuePool FieldNewValuePool
// In some db (e.g. MySQL), Unique and UniqueIndex are indistinguishable.
// When a column has a (not Mul) UniqueIndex, Migrator always reports its gorm.ColumnType is Unique.
// It causes field unnecessarily migration.
// Therefore, we need to record the UniqueIndex on this column (exclude Mul UniqueIndex) for MigrateColumnUnique.
UniqueIndex string
}
Field is the representation of model schema's field
Field.BindName
func (field *Field) BindName() string
FieldNewValuePool
type FieldNewValuePool interface {
Get() interface{}
Put(interface{})
}
FieldNewValuePool field new scan value pool
GobSerializer
type GobSerializer struct{}
GobSerializer gob serializer
GobSerializer.Scan
func (GobSerializer) Scan(ctx context.Context, field *Field, dst reflect.Value, dbValue interface{}) (err error)
Scan implements serializer interface
GobSerializer.Value
func (GobSerializer) Value(ctx context.Context, field *Field, dst reflect.Value, fieldValue interface{}) (interface{}, error)
Value implements serializer interface
GormDataTypeInterface
type GormDataTypeInterface interface {
GormDataType() string
}
GormDataTypeInterface gorm data type interface
Index
type Index struct {
Name string
Class string // UNIQUE | FULLTEXT | SPATIAL
Type string // btree, hash, gist, spgist, gin, and brin
Where string
Comment string
Option string // WITH PARSER parser_name
Fields []IndexOption // Note: IndexOption's Field maybe the same
}
IndexOption
type IndexOption struct {
*Field
Expression string
Sort string // DESC, ASC
Collate string
Length int
Priority int
}
JSONSerializer
type JSONSerializer struct{}
JSONSerializer json serializer
JSONSerializer.Scan
func (JSONSerializer) Scan(ctx context.Context, field *Field, dst reflect.Value, dbValue interface{}) (err error)
Scan implements serializer interface
JSONSerializer.Value
func (JSONSerializer) Value(ctx context.Context, field *Field, dst reflect.Value, fieldValue interface{}) (interface{}, error)
Value implements serializer interface
Namer
type Namer interface {
TableName(table string) string
SchemaName(table string) string
ColumnName(table, column string) string
JoinTableName(joinTable string) string
RelationshipFKName(Relationship) string
CheckerName(table, column string) string
IndexName(table, column string) string
UniqueName(table, column string) string
}
Namer namer interface
NamingStrategy
type NamingStrategy struct {
TablePrefix string
SingularTable bool
NameReplacer Replacer
NoLowerCase bool
IdentifierMaxLength int
}
NamingStrategy tables, columns naming strategy
NamingStrategy.CheckerName
func (ns NamingStrategy) CheckerName(table, column string) string
CheckerName generate checker name
NamingStrategy.ColumnName
func (ns NamingStrategy) ColumnName(table, column string) string
ColumnName convert string to column name
NamingStrategy.IndexName
func (ns NamingStrategy) IndexName(table, column string) string
IndexName generate index name
NamingStrategy.JoinTableName
func (ns NamingStrategy) JoinTableName(str string) string
JoinTableName convert string to join table name
NamingStrategy.RelationshipFKName
func (ns NamingStrategy) RelationshipFKName(rel Relationship) string
RelationshipFKName generate fk name for relation
NamingStrategy.SchemaName
func (ns NamingStrategy) SchemaName(table string) string
SchemaName generate schema name from table name, don't guarantee it is the reverse value of TableName
NamingStrategy.TableName
func (ns NamingStrategy) TableName(str string) string
TableName convert string to table name
NamingStrategy.UniqueName
func (ns NamingStrategy) UniqueName(table, column string) string
UniqueName generate unique constraint name
Polymorphic
type Polymorphic struct {
PolymorphicID *Field
PolymorphicType *Field
Value string
}
QueryClausesInterface
type QueryClausesInterface interface {
QueryClauses(*Field) []clause.Interface
}
QueryClausesInterface query clauses interface
Reference
type Reference struct {
PrimaryKey *Field
PrimaryValue string
ForeignKey *Field
OwnPrimaryKey bool
}
Relationship
type Relationship struct {
Name string
Type RelationshipType
Field *Field
Polymorphic *Polymorphic
References []*Reference
Schema *Schema
FieldSchema *Schema
JoinTable *Schema
// contains filtered or unexported fields
}
Relationship.ParseConstraint
func (rel *Relationship) ParseConstraint() *Constraint
Relationship.ToQueryConditions
func (rel *Relationship) ToQueryConditions(ctx context.Context, reflectValue reflect.Value) (conds []clause.Expression)
RelationshipType
type RelationshipType string
RelationshipType relationship type
HasOne (4 declarations)
const ( HasOne RelationshipType = "has_one" // HasOneRel has one relationship HasMany RelationshipType = "has_many" // HasManyRel has many relationship BelongsTo RelationshipType = "belongs_to" // BelongsToRel belongs to relationship Many2Many RelationshipType = "many_to_many" // Many2ManyRel many to many relationship )
Relationships
type Relationships struct {
HasOne []*Relationship
BelongsTo []*Relationship
HasMany []*Relationship
Many2Many []*Relationship
Relations map[string]*Relationship
EmbeddedRelations map[string]*Relationships
Mux sync.RWMutex
}
Replacer
type Replacer interface {
Replace(name string) string
}
Replacer replacer interface like strings.Replacer
Schema
type Schema struct {
Name string
ModelType reflect.Type
Table string
PrioritizedPrimaryField *Field
DBNames []string
PrimaryFields []*Field
PrimaryFieldDBNames []string
Fields []*Field
FieldsByName map[string]*Field
FieldsByBindName map[string]*Field // embedded fields is 'Embed.Field'
FieldsByDBName map[string]*Field
FieldsWithDefaultDBValue []*Field // fields with default value assigned by database
Relationships Relationships
CreateClauses []clause.Interface
QueryClauses []clause.Interface
UpdateClauses []clause.Interface
DeleteClauses []clause.Interface
BeforeCreate, AfterCreate bool
BeforeUpdate, AfterUpdate bool
BeforeDelete, AfterDelete bool
BeforeSave, AfterSave bool
AfterFind bool
// contains filtered or unexported fields
}
Parse
func Parse(dest interface{}, cacheStore *sync.Map, namer Namer) (*Schema, error)
Parse get data type from dialector
ParseWithSpecialTableName
func ParseWithSpecialTableName(dest interface{}, cacheStore *sync.Map, namer Namer, specialTableName string) (*Schema, error)
ParseWithSpecialTableName get data type from dialector with extra schema table
Schema.LookIndex
func (schema *Schema) LookIndex(name string) *Index
Schema.LookUpField
func (schema *Schema) LookUpField(name string) *Field
Schema.LookUpFieldByBindName
func (schema *Schema) LookUpFieldByBindName(bindNames []string, name string) *Field
LookUpFieldByBindName looks for the closest field in the embedded struct.
Struct
type Struct struct {
Embedded struct {
ID string // is selected by LookUpFieldByBindName([]string{"Embedded", "ID"}, "ID")
}
ID string // is selected by LookUpFieldByBindName([]string{"ID"}, "ID")
}
Schema.MakeSlice
func (schema *Schema) MakeSlice() reflect.Value
Schema.ParseCheckConstraints
func (schema *Schema) ParseCheckConstraints() map[string]CheckConstraint
ParseCheckConstraints parse schema check constraints
Schema.ParseField
func (schema *Schema) ParseField(fieldStruct reflect.StructField) *Field
ParseField parses reflect.StructField to Field
Schema.ParseIndexes
func (schema *Schema) ParseIndexes() []*Index
ParseIndexes parse schema indexes
Schema.ParseUniqueConstraints
func (schema *Schema) ParseUniqueConstraints() map[string]UniqueConstraint
ParseUniqueConstraints parse schema unique constraints
Schema.String
func (schema *Schema) String() string
SerializerInterface
type SerializerInterface interface {
Scan(ctx context.Context, field *Field, dst reflect.Value, dbValue interface{}) error
SerializerValuerInterface
}
SerializerInterface serializer interface
GetSerializer
func GetSerializer(name string) (serializer SerializerInterface, ok bool)
GetSerializer get serializer
SerializerValuerInterface
type SerializerValuerInterface interface {
Value(ctx context.Context, field *Field, dst reflect.Value, fieldValue interface{}) (interface{}, error)
}
SerializerValuerInterface serializer valuer interface
Tabler
type Tabler interface {
TableName() string
}
TablerWithNamer
type TablerWithNamer interface {
TableName(Namer) string
}
TimeType
type TimeType int64
TimeType GORM time type
UnixTime (4 declarations)
const ( UnixTime TimeType = 1 UnixSecond TimeType = 2 UnixMillisecond TimeType = 3 UnixNanosecond TimeType = 4 )
GORM time types
UniqueConstraint
type UniqueConstraint struct {
Name string
Field *Field
}
UniqueConstraint.Build
func (uni *UniqueConstraint) Build() (sql string, vars []interface{})
UniqueConstraint.GetName
func (uni *UniqueConstraint) GetName() string
UnixSecondSerializer
type UnixSecondSerializer struct{}
UnixSecondSerializer json serializer
UnixSecondSerializer.Scan
func (UnixSecondSerializer) Scan(ctx context.Context, field *Field, dst reflect.Value, dbValue interface{}) (err error)
Scan implements serializer interface
UnixSecondSerializer.Value
func (UnixSecondSerializer) Value(ctx context.Context, field *Field, dst reflect.Value, fieldValue interface{}) (result interface{}, err error)
Value implements serializer interface
UpdateClausesInterface
type UpdateClausesInterface interface {
UpdateClauses(*Field) []clause.Interface
}
UpdateClausesInterface update clauses interface