Refactor query logic and move to job.go

This commit is contained in:
2023-06-20 15:52:16 +02:00
parent 33613cdda0
commit bb7c1005c9
2 changed files with 79 additions and 84 deletions

View File

@@ -293,24 +293,89 @@ func (r *JobRepository) FindById(jobId int64) (*schema.Job, error) {
}
func (r *JobRepository) FindConcurrentJobs(
job *schema.Job) (*model.JobLinkResultList, error) {
job *schema.Job) (*model.JobLinkResultList, error) {
if job == nil {
return nil, nil
}
query := sq.Select("job.id","job.job_id").From("job").Where("cluster = ?",job.Cluster)
var startTime := job.StartTimeUnix
var stopTime int64
query := sq.Select("job.id", "job.job_id").From("job").Where("cluster = ?", job.Cluster)
var startTime int64
var stopTime int64
if job.State == schema.JobStateRunning {
stopTime = time.Now().Unix()
} else {
stopTime = startTime + int64(job.Duration)
}
startTime = job.StartTimeUnix
// Add 5m overlap for jobs start time at the end
stopTime -= 300
if job.State == schema.JobStateRunning {
stopTime = time.Now().Unix()
} else {
stopTime = startTime + int64(job.Duration)
}
query = query.Where("start_time BETWEEN ? AND ?", startTime, stopTime)
// Add 5m overlap for jobs start time at the end
stopTimeTail := stopTime - 300
startTimeTail := startTime + 10
startTimeFront := startTime + 300
}
queryRunning := query.Where("job.job_state = ?").Where("(job.start_time BETWEEN ? AND ?) OR (job.start_time < ?))",
"running", startTimeTail, stopTimeTail, startTime)
query = query.Where("job.job_state != ?").Where("(job.start_time BETWEEN ? AND ?) OR ((job.start_time + job.duration) BETWEEN ? AND ?) OR ((job.start_time < ?) AND ((job.start_time + job.duration)) > ?)",
"running", startTimeTail, stopTimeTail, startTimeFront, stopTime, startTime, stopTime)
rows, err := query.RunWith(r.stmtCache).Query()
if err != nil {
log.Errorf("Error while running query: %v", err)
return nil, err
}
items := make([]*model.JobLink, 0, 10)
for rows.Next() {
var id, jobId sql.NullInt64
if err = rows.Scan(&id, &jobId); err != nil {
log.Warn("Error while scanning rows")
return nil, err
}
if id.Valid {
items = append(items,
&model.JobLink{
ID: fmt.Sprint(id),
JobID: int(jobId.Int64),
})
}
}
rows, err = queryRunning.RunWith(r.stmtCache).Query()
if err != nil {
log.Errorf("Error while running query: %v", err)
return nil, err
}
for rows.Next() {
var id, jobId sql.NullInt64
if err := rows.Scan(&id, &jobId); err != nil {
log.Warn("Error while scanning rows")
return nil, err
}
if id.Valid {
items = append(items,
&model.JobLink{
ID: fmt.Sprint(id),
JobID: int(jobId.Int64),
})
}
}
cnt := len(items)
return &model.JobLinkResultList{
Items: items,
Count: &cnt,
}, nil
}
// Start inserts a new job in the table, returning the unique job ID.
// Statistics are not transfered!