olirice / alembic_utils

An alembic/sqlalchemy extension for migrating sql views, functions, triggers, and policies
MIT License
193 stars 42 forks source link

Downgrade does not reflect old definition #97

Closed shanelanan closed 2 years ago

shanelanan commented 2 years ago

As of version 0.4.2, the downgrade for views and functions show the new definition, not the old definition.

Steps to reproduce are simply the example in the documentation is not correct.

My migration file that was autogenerated by alembic_utils

"""auto

Revision ID: a5dc9a524375
Revises: d69abee2dacd
Create Date: 2022-07-07 02:14:26.027634

"""
from alembic import op
import sqlalchemy as sa
from alembic_utils.pg_function import PGFunction
from sqlalchemy import text as sql_text

# revision identifiers, used by Alembic.
revision = 'a5dc9a524375'
down_revision = 'd69abee2dacd'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    public_fn_sample = PGFunction(
        schema="public",
        signature="fn_sample(some_text text)",
        definition="returns text\n        as\n        $$ select upper(some_text) || 'def' $$ language SQL"
    )
    op.replace_entity(public_fn_sample)

    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    public_fn_sample = PGFunction(
        schema="public",
        signature="fn_sample(some_text text)",
        definition="returns text\n LANGUAGE sql\nAS $function$ select upper(some_text) || 'def' $function$"
    )
    op.replace_entity(public_fn_sample)
    # ### end Alembic commands ###

The example showing this feature of detecting the old version, but does not:

"""replace

Revision ID: 2
Revises: 1
Create Date: 2020-04-22 09:24:25.679031
"""
from alembic import op
import sqlalchemy as sa
from alembic_utils.pg_function import PGFunction

# revision identifiers, used by Alembic.
revision = '2'
down_revision = '1'
branch_labels = None
depends_on = None

def upgrade():
    public_to_upper_6fa0de = PGFunction(
            schema="public",
            signature="to_upper(some_text text)",
            definition="""
            returns text
            as
            $$ select upper(some_text) || 'def' $$ language SQL;
        """
    )

    op.replace_entity(public_to_upper_6fa0de)

def downgrade():
    public_to_upper_6fa0de = PGFunction(
            schema="public",
            signature="to_upper(some_text text)",
            definition="""returns text
     LANGUAGE sql
    AS $function$ select upper(some_text) || 'abc' $function$"""
    )

    op.replace_entity(public_to_upper_6fa0de)

You will see in def downgrade() that the function definition will be the new definition, and not the old definition to downgrade to.

This defect was detected on Postgres13.