annotation.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  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. _, err = sess.Table("annotation").Id(existing.Id).Cols("epoch", "text", "region_id", "tags").Update(existing)
  90. return err
  91. })
  92. }
  93. func (r *SqlAnnotationRepo) Find(query *annotations.ItemQuery) ([]*annotations.ItemDTO, error) {
  94. var sql bytes.Buffer
  95. params := make([]interface{}, 0)
  96. sql.WriteString(`
  97. SELECT
  98. annotation.id,
  99. annotation.epoch as time,
  100. annotation.dashboard_id,
  101. annotation.panel_id,
  102. annotation.new_state,
  103. annotation.prev_state,
  104. annotation.alert_id,
  105. annotation.region_id,
  106. annotation.text,
  107. annotation.tags,
  108. annotation.data,
  109. usr.email,
  110. usr.login,
  111. alert.name as alert_name
  112. FROM annotation
  113. LEFT OUTER JOIN ` + dialect.Quote("user") + ` as usr on usr.id = annotation.user_id
  114. LEFT OUTER JOIN alert on alert.id = annotation.alert_id
  115. `)
  116. sql.WriteString(`WHERE annotation.org_id = ?`)
  117. params = append(params, query.OrgId)
  118. if query.AnnotationId != 0 {
  119. fmt.Print("annotation query")
  120. sql.WriteString(` AND annotation.id = ?`)
  121. params = append(params, query.AnnotationId)
  122. }
  123. if query.RegionId != 0 {
  124. sql.WriteString(` AND annotation.region_id = ?`)
  125. params = append(params, query.RegionId)
  126. }
  127. if query.AlertId != 0 {
  128. sql.WriteString(` AND annotation.alert_id = ?`)
  129. params = append(params, query.AlertId)
  130. }
  131. if query.DashboardId != 0 {
  132. sql.WriteString(` AND annotation.dashboard_id = ?`)
  133. params = append(params, query.DashboardId)
  134. }
  135. if query.PanelId != 0 {
  136. sql.WriteString(` AND annotation.panel_id = ?`)
  137. params = append(params, query.PanelId)
  138. }
  139. if query.From > 0 && query.To > 0 {
  140. sql.WriteString(` AND annotation.epoch BETWEEN ? AND ?`)
  141. params = append(params, query.From, query.To)
  142. }
  143. if query.Type == "alert" {
  144. sql.WriteString(` AND annotation.alert_id > 0`)
  145. }
  146. if len(query.Tags) > 0 {
  147. keyValueFilters := []string{}
  148. tags := models.ParseTagPairs(query.Tags)
  149. for _, tag := range tags {
  150. if tag.Value == "" {
  151. keyValueFilters = append(keyValueFilters, "(tag.key = ?)")
  152. params = append(params, tag.Key)
  153. } else {
  154. keyValueFilters = append(keyValueFilters, "(tag.key = ? AND tag.value = ?)")
  155. params = append(params, tag.Key, tag.Value)
  156. }
  157. }
  158. if len(tags) > 0 {
  159. tagsSubQuery := fmt.Sprintf(`
  160. SELECT SUM(1) FROM annotation_tag at
  161. INNER JOIN tag on tag.id = at.tag_id
  162. WHERE at.annotation_id = annotation.id
  163. AND (
  164. %s
  165. )
  166. `, strings.Join(keyValueFilters, " OR "))
  167. sql.WriteString(fmt.Sprintf(" AND (%s) = %d ", tagsSubQuery, len(tags)))
  168. }
  169. }
  170. if query.Limit == 0 {
  171. query.Limit = 100
  172. }
  173. sql.WriteString(fmt.Sprintf(" ORDER BY epoch DESC LIMIT %v", query.Limit))
  174. items := make([]*annotations.ItemDTO, 0)
  175. if err := x.Sql(sql.String(), params...).Find(&items); err != nil {
  176. return nil, err
  177. }
  178. return items, nil
  179. }
  180. func (r *SqlAnnotationRepo) Delete(params *annotations.DeleteParams) error {
  181. return inTransaction(func(sess *DBSession) error {
  182. var (
  183. sql string
  184. annoTagSql string
  185. queryParams []interface{}
  186. )
  187. if params.RegionId != 0 {
  188. annoTagSql = "DELETE FROM annotation_tag WHERE annotation_id IN (SELECT id FROM annotation WHERE region_id = ?)"
  189. sql = "DELETE FROM annotation WHERE region_id = ?"
  190. queryParams = []interface{}{params.RegionId}
  191. } else if params.Id != 0 {
  192. annoTagSql = "DELETE FROM annotation_tag WHERE annotation_id IN (SELECT id FROM annotation WHERE id = ?)"
  193. sql = "DELETE FROM annotation WHERE id = ?"
  194. queryParams = []interface{}{params.Id}
  195. } else {
  196. annoTagSql = "DELETE FROM annotation_tag WHERE annotation_id IN (SELECT id FROM annotation WHERE dashboard_id = ? AND panel_id = ?)"
  197. sql = "DELETE FROM annotation WHERE dashboard_id = ? AND panel_id = ?"
  198. queryParams = []interface{}{params.DashboardId, params.PanelId}
  199. }
  200. if _, err := sess.Exec(annoTagSql, queryParams...); err != nil {
  201. return err
  202. }
  203. if _, err := sess.Exec(sql, queryParams...); err != nil {
  204. return err
  205. }
  206. return nil
  207. })
  208. }