Spaces:
Sleeping
Sleeping
File size: 6,945 Bytes
5be081e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 | """
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
|