database_sql_test.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package test
  2. import (
  3. "git.sxidc.com/go-framework/baize/framework/core/infrastructure/database/sql"
  4. "github.com/pkg/errors"
  5. "testing"
  6. )
  7. func TestDatabaseSqlConditions(t *testing.T) {
  8. conditions := sql.NewConditions().
  9. AddCondition("name1 = ?", "foo").
  10. Equal("age", 20).
  11. Like("name2", "%foo%").
  12. In("id1", []string{"111", "222"}).
  13. NotIn("id2", []string{"33", "444"}).
  14. Not("id3", "555").
  15. LessThan("num1", 10).
  16. LessThanAndEqual("num2", 20).
  17. GreaterThan("num3", 30).
  18. GreaterThanAndEqual("num4", 40)
  19. exceptQueries := []string{
  20. `name1 = ?`,
  21. `"age" = ?`,
  22. `"name2" LIKE ?`,
  23. `"id1" IN ?`,
  24. `"id2" NOT IN ?`,
  25. `"id3" != ?`,
  26. `"num1" < ?`,
  27. `"num2" <= ?`,
  28. `"num3" > ?`,
  29. `"num4" >= ?`,
  30. }
  31. exceptArgs := []any{
  32. "foo",
  33. 20,
  34. "%foo%",
  35. []string{"111", "222"},
  36. []string{"33", "444"},
  37. "555",
  38. 10,
  39. 20,
  40. 30,
  41. 40,
  42. }
  43. exceptAnd := `WHERE name1 = ? AND "age" = ? AND "name2" LIKE ? AND "id1" IN ? AND "id2" NOT IN ? AND "id3" != ? AND "num1" < ? AND "num2" <= ? AND "num3" > ? AND "num4" >= ?`
  44. for i, query := range conditions.Queries() {
  45. if exceptQueries[i] != query {
  46. t.Fatalf("%+v\n", errors.Errorf("Query Error: except %v, actural %v",
  47. exceptQueries[i], query))
  48. }
  49. }
  50. for i, arg := range conditions.Args() {
  51. argStringSlice, ok := arg.([]string)
  52. if ok {
  53. for j, stringArg := range argStringSlice {
  54. exceptArg, ok := exceptArgs[i].([]string)
  55. if !ok {
  56. t.Fatalf("%+v\n", errors.New("参数类型不匹配"))
  57. }
  58. if exceptArg[j] != stringArg {
  59. t.Fatalf("%+v\n", errors.Errorf("Args Error: except %v, actural %v",
  60. exceptQueries[i], stringArg))
  61. }
  62. }
  63. continue
  64. }
  65. if exceptArgs[i] != arg {
  66. t.Fatalf("%+v\n", errors.Errorf("Args Error: except %v, actural %v",
  67. exceptQueries[i], arg))
  68. }
  69. }
  70. if conditions.And() != exceptAnd {
  71. t.Fatalf("%+v\n", errors.Errorf("And Error:\nexcept %v\nactural %v\n",
  72. exceptAnd, conditions.And()))
  73. }
  74. }