"""Allow the namespace column to be nullable.

Revision ID: 9a1087b007d
Revises: 3f4fe1194671
Create Date: 2014-10-01 16:11:21.277226

"""

# revision identifiers, used by Alembic.
revision = '9a1087b007d'
down_revision = '3f4fe1194671'

from alembic import op
import sqlalchemy as sa


def upgrade(tables):
    op.drop_index('repository_namespace_name', table_name='repository')
    op.alter_column('repository', 'namespace', nullable=True, existing_type=sa.String(length=255),
                    server_default=sa.text('NULL'))


def downgrade(tables):
    conn = op.get_bind()
    user_table_name_escaped = conn.dialect.identifier_preparer.format_table(tables['user'])
    conn.execute('update repository set namespace = (select username from {0} where {0}.id = repository.namespace_user_id) where namespace is NULL'.format(user_table_name_escaped))

    op.create_index('repository_namespace_name', 'repository', ['namespace', 'name'], unique=True)
    op.alter_column('repository', 'namespace', nullable=False, existing_type=sa.String(length=255))
