datasource.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. cmd.Result = &ds
  52. return err
  53. })
  54. }
  55. func UpdateDataSource(cmd *m.UpdateDataSourceCommand) error {
  56. return inTransaction(func(sess *xorm.Session) error {
  57. var err error
  58. ds := m.DataSource{
  59. Id: cmd.Id,
  60. AccountId: cmd.AccountId,
  61. Name: cmd.Name,
  62. Type: cmd.Type,
  63. Access: cmd.Access,
  64. Url: cmd.Url,
  65. User: cmd.User,
  66. Password: cmd.Password,
  67. Database: cmd.Database,
  68. Updated: time.Now(),
  69. }
  70. _, err = sess.Where("id=? and account_id=?", ds.Id, ds.AccountId).Update(&ds)
  71. return err
  72. })
  73. }