annotation.go 1.8 KB

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