session_update.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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. "reflect"
  9. "strconv"
  10. "strings"
  11. "github.com/go-xorm/builder"
  12. "github.com/go-xorm/core"
  13. )
  14. func (session *Session) cacheUpdate(sqlStr string, args ...interface{}) error {
  15. if session.Statement.RefTable == nil ||
  16. session.Tx != nil {
  17. return ErrCacheFailed
  18. }
  19. oldhead, newsql := session.Statement.convertUpdateSQL(sqlStr)
  20. if newsql == "" {
  21. return ErrCacheFailed
  22. }
  23. for _, filter := range session.Engine.dialect.Filters() {
  24. newsql = filter.Do(newsql, session.Engine.dialect, session.Statement.RefTable)
  25. }
  26. session.Engine.logger.Debug("[cacheUpdate] new sql", oldhead, newsql)
  27. var nStart int
  28. if len(args) > 0 {
  29. if strings.Index(sqlStr, "?") > -1 {
  30. nStart = strings.Count(oldhead, "?")
  31. } else {
  32. // only for pq, TODO: if any other databse?
  33. nStart = strings.Count(oldhead, "$")
  34. }
  35. }
  36. table := session.Statement.RefTable
  37. cacher := session.Engine.getCacher2(table)
  38. tableName := session.Statement.TableName()
  39. session.Engine.logger.Debug("[cacheUpdate] get cache sql", newsql, args[nStart:])
  40. ids, err := core.GetCacheSql(cacher, tableName, newsql, args[nStart:])
  41. if err != nil {
  42. rows, err := session.DB().Query(newsql, args[nStart:]...)
  43. if err != nil {
  44. return err
  45. }
  46. defer rows.Close()
  47. ids = make([]core.PK, 0)
  48. for rows.Next() {
  49. var res = make([]string, len(table.PrimaryKeys))
  50. err = rows.ScanSlice(&res)
  51. if err != nil {
  52. return err
  53. }
  54. var pk core.PK = make([]interface{}, len(table.PrimaryKeys))
  55. for i, col := range table.PKColumns() {
  56. if col.SQLType.IsNumeric() {
  57. n, err := strconv.ParseInt(res[i], 10, 64)
  58. if err != nil {
  59. return err
  60. }
  61. pk[i] = n
  62. } else if col.SQLType.IsText() {
  63. pk[i] = res[i]
  64. } else {
  65. return errors.New("not supported")
  66. }
  67. }
  68. ids = append(ids, pk)
  69. }
  70. session.Engine.logger.Debug("[cacheUpdate] find updated id", ids)
  71. } /*else {
  72. session.Engine.LogDebug("[xorm:cacheUpdate] del cached sql:", tableName, newsql, args)
  73. cacher.DelIds(tableName, genSqlKey(newsql, args))
  74. }*/
  75. for _, id := range ids {
  76. sid, err := id.ToString()
  77. if err != nil {
  78. return err
  79. }
  80. if bean := cacher.GetBean(tableName, sid); bean != nil {
  81. sqls := splitNNoCase(sqlStr, "where", 2)
  82. if len(sqls) == 0 || len(sqls) > 2 {
  83. return ErrCacheFailed
  84. }
  85. sqls = splitNNoCase(sqls[0], "set", 2)
  86. if len(sqls) != 2 {
  87. return ErrCacheFailed
  88. }
  89. kvs := strings.Split(strings.TrimSpace(sqls[1]), ",")
  90. for idx, kv := range kvs {
  91. sps := strings.SplitN(kv, "=", 2)
  92. sps2 := strings.Split(sps[0], ".")
  93. colName := sps2[len(sps2)-1]
  94. if strings.Contains(colName, "`") {
  95. colName = strings.TrimSpace(strings.Replace(colName, "`", "", -1))
  96. } else if strings.Contains(colName, session.Engine.QuoteStr()) {
  97. colName = strings.TrimSpace(strings.Replace(colName, session.Engine.QuoteStr(), "", -1))
  98. } else {
  99. session.Engine.logger.Debug("[cacheUpdate] cannot find column", tableName, colName)
  100. return ErrCacheFailed
  101. }
  102. if col := table.GetColumn(colName); col != nil {
  103. fieldValue, err := col.ValueOf(bean)
  104. if err != nil {
  105. session.Engine.logger.Error(err)
  106. } else {
  107. session.Engine.logger.Debug("[cacheUpdate] set bean field", bean, colName, fieldValue.Interface())
  108. if col.IsVersion && session.Statement.checkVersion {
  109. fieldValue.SetInt(fieldValue.Int() + 1)
  110. } else {
  111. fieldValue.Set(reflect.ValueOf(args[idx]))
  112. }
  113. }
  114. } else {
  115. session.Engine.logger.Errorf("[cacheUpdate] ERROR: column %v is not table %v's",
  116. colName, table.Name)
  117. }
  118. }
  119. session.Engine.logger.Debug("[cacheUpdate] update cache", tableName, id, bean)
  120. cacher.PutBean(tableName, sid, bean)
  121. }
  122. }
  123. session.Engine.logger.Debug("[cacheUpdate] clear cached table sql:", tableName)
  124. cacher.ClearIds(tableName)
  125. return nil
  126. }
  127. // Update records, bean's non-empty fields are updated contents,
  128. // condiBean' non-empty filds are conditions
  129. // CAUTION:
  130. // 1.bool will defaultly be updated content nor conditions
  131. // You should call UseBool if you have bool to use.
  132. // 2.float32 & float64 may be not inexact as conditions
  133. func (session *Session) Update(bean interface{}, condiBean ...interface{}) (int64, error) {
  134. defer session.resetStatement()
  135. if session.IsAutoClose {
  136. defer session.Close()
  137. }
  138. v := rValue(bean)
  139. t := v.Type()
  140. var colNames []string
  141. var args []interface{}
  142. // handle before update processors
  143. for _, closure := range session.beforeClosures {
  144. closure(bean)
  145. }
  146. cleanupProcessorsClosures(&session.beforeClosures) // cleanup after used
  147. if processor, ok := interface{}(bean).(BeforeUpdateProcessor); ok {
  148. processor.BeforeUpdate()
  149. }
  150. // --
  151. var err error
  152. var isMap = t.Kind() == reflect.Map
  153. var isStruct = t.Kind() == reflect.Struct
  154. if isStruct {
  155. session.Statement.setRefValue(v)
  156. if len(session.Statement.TableName()) <= 0 {
  157. return 0, ErrTableNotFound
  158. }
  159. if session.Statement.ColumnStr == "" {
  160. colNames, args = buildUpdates(session.Engine, session.Statement.RefTable, bean, false, false,
  161. false, false, session.Statement.allUseBool, session.Statement.useAllCols,
  162. session.Statement.mustColumnMap, session.Statement.nullableMap,
  163. session.Statement.columnMap, true, session.Statement.unscoped)
  164. } else {
  165. colNames, args, err = genCols(session.Statement.RefTable, session, bean, true, true)
  166. if err != nil {
  167. return 0, err
  168. }
  169. }
  170. } else if isMap {
  171. colNames = make([]string, 0)
  172. args = make([]interface{}, 0)
  173. bValue := reflect.Indirect(reflect.ValueOf(bean))
  174. for _, v := range bValue.MapKeys() {
  175. colNames = append(colNames, session.Engine.Quote(v.String())+" = ?")
  176. args = append(args, bValue.MapIndex(v).Interface())
  177. }
  178. } else {
  179. return 0, ErrParamsType
  180. }
  181. table := session.Statement.RefTable
  182. if session.Statement.UseAutoTime && table != nil && table.Updated != "" {
  183. colNames = append(colNames, session.Engine.Quote(table.Updated)+" = ?")
  184. col := table.UpdatedColumn()
  185. val, t := session.Engine.NowTime2(col.SQLType.Name)
  186. args = append(args, val)
  187. var colName = col.Name
  188. if isStruct {
  189. session.afterClosures = append(session.afterClosures, func(bean interface{}) {
  190. col := table.GetColumn(colName)
  191. setColumnTime(bean, col, t)
  192. })
  193. }
  194. }
  195. //for update action to like "column = column + ?"
  196. incColumns := session.Statement.getInc()
  197. for _, v := range incColumns {
  198. colNames = append(colNames, session.Engine.Quote(v.colName)+" = "+session.Engine.Quote(v.colName)+" + ?")
  199. args = append(args, v.arg)
  200. }
  201. //for update action to like "column = column - ?"
  202. decColumns := session.Statement.getDec()
  203. for _, v := range decColumns {
  204. colNames = append(colNames, session.Engine.Quote(v.colName)+" = "+session.Engine.Quote(v.colName)+" - ?")
  205. args = append(args, v.arg)
  206. }
  207. //for update action to like "column = expression"
  208. exprColumns := session.Statement.getExpr()
  209. for _, v := range exprColumns {
  210. colNames = append(colNames, session.Engine.Quote(v.colName)+" = "+v.expr)
  211. }
  212. session.Statement.processIDParam()
  213. var autoCond builder.Cond
  214. if !session.Statement.noAutoCondition && len(condiBean) > 0 {
  215. var err error
  216. autoCond, err = session.Statement.buildConds(session.Statement.RefTable, condiBean[0], true, true, false, true, false)
  217. if err != nil {
  218. return 0, err
  219. }
  220. }
  221. st := session.Statement
  222. defer session.resetStatement()
  223. var sqlStr string
  224. var condArgs []interface{}
  225. var condSQL string
  226. cond := session.Statement.cond.And(autoCond)
  227. doIncVer := false
  228. var verValue *reflect.Value
  229. if table != nil && table.Version != "" && session.Statement.checkVersion {
  230. verValue, err = table.VersionColumn().ValueOf(bean)
  231. if err != nil {
  232. return 0, err
  233. }
  234. cond = cond.And(builder.Eq{session.Engine.Quote(table.Version): verValue.Interface()})
  235. condSQL, condArgs, _ = builder.ToSQL(cond)
  236. if len(condSQL) > 0 {
  237. condSQL = "WHERE " + condSQL
  238. }
  239. if st.LimitN > 0 {
  240. condSQL = condSQL + fmt.Sprintf(" LIMIT %d", st.LimitN)
  241. }
  242. sqlStr = fmt.Sprintf("UPDATE %v SET %v, %v %v",
  243. session.Engine.Quote(session.Statement.TableName()),
  244. strings.Join(colNames, ", "),
  245. session.Engine.Quote(table.Version)+" = "+session.Engine.Quote(table.Version)+" + 1",
  246. condSQL)
  247. doIncVer = true
  248. } else {
  249. condSQL, condArgs, _ = builder.ToSQL(cond)
  250. if len(condSQL) > 0 {
  251. condSQL = "WHERE " + condSQL
  252. }
  253. if st.LimitN > 0 {
  254. condSQL = condSQL + fmt.Sprintf(" LIMIT %d", st.LimitN)
  255. }
  256. sqlStr = fmt.Sprintf("UPDATE %v SET %v %v",
  257. session.Engine.Quote(session.Statement.TableName()),
  258. strings.Join(colNames, ", "),
  259. condSQL)
  260. }
  261. res, err := session.exec(sqlStr, append(args, condArgs...)...)
  262. if err != nil {
  263. return 0, err
  264. } else if doIncVer {
  265. if verValue != nil && verValue.IsValid() && verValue.CanSet() {
  266. verValue.SetInt(verValue.Int() + 1)
  267. }
  268. }
  269. if table != nil {
  270. if cacher := session.Engine.getCacher2(table); cacher != nil && session.Statement.UseCache {
  271. cacher.ClearIds(session.Statement.TableName())
  272. cacher.ClearBeans(session.Statement.TableName())
  273. }
  274. }
  275. // handle after update processors
  276. if session.IsAutoCommit {
  277. for _, closure := range session.afterClosures {
  278. closure(bean)
  279. }
  280. if processor, ok := interface{}(bean).(AfterUpdateProcessor); ok {
  281. session.Engine.logger.Debug("[event]", session.Statement.TableName(), " has after update processor")
  282. processor.AfterUpdate()
  283. }
  284. } else {
  285. lenAfterClosures := len(session.afterClosures)
  286. if lenAfterClosures > 0 {
  287. if value, has := session.afterUpdateBeans[bean]; has && value != nil {
  288. *value = append(*value, session.afterClosures...)
  289. } else {
  290. afterClosures := make([]func(interface{}), lenAfterClosures)
  291. copy(afterClosures, session.afterClosures)
  292. // FIXME: if bean is a map type, it will panic because map cannot be as map key
  293. session.afterUpdateBeans[bean] = &afterClosures
  294. }
  295. } else {
  296. if _, ok := interface{}(bean).(AfterUpdateProcessor); ok {
  297. session.afterUpdateBeans[bean] = nil
  298. }
  299. }
  300. }
  301. cleanupProcessorsClosures(&session.afterClosures) // cleanup after used
  302. // --
  303. return res.RowsAffected()
  304. }