gorm/association.go

387 lines
13 KiB
Go
Raw Normal View History

2014-07-30 10:30:21 +04:00
package gorm
2014-07-30 12:22:26 +04:00
import (
"errors"
"fmt"
"reflect"
2015-07-30 12:26:10 +03:00
"strings"
2014-07-30 12:22:26 +04:00
)
2014-07-30 10:30:21 +04:00
type Association struct {
2015-07-30 12:26:10 +03:00
Scope *Scope
Column string
Error error
Field *Field
2014-07-30 10:30:21 +04:00
}
2015-02-13 06:26:02 +03:00
func (association *Association) setErr(err error) *Association {
2014-07-30 16:48:36 +04:00
if err != nil {
association.Error = err
2014-07-30 12:22:26 +04:00
}
2014-07-30 16:48:36 +04:00
return association
}
func (association *Association) Find(value interface{}) *Association {
association.Scope.related(value, association.Column)
2015-02-13 06:26:02 +03:00
return association.setErr(association.Scope.db.Error)
2014-07-30 16:48:36 +04:00
}
2014-07-30 12:22:26 +04:00
2015-12-26 10:19:56 +03:00
func (association *Association) saveAssociations(values ...interface{}) *Association {
2014-07-30 16:48:36 +04:00
scope := association.Scope
2014-09-02 15:03:01 +04:00
field := association.Field
relationship := association.Field.Relationship
2014-09-02 15:03:01 +04:00
saveAssociation := func(reflectValue reflect.Value) {
// value has to been pointer
if reflectValue.Kind() != reflect.Ptr {
reflectPtr := reflect.New(reflectValue.Type())
reflectPtr.Elem().Set(reflectValue)
reflectValue = reflectPtr
}
// value has to been saved
if scope.New(reflectValue.Interface()).PrimaryKeyZero() {
scope.NewDB().Save(reflectValue.Interface())
}
// Assign Fields
fieldType := field.Field.Type()
if reflectValue.Type().AssignableTo(fieldType) {
field.Set(reflectValue)
} else if reflectValue.Type().Elem().AssignableTo(fieldType) {
field.Set(reflectValue.Elem())
} else if fieldType.Kind() == reflect.Slice {
if reflectValue.Type().AssignableTo(fieldType.Elem()) {
field.Set(reflect.Append(field.Field, reflectValue))
} else if reflectValue.Type().Elem().AssignableTo(fieldType.Elem()) {
field.Set(reflect.Append(field.Field, reflectValue.Elem()))
}
}
if relationship.Kind == "many_to_many" {
association.setErr(relationship.JoinTableHandler.Add(relationship.JoinTableHandler, scope.NewDB(), scope.Value, reflectValue.Interface()))
} else {
association.setErr(scope.NewDB().Select(field.Name).Save(scope.Value).Error)
}
}
2014-07-30 16:48:36 +04:00
for _, value := range values {
reflectValue := reflect.ValueOf(value)
indirectReflectValue := reflect.Indirect(reflectValue)
if indirectReflectValue.Kind() == reflect.Struct {
saveAssociation(reflectValue)
} else if indirectReflectValue.Kind() == reflect.Slice {
for i := 0; i < indirectReflectValue.Len(); i++ {
saveAssociation(indirectReflectValue.Index(i))
}
2014-07-30 12:22:26 +04:00
} else {
association.setErr(errors.New("invalid value type"))
2014-07-30 12:22:26 +04:00
}
}
return association
2014-07-30 10:30:21 +04:00
}
2015-12-26 10:19:56 +03:00
func (association *Association) Append(values ...interface{}) *Association {
if relationship := association.Field.Relationship; relationship.Kind == "has_one" {
return association.Replace(values...)
}
return association.saveAssociations(values...)
}
func (association *Association) Replace(values ...interface{}) *Association {
2015-12-25 17:59:01 +03:00
var (
relationship = association.Field.Relationship
scope = association.Scope
field = association.Field.Field
newDB = scope.NewDB()
)
// Append new values
association.Field.Set(reflect.Zero(association.Field.Field.Type()))
2015-12-26 10:19:56 +03:00
association.saveAssociations(values...)
2015-12-25 15:43:51 +03:00
2015-12-25 17:59:01 +03:00
// Belongs To
2015-12-25 15:43:51 +03:00
if relationship.Kind == "belongs_to" {
2015-12-25 17:59:01 +03:00
// Set foreign key to be null only when clearing value
if len(values) == 0 {
// Set foreign key to be nil
var foreignKeyMap = map[string]interface{}{}
for _, foreignKey := range relationship.ForeignDBNames {
foreignKeyMap[foreignKey] = nil
2015-12-25 15:43:51 +03:00
}
2015-12-25 17:59:01 +03:00
association.setErr(newDB.Model(scope.Value).UpdateColumn(foreignKeyMap).Error)
}
2015-12-25 15:43:51 +03:00
} else {
2015-12-25 17:59:01 +03:00
// Relations
var foreignKeyMap = map[string]interface{}{}
2015-12-25 15:43:51 +03:00
for idx, foreignKey := range relationship.ForeignDBNames {
foreignKeyMap[foreignKey] = nil
if field, ok := scope.FieldByName(relationship.AssociationForeignFieldNames[idx]); ok {
2015-12-25 17:59:01 +03:00
newDB = newDB.Where(fmt.Sprintf("%v = ?", scope.Quote(foreignKey)), field.Field.Interface())
2015-12-25 15:43:51 +03:00
}
}
2015-12-26 10:19:56 +03:00
if relationship.PolymorphicDBName != "" {
newDB = newDB.Where(fmt.Sprintf("%v = ?", scope.Quote(relationship.PolymorphicDBName)), scope.TableName())
}
2015-12-25 17:59:01 +03:00
// Relations except new created
if len(values) > 0 {
var newPrimaryKeys [][]interface{}
var associationForeignFieldNames []string
if relationship.Kind == "many2many" {
// If many to many relations, get it from foreign key
associationForeignFieldNames = relationship.AssociationForeignFieldNames
} else {
// If other relations, get real primary keys
for _, field := range scope.New(reflect.New(field.Type()).Interface()).Fields() {
if field.IsPrimaryKey {
associationForeignFieldNames = append(associationForeignFieldNames, field.Name)
}
}
}
newPrimaryKeys = association.getPrimaryKeys(associationForeignFieldNames, field.Interface())
sql := fmt.Sprintf("%v NOT IN (%v)", toQueryCondition(scope, relationship.AssociationForeignDBNames), toQueryMarks(newPrimaryKeys))
newDB = newDB.Where(sql, toQueryValues(newPrimaryKeys)...)
2015-12-25 15:43:51 +03:00
}
if relationship.Kind == "many_to_many" {
2015-12-25 17:59:01 +03:00
association.setErr(relationship.JoinTableHandler.Delete(relationship.JoinTableHandler, newDB, relationship))
2015-12-25 15:43:51 +03:00
} else if relationship.Kind == "has_one" || relationship.Kind == "has_many" {
fieldValue := reflect.New(association.Field.Field.Type()).Interface()
2015-12-25 19:23:17 +03:00
association.setErr(newDB.Model(fieldValue).UpdateColumn(foreignKeyMap).Error)
2015-12-25 15:43:51 +03:00
}
}
return association
}
2015-07-30 12:26:10 +03:00
func (association *Association) Delete(values ...interface{}) *Association {
2015-12-25 19:23:17 +03:00
var (
relationship = association.Field.Relationship
scope = association.Scope
field = association.Field.Field
newDB = scope.NewDB()
)
2014-07-30 18:10:12 +04:00
if len(values) == 0 {
return association
}
2015-12-26 11:06:53 +03:00
var deletingResourcePrimaryFieldNames, deletingResourcePrimaryDBNames []string
for _, field := range scope.New(reflect.New(field.Type()).Interface()).Fields() {
if field.IsPrimaryKey {
deletingResourcePrimaryFieldNames = append(deletingResourcePrimaryFieldNames, field.Name)
deletingResourcePrimaryDBNames = append(deletingResourcePrimaryDBNames, field.DBName)
}
}
deletingPrimaryKeys := association.getPrimaryKeys(deletingResourcePrimaryFieldNames, values...)
2015-07-30 12:26:10 +03:00
if relationship.Kind == "many_to_many" {
2015-12-26 11:06:53 +03:00
// source value's foreign keys
2015-07-30 12:26:10 +03:00
for idx, foreignKey := range relationship.ForeignDBNames {
if field, ok := scope.FieldByName(relationship.ForeignFieldNames[idx]); ok {
2015-12-25 19:23:17 +03:00
newDB = newDB.Where(fmt.Sprintf("%v = ?", scope.Quote(foreignKey)), field.Field.Interface())
2014-07-30 16:48:36 +04:00
}
}
2014-07-30 18:10:12 +04:00
2015-12-26 11:06:53 +03:00
// association value's foreign keys
deletingPrimaryKeys := association.getPrimaryKeys(relationship.AssociationForeignFieldNames, values...)
sql := fmt.Sprintf("%v IN (%v)", toQueryCondition(scope, relationship.AssociationForeignDBNames), toQueryMarks(deletingPrimaryKeys))
newDB = newDB.Where(sql, toQueryValues(deletingPrimaryKeys)...)
2014-07-30 16:48:36 +04:00
2015-12-26 11:06:53 +03:00
association.setErr(relationship.JoinTableHandler.Delete(relationship.JoinTableHandler, newDB, relationship))
2015-07-30 12:26:10 +03:00
} else {
2015-12-25 19:23:17 +03:00
var foreignKeyMap = map[string]interface{}{}
for _, foreignKey := range relationship.ForeignDBNames {
foreignKeyMap[foreignKey] = nil
}
if relationship.Kind == "belongs_to" {
2015-12-25 19:23:17 +03:00
// find with deleting relation's foreign keys
primaryKeys := association.getPrimaryKeys(relationship.AssociationForeignFieldNames, values...)
2015-12-25 19:23:17 +03:00
newDB = newDB.Where(
fmt.Sprintf("%v IN (%v)", toQueryCondition(scope, relationship.ForeignDBNames), toQueryMarks(primaryKeys)),
toQueryValues(primaryKeys)...,
)
2015-12-25 19:23:17 +03:00
// set foreign key to be null
modelValue := reflect.New(scope.GetModelStruct().ModelType).Interface()
if results := newDB.Model(modelValue).UpdateColumn(foreignKeyMap); results.Error == nil {
if results.RowsAffected > 0 {
scope.updatedAttrsWithValues(foreignKeyMap, false)
}
} else {
association.setErr(results.Error)
}
} else if relationship.Kind == "has_one" || relationship.Kind == "has_many" {
2015-12-25 19:23:17 +03:00
// find all relations
primaryKeys := association.getPrimaryKeys(relationship.AssociationForeignFieldNames, scope.Value)
2015-12-25 19:23:17 +03:00
newDB = newDB.Where(
fmt.Sprintf("%v IN (%v)", toQueryCondition(scope, relationship.ForeignDBNames), toQueryMarks(primaryKeys)),
toQueryValues(primaryKeys)...,
)
2015-12-25 19:23:17 +03:00
// only include those deleting relations
newDB = newDB.Where(
2015-12-26 11:06:53 +03:00
fmt.Sprintf("%v IN (%v)", toQueryCondition(scope, deletingResourcePrimaryDBNames), toQueryMarks(deletingPrimaryKeys)),
toQueryValues(deletingPrimaryKeys)...,
2015-12-25 19:23:17 +03:00
)
2015-12-25 19:23:17 +03:00
// set matched relation's foreign key to be null
2015-12-26 09:23:18 +03:00
fieldValue := reflect.New(association.Field.Field.Type()).Interface()
2015-12-26 11:06:53 +03:00
association.setErr(newDB.Model(fieldValue).UpdateColumn(foreignKeyMap).Error)
}
}
// Remove deleted records from field
if association.Error == nil {
if association.Field.Field.Kind() == reflect.Slice {
leftValues := reflect.Zero(association.Field.Field.Type())
for i := 0; i < association.Field.Field.Len(); i++ {
reflectValue := association.Field.Field.Index(i)
primaryKey := association.getPrimaryKeys(deletingResourcePrimaryFieldNames, reflectValue.Interface())[0]
var included = false
for _, pk := range deletingPrimaryKeys {
if equalAsString(primaryKey, pk) {
included = true
}
}
if !included {
leftValues = reflect.Append(leftValues, reflectValue)
}
}
association.Field.Set(leftValues)
} else if association.Field.Field.Kind() == reflect.Struct {
2015-12-26 11:39:08 +03:00
primaryKey := association.getPrimaryKeys(deletingResourcePrimaryFieldNames, association.Field.Field.Interface())[0]
2015-12-26 11:06:53 +03:00
for _, pk := range deletingPrimaryKeys {
if equalAsString(primaryKey, pk) {
association.Field.Set(reflect.Zero(association.Field.Field.Type()))
break
}
}
}
2014-07-30 16:48:36 +04:00
}
2015-12-25 19:23:17 +03:00
2014-07-30 12:22:26 +04:00
return association
2014-07-30 10:30:21 +04:00
}
func (association *Association) Clear() *Association {
2015-12-25 14:33:57 +03:00
return association.Replace()
2014-07-30 10:30:21 +04:00
}
2014-07-30 17:43:53 +04:00
func (association *Association) Count() int {
count := -1
2014-07-30 16:59:52 +04:00
relationship := association.Field.Relationship
2014-07-30 16:48:36 +04:00
scope := association.Scope
2015-02-17 15:19:47 +03:00
newScope := scope.New(association.Field.Field.Interface())
2014-07-30 10:30:21 +04:00
2014-07-31 07:08:26 +04:00
if relationship.Kind == "many_to_many" {
2015-06-19 06:32:11 +03:00
relationship.JoinTableHandler.JoinWith(relationship.JoinTableHandler, scope.NewDB(), association.Scope.Value).Table(newScope.TableName()).Count(&count)
} else if relationship.Kind == "has_many" || relationship.Kind == "has_one" {
2015-07-30 12:26:10 +03:00
query := scope.DB()
for idx, foreignKey := range relationship.ForeignDBNames {
if field, ok := scope.FieldByName(relationship.AssociationForeignDBNames[idx]); ok {
query = query.Where(fmt.Sprintf("%v.%v = ?", newScope.QuotedTableName(), scope.Quote(foreignKey)),
field.Field.Interface())
}
}
2015-02-18 07:30:09 +03:00
if relationship.PolymorphicType != "" {
2015-07-30 12:26:10 +03:00
query = query.Where(fmt.Sprintf("%v.%v = ?", newScope.QuotedTableName(), newScope.Quote(relationship.PolymorphicDBName)), scope.TableName())
}
query.Table(newScope.TableName()).Count(&count)
2014-07-31 07:08:26 +04:00
} else if relationship.Kind == "belongs_to" {
2015-07-30 12:26:10 +03:00
query := scope.DB()
for idx, foreignKey := range relationship.ForeignDBNames {
if field, ok := scope.FieldByName(relationship.AssociationForeignDBNames[idx]); ok {
query = query.Where(fmt.Sprintf("%v.%v = ?", newScope.QuotedTableName(), scope.Quote(foreignKey)),
field.Field.Interface())
}
2014-07-30 17:43:53 +04:00
}
2015-07-30 12:26:10 +03:00
query.Table(newScope.TableName()).Count(&count)
2014-07-30 16:48:36 +04:00
}
2014-07-30 17:43:53 +04:00
return count
2014-07-30 10:30:21 +04:00
}
2015-07-30 12:26:10 +03:00
2015-12-25 15:43:51 +03:00
func (association *Association) getPrimaryKeys(columns []string, values ...interface{}) (results [][]interface{}) {
2015-07-30 12:26:10 +03:00
scope := association.Scope
for _, value := range values {
reflectValue := reflect.Indirect(reflect.ValueOf(value))
if reflectValue.Kind() == reflect.Slice {
for i := 0; i < reflectValue.Len(); i++ {
2015-07-30 17:18:56 +03:00
primaryKeys := []interface{}{}
2015-07-30 12:26:10 +03:00
newScope := scope.New(reflectValue.Index(i).Interface())
for _, column := range columns {
if field, ok := newScope.FieldByName(column); ok {
primaryKeys = append(primaryKeys, field.Field.Interface())
} else {
primaryKeys = append(primaryKeys, "")
}
}
2015-07-30 17:18:56 +03:00
results = append(results, primaryKeys)
2015-07-30 12:26:10 +03:00
}
} else if reflectValue.Kind() == reflect.Struct {
newScope := scope.New(value)
2015-07-30 17:18:56 +03:00
var primaryKeys []interface{}
2015-07-30 12:26:10 +03:00
for _, column := range columns {
if field, ok := newScope.FieldByName(column); ok {
primaryKeys = append(primaryKeys, field.Field.Interface())
} else {
primaryKeys = append(primaryKeys, "")
}
}
2015-07-30 17:18:56 +03:00
results = append(results, primaryKeys)
}
2015-07-30 12:26:10 +03:00
}
2015-12-25 15:43:51 +03:00
return
2015-07-30 12:26:10 +03:00
}
func toQueryMarks(primaryValues [][]interface{}) string {
var results []string
for _, primaryValue := range primaryValues {
var marks []string
for _, _ = range primaryValue {
2015-07-30 12:26:10 +03:00
marks = append(marks, "?")
}
if len(marks) > 1 {
results = append(results, fmt.Sprintf("(%v)", strings.Join(marks, ",")))
} else {
results = append(results, strings.Join(marks, ""))
}
}
return strings.Join(results, ",")
}
func toQueryCondition(scope *Scope, columns []string) string {
var newColumns []string
for _, column := range columns {
newColumns = append(newColumns, scope.Quote(column))
}
if len(columns) > 1 {
return fmt.Sprintf("(%v)", strings.Join(newColumns, ","))
} else {
return strings.Join(columns, ",")
}
}
func toQueryValues(primaryValues [][]interface{}) (values []interface{}) {
for _, primaryValue := range primaryValues {
for _, value := range primaryValue {
values = append(values, value)
}
}
return values
}