Refactor Associations

This commit is contained in:
Jinzhu 2015-02-17 20:19:47 +08:00
parent 00d1187c4c
commit 38cbff9c79
4 changed files with 38 additions and 80 deletions

View File

@ -53,14 +53,12 @@ func (association *Association) getPrimaryKeys(values ...interface{}) []interfac
reflectValue := reflect.Indirect(reflect.ValueOf(value)) reflectValue := reflect.Indirect(reflect.ValueOf(value))
if reflectValue.Kind() == reflect.Slice { if reflectValue.Kind() == reflect.Slice {
for i := 0; i < reflectValue.Len(); i++ { for i := 0; i < reflectValue.Len(); i++ {
primaryField := scope.New(reflectValue.Index(i).Interface()).PrimaryKeyField() if primaryField := scope.New(reflectValue.Index(i).Interface()).PrimaryKeyField(); !primaryField.IsBlank {
if !primaryField.IsBlank {
primaryKeys = append(primaryKeys, primaryField.Field.Interface()) primaryKeys = append(primaryKeys, primaryField.Field.Interface())
} }
} }
} else if reflectValue.Kind() == reflect.Struct { } else if reflectValue.Kind() == reflect.Struct {
primaryField := scope.New(value).PrimaryKeyField() if primaryField := scope.New(value).PrimaryKeyField(); !primaryField.IsBlank {
if !primaryField.IsBlank {
primaryKeys = append(primaryKeys, primaryField.Field.Interface()) primaryKeys = append(primaryKeys, primaryField.Field.Interface())
} }
} }
@ -144,9 +142,7 @@ func (association *Association) Count() int {
count := -1 count := -1
relationship := association.Field.Relationship relationship := association.Field.Relationship
scope := association.Scope scope := association.Scope
field := association.Field.Field newScope := scope.New(association.Field.Field.Interface())
fieldValue := field.Interface()
newScope := scope.New(fieldValue)
if relationship.Kind == "many_to_many" { if relationship.Kind == "many_to_many" {
whereSql := fmt.Sprintf("%v.%v IN (SELECT %v.%v FROM %v WHERE %v.%v = ?)", whereSql := fmt.Sprintf("%v.%v IN (SELECT %v.%v FROM %v WHERE %v.%v = ?)",

View File

@ -25,7 +25,7 @@ func Create(scope *Scope) {
// set create sql // set create sql
var sqls, columns []string var sqls, columns []string
for _, field := range scope.Fields() { for _, field := range scope.Fields() {
if field.IsNormal && (!field.IsPrimaryKey || !scope.PrimaryKeyZero()) { if (field.IsNormal && !field.IsPrimaryKey) || (field.IsPrimaryKey && !field.IsBlank) {
if field.DefaultValue != nil && field.IsBlank { if field.DefaultValue != nil && field.IsBlank {
continue continue
} }
@ -35,8 +35,9 @@ func Create(scope *Scope) {
} }
returningKey := "*" returningKey := "*"
if scope.PrimaryKey() != "" { primaryField := scope.PrimaryKeyField()
returningKey = scope.Quote(scope.PrimaryKey()) if primaryField != nil {
returningKey = scope.Quote(primaryField.DBName)
} }
if len(columns) == 0 { if len(columns) == 0 {
@ -64,19 +65,17 @@ func Create(scope *Scope) {
} }
} }
} else { } else {
if scope.PrimaryKey() == "" { if primaryField == nil {
if results, err := scope.DB().Exec(scope.Sql, scope.SqlVars...); err != nil { if results, err := scope.DB().Exec(scope.Sql, scope.SqlVars...); err != nil {
scope.db.RowsAffected, _ = results.RowsAffected() scope.db.RowsAffected, _ = results.RowsAffected()
} }
} else { } else if scope.Err(scope.DB().QueryRow(scope.Sql, scope.SqlVars...).Scan(&id)) == nil {
if scope.Err(scope.DB().QueryRow(scope.Sql, scope.SqlVars...).Scan(&id)) == nil { scope.db.RowsAffected = 1
scope.db.RowsAffected = 1
}
} }
} }
if scope.PrimaryKey() != "" && !scope.HasError() && scope.PrimaryKeyZero() { if primaryField != nil && primaryField.IsBlank && !scope.HasError() {
scope.SetColumn(scope.PrimaryKey(), id) scope.SetColumn(primaryField, id)
} }
} }
} }

View File

@ -46,9 +46,9 @@ func Query(scope *Scope) {
if scope.Err(err) != nil { if scope.Err(err) != nil {
return return
} }
defer rows.Close()
columns, _ := rows.Columns() columns, _ := rows.Columns()
defer rows.Close()
for rows.Next() { for rows.Next() {
scope.db.RowsAffected++ scope.db.RowsAffected++

View File

@ -17,27 +17,11 @@ func CommitOrRollbackTransaction(scope *Scope) {
func SaveBeforeAssociations(scope *Scope) { func SaveBeforeAssociations(scope *Scope) {
for _, field := range scope.Fields() { for _, field := range scope.Fields() {
if !field.IsBlank && !field.IsIgnored { if !field.IsBlank && !field.IsIgnored {
relationship := field.Relationship if relationship := field.Relationship; relationship != nil && relationship.Kind == "belongs_to" {
if relationship != nil && relationship.Kind == "belongs_to" {
value := field.Field value := field.Field
newDB := scope.NewDB() scope.Err(scope.NewDB().Save(value.Addr().Interface()).Error)
if !value.CanAddr() {
// If can't take address, then clone the value and set it back
value = reflect.New(value.Type()).Elem()
for _, f := range newDB.NewScope(field.Field.Addr().Interface()).Fields() {
value.FieldByName(f.Name).Set(reflect.ValueOf(f.Field.Interface()))
}
scope.SetColumn(field, value.Interface())
}
scope.Err(newDB.Save(value.Addr().Interface()).Error)
if relationship.ForeignFieldName != "" { if relationship.ForeignFieldName != "" {
scope.SetColumn(relationship.ForeignFieldName, newDB.NewScope(value.Addr().Interface()).PrimaryKeyValue()) scope.SetColumn(relationship.ForeignFieldName, scope.New(value.Addr().Interface()).PrimaryKeyValue())
}
if relationship.ForeignType != "" {
scope.Err(fmt.Errorf("gorm does not support polymorphic belongs_to associations"))
return
} }
} }
} }
@ -47,8 +31,7 @@ func SaveBeforeAssociations(scope *Scope) {
func SaveAfterAssociations(scope *Scope) { func SaveAfterAssociations(scope *Scope) {
for _, field := range scope.Fields() { for _, field := range scope.Fields() {
if !field.IsBlank && !field.IsIgnored { if !field.IsBlank && !field.IsIgnored {
relationship := field.Relationship if relationship := field.Relationship; relationship != nil &&
if relationship != nil &&
(relationship.Kind == "has_one" || relationship.Kind == "has_many" || relationship.Kind == "many_to_many") { (relationship.Kind == "has_one" || relationship.Kind == "has_many" || relationship.Kind == "many_to_many") {
value := field.Field value := field.Field
@ -57,70 +40,50 @@ func SaveAfterAssociations(scope *Scope) {
for i := 0; i < value.Len(); i++ { for i := 0; i < value.Len(); i++ {
newDB := scope.NewDB() newDB := scope.NewDB()
elem := value.Index(i).Addr().Interface() elem := value.Index(i).Addr().Interface()
newScope := newDB.NewScope(elem)
if relationship.JoinTable == "" && relationship.ForeignFieldName != "" { if relationship.JoinTable == "" && relationship.ForeignFieldName != "" {
newDB.NewScope(elem).SetColumn(relationship.ForeignFieldName, scope.PrimaryKeyValue()) newScope.SetColumn(relationship.ForeignFieldName, scope.PrimaryKeyValue())
} }
if relationship.ForeignType != "" { if relationship.ForeignType != "" {
newDB.NewScope(elem).SetColumn(relationship.ForeignType, scope.TableName()) newScope.SetColumn(relationship.ForeignType, scope.TableName())
} }
scope.Err(newDB.Save(elem).Error) scope.Err(newDB.Save(elem).Error)
if relationship.JoinTable != "" { if joinTable := relationship.JoinTable; joinTable != "" {
if relationship.ForeignType != "" { quotedForeignDBName := scope.Quote(relationship.ForeignDBName)
scope.Err(fmt.Errorf("gorm does not support polymorphic many-to-many associations")) foreignValue := scope.PrimaryKeyValue()
} quoteAssociationForeignDBName := scope.Quote(relationship.AssociationForeignDBName)
associationForeignValue := newScope.PrimaryKeyValue()
newScope := scope.New(elem)
joinTable := relationship.JoinTable
foreignKey := ToSnake(relationship.ForeignFieldName)
foreignValue := fmt.Sprintf("%v", scope.PrimaryKeyValue())
associationForeignKey := ToSnake(relationship.AssociationForeignFieldName)
associationForeignValue := fmt.Sprintf("%v", newScope.PrimaryKeyValue())
newScope.Raw(fmt.Sprintf( newScope.Raw(fmt.Sprintf(
"INSERT INTO %v (%v) SELECT %v %v WHERE NOT EXISTS (SELECT * FROM %v WHERE %v = %v AND %v = %v);", "INSERT INTO %v (%v) SELECT %v %v WHERE NOT EXISTS (SELECT * FROM %v WHERE %v = %v AND %v = %v);",
joinTable, joinTable,
strings.Join([]string{scope.Quote(foreignKey), scope.Quote(associationForeignKey)}, ","), strings.Join([]string{quotedForeignDBName, quoteAssociationForeignDBName}, ","),
strings.Join([]string{newScope.AddToVars(foreignValue), newScope.AddToVars(associationForeignValue)}, ","), strings.Join([]string{newScope.AddToVars(foreignValue), newScope.AddToVars(associationForeignValue)}, ","),
scope.Dialect().SelectFromDummyTable(), scope.Dialect().SelectFromDummyTable(),
joinTable, joinTable,
scope.Quote(foreignKey), quotedForeignDBName,
newScope.AddToVars(foreignValue), newScope.AddToVars(foreignValue),
scope.Quote(associationForeignKey), quoteAssociationForeignDBName,
newScope.AddToVars(associationForeignValue), newScope.AddToVars(associationForeignValue),
)) ))
scope.Err(scope.NewDB().Exec(newScope.Sql, newScope.SqlVars...).Error) scope.Err(scope.NewDB().Exec(newScope.Sql, newScope.SqlVars...).Error)
} }
} }
default: default:
newDB := scope.NewDB() elem := value.Addr().Interface()
if value.CanAddr() { newScope := scope.New(elem)
if relationship.ForeignFieldName != "" { if relationship.ForeignFieldName != "" {
newDB.NewScope(value.Addr().Interface()).SetColumn(relationship.ForeignFieldName, scope.PrimaryKeyValue()) newScope.SetColumn(relationship.ForeignFieldName, scope.PrimaryKeyValue())
}
if relationship.ForeignType != "" {
newDB.NewScope(value.Addr().Interface()).SetColumn(relationship.ForeignType, scope.TableName())
}
scope.Err(newDB.Save(value.Addr().Interface()).Error)
} else {
destValue := reflect.New(field.Field.Type()).Elem()
for _, f := range newDB.NewScope(field.Field.Addr().Interface()).Fields() {
destValue.FieldByName(f.Name).Set(f.Field)
}
elem := destValue.Addr().Interface()
if relationship.ForeignFieldName != "" {
newDB.NewScope(elem).SetColumn(relationship.ForeignFieldName, scope.PrimaryKeyValue())
}
if relationship.ForeignType != "" {
newDB.NewScope(value.Addr().Interface()).SetColumn(relationship.ForeignType, scope.TableName())
}
scope.Err(newDB.Save(elem).Error)
scope.SetColumn(field.Name, destValue.Interface())
} }
if relationship.ForeignType != "" {
newScope.SetColumn(relationship.ForeignType, scope.TableName())
}
scope.Err(scope.NewDB().Save(elem).Error)
} }
} }
} }