gorm/model_struct.go

362 lines
11 KiB
Go
Raw Normal View History

2015-02-15 18:01:09 +03:00
package gorm
import (
"database/sql"
2015-02-16 11:35:26 +03:00
"fmt"
2015-02-15 18:01:09 +03:00
"go/ast"
"reflect"
2015-02-16 11:35:26 +03:00
"regexp"
2015-02-15 18:01:09 +03:00
"strconv"
2015-02-16 11:35:26 +03:00
"strings"
2015-02-15 18:01:09 +03:00
"time"
)
2015-02-16 07:04:46 +03:00
type ModelStruct struct {
PrimaryKeyField *StructField
StructFields []*StructField
2015-02-18 07:30:09 +03:00
ModelType reflect.Type
2015-02-16 07:04:46 +03:00
TableName string
}
2015-02-15 18:01:09 +03:00
type StructField struct {
2015-02-18 05:19:34 +03:00
DBName string
Name string
Names []string
IsPrimaryKey bool
IsNormal bool
IsIgnored bool
IsScanner bool
HasDefaultValue bool
SqlTag string
Tag reflect.StructTag
Struct reflect.StructField
IsForeignKey bool
Relationship *Relationship
2015-02-16 07:04:46 +03:00
}
2015-02-17 18:18:12 +03:00
func (structField *StructField) clone() *StructField {
return &StructField{
2015-02-18 05:19:34 +03:00
DBName: structField.DBName,
Name: structField.Name,
Names: structField.Names,
IsPrimaryKey: structField.IsPrimaryKey,
IsNormal: structField.IsNormal,
IsIgnored: structField.IsIgnored,
IsScanner: structField.IsScanner,
HasDefaultValue: structField.HasDefaultValue,
SqlTag: structField.SqlTag,
Tag: structField.Tag,
Struct: structField.Struct,
IsForeignKey: structField.IsForeignKey,
Relationship: structField.Relationship,
2015-02-17 18:18:12 +03:00
}
}
2015-02-16 07:04:46 +03:00
type Relationship struct {
Kind string
2015-02-18 07:30:09 +03:00
PolymorphicType string
PolymorphicDBName string
2015-02-16 07:04:46 +03:00
ForeignFieldName string
ForeignDBName string
AssociationForeignFieldName string
AssociationForeignDBName string
JoinTable string
2015-02-15 18:01:09 +03:00
}
2015-02-16 11:35:26 +03:00
var pluralMapKeys = []*regexp.Regexp{regexp.MustCompile("ch$"), regexp.MustCompile("ss$"), regexp.MustCompile("sh$"), regexp.MustCompile("day$"), regexp.MustCompile("y$"), regexp.MustCompile("x$"), regexp.MustCompile("([^s])s?$")}
var pluralMapValues = []string{"ches", "sses", "shes", "days", "ies", "xes", "${1}s"}
2015-02-18 08:16:32 +03:00
func (scope *Scope) GetModelStruct(noRelationship ...bool) *ModelStruct {
2015-02-16 11:35:26 +03:00
var modelStruct ModelStruct
2015-02-15 18:01:09 +03:00
reflectValue := reflect.Indirect(reflect.ValueOf(scope.Value))
2015-02-17 12:40:21 +03:00
if !reflectValue.IsValid() {
return &modelStruct
}
2015-02-15 18:01:09 +03:00
if reflectValue.Kind() == reflect.Slice {
2015-02-17 09:30:37 +03:00
reflectValue = reflect.Indirect(reflect.New(reflectValue.Type().Elem()))
2015-02-15 18:01:09 +03:00
}
2015-02-17 13:37:47 +03:00
2015-02-17 12:40:21 +03:00
scopeType := reflectValue.Type()
2015-02-18 03:47:44 +03:00
if scopeType.Kind() == reflect.Ptr {
scopeType = scopeType.Elem()
}
2015-02-17 18:18:12 +03:00
if scope.db != nil {
if value, ok := scope.db.parent.ModelStructs[scopeType]; ok {
return value
}
}
2015-02-18 07:30:09 +03:00
modelStruct.ModelType = scopeType
2015-02-17 12:40:21 +03:00
if scopeType.Kind() != reflect.Struct {
return &modelStruct
}
2015-02-16 11:35:26 +03:00
// Set tablename
2015-02-17 12:40:21 +03:00
if fm := reflect.New(scopeType).MethodByName("TableName"); fm.IsValid() {
2015-02-16 11:35:26 +03:00
if results := fm.Call([]reflect.Value{}); len(results) > 0 {
if name, ok := results[0].Interface().(string); ok {
modelStruct.TableName = name
}
}
} else {
2015-02-18 05:19:34 +03:00
modelStruct.TableName = ToDBName(scopeType.Name())
2015-02-16 11:35:26 +03:00
if scope.db == nil || !scope.db.parent.singularTable {
for index, reg := range pluralMapKeys {
if reg.MatchString(modelStruct.TableName) {
modelStruct.TableName = reg.ReplaceAllString(modelStruct.TableName, pluralMapValues[index])
}
}
}
}
2015-02-18 06:37:08 +03:00
// Get all fields
fields := []*StructField{}
2015-02-17 12:40:21 +03:00
for i := 0; i < scopeType.NumField(); i++ {
2015-02-17 17:55:14 +03:00
if fieldStruct := scopeType.Field(i); ast.IsExported(fieldStruct.Name) {
field := &StructField{
Struct: fieldStruct,
Name: fieldStruct.Name,
Names: []string{fieldStruct.Name},
Tag: fieldStruct.Tag,
2015-02-15 18:01:09 +03:00
}
2015-02-17 17:55:14 +03:00
if fieldStruct.Tag.Get("sql") == "-" {
field.IsIgnored = true
2015-02-15 18:01:09 +03:00
} else {
2015-02-17 17:55:14 +03:00
sqlSettings := parseTagSetting(field.Tag.Get("sql"))
gormSettings := parseTagSetting(field.Tag.Get("gorm"))
if _, ok := gormSettings["PRIMARY_KEY"]; ok {
field.IsPrimaryKey = true
modelStruct.PrimaryKeyField = field
}
2015-02-15 18:01:09 +03:00
2015-02-18 05:19:34 +03:00
if _, ok := sqlSettings["DEFAULT"]; ok {
field.HasDefaultValue = true
2015-02-17 17:55:14 +03:00
}
2015-02-15 18:01:09 +03:00
2015-02-17 17:55:14 +03:00
if value, ok := gormSettings["COLUMN"]; ok {
field.DBName = value
} else {
2015-02-18 05:19:34 +03:00
field.DBName = ToDBName(fieldStruct.Name)
2015-02-17 17:55:14 +03:00
}
2015-02-18 06:37:08 +03:00
}
fields = append(fields, field)
}
}
2015-02-15 18:01:09 +03:00
2015-02-18 06:37:08 +03:00
for _, field := range fields {
if !field.IsIgnored {
fieldStruct := field.Struct
fieldType, indirectType := fieldStruct.Type, fieldStruct.Type
if indirectType.Kind() == reflect.Ptr {
indirectType = indirectType.Elem()
}
2015-02-15 18:01:09 +03:00
2015-02-18 06:37:08 +03:00
if _, isScanner := reflect.New(fieldType).Interface().(sql.Scanner); isScanner {
field.IsScanner, field.IsNormal = true, true
}
2015-02-15 18:01:09 +03:00
2015-02-18 06:37:08 +03:00
if _, isTime := reflect.New(indirectType).Interface().(*time.Time); isTime {
field.IsNormal = true
}
2015-02-15 18:01:09 +03:00
2015-02-18 08:16:32 +03:00
if !field.IsNormal && len(noRelationship) == 0 {
2015-02-18 06:37:08 +03:00
gormSettings := parseTagSetting(field.Tag.Get("gorm"))
2015-02-18 08:16:32 +03:00
toModelStruct := scope.New(reflect.New(fieldStruct.Type).Interface()).GetModelStruct(true)
2015-02-18 07:30:09 +03:00
getForeignField := func(column string, fields []*StructField) *StructField {
for _, field := range fields {
if field.Name == column || field.DBName == ToDBName(column) {
return field
}
}
return nil
}
var relationship = &Relationship{}
2015-02-18 04:26:35 +03:00
foreignKey := gormSettings["FOREIGNKEY"]
if polymorphic := gormSettings["POLYMORPHIC"]; polymorphic != "" {
2015-02-18 07:30:09 +03:00
if polymorphicField := getForeignField(polymorphic+"Id", toModelStruct.StructFields); polymorphicField != nil {
if polymorphicType := getForeignField(polymorphic+"Type", toModelStruct.StructFields); polymorphicType != nil {
relationship.ForeignFieldName = polymorphicField.Name
relationship.ForeignDBName = polymorphicField.DBName
relationship.PolymorphicType = polymorphicType.Name
relationship.PolymorphicDBName = polymorphicType.DBName
polymorphicType.IsForeignKey = true
polymorphicField.IsForeignKey = true
}
}
2015-02-17 17:55:14 +03:00
}
2015-02-15 18:01:09 +03:00
2015-02-18 06:37:08 +03:00
switch indirectType.Kind() {
case reflect.Slice:
2015-02-18 07:30:09 +03:00
if len(toModelStruct.StructFields) > 0 {
2015-02-18 06:37:08 +03:00
if foreignKey == "" {
foreignKey = scopeType.Name() + "Id"
}
2015-02-18 07:30:09 +03:00
if many2many := gormSettings["MANY2MANY"]; many2many != "" {
relationship.Kind = "many_to_many"
relationship.JoinTable = many2many
2015-02-18 06:37:08 +03:00
2015-02-18 07:30:09 +03:00
associationForeignKey := gormSettings["ASSOCIATIONFOREIGNKEY"]
if associationForeignKey == "" {
associationForeignKey = toModelStruct.ModelType.Name() + "Id"
}
2015-02-15 18:01:09 +03:00
2015-02-18 07:30:09 +03:00
relationship.ForeignFieldName = foreignKey
relationship.ForeignDBName = ToDBName(foreignKey)
relationship.AssociationForeignFieldName = associationForeignKey
relationship.AssociationForeignDBName = ToDBName(associationForeignKey)
field.Relationship = relationship
} else {
relationship.Kind = "has_many"
if foreignField := getForeignField(foreignKey, toModelStruct.StructFields); foreignField != nil {
relationship.ForeignFieldName = foreignField.Name
relationship.ForeignDBName = foreignField.DBName
foreignField.IsForeignKey = true
field.Relationship = relationship
} else if relationship.ForeignFieldName != "" {
field.Relationship = relationship
}
2015-02-18 06:37:08 +03:00
}
} else {
field.IsNormal = true
}
case reflect.Struct:
if _, ok := gormSettings["EMBEDDED"]; ok || fieldStruct.Anonymous {
for _, f := range scope.New(reflect.New(indirectType).Interface()).GetStructFields() {
f = f.clone()
f.Names = append([]string{fieldStruct.Name}, f.Names...)
modelStruct.StructFields = append(modelStruct.StructFields, f)
2015-02-25 05:56:05 +03:00
if f.IsPrimaryKey {
modelStruct.PrimaryKeyField = f
}
2015-02-18 06:37:08 +03:00
}
break
} else {
2015-02-18 07:30:09 +03:00
belongsToForeignKey := foreignKey
if belongsToForeignKey == "" {
2015-02-18 06:37:08 +03:00
belongsToForeignKey = field.Name + "Id"
2015-02-15 18:01:09 +03:00
}
2015-02-18 06:37:08 +03:00
2015-02-18 07:30:09 +03:00
if foreignField := getForeignField(belongsToForeignKey, fields); foreignField != nil {
relationship.Kind = "belongs_to"
relationship.ForeignFieldName = foreignField.Name
relationship.ForeignDBName = foreignField.DBName
foreignField.IsForeignKey = true
field.Relationship = relationship
2015-02-15 18:01:09 +03:00
} else {
2015-02-18 07:30:09 +03:00
if foreignKey == "" {
foreignKey = modelStruct.ModelType.Name() + "Id"
}
relationship.Kind = "has_one"
if foreignField := getForeignField(foreignKey, toModelStruct.StructFields); foreignField != nil {
relationship.ForeignFieldName = foreignField.Name
relationship.ForeignDBName = foreignField.DBName
foreignField.IsForeignKey = true
field.Relationship = relationship
} else if relationship.ForeignFieldName != "" {
field.Relationship = relationship
}
2015-02-18 06:37:08 +03:00
}
2015-02-15 18:01:09 +03:00
}
2015-02-18 06:37:08 +03:00
default:
field.IsNormal = true
2015-02-15 18:01:09 +03:00
}
}
2015-02-18 06:37:08 +03:00
if field.IsNormal {
if modelStruct.PrimaryKeyField == nil && field.DBName == "id" {
field.IsPrimaryKey = true
modelStruct.PrimaryKeyField = field
}
2015-02-15 18:01:09 +03:00
2015-02-18 06:37:08 +03:00
if scope.db != nil {
scope.generateSqlTag(field)
}
2015-02-17 12:40:21 +03:00
}
2015-02-16 12:10:13 +03:00
}
2015-02-18 06:37:08 +03:00
modelStruct.StructFields = append(modelStruct.StructFields, field)
2015-02-16 11:35:26 +03:00
}
2015-02-15 18:01:09 +03:00
2015-02-18 08:16:32 +03:00
if scope.db != nil && len(noRelationship) == 0 {
2015-02-18 03:47:44 +03:00
scope.db.parent.ModelStructs[scopeType] = &modelStruct
}
2015-02-16 11:35:26 +03:00
return &modelStruct
}
2015-02-15 18:01:09 +03:00
2015-02-16 11:35:26 +03:00
func (scope *Scope) GetStructFields() (fields []*StructField) {
return scope.GetModelStruct().StructFields
2015-02-15 18:01:09 +03:00
}
2015-02-24 17:06:35 +03:00
func (scope *Scope) generateSqlTag(field *StructField) {
var sqlType string
structType := field.Struct.Type
if structType.Kind() == reflect.Ptr {
structType = structType.Elem()
}
reflectValue := reflect.Indirect(reflect.New(structType))
sqlSettings := parseTagSetting(field.Tag.Get("sql"))
if value, ok := sqlSettings["TYPE"]; ok {
sqlType = value
}
additionalType := sqlSettings["NOT NULL"] + " " + sqlSettings["UNIQUE"]
if value, ok := sqlSettings["DEFAULT"]; ok {
additionalType = additionalType + "DEFAULT " + value
}
if field.IsScanner {
var getScannerValue func(reflect.Value)
getScannerValue = func(value reflect.Value) {
reflectValue = value
if _, isScanner := reflect.New(reflectValue.Type()).Interface().(sql.Scanner); isScanner && reflectValue.Kind() == reflect.Struct {
getScannerValue(reflectValue.Field(0))
}
}
getScannerValue(reflectValue)
}
if sqlType == "" {
var size = 255
if value, ok := sqlSettings["SIZE"]; ok {
size, _ = strconv.Atoi(value)
}
if field.IsPrimaryKey {
sqlType = scope.Dialect().PrimaryKeyTag(reflectValue, size)
} else {
sqlType = scope.Dialect().SqlTag(reflectValue, size)
}
}
if strings.TrimSpace(additionalType) == "" {
field.SqlTag = sqlType
} else {
field.SqlTag = fmt.Sprintf("%v %v", sqlType, additionalType)
}
}
func parseTagSetting(str string) map[string]string {
tags := strings.Split(str, ";")
setting := map[string]string{}
for _, value := range tags {
v := strings.Split(value, ":")
k := strings.TrimSpace(strings.ToUpper(v[0]))
if len(v) == 2 {
setting[k] = v[1]
} else {
setting[k] = k
}
}
return setting
}