"""Add User.created_at

Revision ID: 5ac51663112f
Revises: ce96e75a85e4
Create Date: 2022-07-28 17:59:59.649050

"""
from datetime import datetime

import sqlalchemy as sa
from alembic import op
from sqlalchemy import orm

# revision identifiers, used by Alembic.
revision = "5ac51663112f"
down_revision = "ce96e75a85e4"
branch_labels = None
depends_on = None

Base = orm.declarative_base()


class User(Base):
    __tablename__ = "users"
    id = sa.Column(sa.Integer, primary_key=True)
    created_at = sa.Column(sa.DateTime, default=datetime.utcnow, nullable=False)


def upgrade() -> None:
    now = datetime.utcnow()
    op.add_column("users", sa.Column("created_at", sa.DateTime(), nullable=True))

    bind = op.get_bind()
    session = orm.Session(bind=bind)
    for user in session.query(User).all():
        user.created_at = now
        session.add(user)
    session.commit()

    with op.batch_alter_table("users") as batch_op:
        batch_op.alter_column("created_at", existing_type=sa.DATETIME(), nullable=False)


def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_column("users", "created_at")
    # ### end Alembic commands ###
