This skill provides guidance on reviewing SQLAlchemy Alembic migrations, aimed at developers working with database migrations. It focuses on best practices to ensure migrations are efficient and maintainable.
$ npx skills add https://github.com/wispbit-ai/skills --skill sqlalchemy-alembic-expert-best-practices-code-reviewThis skill delivers production-grade guidance for reviewing SQLAlchemy ORM code and Alembic database migrations. It provides opinionated, specific rules organized by impact—not abstract best practices—so your code reviews focus on what matters most. Each rule includes clear constraints, actionable examples, and patterns showing correct versus incorrect implementations. The skill helps development teams catch migration inefficiencies, maintainability issues, and common pitfalls before they reach production. Developers working with SQLAlchemy and Alembic benefit from consistent, enforceable standards that improve code quality and long-term database maintainability.
Install via npx command provided below.
Conduct thorough code reviews for Alembic migration scripts
Identify common pitfalls in database migrations
Ensure adherence to best practices in migration development
$ npx skills add https://github.com/wispbit-ai/skills --skill sqlalchemy-alembic-expert-best-practices-code-reviewgit clone https://github.com/wispbit-ai/skillsCopy the install command above and run it in your terminal.
Launch Claude Code, Cursor, or your preferred AI coding agent.
Use the prompt template or examples below to test the skill.
Adapt the skill to your specific use case and workflow.
Review this SQLAlchemy Alembic migration script for [COMPANY]'s [INDUSTRY] application. Focus on best practices for efficiency, maintainability, and potential issues. Here's the migration script: ```python [MIGRATION_SCRIPT] ``` Provide a detailed analysis of any problems, optimizations, or improvements needed, including: - Schema design issues (e.g., missing indexes, inefficient data types) - Migration logic flaws (e.g., unsafe operations, lack of transactions) - Performance concerns (e.g., long-running operations, locking issues) - Alembic-specific recommendations (e.g., downgrade safety, batch size for large tables) - Best practice violations (e.g., hardcoded values, lack of idempotency)
# SQLAlchemy Alembic Migration Review: `2024_05_15_add_user_email_index.py`
## Critical Issues ⚠️
### 1. **Missing Transaction Block**
```python
op.create_index('ix_user_email', 'users', ['email'], unique=True)
```
**Problem**: This operation isn't wrapped in a transaction block. If the migration fails mid-execution, your database could be left in an inconsistent state.
**Fix**: Wrap in `op.execute('BEGIN;')` and `op.execute('COMMIT;')` or use Alembic's built-in transaction handling:
```python
with op.batch_alter_table('users') as batch_op:
batch_op.create_index('ix_user_email', ['email'], unique=True)
```
### 2. **Inefficient Data Type**
```python
sa.Column('email', sa.String(length=255), nullable=False)
```
**Problem**: `String(255)` is legacy. Modern email systems rarely exceed 254 chars, but consider:
- Using `String(320)` for RFC 5321 compliance
- Or better, `EmailType()` from `sqlalchemy_utils` for validation
### 3. **No Downgrade Safety**
```python
def downgrade():
op.drop_index('ix_user_email', table_name='users')
```
**Problem**: No check for index existence. If the index was dropped manually, this will fail catastrophically.
**Fix**:
```python
def downgrade():
if op.get_indexes('users', 'ix_user_email'):
op.drop_index('ix_user_email', table_name='users')
```
## Performance Recommendations 🚀
- **Batch Operations**: For large tables (>100k rows), use `batch_alter_table` to reduce lock contention
- **Indexing Strategy**: Add a composite index for frequent queries:
```python
op.create_index('ix_user_email_status', 'users', ['email', 'status'])
```
## Best Practices Violations ❌
- Hardcoded schema name (should use `op.get_bind().table_names()`)
- No migration batch size specified for large tables
- Missing docstring explaining the migration's purpose
## Approved Migration (Fixed Version)
```python
"""Add unique index to users.email for authentication performance."""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
def upgrade():
with op.batch_alter_table('users', table_args=sa.Index('ix_user_email', 'email', unique=True)) as batch_op:
batch_op.alter_column('email', existing_type=sa.String(length=255), type_=sa.String(length=320))
def downgrade():
with op.batch_alter_table('users') as batch_op:
batch_op.drop_index('ix_user_email')
batch_op.alter_column('email', existing_type=sa.String(length=320), type_=sa.String(length=255))
```Take a free 3-minute scan and get personalized AI skill recommendations.
Take free scan