3

Using flask-migrate and flask-script, I set my project up, such that I only have to do

python manage.py db migrate

Inside the migrations folder, I get files such as

0f46602752b7_.py
8fdf8259859b_.py

There is no guarantee that the first migration precedes the second one. Django fixes this issue by prefixing all migrations with an auto-incrementing number. Can we tell flask-migrate / alembic to do the same?

Ideally, the two files in the example above would be

001_8fdf8259859b_.py
002_0f46602752b7_.py
Andrei Cioara
  • 3,404
  • 5
  • 34
  • 62
  • Alembic is a more advanced migration system than Django's and it supports migration branches and other special cases. The migration script includes a line that mentions its parent migration and Alembic will scan the files and resolve the hierarchy. No need to rename the scripts. Also, the part after the underscore is supposed to contain a description of the migration script (e.g. `0f46602752b7_add_user_signin_timestamp_column.py`). – sleblanc May 25 '19 at 15:28
  • Think of it like git commit numbers. – sleblanc May 25 '19 at 15:29
  • How am I able to generate such a description @selblanc? – Ndrslmpk Apr 15 '22 at 10:54

1 Answers1

9

If you check every migration file you'll discover lines such as:

revision = '09364330399c'
down_revision = None

down_revision stands for the preceding migration. If you really want to change naming convention you can do it by adding file_template field to your alembic.ini

Following docs:

file_template - this is the naming scheme used to generate new migration > files. The value present is the default, so is commented out. Tokens available include:

   %%(rev)s - revision id

   %%(slug)s - a truncated string derived from the revision message

   %%(year)d, %%(month).2d, %%(day).2d, %%(hour).2d, %%(minute).2d, %%(second).2d - components of the create date, by default datetime.datetime.now() unless the timezone configuration option is also used.

For your particular example, add the following line inside alembic.ini

file_template = %%(year)d%%(month).2d%%(day).2d_%%(hour).2d%%(minute).2d%%(second).2d_%%(rev)s_%%(slug)s

It will generate a filename such as

20190527_122029_de2c595ec169_hello_world.py
Community
  • 1
  • 1
maslak
  • 1,115
  • 3
  • 8
  • 22
  • 1
    is there a certain command existing to overwrite the file name of existing migration files? – Ndrslmpk Apr 15 '22 at 10:57
  • @Ndrslmpk You can just rename the existing migration files but ensure that you don't change the revision variable inside them. If you are looking for a command to rename all the files with the new format, unfortunately there's no existing method but you can create your own script to do so. – Samkit Jain Jul 11 '23 at 18:18