---
description: Database patterns for SQLAlchemy registry and schema change management for src/database/**/* and src/repositories/**/*
alwaysApply: false
---
# Database Patterns Rule

## Core Principles
- **Registry Pattern**: Prevent SQLAlchemy "multiple classes" errors
- **Schema Documentation**: Track all database changes
- **Centralized Models**: Import models from a single package
- **Change History**: Document schema evolution

## Implementation Patterns

### SQLAlchemy Registry Pattern
```python
# ✅ DO: Use the registry pattern for SQLAlchemy models
# src/database/__init__.py
from typing import Dict, Type
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

# Model registry to prevent SQLAlchemy conflicts
_model_registry: Dict[str, Type[Base]] = {}

def register_model(model_class: Type[Base]) -> Type[Base]:
    """Register a model in the central registry."""
    name = model_class.__name__
    if name in _model_registry:
        return _model_registry[name]  # Return existing
    _model_registry[name] = model_class
    return model_class

# Usage in models
@register_model
class MediaFile(Base):
    __tablename__ = "media_files"
    # Model definition here
```

### Model Import Pattern
```python
# ✅ DO: Import models from the models package
from src.database.models import MediaFile, TranscriptionResult

# ❌ DON'T: Import models directly from individual files
from src.database.models.media_file import MediaFile  # WRONG!
```

### Schema Change Documentation
```python
# ✅ DO: Document schema changes in both files
# In alembic migration file:
"""Add user preferences table

Revision ID: a1b2c3d4e5f6
Revises: previous_revision_id
Create Date: 2023-06-15 10:30:45.123456

Changes:
- Add user_preferences table with JSON column for storing preferences
- Add foreign key to users table
"""

# Then update DB-SCHEMA.md and CHANGELOG.md
```

### Anti-Patterns
```python
# ❌ DON'T: Create models without registry
class User(Base):  # Missing @register_model decorator
    __tablename__ = "users"
    # This can cause "multiple classes" errors

# ❌ DON'T: Make schema changes without documentation
# Undocumented migration that doesn't update DB-SCHEMA.md
```

When creating database models, ALWAYS use the registry pattern to prevent SQLAlchemy "multiple classes" errors. Import all models in models/__init__.py and use the register_model() function. Never import models directly from individual files - always import from the models package.

When updating a database schema, ALWAYS be sure to track the changes in the DB-SCHEMA.md along with CHANGELOG.md to maintain a complete history of database evolution.