DO $$
DECLARE
    r RECORD;
BEGIN
    FOR r IN
        SELECT table_schema, table_name, column_name
        FROM information_schema.columns
        WHERE table_schema = 'public'
          AND column_name <> lower(column_name)
        ORDER BY table_name, column_name
    LOOP
        -- Skip if a lowercase version already exists to avoid collisions.
        IF EXISTS (
            SELECT 1
            FROM information_schema.columns c
            WHERE c.table_schema = r.table_schema
              AND c.table_name = r.table_name
              AND c.column_name = lower(r.column_name)
        ) THEN
            RAISE NOTICE 'Skip %.%: % -> % (target exists)', r.table_name, r.column_name, r.column_name, lower(r.column_name);
        ELSE
            EXECUTE format(
                'ALTER TABLE %I.%I RENAME COLUMN %I TO %I',
                r.table_schema,
                r.table_name,
                r.column_name,
                lower(r.column_name)
            );
            RAISE NOTICE 'Renamed %.%: % -> %', r.table_name, r.column_name, r.column_name, lower(r.column_name);
        END IF;
    END LOOP;
END $$;
