"""views-start

Revision ID: 53fb4e66bf09
Revises: a6a6cdd6ba67
Create Date: 2018-10-05 16:15:48.495745

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

# revision identifiers, used by Alembic.
revision = '53fb4e66bf09'
down_revision = 'a6a6cdd6ba67'
branch_labels = None
depends_on = None


def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###

    create_view_statements = '''
    create view "offer"
     as
    select 
      offer.value->>'id' as offer_id,
      collection,
      id as deal_table_id,
      deal_id,
      deal->>'title' deal_title,
      deal->>'status' deal_status,
      offer.value as offer 
    from 
      deal, 
      jsonb_array_elements(deal->'offers') offer;
     
    create view "project"
     as
    select 
      project.value->>'id' as project_id,
      collection,
      id as deal_table_id,
      deal_id,
      deal->>'title' deal_title,
      deal->>'status' deal_status,
      project.value as project 
    from 
      deal, 
      jsonb_array_elements(deal->'projects') project;

    create view "grant"
     as
    select 
      "grant".value->>'id' as grant_id,
      deal->'investments'->> 'summary' as investment_summary,
      collection,
      id as deal_table_id,
      deal_id,
      deal->>'title' deal_title,
      deal->>'status' deal_status,
      "grant".value as grant 
    from 
      deal, 
      jsonb_array_elements(deal->'investments'->'grants') "grant";

    create view "equity"
     as
    select 
      equity.value->>'id' as equity_id,
      deal->'investments'->> 'summary' as investment_summary,
      collection,
      id as deal_table_id,
      deal_id,
      deal->>'title' deal_title,
      deal->>'status' deal_status,
      equity.value as equity 
    from 
      deal, 
      jsonb_array_elements(deal->'investments'->'equity') equity;

    create view "credit"
     as
    select 
      "credit".value->>'id' as credit_id,
      deal->'investments'->> 'summary' as investment_summary,
      collection,
      id as deal_table_id,
      deal_id,
      deal->>'title' deal_title,
      deal->>'status' deal_status,
      "credit".value as credit 
    from 
      deal, 
      jsonb_array_elements(deal->'investments'->'credit') credit;
    '''

    op.execute(create_view_statements)

    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    drop_view_statements = '''
    drop view "offer";
    drop view "project";
    drop view "grant";
    drop view "equity";
    drop view "credit";
    '''

    op.execute(drop_view_statements)
    # ### end Alembic commands ###
