# Alembic Database Migrations

This directory contains database migration scripts managed by Alembic.

## Directory Structure

```
alembic/
├── env.py              # Environment configuration
├── script.py.mako      # Template for migration scripts
├── versions/           # Migration scripts directory
└── README              # This file
```

## Usage

### Create a new migration

```bash
# Auto-generate migration from model changes
alembic revision --autogenerate -m "description of changes"

# Create empty migration
alembic revision -m "description"
```

### Apply migrations

```bash
# Upgrade to latest version
alembic upgrade head

# Upgrade by 1 version
alembic upgrade +1

# Upgrade to specific version
alembic upgrade <revision>
```

### Rollback migrations

```bash
# Downgrade by 1 version
alembic downgrade -1

# Downgrade to specific version
alembic downgrade <revision>

# Downgrade to base (remove all)
alembic downgrade base
```

### View migration history

```bash
# Show current version
alembic current

# Show migration history
alembic history

# Show migration history with details
alembic history --verbose
```

## Naming Convention

Migration files are auto-generated with the format:
```
V{year}_{month}_{day}_{hour}{minute}__{description}.py
```

Example:
```
V2025_01_15_1430__create_user_tables.py
```

## Best Practices

1. **Always review auto-generated migrations** before applying
2. **Test migrations** in development environment first
3. **Backup database** before applying migrations in production
4. **Write reversible migrations** when possible (implement downgrade)
5. **One logical change per migration** for easier rollback
6. **Don't modify existing migrations** that have been applied to production

## Forward Compatibility

When making schema changes, follow these principles:

1. **Adding columns**: Make them nullable or provide defaults
2. **Removing columns**:
   - Version A: Stop using the column in code
   - Version B: Remove the column from database
3. **Renaming columns**:
   - Version A: Add new column, copy data
   - Version B: Update code to use new column
   - Version C: Remove old column

This allows for zero-downtime deployments.
