database_clause_test.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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 ?) AND (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([]clause.Clause{
  28. clause.NewConditions().
  29. Equal("name", "test").
  30. In("hobby", []string{"football", "basketball"}).
  31. And(),
  32. clause.NewConditions().
  33. Equal("age", 18).
  34. Equal("gender", "male").
  35. Or(),
  36. }),
  37. clause.NewOrderBy("name", false),
  38. clause.NewLimit(1, 10),
  39. }...)
  40. selectClauseStr, err := selectClause.Clause()
  41. if err != nil {
  42. t.Fatal(err)
  43. }
  44. if exceptSql != selectClauseStr {
  45. t.Errorf("%+v\n", errors.Errorf("except: %s\nactual: %s", exceptSql, selectClauseStr))
  46. }
  47. args := selectClause.Args()
  48. if len(args) != 6 {
  49. t.Errorf("%+v\n", errors.Errorf("args len: %d", len(args)))
  50. }
  51. if args[0] != "test" {
  52. t.Errorf("%+v\n", errors.Errorf("args[0]: %s", args[0]))
  53. }
  54. if args[1].([]string)[0] != "football" {
  55. t.Errorf("%+v\n", errors.Errorf("args[1]: %s", args[1]))
  56. }
  57. if args[1].([]string)[1] != "basketball" {
  58. t.Errorf("%+v\n", errors.Errorf("args[1]: %s", args[1]))
  59. }
  60. if args[2] != 18 {
  61. t.Errorf("%+v\n", errors.Errorf("args[2]: %s", args[2]))
  62. }
  63. if args[3] != "male" {
  64. t.Errorf("%+v\n", errors.Errorf("args[3]: %s", args[3]))
  65. }
  66. if args[4] != 10 {
  67. t.Errorf("%+v\n", errors.Errorf("args[4]: %s", args[4]))
  68. }
  69. if args[5] != 0 {
  70. t.Errorf("%+v\n", errors.Errorf("args[5]: %s", args[5]))
  71. }
  72. }