session_update.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  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. if err := session.Statement.setRefValue(v); err != nil {
  156. return 0, err
  157. }
  158. if len(session.Statement.TableName()) <= 0 {
  159. return 0, ErrTableNotFound
  160. }
  161. if session.Statement.ColumnStr == "" {
  162. colNames, args = buildUpdates(session.Engine, session.Statement.RefTable, bean, false, false,
  163. false, false, session.Statement.allUseBool, session.Statement.useAllCols,
  164. session.Statement.mustColumnMap, session.Statement.nullableMap,
  165. session.Statement.columnMap, true, session.Statement.unscoped)
  166. } else {
  167. colNames, args, err = genCols(session.Statement.RefTable, session, bean, true, true)
  168. if err != nil {
  169. return 0, err
  170. }
  171. }
  172. } else if isMap {
  173. colNames = make([]string, 0)
  174. args = make([]interface{}, 0)
  175. bValue := reflect.Indirect(reflect.ValueOf(bean))
  176. for _, v := range bValue.MapKeys() {
  177. colNames = append(colNames, session.Engine.Quote(v.String())+" = ?")
  178. args = append(args, bValue.MapIndex(v).Interface())
  179. }
  180. } else {
  181. return 0, ErrParamsType
  182. }
  183. table := session.Statement.RefTable
  184. if session.Statement.UseAutoTime && table != nil && table.Updated != "" {
  185. colNames = append(colNames, session.Engine.Quote(table.Updated)+" = ?")
  186. col := table.UpdatedColumn()
  187. val, t := session.Engine.NowTime2(col.SQLType.Name)
  188. args = append(args, val)
  189. var colName = col.Name
  190. if isStruct {
  191. session.afterClosures = append(session.afterClosures, func(bean interface{}) {
  192. col := table.GetColumn(colName)
  193. setColumnTime(bean, col, t)
  194. })
  195. }
  196. }
  197. //for update action to like "column = column + ?"
  198. incColumns := session.Statement.getInc()
  199. for _, v := range incColumns {
  200. colNames = append(colNames, session.Engine.Quote(v.colName)+" = "+session.Engine.Quote(v.colName)+" + ?")
  201. args = append(args, v.arg)
  202. }
  203. //for update action to like "column = column - ?"
  204. decColumns := session.Statement.getDec()
  205. for _, v := range decColumns {
  206. colNames = append(colNames, session.Engine.Quote(v.colName)+" = "+session.Engine.Quote(v.colName)+" - ?")
  207. args = append(args, v.arg)
  208. }
  209. //for update action to like "column = expression"
  210. exprColumns := session.Statement.getExpr()
  211. for _, v := range exprColumns {
  212. colNames = append(colNames, session.Engine.Quote(v.colName)+" = "+v.expr)
  213. }
  214. session.Statement.processIDParam()
  215. var autoCond builder.Cond
  216. if !session.Statement.noAutoCondition && len(condiBean) > 0 {
  217. var err error
  218. autoCond, err = session.Statement.buildConds(session.Statement.RefTable, condiBean[0], true, true, false, true, false)
  219. if err != nil {
  220. return 0, err
  221. }
  222. }
  223. st := session.Statement
  224. defer session.resetStatement()
  225. var sqlStr string
  226. var condArgs []interface{}
  227. var condSQL string
  228. cond := session.Statement.cond.And(autoCond)
  229. var doIncVer = (table != nil && table.Version != "" && session.Statement.checkVersion)
  230. var verValue *reflect.Value
  231. if doIncVer {
  232. verValue, err = table.VersionColumn().ValueOf(bean)
  233. if err != nil {
  234. return 0, err
  235. }
  236. cond = cond.And(builder.Eq{session.Engine.Quote(table.Version): verValue.Interface()})
  237. colNames = append(colNames, session.Engine.Quote(table.Version)+" = "+session.Engine.Quote(table.Version)+" + 1")
  238. }
  239. condSQL, condArgs, _ = builder.ToSQL(cond)
  240. if len(condSQL) > 0 {
  241. condSQL = "WHERE " + condSQL
  242. }
  243. if st.OrderStr != "" {
  244. condSQL = condSQL + fmt.Sprintf(" ORDER BY %v", st.OrderStr)
  245. }
  246. // TODO: Oracle support needed
  247. var top string
  248. if st.LimitN > 0 {
  249. if st.Engine.dialect.DBType() == core.MYSQL {
  250. condSQL = condSQL + fmt.Sprintf(" LIMIT %d", st.LimitN)
  251. } else if st.Engine.dialect.DBType() == core.SQLITE {
  252. tempCondSQL := condSQL + fmt.Sprintf(" LIMIT %d", st.LimitN)
  253. cond = cond.And(builder.Expr(fmt.Sprintf("rowid IN (SELECT rowid FROM %v %v)",
  254. session.Engine.Quote(session.Statement.TableName()), tempCondSQL), condArgs...))
  255. condSQL, condArgs, _ = builder.ToSQL(cond)
  256. if len(condSQL) > 0 {
  257. condSQL = "WHERE " + condSQL
  258. }
  259. } else if st.Engine.dialect.DBType() == core.POSTGRES {
  260. tempCondSQL := condSQL + fmt.Sprintf(" LIMIT %d", st.LimitN)
  261. cond = cond.And(builder.Expr(fmt.Sprintf("CTID IN (SELECT CTID FROM %v %v)",
  262. session.Engine.Quote(session.Statement.TableName()), tempCondSQL), condArgs...))
  263. condSQL, condArgs, _ = builder.ToSQL(cond)
  264. if len(condSQL) > 0 {
  265. condSQL = "WHERE " + condSQL
  266. }
  267. } else if st.Engine.dialect.DBType() == core.MSSQL {
  268. top = fmt.Sprintf("top (%d) ", st.LimitN)
  269. }
  270. }
  271. sqlStr = fmt.Sprintf("UPDATE %v%v SET %v %v",
  272. top,
  273. session.Engine.Quote(session.Statement.TableName()),
  274. strings.Join(colNames, ", "),
  275. condSQL)
  276. res, err := session.exec(sqlStr, append(args, condArgs...)...)
  277. if err != nil {
  278. return 0, err
  279. } else if doIncVer {
  280. if verValue != nil && verValue.IsValid() && verValue.CanSet() {
  281. verValue.SetInt(verValue.Int() + 1)
  282. }
  283. }
  284. if table != nil {
  285. if cacher := session.Engine.getCacher2(table); cacher != nil && session.Statement.UseCache {
  286. cacher.ClearIds(session.Statement.TableName())
  287. cacher.ClearBeans(session.Statement.TableName())
  288. }
  289. }
  290. // handle after update processors
  291. if session.IsAutoCommit {
  292. for _, closure := range session.afterClosures {
  293. closure(bean)
  294. }
  295. if processor, ok := interface{}(bean).(AfterUpdateProcessor); ok {
  296. session.Engine.logger.Debug("[event]", session.Statement.TableName(), " has after update processor")
  297. processor.AfterUpdate()
  298. }
  299. } else {
  300. lenAfterClosures := len(session.afterClosures)
  301. if lenAfterClosures > 0 {
  302. if value, has := session.afterUpdateBeans[bean]; has && value != nil {
  303. *value = append(*value, session.afterClosures...)
  304. } else {
  305. afterClosures := make([]func(interface{}), lenAfterClosures)
  306. copy(afterClosures, session.afterClosures)
  307. // FIXME: if bean is a map type, it will panic because map cannot be as map key
  308. session.afterUpdateBeans[bean] = &afterClosures
  309. }
  310. } else {
  311. if _, ok := interface{}(bean).(AfterUpdateProcessor); ok {
  312. session.afterUpdateBeans[bean] = nil
  313. }
  314. }
  315. }
  316. cleanupProcessorsClosures(&session.afterClosures) // cleanup after used
  317. // --
  318. return res.RowsAffected()
  319. }