"""Adds api key field to pool table

Revision ID: a08ce5e7246a
Revises: 6a59928efeb7
Create Date: 2022-12-20 18:10:19.540534

"""
import secrets

from alembic import op
import sqlalchemy as sa
from sqlalchemy.orm import Session
from sqlalchemy.ext.automap import automap_base

revision = 'a08ce5e7246a'
down_revision = '6a59928efeb7'
branch_labels = None
depends_on = None

Base = automap_base()


def upgrade():
    with op.batch_alter_table('pool', schema=None) as batch_op:
        batch_op.add_column(sa.Column('api_key', sa.String(length=80), nullable=True, unique=False))
    bind = op.get_bind()
    Base.prepare(autoload_with=bind)
    Pool = Base.classes.pool
    session = Session(bind=bind)
    for pool in session.query(Pool).all():
        pool.api_key = secrets.token_urlsafe(nbytes=32)
    session.commit()
    with op.batch_alter_table('pool', schema=None) as batch_op:
        batch_op.alter_column('api_key', nullable=False, unique=True)


def downgrade():
    with op.batch_alter_table('pool', schema=None) as batch_op:
        batch_op.drop_column('api_key')
