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.
 
 
 
 

529 regels
15 KiB

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