"""Added instance_url field to GitProject

Revision ID: e35bb9ce7313
Revises: a0e48c400be4
Create Date: 2020-11-05 11:33:02.769607

"""
from urllib.parse import urlparse

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

from packit_service.models import GitProjectModel

# revision identifiers, used by Alembic.
revision = "e35bb9ce7313"
down_revision = "a0e48c400be4"
branch_labels = None
depends_on = None


def upgrade():
    bind = op.get_bind()
    session = orm.Session(bind=bind)
    op.add_column("git_projects", sa.Column("instance_url", sa.String(), nullable=True))
    for git_project in session.query(GitProjectModel):
        git_project.instance_url = urlparse(git_project.project_url).hostname
    session.commit()
    op.alter_column("git_projects", "instance_url", nullable=False)


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_column("git_projects", "instance_url")
    # ### end Alembic commands ###
