builder_update_test.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // Copyright 2018 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 builder
  5. import (
  6. "testing"
  7. "github.com/stretchr/testify/assert"
  8. )
  9. func TestBuilderUpdate(t *testing.T) {
  10. sql, args, err := Update(Eq{"a": 2}).From("table1").Where(Eq{"a": 1}).ToSQL()
  11. assert.NoError(t, err)
  12. assert.EqualValues(t, "UPDATE table1 SET a=? WHERE a=?", sql)
  13. assert.EqualValues(t, []interface{}{2, 1}, args)
  14. sql, args, err = Update(Eq{"a": 2, "b": 1}).From("table1").Where(Eq{"a": 1}).ToSQL()
  15. assert.NoError(t, err)
  16. assert.EqualValues(t, "UPDATE table1 SET a=?,b=? WHERE a=?", sql)
  17. assert.EqualValues(t, []interface{}{2, 1, 1}, args)
  18. sql, args, err = Update(Eq{"a": 2}, Eq{"b": 1}).From("table1").Where(Eq{"a": 1}).ToSQL()
  19. assert.NoError(t, err)
  20. assert.EqualValues(t, "UPDATE table1 SET a=?,b=? WHERE a=?", sql)
  21. assert.EqualValues(t, []interface{}{2, 1, 1}, args)
  22. sql, args, err = Update(Eq{"a": 2, "b": Incr(1)}).From("table2").Where(Eq{"a": 1}).ToSQL()
  23. assert.NoError(t, err)
  24. assert.EqualValues(t, "UPDATE table2 SET a=?,b=b+? WHERE a=?", sql)
  25. assert.EqualValues(t, []interface{}{2, 1, 1}, args)
  26. sql, args, err = Update(Eq{"a": 2, "b": Incr(1), "c": Decr(1), "d": Expr("select count(*) from table2")}).From("table2").Where(Eq{"a": 1}).ToSQL()
  27. assert.NoError(t, err)
  28. assert.EqualValues(t, "UPDATE table2 SET a=?,b=b+?,c=c-?,d=(select count(*) from table2) WHERE a=?", sql)
  29. assert.EqualValues(t, []interface{}{2, 1, 1, 1}, args)
  30. sql, args, err = Update(Eq{"a": 2}).Where(Eq{"a": 1}).ToSQL()
  31. assert.Error(t, err)
  32. assert.EqualValues(t, ErrNoTableName, err)
  33. sql, args, err = Update(Eq{}).From("table1").Where(Eq{"a": 1}).ToSQL()
  34. assert.Error(t, err)
  35. assert.EqualValues(t, ErrNoColumnToUpdate, err)
  36. var builder = Builder{cond: NewCond()}
  37. sql, args, err = builder.Update(Eq{"a": 2, "b": 1}).From("table1").Where(Eq{"a": 1}).ToSQL()
  38. assert.NoError(t, err)
  39. assert.EqualValues(t, "UPDATE table1 SET a=?,b=? WHERE a=?", sql)
  40. assert.EqualValues(t, []interface{}{2, 1, 1}, args)
  41. sql, args, err = Update(Eq{"a": 1}, Expr("c = c+1")).From("table1").Where(Eq{"b": 2}).ToSQL()
  42. assert.NoError(t, err)
  43. assert.EqualValues(t, "UPDATE table1 SET a=?,c = c+1 WHERE b=?", sql)
  44. assert.EqualValues(t, []interface{}{1, 2}, args)
  45. }