"""add created at

Revision ID: f4fe705a0e6f
Revises: 2ac96cb22a98
Create Date: 2020-06-08 19:10:58.584416

"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.orm import sessionmaker

Session = sessionmaker()

# revision identifiers, used by Alembic.
revision = "f4fe705a0e6f"
down_revision = "2ac96cb22a98"
branch_labels = None
depends_on = None


def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column("cores", sa.Column("created_at", sa.DateTime()))
    op.drop_column("cores", "sections")
    op.add_column("expeditions", sa.Column("created_at", sa.DateTime()))
    op.add_column("holes", sa.Column("created_at", sa.DateTime()))
    op.add_column("samples", sa.Column("created_at", sa.DateTime()))
    op.add_column("samples_taxa", sa.Column("created_at", sa.DateTime()))
    op.add_column("sections", sa.Column("created_at", sa.DateTime()))
    op.add_column("sites", sa.Column("created_at", sa.DateTime()))
    op.add_column("taxa", sa.Column("created_at", sa.DateTime()))

    bind = op.get_bind()
    session = Session(bind=bind)
    session.execute("UPDATE cores set created_at = now();")
    session.execute("UPDATE expeditions set created_at = now();")
    session.execute("UPDATE holes set created_at = now();")
    session.execute("UPDATE samples set created_at = now();")
    session.execute("UPDATE samples_taxa set created_at = now();")
    session.execute("UPDATE sections set created_at = now();")
    session.execute("UPDATE sites set created_at = now();")
    session.execute("UPDATE taxa set created_at = now();")

    op.alter_column("cores", "created_at", existing_type=sa.DateTime(), nullable=False)
    op.alter_column(
        "expeditions", "created_at", existing_type=sa.DateTime(), nullable=False
    )
    op.alter_column("holes", "created_at", existing_type=sa.DateTime(), nullable=False)
    op.alter_column(
        "samples", "created_at", existing_type=sa.DateTime(), nullable=False
    )
    op.alter_column(
        "samples_taxa", "created_at", existing_type=sa.DateTime(), nullable=False
    )
    op.alter_column(
        "sections", "created_at", existing_type=sa.DateTime(), nullable=False
    )
    op.alter_column("sites", "created_at", existing_type=sa.DateTime(), nullable=False)
    op.alter_column("taxa", "created_at", existing_type=sa.DateTime(), nullable=False)

    # # ### end Alembic commands ###


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_column("taxa", "created_at")
    op.drop_column("sites", "created_at")
    op.drop_column("sections", "created_at")
    op.drop_column("samples_taxa", "created_at")
    op.drop_column("samples", "created_at")
    op.drop_column("holes", "created_at")
    op.drop_column("expeditions", "created_at")
    op.add_column(
        "cores", sa.Column("sections", sa.INTEGER(), autoincrement=False, nullable=True)
    )
    op.drop_column("cores", "created_at")
    # ### end Alembic commands ###
