"""deduplicate_ref

Revision: 0154
Revision ID: 64703a6228b
Revises: 25a07f58df10
Create Date: 2018-12-13 16:28:06.429052

"""

# revision identifiers, used by Alembic.
revision = '64703a6228b'
down_revision = '25a07f58df10'
branch_labels = None
depends_on = None

from alembic import op
import sqlalchemy as sa


def upgrade():
    conn = op.get_bind()
    q = sa.text("select id, project_id, ref from cards c1 where (select count(*) from cards c2 where c2.ref = c1.ref and c2.project_id = c1.project_id) > 1")

    refs_per_project = {}
    for r in conn.execute(q):
        refs = refs_per_project.setdefault(r[1], [])
        if r[2] not in refs:
            refs.append(r[2])
        else:
            new_ref = conn.execute(sa.text("UPDATE projects SET ref_counter = ref_counter + 1 WHERE id = %s RETURNING ref_counter" % r[1])).scalar()
            op.execute("UPDATE cards SET ref = %s, cache_id = uuid_generate_v4() WHERE id = %s" % (new_ref, r[0]))



def downgrade():
    pass
