"""

Revision ID: 0336_broadcast_msg_content_2
Revises: 0335_broadcast_msg_content
Create Date: 2020-12-04 15:06:22.544803

"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
from sqlalchemy.orm.session import Session

from app.models import BroadcastMessage

revision = '0336_broadcast_msg_content_2'
down_revision = '0335_broadcast_msg_content'


def upgrade():
    session = Session(bind=op.get_bind())

    broadcast_messages = session.query(BroadcastMessage).filter(BroadcastMessage.content == None)

    for broadcast_message in broadcast_messages:
        broadcast_message.content = broadcast_message.template._as_utils_template_with_personalisation(
            broadcast_message.personalisation
        ).content_with_placeholders_filled_in

    session.commit()

    op.alter_column('broadcast_message', 'content', nullable=False)


def downgrade():
    op.alter_column('broadcast_message', 'content', nullable=True)

"""

Revision ID: 0336_broadcast_msg_content_2
Revises: 0335_broadcast_msg_content
Create Date: 2020-12-04 15:06:22.544803

"""
from alembic import op
import sqlalchemy as sa
from notifications_utils.template import BroadcastMessageTemplate
from sqlalchemy.dialects import postgresql
from sqlalchemy.orm.session import Session

from app.models import BroadcastMessage

revision = '0336_broadcast_msg_content_2'
down_revision = '0335_broadcast_msg_content'


def upgrade():

    conn = op.get_bind()

    results = conn.execute(sa.text("""
        UPDATE
            broadcast_message
        SET
            content = templates_history.content
        FROM
            templates_history
        WHERE
            broadcast_message.content is NULL and
            broadcast_message.template_id = templates_history.id and
            broadcast_message.template_version = templates_history.version
        ;
    """))


def downgrade():
    op.alter_column('broadcast_message', 'content', nullable=True)

Rewrite previous migration in raw SQL
Rewrite previous migration in raw SQL

We shouldn’t import models into migrations because if the model changes
later down the line then the migration can’t be re-run at a later date
(for example to rebuild a database from scratch).

We don’t need to encode the content before storing it (we’ll always do
that before rendering/sending) so we don’t need to use
`BroadcastMessageTemplate`.

And given that no past broadcasts will have personalisation, we don’t
need to replace the personalisation in the template before rendering it.
So we can just copy the raw content from the templates table.
