session_update.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  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. "xorm.io/builder"
  12. "xorm.io/xorm/caches"
  13. "xorm.io/xorm/internal/utils"
  14. "xorm.io/xorm/schemas"
  15. )
  16. func (session *Session) cacheUpdate(table *schemas.Table, tableName, sqlStr string, args ...interface{}) error {
  17. if table == nil ||
  18. session.tx != nil {
  19. return ErrCacheFailed
  20. }
  21. oldhead, newsql := session.statement.ConvertUpdateSQL(sqlStr)
  22. if newsql == "" {
  23. return ErrCacheFailed
  24. }
  25. for _, filter := range session.engine.dialect.Filters() {
  26. newsql = filter.Do(newsql)
  27. }
  28. session.engine.logger.Debugf("[cache] new sql: %v, %v", oldhead, newsql)
  29. var nStart int
  30. if len(args) > 0 {
  31. if strings.Index(sqlStr, "?") > -1 {
  32. nStart = strings.Count(oldhead, "?")
  33. } else {
  34. // only for pq, TODO: if any other databse?
  35. nStart = strings.Count(oldhead, "$")
  36. }
  37. }
  38. cacher := session.engine.GetCacher(tableName)
  39. session.engine.logger.Debugf("[cache] get cache sql: %v, %v", newsql, args[nStart:])
  40. ids, err := caches.GetCacheSql(cacher, tableName, newsql, args[nStart:])
  41. if err != nil {
  42. rows, err := session.NoCache().queryRows(newsql, args[nStart:]...)
  43. if err != nil {
  44. return err
  45. }
  46. defer rows.Close()
  47. ids = make([]schemas.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 schemas.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.Debugf("[cache] find updated id: %v", 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 := utils.SplitNNoCase(sqlStr, "where", 2)
  82. if len(sqls) == 0 || len(sqls) > 2 {
  83. return ErrCacheFailed
  84. }
  85. sqls = utils.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. colName = session.engine.dialect.Quoter().Trim(colName)
  95. colName = schemas.CommonQuoter.Trim(colName)
  96. if col := table.GetColumn(colName); col != nil {
  97. fieldValue, err := col.ValueOf(bean)
  98. if err != nil {
  99. session.engine.logger.Errorf("%v", err)
  100. } else {
  101. session.engine.logger.Debugf("[cache] set bean field: %v, %v, %v", bean, colName, fieldValue.Interface())
  102. if col.IsVersion && session.statement.CheckVersion {
  103. session.incrVersionFieldValue(fieldValue)
  104. } else {
  105. fieldValue.Set(reflect.ValueOf(args[idx]))
  106. }
  107. }
  108. } else {
  109. session.engine.logger.Errorf("[cache] ERROR: column %v is not table %v's",
  110. colName, table.Name)
  111. }
  112. }
  113. session.engine.logger.Debugf("[cache] update cache: %v, %v, %v", tableName, id, bean)
  114. cacher.PutBean(tableName, sid, bean)
  115. }
  116. }
  117. session.engine.logger.Debugf("[cache] clear cached table sql: %v", tableName)
  118. cacher.ClearIds(tableName)
  119. return nil
  120. }
  121. // Update records, bean's non-empty fields are updated contents,
  122. // condiBean' non-empty filds are conditions
  123. // CAUTION:
  124. // 1.bool will defaultly be updated content nor conditions
  125. // You should call UseBool if you have bool to use.
  126. // 2.float32 & float64 may be not inexact as conditions
  127. func (session *Session) Update(bean interface{}, condiBean ...interface{}) (int64, error) {
  128. if session.isAutoClose {
  129. defer session.Close()
  130. }
  131. if session.statement.LastError != nil {
  132. return 0, session.statement.LastError
  133. }
  134. v := utils.ReflectValue(bean)
  135. t := v.Type()
  136. var colNames []string
  137. var args []interface{}
  138. // handle before update processors
  139. for _, closure := range session.beforeClosures {
  140. closure(bean)
  141. }
  142. cleanupProcessorsClosures(&session.beforeClosures) // cleanup after used
  143. if processor, ok := interface{}(bean).(BeforeUpdateProcessor); ok {
  144. processor.BeforeUpdate()
  145. }
  146. // --
  147. var err error
  148. var isMap = t.Kind() == reflect.Map
  149. var isStruct = t.Kind() == reflect.Struct
  150. if isStruct {
  151. if err := session.statement.SetRefBean(bean); err != nil {
  152. return 0, err
  153. }
  154. if len(session.statement.TableName()) <= 0 {
  155. return 0, ErrTableNotFound
  156. }
  157. if session.statement.ColumnStr() == "" {
  158. colNames, args, err = session.statement.BuildUpdates(v, false, false,
  159. false, false, true)
  160. } else {
  161. colNames, args, err = session.genUpdateColumns(bean)
  162. }
  163. if err != nil {
  164. return 0, err
  165. }
  166. } else if isMap {
  167. colNames = make([]string, 0)
  168. args = make([]interface{}, 0)
  169. bValue := reflect.Indirect(reflect.ValueOf(bean))
  170. for _, v := range bValue.MapKeys() {
  171. colNames = append(colNames, session.engine.Quote(v.String())+" = ?")
  172. args = append(args, bValue.MapIndex(v).Interface())
  173. }
  174. } else {
  175. return 0, ErrParamsType
  176. }
  177. table := session.statement.RefTable
  178. if session.statement.UseAutoTime && table != nil && table.Updated != "" {
  179. if !session.statement.ColumnMap.Contain(table.Updated) &&
  180. !session.statement.OmitColumnMap.Contain(table.Updated) {
  181. colNames = append(colNames, session.engine.Quote(table.Updated)+" = ?")
  182. col := table.UpdatedColumn()
  183. val, t := session.engine.nowTime(col)
  184. if session.engine.dialect.URI().DBType == schemas.ORACLE {
  185. args = append(args, t)
  186. } else {
  187. args = append(args, val)
  188. }
  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. }
  198. // for update action to like "column = column + ?"
  199. incColumns := session.statement.IncrColumns
  200. for i, colName := range incColumns.ColNames {
  201. colNames = append(colNames, session.engine.Quote(colName)+" = "+session.engine.Quote(colName)+" + ?")
  202. args = append(args, incColumns.Args[i])
  203. }
  204. // for update action to like "column = column - ?"
  205. decColumns := session.statement.DecrColumns
  206. for i, colName := range decColumns.ColNames {
  207. colNames = append(colNames, session.engine.Quote(colName)+" = "+session.engine.Quote(colName)+" - ?")
  208. args = append(args, decColumns.Args[i])
  209. }
  210. // for update action to like "column = expression"
  211. exprColumns := session.statement.ExprColumns
  212. for i, colName := range exprColumns.ColNames {
  213. switch tp := exprColumns.Args[i].(type) {
  214. case string:
  215. if len(tp) == 0 {
  216. tp = "''"
  217. }
  218. colNames = append(colNames, session.engine.Quote(colName)+"="+tp)
  219. case *builder.Builder:
  220. subQuery, subArgs, err := session.statement.GenCondSQL(tp)
  221. if err != nil {
  222. return 0, err
  223. }
  224. colNames = append(colNames, session.engine.Quote(colName)+"=("+subQuery+")")
  225. args = append(args, subArgs...)
  226. default:
  227. colNames = append(colNames, session.engine.Quote(colName)+"=?")
  228. args = append(args, exprColumns.Args[i])
  229. }
  230. }
  231. if err = session.statement.ProcessIDParam(); err != nil {
  232. return 0, err
  233. }
  234. var autoCond builder.Cond
  235. if !session.statement.NoAutoCondition {
  236. condBeanIsStruct := false
  237. if len(condiBean) > 0 {
  238. if c, ok := condiBean[0].(map[string]interface{}); ok {
  239. autoCond = builder.Eq(c)
  240. } else {
  241. ct := reflect.TypeOf(condiBean[0])
  242. k := ct.Kind()
  243. if k == reflect.Ptr {
  244. k = ct.Elem().Kind()
  245. }
  246. if k == reflect.Struct {
  247. var refTable = session.statement.RefTable
  248. if refTable == nil {
  249. refTable, err = session.engine.TableInfo(condiBean[0])
  250. if err != nil {
  251. return 0, err
  252. }
  253. }
  254. var err error
  255. autoCond, err = session.statement.BuildConds(refTable, condiBean[0], true, true, false, true, false)
  256. if err != nil {
  257. return 0, err
  258. }
  259. condBeanIsStruct = true
  260. } else {
  261. return 0, ErrConditionType
  262. }
  263. }
  264. }
  265. if !condBeanIsStruct && table != nil {
  266. if col := table.DeletedColumn(); col != nil && !session.statement.GetUnscoped() { // tag "deleted" is enabled
  267. autoCond1 := session.statement.CondDeleted(col)
  268. if autoCond == nil {
  269. autoCond = autoCond1
  270. } else {
  271. autoCond = autoCond.And(autoCond1)
  272. }
  273. }
  274. }
  275. }
  276. st := session.statement
  277. var (
  278. sqlStr string
  279. condArgs []interface{}
  280. condSQL string
  281. cond = session.statement.Conds().And(autoCond)
  282. doIncVer = isStruct && (table != nil && table.Version != "" && session.statement.CheckVersion)
  283. verValue *reflect.Value
  284. )
  285. if doIncVer {
  286. verValue, err = table.VersionColumn().ValueOf(bean)
  287. if err != nil {
  288. return 0, err
  289. }
  290. if verValue != nil {
  291. cond = cond.And(builder.Eq{session.engine.Quote(table.Version): verValue.Interface()})
  292. colNames = append(colNames, session.engine.Quote(table.Version)+" = "+session.engine.Quote(table.Version)+" + 1")
  293. }
  294. }
  295. if len(colNames) <= 0 {
  296. return 0, errors.New("No content found to be updated")
  297. }
  298. condSQL, condArgs, err = session.statement.GenCondSQL(cond)
  299. if err != nil {
  300. return 0, err
  301. }
  302. if len(condSQL) > 0 {
  303. condSQL = "WHERE " + condSQL
  304. }
  305. if st.OrderStr != "" {
  306. condSQL = condSQL + fmt.Sprintf(" ORDER BY %v", st.OrderStr)
  307. }
  308. var tableName = session.statement.TableName()
  309. // TODO: Oracle support needed
  310. var top string
  311. if st.LimitN != nil {
  312. limitValue := *st.LimitN
  313. switch session.engine.dialect.URI().DBType {
  314. case schemas.MYSQL:
  315. condSQL = condSQL + fmt.Sprintf(" LIMIT %d", limitValue)
  316. case schemas.SQLITE:
  317. tempCondSQL := condSQL + fmt.Sprintf(" LIMIT %d", limitValue)
  318. cond = cond.And(builder.Expr(fmt.Sprintf("rowid IN (SELECT rowid FROM %v %v)",
  319. session.engine.Quote(tableName), tempCondSQL), condArgs...))
  320. condSQL, condArgs, err = session.statement.GenCondSQL(cond)
  321. if err != nil {
  322. return 0, err
  323. }
  324. if len(condSQL) > 0 {
  325. condSQL = "WHERE " + condSQL
  326. }
  327. case schemas.POSTGRES:
  328. tempCondSQL := condSQL + fmt.Sprintf(" LIMIT %d", limitValue)
  329. cond = cond.And(builder.Expr(fmt.Sprintf("CTID IN (SELECT CTID FROM %v %v)",
  330. session.engine.Quote(tableName), tempCondSQL), condArgs...))
  331. condSQL, condArgs, err = session.statement.GenCondSQL(cond)
  332. if err != nil {
  333. return 0, err
  334. }
  335. if len(condSQL) > 0 {
  336. condSQL = "WHERE " + condSQL
  337. }
  338. case schemas.MSSQL:
  339. if st.OrderStr != "" && table != nil && len(table.PrimaryKeys) == 1 {
  340. cond = builder.Expr(fmt.Sprintf("%s IN (SELECT TOP (%d) %s FROM %v%v)",
  341. table.PrimaryKeys[0], limitValue, table.PrimaryKeys[0],
  342. session.engine.Quote(tableName), condSQL), condArgs...)
  343. condSQL, condArgs, err = session.statement.GenCondSQL(cond)
  344. if err != nil {
  345. return 0, err
  346. }
  347. if len(condSQL) > 0 {
  348. condSQL = "WHERE " + condSQL
  349. }
  350. } else {
  351. top = fmt.Sprintf("TOP (%d) ", limitValue)
  352. }
  353. }
  354. }
  355. var tableAlias = session.engine.Quote(tableName)
  356. var fromSQL string
  357. if session.statement.TableAlias != "" {
  358. switch session.engine.dialect.URI().DBType {
  359. case schemas.MSSQL:
  360. fromSQL = fmt.Sprintf("FROM %s %s ", tableAlias, session.statement.TableAlias)
  361. tableAlias = session.statement.TableAlias
  362. default:
  363. tableAlias = fmt.Sprintf("%s AS %s", tableAlias, session.statement.TableAlias)
  364. }
  365. }
  366. sqlStr = fmt.Sprintf("UPDATE %v%v SET %v %v%v",
  367. top,
  368. tableAlias,
  369. strings.Join(colNames, ", "),
  370. fromSQL,
  371. condSQL)
  372. res, err := session.exec(sqlStr, append(args, condArgs...)...)
  373. if err != nil {
  374. return 0, err
  375. } else if doIncVer {
  376. if verValue != nil && verValue.IsValid() && verValue.CanSet() {
  377. session.incrVersionFieldValue(verValue)
  378. }
  379. }
  380. if cacher := session.engine.GetCacher(tableName); cacher != nil && session.statement.UseCache {
  381. // session.cacheUpdate(table, tableName, sqlStr, args...)
  382. session.engine.logger.Debugf("[cache] clear table: %v", tableName)
  383. cacher.ClearIds(tableName)
  384. cacher.ClearBeans(tableName)
  385. }
  386. // handle after update processors
  387. if session.isAutoCommit {
  388. for _, closure := range session.afterClosures {
  389. closure(bean)
  390. }
  391. if processor, ok := interface{}(bean).(AfterUpdateProcessor); ok {
  392. session.engine.logger.Debugf("[event] %v has after update processor", tableName)
  393. processor.AfterUpdate()
  394. }
  395. } else {
  396. lenAfterClosures := len(session.afterClosures)
  397. if lenAfterClosures > 0 {
  398. if value, has := session.afterUpdateBeans[bean]; has && value != nil {
  399. *value = append(*value, session.afterClosures...)
  400. } else {
  401. afterClosures := make([]func(interface{}), lenAfterClosures)
  402. copy(afterClosures, session.afterClosures)
  403. // FIXME: if bean is a map type, it will panic because map cannot be as map key
  404. session.afterUpdateBeans[bean] = &afterClosures
  405. }
  406. } else {
  407. if _, ok := interface{}(bean).(AfterUpdateProcessor); ok {
  408. session.afterUpdateBeans[bean] = nil
  409. }
  410. }
  411. }
  412. cleanupProcessorsClosures(&session.afterClosures) // cleanup after used
  413. // --
  414. return res.RowsAffected()
  415. }
  416. func (session *Session) genUpdateColumns(bean interface{}) ([]string, []interface{}, error) {
  417. table := session.statement.RefTable
  418. colNames := make([]string, 0, len(table.ColumnsSeq()))
  419. args := make([]interface{}, 0, len(table.ColumnsSeq()))
  420. for _, col := range table.Columns() {
  421. if !col.IsVersion && !col.IsCreated && !col.IsUpdated {
  422. if session.statement.OmitColumnMap.Contain(col.Name) {
  423. continue
  424. }
  425. }
  426. if col.MapType == schemas.ONLYFROMDB {
  427. continue
  428. }
  429. fieldValuePtr, err := col.ValueOf(bean)
  430. if err != nil {
  431. return nil, nil, err
  432. }
  433. fieldValue := *fieldValuePtr
  434. if col.IsAutoIncrement && utils.IsValueZero(fieldValue) {
  435. continue
  436. }
  437. if (col.IsDeleted && !session.statement.GetUnscoped()) || col.IsCreated {
  438. continue
  439. }
  440. // if only update specify columns
  441. if len(session.statement.ColumnMap) > 0 && !session.statement.ColumnMap.Contain(col.Name) {
  442. continue
  443. }
  444. if session.statement.IncrColumns.IsColExist(col.Name) {
  445. continue
  446. } else if session.statement.DecrColumns.IsColExist(col.Name) {
  447. continue
  448. } else if session.statement.ExprColumns.IsColExist(col.Name) {
  449. continue
  450. }
  451. // !evalphobia! set fieldValue as nil when column is nullable and zero-value
  452. if _, ok := getFlagForColumn(session.statement.NullableMap, col); ok {
  453. if col.Nullable && utils.IsValueZero(fieldValue) {
  454. var nilValue *int
  455. fieldValue = reflect.ValueOf(nilValue)
  456. }
  457. }
  458. if col.IsUpdated && session.statement.UseAutoTime /*&& isZero(fieldValue.Interface())*/ {
  459. // if time is non-empty, then set to auto time
  460. val, t := session.engine.nowTime(col)
  461. args = append(args, val)
  462. var colName = col.Name
  463. session.afterClosures = append(session.afterClosures, func(bean interface{}) {
  464. col := table.GetColumn(colName)
  465. setColumnTime(bean, col, t)
  466. })
  467. } else if col.IsVersion && session.statement.CheckVersion {
  468. args = append(args, 1)
  469. } else {
  470. arg, err := session.statement.Value2Interface(col, fieldValue)
  471. if err != nil {
  472. return colNames, args, err
  473. }
  474. args = append(args, arg)
  475. }
  476. colNames = append(colNames, session.engine.Quote(col.Name)+" = ?")
  477. }
  478. return colNames, args, nil
  479. }