2020-01-31 07:22:37 +03:00
|
|
|
package schema
|
2020-01-29 14:22:44 +03:00
|
|
|
|
2020-02-01 07:46:52 +03:00
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"reflect"
|
2020-02-22 06:15:51 +03:00
|
|
|
"regexp"
|
2020-02-01 07:46:52 +03:00
|
|
|
"strings"
|
2020-02-01 19:03:56 +03:00
|
|
|
|
2020-05-19 16:50:06 +03:00
|
|
|
"github.com/jinzhu/gorm/clause"
|
2020-02-01 19:03:56 +03:00
|
|
|
"github.com/jinzhu/inflection"
|
2020-02-01 07:46:52 +03:00
|
|
|
)
|
|
|
|
|
2020-01-29 14:22:44 +03:00
|
|
|
// RelationshipType relationship type
|
|
|
|
type RelationshipType string
|
|
|
|
|
|
|
|
const (
|
2020-02-01 07:46:52 +03:00
|
|
|
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
|
2020-01-29 14:22:44 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
type Relationships struct {
|
2020-02-01 07:46:52 +03:00
|
|
|
HasOne []*Relationship
|
|
|
|
BelongsTo []*Relationship
|
|
|
|
HasMany []*Relationship
|
|
|
|
Many2Many []*Relationship
|
|
|
|
Relations map[string]*Relationship
|
2020-01-29 14:22:44 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
type Relationship struct {
|
2020-02-01 10:23:45 +03:00
|
|
|
Name string
|
|
|
|
Type RelationshipType
|
|
|
|
Field *Field
|
|
|
|
Polymorphic *Polymorphic
|
|
|
|
References []Reference
|
|
|
|
Schema *Schema
|
|
|
|
FieldSchema *Schema
|
|
|
|
JoinTable *Schema
|
2020-02-01 16:48:06 +03:00
|
|
|
foreignKeys, primaryKeys []string
|
2020-02-01 07:46:52 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
type Polymorphic struct {
|
|
|
|
PolymorphicID *Field
|
|
|
|
PolymorphicType *Field
|
|
|
|
Value string
|
2020-01-29 14:22:44 +03:00
|
|
|
}
|
|
|
|
|
2020-02-01 07:46:52 +03:00
|
|
|
type Reference struct {
|
2020-02-01 19:03:56 +03:00
|
|
|
PrimaryKey *Field
|
|
|
|
PrimaryValue string
|
2020-02-01 07:46:52 +03:00
|
|
|
ForeignKey *Field
|
2020-02-01 19:03:56 +03:00
|
|
|
OwnPrimaryKey bool
|
2020-01-29 14:22:44 +03:00
|
|
|
}
|
|
|
|
|
2020-02-01 07:46:52 +03:00
|
|
|
func (schema *Schema) parseRelation(field *Field) {
|
|
|
|
var (
|
2020-02-01 16:48:06 +03:00
|
|
|
err error
|
2020-02-15 14:45:27 +03:00
|
|
|
fieldValue = reflect.New(field.IndirectFieldType).Interface()
|
2020-02-01 07:46:52 +03:00
|
|
|
relation = &Relationship{
|
2020-02-01 10:23:45 +03:00
|
|
|
Name: field.Name,
|
|
|
|
Field: field,
|
|
|
|
Schema: schema,
|
2020-02-01 16:48:06 +03:00
|
|
|
foreignKeys: toColumns(field.TagSettings["FOREIGNKEY"]),
|
|
|
|
primaryKeys: toColumns(field.TagSettings["REFERENCES"]),
|
2020-02-01 07:46:52 +03:00
|
|
|
}
|
|
|
|
)
|
|
|
|
|
2020-02-24 03:51:35 +03:00
|
|
|
if relation.FieldSchema, err = Parse(fieldValue, schema.cacheStore, schema.namer); err != nil {
|
2020-02-01 16:48:06 +03:00
|
|
|
schema.err = err
|
2020-02-01 07:46:52 +03:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if polymorphic, _ := field.TagSettings["POLYMORPHIC"]; polymorphic != "" {
|
2020-02-01 13:02:19 +03:00
|
|
|
schema.buildPolymorphicRelation(relation, field, polymorphic)
|
|
|
|
} else if many2many, _ := field.TagSettings["MANY2MANY"]; many2many != "" {
|
|
|
|
schema.buildMany2ManyRelation(relation, field, many2many)
|
2020-02-01 10:23:45 +03:00
|
|
|
} else {
|
2020-02-15 14:45:27 +03:00
|
|
|
switch field.IndirectFieldType.Kind() {
|
2020-02-01 13:02:19 +03:00
|
|
|
case reflect.Struct, reflect.Slice:
|
2020-02-01 10:23:45 +03:00
|
|
|
schema.guessRelation(relation, field, true)
|
|
|
|
default:
|
|
|
|
schema.err = fmt.Errorf("unsupported data type %v for %v on field %v", relation.FieldSchema, schema, field.Name)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if relation.Type == "has" {
|
2020-02-15 14:45:27 +03:00
|
|
|
switch field.IndirectFieldType.Kind() {
|
2020-02-01 07:46:52 +03:00
|
|
|
case reflect.Struct:
|
|
|
|
relation.Type = HasOne
|
|
|
|
case reflect.Slice:
|
|
|
|
relation.Type = HasMany
|
|
|
|
}
|
2020-02-01 10:23:45 +03:00
|
|
|
}
|
2020-02-01 16:48:06 +03:00
|
|
|
|
|
|
|
if schema.err == nil {
|
|
|
|
schema.Relationships.Relations[relation.Name] = relation
|
|
|
|
switch relation.Type {
|
|
|
|
case HasOne:
|
|
|
|
schema.Relationships.HasOne = append(schema.Relationships.HasOne, relation)
|
|
|
|
case HasMany:
|
|
|
|
schema.Relationships.HasMany = append(schema.Relationships.HasMany, relation)
|
|
|
|
case BelongsTo:
|
|
|
|
schema.Relationships.BelongsTo = append(schema.Relationships.BelongsTo, relation)
|
|
|
|
case Many2Many:
|
|
|
|
schema.Relationships.Many2Many = append(schema.Relationships.Many2Many, relation)
|
|
|
|
}
|
|
|
|
}
|
2020-02-01 10:23:45 +03:00
|
|
|
}
|
|
|
|
|
2020-02-01 13:02:19 +03:00
|
|
|
// User has many Toys, its `Polymorphic` is `Owner`, Pet has one Toy, its `Polymorphic` is `Owner`
|
|
|
|
// type User struct {
|
|
|
|
// Toys []Toy `gorm:"polymorphic:Owner;"`
|
|
|
|
// }
|
|
|
|
// type Pet struct {
|
|
|
|
// Toy Toy `gorm:"polymorphic:Owner;"`
|
|
|
|
// }
|
|
|
|
// type Toy struct {
|
|
|
|
// OwnerID int
|
|
|
|
// OwnerType string
|
|
|
|
// }
|
|
|
|
func (schema *Schema) buildPolymorphicRelation(relation *Relationship, field *Field, polymorphic string) {
|
|
|
|
relation.Polymorphic = &Polymorphic{
|
|
|
|
Value: schema.Table,
|
|
|
|
PolymorphicType: relation.FieldSchema.FieldsByName[polymorphic+"Type"],
|
|
|
|
PolymorphicID: relation.FieldSchema.FieldsByName[polymorphic+"ID"],
|
|
|
|
}
|
|
|
|
|
|
|
|
if value, ok := field.TagSettings["POLYMORPHIC_VALUE"]; ok {
|
|
|
|
relation.Polymorphic.Value = strings.TrimSpace(value)
|
|
|
|
}
|
|
|
|
|
|
|
|
if relation.Polymorphic.PolymorphicType == nil {
|
|
|
|
schema.err = fmt.Errorf("invalid polymorphic type %v for %v on field %v, missing field %v", relation.FieldSchema, schema, field.Name, polymorphic+"Type")
|
|
|
|
}
|
|
|
|
|
|
|
|
if relation.Polymorphic.PolymorphicID == nil {
|
|
|
|
schema.err = fmt.Errorf("invalid polymorphic type %v for %v on field %v, missing field %v", relation.FieldSchema, schema, field.Name, polymorphic+"ID")
|
|
|
|
}
|
|
|
|
|
|
|
|
if schema.err == nil {
|
|
|
|
relation.References = append(relation.References, Reference{
|
2020-02-01 19:03:56 +03:00
|
|
|
PrimaryValue: relation.Polymorphic.Value,
|
2020-02-01 13:02:19 +03:00
|
|
|
ForeignKey: relation.Polymorphic.PolymorphicType,
|
|
|
|
})
|
|
|
|
|
|
|
|
primaryKeyField := schema.PrioritizedPrimaryField
|
2020-02-01 16:48:06 +03:00
|
|
|
if len(relation.foreignKeys) > 0 {
|
|
|
|
if primaryKeyField = schema.LookUpField(relation.foreignKeys[0]); primaryKeyField == nil || len(relation.foreignKeys) > 1 {
|
|
|
|
schema.err = fmt.Errorf("invalid polymorphic foreign keys %+v for %v on field %v", relation.foreignKeys, schema, field.Name)
|
2020-02-01 13:02:19 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
relation.References = append(relation.References, Reference{
|
2020-02-01 19:03:56 +03:00
|
|
|
PrimaryKey: primaryKeyField,
|
|
|
|
ForeignKey: relation.Polymorphic.PolymorphicID,
|
|
|
|
OwnPrimaryKey: true,
|
2020-02-01 13:02:19 +03:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
relation.Type = "has"
|
|
|
|
}
|
|
|
|
|
|
|
|
func (schema *Schema) buildMany2ManyRelation(relation *Relationship, field *Field, many2many string) {
|
|
|
|
relation.Type = Many2Many
|
|
|
|
|
|
|
|
var (
|
2020-02-01 16:48:06 +03:00
|
|
|
err error
|
2020-02-01 13:02:19 +03:00
|
|
|
joinTableFields []reflect.StructField
|
|
|
|
fieldsMap = map[string]*Field{}
|
2020-02-01 19:03:56 +03:00
|
|
|
ownFieldsMap = map[string]bool{} // fix self join many2many
|
2020-02-01 13:02:19 +03:00
|
|
|
)
|
|
|
|
|
2020-02-01 19:03:56 +03:00
|
|
|
for _, s := range []*Schema{schema, relation.FieldSchema} {
|
2020-02-01 13:02:19 +03:00
|
|
|
for _, primaryField := range s.PrimaryFields {
|
|
|
|
fieldName := s.Name + primaryField.Name
|
|
|
|
if _, ok := fieldsMap[fieldName]; ok {
|
|
|
|
if field.Name != s.Name {
|
2020-02-01 19:03:56 +03:00
|
|
|
fieldName = inflection.Singular(field.Name) + primaryField.Name
|
2020-02-01 13:02:19 +03:00
|
|
|
} else {
|
|
|
|
fieldName = s.Name + primaryField.Name + "Reference"
|
|
|
|
}
|
2020-02-01 19:03:56 +03:00
|
|
|
} else {
|
|
|
|
ownFieldsMap[fieldName] = true
|
2020-02-01 13:02:19 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
fieldsMap[fieldName] = primaryField
|
|
|
|
joinTableFields = append(joinTableFields, reflect.StructField{
|
|
|
|
Name: fieldName,
|
|
|
|
PkgPath: primaryField.StructField.PkgPath,
|
|
|
|
Type: primaryField.StructField.Type,
|
|
|
|
Tag: removeSettingFromTag(primaryField.StructField.Tag, "column"),
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-02-24 03:51:35 +03:00
|
|
|
if relation.JoinTable, err = Parse(reflect.New(reflect.StructOf(joinTableFields)).Interface(), schema.cacheStore, schema.namer); err != nil {
|
2020-02-01 16:48:06 +03:00
|
|
|
schema.err = err
|
|
|
|
}
|
2020-02-01 13:02:19 +03:00
|
|
|
relation.JoinTable.Name = many2many
|
|
|
|
relation.JoinTable.Table = schema.namer.JoinTableName(many2many)
|
|
|
|
|
|
|
|
// build references
|
|
|
|
for _, f := range relation.JoinTable.Fields {
|
|
|
|
relation.References = append(relation.References, Reference{
|
2020-02-01 19:03:56 +03:00
|
|
|
PrimaryKey: fieldsMap[f.Name],
|
2020-02-01 13:02:19 +03:00
|
|
|
ForeignKey: f,
|
2020-02-01 19:03:56 +03:00
|
|
|
OwnPrimaryKey: schema == fieldsMap[f.Name].Schema && ownFieldsMap[f.Name],
|
2020-02-01 13:02:19 +03:00
|
|
|
})
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2020-02-01 10:23:45 +03:00
|
|
|
func (schema *Schema) guessRelation(relation *Relationship, field *Field, guessHas bool) {
|
|
|
|
var (
|
|
|
|
primaryFields, foreignFields []*Field
|
|
|
|
primarySchema, foreignSchema = schema, relation.FieldSchema
|
|
|
|
)
|
|
|
|
|
|
|
|
if !guessHas {
|
|
|
|
primarySchema, foreignSchema = relation.FieldSchema, schema
|
|
|
|
}
|
|
|
|
|
|
|
|
reguessOrErr := func(err string, args ...interface{}) {
|
|
|
|
if guessHas {
|
|
|
|
schema.guessRelation(relation, field, false)
|
|
|
|
} else {
|
|
|
|
schema.err = fmt.Errorf(err, args...)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-02-01 16:48:06 +03:00
|
|
|
if len(relation.foreignKeys) > 0 {
|
|
|
|
for _, foreignKey := range relation.foreignKeys {
|
2020-02-01 10:23:45 +03:00
|
|
|
if f := foreignSchema.LookUpField(foreignKey); f != nil {
|
|
|
|
foreignFields = append(foreignFields, f)
|
|
|
|
} else {
|
2020-02-01 16:48:06 +03:00
|
|
|
reguessOrErr("unsupported relations %v for %v on field %v with foreign keys %v", relation.FieldSchema, schema, field.Name, relation.foreignKeys)
|
2020-02-01 10:23:45 +03:00
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
for _, primaryField := range primarySchema.PrimaryFields {
|
2020-02-01 16:48:06 +03:00
|
|
|
lookUpName := schema.Name + primaryField.Name
|
|
|
|
if !guessHas {
|
|
|
|
lookUpName = field.Name + primaryField.Name
|
|
|
|
}
|
|
|
|
|
|
|
|
if f := foreignSchema.LookUpField(lookUpName); f != nil {
|
2020-02-01 10:23:45 +03:00
|
|
|
foreignFields = append(foreignFields, f)
|
|
|
|
primaryFields = append(primaryFields, primaryField)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(foreignFields) == 0 {
|
2020-02-01 16:48:06 +03:00
|
|
|
reguessOrErr("failed to guess %v's relations with %v's field %v 1 g %v", relation.FieldSchema, schema, field.Name, guessHas)
|
2020-02-01 07:46:52 +03:00
|
|
|
return
|
2020-02-01 16:48:06 +03:00
|
|
|
} else if len(relation.primaryKeys) > 0 {
|
|
|
|
for idx, primaryKey := range relation.primaryKeys {
|
2020-02-01 10:23:45 +03:00
|
|
|
if f := primarySchema.LookUpField(primaryKey); f != nil {
|
|
|
|
if len(primaryFields) < idx+1 {
|
|
|
|
primaryFields = append(primaryFields, f)
|
|
|
|
} else if f != primaryFields[idx] {
|
2020-02-01 16:48:06 +03:00
|
|
|
reguessOrErr("unsupported relations %v for %v on field %v with primary keys %v", relation.FieldSchema, schema, field.Name, relation.primaryKeys)
|
2020-02-01 10:23:45 +03:00
|
|
|
return
|
|
|
|
}
|
|
|
|
} else {
|
2020-02-01 16:48:06 +03:00
|
|
|
reguessOrErr("unsupported relations %v for %v on field %v with primary keys %v", relation.FieldSchema, schema, field.Name, relation.primaryKeys)
|
2020-02-01 10:23:45 +03:00
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
} else if len(primaryFields) == 0 {
|
|
|
|
if len(foreignFields) == 1 {
|
|
|
|
primaryFields = append(primaryFields, primarySchema.PrioritizedPrimaryField)
|
|
|
|
} else if len(primarySchema.PrimaryFields) == len(foreignFields) {
|
|
|
|
primaryFields = append(primaryFields, primarySchema.PrimaryFields...)
|
|
|
|
} else {
|
|
|
|
reguessOrErr("unsupported relations %v for %v on field %v", relation.FieldSchema, schema, field.Name)
|
|
|
|
return
|
|
|
|
}
|
2020-02-01 07:46:52 +03:00
|
|
|
}
|
|
|
|
|
2020-02-01 10:23:45 +03:00
|
|
|
// build references
|
|
|
|
for idx, foreignField := range foreignFields {
|
|
|
|
relation.References = append(relation.References, Reference{
|
2020-02-01 19:03:56 +03:00
|
|
|
PrimaryKey: primaryFields[idx],
|
2020-02-01 10:23:45 +03:00
|
|
|
ForeignKey: foreignField,
|
2020-02-01 19:03:56 +03:00
|
|
|
OwnPrimaryKey: schema == primarySchema && guessHas,
|
2020-02-01 10:23:45 +03:00
|
|
|
})
|
2020-02-01 07:46:52 +03:00
|
|
|
}
|
2020-01-31 07:22:37 +03:00
|
|
|
|
2020-02-01 10:23:45 +03:00
|
|
|
if guessHas {
|
|
|
|
relation.Type = "has"
|
|
|
|
} else {
|
2020-02-01 13:02:19 +03:00
|
|
|
relation.Type = BelongsTo
|
2020-02-01 10:23:45 +03:00
|
|
|
}
|
2020-01-31 07:22:37 +03:00
|
|
|
}
|
2020-02-22 06:15:51 +03:00
|
|
|
|
|
|
|
type Constraint struct {
|
|
|
|
Name string
|
|
|
|
Field *Field
|
|
|
|
Schema *Schema
|
|
|
|
ForeignKeys []*Field
|
|
|
|
ReferenceSchema *Schema
|
|
|
|
References []*Field
|
|
|
|
OnDelete string
|
|
|
|
OnUpdate string
|
|
|
|
}
|
|
|
|
|
|
|
|
func (rel *Relationship) ParseConstraint() *Constraint {
|
|
|
|
str := rel.Field.TagSettings["CONSTRAINT"]
|
|
|
|
if str == "-" {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
var (
|
|
|
|
name string
|
|
|
|
idx = strings.Index(str, ",")
|
|
|
|
settings = ParseTagSetting(str, ",")
|
|
|
|
)
|
|
|
|
|
2020-02-22 14:41:01 +03:00
|
|
|
if idx != -1 && regexp.MustCompile("^[A-Za-z-_]+$").MatchString(str[0:idx]) {
|
2020-02-22 06:15:51 +03:00
|
|
|
name = str[0:idx]
|
|
|
|
} else {
|
|
|
|
name = rel.Schema.namer.RelationshipFKName(*rel)
|
|
|
|
}
|
|
|
|
|
|
|
|
constraint := Constraint{
|
|
|
|
Name: name,
|
|
|
|
Field: rel.Field,
|
|
|
|
OnUpdate: settings["ONUPDATE"],
|
|
|
|
OnDelete: settings["ONDELETE"],
|
|
|
|
Schema: rel.Schema,
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, ref := range rel.References {
|
|
|
|
if ref.PrimaryKey != nil && !ref.OwnPrimaryKey {
|
|
|
|
constraint.ForeignKeys = append(constraint.ForeignKeys, ref.ForeignKey)
|
|
|
|
constraint.References = append(constraint.References, ref.PrimaryKey)
|
|
|
|
constraint.ReferenceSchema = ref.PrimaryKey.Schema
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-02-22 15:57:29 +03:00
|
|
|
if rel.JoinTable != nil || constraint.ReferenceSchema == nil {
|
2020-02-22 14:41:01 +03:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-02-22 06:15:51 +03:00
|
|
|
return &constraint
|
|
|
|
}
|
2020-05-19 16:50:06 +03:00
|
|
|
|
|
|
|
func (rel *Relationship) ToQueryConditions(reflectValue reflect.Value) (conds []clause.Expression) {
|
|
|
|
foreignFields := []*Field{}
|
|
|
|
relForeignKeys := []string{}
|
|
|
|
|
|
|
|
if rel.JoinTable != nil {
|
|
|
|
for _, ref := range rel.References {
|
|
|
|
if ref.OwnPrimaryKey {
|
|
|
|
foreignFields = append(foreignFields, ref.PrimaryKey)
|
|
|
|
relForeignKeys = append(relForeignKeys, ref.PrimaryKey.DBName)
|
|
|
|
} else if ref.PrimaryValue != "" {
|
|
|
|
conds = append(conds, clause.Eq{
|
|
|
|
Column: clause.Column{Table: rel.JoinTable.Table, Name: ref.ForeignKey.DBName},
|
|
|
|
Value: ref.PrimaryValue,
|
|
|
|
})
|
|
|
|
} else {
|
|
|
|
conds = append(conds, clause.Eq{
|
|
|
|
Column: clause.Column{Table: rel.JoinTable.Table, Name: ref.ForeignKey.DBName},
|
|
|
|
Value: clause.Column{Table: rel.FieldSchema.Table, Name: ref.PrimaryKey.DBName},
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
for _, ref := range rel.References {
|
|
|
|
if ref.OwnPrimaryKey {
|
|
|
|
relForeignKeys = append(relForeignKeys, ref.ForeignKey.DBName)
|
|
|
|
foreignFields = append(foreignFields, ref.PrimaryKey)
|
|
|
|
} else if ref.PrimaryValue != "" {
|
|
|
|
conds = append(conds, clause.Eq{
|
|
|
|
Column: clause.Column{Table: rel.FieldSchema.Table, Name: ref.ForeignKey.DBName},
|
|
|
|
Value: ref.PrimaryValue,
|
|
|
|
})
|
|
|
|
} else {
|
|
|
|
relForeignKeys = append(relForeignKeys, ref.PrimaryKey.DBName)
|
|
|
|
foreignFields = append(foreignFields, ref.ForeignKey)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
_, foreignValues := GetIdentityFieldValuesMap(reflectValue, foreignFields)
|
|
|
|
column, values := ToQueryValues(relForeignKeys, foreignValues)
|
2020-05-24 12:24:23 +03:00
|
|
|
|
2020-05-19 16:50:06 +03:00
|
|
|
conds = append(conds, clause.IN{Column: column, Values: values})
|
|
|
|
return
|
|
|
|
}
|