A comprehensive database migration system with FastAPI integration
Project description
Database Migration System with PostgreSQL and Docker
A comprehensive, ORM-agnostic database migration system built with FastAPI and PostgreSQL, featuring:
- Version Control: Track and apply database schema changes systematically
- Auto-diff: Generate migrations automatically from schema differences
- Rollback Support: Safely rollback migrations when needed
- FastAPI Integration: REST API for migration management
- Docker Support: Easy setup with Docker Compose
- PostgreSQL Optimized: Secure parameterized queries and proper transaction handling
๐ Quick Start
Prerequisites
- Docker and Docker Compose
- Python 3.11+ (if running locally)
1. Clone and Setup
git clone <your-repo>
cd demo
# Start services
docker-compose up --build
2. Verify Setup
The application will be available at:
- API: http://localhost:8000
- API Documentation: http://localhost:8000/docs
- PostgreSQL: localhost:5432
3. Test the System
# Check health
curl http://localhost:8000/health
# Get migration status
curl http://localhost:8000/migrations/status
# Run demo setup (creates and applies example migrations)
curl -X POST http://localhost:8000/demo/setup
๐ Project Structure
demo/
โโโ database_manager.py # Original migration system
โโโ database_manager_fixed.py # Fixed version with security improvements
โโโ main.py # FastAPI application
โโโ docker-compose.yml # Docker services configuration
โโโ Dockerfile # Application container
โโโ requirements.txt # Python dependencies
โโโ .env # Environment variables
โโโ init.sql # PostgreSQL initialization
โโโ migrations/ # Migration files directory
โโโ README.md # This file
๐ ๏ธ API Endpoints
Core Migration Endpoints
| Method | Endpoint | Description |
|---|---|---|
| GET | /health |
Health check and database connectivity |
| GET | /migrations/status |
Get current migration status |
| GET | /migrations/pending |
List pending migrations |
| POST | /migrations/migrate |
Apply pending migrations |
| POST | /migrations/rollback |
Rollback to specific version |
| POST | /migrations/create |
Create new migration |
Demo Endpoints
| Method | Endpoint | Description |
|---|---|---|
| POST | /demo/setup |
Create and apply example migrations |
๐ Usage Examples
1. Check Migration Status
curl http://localhost:8000/migrations/status
Response:
{
"success": true,
"message": "Migration status retrieved successfully",
"data": {
"applied_count": 2,
"pending_count": 0,
"last_applied": "20241220_143022",
"next_pending": null,
"applied_migrations": [...],
"pending_migrations": []
}
}
2. Create a New Migration
curl -X POST http://localhost:8000/migrations/create \
-H "Content-Type: application/json" \
-d '{
"name": "add_user_profile",
"up_sql": "ALTER TABLE users ADD COLUMN profile_image VARCHAR(500);",
"down_sql": "ALTER TABLE users DROP COLUMN profile_image;"
}'
3. Apply Migrations
curl -X POST http://localhost:8000/migrations/migrate \
-H "Content-Type: application/json" \
-d '{"target_version": null}'
4. Rollback Migrations
curl -X POST http://localhost:8000/migrations/rollback \
-H "Content-Type: application/json" \
-d '{"target_version": "20241220_143022"}'
๐ง Configuration
Environment Variables
| Variable | Default | Description |
|---|---|---|
DATABASE_URL |
postgresql://migration_user:migration_password@postgres:5432/migration_db |
PostgreSQL connection string |
MIGRATIONS_DIR |
migrations |
Directory for migration files |
DEBUG |
True |
Enable debug mode |
HOST |
0.0.0.0 |
API host |
PORT |
8000 |
API port |
Docker Compose Configuration
The docker-compose.yml includes:
- PostgreSQL 15 with health checks
- Application container with hot reload
- Volume persistence for database data
- Network isolation between services
๐ก๏ธ Security Features
The fixed version (database_manager_fixed.py) includes:
- Parameterized Queries: Prevents SQL injection attacks
- Transaction Safety: Proper rollback on failures
- Connection Management: Secure connection handling
- Input Validation: Pydantic models for request validation
๐ Migration File Format
Migrations are Python files with a specific structure:
"""
Migration: create_users_table
Created: 2024-12-20T14:30:22.123456
"""
from database_manager_fixed import Migration
class CreateUsersTable(Migration):
def __init__(self):
super().__init__("20241220_143022", "create_users_table")
self.up_sql = """
CREATE TABLE users (
id SERIAL PRIMARY KEY,
email VARCHAR(255) UNIQUE NOT NULL,
name VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
"""
self.down_sql = "DROP TABLE users;"
๐ Migration Workflow
- Create Migration: Use API or manually create migration file
- Review: Check generated SQL before applying
- Apply: Run migrations in order
- Verify: Check database schema and data
- Rollback: If needed, rollback to previous version
๐งช Testing
Manual Testing
# Start services
docker-compose up -d
# Wait for services to be ready
sleep 10
# Test API endpoints
curl http://localhost:8000/health
curl http://localhost:8000/migrations/status
curl -X POST http://localhost:8000/demo/setup
# Check database directly
docker exec -it migration_postgres psql -U migration_user -d migration_db -c "\dt"
Database Connection
# Connect to PostgreSQL container
docker exec -it migration_postgres psql -U migration_user -d migration_db
# Check migration history
SELECT * FROM migration_history;
# Check created tables
\dt
๐ Troubleshooting
Common Issues
-
Connection Refused
# Check container status docker-compose ps # Check logs docker-compose logs postgres docker-compose logs app
-
Migration Fails
# Check migration status curl http://localhost:8000/migrations/status # Check application logs docker-compose logs app
-
Database Not Ready
# Check health curl http://localhost:8000/health # Restart services docker-compose restart
Reset Database
# Stop services
docker-compose down
# Remove volumes
docker-compose down -v
# Restart clean
docker-compose up --build
๐ Development
Local Development
# Install dependencies
pip install -r requirements.txt
# Set environment variables
export DATABASE_URL="postgresql://migration_user:migration_password@localhost:5432/migration_db"
# Start PostgreSQL only
docker-compose up postgres -d
# Run application locally
uvicorn main:app --reload
Adding New Features
- Extend
DatabaseAdapterfor new database types - Add new migration types by extending
Migrationclass - Create additional API endpoints in
main.py - Update documentation
๐ Advanced Features
Custom Migration Types
from database_manager_fixed import Migration
class DataMigration(Migration):
"""Migration with data transformation"""
async def up_with_data(self, db_adapter):
# Apply schema changes
await db_adapter.execute_sql(self.up())
# Transform existing data
await self.transform_data(db_adapter)
async def transform_data(self, db_adapter):
# Custom data transformation logic
pass
Schema Validation
class ValidatedMigration(Migration):
"""Migration with pre/post validation"""
async def validate_pre_migration(self, db_adapter):
# Validate prerequisites
return True
async def validate_post_migration(self, db_adapter):
# Validate results
return True
๐ค Contributing
- Fork the repository
- Create a feature branch
- Add tests for new functionality
- Update documentation
- Submit a pull request
๐ License
This project is licensed under the MIT License - see the LICENSE file for details.
๐ Acknowledgments
- FastAPI for the excellent web framework
- asyncpg for PostgreSQL async driver
- Docker for containerization
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file db_migration_manager-1.0.0.tar.gz.
File metadata
- Download URL: db_migration_manager-1.0.0.tar.gz
- Upload date:
- Size: 19.5 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.10.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
9c45e7ff5ddebae5f96b4dad60b09f149bff11bfd7578cb1cdece922a718ceed
|
|
| MD5 |
7fbffb9d0cf9e5244cb833a2d3b8bac5
|
|
| BLAKE2b-256 |
047a255dee65da85e6422a79a799d58e844aeb137a36e2b6647a4cf562d25d5f
|
File details
Details for the file db_migration_manager-1.0.0-py3-none-any.whl.
File metadata
- Download URL: db_migration_manager-1.0.0-py3-none-any.whl
- Upload date:
- Size: 21.7 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.10.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
1056ca398668bb72ec1ce4c4b1ac99d071bcc0a4ef9d24c7715763396ddd509e
|
|
| MD5 |
b9d32723117156c926399e06c5f17001
|
|
| BLAKE2b-256 |
16854f4672d6514f38d86b4f2efece74aa24b5a7568589f49ddfbe45ddfc511a
|