incrementor.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package sqlite
  2. // BindIndexStart is the index of the first parameter when using the Stmt.Bind*
  3. // functions.
  4. const BindIndexStart = 1
  5. // BindIncrementor returns an Incrementor that starts on 1, the first index
  6. // used in Stmt.Bind* functions. This is provided as syntactic sugar for
  7. // binding parameter values to a Stmt. It allows for easily changing query
  8. // parameters without manually fixing up the bind indexes, which can be error
  9. // prone. For example,
  10. //
  11. // stmt := conn.Prep(`INSERT INTO test (a, b, c) VALUES (?, ?, ?);`)
  12. // i := BindIncrementor()
  13. // stmt.BindInt64(i(), a) // i() == 1
  14. // if b > 0 {
  15. // stmt.BindInt64(i(), b) // i() == 2
  16. // } else {
  17. // // Remember to increment the index even if a param is NULL
  18. // stmt.BindNull(i()) // i() == 2
  19. // }
  20. // stmt.BindText(i(), c) // i() == 3
  21. func BindIncrementor() Incrementor {
  22. return NewIncrementor(BindIndexStart)
  23. }
  24. // ColumnIndexStart is the index of the first column when using the
  25. // Stmt.Column* functions.
  26. const ColumnIndexStart = 0
  27. // ColumnIncrementor returns an Incrementor that starts on 0, the first index
  28. // used in Stmt.Column* functions. This is provided as syntactic sugar for
  29. // parsing column values from a Stmt. It allows for easily changing queried
  30. // columns without manually fixing up the column indexes, which can be error
  31. // prone. For example,
  32. //
  33. // stmt := conn.Prep(`SELECT a, b, c FROM test;`)
  34. // stmt.Step()
  35. // i := ColumnIncrementor()
  36. // a := stmt.ColumnInt64(i()) // i() == 1
  37. // b := stmt.ColumnInt64(i()) // i() == 2
  38. // c := stmt.ColumnText(i()) // i() == 3
  39. func ColumnIncrementor() Incrementor {
  40. return NewIncrementor(ColumnIndexStart)
  41. }
  42. // NewIncrementor returns an Incrementor that starts on start.
  43. func NewIncrementor(start int) Incrementor {
  44. return func() int {
  45. start++
  46. return start - 1
  47. }
  48. }
  49. // Incrementor is a closure around a value that returns and increments the
  50. // value on each call. For example, the boolean statments in the following code
  51. // snippet would all be true.
  52. //
  53. // i := NewIncrementor(3)
  54. // i() == 3
  55. // i() == 4
  56. // i() == 5
  57. //
  58. // This is provided as syntactic sugar for dealing with bind param and column
  59. // indexes. See BindIncrementor and ColumnIncrementor for small examples.
  60. type Incrementor func() int