インストール
pip install sqlalchemy-migrate
初期設定
migrate create migration car_quiz_maker
とすると
migrationというディレクトリが作成されてひな形が出来上がる
その中のmanage.pyに接続情報を記述していく
#!/usr/bin/env python
from migrate.versioning.shell import main
if __name__ == '__main__':
    main(debug='False', url='接続情報', repository='.')
この接続情報には
https://monaledge.com/article/279
これでcreate_engineに使っている文字列を使う
この状態で
python manage.py version_control
を実行すると
バージョンに関するテーブルが作成されていることがわかる
postgres@raiu:~$ psql
psql (10.19 (Ubuntu 10.19-0ubuntu0.18.04.1))
Type "help" for help.
postgres=$ \l
postgres=$ \c car_quiz_maker 
You are now connected to database "car_quiz_maker" as user "postgres".
car_quiz_maker=$ \dt
              List of relations
 Schema |      Name       | Type  |  Owner   
--------+-----------------+-------+----------
 public | migrate_version | table | omaemona
(1 row)
テーブルの作成
さて、マイグレーションファイルの作成をしましょう
まずはユーザテーブルを作成したいので
python manage.py script "add user table"
と入力すると、versionsの下に
001_add_user_table.py
というファイルが作成されていると思います。
スペースは勝手にアンダースコアでつないでくれるんですね
便利だ
ファイルの中身は、マイグレーションを知っている人ならなじみのある形になっているでしょう
from sqlalchemy import *
from migrate import *
def upgrade(migrate_engine):
    # Upgrade operations go here. Don't create your own engine; bind
    # migrate_engine to your metadata
    pass
def downgrade(migrate_engine):
    # Operations to reverse the above upgrade go here.
    pass
importしているsqlalchemyの中にいろいろ入っているそうなのでMetaDataやIntegerなどのクラスを使って定義をしていきます
https://sqlalchemy-migrate.readthedocs.io/en/latest/versioning.html
とりあえずこんな感じで書いてみました
from sqlalchemy import *
from migrate import *
meta = MetaData()
 
user = Table(
    'user', meta,
    Column('id',            Integer, primary_key=True, nullable=False),
    Column('name',          String(255), nullable=False, unique=True),
    Column('email',         String(255), nullable=False, unique=True),
    Column('password',      String(255), nullable=False, unique=True),
    Column('created_at',    DateTime, nullable=False),
    Column('updated_at',    DateTime),
)
def upgrade(migrate_engine):
    # Upgrade operations go here. Don't create your own engine; bind
    # migrate_engine to your metadata
    meta.bind = migrate_engine
    user.create()
def downgrade(migrate_engine):
    # Operations to reverse the above upgrade go here.
    meta.bind = migrate_engine
    user.drop()
この状態で
$ python manage.py test
manage.py upgrade
0 -> 1... 
done
とすると、upgradingとdowngradingのテストが走ります。
テストがオッケーだったらupgradeしてテーブルを作成します
python manage.py upgrade
これを実行した後に確認してみるとuserテーブルが作成されています
car_quiz_maker=$ \dt
              List of relations
 Schema |      Name       | Type  |  Owner   
--------+-----------------+-------+----------
 public | migrate_version | table | omaemona
 public | user            | table | omaemona
(2 rows)
car_quiz_maker=$ \d user
                                        Table "public.user"
   Column   |            Type             | Collation | Nullable |             Default              
------------+-----------------------------+-----------+----------+----------------------------------
 id         | integer                     |           | not null | nextval('user_id_seq'::regclass)
 name       | character varying(255)      |           | not null | 
 email      | character varying(255)      |           | not null | 
 password   | character varying(255)      |           | not null | 
 created_at | timestamp without time zone |           | not null | 
 updated_at | timestamp without time zone |           |          | 
Indexes:
    "user_pkey" PRIMARY KEY, btree (id)
    "user_email_key" UNIQUE CONSTRAINT, btree (email)
    "user_name_key" UNIQUE CONSTRAINT, btree (name)
    "user_password_key" UNIQUE CONSTRAINT, btree (password)
こんな感じでちゃんとテーブルが作られていますね
とりあえずマイグレーションの第一歩が踏み出せました