You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

240 lines
6.5 KiB

  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(table *core.Table, tableName, sqlStr string, args ...interface{}) error {
  12. if table == 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, table)
  18. }
  19. newsql := session.statement.convertIDSQL(sqlStr)
  20. if newsql == "" {
  21. return ErrCacheFailed
  22. }
  23. cacher := session.engine.getCacher2(table)
  24. pkColumns := table.PKColumns()
  25. ids, err := core.GetCacheSql(cacher, tableName, newsql, args)
  26. if err != nil {
  27. resultsSlice, err := session.queryBytes(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 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. }
  55. for _, id := range ids {
  56. session.engine.logger.Debug("[cacheDelete] delete cache obj:", tableName, id)
  57. sid, err := id.ToString()
  58. if err != nil {
  59. return err
  60. }
  61. cacher.DelBean(tableName, sid)
  62. }
  63. session.engine.logger.Debug("[cacheDelete] clear cache table:", tableName)
  64. cacher.ClearIds(tableName)
  65. return nil
  66. }
  67. // Delete records, bean's non-empty fields are conditions
  68. func (session *Session) Delete(bean interface{}) (int64, error) {
  69. if session.isAutoClose {
  70. defer session.Close()
  71. }
  72. if err := session.statement.setRefValue(rValue(bean)); err != nil {
  73. return 0, err
  74. }
  75. // handle before delete processors
  76. for _, closure := range session.beforeClosures {
  77. closure(bean)
  78. }
  79. cleanupProcessorsClosures(&session.beforeClosures)
  80. if processor, ok := interface{}(bean).(BeforeDeleteProcessor); ok {
  81. processor.BeforeDelete()
  82. }
  83. condSQL, condArgs, err := session.statement.genConds(bean)
  84. if err != nil {
  85. return 0, err
  86. }
  87. if len(condSQL) == 0 && session.statement.LimitN == 0 {
  88. return 0, ErrNeedDeletedCond
  89. }
  90. var tableNameNoQuote = session.statement.TableName()
  91. var tableName = session.engine.Quote(tableNameNoQuote)
  92. var table = session.statement.RefTable
  93. var deleteSQL string
  94. if len(condSQL) > 0 {
  95. deleteSQL = fmt.Sprintf("DELETE FROM %v WHERE %v", tableName, condSQL)
  96. } else {
  97. deleteSQL = fmt.Sprintf("DELETE FROM %v", tableName)
  98. }
  99. var orderSQL string
  100. if len(session.statement.OrderStr) > 0 {
  101. orderSQL += fmt.Sprintf(" ORDER BY %s", session.statement.OrderStr)
  102. }
  103. if session.statement.LimitN > 0 {
  104. orderSQL += fmt.Sprintf(" LIMIT %d", session.statement.LimitN)
  105. }
  106. if len(orderSQL) > 0 {
  107. switch session.engine.dialect.DBType() {
  108. case core.POSTGRES:
  109. inSQL := fmt.Sprintf("ctid IN (SELECT ctid FROM %s%s)", tableName, orderSQL)
  110. if len(condSQL) > 0 {
  111. deleteSQL += " AND " + inSQL
  112. } else {
  113. deleteSQL += " WHERE " + inSQL
  114. }
  115. case core.SQLITE:
  116. inSQL := fmt.Sprintf("rowid IN (SELECT rowid FROM %s%s)", tableName, orderSQL)
  117. if len(condSQL) > 0 {
  118. deleteSQL += " AND " + inSQL
  119. } else {
  120. deleteSQL += " WHERE " + inSQL
  121. }
  122. // TODO: how to handle delete limit on mssql?
  123. case core.MSSQL:
  124. return 0, ErrNotImplemented
  125. default:
  126. deleteSQL += orderSQL
  127. }
  128. }
  129. var realSQL string
  130. argsForCache := make([]interface{}, 0, len(condArgs)*2)
  131. if session.statement.unscoped || table.DeletedColumn() == nil { // tag "deleted" is disabled
  132. realSQL = deleteSQL
  133. copy(argsForCache, condArgs)
  134. argsForCache = append(condArgs, argsForCache...)
  135. } else {
  136. // !oinume! sqlStrForCache and argsForCache is needed to behave as executing "DELETE FROM ..." for cache.
  137. copy(argsForCache, condArgs)
  138. argsForCache = append(condArgs, argsForCache...)
  139. deletedColumn := table.DeletedColumn()
  140. realSQL = fmt.Sprintf("UPDATE %v SET %v = ? WHERE %v",
  141. session.engine.Quote(session.statement.TableName()),
  142. session.engine.Quote(deletedColumn.Name),
  143. condSQL)
  144. if len(orderSQL) > 0 {
  145. switch session.engine.dialect.DBType() {
  146. case core.POSTGRES:
  147. inSQL := fmt.Sprintf("ctid IN (SELECT ctid FROM %s%s)", tableName, orderSQL)
  148. if len(condSQL) > 0 {
  149. realSQL += " AND " + inSQL
  150. } else {
  151. realSQL += " WHERE " + inSQL
  152. }
  153. case core.SQLITE:
  154. inSQL := fmt.Sprintf("rowid IN (SELECT rowid FROM %s%s)", tableName, orderSQL)
  155. if len(condSQL) > 0 {
  156. realSQL += " AND " + inSQL
  157. } else {
  158. realSQL += " WHERE " + inSQL
  159. }
  160. // TODO: how to handle delete limit on mssql?
  161. case core.MSSQL:
  162. return 0, ErrNotImplemented
  163. default:
  164. realSQL += orderSQL
  165. }
  166. }
  167. // !oinume! Insert nowTime to the head of session.statement.Params
  168. condArgs = append(condArgs, "")
  169. paramsLen := len(condArgs)
  170. copy(condArgs[1:paramsLen], condArgs[0:paramsLen-1])
  171. val, t := session.engine.nowTime(deletedColumn)
  172. condArgs[0] = val
  173. var colName = deletedColumn.Name
  174. session.afterClosures = append(session.afterClosures, func(bean interface{}) {
  175. col := table.GetColumn(colName)
  176. setColumnTime(bean, col, t)
  177. })
  178. }
  179. if cacher := session.engine.getCacher2(table); cacher != nil && session.statement.UseCache {
  180. session.cacheDelete(table, tableNameNoQuote, deleteSQL, argsForCache...)
  181. }
  182. session.statement.RefTable = table
  183. res, err := session.exec(realSQL, condArgs...)
  184. if err != nil {
  185. return 0, err
  186. }
  187. // handle after delete processors
  188. if session.isAutoCommit {
  189. for _, closure := range session.afterClosures {
  190. closure(bean)
  191. }
  192. if processor, ok := interface{}(bean).(AfterDeleteProcessor); ok {
  193. processor.AfterDelete()
  194. }
  195. } else {
  196. lenAfterClosures := len(session.afterClosures)
  197. if lenAfterClosures > 0 {
  198. if value, has := session.afterDeleteBeans[bean]; has && value != nil {
  199. *value = append(*value, session.afterClosures...)
  200. } else {
  201. afterClosures := make([]func(interface{}), lenAfterClosures)
  202. copy(afterClosures, session.afterClosures)
  203. session.afterDeleteBeans[bean] = &afterClosures
  204. }
  205. } else {
  206. if _, ok := interface{}(bean).(AfterDeleteProcessor); ok {
  207. session.afterDeleteBeans[bean] = nil
  208. }
  209. }
  210. }
  211. cleanupProcessorsClosures(&session.afterClosures)
  212. // --
  213. return res.RowsAffected()
  214. }