dashboards.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package sqlstore
  2. import (
  3. "github.com/go-xorm/xorm"
  4. "github.com/torkelo/grafana-pro/pkg/bus"
  5. m "github.com/torkelo/grafana-pro/pkg/models"
  6. )
  7. func init() {
  8. bus.AddHandler("sql", SaveDashboard)
  9. bus.AddHandler("sql", GetDashboard)
  10. bus.AddHandler("sql", DeleteDashboard)
  11. bus.AddHandler("sql", SearchDashboards)
  12. bus.AddHandler("sql", GetDashboardTags)
  13. }
  14. func SaveDashboard(cmd *m.SaveDashboardCommand) error {
  15. return inTransaction(func(sess *xorm.Session) error {
  16. dash := cmd.GetDashboardModel()
  17. // try get existing dashboard
  18. existing := m.Dashboard{Slug: dash.Slug, AccountId: dash.AccountId}
  19. hasExisting, err := sess.Get(&existing)
  20. if err != nil {
  21. return err
  22. }
  23. if hasExisting && dash.Id != existing.Id {
  24. return m.ErrDashboardWithSameNameExists
  25. }
  26. if dash.Id == 0 {
  27. _, err = sess.Insert(dash)
  28. } else {
  29. _, err = sess.Id(dash.Id).Update(dash)
  30. }
  31. cmd.Result = dash
  32. return err
  33. })
  34. }
  35. func GetDashboard(query *m.GetDashboardQuery) error {
  36. dashboard := m.Dashboard{Slug: query.Slug, AccountId: query.AccountId}
  37. has, err := x.Get(&dashboard)
  38. if err != nil {
  39. return err
  40. } else if has == false {
  41. return m.ErrDashboardNotFound
  42. }
  43. query.Result = &dashboard
  44. return nil
  45. }
  46. func SearchDashboards(query *m.SearchDashboardsQuery) error {
  47. titleQuery := "%" + query.Query + "%"
  48. sess := x.Limit(100, 0).Where("account_id=? AND title LIKE ?", query.AccountId, titleQuery)
  49. sess.Table("Dashboard")
  50. query.Result = make([]m.DashboardSearchHit, 0)
  51. err := sess.Find(&query.Result)
  52. return err
  53. }
  54. func GetDashboardTags(query *m.GetDashboardTagsQuery) error {
  55. query.Result = []m.DashboardTagCloudItem{
  56. m.DashboardTagCloudItem{Term: "test", Count: 10},
  57. m.DashboardTagCloudItem{Term: "prod", Count: 20},
  58. }
  59. return nil
  60. }
  61. func DeleteDashboard(cmd *m.DeleteDashboardCommand) error {
  62. sess := x.NewSession()
  63. defer sess.Close()
  64. rawSql := "DELETE FROM Dashboard WHERE account_id=? and slug=?"
  65. _, err := sess.Exec(rawSql, cmd.AccountId, cmd.Slug)
  66. return err
  67. }