callback.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. package gorm
  2. import (
  3. "fmt"
  4. )
  5. // DefaultCallback default callbacks defined by gorm
  6. var DefaultCallback = &Callback{}
  7. // Callback is a struct that contains all CRUD callbacks
  8. // Field `creates` contains callbacks will be call when creating object
  9. // Field `updates` contains callbacks will be call when updating object
  10. // Field `deletes` contains callbacks will be call when deleting object
  11. // Field `queries` contains callbacks will be call when querying object with query methods like Find, First, Related, Association...
  12. // Field `rowQueries` contains callbacks will be call when querying object with Row, Rows...
  13. // Field `processors` contains all callback processors, will be used to generate above callbacks in order
  14. type Callback struct {
  15. creates []*func(scope *Scope)
  16. updates []*func(scope *Scope)
  17. deletes []*func(scope *Scope)
  18. queries []*func(scope *Scope)
  19. rowQueries []*func(scope *Scope)
  20. processors []*CallbackProcessor
  21. }
  22. // CallbackProcessor contains callback informations
  23. type CallbackProcessor struct {
  24. name string // current callback's name
  25. before string // register current callback before a callback
  26. after string // register current callback after a callback
  27. replace bool // replace callbacks with same name
  28. remove bool // delete callbacks with same name
  29. kind string // callback type: create, update, delete, query, row_query
  30. processor *func(scope *Scope) // callback handler
  31. parent *Callback
  32. }
  33. func (c *Callback) clone() *Callback {
  34. return &Callback{
  35. creates: c.creates,
  36. updates: c.updates,
  37. deletes: c.deletes,
  38. queries: c.queries,
  39. rowQueries: c.rowQueries,
  40. processors: c.processors,
  41. }
  42. }
  43. // Create could be used to register callbacks for creating object
  44. // db.Callback().Create().After("gorm:create").Register("plugin:run_after_create", func(*Scope) {
  45. // // business logic
  46. // ...
  47. //
  48. // // set error if some thing wrong happened, will rollback the creating
  49. // scope.Err(errors.New("error"))
  50. // })
  51. func (c *Callback) Create() *CallbackProcessor {
  52. return &CallbackProcessor{kind: "create", parent: c}
  53. }
  54. // Update could be used to register callbacks for updating object, refer `Create` for usage
  55. func (c *Callback) Update() *CallbackProcessor {
  56. return &CallbackProcessor{kind: "update", parent: c}
  57. }
  58. // Delete could be used to register callbacks for deleting object, refer `Create` for usage
  59. func (c *Callback) Delete() *CallbackProcessor {
  60. return &CallbackProcessor{kind: "delete", parent: c}
  61. }
  62. // Query could be used to register callbacks for querying objects with query methods like `Find`, `First`, `Related`, `Association`...
  63. // Refer `Create` for usage
  64. func (c *Callback) Query() *CallbackProcessor {
  65. return &CallbackProcessor{kind: "query", parent: c}
  66. }
  67. // RowQuery could be used to register callbacks for querying objects with `Row`, `Rows`, refer `Create` for usage
  68. func (c *Callback) RowQuery() *CallbackProcessor {
  69. return &CallbackProcessor{kind: "row_query", parent: c}
  70. }
  71. // After insert a new callback after callback `callbackName`, refer `Callbacks.Create`
  72. func (cp *CallbackProcessor) After(callbackName string) *CallbackProcessor {
  73. cp.after = callbackName
  74. return cp
  75. }
  76. // Before insert a new callback before callback `callbackName`, refer `Callbacks.Create`
  77. func (cp *CallbackProcessor) Before(callbackName string) *CallbackProcessor {
  78. cp.before = callbackName
  79. return cp
  80. }
  81. // Register a new callback, refer `Callbacks.Create`
  82. func (cp *CallbackProcessor) Register(callbackName string, callback func(scope *Scope)) {
  83. if cp.kind == "row_query" {
  84. if cp.before == "" && cp.after == "" && callbackName != "gorm:row_query" {
  85. fmt.Printf("Registing RowQuery callback %v without specify order with Before(), After(), applying Before('gorm:row_query') by default for compatibility...\n", callbackName)
  86. cp.before = "gorm:row_query"
  87. }
  88. }
  89. cp.name = callbackName
  90. cp.processor = &callback
  91. cp.parent.processors = append(cp.parent.processors, cp)
  92. cp.parent.reorder()
  93. }
  94. // Remove a registered callback
  95. // db.Callback().Create().Remove("gorm:update_time_stamp_when_create")
  96. func (cp *CallbackProcessor) Remove(callbackName string) {
  97. fmt.Printf("[info] removing callback `%v` from %v\n", callbackName, fileWithLineNum())
  98. cp.name = callbackName
  99. cp.remove = true
  100. cp.parent.processors = append(cp.parent.processors, cp)
  101. cp.parent.reorder()
  102. }
  103. // Replace a registered callback with new callback
  104. // db.Callback().Create().Replace("gorm:update_time_stamp_when_create", func(*Scope) {
  105. // scope.SetColumn("Created", now)
  106. // scope.SetColumn("Updated", now)
  107. // })
  108. func (cp *CallbackProcessor) Replace(callbackName string, callback func(scope *Scope)) {
  109. fmt.Printf("[info] replacing callback `%v` from %v\n", callbackName, fileWithLineNum())
  110. cp.name = callbackName
  111. cp.processor = &callback
  112. cp.replace = true
  113. cp.parent.processors = append(cp.parent.processors, cp)
  114. cp.parent.reorder()
  115. }
  116. // Get registered callback
  117. // db.Callback().Create().Get("gorm:create")
  118. func (cp *CallbackProcessor) Get(callbackName string) (callback func(scope *Scope)) {
  119. for _, p := range cp.parent.processors {
  120. if p.name == callbackName && p.kind == cp.kind && !cp.remove {
  121. return *p.processor
  122. }
  123. }
  124. return nil
  125. }
  126. // getRIndex get right index from string slice
  127. func getRIndex(strs []string, str string) int {
  128. for i := len(strs) - 1; i >= 0; i-- {
  129. if strs[i] == str {
  130. return i
  131. }
  132. }
  133. return -1
  134. }
  135. // sortProcessors sort callback processors based on its before, after, remove, replace
  136. func sortProcessors(cps []*CallbackProcessor) []*func(scope *Scope) {
  137. var (
  138. allNames, sortedNames []string
  139. sortCallbackProcessor func(c *CallbackProcessor)
  140. )
  141. for _, cp := range cps {
  142. // show warning message the callback name already exists
  143. if index := getRIndex(allNames, cp.name); index > -1 && !cp.replace && !cp.remove {
  144. fmt.Printf("[warning] duplicated callback `%v` from %v\n", cp.name, fileWithLineNum())
  145. }
  146. allNames = append(allNames, cp.name)
  147. }
  148. sortCallbackProcessor = func(c *CallbackProcessor) {
  149. if getRIndex(sortedNames, c.name) == -1 { // if not sorted
  150. if c.before != "" { // if defined before callback
  151. if index := getRIndex(sortedNames, c.before); index != -1 {
  152. // if before callback already sorted, append current callback just after it
  153. sortedNames = append(sortedNames[:index], append([]string{c.name}, sortedNames[index:]...)...)
  154. } else if index := getRIndex(allNames, c.before); index != -1 {
  155. // if before callback exists but haven't sorted, append current callback to last
  156. sortedNames = append(sortedNames, c.name)
  157. sortCallbackProcessor(cps[index])
  158. }
  159. }
  160. if c.after != "" { // if defined after callback
  161. if index := getRIndex(sortedNames, c.after); index != -1 {
  162. // if after callback already sorted, append current callback just before it
  163. sortedNames = append(sortedNames[:index+1], append([]string{c.name}, sortedNames[index+1:]...)...)
  164. } else if index := getRIndex(allNames, c.after); index != -1 {
  165. // if after callback exists but haven't sorted
  166. cp := cps[index]
  167. // set after callback's before callback to current callback
  168. if cp.before == "" {
  169. cp.before = c.name
  170. }
  171. sortCallbackProcessor(cp)
  172. }
  173. }
  174. // if current callback haven't been sorted, append it to last
  175. if getRIndex(sortedNames, c.name) == -1 {
  176. sortedNames = append(sortedNames, c.name)
  177. }
  178. }
  179. }
  180. for _, cp := range cps {
  181. sortCallbackProcessor(cp)
  182. }
  183. var sortedFuncs []*func(scope *Scope)
  184. for _, name := range sortedNames {
  185. if index := getRIndex(allNames, name); !cps[index].remove {
  186. sortedFuncs = append(sortedFuncs, cps[index].processor)
  187. }
  188. }
  189. return sortedFuncs
  190. }
  191. // reorder all registered processors, and reset CRUD callbacks
  192. func (c *Callback) reorder() {
  193. var creates, updates, deletes, queries, rowQueries []*CallbackProcessor
  194. for _, processor := range c.processors {
  195. if processor.name != "" {
  196. switch processor.kind {
  197. case "create":
  198. creates = append(creates, processor)
  199. case "update":
  200. updates = append(updates, processor)
  201. case "delete":
  202. deletes = append(deletes, processor)
  203. case "query":
  204. queries = append(queries, processor)
  205. case "row_query":
  206. rowQueries = append(rowQueries, processor)
  207. }
  208. }
  209. }
  210. c.creates = sortProcessors(creates)
  211. c.updates = sortProcessors(updates)
  212. c.deletes = sortProcessors(deletes)
  213. c.queries = sortProcessors(queries)
  214. c.rowQueries = sortProcessors(rowQueries)
  215. }