"""remove projects members_cache_id duplicates

Revision: 0093
Revision ID: 248a52525842
Revises: 1f5aaa83bebb
Create Date: 2017-05-18 23:22:19.424028

"""

# revision identifiers, used by Alembic.
revision = '248a52525842'
down_revision = '1f5aaa83bebb'
branch_labels = None
depends_on = None

from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql

import uuid

projects = sa.Table(
    'projects',
    sa.MetaData(),
    sa.Column('id', sa.Integer, primary_key=True),
    sa.Column('members_cache_id', sa.String)
)

def upgrade():
    conn = op.get_bind()

    q = sa.text("""
        SELECT id FROM projects WHERE members_cache_id IN (
        SELECT projects.members_cache_id
        FROM projects
        GROUP BY projects.members_cache_id
        HAVING count(projects.members_cache_id) > 1 )
    """)
    updates = []
    for r in conn.execute(q):
        updates.append({'pid': r[0], 'members_cache_id': uuid.uuid4()})
    if updates:
        conn.execute(projects.update().where(projects.c.id==sa.bindparam('pid')).values(
            members_cache_id=sa.bindparam('members_cache_id')), updates)


def downgrade():
    pass
