sqlstore_datasource.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package sqlstore
  2. import (
  3. "time"
  4. "github.com/torkelo/grafana-pro/pkg/bus"
  5. m "github.com/torkelo/grafana-pro/pkg/models"
  6. "github.com/go-xorm/xorm"
  7. )
  8. func init() {
  9. bus.AddHandler("sql", GetDataSources)
  10. bus.AddHandler("sql", AddDataSource)
  11. bus.AddHandler("sql", DeleteDataSource)
  12. bus.AddHandler("sql", UpdateDataSource)
  13. bus.AddHandler("sql", GetDataSourceByName)
  14. }
  15. func GetDataSourceByName(query *m.GetDataSourceByNameQuery) error {
  16. sess := x.Limit(100, 0).Where("account_id=? AND name=?", query.AccountId, query.Name)
  17. has, err := sess.Get(&query.Result)
  18. if !has {
  19. return m.ErrDataSourceNotFound
  20. }
  21. return err
  22. }
  23. func GetDataSources(query *m.GetDataSourcesQuery) error {
  24. sess := x.Limit(100, 0).Where("account_id=?", query.AccountId)
  25. query.Result = make([]*m.DataSource, 0)
  26. return sess.Find(&query.Result)
  27. }
  28. func DeleteDataSource(cmd *m.DeleteDataSourceCommand) error {
  29. return inTransaction(func(sess *xorm.Session) error {
  30. var rawSql = "DELETE FROM data_source WHERE id=? and account_id=?"
  31. _, err := sess.Exec(rawSql, cmd.Id, cmd.AccountId)
  32. return err
  33. })
  34. }
  35. func AddDataSource(cmd *m.AddDataSourceCommand) error {
  36. return inTransaction(func(sess *xorm.Session) error {
  37. var err error
  38. ds := m.DataSource{
  39. AccountId: cmd.AccountId,
  40. Name: cmd.Name,
  41. Type: cmd.Type,
  42. Access: cmd.Access,
  43. Url: cmd.Url,
  44. Created: time.Now(),
  45. Updated: time.Now(),
  46. }
  47. _, err = sess.Insert(ds)
  48. return err
  49. })
  50. }
  51. func UpdateDataSource(cmd *m.UpdateDataSourceCommand) error {
  52. return inTransaction(func(sess *xorm.Session) error {
  53. var err error
  54. ds := m.DataSource{
  55. Id: cmd.Id,
  56. AccountId: cmd.AccountId,
  57. Name: cmd.Name,
  58. Type: cmd.Type,
  59. Access: cmd.Access,
  60. Url: cmd.Url,
  61. Updated: time.Now(),
  62. }
  63. _, err = sess.Where("id=? and account_id=?", ds.Id, ds.AccountId).Update(&ds)
  64. return err
  65. })
  66. }