database_clause_test.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package test
  2. import (
  3. "git.sxidc.com/go-framework/baize/framework/core/infrastructure/database/clause"
  4. "github.com/pkg/errors"
  5. "testing"
  6. )
  7. func TestDatabaseClause(t *testing.T) {
  8. exceptSql := `SELECT
  9. name,
  10. age,
  11. gender,
  12. hobby
  13. FROM
  14. test.students
  15. JOIN test.classes ON classes.id = test.students.class_id
  16. WHERE
  17. (name = ? AND hobby IN ?) OR (age = ? OR gender = ?)
  18. ORDER BY name DESC
  19. LIMIT ? OFFSET ?`
  20. selectClause := clause.NewSelect(
  21. []string{"name", "age", "gender", "hobby"},
  22. clause.NewFrom([]clause.Clause{
  23. clause.TableName("test.students"),
  24. clause.NewJoin("test.classes", "classes.id = test.students.class_id"),
  25. }),
  26. []clause.Clause{
  27. clause.NewWhere(
  28. clause.NewConditionJoin(
  29. clause.NewConditions().
  30. Equal("name", "test").
  31. In("hobby", []string{"football", "basketball"}).
  32. And(),
  33. clause.NewConditions().
  34. Equal("age", 18).
  35. Equal("gender", "male").
  36. Or(),
  37. ).Or(),
  38. ),
  39. clause.NewOrderBy("name", false),
  40. clause.NewLimit(1, 10),
  41. }...)
  42. selectClauseStr, err := selectClause.Clause()
  43. if err != nil {
  44. t.Fatal(err)
  45. }
  46. if exceptSql != selectClauseStr {
  47. t.Errorf("%+v\n", errors.Errorf("except: %s\nactual: %s", exceptSql, selectClauseStr))
  48. }
  49. args := selectClause.Args()
  50. if len(args) != 6 {
  51. t.Errorf("%+v\n", errors.Errorf("args len: %d", len(args)))
  52. }
  53. if args[0] != "test" {
  54. t.Errorf("%+v\n", errors.Errorf("args[0]: %s", args[0]))
  55. }
  56. if args[1].([]string)[0] != "football" {
  57. t.Errorf("%+v\n", errors.Errorf("args[1]: %s", args[1]))
  58. }
  59. if args[1].([]string)[1] != "basketball" {
  60. t.Errorf("%+v\n", errors.Errorf("args[1]: %s", args[1]))
  61. }
  62. if args[2] != 18 {
  63. t.Errorf("%+v\n", errors.Errorf("args[2]: %s", args[2]))
  64. }
  65. if args[3] != "male" {
  66. t.Errorf("%+v\n", errors.Errorf("args[3]: %s", args[3]))
  67. }
  68. if args[4] != 10 {
  69. t.Errorf("%+v\n", errors.Errorf("args[4]: %s", args[4]))
  70. }
  71. if args[5] != 0 {
  72. t.Errorf("%+v\n", errors.Errorf("args[5]: %s", args[5]))
  73. }
  74. }