<gh_stars>1-10
"""empty message

Revision ID: 0061 orders txn_id unique
Revises: 0060 set all show_banner_text
Create Date: 2021-11-13 01:20:44.784284

"""

# revision identifiers, used by Alembic.
revision = '0061 orders txn_id unique'
down_revision = '0060 set all show_banner_text'

from alembic import op
import sqlalchemy as sa


def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    conn = op.get_bind()
    res = conn.execute(
        "SELECT txn_id FROM orders GROUP BY txn_id HAVING COUNT(*) > 1"
    )

    results = res.fetchall()

    for r in results:
        res = conn.execute(
            "SELECT id FROM orders WHERE id NOT IN (SELECT order_id FROM tickets) AND"
            " id NOT IN (SELECT order_id FROM book_to_order) AND txn_id='%s'" % r[0]
        )
        res_2 = res.fetchall()

        for i, r_2 in enumerate(res_2):
            print(f"Updating {str(r_2[0])}")
            op.execute(f"UPDATE orders SET txn_id = 'XX-{i}-{r[0]}' WHERE id = '{str(r_2[0])}'")

    op.create_unique_constraint('orders_txn_id_key', 'orders', ['txn_id'])
    # ### end Alembic commands ###


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_constraint('orders_txn_id_key', 'orders', type_='unique')
    # ### end Alembic commands ###
