join_table_handler.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  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. for idx, dbName := range relationship.ForeignFieldNames {
  54. s.Source.ForeignKeys = append(s.Source.ForeignKeys, JoinTableForeignKey{
  55. DBName: relationship.ForeignDBNames[idx],
  56. AssociationDBName: dbName,
  57. })
  58. }
  59. s.Destination = JoinTableSource{ModelType: destination}
  60. for idx, dbName := range relationship.AssociationForeignFieldNames {
  61. s.Destination.ForeignKeys = append(s.Destination.ForeignKeys, JoinTableForeignKey{
  62. DBName: relationship.AssociationForeignDBNames[idx],
  63. AssociationDBName: dbName,
  64. })
  65. }
  66. }
  67. // Table return join table's table name
  68. func (s JoinTableHandler) Table(db *DB) string {
  69. return s.TableName
  70. }
  71. func (s JoinTableHandler) getSearchMap(db *DB, sources ...interface{}) map[string]interface{} {
  72. values := map[string]interface{}{}
  73. for _, source := range sources {
  74. scope := db.NewScope(source)
  75. modelType := scope.GetModelStruct().ModelType
  76. if s.Source.ModelType == modelType {
  77. for _, foreignKey := range s.Source.ForeignKeys {
  78. if field, ok := scope.FieldByName(foreignKey.AssociationDBName); ok {
  79. values[foreignKey.DBName] = field.Field.Interface()
  80. }
  81. }
  82. } else if s.Destination.ModelType == modelType {
  83. for _, foreignKey := range s.Destination.ForeignKeys {
  84. if field, ok := scope.FieldByName(foreignKey.AssociationDBName); ok {
  85. values[foreignKey.DBName] = field.Field.Interface()
  86. }
  87. }
  88. }
  89. }
  90. return values
  91. }
  92. // Add create relationship in join table for source and destination
  93. func (s JoinTableHandler) Add(handler JoinTableHandlerInterface, db *DB, source interface{}, destination interface{}) error {
  94. scope := db.NewScope("")
  95. searchMap := s.getSearchMap(db, source, destination)
  96. var assignColumns, binVars, conditions []string
  97. var values []interface{}
  98. for key, value := range searchMap {
  99. assignColumns = append(assignColumns, scope.Quote(key))
  100. binVars = append(binVars, `?`)
  101. conditions = append(conditions, fmt.Sprintf("%v = ?", scope.Quote(key)))
  102. values = append(values, value)
  103. }
  104. for _, value := range values {
  105. values = append(values, value)
  106. }
  107. quotedTable := scope.Quote(handler.Table(db))
  108. sql := fmt.Sprintf(
  109. "INSERT INTO %v (%v) SELECT %v %v WHERE NOT EXISTS (SELECT * FROM %v WHERE %v)",
  110. quotedTable,
  111. strings.Join(assignColumns, ","),
  112. strings.Join(binVars, ","),
  113. scope.Dialect().SelectFromDummyTable(),
  114. quotedTable,
  115. strings.Join(conditions, " AND "),
  116. )
  117. return db.Exec(sql, values...).Error
  118. }
  119. // Delete delete relationship in join table for sources
  120. func (s JoinTableHandler) Delete(handler JoinTableHandlerInterface, db *DB, sources ...interface{}) error {
  121. var (
  122. scope = db.NewScope(nil)
  123. conditions []string
  124. values []interface{}
  125. )
  126. for key, value := range s.getSearchMap(db, sources...) {
  127. conditions = append(conditions, fmt.Sprintf("%v = ?", scope.Quote(key)))
  128. values = append(values, value)
  129. }
  130. return db.Table(handler.Table(db)).Where(strings.Join(conditions, " AND "), values...).Delete("").Error
  131. }
  132. // JoinWith query with `Join` conditions
  133. func (s JoinTableHandler) JoinWith(handler JoinTableHandlerInterface, db *DB, source interface{}) *DB {
  134. var (
  135. scope = db.NewScope(source)
  136. tableName = handler.Table(db)
  137. quotedTableName = scope.Quote(tableName)
  138. joinConditions []string
  139. values []interface{}
  140. )
  141. if s.Source.ModelType == scope.GetModelStruct().ModelType {
  142. destinationTableName := db.NewScope(reflect.New(s.Destination.ModelType).Interface()).QuotedTableName()
  143. for _, foreignKey := range s.Destination.ForeignKeys {
  144. joinConditions = append(joinConditions, fmt.Sprintf("%v.%v = %v.%v", quotedTableName, scope.Quote(foreignKey.DBName), destinationTableName, scope.Quote(foreignKey.AssociationDBName)))
  145. }
  146. var foreignDBNames []string
  147. var foreignFieldNames []string
  148. for _, foreignKey := range s.Source.ForeignKeys {
  149. foreignDBNames = append(foreignDBNames, foreignKey.DBName)
  150. if field, ok := scope.FieldByName(foreignKey.AssociationDBName); ok {
  151. foreignFieldNames = append(foreignFieldNames, field.Name)
  152. }
  153. }
  154. foreignFieldValues := scope.getColumnAsArray(foreignFieldNames, scope.Value)
  155. var condString string
  156. if len(foreignFieldValues) > 0 {
  157. var quotedForeignDBNames []string
  158. for _, dbName := range foreignDBNames {
  159. quotedForeignDBNames = append(quotedForeignDBNames, tableName+"."+dbName)
  160. }
  161. condString = fmt.Sprintf("%v IN (%v)", toQueryCondition(scope, quotedForeignDBNames), toQueryMarks(foreignFieldValues))
  162. keys := scope.getColumnAsArray(foreignFieldNames, scope.Value)
  163. values = append(values, toQueryValues(keys))
  164. } else {
  165. condString = fmt.Sprintf("1 <> 1")
  166. }
  167. return db.Joins(fmt.Sprintf("INNER JOIN %v ON %v", quotedTableName, strings.Join(joinConditions, " AND "))).
  168. Where(condString, toQueryValues(foreignFieldValues)...)
  169. }
  170. db.Error = errors.New("wrong source type for join table handler")
  171. return db
  172. }