join_table_handler.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. package gorm
  2. import (
  3. "errors"
  4. "fmt"
  5. "reflect"
  6. "strings"
  7. )
  8. // JoinTableHandlerInterface is an interface for how to handle many2many relations
  9. type JoinTableHandlerInterface interface {
  10. // initialize join table handler
  11. Setup(relationship *Relationship, tableName string, source reflect.Type, destination reflect.Type)
  12. // Table return join table's table name
  13. Table(db *DB) string
  14. // Add create relationship in join table for source and destination
  15. Add(handler JoinTableHandlerInterface, db *DB, source interface{}, destination interface{}) error
  16. // Delete delete relationship in join table for sources
  17. Delete(handler JoinTableHandlerInterface, db *DB, sources ...interface{}) error
  18. // JoinWith query with `Join` conditions
  19. JoinWith(handler JoinTableHandlerInterface, db *DB, source interface{}) *DB
  20. // SourceForeignKeys return source foreign keys
  21. SourceForeignKeys() []JoinTableForeignKey
  22. // DestinationForeignKeys return destination foreign keys
  23. DestinationForeignKeys() []JoinTableForeignKey
  24. }
  25. // JoinTableForeignKey join table foreign key struct
  26. type JoinTableForeignKey struct {
  27. DBName string
  28. AssociationDBName string
  29. }
  30. // JoinTableSource is a struct that contains model type and foreign keys
  31. type JoinTableSource struct {
  32. ModelType reflect.Type
  33. ForeignKeys []JoinTableForeignKey
  34. }
  35. // JoinTableHandler default join table handler
  36. type JoinTableHandler struct {
  37. TableName string `sql:"-"`
  38. Source JoinTableSource `sql:"-"`
  39. Destination JoinTableSource `sql:"-"`
  40. }
  41. // SourceForeignKeys return source foreign keys
  42. func (s *JoinTableHandler) SourceForeignKeys() []JoinTableForeignKey {
  43. return s.Source.ForeignKeys
  44. }
  45. // DestinationForeignKeys return destination foreign keys
  46. func (s *JoinTableHandler) DestinationForeignKeys() []JoinTableForeignKey {
  47. return s.Destination.ForeignKeys
  48. }
  49. // Setup initialize a default join table handler
  50. func (s *JoinTableHandler) Setup(relationship *Relationship, tableName string, source reflect.Type, destination reflect.Type) {
  51. s.TableName = tableName
  52. s.Source = JoinTableSource{ModelType: source}
  53. s.Source.ForeignKeys = []JoinTableForeignKey{}
  54. for idx, dbName := range relationship.ForeignFieldNames {
  55. s.Source.ForeignKeys = append(s.Source.ForeignKeys, JoinTableForeignKey{
  56. DBName: relationship.ForeignDBNames[idx],
  57. AssociationDBName: dbName,
  58. })
  59. }
  60. s.Destination = JoinTableSource{ModelType: destination}
  61. s.Destination.ForeignKeys = []JoinTableForeignKey{}
  62. for idx, dbName := range relationship.AssociationForeignFieldNames {
  63. s.Destination.ForeignKeys = append(s.Destination.ForeignKeys, JoinTableForeignKey{
  64. DBName: relationship.AssociationForeignDBNames[idx],
  65. AssociationDBName: dbName,
  66. })
  67. }
  68. }
  69. // Table return join table's table name
  70. func (s JoinTableHandler) Table(db *DB) string {
  71. return s.TableName
  72. }
  73. func (s JoinTableHandler) getSearchMap(db *DB, sources ...interface{}) map[string]interface{} {
  74. values := map[string]interface{}{}
  75. for _, source := range sources {
  76. scope := db.NewScope(source)
  77. modelType := scope.GetModelStruct().ModelType
  78. if s.Source.ModelType == modelType {
  79. for _, foreignKey := range s.Source.ForeignKeys {
  80. if field, ok := scope.FieldByName(foreignKey.AssociationDBName); ok {
  81. values[foreignKey.DBName] = field.Field.Interface()
  82. }
  83. }
  84. } else if s.Destination.ModelType == modelType {
  85. for _, foreignKey := range s.Destination.ForeignKeys {
  86. if field, ok := scope.FieldByName(foreignKey.AssociationDBName); ok {
  87. values[foreignKey.DBName] = field.Field.Interface()
  88. }
  89. }
  90. }
  91. }
  92. return values
  93. }
  94. // Add create relationship in join table for source and destination
  95. func (s JoinTableHandler) Add(handler JoinTableHandlerInterface, db *DB, source interface{}, destination interface{}) error {
  96. scope := db.NewScope("")
  97. searchMap := s.getSearchMap(db, source, destination)
  98. var assignColumns, binVars, conditions []string
  99. var values []interface{}
  100. for key, value := range searchMap {
  101. assignColumns = append(assignColumns, scope.Quote(key))
  102. binVars = append(binVars, `?`)
  103. conditions = append(conditions, fmt.Sprintf("%v = ?", scope.Quote(key)))
  104. values = append(values, value)
  105. }
  106. for _, value := range values {
  107. values = append(values, value)
  108. }
  109. quotedTable := scope.Quote(handler.Table(db))
  110. sql := fmt.Sprintf(
  111. "INSERT INTO %v (%v) SELECT %v %v WHERE NOT EXISTS (SELECT * FROM %v WHERE %v)",
  112. quotedTable,
  113. strings.Join(assignColumns, ","),
  114. strings.Join(binVars, ","),
  115. scope.Dialect().SelectFromDummyTable(),
  116. quotedTable,
  117. strings.Join(conditions, " AND "),
  118. )
  119. return db.Exec(sql, values...).Error
  120. }
  121. // Delete delete relationship in join table for sources
  122. func (s JoinTableHandler) Delete(handler JoinTableHandlerInterface, db *DB, sources ...interface{}) error {
  123. var (
  124. scope = db.NewScope(nil)
  125. conditions []string
  126. values []interface{}
  127. )
  128. for key, value := range s.getSearchMap(db, sources...) {
  129. conditions = append(conditions, fmt.Sprintf("%v = ?", scope.Quote(key)))
  130. values = append(values, value)
  131. }
  132. return db.Table(handler.Table(db)).Where(strings.Join(conditions, " AND "), values...).Delete("").Error
  133. }
  134. // JoinWith query with `Join` conditions
  135. func (s JoinTableHandler) JoinWith(handler JoinTableHandlerInterface, db *DB, source interface{}) *DB {
  136. var (
  137. scope = db.NewScope(source)
  138. tableName = handler.Table(db)
  139. quotedTableName = scope.Quote(tableName)
  140. joinConditions []string
  141. values []interface{}
  142. )
  143. if s.Source.ModelType == scope.GetModelStruct().ModelType {
  144. destinationTableName := db.NewScope(reflect.New(s.Destination.ModelType).Interface()).QuotedTableName()
  145. for _, foreignKey := range s.Destination.ForeignKeys {
  146. joinConditions = append(joinConditions, fmt.Sprintf("%v.%v = %v.%v", quotedTableName, scope.Quote(foreignKey.DBName), destinationTableName, scope.Quote(foreignKey.AssociationDBName)))
  147. }
  148. var foreignDBNames []string
  149. var foreignFieldNames []string
  150. for _, foreignKey := range s.Source.ForeignKeys {
  151. foreignDBNames = append(foreignDBNames, foreignKey.DBName)
  152. if field, ok := scope.FieldByName(foreignKey.AssociationDBName); ok {
  153. foreignFieldNames = append(foreignFieldNames, field.Name)
  154. }
  155. }
  156. foreignFieldValues := scope.getColumnAsArray(foreignFieldNames, scope.Value)
  157. var condString string
  158. if len(foreignFieldValues) > 0 {
  159. var quotedForeignDBNames []string
  160. for _, dbName := range foreignDBNames {
  161. quotedForeignDBNames = append(quotedForeignDBNames, tableName+"."+dbName)
  162. }
  163. condString = fmt.Sprintf("%v IN (%v)", toQueryCondition(scope, quotedForeignDBNames), toQueryMarks(foreignFieldValues))
  164. keys := scope.getColumnAsArray(foreignFieldNames, scope.Value)
  165. values = append(values, toQueryValues(keys))
  166. } else {
  167. condString = fmt.Sprintf("1 <> 1")
  168. }
  169. return db.Joins(fmt.Sprintf("INNER JOIN %v ON %v", quotedTableName, strings.Join(joinConditions, " AND "))).
  170. Where(condString, toQueryValues(foreignFieldValues)...)
  171. }
  172. db.Error = errors.New("wrong source type for join table handler")
  173. return db
  174. }