select_test.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. "database/sql"
  6. "fmt"
  7. )
  8. func ExampleSelectBuilder() {
  9. sb := NewSelectBuilder()
  10. sb.Distinct().Select("id", "name", sb.As("COUNT(*)", "t"))
  11. sb.From("demo.user")
  12. sb.Where(
  13. sb.GreaterThan("id", 1234),
  14. sb.Like("name", "%Du"),
  15. sb.Or(
  16. sb.IsNull("id_card"),
  17. sb.In("status", 1, 2, 5),
  18. ),
  19. sb.NotIn(
  20. "id",
  21. NewSelectBuilder().Select("id").From("banned"),
  22. ), // Nested SELECT.
  23. "modified_at > created_at + "+sb.Var(86400), // It's allowed to write arbitrary SQL.
  24. )
  25. sb.GroupBy("status").Having(sb.NotIn("status", 4, 5))
  26. sb.OrderBy("modified_at").Asc()
  27. sb.Limit(10).Offset(5)
  28. sql, args := sb.Build()
  29. fmt.Println(sql)
  30. fmt.Println(args)
  31. // Output:
  32. // SELECT DISTINCT id, name, COUNT(*) AS t FROM demo.user WHERE id > ? AND name LIKE ? AND (id_card IS NULL OR status IN (?, ?, ?)) AND id NOT IN (SELECT id FROM banned) AND modified_at > created_at + ? GROUP BY status HAVING status NOT IN (?, ?) ORDER BY modified_at ASC LIMIT 10 OFFSET 5
  33. // [1234 %Du 1 2 5 86400 4 5]
  34. }
  35. func ExampleSelectBuilder_advancedUsage() {
  36. sb := NewSelectBuilder()
  37. innerSb := NewSelectBuilder()
  38. sb.Select("id", "name")
  39. sb.From(
  40. sb.BuilderAs(innerSb, "user"),
  41. )
  42. sb.Where(
  43. sb.In("status", Flatten([]int{1, 2, 3})...),
  44. sb.Between("created_at", sql.Named("start", 1234567890), sql.Named("end", 1234599999)),
  45. )
  46. innerSb.Select("*")
  47. innerSb.From("banned")
  48. innerSb.Where(
  49. innerSb.NotIn("name", Flatten([]string{"Huan Du", "Charmy Liu"})...),
  50. )
  51. sql, args := sb.Build()
  52. fmt.Println(sql)
  53. fmt.Println(args)
  54. // Output:
  55. // SELECT id, name FROM (SELECT * FROM banned WHERE name NOT IN (?, ?)) AS user WHERE status IN (?, ?, ?) AND created_at BETWEEN @start AND @end
  56. // [Huan Du Charmy Liu 1 2 3 {{} start 1234567890} {{} end 1234599999}]
  57. }