"""empty message

Revision ID: d7067cd4169
Revises: 5a34d3b6a160
Create Date: 2014-03-14 16:25:25.820714

"""

# revision identifiers, used by Alembic.
revision = 'd7067cd4169'
down_revision = '5a34d3b6a160'

from alembic import op
import sqlalchemy as sa


def upgrade():
    op.add_column('grano_property', sa.Column('attribute_id', sa.Integer(), nullable=True))

    attributes = sa.sql.table('grano_attribute',
        sa.sql.column('id', sa.Integer),
        sa.sql.column('schema_id', sa.Integer),
        sa.sql.column('name', sa.Unicode)
    )

    properties = sa.sql.table('grano_property',
        sa.sql.column('schema_id', sa.Integer),
        sa.sql.column('attribute_id', sa.Integer),
        sa.sql.column('name', sa.Unicode)
    )

    connection = op.get_bind()
    rp = connection.execute(attributes.select())

    if rp is None:
        return None

    rows = [dict(zip(r.keys(), tuple(r))) for r in rp.fetchall()]
    for row in rows:
        #print row
        q = properties.update()
        q = q.where(properties.c.schema_id==row.get('schema_id'))
        q = q.where(properties.c.name==row.get('name'))
        q = q.values({'attribute_id': row.get('id')})
        #print q, row.get('id')
        op.execute(q)

    q = properties.delete()
    q = q.where(properties.c.attribute_id==None)
    op.execute(q)


def downgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.drop_column('grano_property', 'attribute_id')
    ### end Alembic commands ###
