session_delete.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. // Copyright 2016 The Xorm Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package xorm
  5. import (
  6. "errors"
  7. "fmt"
  8. "strconv"
  9. "github.com/go-xorm/core"
  10. )
  11. func (session *Session) cacheDelete(sqlStr string, args ...interface{}) error {
  12. if session.Statement.RefTable == nil ||
  13. session.Tx != nil {
  14. return ErrCacheFailed
  15. }
  16. for _, filter := range session.Engine.dialect.Filters() {
  17. sqlStr = filter.Do(sqlStr, session.Engine.dialect, session.Statement.RefTable)
  18. }
  19. newsql := session.Statement.convertIDSQL(sqlStr)
  20. if newsql == "" {
  21. return ErrCacheFailed
  22. }
  23. cacher := session.Engine.getCacher2(session.Statement.RefTable)
  24. tableName := session.Statement.TableName()
  25. ids, err := core.GetCacheSql(cacher, tableName, newsql, args)
  26. if err != nil {
  27. resultsSlice, err := session.query(newsql, args...)
  28. if err != nil {
  29. return err
  30. }
  31. ids = make([]core.PK, 0)
  32. if len(resultsSlice) > 0 {
  33. for _, data := range resultsSlice {
  34. var id int64
  35. var pk core.PK = make([]interface{}, 0)
  36. for _, col := range session.Statement.RefTable.PKColumns() {
  37. if v, ok := data[col.Name]; !ok {
  38. return errors.New("no id")
  39. } else if col.SQLType.IsText() {
  40. pk = append(pk, string(v))
  41. } else if col.SQLType.IsNumeric() {
  42. id, err = strconv.ParseInt(string(v), 10, 64)
  43. if err != nil {
  44. return err
  45. }
  46. pk = append(pk, id)
  47. } else {
  48. return errors.New("not supported primary key type")
  49. }
  50. }
  51. ids = append(ids, pk)
  52. }
  53. }
  54. } /*else {
  55. session.Engine.LogDebug("delete cache sql %v", newsql)
  56. cacher.DelIds(tableName, genSqlKey(newsql, args))
  57. }*/
  58. for _, id := range ids {
  59. session.Engine.logger.Debug("[cacheDelete] delete cache obj", tableName, id)
  60. sid, err := id.ToString()
  61. if err != nil {
  62. return err
  63. }
  64. cacher.DelBean(tableName, sid)
  65. }
  66. session.Engine.logger.Debug("[cacheDelete] clear cache sql", tableName)
  67. cacher.ClearIds(tableName)
  68. return nil
  69. }
  70. // Delete records, bean's non-empty fields are conditions
  71. func (session *Session) Delete(bean interface{}) (int64, error) {
  72. defer session.resetStatement()
  73. if session.IsAutoClose {
  74. defer session.Close()
  75. }
  76. session.Statement.setRefValue(rValue(bean))
  77. var table = session.Statement.RefTable
  78. // handle before delete processors
  79. for _, closure := range session.beforeClosures {
  80. closure(bean)
  81. }
  82. cleanupProcessorsClosures(&session.beforeClosures)
  83. if processor, ok := interface{}(bean).(BeforeDeleteProcessor); ok {
  84. processor.BeforeDelete()
  85. }
  86. // --
  87. condSQL, condArgs, _ := session.Statement.genConds(bean)
  88. if len(condSQL) == 0 && session.Statement.LimitN == 0 {
  89. return 0, ErrNeedDeletedCond
  90. }
  91. var tableName = session.Engine.Quote(session.Statement.TableName())
  92. var deleteSQL string
  93. if len(condSQL) > 0 {
  94. deleteSQL = fmt.Sprintf("DELETE FROM %v WHERE %v", tableName, condSQL)
  95. } else {
  96. deleteSQL = fmt.Sprintf("DELETE FROM %v", tableName)
  97. }
  98. var orderSQL string
  99. if len(session.Statement.OrderStr) > 0 {
  100. orderSQL += fmt.Sprintf(" ORDER BY %s", session.Statement.OrderStr)
  101. }
  102. if session.Statement.LimitN > 0 {
  103. orderSQL += fmt.Sprintf(" LIMIT %d", session.Statement.LimitN)
  104. }
  105. if len(orderSQL) > 0 {
  106. switch session.Engine.dialect.DBType() {
  107. case core.POSTGRES:
  108. inSQL := fmt.Sprintf("ctid IN (SELECT ctid FROM %s%s)", tableName, orderSQL)
  109. if len(condSQL) > 0 {
  110. deleteSQL += " AND " + inSQL
  111. } else {
  112. deleteSQL += " WHERE " + inSQL
  113. }
  114. case core.SQLITE:
  115. inSQL := fmt.Sprintf("rowid IN (SELECT rowid FROM %s%s)", tableName, orderSQL)
  116. if len(condSQL) > 0 {
  117. deleteSQL += " AND " + inSQL
  118. } else {
  119. deleteSQL += " WHERE " + inSQL
  120. }
  121. // TODO: how to handle delete limit on mssql?
  122. case core.MSSQL:
  123. return 0, ErrNotImplemented
  124. default:
  125. deleteSQL += orderSQL
  126. }
  127. }
  128. var realSQL string
  129. argsForCache := make([]interface{}, 0, len(condArgs)*2)
  130. if session.Statement.unscoped || table.DeletedColumn() == nil { // tag "deleted" is disabled
  131. realSQL = deleteSQL
  132. copy(argsForCache, condArgs)
  133. argsForCache = append(condArgs, argsForCache...)
  134. } else {
  135. // !oinume! sqlStrForCache and argsForCache is needed to behave as executing "DELETE FROM ..." for cache.
  136. copy(argsForCache, condArgs)
  137. argsForCache = append(condArgs, argsForCache...)
  138. deletedColumn := table.DeletedColumn()
  139. realSQL = fmt.Sprintf("UPDATE %v SET %v = ? WHERE %v",
  140. session.Engine.Quote(session.Statement.TableName()),
  141. session.Engine.Quote(deletedColumn.Name),
  142. condSQL)
  143. if len(orderSQL) > 0 {
  144. switch session.Engine.dialect.DBType() {
  145. case core.POSTGRES:
  146. inSQL := fmt.Sprintf("ctid IN (SELECT ctid FROM %s%s)", tableName, orderSQL)
  147. if len(condSQL) > 0 {
  148. realSQL += " AND " + inSQL
  149. } else {
  150. realSQL += " WHERE " + inSQL
  151. }
  152. case core.SQLITE:
  153. inSQL := fmt.Sprintf("rowid IN (SELECT rowid FROM %s%s)", tableName, orderSQL)
  154. if len(condSQL) > 0 {
  155. realSQL += " AND " + inSQL
  156. } else {
  157. realSQL += " WHERE " + inSQL
  158. }
  159. // TODO: how to handle delete limit on mssql?
  160. case core.MSSQL:
  161. return 0, ErrNotImplemented
  162. default:
  163. realSQL += orderSQL
  164. }
  165. }
  166. // !oinume! Insert NowTime to the head of session.Statement.Params
  167. condArgs = append(condArgs, "")
  168. paramsLen := len(condArgs)
  169. copy(condArgs[1:paramsLen], condArgs[0:paramsLen-1])
  170. val, t := session.Engine.NowTime2(deletedColumn.SQLType.Name)
  171. condArgs[0] = val
  172. var colName = deletedColumn.Name
  173. session.afterClosures = append(session.afterClosures, func(bean interface{}) {
  174. col := table.GetColumn(colName)
  175. setColumnTime(bean, col, t)
  176. })
  177. }
  178. if cacher := session.Engine.getCacher2(session.Statement.RefTable); cacher != nil && session.Statement.UseCache {
  179. session.cacheDelete(deleteSQL, argsForCache...)
  180. }
  181. res, err := session.exec(realSQL, condArgs...)
  182. if err != nil {
  183. return 0, err
  184. }
  185. // handle after delete processors
  186. if session.IsAutoCommit {
  187. for _, closure := range session.afterClosures {
  188. closure(bean)
  189. }
  190. if processor, ok := interface{}(bean).(AfterDeleteProcessor); ok {
  191. processor.AfterDelete()
  192. }
  193. } else {
  194. lenAfterClosures := len(session.afterClosures)
  195. if lenAfterClosures > 0 {
  196. if value, has := session.afterDeleteBeans[bean]; has && value != nil {
  197. *value = append(*value, session.afterClosures...)
  198. } else {
  199. afterClosures := make([]func(interface{}), lenAfterClosures)
  200. copy(afterClosures, session.afterClosures)
  201. session.afterDeleteBeans[bean] = &afterClosures
  202. }
  203. } else {
  204. if _, ok := interface{}(bean).(AfterDeleteProcessor); ok {
  205. session.afterDeleteBeans[bean] = nil
  206. }
  207. }
  208. }
  209. cleanupProcessorsClosures(&session.afterClosures)
  210. // --
  211. return res.RowsAffected()
  212. }