-
Notifications
You must be signed in to change notification settings - Fork 230
/
db.go
91 lines (83 loc) · 1.99 KB
/
db.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package schedulemanager
import (
"context"
"database/sql"
"github.com/target/goalert/engine/processinglock"
"github.com/target/goalert/util"
)
// DB will manage schedules and schedule rules in Postgres.
type DB struct {
lock *processinglock.Lock
overrides *sql.Stmt
rules *sql.Stmt
currentTime *sql.Stmt
getOnCall *sql.Stmt
endOnCall *sql.Stmt
startOnCall *sql.Stmt
}
// Name returns the name of the module.
func (db *DB) Name() string { return "Engine.ScheduleManager" }
// NewDB will create a new DB instance, preparing all statements.
func NewDB(ctx context.Context, db *sql.DB) (*DB, error) {
lock, err := processinglock.NewLock(ctx, db, processinglock.Config{
Type: processinglock.TypeSchedule,
Version: 2,
})
if err != nil {
return nil, err
}
p := &util.Prepare{DB: db, Ctx: ctx}
return &DB{
lock: lock,
overrides: p.P(`
select
add_user_id,
remove_user_id,
tgt_schedule_id
from user_overrides
where now() between start_time and end_time
`),
rules: p.P(`
select
rule.schedule_id,
ARRAY[
sunday,
monday,
tuesday,
wednesday,
thursday,
friday,
saturday
],
start_time,
end_time,
sched.time_zone,
coalesce(rule.tgt_user_id, part.user_id)
from schedule_rules rule
join schedules sched on sched.id = rule.schedule_id
left join rotation_state rState on rState.rotation_id = rule.tgt_rotation_id
left join rotation_participants part on part.id = rState.rotation_participant_id
where
coalesce(rule.tgt_user_id, part.user_id) notnull
`),
getOnCall: p.P(`
select schedule_id, user_id
from schedule_on_call_users
where
end_time isnull
`),
startOnCall: p.P(`
insert into schedule_on_call_users (schedule_id, start_time, user_id)
values ($1, now(), $2)
`),
endOnCall: p.P(`
update schedule_on_call_users
set end_time = now()
where
schedule_id = $1 and
user_id = $2 and
end_time isnull
`),
currentTime: p.P(`select now()`),
}, p.Err
}