Simple and Powerful ORM for Go, support mysql,postgres,tidb,sqlite3,mssql,oracle https://xorm.io
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

539 lines
15KB

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