annotation.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. package sqlstore
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "strings"
  7. "github.com/grafana/grafana/pkg/models"
  8. "github.com/grafana/grafana/pkg/services/annotations"
  9. )
  10. type SqlAnnotationRepo struct {
  11. }
  12. func (r *SqlAnnotationRepo) Save(item *annotations.Item) error {
  13. return inTransaction(func(sess *DBSession) error {
  14. tags := models.ParseTagPairs(item.Tags)
  15. item.Tags = models.JoinTagPairs(tags)
  16. if _, err := sess.Table("annotation").Insert(item); err != nil {
  17. return err
  18. }
  19. if item.Tags != nil {
  20. if tags, err := r.ensureTagsExist(sess, tags); err != nil {
  21. return err
  22. } else {
  23. for _, tag := range tags {
  24. if _, err := sess.Exec("INSERT INTO annotation_tag (annotation_id, tag_id) VALUES(?,?)", item.Id, tag.Id); err != nil {
  25. return err
  26. }
  27. }
  28. }
  29. }
  30. return nil
  31. })
  32. }
  33. // Will insert if needed any new key/value pars and return ids
  34. func (r *SqlAnnotationRepo) ensureTagsExist(sess *DBSession, tags []*models.Tag) ([]*models.Tag, error) {
  35. for _, tag := range tags {
  36. var existingTag models.Tag
  37. // check if it exists
  38. if exists, err := sess.Table("tag").Where("key=? AND value=?", tag.Key, tag.Value).Get(&existingTag); err != nil {
  39. return nil, err
  40. } else if exists {
  41. tag.Id = existingTag.Id
  42. } else {
  43. if _, err := sess.Table("tag").Insert(tag); err != nil {
  44. return nil, err
  45. }
  46. }
  47. }
  48. return tags, nil
  49. }
  50. func (r *SqlAnnotationRepo) Update(item *annotations.Item) error {
  51. return inTransaction(func(sess *DBSession) error {
  52. var (
  53. isExist bool
  54. err error
  55. )
  56. existing := new(annotations.Item)
  57. if item.Id == 0 && item.RegionId != 0 {
  58. // Update region end time
  59. isExist, err = sess.Table("annotation").Where("region_id=? AND id!=? AND org_id=?", item.RegionId, item.RegionId, item.OrgId).Get(existing)
  60. } else {
  61. isExist, err = sess.Table("annotation").Where("id=? AND org_id=?", item.Id, item.OrgId).Get(existing)
  62. }
  63. if err != nil {
  64. return err
  65. }
  66. if !isExist {
  67. return errors.New("Annotation not found")
  68. }
  69. existing.Epoch = item.Epoch
  70. existing.Text = item.Text
  71. if item.RegionId != 0 {
  72. existing.RegionId = item.RegionId
  73. }
  74. if item.Tags != nil {
  75. if tags, err := r.ensureTagsExist(sess, models.ParseTagPairs(item.Tags)); err != nil {
  76. return err
  77. } else {
  78. if _, err := sess.Exec("DELETE FROM annotation_tag WHERE annotation_id = ?", existing.Id); err != nil {
  79. return err
  80. }
  81. for _, tag := range tags {
  82. if _, err := sess.Exec("INSERT INTO annotation_tag (annotation_id, tag_id) VALUES(?,?)", existing.Id, tag.Id); err != nil {
  83. return err
  84. }
  85. }
  86. }
  87. }
  88. existing.Tags = item.Tags
  89. if _, err := sess.Table("annotation").Id(existing.Id).Cols("epoch", "text", "region_id", "tags").Update(existing); err != nil {
  90. return err
  91. }
  92. return nil
  93. })
  94. }
  95. func (r *SqlAnnotationRepo) Find(query *annotations.ItemQuery) ([]*annotations.ItemDTO, error) {
  96. var sql bytes.Buffer
  97. params := make([]interface{}, 0)
  98. sql.WriteString(`
  99. SELECT
  100. annotation.id,
  101. annotation.epoch as time,
  102. annotation.dashboard_id,
  103. annotation.panel_id,
  104. annotation.new_state,
  105. annotation.prev_state,
  106. annotation.alert_id,
  107. annotation.region_id,
  108. annotation.text,
  109. annotation.tags,
  110. annotation.data,
  111. usr.email,
  112. usr.login,
  113. alert.name as alert_name
  114. FROM annotation
  115. LEFT OUTER JOIN ` + dialect.Quote("user") + ` as usr on usr.id = annotation.user_id
  116. LEFT OUTER JOIN alert on alert.id = annotation.alert_id
  117. `)
  118. sql.WriteString(`WHERE annotation.org_id = ?`)
  119. params = append(params, query.OrgId)
  120. if query.AlertId != 0 {
  121. sql.WriteString(` AND annotation.alert_id = ?`)
  122. params = append(params, query.AlertId)
  123. }
  124. if query.DashboardId != 0 {
  125. sql.WriteString(` AND annotation.dashboard_id = ?`)
  126. params = append(params, query.DashboardId)
  127. }
  128. if query.PanelId != 0 {
  129. sql.WriteString(` AND annotation.panel_id = ?`)
  130. params = append(params, query.PanelId)
  131. }
  132. if query.From > 0 && query.To > 0 {
  133. sql.WriteString(` AND annotation.epoch BETWEEN ? AND ?`)
  134. params = append(params, query.From, query.To)
  135. }
  136. if len(query.Tags) > 0 {
  137. keyValueFilters := []string{}
  138. tags := models.ParseTagPairs(query.Tags)
  139. for _, tag := range tags {
  140. if tag.Value == "" {
  141. keyValueFilters = append(keyValueFilters, "(tag.key = ?)")
  142. params = append(params, tag.Key)
  143. } else {
  144. keyValueFilters = append(keyValueFilters, "(tag.key = ? AND tag.value = ?)")
  145. params = append(params, tag.Key, tag.Value)
  146. }
  147. }
  148. if len(tags) > 0 {
  149. tagsSubQuery := fmt.Sprintf(`
  150. SELECT SUM(1) FROM annotation_tag at
  151. INNER JOIN tag on tag.id = at.tag_id
  152. WHERE at.annotation_id = annotation.id
  153. AND (
  154. %s
  155. )
  156. `, strings.Join(keyValueFilters, " OR "))
  157. sql.WriteString(fmt.Sprintf(" AND (%s) = %d ", tagsSubQuery, len(tags)))
  158. }
  159. }
  160. if query.Limit == 0 {
  161. query.Limit = 10
  162. }
  163. sql.WriteString(fmt.Sprintf(" ORDER BY epoch DESC LIMIT %v", query.Limit))
  164. items := make([]*annotations.ItemDTO, 0)
  165. if err := x.Sql(sql.String(), params...).Find(&items); err != nil {
  166. return nil, err
  167. }
  168. return items, nil
  169. }
  170. func (r *SqlAnnotationRepo) Delete(params *annotations.DeleteParams) error {
  171. return inTransaction(func(sess *DBSession) error {
  172. var (
  173. sql string
  174. annoTagSql string
  175. queryParams []interface{}
  176. )
  177. if params.RegionId != 0 {
  178. annoTagSql = "DELETE FROM annotation_tag WHERE annotation_id IN (SELECT id FROM annotation WHERE region_id = ?)"
  179. sql = "DELETE FROM annotation WHERE region_id = ?"
  180. queryParams = []interface{}{params.RegionId}
  181. } else if params.Id != 0 {
  182. annoTagSql = "DELETE FROM annotation_tag WHERE annotation_id IN (SELECT id FROM annotation WHERE id = ?)"
  183. sql = "DELETE FROM annotation WHERE id = ?"
  184. queryParams = []interface{}{params.Id}
  185. } else {
  186. annoTagSql = "DELETE FROM annotation_tag WHERE annotation_id IN (SELECT id FROM annotation WHERE dashboard_id = ? AND panel_id = ?)"
  187. sql = "DELETE FROM annotation WHERE dashboard_id = ? AND panel_id = ?"
  188. queryParams = []interface{}{params.DashboardId, params.PanelId}
  189. }
  190. if _, err := sess.Exec(annoTagSql, queryParams...); err != nil {
  191. return err
  192. }
  193. if _, err := sess.Exec(sql, queryParams...); err != nil {
  194. return err
  195. }
  196. return nil
  197. })
  198. }