db.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package zlimit
  2. import (
  3. "context"
  4. "go-common/library/database/sql"
  5. "go-common/library/log"
  6. "go-common/library/xstr"
  7. )
  8. const (
  9. _getPolicySQL = "SELECT id, play_auth, down_auth, zone_id FROM policy_item WHERE zone_id <> '' AND state=1"
  10. _getRelationSQL = "SELECT policy_id FROM archive_relation WHERE aid=?"
  11. _getGolbalPolicySQL = "select group_id,group_concat(id) from policy_item WHERE zone_id <> '' AND state=1 GROUP BY group_id"
  12. )
  13. // policies get policy data from db
  14. func (s *Service) policies(c context.Context) (res map[int64]map[int64]int64, err error) {
  15. var (
  16. tmpres map[int64]int64
  17. ok bool
  18. )
  19. rows, err := s.db.Query(c, _getPolicySQL)
  20. if err != nil {
  21. log.Error("db.Query error(%v)", err)
  22. return
  23. }
  24. defer rows.Close()
  25. res = make(map[int64]map[int64]int64)
  26. for rows.Next() {
  27. var (
  28. pid, playAuth, downAuth int64
  29. zoneID string
  30. zoneIDs []int64
  31. )
  32. if err = rows.Scan(&pid, &playAuth, &downAuth, &zoneID); err != nil {
  33. log.Error("rows.Scan error(%v)", err)
  34. return
  35. }
  36. if zoneIDs, err = xstr.SplitInts(zoneID); err != nil {
  37. log.Error("xstr.SplitInts(%s) error(%v)", zoneID, err)
  38. continue
  39. }
  40. for _, zoneid := range zoneIDs {
  41. if tmpres, ok = res[pid]; !ok {
  42. tmpres = make(map[int64]int64)
  43. res[pid] = tmpres
  44. }
  45. resCode := playAuth<<8 | downAuth
  46. tmpres[zoneid] = resCode
  47. }
  48. }
  49. return
  50. }
  51. // groupPolicies get policy data from db group by group_id
  52. func (s *Service) groupPolicies(c context.Context) (res map[int64][]int64, err error) {
  53. rows, err := s.db.Query(c, _getGolbalPolicySQL)
  54. if err != nil {
  55. log.Error("db.Query error(%v)", err)
  56. return
  57. }
  58. defer rows.Close()
  59. res = make(map[int64][]int64)
  60. for rows.Next() {
  61. var (
  62. groupID int64
  63. pids string
  64. zoneIDs []int64
  65. )
  66. if err = rows.Scan(&groupID, &pids); err != nil {
  67. log.Error("rows.Scan error(%v)", err)
  68. return
  69. }
  70. if zoneIDs, err = xstr.SplitInts(pids); err != nil {
  71. log.Error("xstr.SplitInts(%s) error(%v)", pids, err)
  72. continue
  73. }
  74. res[groupID] = zoneIDs
  75. }
  76. return
  77. }
  78. // policy get pids from db by aid
  79. func (s *Service) groupid(c context.Context, aid int64) (gid int64, err error) {
  80. row := s.getRelationStmt.QueryRow(c, aid)
  81. if err = row.Scan(&gid); err != nil {
  82. if err == sql.ErrNoRows {
  83. gid = 0
  84. err = nil
  85. } else {
  86. log.Error("rows.Scan error(%v)", err)
  87. }
  88. }
  89. return
  90. }