"""query_charts_options

Revision ID: 0277
Revises: 0276
Create Date: 2025-08-19 10:25:34.363934

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


# revision identifiers, used by Alembic.
revision = '0277'
down_revision = '0276'
branch_labels = None
depends_on = None


views = sa.Table(
    'views',
    sa.MetaData(),
    sa.Column('id', sa.Integer, primary_key=True),
    sa.Column('mode', sa.String),
    sa.Column('mode_options', postgresql.JSONB)
)


def upgrade():
    conn = op.get_bind()
    updates = []
    for view in conn.execute(views.select().where(views.c.mode == 'report')):
        if isinstance(view['mode_options'], dict) and view['mode_options'].get('widgets'):
            for widget in view['mode_options']['widgets']:
                if isinstance(widget['options'], list):
                    widget['options'] = {} # catch a previous bug
                if not widget['options'].get('compute') and widget['options'].get('query'):
                    widget['options']['compute'] = "query"
            updates.append({'vid': view['id'], 'opts': view['mode_options']})

    if updates:
        stmt = views.update().where(views.c.id==sa.bindparam('vid')).values(mode_options=sa.bindparam('opts'))
        conn.execute(stmt, updates)


def downgrade():
    pass
