association.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. package gorm
  2. import (
  3. "errors"
  4. "fmt"
  5. "reflect"
  6. )
  7. // Association Mode contains some helper methods to handle relationship things easily.
  8. type Association struct {
  9. Error error
  10. scope *Scope
  11. column string
  12. field *Field
  13. }
  14. // Find find out all related associations
  15. func (association *Association) Find(value interface{}) *Association {
  16. association.scope.related(value, association.column)
  17. return association.setErr(association.scope.db.Error)
  18. }
  19. // Append append new associations for many2many, has_many, replace current association for has_one, belongs_to
  20. func (association *Association) Append(values ...interface{}) *Association {
  21. if association.Error != nil {
  22. return association
  23. }
  24. if relationship := association.field.Relationship; relationship.Kind == "has_one" {
  25. return association.Replace(values...)
  26. }
  27. return association.saveAssociations(values...)
  28. }
  29. // Replace replace current associations with new one
  30. func (association *Association) Replace(values ...interface{}) *Association {
  31. if association.Error != nil {
  32. return association
  33. }
  34. var (
  35. relationship = association.field.Relationship
  36. scope = association.scope
  37. field = association.field.Field
  38. newDB = scope.NewDB()
  39. )
  40. // Append new values
  41. association.field.Set(reflect.Zero(association.field.Field.Type()))
  42. association.saveAssociations(values...)
  43. // Belongs To
  44. if relationship.Kind == "belongs_to" {
  45. // Set foreign key to be null when clearing value (length equals 0)
  46. if len(values) == 0 {
  47. // Set foreign key to be nil
  48. var foreignKeyMap = map[string]interface{}{}
  49. for _, foreignKey := range relationship.ForeignDBNames {
  50. foreignKeyMap[foreignKey] = nil
  51. }
  52. association.setErr(newDB.Model(scope.Value).UpdateColumn(foreignKeyMap).Error)
  53. }
  54. } else {
  55. // Polymorphic Relations
  56. if relationship.PolymorphicDBName != "" {
  57. newDB = newDB.Where(fmt.Sprintf("%v = ?", scope.Quote(relationship.PolymorphicDBName)), relationship.PolymorphicValue)
  58. }
  59. // Delete Relations except new created
  60. if len(values) > 0 {
  61. var associationForeignFieldNames, associationForeignDBNames []string
  62. if relationship.Kind == "many_to_many" {
  63. // if many to many relations, get association fields name from association foreign keys
  64. associationScope := scope.New(reflect.New(field.Type()).Interface())
  65. for idx, dbName := range relationship.AssociationForeignFieldNames {
  66. if field, ok := associationScope.FieldByName(dbName); ok {
  67. associationForeignFieldNames = append(associationForeignFieldNames, field.Name)
  68. associationForeignDBNames = append(associationForeignDBNames, relationship.AssociationForeignDBNames[idx])
  69. }
  70. }
  71. } else {
  72. // If has one/many relations, use primary keys
  73. for _, field := range scope.New(reflect.New(field.Type()).Interface()).PrimaryFields() {
  74. associationForeignFieldNames = append(associationForeignFieldNames, field.Name)
  75. associationForeignDBNames = append(associationForeignDBNames, field.DBName)
  76. }
  77. }
  78. newPrimaryKeys := scope.getColumnAsArray(associationForeignFieldNames, field.Interface())
  79. if len(newPrimaryKeys) > 0 {
  80. sql := fmt.Sprintf("%v NOT IN (%v)", toQueryCondition(scope, associationForeignDBNames), toQueryMarks(newPrimaryKeys))
  81. newDB = newDB.Where(sql, toQueryValues(newPrimaryKeys)...)
  82. }
  83. }
  84. if relationship.Kind == "many_to_many" {
  85. // if many to many relations, delete related relations from join table
  86. var sourceForeignFieldNames []string
  87. for _, dbName := range relationship.ForeignFieldNames {
  88. if field, ok := scope.FieldByName(dbName); ok {
  89. sourceForeignFieldNames = append(sourceForeignFieldNames, field.Name)
  90. }
  91. }
  92. if sourcePrimaryKeys := scope.getColumnAsArray(sourceForeignFieldNames, scope.Value); len(sourcePrimaryKeys) > 0 {
  93. newDB = newDB.Where(fmt.Sprintf("%v IN (%v)", toQueryCondition(scope, relationship.ForeignDBNames), toQueryMarks(sourcePrimaryKeys)), toQueryValues(sourcePrimaryKeys)...)
  94. association.setErr(relationship.JoinTableHandler.Delete(relationship.JoinTableHandler, newDB))
  95. }
  96. } else if relationship.Kind == "has_one" || relationship.Kind == "has_many" {
  97. // has_one or has_many relations, set foreign key to be nil (TODO or delete them?)
  98. var foreignKeyMap = map[string]interface{}{}
  99. for idx, foreignKey := range relationship.ForeignDBNames {
  100. foreignKeyMap[foreignKey] = nil
  101. if field, ok := scope.FieldByName(relationship.AssociationForeignFieldNames[idx]); ok {
  102. newDB = newDB.Where(fmt.Sprintf("%v = ?", scope.Quote(foreignKey)), field.Field.Interface())
  103. }
  104. }
  105. fieldValue := reflect.New(association.field.Field.Type()).Interface()
  106. association.setErr(newDB.Model(fieldValue).UpdateColumn(foreignKeyMap).Error)
  107. }
  108. }
  109. return association
  110. }
  111. // Delete remove relationship between source & passed arguments, but won't delete those arguments
  112. func (association *Association) Delete(values ...interface{}) *Association {
  113. if association.Error != nil {
  114. return association
  115. }
  116. var (
  117. relationship = association.field.Relationship
  118. scope = association.scope
  119. field = association.field.Field
  120. newDB = scope.NewDB()
  121. )
  122. if len(values) == 0 {
  123. return association
  124. }
  125. var deletingResourcePrimaryFieldNames, deletingResourcePrimaryDBNames []string
  126. for _, field := range scope.New(reflect.New(field.Type()).Interface()).PrimaryFields() {
  127. deletingResourcePrimaryFieldNames = append(deletingResourcePrimaryFieldNames, field.Name)
  128. deletingResourcePrimaryDBNames = append(deletingResourcePrimaryDBNames, field.DBName)
  129. }
  130. deletingPrimaryKeys := scope.getColumnAsArray(deletingResourcePrimaryFieldNames, values...)
  131. if relationship.Kind == "many_to_many" {
  132. // source value's foreign keys
  133. for idx, foreignKey := range relationship.ForeignDBNames {
  134. if field, ok := scope.FieldByName(relationship.ForeignFieldNames[idx]); ok {
  135. newDB = newDB.Where(fmt.Sprintf("%v = ?", scope.Quote(foreignKey)), field.Field.Interface())
  136. }
  137. }
  138. // get association's foreign fields name
  139. var associationScope = scope.New(reflect.New(field.Type()).Interface())
  140. var associationForeignFieldNames []string
  141. for _, associationDBName := range relationship.AssociationForeignFieldNames {
  142. if field, ok := associationScope.FieldByName(associationDBName); ok {
  143. associationForeignFieldNames = append(associationForeignFieldNames, field.Name)
  144. }
  145. }
  146. // association value's foreign keys
  147. deletingPrimaryKeys := scope.getColumnAsArray(associationForeignFieldNames, values...)
  148. sql := fmt.Sprintf("%v IN (%v)", toQueryCondition(scope, relationship.AssociationForeignDBNames), toQueryMarks(deletingPrimaryKeys))
  149. newDB = newDB.Where(sql, toQueryValues(deletingPrimaryKeys)...)
  150. association.setErr(relationship.JoinTableHandler.Delete(relationship.JoinTableHandler, newDB))
  151. } else {
  152. var foreignKeyMap = map[string]interface{}{}
  153. for _, foreignKey := range relationship.ForeignDBNames {
  154. foreignKeyMap[foreignKey] = nil
  155. }
  156. if relationship.Kind == "belongs_to" {
  157. // find with deleting relation's foreign keys
  158. primaryKeys := scope.getColumnAsArray(relationship.AssociationForeignFieldNames, values...)
  159. newDB = newDB.Where(
  160. fmt.Sprintf("%v IN (%v)", toQueryCondition(scope, relationship.ForeignDBNames), toQueryMarks(primaryKeys)),
  161. toQueryValues(primaryKeys)...,
  162. )
  163. // set foreign key to be null if there are some records affected
  164. modelValue := reflect.New(scope.GetModelStruct().ModelType).Interface()
  165. if results := newDB.Model(modelValue).UpdateColumn(foreignKeyMap); results.Error == nil {
  166. if results.RowsAffected > 0 {
  167. scope.updatedAttrsWithValues(foreignKeyMap)
  168. }
  169. } else {
  170. association.setErr(results.Error)
  171. }
  172. } else if relationship.Kind == "has_one" || relationship.Kind == "has_many" {
  173. // find all relations
  174. primaryKeys := scope.getColumnAsArray(relationship.AssociationForeignFieldNames, scope.Value)
  175. newDB = newDB.Where(
  176. fmt.Sprintf("%v IN (%v)", toQueryCondition(scope, relationship.ForeignDBNames), toQueryMarks(primaryKeys)),
  177. toQueryValues(primaryKeys)...,
  178. )
  179. // only include those deleting relations
  180. newDB = newDB.Where(
  181. fmt.Sprintf("%v IN (%v)", toQueryCondition(scope, deletingResourcePrimaryDBNames), toQueryMarks(deletingPrimaryKeys)),
  182. toQueryValues(deletingPrimaryKeys)...,
  183. )
  184. // set matched relation's foreign key to be null
  185. fieldValue := reflect.New(association.field.Field.Type()).Interface()
  186. association.setErr(newDB.Model(fieldValue).UpdateColumn(foreignKeyMap).Error)
  187. }
  188. }
  189. // Remove deleted records from source's field
  190. if association.Error == nil {
  191. if field.Kind() == reflect.Slice {
  192. leftValues := reflect.Zero(field.Type())
  193. for i := 0; i < field.Len(); i++ {
  194. reflectValue := field.Index(i)
  195. primaryKey := scope.getColumnAsArray(deletingResourcePrimaryFieldNames, reflectValue.Interface())[0]
  196. var isDeleted = false
  197. for _, pk := range deletingPrimaryKeys {
  198. if equalAsString(primaryKey, pk) {
  199. isDeleted = true
  200. break
  201. }
  202. }
  203. if !isDeleted {
  204. leftValues = reflect.Append(leftValues, reflectValue)
  205. }
  206. }
  207. association.field.Set(leftValues)
  208. } else if field.Kind() == reflect.Struct {
  209. primaryKey := scope.getColumnAsArray(deletingResourcePrimaryFieldNames, field.Interface())[0]
  210. for _, pk := range deletingPrimaryKeys {
  211. if equalAsString(primaryKey, pk) {
  212. association.field.Set(reflect.Zero(field.Type()))
  213. break
  214. }
  215. }
  216. }
  217. }
  218. return association
  219. }
  220. // Clear remove relationship between source & current associations, won't delete those associations
  221. func (association *Association) Clear() *Association {
  222. return association.Replace()
  223. }
  224. // Count return the count of current associations
  225. func (association *Association) Count() int {
  226. var (
  227. count = 0
  228. relationship = association.field.Relationship
  229. scope = association.scope
  230. fieldValue = association.field.Field.Interface()
  231. query = scope.DB()
  232. )
  233. switch relationship.Kind {
  234. case "many_to_many":
  235. query = relationship.JoinTableHandler.JoinWith(relationship.JoinTableHandler, query, scope.Value)
  236. case "has_many", "has_one":
  237. primaryKeys := scope.getColumnAsArray(relationship.AssociationForeignFieldNames, scope.Value)
  238. query = query.Where(
  239. fmt.Sprintf("%v IN (%v)", toQueryCondition(scope, relationship.ForeignDBNames), toQueryMarks(primaryKeys)),
  240. toQueryValues(primaryKeys)...,
  241. )
  242. case "belongs_to":
  243. primaryKeys := scope.getColumnAsArray(relationship.ForeignFieldNames, scope.Value)
  244. query = query.Where(
  245. fmt.Sprintf("%v IN (%v)", toQueryCondition(scope, relationship.AssociationForeignDBNames), toQueryMarks(primaryKeys)),
  246. toQueryValues(primaryKeys)...,
  247. )
  248. }
  249. if relationship.PolymorphicType != "" {
  250. query = query.Where(
  251. fmt.Sprintf("%v.%v = ?", scope.New(fieldValue).QuotedTableName(), scope.Quote(relationship.PolymorphicDBName)),
  252. relationship.PolymorphicValue,
  253. )
  254. }
  255. if err := query.Model(fieldValue).Count(&count).Error; err != nil {
  256. association.Error = err
  257. }
  258. return count
  259. }
  260. // saveAssociations save passed values as associations
  261. func (association *Association) saveAssociations(values ...interface{}) *Association {
  262. var (
  263. scope = association.scope
  264. field = association.field
  265. relationship = field.Relationship
  266. )
  267. saveAssociation := func(reflectValue reflect.Value) {
  268. // value has to been pointer
  269. if reflectValue.Kind() != reflect.Ptr {
  270. reflectPtr := reflect.New(reflectValue.Type())
  271. reflectPtr.Elem().Set(reflectValue)
  272. reflectValue = reflectPtr
  273. }
  274. // value has to been saved for many2many
  275. if relationship.Kind == "many_to_many" {
  276. if scope.New(reflectValue.Interface()).PrimaryKeyZero() {
  277. association.setErr(scope.NewDB().Save(reflectValue.Interface()).Error)
  278. }
  279. }
  280. // Assign Fields
  281. var fieldType = field.Field.Type()
  282. var setFieldBackToValue, setSliceFieldBackToValue bool
  283. if reflectValue.Type().AssignableTo(fieldType) {
  284. field.Set(reflectValue)
  285. } else if reflectValue.Type().Elem().AssignableTo(fieldType) {
  286. // if field's type is struct, then need to set value back to argument after save
  287. setFieldBackToValue = true
  288. field.Set(reflectValue.Elem())
  289. } else if fieldType.Kind() == reflect.Slice {
  290. if reflectValue.Type().AssignableTo(fieldType.Elem()) {
  291. field.Set(reflect.Append(field.Field, reflectValue))
  292. } else if reflectValue.Type().Elem().AssignableTo(fieldType.Elem()) {
  293. // if field's type is slice of struct, then need to set value back to argument after save
  294. setSliceFieldBackToValue = true
  295. field.Set(reflect.Append(field.Field, reflectValue.Elem()))
  296. }
  297. }
  298. if relationship.Kind == "many_to_many" {
  299. association.setErr(relationship.JoinTableHandler.Add(relationship.JoinTableHandler, scope.NewDB(), scope.Value, reflectValue.Interface()))
  300. } else {
  301. association.setErr(scope.NewDB().Select(field.Name).Save(scope.Value).Error)
  302. if setFieldBackToValue {
  303. reflectValue.Elem().Set(field.Field)
  304. } else if setSliceFieldBackToValue {
  305. reflectValue.Elem().Set(field.Field.Index(field.Field.Len() - 1))
  306. }
  307. }
  308. }
  309. for _, value := range values {
  310. reflectValue := reflect.ValueOf(value)
  311. indirectReflectValue := reflect.Indirect(reflectValue)
  312. if indirectReflectValue.Kind() == reflect.Struct {
  313. saveAssociation(reflectValue)
  314. } else if indirectReflectValue.Kind() == reflect.Slice {
  315. for i := 0; i < indirectReflectValue.Len(); i++ {
  316. saveAssociation(indirectReflectValue.Index(i))
  317. }
  318. } else {
  319. association.setErr(errors.New("invalid value type"))
  320. }
  321. }
  322. return association
  323. }
  324. // setErr set error when the error is not nil. And return Association.
  325. func (association *Association) setErr(err error) *Association {
  326. if err != nil {
  327. association.Error = err
  328. }
  329. return association
  330. }