rethinkdb.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package stores
  2. import (
  3. "time"
  4. log "github.com/alecthomas/log4go"
  5. r "github.com/dancannon/gorethink"
  6. "github.com/torkelo/grafana-pro/pkg/models"
  7. )
  8. type rethinkStore struct {
  9. session *r.Session
  10. }
  11. type RethinkCfg struct {
  12. DatabaseName string
  13. }
  14. func NewRethinkStore(config *RethinkCfg) *rethinkStore {
  15. log.Info("Initializing rethink storage")
  16. session, err := r.Connect(r.ConnectOpts{
  17. Address: "localhost:28015",
  18. Database: config.DatabaseName,
  19. MaxIdle: 10,
  20. IdleTimeout: time.Second * 10,
  21. })
  22. if err != nil {
  23. log.Crash("Failed to connect to rethink database %v", err)
  24. }
  25. r.DbCreate(config.DatabaseName).Exec(session)
  26. r.Db(config.DatabaseName).TableCreate("dashboards").Exec(session)
  27. r.Db(config.DatabaseName).Table("dashboards").IndexCreateFunc("AccountIdTitle", func(row r.Term) interface{} {
  28. return []interface{}{row.Field("AccountId"), row.Field("Title")}
  29. }).Exec(session)
  30. return &rethinkStore{
  31. session: session,
  32. }
  33. }
  34. func (self *rethinkStore) SaveDashboard(dash *models.Dashboard) error {
  35. resp, err := r.Table("dashboards").Insert(dash).RunWrite(self.session)
  36. if err != nil {
  37. return err
  38. }
  39. log.Info("Inserted: %v, Errors: %v, Updated: %v", resp.Inserted, resp.Errors, resp.Updated)
  40. log.Info("First error:", resp.FirstError)
  41. if len(resp.GeneratedKeys) > 0 {
  42. dash.Id = resp.GeneratedKeys[0]
  43. }
  44. return nil
  45. }
  46. func (self *rethinkStore) GetDashboardByTitle(title string, accountId string) (*models.Dashboard, error) {
  47. resp, err := r.Table("dashboards").GetAllByIndex("AccountIdTitle", []interface{}{accountId, title}).Run(self.session)
  48. if err != nil {
  49. return nil, err
  50. }
  51. var dashboard models.Dashboard
  52. err = resp.One(&dashboard)
  53. if err != nil {
  54. return nil, err
  55. }
  56. return &dashboard, nil
  57. }
  58. func (self *rethinkStore) Query(query string) ([]*models.SearchResult, error) {
  59. docs, err := r.Table("dashboards").Filter(r.Row.Field("Title").Match(".*")).Run(self.session)
  60. if err != nil {
  61. return nil, err
  62. }
  63. results := make([]*models.SearchResult, 0, 50)
  64. var dashboard models.Dashboard
  65. for docs.Next(&dashboard) {
  66. log.Info("title: ", dashboard.Title)
  67. results = append(results, &models.SearchResult{
  68. Title: dashboard.Title,
  69. Id: dashboard.Id,
  70. })
  71. }
  72. return results, nil
  73. }
  74. func (self *rethinkStore) Close() {}