mysql.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  1. package dao
  2. import (
  3. "context"
  4. xsql "database/sql"
  5. "fmt"
  6. "time"
  7. "go-common/app/service/main/spy/conf"
  8. "go-common/app/service/main/spy/model"
  9. "go-common/library/database/sql"
  10. "go-common/library/log"
  11. )
  12. const (
  13. _serviceSQL = "SELECT id,name,nick_name,status,ctime,mtime FROM spy_service WHERE name=? AND status<>0 LIMIT 1"
  14. _addServiceSQL = "INSERT INTO spy_service (name,nick_name,status,ctime) VALUES (?,?,?,?)"
  15. _eventSQL = "SELECT id,name,nick_name,service_id,status,ctime,mtime FROM spy_event WHERE name=? AND status<>0 LIMIT 1"
  16. _addEventSQL = "INSERT INTO spy_event (name,nick_name,service_id,status,ctime) VALUES (?,?,?,?,?)"
  17. _factorSQL = "SELECT id,nick_name,service_id,event_id,group_id,risk_level,factor_val,ctime,mtime FROM spy_factor WHERE service_id=? AND event_id=? AND risk_level=? LIMIT 1"
  18. _factorGroupSQL = "SELECT id,name,ctime FROM spy_factor_group WHERE name=? LIMIT 1"
  19. _userInfoSQL = "SELECT id,mid,score,base_score,event_score,state,relive_times,ctime,mtime FROM spy_user_info_%02d WHERE mid=? LIMIT 1"
  20. _addUserInfoSQL = "INSERT IGNORE INTO spy_user_info_%02d (mid,score,base_score,event_score,state,ctime,mtime) VALUES (?,?,?,?,?,?,?)"
  21. _updateEventScoreSQL = "UPDATE spy_user_info_%02d SET event_score=?, score=? WHERE mid=?"
  22. _updateInfoSQL = "UPDATE spy_user_info_%02d SET base_score=?, event_score=?, score=?, state=? WHERE mid=?;"
  23. _updateBaseScoreSQL = "UPDATE spy_user_info_%02d SET base_score=?, score=? WHERE mid=?;"
  24. _addEventHistorySQL = "INSERT INTO spy_user_event_history_%02d (mid,event_id,score,base_score,event_score,remark,reason,factor_val,ctime) VALUES (?,?,?,?,?,?,?,?,?);"
  25. _getEventHistoryByMidAndEventSQL = "SELECT mid, event_id FROM spy_user_event_history_%02d WHERE mid = ? and event_id = ? limit 1"
  26. _addPunishmentSQL = "INSERT INTO spy_punishment (mid,type,reason,ctime) VALUES (?,?,?,?);"
  27. _addPunishmentQueueSQL = "INSERT INTO spy_punishment_queue (mid,batch_no,ctime) VALUES (?,?,?) ON DUPLICATE KEY UPDATE mtime=?;"
  28. _getAllConfigSQL = "SELECT id, property,name,val,ctime FROM spy_system_config;"
  29. _clearReliveTimesSQL = "UPDATE spy_user_info_%02d SET relive_times=? WHERE mid=?;"
  30. _getHistoryListSQL = "SELECT remark,reason FROM spy_user_event_history_%02d WHERE mid= ? ORDER BY id DESC LIMIT ?;"
  31. _updateEventScoreReLiveSQL = "UPDATE spy_user_info_%02d SET event_score=?, score=?, relive_times=relive_times+1 WHERE mid=?"
  32. _statListByMidSQL = "SELECT event_id,quantity FROM spy_statistics WHERE target_mid = ? AND isdel = 0 ORDER BY id desc LIMIT 100;"
  33. _statListByIDSQL = "SELECT event_id,quantity FROM spy_statistics WHERE target_id = ? AND isdel = 0 ORDER BY id desc LIMIT 100;"
  34. _statListByIDAndMidSQL = "SELECT event_id,quantity FROM spy_statistics WHERE target_mid = ? AND target_id = ? AND isdel = 0 ORDER BY id desc LIMIT 100;"
  35. _allEventSQL = "SELECT id,name,nick_name,service_id,status,ctime,mtime FROM spy_event WHERE status<>0"
  36. _telLevelSQL = "SELECT id,mid,level,origin,ctime,mtime FROM spy_tel_risk_level WHERE mid = ? LIMIT 1;"
  37. _addTelLevelSQL = "INSERT INTO spy_tel_risk_level (mid,level,origin,ctime) VALUES (?,?,?,?) "
  38. )
  39. // Service get service from db.
  40. func (d *Dao) Service(c context.Context, serviceName string) (service *model.Service, err error) {
  41. var (
  42. row *sql.Row
  43. )
  44. service = &model.Service{}
  45. row = d.db.QueryRow(c, _serviceSQL, serviceName)
  46. if err = row.Scan(&service.ID, &service.Name, &service.NickName, &service.Status, &service.CTime, &service.MTime); err != nil {
  47. if err == sql.ErrNoRows {
  48. err = nil
  49. service = nil
  50. return
  51. }
  52. log.Error("row.Scan() error(%v)", err)
  53. }
  54. return
  55. }
  56. // Event get event from db.
  57. func (d *Dao) Event(c context.Context, eventName string) (event *model.Event, err error) {
  58. var row *sql.Row
  59. event = &model.Event{}
  60. row = d.db.QueryRow(c, _eventSQL, eventName)
  61. if err = row.Scan(&event.ID, &event.Name, &event.NickName, &event.ServiceID, &event.Status, &event.CTime, &event.MTime); err != nil {
  62. if err == sql.ErrNoRows {
  63. err = nil
  64. event = nil
  65. return
  66. }
  67. log.Error("row.Scan() error(%v)", err)
  68. }
  69. return
  70. }
  71. // AddService insert service to db.
  72. func (d *Dao) AddService(c context.Context, service *model.Service) (id int64, err error) {
  73. var (
  74. res xsql.Result
  75. )
  76. if res, err = d.db.Exec(c, _addServiceSQL, service.Name, service.NickName, service.Status, time.Now()); err != nil {
  77. log.Error("d.db.Exec(%s, %s, %d) error(%v)", _addServiceSQL, service.Name, service.Status, err)
  78. return
  79. }
  80. if id, err = res.LastInsertId(); err != nil {
  81. log.Error("res.LastInsertId() error(%v)", err)
  82. }
  83. return
  84. }
  85. // AddEvent insert service to db.
  86. func (d *Dao) AddEvent(c context.Context, event *model.Event) (id int64, err error) {
  87. var (
  88. res xsql.Result
  89. )
  90. if res, err = d.db.Exec(c, _addEventSQL, event.Name, event.NickName, event.ServiceID, event.Status, time.Now()); err != nil {
  91. log.Error("d.db.Exec(%s, %s, %s, %d, %d) error(%v)", _addEventSQL, event.Name, event.NickName, event.ServiceID, event.Status, err)
  92. return
  93. }
  94. if id, err = res.LastInsertId(); err != nil {
  95. log.Error("res.LastInsertId() error(%v)", err)
  96. }
  97. return
  98. }
  99. // Factor get factor from db.
  100. func (d *Dao) Factor(c context.Context, serviceID, eventID int64, riskLevel int8) (factor *model.Factor, err error) {
  101. var (
  102. row *sql.Row
  103. )
  104. factor = &model.Factor{}
  105. row = d.db.QueryRow(c, _factorSQL, serviceID, eventID, riskLevel)
  106. if err = row.Scan(&factor.ID, &factor.NickName, &factor.ServiceID, &factor.EventID, &factor.GroupID, &factor.RiskLevel, &factor.FactorVal, &factor.CTime, &factor.MTime); err != nil {
  107. if err == sql.ErrNoRows {
  108. err = nil
  109. factor = nil
  110. return
  111. }
  112. log.Error("row.Scan() error(%v)", err)
  113. }
  114. return
  115. }
  116. // FactorGroup get factor group from db.
  117. func (d *Dao) FactorGroup(c context.Context, groupName string) (factorGroup *model.FactorGroup, err error) {
  118. var (
  119. row *sql.Row
  120. )
  121. factorGroup = &model.FactorGroup{}
  122. row = d.db.QueryRow(c, _factorGroupSQL, groupName)
  123. if err = row.Scan(&factorGroup.ID, &factorGroup.Name, &factorGroup.CTime); err != nil {
  124. if err == sql.ErrNoRows {
  125. err = nil
  126. factorGroup = nil
  127. return
  128. }
  129. log.Error("row.Scan() error(%v)", err)
  130. }
  131. return
  132. }
  133. func hitInfo(id int64) int64 {
  134. return id % conf.Conf.Property.UserInfoShard
  135. }
  136. func hitHistory(id int64) int64 {
  137. return id % conf.Conf.Property.HistoryShard
  138. }
  139. // BeginTran begin transaction.
  140. func (d *Dao) BeginTran(c context.Context) (*sql.Tx, error) {
  141. return d.db.Begin(c)
  142. }
  143. // UserInfo get info by mid.
  144. func (d *Dao) UserInfo(c context.Context, mid int64) (res *model.UserInfo, err error) {
  145. var (
  146. row *sql.Row
  147. )
  148. res = &model.UserInfo{}
  149. row = d.db.QueryRow(c, fmt.Sprintf(_userInfoSQL, hitInfo(mid)), mid)
  150. if err = row.Scan(&res.ID, &res.Mid, &res.Score, &res.BaseScore, &res.EventScore, &res.State, &res.ReliveTimes, &res.CTime, &res.MTime); err != nil {
  151. if err == sql.ErrNoRows {
  152. err = nil
  153. res = nil
  154. return
  155. }
  156. log.Error("row.Scan() error(%v)", err)
  157. }
  158. return
  159. }
  160. // TxUpdateInfo insert or update user info by mid.
  161. func (d *Dao) TxUpdateInfo(c context.Context, tx *sql.Tx, info *model.UserInfo) (err error) {
  162. if _, err = d.db.Exec(c, fmt.Sprintf(_updateInfoSQL, hitInfo(info.Mid)), info.BaseScore, info.EventScore, info.Score, info.State, info.Mid); err != nil {
  163. log.Error("db.Exec(%d, %+v) error(%v)", info.Mid, info, err)
  164. return
  165. }
  166. return
  167. }
  168. // TxAddInfo add user info.
  169. func (d *Dao) TxAddInfo(c context.Context, tx *sql.Tx, info *model.UserInfo) (id int64, err error) {
  170. var (
  171. res xsql.Result
  172. now = time.Now()
  173. )
  174. if res, err = tx.Exec(fmt.Sprintf(_addUserInfoSQL, hitInfo(info.Mid)), info.Mid, info.Score, info.BaseScore, info.EventScore, info.State, now, now); err != nil {
  175. log.Error("db.Exec(%d, %v) error(%v)", info.Mid, *info, err)
  176. return
  177. }
  178. return res.LastInsertId()
  179. }
  180. // TxAddEventHistory insert user_event_history.
  181. func (d *Dao) TxAddEventHistory(c context.Context, tx *sql.Tx, ueh *model.UserEventHistory) (err error) {
  182. var (
  183. now = time.Now()
  184. )
  185. if _, err = tx.Exec(fmt.Sprintf(_addEventHistorySQL, hitHistory(ueh.Mid)), ueh.Mid, ueh.EventID, ueh.Score, ueh.BaseScore, ueh.EventScore, ueh.Remark, ueh.Reason, ueh.FactorVal, now); err != nil {
  186. log.Error("db.Exec(%v) error(%v)", ueh, err)
  187. return
  188. }
  189. return
  190. }
  191. // EventHistoryByMidAndEvent get one event history with mid and eventID from db.
  192. func (d *Dao) EventHistoryByMidAndEvent(c context.Context, mid int64, eventID int64) (res *model.UserEventHistory, err error) {
  193. var (
  194. row *sql.Row
  195. )
  196. res = &model.UserEventHistory{}
  197. row = d.db.QueryRow(c, fmt.Sprintf(_getEventHistoryByMidAndEventSQL, hitHistory(mid)), mid, eventID)
  198. if err = row.Scan(&res.Mid, &res.EventID); err != nil {
  199. if err == sql.ErrNoRows {
  200. return nil, nil
  201. }
  202. log.Error("row.Scan() error:(%v)", err)
  203. }
  204. return
  205. }
  206. // TxAddPunishment insert punishment.
  207. func (d *Dao) TxAddPunishment(c context.Context, tx *sql.Tx, mid int64, t int8, reason string) (err error) {
  208. var (
  209. now = time.Now()
  210. )
  211. if _, err = tx.Exec(_addPunishmentSQL, mid, t, reason, now); err != nil {
  212. log.Error("db.Exec(%d, %d, %s) error(%v)", mid, t, reason, err)
  213. return
  214. }
  215. return
  216. }
  217. // TxAddPunishmentQueue insert punishment queue.
  218. func (d *Dao) TxAddPunishmentQueue(c context.Context, tx *sql.Tx, mid int64, blockNo int64) (err error) {
  219. var (
  220. now = time.Now()
  221. )
  222. if _, err = tx.Exec(_addPunishmentQueueSQL, mid, blockNo, now, now); err != nil {
  223. log.Error("TxAddPunishmentQueue:db.Exec(%d) error(%v)", mid, err)
  224. return
  225. }
  226. return
  227. }
  228. // AddPunishmentQueue insert punishment queue.
  229. func (d *Dao) AddPunishmentQueue(c context.Context, mid int64, blockNo int64) (err error) {
  230. var (
  231. now = time.Now()
  232. )
  233. if _, err = d.db.Exec(c, _addPunishmentQueueSQL, mid, blockNo, now, now); err != nil {
  234. log.Error("AddPunishmentQueue:db.Exec(%d) error(%v)", mid, err)
  235. return
  236. }
  237. return
  238. }
  239. // TxUpdateEventScore update user event score.
  240. func (d *Dao) TxUpdateEventScore(c context.Context, tx *sql.Tx, mid int64, escore, score int8) (err error) {
  241. if _, err = tx.Exec(fmt.Sprintf(_updateEventScoreSQL, hitInfo(mid)), escore, score, mid); err != nil {
  242. log.Error("db.TxUpdateEventScore(%s, %d, %d, %d) error(%v)", _updateEventScoreSQL, escore, score, mid, err)
  243. return
  244. }
  245. return
  246. }
  247. //TxUpdateBaseScore do update user base score.
  248. func (d *Dao) TxUpdateBaseScore(c context.Context, tx *sql.Tx, ui *model.UserInfo) (err error) {
  249. if _, err = tx.Exec(fmt.Sprintf(_updateBaseScoreSQL, hitInfo(ui.Mid)), ui.BaseScore, ui.Score, ui.Mid); err != nil {
  250. log.Error("db.TxUpdateBaseScore(%d, %d, %d) error(%v)", ui.BaseScore, ui.Score, ui.Mid, err)
  251. return
  252. }
  253. return
  254. }
  255. //TxClearReliveTimes do clear user relivetimes.
  256. func (d *Dao) TxClearReliveTimes(c context.Context, tx *sql.Tx, ui *model.UserInfo) (err error) {
  257. if _, err = tx.Exec(fmt.Sprintf(_clearReliveTimesSQL, hitInfo(ui.Mid)), ui.ReliveTimes, ui.Mid); err != nil {
  258. log.Error("db.TxClearReliveTimes(%d, %d) error(%v)", ui.ReliveTimes, ui.Mid, err)
  259. return
  260. }
  261. return
  262. }
  263. // Configs spy system configs.
  264. func (d *Dao) Configs(c context.Context) (res map[string]string, err error) {
  265. var rows *sql.Rows
  266. if rows, err = d.db.Query(c, _getAllConfigSQL); err != nil {
  267. log.Error("d.getAllConfigSQL.Query error(%v)", err)
  268. return
  269. }
  270. defer rows.Close()
  271. res = make(map[string]string)
  272. for rows.Next() {
  273. var r model.Config
  274. if err = rows.Scan(&r.ID, &r.Property, &r.Name, &r.Val, &r.Ctime); err != nil {
  275. log.Error("row.Scan() error(%v)", err)
  276. res = nil
  277. return
  278. }
  279. res[r.Property] = r.Val
  280. }
  281. err = rows.Err()
  282. return
  283. }
  284. // HistoryList query .
  285. func (d *Dao) HistoryList(c context.Context, mid int64, size int) (res []*model.UserEventHistory, err error) {
  286. var rows *sql.Rows
  287. if rows, err = d.db.Query(c, fmt.Sprintf(_getHistoryListSQL, hitHistory(mid)), mid, size); err != nil {
  288. log.Error("d.HistoryList.Query(%d, %d) error(%v)", mid, size, err)
  289. return
  290. }
  291. defer rows.Close()
  292. for rows.Next() {
  293. r := &model.UserEventHistory{}
  294. if err = rows.Scan(&r.Remark, &r.Reason); err != nil {
  295. log.Error("row.Scan() error(%v)", err)
  296. res = nil
  297. return
  298. }
  299. res = append(res, r)
  300. }
  301. err = rows.Err()
  302. return
  303. }
  304. // TxUpdateEventScoreReLive update event score and times
  305. func (d *Dao) TxUpdateEventScoreReLive(c context.Context, tx *sql.Tx, mid int64, escore, score int8) (err error) {
  306. if _, err = tx.Exec(fmt.Sprintf(_updateEventScoreReLiveSQL, hitInfo(mid)), escore, score, mid); err != nil {
  307. log.Error("db.TxUpdateEventScoreReLive(%s, %d, %d, %d) error(%v)", _updateEventScoreReLiveSQL, escore, score, mid, err)
  308. return
  309. }
  310. return
  311. }
  312. //StatListByMid stat list by mid.
  313. func (d *Dao) StatListByMid(c context.Context, mid int64) (list []*model.Statistics, err error) {
  314. var (
  315. rows *sql.Rows
  316. )
  317. list = make([]*model.Statistics, 0)
  318. if rows, err = d.db.Query(c, _statListByMidSQL, mid); err != nil {
  319. log.Error("d.db.Query(%s) error(%v)", _statListByMidSQL, err)
  320. return
  321. }
  322. defer rows.Close()
  323. for rows.Next() {
  324. var r = &model.Statistics{}
  325. if err = rows.Scan(&r.EventID, &r.Quantity); err != nil {
  326. log.Error("rows.Scan() error(%v)", err)
  327. return
  328. }
  329. list = append(list, &model.Statistics{
  330. EventID: r.EventID,
  331. Quantity: r.Quantity,
  332. })
  333. }
  334. return
  335. }
  336. //StatListByIDAndMid stat list by id.
  337. func (d *Dao) StatListByIDAndMid(c context.Context, mid, id int64) (list []*model.Statistics, err error) {
  338. var (
  339. rows *sql.Rows
  340. )
  341. list = make([]*model.Statistics, 0)
  342. if rows, err = d.db.Query(c, _statListByIDAndMidSQL, mid, id); err != nil {
  343. log.Error("d.db.Query(%s) error(%v)", _statListByIDAndMidSQL, err)
  344. return
  345. }
  346. defer rows.Close()
  347. for rows.Next() {
  348. var r = &model.Statistics{}
  349. if err = rows.Scan(&r.EventID, &r.Quantity); err != nil {
  350. log.Error("rows.Scan() error(%v)", err)
  351. return
  352. }
  353. list = append(list, &model.Statistics{
  354. EventID: r.EventID,
  355. Quantity: r.Quantity,
  356. })
  357. }
  358. return
  359. }
  360. //StatListByID stat list by id.
  361. func (d *Dao) StatListByID(c context.Context, id int64) (list []*model.Statistics, err error) {
  362. var (
  363. rows *sql.Rows
  364. )
  365. list = make([]*model.Statistics, 0)
  366. if rows, err = d.db.Query(c, _statListByIDSQL, id); err != nil {
  367. log.Error("d.db.Query(%s) error(%v)", _statListByIDSQL, err)
  368. return
  369. }
  370. defer rows.Close()
  371. for rows.Next() {
  372. var r = &model.Statistics{}
  373. if err = rows.Scan(&r.EventID, &r.Quantity); err != nil {
  374. log.Error("rows.Scan() error(%v)", err)
  375. return
  376. }
  377. list = append(list, &model.Statistics{
  378. EventID: r.EventID,
  379. Quantity: r.Quantity,
  380. })
  381. }
  382. return
  383. }
  384. //AllEvent all event.
  385. func (d *Dao) AllEvent(c context.Context) (list []*model.Event, err error) {
  386. var (
  387. rows *sql.Rows
  388. )
  389. list = make([]*model.Event, 0)
  390. if rows, err = d.db.Query(c, _allEventSQL); err != nil {
  391. log.Error("d.db.Query(%s) error(%v)", _allEventSQL, err)
  392. return
  393. }
  394. defer rows.Close()
  395. for rows.Next() {
  396. var event = &model.Event{}
  397. if err = rows.Scan(&event.ID, &event.Name, &event.NickName, &event.ServiceID, &event.Status, &event.CTime, &event.MTime); err != nil {
  398. log.Error("rows.Scan() error(%v)", err)
  399. return
  400. }
  401. list = append(list, &model.Event{
  402. ID: event.ID,
  403. Name: event.Name,
  404. NickName: event.NickName,
  405. ServiceID: event.ServiceID,
  406. Status: event.Status,
  407. CTime: event.CTime,
  408. MTime: event.MTime,
  409. })
  410. }
  411. return
  412. }
  413. // TelLevel tel level.
  414. func (d *Dao) TelLevel(c context.Context, mid int64) (res *model.TelRiskLevel, err error) {
  415. var (
  416. row *sql.Row
  417. )
  418. res = &model.TelRiskLevel{}
  419. row = d.db.QueryRow(c, _telLevelSQL, mid)
  420. if err = row.Scan(&res.ID, &res.Mid, &res.Level, &res.Origin, &res.Ctime, &res.Mtime); err != nil {
  421. if err == sql.ErrNoRows {
  422. err = nil
  423. res = nil
  424. return
  425. }
  426. log.Error("row.Scan() error(%v)", err)
  427. }
  428. return
  429. }
  430. // AddTelLevelInfo add tel level info.
  431. func (d *Dao) AddTelLevelInfo(c context.Context, t *model.TelRiskLevel) (id int64, err error) {
  432. var (
  433. res xsql.Result
  434. )
  435. if res, err = d.db.Exec(c, _addTelLevelSQL, t.Mid, t.Level, t.Origin, time.Now()); err != nil {
  436. log.Error("d.db.Exec(%s, %v) error(%v)", _addTelLevelSQL, t, err)
  437. return
  438. }
  439. if id, err = res.LastInsertId(); err != nil {
  440. log.Error("res.LastInsertId() error(%v)", err)
  441. }
  442. return
  443. }