"""clean orgs

Revision: 0056
Revision ID: 24537c5bdb0
Revises: 50cea6671951
Create Date: 2016-04-14 19:26:53.721677

"""

# revision identifiers, used by Alembic.
revision = '24537c5bdb0'
down_revision = '50cea6671951'
branch_labels = None
depends_on = None

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

def upgrade():
    op.execute("DELETE FROM organizations WHERE is_user_org IS TRUE AND created_by_id IS NULL")
    op.execute("""DELETE FROM organizations WHERE id IN (
                SELECT req.id FROM (
                SELECT o.id, COUNT(o.name) \"members\" FROM organizations o
                LEFT OUTER JOIN organization_members om ON o.id = om.org_id
                WHERE o.created_by_id IS NULL AND o.is_user_org IS FALSE
                GROUP BY o.id) req
                WHERE members > 0)""")


def downgrade():
    pass
