-- ============================================================================ -- OrbiQuant IA - Trading Platform -- Schema: auth -- File: functions/03-cleanup_expired_sessions.sql -- Description: Function to cleanup expired and inactive sessions -- ============================================================================ CREATE OR REPLACE FUNCTION auth.cleanup_expired_sessions( p_batch_size INTEGER DEFAULT 1000 ) RETURNS TABLE( deleted_count INTEGER, execution_time_ms NUMERIC ) AS $$ DECLARE v_start_time TIMESTAMPTZ; v_deleted_count INTEGER; BEGIN v_start_time := clock_timestamp(); -- Delete expired sessions WITH deleted AS ( DELETE FROM auth.sessions WHERE ( -- Expired sessions expires_at < NOW() OR -- Inactive sessions older than 30 days (is_active = false AND invalidated_at < NOW() - INTERVAL '30 days') ) AND id IN ( SELECT id FROM auth.sessions WHERE ( expires_at < NOW() OR (is_active = false AND invalidated_at < NOW() - INTERVAL '30 days') ) LIMIT p_batch_size ) RETURNING * ) SELECT COUNT(*)::INTEGER INTO v_deleted_count FROM deleted; RETURN QUERY SELECT v_deleted_count, EXTRACT(EPOCH FROM (clock_timestamp() - v_start_time) * 1000)::NUMERIC; END; $$ LANGUAGE plpgsql; COMMENT ON FUNCTION auth.cleanup_expired_sessions(INTEGER) IS 'Deletes expired and old inactive sessions in batches. Returns deleted count and execution time.'; -- Example usage: -- SELECT * FROM auth.cleanup_expired_sessions(1000); -- Recommended: Schedule this function to run periodically via pg_cron or external scheduler -- Example pg_cron schedule (runs daily at 2 AM): -- SELECT cron.schedule('cleanup-expired-sessions', '0 2 * * *', -- 'SELECT auth.cleanup_expired_sessions(1000);');