Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

## Commands

```bash
# Start services (PostgreSQL + app with auto-migration)
docker compose up

# Run full test suite (requires test DB and venv)
source .venv/bin/activate
DATABASE_URL=postgresql://taskmanager:taskmanager@localhost:5433/taskmanager \
TEST_DATABASE_URL=postgresql://taskmanager:taskmanager@localhost:5433/taskmanager_test \
pytest tests/ -v

# Run a single test
pytest tests/test_create_task.py::test_create_task_minimal -v

# Generate a new migration after model changes
DATABASE_URL=postgresql://taskmanager:taskmanager@localhost:5433/taskmanager \
alembic revision --autogenerate -m "description"

# Apply migrations
DATABASE_URL=postgresql://taskmanager:taskmanager@localhost:5433/taskmanager \
alembic upgrade head
```

Database credentials: `taskmanager`/`taskmanager`, DB name `taskmanager`, Docker-exposed on port **5433** (not 5432). Test DB: `taskmanager_test` on same server.

## Architecture

FastAPI REST API with SQLAlchemy ORM and PostgreSQL. Single domain entity: **Task**.

- `app/main.py` — FastAPI app, includes the tasks router
- `app/models.py` — `Task` SQLAlchemy model with `TaskStatus` and `TaskPriority` enums
- `app/schemas.py` — Pydantic v2 request/response schemas with `from_attributes` for ORM mapping
- `app/routers/tasks.py` — all 8 endpoints in a single router (prefix `/tasks`)
- `app/database.py` — engine, session factory, `get_db()` dependency
- `app/config.py` — reads `DATABASE_URL` from environment via pydantic-settings

**Route ordering matters:** `/tasks/search` and `/tasks/stats` are defined before `/tasks/{task_id}` to prevent FastAPI from parsing literal paths as UUID parameters.

**Status transitions** follow a strict state machine (`VALID_TRANSITIONS` dict): `todo → in_progress → done`. No skipping, no backwards. Enforced in `PATCH /tasks/{task_id}/status`.

**Partial updates** use `model_dump(exclude_unset=True)` so only client-supplied fields are changed.

## Testing

Tests use a real PostgreSQL database (not SQLite) because the app uses PG-specific features (UUID type, ILIKE, ENUM). Each test runs in a transaction that rolls back automatically (`conftest.py` overrides `get_db` with a transactional session). The `db_session` fixture is available for direct ORM access when bypassing API validation (e.g., inserting overdue tasks with past due dates).
10 changes: 10 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
FROM python:3.12-slim

WORKDIR /app

COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY . .

CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
38 changes: 38 additions & 0 deletions alembic.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
[alembic]
script_location = alembic
prepend_sys_path = .
version_path_separator = os

[loggers]
keys = root,sqlalchemy,alembic

[handlers]
keys = console

[formatters]
keys = generic

[logger_root]
level = WARN
handlers = console
qualname =

[logger_sqlalchemy]
level = WARN
handlers =
qualname = sqlalchemy.engine

[logger_alembic]
level = INFO
handlers =
qualname = alembic

[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic

[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S
47 changes: 47 additions & 0 deletions alembic/env.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import os
from logging.config import fileConfig

from alembic import context
from sqlalchemy import engine_from_config, pool

from app.database import Base
from app.models import Task # noqa: F401 — ensure model is registered

config = context.config

if config.config_file_name is not None:
fileConfig(config.config_file_name)

config.set_main_option("sqlalchemy.url", os.environ["DATABASE_URL"])

target_metadata = Base.metadata


def run_migrations_offline() -> None:
url = config.get_main_option("sqlalchemy.url")
context.configure(
url=url,
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
)
with context.begin_transaction():
context.run_migrations()


def run_migrations_online() -> None:
connectable = engine_from_config(
config.get_section(config.config_ini_section, {}),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
with connectable.connect() as connection:
context.configure(connection=connection, target_metadata=target_metadata)
with context.begin_transaction():
context.run_migrations()


if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
26 changes: 26 additions & 0 deletions alembic/script.py.mako
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
"""${message}

Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}

"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa
${imports if imports else ""}

# revision identifiers, used by Alembic.
revision: str = ${repr(up_revision)}
down_revision: Union[str, None] = ${repr(down_revision)}
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}


def upgrade() -> None:
${upgrades if upgrades else "pass"}


def downgrade() -> None:
${downgrades if downgrades else "pass"}
40 changes: 40 additions & 0 deletions alembic/versions/44c2bc677b36_create_tasks_table.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
"""create tasks table

Revision ID: 44c2bc677b36
Revises:
Create Date: 2026-03-18 18:23:24.746897

"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision: str = '44c2bc677b36'
down_revision: Union[str, None] = None
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('tasks',
sa.Column('id', sa.UUID(), nullable=False),
sa.Column('title', sa.String(length=200), nullable=False),
sa.Column('description', sa.Text(), nullable=True),
sa.Column('priority', sa.Enum('low', 'medium', 'high', name='taskpriority'), nullable=False),
sa.Column('status', sa.Enum('todo', 'in_progress', 'done', name='taskstatus'), nullable=False),
sa.Column('due_date', sa.Date(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.Column('updated_at', sa.DateTime(), nullable=False),
sa.PrimaryKeyConstraint('id')
)
# ### end Alembic commands ###


def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('tasks')
# ### end Alembic commands ###
Empty file added app/__init__.py
Empty file.
10 changes: 10 additions & 0 deletions app/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
from pydantic_settings import BaseSettings


class Settings(BaseSettings):
database_url: str

model_config = {"env_file": ".env"}


settings = Settings()
16 changes: 16 additions & 0 deletions app/database.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, declarative_base

from app.config import settings

engine = create_engine(settings.database_url)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()


def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
11 changes: 11 additions & 0 deletions app/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
from fastapi import FastAPI

from app.routers import tasks

app = FastAPI(title="Task Manager", version="1.0.0")
app.include_router(tasks.router)


@app.get("/")
def health_check():
return {"status": "ok"}
38 changes: 38 additions & 0 deletions app/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import enum
import uuid
from datetime import UTC, datetime

from sqlalchemy import Column, String, Text, Date, DateTime
from sqlalchemy import Enum as SAEnum
from sqlalchemy.dialects.postgresql import UUID

from app.database import Base


def _utcnow():
return datetime.now(UTC).replace(tzinfo=None)


class TaskStatus(str, enum.Enum):
todo = "todo"
in_progress = "in_progress"
done = "done"


class TaskPriority(str, enum.Enum):
low = "low"
medium = "medium"
high = "high"


class Task(Base):
__tablename__ = "tasks"

id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
title = Column(String(200), nullable=False)
description = Column(Text, nullable=True)
priority = Column(SAEnum(TaskPriority), nullable=False, default=TaskPriority.medium)
status = Column(SAEnum(TaskStatus), nullable=False, default=TaskStatus.todo)
due_date = Column(Date, nullable=True)
created_at = Column(DateTime, nullable=False, default=_utcnow)
updated_at = Column(DateTime, nullable=False, default=_utcnow, onupdate=_utcnow)
Empty file added app/routers/__init__.py
Empty file.
Loading