query.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package arango
  2. import (
  3. "strings"
  4. )
  5. // Query provides a simple way to build ArangoDB queries.
  6. type Query struct {
  7. Lines []string
  8. Params map[string]any
  9. }
  10. // Append adds a line to the query, attaching (optional) values to bind parameters.
  11. //
  12. // Any variables given are assigned to bind parameters in the same order as they appear in the line.
  13. // Keep in mind the following behaviours:
  14. //
  15. // - If more variables are provided than there are parameters in the line, leftover variables are discarded
  16. // - If more parameters are used than variables are given, remaining parameters are left unmapped
  17. // - Reused parameters are overwritten
  18. func (query *Query) Append(line string, values ...any) *Query {
  19. var params map[string]any = nil
  20. names := ReadParams(line)
  21. if len(names) > 0 {
  22. params = map[string]any{}
  23. for i, name := range names {
  24. if i == len(values) {
  25. break
  26. }
  27. params[name] = values[i]
  28. }
  29. }
  30. query.Lines = append(query.Lines, line)
  31. return query.BindMap(params)
  32. }
  33. // Bind binds a value to a bind parameter.
  34. func (query *Query) Bind(name string, value any) *Query {
  35. query.Params[name] = value
  36. return query
  37. }
  38. // BindMap assigns values to bind parameters.
  39. func (query *Query) BindMap(params map[string]any) *Query {
  40. if params != nil {
  41. for name, value := range params {
  42. query.Params[name] = value
  43. }
  44. }
  45. return query
  46. }
  47. // Copy creates a copy of the query.
  48. func (query *Query) Copy() *Query {
  49. newQuery := NewQuery()
  50. for _, line := range query.Lines {
  51. newQuery.Lines = append(newQuery.Lines, line)
  52. }
  53. for name, value := range query.Params {
  54. newQuery.Params[name] = value
  55. }
  56. return newQuery
  57. }
  58. func (query *Query) String() string {
  59. return strings.Join(query.Lines, "\n")
  60. }
  61. // NewQuery creates a new, empty Query.
  62. func NewQuery() *Query {
  63. return &Query{
  64. Lines: []string{},
  65. Params: map[string]any{},
  66. }
  67. }