annotation.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package sqlstore
  2. import (
  3. "bytes"
  4. "fmt"
  5. "github.com/go-xorm/xorm"
  6. "github.com/grafana/grafana/pkg/services/annotations"
  7. )
  8. type SqlAnnotationRepo struct {
  9. }
  10. func (r *SqlAnnotationRepo) Save(item *annotations.Item) error {
  11. return inTransaction(func(sess *xorm.Session) error {
  12. if _, err := sess.Table("annotation").Insert(item); err != nil {
  13. return err
  14. }
  15. return nil
  16. })
  17. }
  18. func (r *SqlAnnotationRepo) Find(query *annotations.ItemQuery) ([]*annotations.Item, error) {
  19. var sql bytes.Buffer
  20. params := make([]interface{}, 0)
  21. sql.WriteString(`SELECT *
  22. from annotation
  23. `)
  24. sql.WriteString(`WHERE org_id = ?`)
  25. params = append(params, query.OrgId)
  26. if query.AlertId != 0 {
  27. sql.WriteString(` AND alert_id = ?`)
  28. params = append(params, query.AlertId)
  29. }
  30. if query.AlertId != 0 {
  31. sql.WriteString(` AND alert_id = ?`)
  32. params = append(params, query.AlertId)
  33. }
  34. if query.DashboardId != 0 {
  35. sql.WriteString(` AND dashboard_id = ?`)
  36. params = append(params, query.DashboardId)
  37. }
  38. if query.PanelId != 0 {
  39. sql.WriteString(` AND panel_id = ?`)
  40. params = append(params, query.PanelId)
  41. }
  42. if query.From > 0 && query.To > 0 {
  43. sql.WriteString(` AND epoch BETWEEN ? AND ?`)
  44. params = append(params, query.From, query.To)
  45. }
  46. if query.Type != "" {
  47. sql.WriteString(` AND type = ?`)
  48. params = append(params, string(query.Type))
  49. }
  50. if query.Limit == 0 {
  51. query.Limit = 10
  52. }
  53. sql.WriteString(fmt.Sprintf("ORDER BY epoch DESC LIMIT %v", query.Limit))
  54. items := make([]*annotations.Item, 0)
  55. if err := x.Sql(sql.String(), params...).Find(&items); err != nil {
  56. return nil, err
  57. }
  58. return items, nil
  59. }