task_db.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package dao
  2. import (
  3. "context"
  4. "database/sql"
  5. "time"
  6. "go-common/app/job/main/aegis/model"
  7. xsql "go-common/library/database/sql"
  8. "go-common/library/log"
  9. "github.com/pkg/errors"
  10. )
  11. const (
  12. _queryTaskSQL = "SELECT id,business_id,flow_id,rid,admin_id,uid,state,weight,utime,gtime,mid,fans,`group`,reason,ctime,mtime FROM task WHERE state=? AND mtime<=? AND id>? ORDER BY id LIMIT ?"
  13. _upSetWeightSQL = "UPDATE task SET weight=? WHERE id=?"
  14. _assignTaskSQL = "UPDATE task SET admin_id=?,uid=? WHERE id=? AND state=?"
  15. _checkTaskSQL = "SELECT id FROM task WHERE flow_id=? AND rid=? AND state<?"
  16. )
  17. // CheckTask 某资源存在未完成任务,不重复添加
  18. func (d *Dao) CheckTask(c context.Context, flowid, rid int64) (id int64) {
  19. if err := d.fastdb.QueryRow(c, _checkTaskSQL, flowid, rid, model.TaskStateSubmit).Scan(&id); err != nil {
  20. if err == sql.ErrNoRows {
  21. err = nil
  22. } else {
  23. log.Error("d.db.QueryRow error(%v)", err)
  24. }
  25. }
  26. return
  27. }
  28. // AssignTask .
  29. func (d *Dao) AssignTask(c context.Context, task *model.Task) (rows int64, err error) {
  30. var res sql.Result
  31. if res, err = d.fastdb.Exec(c, _assignTaskSQL, task.AdminID, task.UID, task.ID, model.TaskStateInit); err != nil {
  32. log.Error("d.db.Exec error(%v)", errors.WithStack(err))
  33. return
  34. }
  35. return res.RowsAffected()
  36. }
  37. // QueryTask .
  38. func (d *Dao) QueryTask(c context.Context, state int8, mtime time.Time, id, limit int64) (tasks []*model.Task, lastid int64, err error) {
  39. var rows *xsql.Rows
  40. rows, err = d.slowdb.Query(c, _queryTaskSQL, state, mtime, id, limit)
  41. if err != nil {
  42. log.Error("db.Query error(%v)", err)
  43. return
  44. }
  45. defer rows.Close()
  46. for rows.Next() {
  47. task := &model.Task{}
  48. if err = rows.Scan(&task.ID, &task.BusinessID, &task.FlowID, &task.RID, &task.AdminID, &task.UID, &task.State, &task.Weight,
  49. &task.Utime, &task.Gtime, &task.MID, &task.Fans, &task.Group, &task.Reason, &task.Ctime, &task.Mtime); err != nil {
  50. log.Error("rows.Scan error(%v)", err)
  51. return
  52. }
  53. tasks = append(tasks, task)
  54. lastid = task.ID
  55. }
  56. return
  57. }
  58. // SetWeightDB .
  59. func (d *Dao) SetWeightDB(c context.Context, taskid, weight int64) (rows int64, err error) {
  60. res, err := d.fastdb.Exec(c, _upSetWeightSQL, weight, taskid)
  61. if err != nil {
  62. log.Error("db.Exec error(%v)", err)
  63. return
  64. }
  65. return res.LastInsertId()
  66. }