"""backfill bill congress_urls with proper public URLs Bills stored before this fix have congress_url set to the API endpoint (https://api.congress.gov/v3/bill/...) instead of the public page (https://www.congress.gov/bill/...). This migration rebuilds all URLs from the congress_number, bill_type, and bill_number columns which are already stored correctly. Revision ID: 0010 Revises: 0009 Create Date: 2026-03-01 """ import sqlalchemy as sa from alembic import op revision = "0010" down_revision = "0009" branch_labels = None depends_on = None _BILL_TYPE_SLUG = { "hr": "house-bill", "s": "senate-bill", "hjres": "house-joint-resolution", "sjres": "senate-joint-resolution", "hres": "house-resolution", "sres": "senate-resolution", "hconres": "house-concurrent-resolution", "sconres": "senate-concurrent-resolution", } def _ordinal(n: int) -> str: if 11 <= n % 100 <= 13: return f"{n}th" suffixes = {1: "st", 2: "nd", 3: "rd"} return f"{n}{suffixes.get(n % 10, 'th')}" def upgrade(): conn = op.get_bind() bills = conn.execute( sa.text("SELECT bill_id, congress_number, bill_type, bill_number FROM bills") ).fetchall() for bill in bills: slug = _BILL_TYPE_SLUG.get(bill.bill_type, bill.bill_type) url = f"https://www.congress.gov/bill/{_ordinal(bill.congress_number)}-congress/{slug}/{bill.bill_number}" conn.execute( sa.text("UPDATE bills SET congress_url = :url WHERE bill_id = :bill_id"), {"url": url, "bill_id": bill.bill_id}, ) def downgrade(): # Original API URLs cannot be recovered — no-op pass