"""groups_cache_id

Revision: 0033
Revision ID: 166735e0e8f6
Revises: 21a6d541bc0f
Create Date: 2015-11-19 16:27:35.080081

"""

# revision identifiers, used by Alembic.
revision = '166735e0e8f6'
down_revision = '21a6d541bc0f'
branch_labels = None
depends_on = None

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

def upgrade():
    op.add_column('card_group_types', sa.Column('cache_id', sa.String(), nullable=True))
    op.add_column('card_groups', sa.Column('cache_id', sa.String(), nullable=True))

    conn = op.get_bind()
    r = conn.execute("select exists(select * from pg_proc where proname = 'uuid_generate_v4');")
    if not r.first()[0]:
        op.execute("""CREATE FUNCTION uuid_generate_v4() RETURNS uuid
            AS 'SELECT md5(random()::text || clock_timestamp()::text)::uuid;'
            LANGUAGE SQL;""")

    op.execute('UPDATE card_group_types SET cache_id = uuid_generate_v4()')
    op.execute('UPDATE card_groups SET cache_id = uuid_generate_v4()')


def downgrade():
    op.drop_column('card_groups', 'cache_id')
    op.drop_column('card_group_types', 'cache_id')