database_clause_test.go 1.9 KB

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