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.

54 lines
1.9 KiB

2 years ago
  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. sql, err = Insert(Eq{`a`: nil}).Into(`table1`).ToBoundSQL()
  28. assert.NoError(t, err)
  29. assert.EqualValues(t, `INSERT INTO table1 (a) Values (null)`, sql)
  30. sql, args, err := Insert(Eq{`a`: nil, `b`: `str`}).Into(`table1`).ToSQL()
  31. assert.NoError(t, err)
  32. assert.EqualValues(t, `INSERT INTO table1 (a,b) Values (null,?)`, sql)
  33. assert.EqualValues(t, []interface{}{`str`}, args)
  34. }
  35. func TestBuidlerInsert_Select(t *testing.T) {
  36. sql, err := Insert().Into("table1").Select().From("table2").ToBoundSQL()
  37. assert.NoError(t, err)
  38. assert.EqualValues(t, "INSERT INTO table1 SELECT * FROM table2", sql)
  39. sql, err = Insert("a, b").Into("table1").Select("b, c").From("table2").ToBoundSQL()
  40. assert.NoError(t, err)
  41. assert.EqualValues(t, "INSERT INTO table1 (a, b) SELECT b, c FROM table2", sql)
  42. }