-- Fix partitioned table constraints for PostgreSQL compliance
-- Unique constraints on partitioned tables must include all partitioning columns

-- Only apply fix if hft_performance_stats table exists
DO $$
BEGIN
    IF EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'hft_performance_stats') THEN
        -- Drop the problematic unique index on hft_performance_stats materialized view
        DROP INDEX IF EXISTS idx_hft_performance_stats_unique;

        -- Recreate the unique index including the partitioning column (minute_bucket)
        -- This ensures the constraint includes the partitioning column as required by PostgreSQL
        CREATE UNIQUE INDEX idx_hft_performance_stats_unique
        ON hft_performance_stats(minute_bucket, metric_type, component);

        -- Add comment explaining the fix
        COMMENT ON INDEX idx_hft_performance_stats_unique IS 'Fixed unique index including partitioning column for PostgreSQL compliance';
    END IF;
END $$;