Peewee Migrate
Peewee-migrate, currently at version 1.15.0, provides robust database migration support for the Peewee ORM. It enables developers to manage schema changes through versioned migrations, offering features like creation, application, and rollback of migrations. The library is actively maintained on GitHub with a regular release cadence, ensuring compatibility and ongoing improvements for Peewee projects.
Warnings
- breaking The `Router` constructor signature changed significantly in version 1.0.0. The second positional argument (path to migrations) was removed in favor of a keyword argument `migrate_dir`.
- gotcha Migration files must adhere to the `NNN_name.py` naming convention (e.g., `001_create_user_table.py`) and be placed in the `migrate_dir` specified to the `Router` instance. Files not following this format or placed elsewhere will be ignored.
- gotcha Rollback functions (`rollback(migrator, database, **kwargs)`) are optional but highly recommended. If a `rollback` function is not provided for a `migrate` operation, that specific migration cannot be reversed using `peewee-migrate`'s rollback command.
Install
-
pip install peewee-migrate
Imports
- Router
from peewee_migrate import Router
Quickstart
import os
from peewee import *
from peewee_migrate import Router
# 1. Initialize a Peewee database instance
db = SqliteDatabase('example.db')
# 2. Define the directory where your migration files are stored
migrations_dir = 'my_migrations'
# Create a dummy migration directory and file for the example to be runnable
os.makedirs(migrations_dir, exist_ok=True)
with open(os.path.join(migrations_dir, '001_initial.py'), 'w') as f:
f.write('from peewee import *\ndef migrate(migrator, database, **kwargs):\n pass\ndef rollback(migrator, database, **kwargs):\n pass')
# 3. Initialize the Peewee-Migrate Router
router = Router(db, migrate_dir=migrations_dir)
# 4. Run all pending migrations
# In a real scenario, you would have migration files in 'my_migrations'
# defining schema changes.
print("Running migrations...")
router.run()
print("Migrations completed successfully.")
# Clean up created files/dirs for a repeatable example
if os.path.exists('example.db'):
os.remove('example.db')
if os.path.exists(migrations_dir):
import shutil
shutil.rmtree(migrations_dir)