Phase3-hack2 / src /db /models.py
Quratulain1's picture
first
5be081e
Raw History Blame Contribute Delete
6.95 kB
"""
SQLModel Database Models for Todo API
Owner: Database Reliability Engineer
Purpose: Type-safe database models with multi-tenant isolation
Architecture: SQLModel (Pydantic + SQLAlchemy) with async support
Constitutional Constraints:
- REQUIRED: All tables MUST include user_id: str column (multi-tenant isolation)
- REQUIRED: user_id MUST be indexed for query performance
- REQUIRED: SQLModel exclusive (no raw SQLAlchemy models)
- REQUIRED: Better Auth compatibility (no conflicts with user table)
All models enforce user isolation per constitution Principle IV.
"""
from sqlmodel import SQLModel, Field
from datetime import datetime
from uuid import UUID, uuid4
from typing import Optional
class TodoBase(SQLModel):
"""
Base model with shared fields for requests/responses.
This model contains fields that are common across create/update/response models.
Does not include system-generated fields (id, user_id, timestamps).
"""
title: str = Field(
min_length=1,
max_length=200,
description="Todo title (required, 1-200 characters)"
)
description: Optional[str] = Field(
default=None,
max_length=2000,
description="Optional detailed description (max 2000 characters)"
)
category: Optional[str] = Field(
default=None,
max_length=50,
description="Optional category for organizing todos (e.g., Work, Personal, Shopping)"
)
due_date: Optional[datetime] = Field(
default=None,
description="Optional due date for the todo"
)
is_completed: bool = Field(
default=False,
description="Completion status (default: false)"
)
class Todo(TodoBase, table=True):
"""
Database model for todos table.
Includes all fields including system-generated ones (id, user_id, timestamps).
Multi-Tenant Isolation:
- user_id is REQUIRED and INDEXED
- All queries MUST filter by user_id
- user_id is extracted from JWT sub claim (never from client input)
Better Auth Compatibility:
- user_id references Better Auth's user table (managed externally)
- No foreign key constraint (Better Auth manages users separately)
- Todos remain if user deleted (business decision - can be changed)
Indexes:
- Primary: id (UUID) - Fast lookups by todo ID
- Secondary: user_id - Critical for user isolation queries
- Composite: (user_id, is_completed) - Optimizes filtered lists
"""
__tablename__ = "todos"
id: UUID = Field(
default_factory=uuid4,
primary_key=True,
description="Unique identifier (UUID v4)"
)
user_id: str = Field(
index=True,
nullable=False,
description="Owner user ID from JWT sub claim (REQUIRED for multi-tenant isolation)"
)
created_at: datetime = Field(
default_factory=datetime.utcnow,
nullable=False,
description="Creation timestamp (UTC)"
)
updated_at: datetime = Field(
default_factory=datetime.utcnow,
nullable=False,
description="Last modification timestamp (UTC)"
)
class Config:
"""SQLModel configuration"""
json_schema_extra = {
"example": {
"id": "550e8400-e29b-41d4-a716-446655440000",
"user_id": "user_123abc",
"title": "Buy groceries",
"description": "Milk, eggs, bread",
"category": "Shopping",
"due_date": "2026-01-15T18:00:00Z",
"is_completed": False,
"created_at": "2026-01-09T10:00:00Z",
"updated_at": "2026-01-09T10:00:00Z"
}
}
class TodoCreate(TodoBase):
"""
Request model for creating a todo.
Excludes system-generated fields:
- id: Generated by database
- user_id: Extracted from JWT (security requirement)
- created_at: Set by database
- updated_at: Set by database
Validation:
- title: Required, 1-200 characters
- description: Optional, max 2000 characters
- is_completed: Optional, defaults to False
"""
pass
class TodoUpdate(SQLModel):
"""
Request model for updating a todo.
All fields are optional (partial updates supported).
Only provided fields will be updated.
Validation:
- title: If provided, must be 1-200 characters
- description: If provided, max 2000 characters
- category: If provided, max 50 characters
- due_date: If provided, must be valid datetime
- is_completed: If provided, must be boolean
Note:
- user_id cannot be changed (security requirement)
- id cannot be changed (immutable)
- timestamps are updated automatically
"""
title: Optional[str] = Field(
default=None,
min_length=1,
max_length=200,
description="Todo title (optional for updates)"
)
description: Optional[str] = Field(
default=None,
max_length=2000,
description="Optional detailed description"
)
category: Optional[str] = Field(
default=None,
max_length=50,
description="Optional category"
)
due_date: Optional[datetime] = Field(
default=None,
description="Optional due date"
)
is_completed: Optional[bool] = Field(
default=None,
description="Completion status"
)
class TodoResponse(TodoBase):
"""
Response model with all fields.
Includes all fields from the database model.
Used for API responses to ensure consistent structure.
Fields:
- id: UUID (system-generated)
- user_id: String (from JWT)
- title: String (required)
- description: String | None (optional)
- is_completed: Boolean (default: false)
- created_at: DateTime (UTC)
- updated_at: DateTime (UTC)
"""
id: UUID
user_id: str
created_at: datetime
updated_at: datetime
class Config:
"""SQLModel configuration"""
json_schema_extra = {
"example": {
"id": "550e8400-e29b-41d4-a716-446655440000",
"user_id": "user_123abc",
"title": "Buy groceries",
"description": "Milk, eggs, bread",
"category": "Shopping",
"due_date": "2026-01-15T18:00:00Z",
"is_completed": False,
"created_at": "2026-01-09T10:00:00Z",
"updated_at": "2026-01-09T10:00:00Z"
}
}
# Additional index configuration for composite index
# This will be created during table initialization
# CREATE INDEX idx_todos_user_completed ON todos(user_id, is_completed);
#
# Rationale:
# - Common query pattern: "show me my incomplete todos"
# - Composite index optimizes: WHERE user_id = ? AND is_completed = ?
# - Single user_id index covers: WHERE user_id = ?
# - Both indexes are beneficial for different query patterns