peewee-migrateでマイグレーションをしてみよう
Peewee-migrate について
Peewee-migrate は Kirill Klenov氏によって開発された Peewee ORM のためのデータベース・マイグレーションツールです。
この資料作成時点では、最新バージョンは 1.4.6 で、これは peewee 3.7 以降で動作します。
インストール
peewee-migrate は次のようにインストールします。
code: bash
pip install peewee-migrate
Flask と統合して peewee を使用したい場合は、Flask-PW を使用します。
peewee-migrate の使い方
peewee-migrate をインストールすると pw_migrate コマンドが使用できるようになります。
code: bash
% pw_migrate --help
Usage: pw_migrate OPTIONS COMMAND ARGS...
Just a group.
Options:
--help Show this message and exit.
Commands:
create Create a migration.
list List migrations.
merge Merge migrations into one.
migrate Migrate database.
rollback Rollback a migration with given name or number of last...
マイグレーションファイルの作成
code: bash
% pw_migrate create --help
Usage: pw_migrate create OPTIONS NAME
Create a migration.
Options:
--auto Scan sources and create db migrations automatically.
Supports autodiscovery.
--auto-source TEXT Set to python module path for changes autoscan (e.g.
'package.models'). Current directory will be
recursively scanned by default.
--database TEXT Database connection
--directory TEXT Directory where migrations are stored
--migratetable TEXT Migration table.
-v, --verbose x>=0
--help Show this message and exit.
マイグレーションファイル
デフォルトでは、移行ファイルは os.getcwd()/migrations ディレクトリで検索されますが、カスタムディレクトリを指定することもできます。
マイグレーションファイルは、ファイル名の昇順でソートされ、適用されます。
各マイグレーションファイルは、migrate()関数を指定する必要があり、rollback()関数を指定することもできます。
マイグレーションの実行
code: bash
% pw_migrate migrate --help
Usage: pw_migrate migrate OPTIONS
Migrate database.
Options:
--name TEXT Select migration
--database TEXT Database connection
--directory TEXT Directory where migrations are stored
--fake Run migration as fake.
--migratetable TEXT Migration table.
-v, --verbose x>=0
--help Show this message and exit.
ロールバックの実行
code: bash
% pw_migrate rollback --help
Usage: pw_migrate rollback OPTIONS NAME
Rollback a migration with given name or number of last migrations with given
--count option as integer number
Options:
--count INTEGER Number of last migrations to be rolled back.Ignored in
case of non-empty name
--database TEXT Database connection
--directory TEXT Directory where migrations are stored
--migratetable TEXT Migration table.
-v, --verbose x>=0
--help Show this message and exit.
python スクリプトから実行
code: python
from peewee_migrate import Router
from peewee import SqliteDatabase
router = Router(SqliteDatabase('test.db'))
# Create migration
router.create('migration_name')
# Run migration/migrations
router.run('migration_name')
# Run all unapplied migrations
router.run()
参考
peewee-migrate ソースコード
Flask-PW ソースコード
#database
#migration