dashboards.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. }
  13. func SaveDashboard(cmd *m.SaveDashboardCommand) error {
  14. return inTransaction(func(sess *xorm.Session) error {
  15. dash := cmd.GetDashboardModel()
  16. // try get existing dashboard
  17. existing := m.Dashboard{Slug: dash.Slug, AccountId: dash.AccountId}
  18. hasExisting, err := sess.Get(&existing)
  19. if err != nil {
  20. return err
  21. }
  22. if hasExisting && dash.Id != existing.Id {
  23. return m.ErrDashboardWithSameNameExists
  24. }
  25. if dash.Id == 0 {
  26. _, err = sess.Insert(dash)
  27. } else {
  28. _, err = sess.Id(dash.Id).Update(dash)
  29. }
  30. cmd.Result = dash
  31. return err
  32. })
  33. }
  34. func GetDashboard(query *m.GetDashboardQuery) error {
  35. dashboard := m.Dashboard{Slug: query.Slug, AccountId: query.AccountId}
  36. has, err := x.Get(&dashboard)
  37. if err != nil {
  38. return err
  39. } else if has == false {
  40. return m.ErrDashboardNotFound
  41. }
  42. query.Result = &dashboard
  43. return nil
  44. }
  45. func SearchDashboards(query *m.SearchDashboardsQuery) error {
  46. sess := x.Limit(100, 0).Where("account_id=?", query.AccountId)
  47. sess.Table("Dashboard")
  48. query.Result = make([]*m.SearchResult, 0)
  49. err := sess.Find(&query.Result)
  50. return err
  51. }
  52. func DeleteDashboard(cmd *m.DeleteDashboardCommand) error {
  53. sess := x.NewSession()
  54. defer sess.Close()
  55. rawSql := "DELETE FROM Dashboard WHERE account_id=? and slug=?"
  56. _, err := sess.Exec(rawSql, cmd.AccountId, cmd.Slug)
  57. return err
  58. }