protocal.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package model
  2. import (
  3. "fmt"
  4. "sparrow/pkg/models"
  5. "github.com/jinzhu/gorm"
  6. )
  7. // Protocal ``
  8. type Protocal struct {
  9. db *gorm.DB
  10. }
  11. // Init 初始化
  12. func (a *Protocal) Init(db *gorm.DB) *Protocal {
  13. a.db = db
  14. return a
  15. }
  16. // Create 创建
  17. func (a *Protocal) Create(ptl *models.Protocal) error {
  18. cache := getCache()
  19. key := fmt.Sprintf("Protocal:%d", ptl.ID)
  20. err := a.db.Create(ptl).Error
  21. if err != nil {
  22. return err
  23. }
  24. cache.Set(key, ptl)
  25. return nil
  26. }
  27. // Delete 删除
  28. func (a *Protocal) Delete(ptl *models.Protocal) error {
  29. cache := getCache()
  30. key := fmt.Sprintf("Protocal:%d", ptl.ID)
  31. if _, ok := cache.Get(key); ok {
  32. cache.Delete(key)
  33. }
  34. return a.db.Delete(ptl).Error
  35. }
  36. // Update 更新
  37. func (a *Protocal) Update(ptl *models.Protocal) (data models.Protocal, err error) {
  38. cache := getCache()
  39. key := fmt.Sprintf("Protocal:%d", ptl.ID)
  40. if _, ok := cache.Get(key); ok {
  41. cache.Delete(key)
  42. }
  43. err = a.db.Model(&data).Update(ptl).Error
  44. return
  45. }
  46. // GetProductProtocals 获取产品的数据点列表
  47. func (a *Protocal) GetProductProtocals(productid uint, pi, ps int, name, label string) (datas []models.Protocal, total int, err error) {
  48. tx := a.db.Where("product_id = ? and 1 = 1", productid)
  49. if name != "" {
  50. tx = tx.Where("name like ? ", "%"+name+"%")
  51. }
  52. if label != "" {
  53. tx = tx.Where("label = ?", label)
  54. }
  55. err = tx.Limit(ps).Offset((pi - 1) * ps).Find(&datas).Error
  56. tx.Model(&models.Protocal{}).Count(&total)
  57. return
  58. }
  59. // GetProtocalInfo 获取数据点内容
  60. func (a *Protocal) GetProtocalInfo(pid uint) (data models.Protocal, err error) {
  61. cache := getCache()
  62. key := fmt.Sprintf("Protocal:%d", pid)
  63. if v, ok := cache.Get(key); ok {
  64. data = *(v.(*models.Protocal))
  65. } else {
  66. err = a.db.Where("id = ?", pid).First(&data).Error
  67. if err == nil {
  68. cache.Set(key, &data)
  69. }
  70. }
  71. return
  72. }
  73. // TODO 查询某个产品所有上报类型的数据点