Browse Source

Fix update with Alias (#1455)

master
Lunny Xiao 3 weeks ago
parent
commit
c349d36e95
2 changed files with 46 additions and 2 deletions
  1. +15
    -2
      session_update.go
  2. +31
    -0
      session_update_test.go

+ 15
- 2
session_update.go View File

@@ -377,10 +377,23 @@ func (session *Session) Update(bean interface{}, condiBean ...interface{}) (int6
return 0, errors.New("No content found to be updated")
}

sqlStr = fmt.Sprintf("UPDATE %v%v SET %v %v",
var tableAlias = session.engine.Quote(tableName)
var fromSQL string
if session.statement.TableAlias != "" {
switch session.engine.dialect.DBType() {
case core.MSSQL:
fromSQL = fmt.Sprintf("FROM %s %s ", tableAlias, session.statement.TableAlias)
tableAlias = session.statement.TableAlias
default:
tableAlias = fmt.Sprintf("%s AS %s", tableAlias, session.statement.TableAlias)
}
}

sqlStr = fmt.Sprintf("UPDATE %v%v SET %v %v%v",
top,
session.engine.Quote(tableName),
tableAlias,
strings.Join(colNames, ", "),
fromSQL,
condSQL)

res, err := session.exec(sqlStr, append(args, condArgs...)...)


+ 31
- 0
session_update_test.go View File

@@ -1328,3 +1328,34 @@ func TestUpdateExprs(t *testing.T) {
assert.EqualValues(t, 2, ue.NumIssues)
assert.EqualValues(t, "lunny xiao", ue.Name)
}

func TestUpdateAlias(t *testing.T) {
assert.NoError(t, prepareEngine())

type UpdateAlias struct {
Id int64
NumIssues int
Name string
}

assertSync(t, new(UpdateAlias))

_, err := testEngine.Insert(&UpdateAlias{
NumIssues: 1,
Name: "lunny",
})
assert.NoError(t, err)

_, err = testEngine.Alias("ua").Where("ua.id = ?", 1).Update(&UpdateAlias{
NumIssues: 2,
Name: "lunny xiao",
})
assert.NoError(t, err)

var ue UpdateAlias
has, err := testEngine.Get(&ue)
assert.NoError(t, err)
assert.True(t, has)
assert.EqualValues(t, 2, ue.NumIssues)
assert.EqualValues(t, "lunny xiao", ue.Name)
}

Loading…
Cancel
Save