Simple and Powerful ORM for Go, support mysql,postgres,tidb,sqlite3,mssql,oracle https://xorm.io
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 

252 lignes
6.8 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. "xorm.io/xorm/caches"
  10. "xorm.io/xorm/schemas"
  11. )
  12. var (
  13. // ErrNeedDeletedCond delete needs less one condition error
  14. ErrNeedDeletedCond = errors.New("Delete action needs at least one condition")
  15. // ErrNotImplemented not implemented
  16. ErrNotImplemented = errors.New("Not implemented")
  17. )
  18. func (session *Session) cacheDelete(table *schemas.Table, tableName, sqlStr string, args ...interface{}) error {
  19. if table == nil ||
  20. session.tx != nil {
  21. return ErrCacheFailed
  22. }
  23. for _, filter := range session.engine.dialect.Filters() {
  24. sqlStr = filter.Do(sqlStr)
  25. }
  26. newsql := session.statement.ConvertIDSQL(sqlStr)
  27. if newsql == "" {
  28. return ErrCacheFailed
  29. }
  30. cacher := session.engine.cacherMgr.GetCacher(tableName)
  31. pkColumns := table.PKColumns()
  32. ids, err := caches.GetCacheSql(cacher, tableName, newsql, args)
  33. if err != nil {
  34. resultsSlice, err := session.queryBytes(newsql, args...)
  35. if err != nil {
  36. return err
  37. }
  38. ids = make([]schemas.PK, 0)
  39. if len(resultsSlice) > 0 {
  40. for _, data := range resultsSlice {
  41. var id int64
  42. var pk schemas.PK = make([]interface{}, 0)
  43. for _, col := range pkColumns {
  44. if v, ok := data[col.Name]; !ok {
  45. return errors.New("no id")
  46. } else if col.SQLType.IsText() {
  47. pk = append(pk, string(v))
  48. } else if col.SQLType.IsNumeric() {
  49. id, err = strconv.ParseInt(string(v), 10, 64)
  50. if err != nil {
  51. return err
  52. }
  53. pk = append(pk, id)
  54. } else {
  55. return errors.New("not supported primary key type")
  56. }
  57. }
  58. ids = append(ids, pk)
  59. }
  60. }
  61. }
  62. for _, id := range ids {
  63. session.engine.logger.Debugf("[cache] delete cache obj: %v, %v", tableName, id)
  64. sid, err := id.ToString()
  65. if err != nil {
  66. return err
  67. }
  68. cacher.DelBean(tableName, sid)
  69. }
  70. session.engine.logger.Debugf("[cache] clear cache table: %v", tableName)
  71. cacher.ClearIds(tableName)
  72. return nil
  73. }
  74. // Delete records, bean's non-empty fields are conditions
  75. func (session *Session) Delete(bean interface{}) (int64, error) {
  76. if session.isAutoClose {
  77. defer session.Close()
  78. }
  79. if session.statement.LastError != nil {
  80. return 0, session.statement.LastError
  81. }
  82. if err := session.statement.SetRefBean(bean); err != nil {
  83. return 0, err
  84. }
  85. executeBeforeClosures(session, bean)
  86. if processor, ok := interface{}(bean).(BeforeDeleteProcessor); ok {
  87. processor.BeforeDelete()
  88. }
  89. condSQL, condArgs, err := session.statement.GenConds(bean)
  90. if err != nil {
  91. return 0, err
  92. }
  93. pLimitN := session.statement.LimitN
  94. if len(condSQL) == 0 && (pLimitN == nil || *pLimitN == 0) {
  95. return 0, ErrNeedDeletedCond
  96. }
  97. var tableNameNoQuote = session.statement.TableName()
  98. var tableName = session.engine.Quote(tableNameNoQuote)
  99. var table = session.statement.RefTable
  100. var deleteSQL string
  101. if len(condSQL) > 0 {
  102. deleteSQL = fmt.Sprintf("DELETE FROM %v WHERE %v", tableName, condSQL)
  103. } else {
  104. deleteSQL = fmt.Sprintf("DELETE FROM %v", tableName)
  105. }
  106. var orderSQL string
  107. if len(session.statement.OrderStr) > 0 {
  108. orderSQL += fmt.Sprintf(" ORDER BY %s", session.statement.OrderStr)
  109. }
  110. if pLimitN != nil && *pLimitN > 0 {
  111. limitNValue := *pLimitN
  112. orderSQL += fmt.Sprintf(" LIMIT %d", limitNValue)
  113. }
  114. if len(orderSQL) > 0 {
  115. switch session.engine.dialect.URI().DBType {
  116. case schemas.POSTGRES:
  117. inSQL := fmt.Sprintf("ctid IN (SELECT ctid FROM %s%s)", tableName, orderSQL)
  118. if len(condSQL) > 0 {
  119. deleteSQL += " AND " + inSQL
  120. } else {
  121. deleteSQL += " WHERE " + inSQL
  122. }
  123. case schemas.SQLITE:
  124. inSQL := fmt.Sprintf("rowid IN (SELECT rowid FROM %s%s)", tableName, orderSQL)
  125. if len(condSQL) > 0 {
  126. deleteSQL += " AND " + inSQL
  127. } else {
  128. deleteSQL += " WHERE " + inSQL
  129. }
  130. // TODO: how to handle delete limit on mssql?
  131. case schemas.MSSQL:
  132. return 0, ErrNotImplemented
  133. default:
  134. deleteSQL += orderSQL
  135. }
  136. }
  137. var realSQL string
  138. argsForCache := make([]interface{}, 0, len(condArgs)*2)
  139. if session.statement.GetUnscoped() || table.DeletedColumn() == nil { // tag "deleted" is disabled
  140. realSQL = deleteSQL
  141. copy(argsForCache, condArgs)
  142. argsForCache = append(condArgs, argsForCache...)
  143. } else {
  144. // !oinume! sqlStrForCache and argsForCache is needed to behave as executing "DELETE FROM ..." for caches.
  145. copy(argsForCache, condArgs)
  146. argsForCache = append(condArgs, argsForCache...)
  147. deletedColumn := table.DeletedColumn()
  148. realSQL = fmt.Sprintf("UPDATE %v SET %v = ? WHERE %v",
  149. session.engine.Quote(session.statement.TableName()),
  150. session.engine.Quote(deletedColumn.Name),
  151. condSQL)
  152. if len(orderSQL) > 0 {
  153. switch session.engine.dialect.URI().DBType {
  154. case schemas.POSTGRES:
  155. inSQL := fmt.Sprintf("ctid IN (SELECT ctid FROM %s%s)", tableName, orderSQL)
  156. if len(condSQL) > 0 {
  157. realSQL += " AND " + inSQL
  158. } else {
  159. realSQL += " WHERE " + inSQL
  160. }
  161. case schemas.SQLITE:
  162. inSQL := fmt.Sprintf("rowid IN (SELECT rowid FROM %s%s)", tableName, orderSQL)
  163. if len(condSQL) > 0 {
  164. realSQL += " AND " + inSQL
  165. } else {
  166. realSQL += " WHERE " + inSQL
  167. }
  168. // TODO: how to handle delete limit on mssql?
  169. case schemas.MSSQL:
  170. return 0, ErrNotImplemented
  171. default:
  172. realSQL += orderSQL
  173. }
  174. }
  175. // !oinume! Insert nowTime to the head of session.statement.Params
  176. condArgs = append(condArgs, "")
  177. paramsLen := len(condArgs)
  178. copy(condArgs[1:paramsLen], condArgs[0:paramsLen-1])
  179. val, t := session.engine.nowTime(deletedColumn)
  180. condArgs[0] = val
  181. var colName = deletedColumn.Name
  182. session.afterClosures = append(session.afterClosures, func(bean interface{}) {
  183. col := table.GetColumn(colName)
  184. setColumnTime(bean, col, t)
  185. })
  186. }
  187. if cacher := session.engine.GetCacher(tableNameNoQuote); cacher != nil && session.statement.UseCache {
  188. session.cacheDelete(table, tableNameNoQuote, deleteSQL, argsForCache...)
  189. }
  190. session.statement.RefTable = table
  191. res, err := session.exec(realSQL, condArgs...)
  192. if err != nil {
  193. return 0, err
  194. }
  195. // handle after delete processors
  196. if session.isAutoCommit {
  197. for _, closure := range session.afterClosures {
  198. closure(bean)
  199. }
  200. if processor, ok := interface{}(bean).(AfterDeleteProcessor); ok {
  201. processor.AfterDelete()
  202. }
  203. } else {
  204. lenAfterClosures := len(session.afterClosures)
  205. if lenAfterClosures > 0 {
  206. if value, has := session.afterDeleteBeans[bean]; has && value != nil {
  207. *value = append(*value, session.afterClosures...)
  208. } else {
  209. afterClosures := make([]func(interface{}), lenAfterClosures)
  210. copy(afterClosures, session.afterClosures)
  211. session.afterDeleteBeans[bean] = &afterClosures
  212. }
  213. } else {
  214. if _, ok := interface{}(bean).(AfterDeleteProcessor); ok {
  215. session.afterDeleteBeans[bean] = nil
  216. }
  217. }
  218. }
  219. cleanupProcessorsClosures(&session.afterClosures)
  220. // --
  221. return res.RowsAffected()
  222. }