-- Delivery state is separate from visibility. A scheduled alert becomes visible -- at start_time; this state makes sure its push notification is sent once. ALTER TABLE alerts ADD COLUMN IF NOT EXISTS notification_sent_at TIMESTAMPTZ, ADD COLUMN IF NOT EXISTS notification_claimed_at TIMESTAMPTZ, ADD COLUMN IF NOT EXISTS notification_attempts INTEGER NOT NULL DEFAULT 0; CREATE INDEX IF NOT EXISTS idx_alerts_pending_notification ON alerts (start_time) WHERE is_active = true AND notification_sent_at IS NULL; -- Earlier versions sent every active alert immediately on creation. Mark those -- already-created future alerts as dispatched, so upgrading does not notify -- passengers a second time when the scheduler starts. UPDATE alerts SET notification_sent_at = created_at WHERE notification_sent_at IS NULL AND is_active = true AND start_time > created_at;