eqlconsole.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /*
  2. * EliasDB
  3. *
  4. * Copyright 2016 Matthias Ladkau. All rights reserved.
  5. *
  6. * This Source Code Form is subject to the terms of the Mozilla Public
  7. * License, v. 2.0. If a copy of the MPL was not distributed with this
  8. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  9. */
  10. package console
  11. import (
  12. "fmt"
  13. "net/url"
  14. "devt.de/krotik/common/stringutil"
  15. "devt.de/krotik/eliasdb/api/v1"
  16. )
  17. // EQL Console
  18. // ===========
  19. /*
  20. EQLConsole runs EQL queries.
  21. */
  22. type EQLConsole struct {
  23. parent CommandConsoleAPI // Parent console API
  24. }
  25. /*
  26. eqlConsoleKeywords are all keywords which this console can process.
  27. */
  28. var eqlConsoleKeywords = []string{"part", "get", "lookup"}
  29. /*
  30. Run executes one or more commands. It returns an error if the command
  31. had an unexpected result and a flag if the command was handled.
  32. */
  33. func (c *EQLConsole) Run(cmd string) (bool, error) {
  34. if !cmdStartsWithKeyword(cmd, eqlConsoleKeywords) {
  35. return false, nil
  36. }
  37. // Escape query so it can be used in a request
  38. q := url.QueryEscape(cmd)
  39. resObj, err := c.parent.Req(
  40. fmt.Sprintf("%s%s?q=%s", v1.EndpointQuery, c.parent.Partition(), q), "GET", nil)
  41. if err == nil && resObj != nil {
  42. res := resObj.(map[string]interface{})
  43. var out []string
  44. header := res["header"].(map[string]interface{})
  45. labels := header["labels"].([]interface{})
  46. data := header["data"].([]interface{})
  47. rows := res["rows"].([]interface{})
  48. for _, l := range labels {
  49. out = append(out, fmt.Sprint(l))
  50. }
  51. for _, d := range data {
  52. out = append(out, fmt.Sprint(d))
  53. }
  54. for _, r := range rows {
  55. for _, c := range r.([]interface{}) {
  56. out = append(out, fmt.Sprint(c))
  57. }
  58. }
  59. c.parent.ExportBuffer().WriteString(stringutil.PrintCSVTable(out, len(labels)))
  60. fmt.Fprint(c.parent.Out(), stringutil.PrintGraphicStringTable(out, len(labels), 2, stringutil.SingleLineTable))
  61. }
  62. return true, err
  63. }
  64. /*
  65. Commands returns an empty list. The command line is interpreted as an EQL query.
  66. */
  67. func (c *EQLConsole) Commands() []Command {
  68. return nil
  69. }