本站源代码
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.

245 lines
6.6KB

  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. "xorm.io/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.getCacher(tableName)
  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 session.statement.lastError != nil {
  73. return 0, session.statement.lastError
  74. }
  75. if err := session.statement.setRefBean(bean); err != nil {
  76. return 0, err
  77. }
  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. condSQL, condArgs, err := session.statement.genConds(bean)
  87. if err != nil {
  88. return 0, err
  89. }
  90. if len(condSQL) == 0 && session.statement.LimitN == 0 {
  91. return 0, ErrNeedDeletedCond
  92. }
  93. var tableNameNoQuote = session.statement.TableName()
  94. var tableName = session.engine.Quote(tableNameNoQuote)
  95. var table = session.statement.RefTable
  96. var deleteSQL string
  97. if len(condSQL) > 0 {
  98. deleteSQL = fmt.Sprintf("DELETE FROM %v WHERE %v", tableName, condSQL)
  99. } else {
  100. deleteSQL = fmt.Sprintf("DELETE FROM %v", tableName)
  101. }
  102. var orderSQL string
  103. if len(session.statement.OrderStr) > 0 {
  104. orderSQL += fmt.Sprintf(" ORDER BY %s", session.statement.OrderStr)
  105. }
  106. if session.statement.LimitN > 0 {
  107. orderSQL += fmt.Sprintf(" LIMIT %d", session.statement.LimitN)
  108. }
  109. if len(orderSQL) > 0 {
  110. switch session.engine.dialect.DBType() {
  111. case core.POSTGRES:
  112. inSQL := fmt.Sprintf("ctid IN (SELECT ctid FROM %s%s)", tableName, orderSQL)
  113. if len(condSQL) > 0 {
  114. deleteSQL += " AND " + inSQL
  115. } else {
  116. deleteSQL += " WHERE " + inSQL
  117. }
  118. case core.SQLITE:
  119. inSQL := fmt.Sprintf("rowid IN (SELECT rowid FROM %s%s)", tableName, orderSQL)
  120. if len(condSQL) > 0 {
  121. deleteSQL += " AND " + inSQL
  122. } else {
  123. deleteSQL += " WHERE " + inSQL
  124. }
  125. // TODO: how to handle delete limit on mssql?
  126. case core.MSSQL:
  127. return 0, ErrNotImplemented
  128. default:
  129. deleteSQL += orderSQL
  130. }
  131. }
  132. var realSQL string
  133. argsForCache := make([]interface{}, 0, len(condArgs)*2)
  134. if session.statement.unscoped || table.DeletedColumn() == nil { // tag "deleted" is disabled
  135. realSQL = deleteSQL
  136. copy(argsForCache, condArgs)
  137. argsForCache = append(condArgs, argsForCache...)
  138. } else {
  139. // !oinume! sqlStrForCache and argsForCache is needed to behave as executing "DELETE FROM ..." for cache.
  140. copy(argsForCache, condArgs)
  141. argsForCache = append(condArgs, argsForCache...)
  142. deletedColumn := table.DeletedColumn()
  143. realSQL = fmt.Sprintf("UPDATE %v SET %v = ? WHERE %v",
  144. session.engine.Quote(session.statement.TableName()),
  145. session.engine.Quote(deletedColumn.Name),
  146. condSQL)
  147. if len(orderSQL) > 0 {
  148. switch session.engine.dialect.DBType() {
  149. case core.POSTGRES:
  150. inSQL := fmt.Sprintf("ctid IN (SELECT ctid FROM %s%s)", tableName, orderSQL)
  151. if len(condSQL) > 0 {
  152. realSQL += " AND " + inSQL
  153. } else {
  154. realSQL += " WHERE " + inSQL
  155. }
  156. case core.SQLITE:
  157. inSQL := fmt.Sprintf("rowid IN (SELECT rowid FROM %s%s)", tableName, orderSQL)
  158. if len(condSQL) > 0 {
  159. realSQL += " AND " + inSQL
  160. } else {
  161. realSQL += " WHERE " + inSQL
  162. }
  163. // TODO: how to handle delete limit on mssql?
  164. case core.MSSQL:
  165. return 0, ErrNotImplemented
  166. default:
  167. realSQL += orderSQL
  168. }
  169. }
  170. // !oinume! Insert nowTime to the head of session.statement.Params
  171. condArgs = append(condArgs, "")
  172. paramsLen := len(condArgs)
  173. copy(condArgs[1:paramsLen], condArgs[0:paramsLen-1])
  174. val, t := session.engine.nowTime(deletedColumn)
  175. condArgs[0] = val
  176. var colName = deletedColumn.Name
  177. session.afterClosures = append(session.afterClosures, func(bean interface{}) {
  178. col := table.GetColumn(colName)
  179. setColumnTime(bean, col, t)
  180. })
  181. }
  182. if cacher := session.engine.getCacher(tableNameNoQuote); cacher != nil && session.statement.UseCache {
  183. session.cacheDelete(table, tableNameNoQuote, deleteSQL, argsForCache...)
  184. }
  185. session.statement.RefTable = table
  186. res, err := session.exec(realSQL, condArgs...)
  187. if err != nil {
  188. return 0, err
  189. }
  190. // handle after delete processors
  191. if session.isAutoCommit {
  192. for _, closure := range session.afterClosures {
  193. closure(bean)
  194. }
  195. if processor, ok := interface{}(bean).(AfterDeleteProcessor); ok {
  196. processor.AfterDelete()
  197. }
  198. } else {
  199. lenAfterClosures := len(session.afterClosures)
  200. if lenAfterClosures > 0 {
  201. if value, has := session.afterDeleteBeans[bean]; has && value != nil {
  202. *value = append(*value, session.afterClosures...)
  203. } else {
  204. afterClosures := make([]func(interface{}), lenAfterClosures)
  205. copy(afterClosures, session.afterClosures)
  206. session.afterDeleteBeans[bean] = &afterClosures
  207. }
  208. } else {
  209. if _, ok := interface{}(bean).(AfterDeleteProcessor); ok {
  210. session.afterDeleteBeans[bean] = nil
  211. }
  212. }
  213. }
  214. cleanupProcessorsClosures(&session.afterClosures)
  215. // --
  216. return res.RowsAffected()
  217. }
上海开阖软件有限公司 沪ICP备12045867号-1