4

Technologies I am using:

  • python 3.6
  • postgres 10.4
  • flask
  • flask_migrate
  • flask_sqlalchemy

So far I have relied on the autogenerated migration scripts that result from calling python app.py db migrate. I then apply these migration scripts by calling python app.py db upgrade. However my most recent change involves modifying an Enum that I have used to create a column. Here is a simplified example of my enum:

class EventType(Enum):
    started = 1
    completed = 2
    aborted = 2

(Note the typo with the repeated value of 2.) Here is what I am attempting to change the Enum to:

class EventType(Enum):
    started = 1
    completed = 2
    aborted = 3
    failed = 4

My changes were to fix the typo and to add a new value to the enum.

Here is the (simplified) model that makes use of that enum:

class Event(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    type = db.Column(db.Enum(EventType))

A call to python app.py db migrate did not detect any changes and I have read in the documentation that alembic (which is used under the hood in flask_migrate) does not automatically detect enum changes. 1

This question from ~6 years ago seems to indicate there is a better way to handle this problem after Postgres 9.4

I am looking for the specific steps I need to take to either manually write my own migration script or to get flask_migrate to detect this change and generate the script for me. Please let me know if I need to provide any more information to help with answering this question.

davidism
  • 121,510
  • 29
  • 395
  • 339
jminardi
  • 936
  • 1
  • 11
  • 23

1 Answers1

5

Here was my ultimate solution to my problem:

1) Generate a blank revision file with python app.py db revision --message "new event types"

2) Modify the new file by entering the following lines into the upgrade() method:

op.execute("COMMIT")
op.execute("ALTER TYPE eventtype ADD VALUE 'failed'")

3) Save and apply the usual way with python app.py db upgrade.

Notes:

  • This does not deal with the typo value. From what I could tell Postgres does not store the python enum value anywhere and doesn't care what it is.

  • This does not remove the values in the downgrade() method. I couldn't find a straightforward way to do that so I just ignored it. In my case I do not think it will matter if the downgrade does not remove those extra values.

  • I learned the name of my type (eventtype) by reading through the migration file that initially created the table that included that type.

jminardi
  • 936
  • 1
  • 11
  • 23