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))
if reflectValue.Kind() == reflect.Slice {
for i := 0; i < reflectValue.Len(); i++ {
primaryField := scope.New(reflectValue.Index(i).Interface()).PrimaryKeyField()
if !primaryField.IsBlank {
if primaryField := scope.New(reflectValue.Index(i).Interface()).PrimaryKeyField(); !primaryField.IsBlank {
primaryKeys = append(primaryKeys, primaryField.Field.Interface())
}
}
} else if reflectValue.Kind() == reflect.Struct {
primaryField := scope.New(value).PrimaryKeyField()
if !primaryField.IsBlank {
if primaryField := scope.New(value).PrimaryKeyField(); !primaryField.IsBlank {
primaryKeys = append(primaryKeys, primaryField.Field.Interface())
}
}
@ -144,9 +142,7 @@ func (association *Association) Count() int {
count := -1
relationship := association.Field.Relationship
scope := association.Scope
field := association.Field.Field
fieldValue := field.Interface()
newScope := scope.New(fieldValue)
newScope := scope.New(association.Field.Field.Interface())
if relationship.Kind == "many_to_many" {
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
var sqls, columns []string
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 {
continue
}
@ -35,8 +35,9 @@ func Create(scope *Scope) {
}
returningKey := "*"
if scope.PrimaryKey() != "" {
returningKey = scope.Quote(scope.PrimaryKey())
primaryField := scope.PrimaryKeyField()
if primaryField != nil {
returningKey = scope.Quote(primaryField.DBName)
}
if len(columns) == 0 {
@ -64,19 +65,17 @@ func Create(scope *Scope) {
}
}
} else {
if scope.PrimaryKey() == "" {
if primaryField == nil {
if results, err := scope.DB().Exec(scope.Sql, scope.SqlVars...); err != nil {
scope.db.RowsAffected, _ = results.RowsAffected()
}
} else {
if scope.Err(scope.DB().QueryRow(scope.Sql, scope.SqlVars...).Scan(&id)) == nil {
scope.db.RowsAffected = 1
}
} else if scope.Err(scope.DB().QueryRow(scope.Sql, scope.SqlVars...).Scan(&id)) == nil {
scope.db.RowsAffected = 1
}
}
if scope.PrimaryKey() != "" && !scope.HasError() && scope.PrimaryKeyZero() {
scope.SetColumn(scope.PrimaryKey(), id)
if primaryField != nil && primaryField.IsBlank && !scope.HasError() {
scope.SetColumn(primaryField, id)
}
}
}

View File

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

View File

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