-- +goose Up -- The newest result per monitor and region, kept up to date as results -- arrive. Finding it in check_results means reading a day of results of -- every monitor, which made every console page slow for organizations -- with many monitors. CREATE TABLE latest_results ( monitor_id uuid NOT NULL, region text NOT NULL, org_id uuid NOT NULL, time timestamptz NOT NULL, ok boolean NOT NULL, latency_ms integer, status_code integer, error text, PRIMARY KEY (monitor_id, region), FOREIGN KEY (monitor_id, org_id) REFERENCES monitors (id, org_id) ON DELETE CASCADE ); CREATE INDEX latest_results_org_idx ON latest_results (org_id); INSERT INTO latest_results (monitor_id, region, org_id, time, ok, latency_ms, status_code, error) SELECT DISTINCT ON (r.monitor_id, r.region) r.monitor_id, r.region, r.org_id, r.time, r.ok, r.latency_ms, r.status_code, r.error FROM check_results r JOIN monitors m ON m.id = r.monitor_id AND m.org_id = r.org_id WHERE r.time > now() - INTERVAL '1 day' ORDER BY r.monitor_id, r.region, r.time DESC; ALTER TABLE latest_results ENABLE ROW LEVEL SECURITY; ALTER TABLE latest_results FORCE ROW LEVEL SECURITY; CREATE POLICY latest_results_tenant ON latest_results FOR ALL USING (app_scope_system() OR org_id = app_org_id()) WITH CHECK (app_scope_system() OR org_id = app_org_id()); -- Console queries name the organization so that these can be used; row -- security alone does not let the planner use an index. CREATE INDEX monitor_regions_org_idx ON monitor_regions (org_id); CREATE INDEX incidents_open_org_idx ON incidents (org_id) WHERE resolved_at IS NULL; -- +goose Down DROP INDEX incidents_open_org_idx; DROP INDEX monitor_regions_org_idx; DROP TABLE latest_results;