2017-01-03 09:20:28 +01:00
|
|
|
// Copyright 2016 The Xorm Authors. All rights reserved.
|
|
|
|
// Use of this source code is governed by a BSD-style
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
|
|
|
package xorm
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"reflect"
|
|
|
|
"strconv"
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
"github.com/go-xorm/builder"
|
|
|
|
"github.com/go-xorm/core"
|
|
|
|
)
|
|
|
|
|
|
|
|
func (session *Session) cacheUpdate(sqlStr string, args ...interface{}) error {
|
2017-08-22 13:39:52 +02:00
|
|
|
if session.statement.RefTable == nil ||
|
|
|
|
session.tx != nil {
|
2017-01-03 09:20:28 +01:00
|
|
|
return ErrCacheFailed
|
|
|
|
}
|
|
|
|
|
2017-08-22 13:39:52 +02:00
|
|
|
oldhead, newsql := session.statement.convertUpdateSQL(sqlStr)
|
2017-01-03 09:20:28 +01:00
|
|
|
if newsql == "" {
|
|
|
|
return ErrCacheFailed
|
|
|
|
}
|
2017-08-22 13:39:52 +02:00
|
|
|
for _, filter := range session.engine.dialect.Filters() {
|
|
|
|
newsql = filter.Do(newsql, session.engine.dialect, session.statement.RefTable)
|
2017-01-03 09:20:28 +01:00
|
|
|
}
|
2017-08-22 13:39:52 +02:00
|
|
|
session.engine.logger.Debug("[cacheUpdate] new sql", oldhead, newsql)
|
2017-01-03 09:20:28 +01:00
|
|
|
|
|
|
|
var nStart int
|
|
|
|
if len(args) > 0 {
|
|
|
|
if strings.Index(sqlStr, "?") > -1 {
|
|
|
|
nStart = strings.Count(oldhead, "?")
|
|
|
|
} else {
|
|
|
|
// only for pq, TODO: if any other databse?
|
|
|
|
nStart = strings.Count(oldhead, "$")
|
|
|
|
}
|
|
|
|
}
|
2017-08-22 13:39:52 +02:00
|
|
|
table := session.statement.RefTable
|
|
|
|
cacher := session.engine.getCacher2(table)
|
|
|
|
tableName := session.statement.TableName()
|
|
|
|
session.engine.logger.Debug("[cacheUpdate] get cache sql", newsql, args[nStart:])
|
2017-01-03 09:20:28 +01:00
|
|
|
ids, err := core.GetCacheSql(cacher, tableName, newsql, args[nStart:])
|
|
|
|
if err != nil {
|
|
|
|
rows, err := session.DB().Query(newsql, args[nStart:]...)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer rows.Close()
|
|
|
|
|
|
|
|
ids = make([]core.PK, 0)
|
|
|
|
for rows.Next() {
|
|
|
|
var res = make([]string, len(table.PrimaryKeys))
|
|
|
|
err = rows.ScanSlice(&res)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
var pk core.PK = make([]interface{}, len(table.PrimaryKeys))
|
|
|
|
for i, col := range table.PKColumns() {
|
|
|
|
if col.SQLType.IsNumeric() {
|
|
|
|
n, err := strconv.ParseInt(res[i], 10, 64)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
pk[i] = n
|
|
|
|
} else if col.SQLType.IsText() {
|
|
|
|
pk[i] = res[i]
|
|
|
|
} else {
|
|
|
|
return errors.New("not supported")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
ids = append(ids, pk)
|
|
|
|
}
|
2017-08-22 13:39:52 +02:00
|
|
|
session.engine.logger.Debug("[cacheUpdate] find updated id", ids)
|
2017-01-03 09:20:28 +01:00
|
|
|
} /*else {
|
2017-08-22 13:39:52 +02:00
|
|
|
session.engine.LogDebug("[xorm:cacheUpdate] del cached sql:", tableName, newsql, args)
|
2017-01-03 09:20:28 +01:00
|
|
|
cacher.DelIds(tableName, genSqlKey(newsql, args))
|
|
|
|
}*/
|
|
|
|
|
|
|
|
for _, id := range ids {
|
|
|
|
sid, err := id.ToString()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if bean := cacher.GetBean(tableName, sid); bean != nil {
|
|
|
|
sqls := splitNNoCase(sqlStr, "where", 2)
|
|
|
|
if len(sqls) == 0 || len(sqls) > 2 {
|
|
|
|
return ErrCacheFailed
|
|
|
|
}
|
|
|
|
|
|
|
|
sqls = splitNNoCase(sqls[0], "set", 2)
|
|
|
|
if len(sqls) != 2 {
|
|
|
|
return ErrCacheFailed
|
|
|
|
}
|
|
|
|
kvs := strings.Split(strings.TrimSpace(sqls[1]), ",")
|
|
|
|
for idx, kv := range kvs {
|
|
|
|
sps := strings.SplitN(kv, "=", 2)
|
|
|
|
sps2 := strings.Split(sps[0], ".")
|
|
|
|
colName := sps2[len(sps2)-1]
|
|
|
|
if strings.Contains(colName, "`") {
|
|
|
|
colName = strings.TrimSpace(strings.Replace(colName, "`", "", -1))
|
2017-08-22 13:39:52 +02:00
|
|
|
} else if strings.Contains(colName, session.engine.QuoteStr()) {
|
|
|
|
colName = strings.TrimSpace(strings.Replace(colName, session.engine.QuoteStr(), "", -1))
|
2017-01-03 09:20:28 +01:00
|
|
|
} else {
|
2017-08-22 13:39:52 +02:00
|
|
|
session.engine.logger.Debug("[cacheUpdate] cannot find column", tableName, colName)
|
2017-01-03 09:20:28 +01:00
|
|
|
return ErrCacheFailed
|
|
|
|
}
|
|
|
|
|
|
|
|
if col := table.GetColumn(colName); col != nil {
|
|
|
|
fieldValue, err := col.ValueOf(bean)
|
|
|
|
if err != nil {
|
2017-08-22 13:39:52 +02:00
|
|
|
session.engine.logger.Error(err)
|
2017-01-03 09:20:28 +01:00
|
|
|
} else {
|
2017-08-22 13:39:52 +02:00
|
|
|
session.engine.logger.Debug("[cacheUpdate] set bean field", bean, colName, fieldValue.Interface())
|
|
|
|
if col.IsVersion && session.statement.checkVersion {
|
2017-01-03 09:20:28 +01:00
|
|
|
fieldValue.SetInt(fieldValue.Int() + 1)
|
|
|
|
} else {
|
|
|
|
fieldValue.Set(reflect.ValueOf(args[idx]))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
} else {
|
2017-08-22 13:39:52 +02:00
|
|
|
session.engine.logger.Errorf("[cacheUpdate] ERROR: column %v is not table %v's",
|
2017-01-03 09:20:28 +01:00
|
|
|
colName, table.Name)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-08-22 13:39:52 +02:00
|
|
|
session.engine.logger.Debug("[cacheUpdate] update cache", tableName, id, bean)
|
2017-01-03 09:20:28 +01:00
|
|
|
cacher.PutBean(tableName, sid, bean)
|
|
|
|
}
|
|
|
|
}
|
2017-08-22 13:39:52 +02:00
|
|
|
session.engine.logger.Debug("[cacheUpdate] clear cached table sql:", tableName)
|
2017-01-03 09:20:28 +01:00
|
|
|
cacher.ClearIds(tableName)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Update records, bean's non-empty fields are updated contents,
|
|
|
|
// condiBean' non-empty filds are conditions
|
|
|
|
// CAUTION:
|
|
|
|
// 1.bool will defaultly be updated content nor conditions
|
|
|
|
// You should call UseBool if you have bool to use.
|
|
|
|
// 2.float32 & float64 may be not inexact as conditions
|
|
|
|
func (session *Session) Update(bean interface{}, condiBean ...interface{}) (int64, error) {
|
|
|
|
defer session.resetStatement()
|
2017-08-22 13:39:52 +02:00
|
|
|
if session.isAutoClose {
|
2017-01-03 09:20:28 +01:00
|
|
|
defer session.Close()
|
|
|
|
}
|
|
|
|
|
|
|
|
v := rValue(bean)
|
|
|
|
t := v.Type()
|
|
|
|
|
|
|
|
var colNames []string
|
|
|
|
var args []interface{}
|
|
|
|
|
|
|
|
// handle before update processors
|
|
|
|
for _, closure := range session.beforeClosures {
|
|
|
|
closure(bean)
|
|
|
|
}
|
|
|
|
cleanupProcessorsClosures(&session.beforeClosures) // cleanup after used
|
|
|
|
if processor, ok := interface{}(bean).(BeforeUpdateProcessor); ok {
|
|
|
|
processor.BeforeUpdate()
|
|
|
|
}
|
|
|
|
// --
|
|
|
|
|
|
|
|
var err error
|
|
|
|
var isMap = t.Kind() == reflect.Map
|
|
|
|
var isStruct = t.Kind() == reflect.Struct
|
|
|
|
if isStruct {
|
2017-08-22 13:39:52 +02:00
|
|
|
if err := session.statement.setRefValue(v); err != nil {
|
2017-05-02 02:50:33 +02:00
|
|
|
return 0, err
|
|
|
|
}
|
2017-01-03 09:20:28 +01:00
|
|
|
|
2017-08-22 13:39:52 +02:00
|
|
|
if len(session.statement.TableName()) <= 0 {
|
2017-01-03 09:20:28 +01:00
|
|
|
return 0, ErrTableNotFound
|
|
|
|
}
|
|
|
|
|
2017-08-22 13:39:52 +02:00
|
|
|
if session.statement.ColumnStr == "" {
|
|
|
|
colNames, args = buildUpdates(session.engine, session.statement.RefTable, bean, false, false,
|
|
|
|
false, false, session.statement.allUseBool, session.statement.useAllCols,
|
|
|
|
session.statement.mustColumnMap, session.statement.nullableMap,
|
|
|
|
session.statement.columnMap, true, session.statement.unscoped)
|
2017-01-03 09:20:28 +01:00
|
|
|
} else {
|
2017-08-22 13:39:52 +02:00
|
|
|
colNames, args, err = genCols(session.statement.RefTable, session, bean, true, true)
|
2017-01-03 09:20:28 +01:00
|
|
|
if err != nil {
|
|
|
|
return 0, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
} else if isMap {
|
|
|
|
colNames = make([]string, 0)
|
|
|
|
args = make([]interface{}, 0)
|
|
|
|
bValue := reflect.Indirect(reflect.ValueOf(bean))
|
|
|
|
|
|
|
|
for _, v := range bValue.MapKeys() {
|
2017-08-22 13:39:52 +02:00
|
|
|
colNames = append(colNames, session.engine.Quote(v.String())+" = ?")
|
2017-01-03 09:20:28 +01:00
|
|
|
args = append(args, bValue.MapIndex(v).Interface())
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
return 0, ErrParamsType
|
|
|
|
}
|
|
|
|
|
2017-08-22 13:39:52 +02:00
|
|
|
table := session.statement.RefTable
|
2017-01-03 09:20:28 +01:00
|
|
|
|
2017-08-22 13:39:52 +02:00
|
|
|
if session.statement.UseAutoTime && table != nil && table.Updated != "" {
|
|
|
|
colNames = append(colNames, session.engine.Quote(table.Updated)+" = ?")
|
2017-01-03 09:20:28 +01:00
|
|
|
col := table.UpdatedColumn()
|
2017-08-22 13:39:52 +02:00
|
|
|
val, t := session.engine.NowTime2(col.SQLType.Name)
|
2017-01-03 09:20:28 +01:00
|
|
|
args = append(args, val)
|
|
|
|
|
|
|
|
var colName = col.Name
|
|
|
|
if isStruct {
|
|
|
|
session.afterClosures = append(session.afterClosures, func(bean interface{}) {
|
|
|
|
col := table.GetColumn(colName)
|
|
|
|
setColumnTime(bean, col, t)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
//for update action to like "column = column + ?"
|
2017-08-22 13:39:52 +02:00
|
|
|
incColumns := session.statement.getInc()
|
2017-01-03 09:20:28 +01:00
|
|
|
for _, v := range incColumns {
|
2017-08-22 13:39:52 +02:00
|
|
|
colNames = append(colNames, session.engine.Quote(v.colName)+" = "+session.engine.Quote(v.colName)+" + ?")
|
2017-01-03 09:20:28 +01:00
|
|
|
args = append(args, v.arg)
|
|
|
|
}
|
|
|
|
//for update action to like "column = column - ?"
|
2017-08-22 13:39:52 +02:00
|
|
|
decColumns := session.statement.getDec()
|
2017-01-03 09:20:28 +01:00
|
|
|
for _, v := range decColumns {
|
2017-08-22 13:39:52 +02:00
|
|
|
colNames = append(colNames, session.engine.Quote(v.colName)+" = "+session.engine.Quote(v.colName)+" - ?")
|
2017-01-03 09:20:28 +01:00
|
|
|
args = append(args, v.arg)
|
|
|
|
}
|
|
|
|
//for update action to like "column = expression"
|
2017-08-22 13:39:52 +02:00
|
|
|
exprColumns := session.statement.getExpr()
|
2017-01-03 09:20:28 +01:00
|
|
|
for _, v := range exprColumns {
|
2017-08-22 13:39:52 +02:00
|
|
|
colNames = append(colNames, session.engine.Quote(v.colName)+" = "+v.expr)
|
2017-01-03 09:20:28 +01:00
|
|
|
}
|
|
|
|
|
2017-08-22 13:39:52 +02:00
|
|
|
if err = session.statement.processIDParam(); err != nil {
|
|
|
|
return 0, err
|
|
|
|
}
|
2017-01-03 09:20:28 +01:00
|
|
|
|
|
|
|
var autoCond builder.Cond
|
2017-08-22 13:39:52 +02:00
|
|
|
if !session.statement.noAutoCondition && len(condiBean) > 0 {
|
2017-01-03 09:20:28 +01:00
|
|
|
var err error
|
2017-08-22 13:39:52 +02:00
|
|
|
autoCond, err = session.statement.buildConds(session.statement.RefTable, condiBean[0], true, true, false, true, false)
|
2017-01-03 09:20:28 +01:00
|
|
|
if err != nil {
|
|
|
|
return 0, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-08-22 13:39:52 +02:00
|
|
|
st := session.statement
|
2017-01-03 09:20:28 +01:00
|
|
|
defer session.resetStatement()
|
|
|
|
|
|
|
|
var sqlStr string
|
|
|
|
var condArgs []interface{}
|
|
|
|
var condSQL string
|
2017-08-22 13:39:52 +02:00
|
|
|
cond := session.statement.cond.And(autoCond)
|
2017-01-03 09:20:28 +01:00
|
|
|
|
2017-08-22 13:39:52 +02:00
|
|
|
var doIncVer = (table != nil && table.Version != "" && session.statement.checkVersion)
|
2017-01-03 09:20:28 +01:00
|
|
|
var verValue *reflect.Value
|
2017-04-07 03:47:25 +02:00
|
|
|
if doIncVer {
|
2017-01-03 09:20:28 +01:00
|
|
|
verValue, err = table.VersionColumn().ValueOf(bean)
|
|
|
|
if err != nil {
|
|
|
|
return 0, err
|
|
|
|
}
|
|
|
|
|
2017-08-22 13:39:52 +02:00
|
|
|
cond = cond.And(builder.Eq{session.engine.Quote(table.Version): verValue.Interface()})
|
|
|
|
colNames = append(colNames, session.engine.Quote(table.Version)+" = "+session.engine.Quote(table.Version)+" + 1")
|
|
|
|
}
|
|
|
|
|
|
|
|
condSQL, condArgs, err = builder.ToSQL(cond)
|
|
|
|
if err != nil {
|
|
|
|
return 0, err
|
2017-04-07 03:47:25 +02:00
|
|
|
}
|
2017-01-03 09:20:28 +01:00
|
|
|
|
2017-04-07 03:47:25 +02:00
|
|
|
if len(condSQL) > 0 {
|
|
|
|
condSQL = "WHERE " + condSQL
|
|
|
|
}
|
2017-01-03 09:20:28 +01:00
|
|
|
|
2017-04-07 03:47:25 +02:00
|
|
|
if st.OrderStr != "" {
|
|
|
|
condSQL = condSQL + fmt.Sprintf(" ORDER BY %v", st.OrderStr)
|
|
|
|
}
|
2017-01-03 09:20:28 +01:00
|
|
|
|
2017-04-07 03:47:25 +02:00
|
|
|
// TODO: Oracle support needed
|
|
|
|
var top string
|
|
|
|
if st.LimitN > 0 {
|
|
|
|
if st.Engine.dialect.DBType() == core.MYSQL {
|
2017-01-03 09:20:28 +01:00
|
|
|
condSQL = condSQL + fmt.Sprintf(" LIMIT %d", st.LimitN)
|
2017-04-07 03:47:25 +02:00
|
|
|
} else if st.Engine.dialect.DBType() == core.SQLITE {
|
|
|
|
tempCondSQL := condSQL + fmt.Sprintf(" LIMIT %d", st.LimitN)
|
|
|
|
cond = cond.And(builder.Expr(fmt.Sprintf("rowid IN (SELECT rowid FROM %v %v)",
|
2017-08-22 13:39:52 +02:00
|
|
|
session.engine.Quote(session.statement.TableName()), tempCondSQL), condArgs...))
|
|
|
|
condSQL, condArgs, err = builder.ToSQL(cond)
|
|
|
|
if err != nil {
|
|
|
|
return 0, err
|
|
|
|
}
|
2017-04-07 03:47:25 +02:00
|
|
|
if len(condSQL) > 0 {
|
|
|
|
condSQL = "WHERE " + condSQL
|
|
|
|
}
|
|
|
|
} else if st.Engine.dialect.DBType() == core.POSTGRES {
|
|
|
|
tempCondSQL := condSQL + fmt.Sprintf(" LIMIT %d", st.LimitN)
|
|
|
|
cond = cond.And(builder.Expr(fmt.Sprintf("CTID IN (SELECT CTID FROM %v %v)",
|
2017-08-22 13:39:52 +02:00
|
|
|
session.engine.Quote(session.statement.TableName()), tempCondSQL), condArgs...))
|
|
|
|
condSQL, condArgs, err = builder.ToSQL(cond)
|
|
|
|
if err != nil {
|
|
|
|
return 0, err
|
|
|
|
}
|
|
|
|
|
2017-04-07 03:47:25 +02:00
|
|
|
if len(condSQL) > 0 {
|
|
|
|
condSQL = "WHERE " + condSQL
|
|
|
|
}
|
|
|
|
} else if st.Engine.dialect.DBType() == core.MSSQL {
|
2017-08-22 13:39:52 +02:00
|
|
|
if st.OrderStr != "" && st.Engine.dialect.DBType() == core.MSSQL &&
|
|
|
|
table != nil && len(table.PrimaryKeys) == 1 {
|
|
|
|
cond = builder.Expr(fmt.Sprintf("%s IN (SELECT TOP (%d) %s FROM %v%v)",
|
|
|
|
table.PrimaryKeys[0], st.LimitN, table.PrimaryKeys[0],
|
|
|
|
session.engine.Quote(session.statement.TableName()), condSQL), condArgs...)
|
|
|
|
|
|
|
|
condSQL, condArgs, err = builder.ToSQL(cond)
|
|
|
|
if err != nil {
|
|
|
|
return 0, err
|
|
|
|
}
|
|
|
|
if len(condSQL) > 0 {
|
|
|
|
condSQL = "WHERE " + condSQL
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
top = fmt.Sprintf("TOP (%d) ", st.LimitN)
|
|
|
|
}
|
2017-01-03 09:20:28 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-08-22 13:39:52 +02:00
|
|
|
if len(colNames) <= 0 {
|
|
|
|
return 0, errors.New("No content found to be updated")
|
|
|
|
}
|
|
|
|
|
2017-04-07 03:47:25 +02:00
|
|
|
sqlStr = fmt.Sprintf("UPDATE %v%v SET %v %v",
|
|
|
|
top,
|
2017-08-22 13:39:52 +02:00
|
|
|
session.engine.Quote(session.statement.TableName()),
|
2017-04-07 03:47:25 +02:00
|
|
|
strings.Join(colNames, ", "),
|
|
|
|
condSQL)
|
|
|
|
|
2017-01-03 09:20:28 +01:00
|
|
|
res, err := session.exec(sqlStr, append(args, condArgs...)...)
|
|
|
|
if err != nil {
|
|
|
|
return 0, err
|
|
|
|
} else if doIncVer {
|
|
|
|
if verValue != nil && verValue.IsValid() && verValue.CanSet() {
|
|
|
|
verValue.SetInt(verValue.Int() + 1)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if table != nil {
|
2017-08-22 13:39:52 +02:00
|
|
|
if cacher := session.engine.getCacher2(table); cacher != nil && session.statement.UseCache {
|
|
|
|
cacher.ClearIds(session.statement.TableName())
|
|
|
|
cacher.ClearBeans(session.statement.TableName())
|
2017-01-03 09:20:28 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// handle after update processors
|
2017-08-22 13:39:52 +02:00
|
|
|
if session.isAutoCommit {
|
2017-01-03 09:20:28 +01:00
|
|
|
for _, closure := range session.afterClosures {
|
|
|
|
closure(bean)
|
|
|
|
}
|
|
|
|
if processor, ok := interface{}(bean).(AfterUpdateProcessor); ok {
|
2017-08-22 13:39:52 +02:00
|
|
|
session.engine.logger.Debug("[event]", session.statement.TableName(), " has after update processor")
|
2017-01-03 09:20:28 +01:00
|
|
|
processor.AfterUpdate()
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
lenAfterClosures := len(session.afterClosures)
|
|
|
|
if lenAfterClosures > 0 {
|
|
|
|
if value, has := session.afterUpdateBeans[bean]; has && value != nil {
|
|
|
|
*value = append(*value, session.afterClosures...)
|
|
|
|
} else {
|
|
|
|
afterClosures := make([]func(interface{}), lenAfterClosures)
|
|
|
|
copy(afterClosures, session.afterClosures)
|
|
|
|
// FIXME: if bean is a map type, it will panic because map cannot be as map key
|
|
|
|
session.afterUpdateBeans[bean] = &afterClosures
|
|
|
|
}
|
|
|
|
|
|
|
|
} else {
|
2017-01-25 15:54:52 +01:00
|
|
|
if _, ok := interface{}(bean).(AfterUpdateProcessor); ok {
|
2017-01-03 09:20:28 +01:00
|
|
|
session.afterUpdateBeans[bean] = nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
cleanupProcessorsClosures(&session.afterClosures) // cleanup after used
|
|
|
|
// --
|
|
|
|
|
|
|
|
return res.RowsAffected()
|
|
|
|
}
|