forked from mtusi2026/mtusi2026lab6
34 lines
1.3 KiB
SQL
34 lines
1.3 KiB
SQL
CREATE TABLE attachment_terminal_events (
|
|
job_id UUID PRIMARY KEY,
|
|
status TEXT NOT NULL,
|
|
accepted_at TIMESTAMPTZ NOT NULL,
|
|
terminal_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(),
|
|
CONSTRAINT attachment_terminal_events_status CHECK (status IN ('ready', 'failed')),
|
|
CONSTRAINT attachment_terminal_events_time CHECK (terminal_at >= accepted_at)
|
|
);
|
|
|
|
CREATE INDEX attachment_terminal_events_status_terminal_at_idx
|
|
ON attachment_terminal_events (status, terminal_at);
|
|
|
|
WITH first_replay AS (
|
|
SELECT job_id, MIN(created_at) AS created_at
|
|
FROM attachment_replay_audit
|
|
GROUP BY job_id
|
|
)
|
|
INSERT INTO attachment_terminal_events (job_id, status, accepted_at, terminal_at)
|
|
SELECT jobs.id, 'failed', LEAST(jobs.created_at, first_replay.created_at), first_replay.created_at
|
|
FROM attachment_jobs jobs
|
|
JOIN first_replay ON first_replay.job_id = jobs.id
|
|
ON CONFLICT (job_id) DO NOTHING;
|
|
|
|
INSERT INTO attachment_terminal_events (job_id, status, accepted_at, terminal_at)
|
|
SELECT jobs.id, jobs.status, LEAST(jobs.created_at, jobs.updated_at), jobs.updated_at
|
|
FROM attachment_jobs jobs
|
|
WHERE jobs.status IN ('ready', 'failed')
|
|
AND NOT EXISTS (
|
|
SELECT 1
|
|
FROM attachment_replay_audit replay
|
|
WHERE replay.job_id = jobs.id
|
|
)
|
|
ON CONFLICT (job_id) DO NOTHING;
|