"""Add dataset record count table

Revision ID: 39abe82f389f
Revises: 83127ad1a00e
Create Date: 2026-03-01 09:22:02.306484

"""

import sqlalchemy as sa
from alembic import op

# revision identifiers, used by Alembic.
revision = "39abe82f389f"
down_revision = "83127ad1a00e"
branch_labels = None
depends_on = None


def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table(
        "dataset_record_count",
        sa.Column("dataset_id", sa.Integer(), nullable=False),
        sa.Column("record_count", sa.Integer(), nullable=False),
        sa.ForeignKeyConstraint(["dataset_id"], ["base_dataset.id"], ondelete="cascade"),
        sa.PrimaryKeyConstraint("dataset_id"),
    )

    # Populate the table with initial record counts
    op.execute(sa.text("""
                       INSERT INTO dataset_record_count (dataset_id, record_count)
                            (SELECT dataset_id, COUNT(*) FROM dataset_direct_records_view GROUP BY dataset_id)
                       """))
    # ### end Alembic commands ###


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_table("dataset_record_count")
    # ### end Alembic commands ###
