builder_insert_test.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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 TestBuilderInsert(t *testing.T) {
  10. sql, err := Insert(Eq{"c": 1, "d": 2}).Into("table1").ToBoundSQL()
  11. assert.NoError(t, err)
  12. assert.EqualValues(t, "INSERT INTO table1 (c,d) Values (1,2)", sql)
  13. sql, err = Insert(Eq{"e": 3}, Eq{"c": 1}, Eq{"d": 2}).Into("table1").ToBoundSQL()
  14. assert.NoError(t, err)
  15. assert.EqualValues(t, "INSERT INTO table1 (c,d,e) Values (1,2,3)", sql)
  16. sql, err = Insert(Eq{"c": 1, "d": Expr("SELECT b FROM t WHERE d=? LIMIT 1", 2)}).Into("table1").ToBoundSQL()
  17. assert.NoError(t, err)
  18. assert.EqualValues(t, "INSERT INTO table1 (c,d) Values (1,(SELECT b FROM t WHERE d=2 LIMIT 1))", sql)
  19. sql, err = Insert(Eq{"c": 1, "d": 2}).ToBoundSQL()
  20. assert.Error(t, err)
  21. assert.EqualValues(t, ErrNoTableName, err)
  22. assert.EqualValues(t, "", sql)
  23. sql, err = Insert(Eq{}).Into("table1").ToBoundSQL()
  24. assert.Error(t, err)
  25. assert.EqualValues(t, ErrNoColumnToInsert, err)
  26. assert.EqualValues(t, "", sql)
  27. }
  28. func TestBuidlerInsert_Select(t *testing.T) {
  29. sql, err := Insert().Into("table1").Select().From("table2").ToBoundSQL()
  30. assert.NoError(t, err)
  31. assert.EqualValues(t, "INSERT INTO table1 SELECT * FROM table2", sql)
  32. sql, err = Insert("a, b").Into("table1").Select("b, c").From("table2").ToBoundSQL()
  33. assert.NoError(t, err)
  34. assert.EqualValues(t, "INSERT INTO table1 (a, b) SELECT b, c FROM table2", sql)
  35. }