annotation.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. sql.WriteString(` AND epoch BETWEEN ? AND ?`)
  43. params = append(params, query.From, query.To)
  44. if query.Type != "" {
  45. sql.WriteString(` AND type = ?`)
  46. params = append(params, string(query.Type))
  47. }
  48. if query.Limit == 0 {
  49. query.Limit = 10
  50. }
  51. sql.WriteString(fmt.Sprintf("ORDER BY epoch DESC LIMIT %v", query.Limit))
  52. items := make([]*annotations.Item, 0)
  53. if err := x.Sql(sql.String(), params...).Find(&items); err != nil {
  54. return nil, err
  55. }
  56. return items, nil
  57. }