annotation.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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.Type != "" {
  31. sql.WriteString(` AND type = ?`)
  32. params = append(params, string(query.Type))
  33. }
  34. if query.Limit == 0 {
  35. query.Limit = 10
  36. }
  37. sql.WriteString(fmt.Sprintf("ORDER BY timestamp DESC LIMIT %v", query.Limit))
  38. items := make([]*annotations.Item, 0)
  39. if err := x.Sql(sql.String(), params...).Find(&items); err != nil {
  40. return nil, err
  41. }
  42. return items, nil
  43. }