sqlstore_datasource.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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", GetDataSourceById)
  14. }
  15. func GetDataSourceById(query *m.GetDataSourceByIdQuery) error {
  16. sess := x.Limit(100, 0).Where("account_id=? AND id=?", query.AccountId, query.Id)
  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).Asc("name")
  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. User: cmd.User,
  45. Password: cmd.Password,
  46. Database: cmd.Database,
  47. Created: time.Now(),
  48. Updated: time.Now(),
  49. }
  50. _, err = sess.Insert(ds)
  51. return err
  52. })
  53. }
  54. func UpdateDataSource(cmd *m.UpdateDataSourceCommand) error {
  55. return inTransaction(func(sess *xorm.Session) error {
  56. var err error
  57. ds := m.DataSource{
  58. Id: cmd.Id,
  59. AccountId: cmd.AccountId,
  60. Name: cmd.Name,
  61. Type: cmd.Type,
  62. Access: cmd.Access,
  63. Url: cmd.Url,
  64. User: cmd.User,
  65. Password: cmd.Password,
  66. Database: cmd.Database,
  67. Updated: time.Now(),
  68. }
  69. _, err = sess.Where("id=? and account_id=?", ds.Id, ds.AccountId).Update(&ds)
  70. return err
  71. })
  72. }