File size: 1,657 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
-- name: RotMgrRotationData :one
-- Get rotation data for a given rotation ID
SELECT
    now()::timestamptz AS now,
    sqlc.embed(rot),
    coalesce(state.version, 0) AS state_version,
    coalesce(state.position, 0) AS state_position,
    state.shift_start AS state_shift_start,
    ARRAY (
        SELECT
            p.id
        FROM
            rotation_participants p
        WHERE
            p.rotation_id = rot.id
        ORDER BY
            position)::uuid[] AS participants
    FROM
        rotations rot
    LEFT JOIN rotation_state state ON rot.id = state.rotation_id
WHERE
    rot.id = @rotation_id;

-- name: RotMgrStart :exec
-- Start a rotation.
INSERT INTO rotation_state(rotation_id, position, shift_start, rotation_participant_id)
SELECT
    p.rotation_id,
    0,
    now(),
    id
FROM
    rotation_participants p
WHERE
    p.rotation_id = @rotation_id
    AND position = 0;

-- name: RotMgrEnd :exec
-- End a rotation.
DELETE FROM rotation_state
WHERE rotation_id = @rotation_id;

-- name: RotMgrUpdate :exec
-- Update the rotation state.
UPDATE
    rotation_state
SET
    position = @position,
    shift_start = now(),
    rotation_participant_id = @rotation_participant_id,
    version = 2
WHERE
    rotation_id = @rotation_id;

-- name: RotMgrFindWork :many
WITH items AS (
    SELECT
        id,
        entity_id
    FROM
        entity_updates
    WHERE
        entity_type = 'rotation'
    FOR UPDATE
        SKIP LOCKED
    LIMIT 1000
),
_delete AS (
    DELETE FROM entity_updates
    WHERE id IN (
            SELECT
                id
            FROM
                items))
SELECT DISTINCT
    entity_id
FROM
    items;