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.

50 lines
2.5 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 TestJoin(t *testing.T) {
  10. sql, args, err := Select("c, d").From("table1").LeftJoin("table2", Eq{"table1.id": 1}.And(Lt{"table2.id": 3})).
  11. RightJoin("table3", "table2.id = table3.tid").Where(Eq{"a": 1}).ToSQL()
  12. assert.NoError(t, err)
  13. assert.EqualValues(t, "SELECT c, d FROM table1 LEFT JOIN table2 ON table1.id=? AND table2.id<? RIGHT JOIN table3 ON table2.id = table3.tid WHERE a=?",
  14. sql)
  15. assert.EqualValues(t, []interface{}{1, 3, 1}, args)
  16. sql, args, err = Select("c, d").From("table1").LeftJoin("table2", Eq{"table1.id": 1}.And(Lt{"table2.id": 3})).
  17. FullJoin("table3", "table2.id = table3.tid").Where(Eq{"a": 1}).ToSQL()
  18. assert.NoError(t, err)
  19. assert.EqualValues(t, "SELECT c, d FROM table1 LEFT JOIN table2 ON table1.id=? AND table2.id<? FULL JOIN table3 ON table2.id = table3.tid WHERE a=?",
  20. sql)
  21. assert.EqualValues(t, []interface{}{1, 3, 1}, args)
  22. sql, args, err = Select("c, d").From("table1").LeftJoin("table2", Eq{"table1.id": 1}.And(Lt{"table2.id": 3})).
  23. CrossJoin("table3", "table2.id = table3.tid").Where(Eq{"a": 1}).ToSQL()
  24. assert.NoError(t, err)
  25. assert.EqualValues(t, "SELECT c, d FROM table1 LEFT JOIN table2 ON table1.id=? AND table2.id<? CROSS JOIN table3 ON table2.id = table3.tid WHERE a=?",
  26. sql)
  27. assert.EqualValues(t, []interface{}{1, 3, 1}, args)
  28. sql, args, err = Select("c, d").From("table1").LeftJoin("table2", Eq{"table1.id": 1}.And(Lt{"table2.id": 3})).
  29. InnerJoin("table3", "table2.id = table3.tid").Where(Eq{"a": 1}).ToSQL()
  30. assert.NoError(t, err)
  31. assert.EqualValues(t, "SELECT c, d FROM table1 LEFT JOIN table2 ON table1.id=? AND table2.id<? INNER JOIN table3 ON table2.id = table3.tid WHERE a=?",
  32. sql)
  33. assert.EqualValues(t, []interface{}{1, 3, 1}, args)
  34. subQuery2 := Select("e").From("table2").Where(Gt{"e": 1})
  35. subQuery3 := Select("f").From("table3").Where(Gt{"f": "2"})
  36. sql, args, err = Select("c, d").From("table1").LeftJoin(subQuery2, Eq{"table1.id": 1}.And(Lt{"table2.id": 3})).
  37. InnerJoin(subQuery3, "table2.id = table3.tid").Where(Eq{"a": 1}).ToSQL()
  38. assert.NoError(t, err)
  39. assert.EqualValues(t, "SELECT c, d FROM table1 LEFT JOIN (SELECT e FROM table2 WHERE e>?) ON table1.id=? AND table2.id<? INNER JOIN (SELECT f FROM table3 WHERE f>?) ON table2.id = table3.tid WHERE a=?",
  40. sql)
  41. assert.EqualValues(t, []interface{}{1, 1, 3, "2", 1}, args)
  42. }