session_update.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  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(table *core.Table, tableName, sqlStr string, args ...interface{}) error {
  15. if table == 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, table)
  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. cacher := session.engine.getCacher(tableName)
  37. session.engine.logger.Debug("[cacheUpdate] get cache sql", newsql, args[nStart:])
  38. ids, err := core.GetCacheSql(cacher, tableName, newsql, args[nStart:])
  39. if err != nil {
  40. rows, err := session.NoCache().queryRows(newsql, args[nStart:]...)
  41. if err != nil {
  42. return err
  43. }
  44. defer rows.Close()
  45. ids = make([]core.PK, 0)
  46. for rows.Next() {
  47. var res = make([]string, len(table.PrimaryKeys))
  48. err = rows.ScanSlice(&res)
  49. if err != nil {
  50. return err
  51. }
  52. var pk core.PK = make([]interface{}, len(table.PrimaryKeys))
  53. for i, col := range table.PKColumns() {
  54. if col.SQLType.IsNumeric() {
  55. n, err := strconv.ParseInt(res[i], 10, 64)
  56. if err != nil {
  57. return err
  58. }
  59. pk[i] = n
  60. } else if col.SQLType.IsText() {
  61. pk[i] = res[i]
  62. } else {
  63. return errors.New("not supported")
  64. }
  65. }
  66. ids = append(ids, pk)
  67. }
  68. session.engine.logger.Debug("[cacheUpdate] find updated id", ids)
  69. } /*else {
  70. session.engine.LogDebug("[xorm:cacheUpdate] del cached sql:", tableName, newsql, args)
  71. cacher.DelIds(tableName, genSqlKey(newsql, args))
  72. }*/
  73. for _, id := range ids {
  74. sid, err := id.ToString()
  75. if err != nil {
  76. return err
  77. }
  78. if bean := cacher.GetBean(tableName, sid); bean != nil {
  79. sqls := splitNNoCase(sqlStr, "where", 2)
  80. if len(sqls) == 0 || len(sqls) > 2 {
  81. return ErrCacheFailed
  82. }
  83. sqls = splitNNoCase(sqls[0], "set", 2)
  84. if len(sqls) != 2 {
  85. return ErrCacheFailed
  86. }
  87. kvs := strings.Split(strings.TrimSpace(sqls[1]), ",")
  88. for idx, kv := range kvs {
  89. sps := strings.SplitN(kv, "=", 2)
  90. sps2 := strings.Split(sps[0], ".")
  91. colName := sps2[len(sps2)-1]
  92. if strings.Contains(colName, "`") {
  93. colName = strings.TrimSpace(strings.Replace(colName, "`", "", -1))
  94. } else if strings.Contains(colName, session.engine.QuoteStr()) {
  95. colName = strings.TrimSpace(strings.Replace(colName, session.engine.QuoteStr(), "", -1))
  96. } else {
  97. session.engine.logger.Debug("[cacheUpdate] cannot find column", tableName, colName)
  98. return ErrCacheFailed
  99. }
  100. if col := table.GetColumn(colName); col != nil {
  101. fieldValue, err := col.ValueOf(bean)
  102. if err != nil {
  103. session.engine.logger.Error(err)
  104. } else {
  105. session.engine.logger.Debug("[cacheUpdate] set bean field", bean, colName, fieldValue.Interface())
  106. if col.IsVersion && session.statement.checkVersion {
  107. fieldValue.SetInt(fieldValue.Int() + 1)
  108. } else {
  109. fieldValue.Set(reflect.ValueOf(args[idx]))
  110. }
  111. }
  112. } else {
  113. session.engine.logger.Errorf("[cacheUpdate] ERROR: column %v is not table %v's",
  114. colName, table.Name)
  115. }
  116. }
  117. session.engine.logger.Debug("[cacheUpdate] update cache", tableName, id, bean)
  118. cacher.PutBean(tableName, sid, bean)
  119. }
  120. }
  121. session.engine.logger.Debug("[cacheUpdate] clear cached table sql:", tableName)
  122. cacher.ClearIds(tableName)
  123. return nil
  124. }
  125. // Update records, bean's non-empty fields are updated contents,
  126. // condiBean' non-empty filds are conditions
  127. // CAUTION:
  128. // 1.bool will defaultly be updated content nor conditions
  129. // You should call UseBool if you have bool to use.
  130. // 2.float32 & float64 may be not inexact as conditions
  131. func (session *Session) Update(bean interface{}, condiBean ...interface{}) (int64, error) {
  132. if session.isAutoClose {
  133. defer session.Close()
  134. }
  135. v := rValue(bean)
  136. t := v.Type()
  137. var colNames []string
  138. var args []interface{}
  139. // handle before update processors
  140. for _, closure := range session.beforeClosures {
  141. closure(bean)
  142. }
  143. cleanupProcessorsClosures(&session.beforeClosures) // cleanup after used
  144. if processor, ok := interface{}(bean).(BeforeUpdateProcessor); ok {
  145. processor.BeforeUpdate()
  146. }
  147. // --
  148. var err error
  149. var isMap = t.Kind() == reflect.Map
  150. var isStruct = t.Kind() == reflect.Struct
  151. if isStruct {
  152. if err := session.statement.setRefBean(bean); err != nil {
  153. return 0, err
  154. }
  155. if len(session.statement.TableName()) <= 0 {
  156. return 0, ErrTableNotFound
  157. }
  158. if session.statement.ColumnStr == "" {
  159. colNames, args = session.statement.buildUpdates(bean, false, false,
  160. false, false, true)
  161. } else {
  162. colNames, args, err = session.genUpdateColumns(bean)
  163. if err != nil {
  164. return 0, err
  165. }
  166. }
  167. } else if isMap {
  168. colNames = make([]string, 0)
  169. args = make([]interface{}, 0)
  170. bValue := reflect.Indirect(reflect.ValueOf(bean))
  171. for _, v := range bValue.MapKeys() {
  172. colNames = append(colNames, session.engine.Quote(v.String())+" = ?")
  173. args = append(args, bValue.MapIndex(v).Interface())
  174. }
  175. } else {
  176. return 0, ErrParamsType
  177. }
  178. table := session.statement.RefTable
  179. if session.statement.UseAutoTime && table != nil && table.Updated != "" {
  180. if !session.statement.columnMap.contain(table.Updated) &&
  181. !session.statement.omitColumnMap.contain(table.Updated) {
  182. colNames = append(colNames, session.engine.Quote(table.Updated)+" = ?")
  183. col := table.UpdatedColumn()
  184. val, t := session.engine.nowTime(col)
  185. args = append(args, val)
  186. var colName = col.Name
  187. if isStruct {
  188. session.afterClosures = append(session.afterClosures, func(bean interface{}) {
  189. col := table.GetColumn(colName)
  190. setColumnTime(bean, col, t)
  191. })
  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. if err = session.statement.processIDParam(); err != nil {
  213. return 0, err
  214. }
  215. var autoCond builder.Cond
  216. if !session.statement.noAutoCondition && len(condiBean) > 0 {
  217. if c, ok := condiBean[0].(map[string]interface{}); ok {
  218. autoCond = builder.Eq(c)
  219. } else {
  220. ct := reflect.TypeOf(condiBean[0])
  221. k := ct.Kind()
  222. if k == reflect.Ptr {
  223. k = ct.Elem().Kind()
  224. }
  225. if k == reflect.Struct {
  226. var err error
  227. autoCond, err = session.statement.buildConds(session.statement.RefTable, condiBean[0], true, true, false, true, false)
  228. if err != nil {
  229. return 0, err
  230. }
  231. } else {
  232. return 0, ErrConditionType
  233. }
  234. }
  235. }
  236. st := &session.statement
  237. var sqlStr string
  238. var condArgs []interface{}
  239. var condSQL string
  240. cond := session.statement.cond.And(autoCond)
  241. var doIncVer = (table != nil && table.Version != "" && session.statement.checkVersion)
  242. var verValue *reflect.Value
  243. if doIncVer {
  244. verValue, err = table.VersionColumn().ValueOf(bean)
  245. if err != nil {
  246. return 0, err
  247. }
  248. cond = cond.And(builder.Eq{session.engine.Quote(table.Version): verValue.Interface()})
  249. colNames = append(colNames, session.engine.Quote(table.Version)+" = "+session.engine.Quote(table.Version)+" + 1")
  250. }
  251. condSQL, condArgs, err = builder.ToSQL(cond)
  252. if err != nil {
  253. return 0, err
  254. }
  255. if len(condSQL) > 0 {
  256. condSQL = "WHERE " + condSQL
  257. }
  258. if st.OrderStr != "" {
  259. condSQL = condSQL + fmt.Sprintf(" ORDER BY %v", st.OrderStr)
  260. }
  261. var tableName = session.statement.TableName()
  262. // TODO: Oracle support needed
  263. var top string
  264. if st.LimitN > 0 {
  265. if st.Engine.dialect.DBType() == core.MYSQL {
  266. condSQL = condSQL + fmt.Sprintf(" LIMIT %d", st.LimitN)
  267. } else if st.Engine.dialect.DBType() == core.SQLITE {
  268. tempCondSQL := condSQL + fmt.Sprintf(" LIMIT %d", st.LimitN)
  269. cond = cond.And(builder.Expr(fmt.Sprintf("rowid IN (SELECT rowid FROM %v %v)",
  270. session.engine.Quote(tableName), tempCondSQL), condArgs...))
  271. condSQL, condArgs, err = builder.ToSQL(cond)
  272. if err != nil {
  273. return 0, err
  274. }
  275. if len(condSQL) > 0 {
  276. condSQL = "WHERE " + condSQL
  277. }
  278. } else if st.Engine.dialect.DBType() == core.POSTGRES {
  279. tempCondSQL := condSQL + fmt.Sprintf(" LIMIT %d", st.LimitN)
  280. cond = cond.And(builder.Expr(fmt.Sprintf("CTID IN (SELECT CTID FROM %v %v)",
  281. session.engine.Quote(tableName), tempCondSQL), condArgs...))
  282. condSQL, condArgs, err = builder.ToSQL(cond)
  283. if err != nil {
  284. return 0, err
  285. }
  286. if len(condSQL) > 0 {
  287. condSQL = "WHERE " + condSQL
  288. }
  289. } else if st.Engine.dialect.DBType() == core.MSSQL {
  290. if st.OrderStr != "" && st.Engine.dialect.DBType() == core.MSSQL &&
  291. table != nil && len(table.PrimaryKeys) == 1 {
  292. cond = builder.Expr(fmt.Sprintf("%s IN (SELECT TOP (%d) %s FROM %v%v)",
  293. table.PrimaryKeys[0], st.LimitN, table.PrimaryKeys[0],
  294. session.engine.Quote(tableName), condSQL), condArgs...)
  295. condSQL, condArgs, err = builder.ToSQL(cond)
  296. if err != nil {
  297. return 0, err
  298. }
  299. if len(condSQL) > 0 {
  300. condSQL = "WHERE " + condSQL
  301. }
  302. } else {
  303. top = fmt.Sprintf("TOP (%d) ", st.LimitN)
  304. }
  305. }
  306. }
  307. if len(colNames) <= 0 {
  308. return 0, errors.New("No content found to be updated")
  309. }
  310. sqlStr = fmt.Sprintf("UPDATE %v%v SET %v %v",
  311. top,
  312. session.engine.Quote(tableName),
  313. strings.Join(colNames, ", "),
  314. condSQL)
  315. res, err := session.exec(sqlStr, append(args, condArgs...)...)
  316. if err != nil {
  317. return 0, err
  318. } else if doIncVer {
  319. if verValue != nil && verValue.IsValid() && verValue.CanSet() {
  320. verValue.SetInt(verValue.Int() + 1)
  321. }
  322. }
  323. if cacher := session.engine.getCacher(tableName); cacher != nil && session.statement.UseCache {
  324. //session.cacheUpdate(table, tableName, sqlStr, args...)
  325. session.engine.logger.Debug("[cacheUpdate] clear table ", tableName)
  326. cacher.ClearIds(tableName)
  327. cacher.ClearBeans(tableName)
  328. }
  329. // handle after update processors
  330. if session.isAutoCommit {
  331. for _, closure := range session.afterClosures {
  332. closure(bean)
  333. }
  334. if processor, ok := interface{}(bean).(AfterUpdateProcessor); ok {
  335. session.engine.logger.Debug("[event]", tableName, " has after update processor")
  336. processor.AfterUpdate()
  337. }
  338. } else {
  339. lenAfterClosures := len(session.afterClosures)
  340. if lenAfterClosures > 0 {
  341. if value, has := session.afterUpdateBeans[bean]; has && value != nil {
  342. *value = append(*value, session.afterClosures...)
  343. } else {
  344. afterClosures := make([]func(interface{}), lenAfterClosures)
  345. copy(afterClosures, session.afterClosures)
  346. // FIXME: if bean is a map type, it will panic because map cannot be as map key
  347. session.afterUpdateBeans[bean] = &afterClosures
  348. }
  349. } else {
  350. if _, ok := interface{}(bean).(AfterUpdateProcessor); ok {
  351. session.afterUpdateBeans[bean] = nil
  352. }
  353. }
  354. }
  355. cleanupProcessorsClosures(&session.afterClosures) // cleanup after used
  356. // --
  357. return res.RowsAffected()
  358. }
  359. func (session *Session) genUpdateColumns(bean interface{}) ([]string, []interface{}, error) {
  360. table := session.statement.RefTable
  361. colNames := make([]string, 0, len(table.ColumnsSeq()))
  362. args := make([]interface{}, 0, len(table.ColumnsSeq()))
  363. for _, col := range table.Columns() {
  364. if !col.IsVersion && !col.IsCreated && !col.IsUpdated {
  365. if session.statement.omitColumnMap.contain(col.Name) {
  366. continue
  367. }
  368. }
  369. if col.MapType == core.ONLYFROMDB {
  370. continue
  371. }
  372. fieldValuePtr, err := col.ValueOf(bean)
  373. if err != nil {
  374. return nil, nil, err
  375. }
  376. fieldValue := *fieldValuePtr
  377. if col.IsAutoIncrement {
  378. switch fieldValue.Type().Kind() {
  379. case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int, reflect.Int64:
  380. if fieldValue.Int() == 0 {
  381. continue
  382. }
  383. case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint, reflect.Uint64:
  384. if fieldValue.Uint() == 0 {
  385. continue
  386. }
  387. case reflect.String:
  388. if len(fieldValue.String()) == 0 {
  389. continue
  390. }
  391. case reflect.Ptr:
  392. if fieldValue.Pointer() == 0 {
  393. continue
  394. }
  395. }
  396. }
  397. if col.IsDeleted || col.IsCreated {
  398. continue
  399. }
  400. if len(session.statement.columnMap) > 0 {
  401. if !session.statement.columnMap.contain(col.Name) {
  402. continue
  403. } else if _, ok := session.statement.incrColumns[col.Name]; ok {
  404. continue
  405. } else if _, ok := session.statement.decrColumns[col.Name]; ok {
  406. continue
  407. }
  408. }
  409. // !evalphobia! set fieldValue as nil when column is nullable and zero-value
  410. if _, ok := getFlagForColumn(session.statement.nullableMap, col); ok {
  411. if col.Nullable && isZero(fieldValue.Interface()) {
  412. var nilValue *int
  413. fieldValue = reflect.ValueOf(nilValue)
  414. }
  415. }
  416. if col.IsUpdated && session.statement.UseAutoTime /*&& isZero(fieldValue.Interface())*/ {
  417. // if time is non-empty, then set to auto time
  418. val, t := session.engine.nowTime(col)
  419. args = append(args, val)
  420. var colName = col.Name
  421. session.afterClosures = append(session.afterClosures, func(bean interface{}) {
  422. col := table.GetColumn(colName)
  423. setColumnTime(bean, col, t)
  424. })
  425. } else if col.IsVersion && session.statement.checkVersion {
  426. args = append(args, 1)
  427. } else {
  428. arg, err := session.value2Interface(col, fieldValue)
  429. if err != nil {
  430. return colNames, args, err
  431. }
  432. args = append(args, arg)
  433. }
  434. colNames = append(colNames, session.engine.Quote(col.Name)+" = ?")
  435. }
  436. return colNames, args, nil
  437. }