gorm/join_table.go

49 lines
1.5 KiB
Go
Raw Normal View History

2015-02-28 06:48:18 +03:00
package gorm
import (
"fmt"
"strings"
)
type JoinTableHandler interface {
2015-03-04 07:16:16 +03:00
Table(*DB, *Relationship) string
2015-02-28 06:48:18 +03:00
Add(*DB, *Relationship, interface{}, interface{}) error
Delete(*DB, *Relationship) error
Scope(*DB, *Relationship) *DB
}
type defaultJoinTableHandler struct{}
2015-03-04 07:16:16 +03:00
func (s *defaultJoinTableHandler) Table(db *DB, relationship *Relationship) string {
return relationship.JoinTable
}
func (s *defaultJoinTableHandler) Add(db *DB, relationship *Relationship, foreignValue interface{}, associationValue interface{}) error {
2015-02-28 06:48:18 +03:00
scope := db.NewScope("")
quotedForeignDBName := scope.Quote(relationship.ForeignDBName)
quotedAssociationDBName := scope.Quote(relationship.AssociationForeignDBName)
2015-03-04 07:16:16 +03:00
table := s.Table(db, relationship)
2015-02-28 06:48:18 +03:00
sql := fmt.Sprintf(
"INSERT INTO %v (%v) SELECT ?,? %v WHERE NOT EXISTS (SELECT * FROM %v WHERE %v = ? AND %v = ?);",
2015-03-04 07:16:16 +03:00
scope.Quote(table),
2015-02-28 06:48:18 +03:00
strings.Join([]string{quotedForeignDBName, quotedAssociationDBName}, ","),
scope.Dialect().SelectFromDummyTable(),
2015-03-04 07:16:16 +03:00
scope.Quote(table),
2015-02-28 06:48:18 +03:00
quotedForeignDBName,
quotedAssociationDBName,
)
return db.Exec(sql, foreignValue, associationValue, foreignValue, associationValue).Error
}
2015-03-04 07:16:16 +03:00
func (s *defaultJoinTableHandler) Delete(db *DB, relationship *Relationship) error {
return db.Table(s.Table(db, relationship)).Delete("").Error
2015-02-28 06:48:18 +03:00
}
2015-03-04 07:16:16 +03:00
func (s *defaultJoinTableHandler) Scope(db *DB, relationship *Relationship) *DB {
return db.Table(s.Table(db, relationship))
2015-02-28 06:48:18 +03:00
}
var DefaultJoinTableHandler = &defaultJoinTableHandler{}