Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  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/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. // treat quote prefix, suffix and '`' as quotes
  93. quotes := append(strings.Split(session.engine.Quote(""), ""), "`")
  94. if strings.ContainsAny(colName, strings.Join(quotes, "")) {
  95. colName = strings.TrimSpace(eraseAny(colName, quotes...))
  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. session.incrVersionFieldValue(fieldValue)
  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. if session.statement.lastError != nil {
  136. return 0, session.statement.lastError
  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.setRefBean(bean); 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 = session.statement.buildUpdates(bean, false, false,
  163. false, false, true)
  164. } else {
  165. colNames, args, err = session.genUpdateColumns(bean)
  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. if !session.statement.columnMap.contain(table.Updated) &&
  184. !session.statement.omitColumnMap.contain(table.Updated) {
  185. colNames = append(colNames, session.engine.Quote(table.Updated)+" = ?")
  186. col := table.UpdatedColumn()
  187. val, t := session.engine.nowTime(col)
  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. }
  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 := builder.ToSQL(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 err error
  248. autoCond, err = session.statement.buildConds(session.statement.RefTable, condiBean[0], true, true, false, true, false)
  249. if err != nil {
  250. return 0, err
  251. }
  252. condBeanIsStruct = true
  253. } else {
  254. return 0, ErrConditionType
  255. }
  256. }
  257. }
  258. if !condBeanIsStruct && table != nil {
  259. if col := table.DeletedColumn(); col != nil && !session.statement.unscoped { // tag "deleted" is enabled
  260. autoCond1 := session.engine.CondDeleted(session.engine.Quote(col.Name))
  261. if autoCond == nil {
  262. autoCond = autoCond1
  263. } else {
  264. autoCond = autoCond.And(autoCond1)
  265. }
  266. }
  267. }
  268. }
  269. st := &session.statement
  270. var sqlStr string
  271. var condArgs []interface{}
  272. var condSQL string
  273. cond := session.statement.cond.And(autoCond)
  274. var doIncVer = (table != nil && table.Version != "" && session.statement.checkVersion)
  275. var verValue *reflect.Value
  276. if doIncVer {
  277. verValue, err = table.VersionColumn().ValueOf(bean)
  278. if err != nil {
  279. return 0, err
  280. }
  281. cond = cond.And(builder.Eq{session.engine.Quote(table.Version): verValue.Interface()})
  282. colNames = append(colNames, session.engine.Quote(table.Version)+" = "+session.engine.Quote(table.Version)+" + 1")
  283. }
  284. condSQL, condArgs, err = builder.ToSQL(cond)
  285. if err != nil {
  286. return 0, err
  287. }
  288. if len(condSQL) > 0 {
  289. condSQL = "WHERE " + condSQL
  290. }
  291. if st.OrderStr != "" {
  292. condSQL = condSQL + fmt.Sprintf(" ORDER BY %v", st.OrderStr)
  293. }
  294. var tableName = session.statement.TableName()
  295. // TODO: Oracle support needed
  296. var top string
  297. if st.LimitN > 0 {
  298. if st.Engine.dialect.DBType() == core.MYSQL {
  299. condSQL = condSQL + fmt.Sprintf(" LIMIT %d", st.LimitN)
  300. } else if st.Engine.dialect.DBType() == core.SQLITE {
  301. tempCondSQL := condSQL + fmt.Sprintf(" LIMIT %d", st.LimitN)
  302. cond = cond.And(builder.Expr(fmt.Sprintf("rowid IN (SELECT rowid FROM %v %v)",
  303. session.engine.Quote(tableName), tempCondSQL), condArgs...))
  304. condSQL, condArgs, err = builder.ToSQL(cond)
  305. if err != nil {
  306. return 0, err
  307. }
  308. if len(condSQL) > 0 {
  309. condSQL = "WHERE " + condSQL
  310. }
  311. } else if st.Engine.dialect.DBType() == core.POSTGRES {
  312. tempCondSQL := condSQL + fmt.Sprintf(" LIMIT %d", st.LimitN)
  313. cond = cond.And(builder.Expr(fmt.Sprintf("CTID IN (SELECT CTID FROM %v %v)",
  314. session.engine.Quote(tableName), tempCondSQL), condArgs...))
  315. condSQL, condArgs, err = builder.ToSQL(cond)
  316. if err != nil {
  317. return 0, err
  318. }
  319. if len(condSQL) > 0 {
  320. condSQL = "WHERE " + condSQL
  321. }
  322. } else if st.Engine.dialect.DBType() == core.MSSQL {
  323. if st.OrderStr != "" && st.Engine.dialect.DBType() == core.MSSQL &&
  324. table != nil && len(table.PrimaryKeys) == 1 {
  325. cond = builder.Expr(fmt.Sprintf("%s IN (SELECT TOP (%d) %s FROM %v%v)",
  326. table.PrimaryKeys[0], st.LimitN, table.PrimaryKeys[0],
  327. session.engine.Quote(tableName), condSQL), condArgs...)
  328. condSQL, condArgs, err = builder.ToSQL(cond)
  329. if err != nil {
  330. return 0, err
  331. }
  332. if len(condSQL) > 0 {
  333. condSQL = "WHERE " + condSQL
  334. }
  335. } else {
  336. top = fmt.Sprintf("TOP (%d) ", st.LimitN)
  337. }
  338. }
  339. }
  340. if len(colNames) <= 0 {
  341. return 0, errors.New("No content found to be updated")
  342. }
  343. var tableAlias = session.engine.Quote(tableName)
  344. var fromSQL string
  345. if session.statement.TableAlias != "" {
  346. switch session.engine.dialect.DBType() {
  347. case core.MSSQL:
  348. fromSQL = fmt.Sprintf("FROM %s %s ", tableAlias, session.statement.TableAlias)
  349. tableAlias = session.statement.TableAlias
  350. default:
  351. tableAlias = fmt.Sprintf("%s AS %s", tableAlias, session.statement.TableAlias)
  352. }
  353. }
  354. sqlStr = fmt.Sprintf("UPDATE %v%v SET %v %v%v",
  355. top,
  356. tableAlias,
  357. strings.Join(colNames, ", "),
  358. fromSQL,
  359. condSQL)
  360. res, err := session.exec(sqlStr, append(args, condArgs...)...)
  361. if err != nil {
  362. return 0, err
  363. } else if doIncVer {
  364. if verValue != nil && verValue.IsValid() && verValue.CanSet() {
  365. session.incrVersionFieldValue(verValue)
  366. }
  367. }
  368. if cacher := session.engine.getCacher(tableName); cacher != nil && session.statement.UseCache {
  369. // session.cacheUpdate(table, tableName, sqlStr, args...)
  370. session.engine.logger.Debug("[cacheUpdate] clear table ", tableName)
  371. cacher.ClearIds(tableName)
  372. cacher.ClearBeans(tableName)
  373. }
  374. // handle after update processors
  375. if session.isAutoCommit {
  376. for _, closure := range session.afterClosures {
  377. closure(bean)
  378. }
  379. if processor, ok := interface{}(bean).(AfterUpdateProcessor); ok {
  380. session.engine.logger.Debug("[event]", tableName, " has after update processor")
  381. processor.AfterUpdate()
  382. }
  383. } else {
  384. lenAfterClosures := len(session.afterClosures)
  385. if lenAfterClosures > 0 {
  386. if value, has := session.afterUpdateBeans[bean]; has && value != nil {
  387. *value = append(*value, session.afterClosures...)
  388. } else {
  389. afterClosures := make([]func(interface{}), lenAfterClosures)
  390. copy(afterClosures, session.afterClosures)
  391. // FIXME: if bean is a map type, it will panic because map cannot be as map key
  392. session.afterUpdateBeans[bean] = &afterClosures
  393. }
  394. } else {
  395. if _, ok := interface{}(bean).(AfterUpdateProcessor); ok {
  396. session.afterUpdateBeans[bean] = nil
  397. }
  398. }
  399. }
  400. cleanupProcessorsClosures(&session.afterClosures) // cleanup after used
  401. // --
  402. return res.RowsAffected()
  403. }
  404. func (session *Session) genUpdateColumns(bean interface{}) ([]string, []interface{}, error) {
  405. table := session.statement.RefTable
  406. colNames := make([]string, 0, len(table.ColumnsSeq()))
  407. args := make([]interface{}, 0, len(table.ColumnsSeq()))
  408. for _, col := range table.Columns() {
  409. if !col.IsVersion && !col.IsCreated && !col.IsUpdated {
  410. if session.statement.omitColumnMap.contain(col.Name) {
  411. continue
  412. }
  413. }
  414. if col.MapType == core.ONLYFROMDB {
  415. continue
  416. }
  417. fieldValuePtr, err := col.ValueOf(bean)
  418. if err != nil {
  419. return nil, nil, err
  420. }
  421. fieldValue := *fieldValuePtr
  422. if col.IsAutoIncrement {
  423. switch fieldValue.Type().Kind() {
  424. case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int, reflect.Int64:
  425. if fieldValue.Int() == 0 {
  426. continue
  427. }
  428. case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint, reflect.Uint64:
  429. if fieldValue.Uint() == 0 {
  430. continue
  431. }
  432. case reflect.String:
  433. if len(fieldValue.String()) == 0 {
  434. continue
  435. }
  436. case reflect.Ptr:
  437. if fieldValue.Pointer() == 0 {
  438. continue
  439. }
  440. }
  441. }
  442. if (col.IsDeleted && !session.statement.unscoped) || col.IsCreated {
  443. continue
  444. }
  445. // if only update specify columns
  446. if len(session.statement.columnMap) > 0 && !session.statement.columnMap.contain(col.Name) {
  447. continue
  448. }
  449. if session.statement.incrColumns.isColExist(col.Name) {
  450. continue
  451. } else if session.statement.decrColumns.isColExist(col.Name) {
  452. continue
  453. } else if session.statement.exprColumns.isColExist(col.Name) {
  454. continue
  455. }
  456. // !evalphobia! set fieldValue as nil when column is nullable and zero-value
  457. if _, ok := getFlagForColumn(session.statement.nullableMap, col); ok {
  458. if col.Nullable && isZero(fieldValue.Interface()) {
  459. var nilValue *int
  460. fieldValue = reflect.ValueOf(nilValue)
  461. }
  462. }
  463. if col.IsUpdated && session.statement.UseAutoTime /*&& isZero(fieldValue.Interface())*/ {
  464. // if time is non-empty, then set to auto time
  465. val, t := session.engine.nowTime(col)
  466. args = append(args, val)
  467. var colName = col.Name
  468. session.afterClosures = append(session.afterClosures, func(bean interface{}) {
  469. col := table.GetColumn(colName)
  470. setColumnTime(bean, col, t)
  471. })
  472. } else if col.IsVersion && session.statement.checkVersion {
  473. args = append(args, 1)
  474. } else {
  475. arg, err := session.value2Interface(col, fieldValue)
  476. if err != nil {
  477. return colNames, args, err
  478. }
  479. args = append(args, arg)
  480. }
  481. colNames = append(colNames, session.engine.Quote(col.Name)+" = ?")
  482. }
  483. return colNames, args, nil
  484. }