"""test-permaname-update

Revision ID: d091fc45fa8d
Revises: 2af60fdf97d1
Create Date: 2019-07-23 12:16:08.303441

"""
from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision = "d091fc45fa8d"
down_revision = "2af60fdf97d1"
branch_labels = None
depends_on = None


def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table(
        "dataset_permanames",
        sa.Column("permaname", sa.Text(), nullable=False),
        sa.Column("dataset_id", sa.String(length=80), nullable=True),
        sa.Column("creation_date", sa.DateTime(), nullable=True),
        sa.ForeignKeyConstraint(
            ["dataset_id"],
            ["datasets.id"],
            name=op.f("fk_dataset_permanames_dataset_id_datasets"),
        ),
        sa.PrimaryKeyConstraint("permaname", name=op.f("pk_dataset_permanames")),
    )

    op.execute(
        """
            INSERT into dataset_permanames (permaname, dataset_id, creation_date)
            SELECT d.permaname, d.id, e.creation_date
            FROM datasets d
            JOIN entries e ON e.id = d.id
        """
    )

    op.drop_column("datasets", "permaname")
    # ### end Alembic commands ###


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column(
        "datasets",
        sa.Column("permaname", sa.TEXT(), autoincrement=False, nullable=True),
    )

    op.execute(
        """
            UPDATE
                datasets
            SET
                d.permaname = p.permaname
            FROM
                datasets d
                JOIN dataset_permanames p ON d.id = p.dataset_id
        """
    )

    op.drop_table("dataset_permanames")
    # ### end Alembic commands ###
