args_test.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // Copyright 2018 Huan Du. All rights reserved.
  2. // Licensed under the MIT license that can be found in the LICENSE file.
  3. package sqlbuilder
  4. import (
  5. "bytes"
  6. "fmt"
  7. "strings"
  8. "testing"
  9. )
  10. func TestArgs(t *testing.T) {
  11. cases := map[string][]interface{}{
  12. "abc ? def\n[123]": {"abc $? def", 123},
  13. "abc ? def\n[456]": {"abc $0 def", 456},
  14. "abc def\n[]": {"abc $1 def", 123},
  15. "abc ? def\n[789]": {"abc ${s} def", Named("s", 789)},
  16. "abc def \n[]": {"abc ${unknown} def ", 123},
  17. "abc $ def\n[]": {"abc $$ def", 123},
  18. "abcdef\n[]": {"abcdef$", 123},
  19. "abc ? ? ? ? def\n[123 456 123 456]": {"abc $? $? $0 $? def", 123, 456, 789},
  20. "abc ? raw ? raw def\n[123 123]": {"abc $? $? $0 $? def", 123, Raw("raw"), 789},
  21. }
  22. for expected, c := range cases {
  23. args := new(Args)
  24. for i := 1; i < len(c); i++ {
  25. args.Add(c[i])
  26. }
  27. sql, values := args.Compile(c[0].(string))
  28. actual := fmt.Sprintf("%v\n%v", sql, values)
  29. if actual != expected {
  30. t.Fatalf("invalid compile result. [expected:%v] [actual:%v]", expected, actual)
  31. }
  32. }
  33. old := DefaultFlavor
  34. DefaultFlavor = PostgreSQL
  35. defer func() {
  36. DefaultFlavor = old
  37. }()
  38. // PostgreSQL flavor compiled sql.
  39. for expected, c := range cases {
  40. args := new(Args)
  41. for i := 1; i < len(c); i++ {
  42. args.Add(c[i])
  43. }
  44. sql, values := args.Compile(c[0].(string))
  45. actual := fmt.Sprintf("%v\n%v", sql, values)
  46. expected = toPostgreSQL(expected)
  47. if actual != expected {
  48. t.Fatalf("invalid compile result. [expected:%v] [actual:%v]", expected, actual)
  49. }
  50. }
  51. }
  52. func toPostgreSQL(sql string) string {
  53. parts := strings.Split(sql, "?")
  54. buf := &bytes.Buffer{}
  55. buf.WriteString(parts[0])
  56. for i, p := range parts[1:] {
  57. fmt.Fprintf(buf, "$%v", i+1)
  58. buf.WriteString(p)
  59. }
  60. return buf.String()
  61. }