Datalumina

Database

Database

Run Postgres 17 in Docker Compose and define the one contracts table as a SQLAlchemy model that FastAPI creates on startup.

By the end of this page Postgres runs in Docker on your laptop, with one table called contracts.

One table is enough. The notes, the extracted fields, the sections, the signature, and the signed PDF all belong to one contract. The fields and the sections are JSONB, so a new contract type needs no new column.

The table is a Python class, not a SQL file. SQLAlchemy turns the class into the table, and later pages read and write contracts as Python objects instead of SQL strings. Your editor then knows every column, autocompletes it, and flags a typo before you run anything.

Write the Compose file

docker-compose.yml
services:
  db:
    image: postgres:17
    environment:
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
    volumes:
      - postgres:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD", "pg_isready", "-U", "postgres"]
      interval: 5s
      retries: 10
    restart: unless-stopped

volumes:
  postgres:

Postgres reads POSTGRES_PASSWORD from your .env. The data lives in a named volume and survives a restart. The database starts empty, and FastAPI creates the table in a later step.

The image is pinned to postgres:17. Postgres 18 images moved the data directory, so the volume path above would be wrong for 18.

Open the port on your laptop only

docker-compose.dev.yml
# Local development only: Postgres on 127.0.0.1:5432 for the backend on your laptop.
# docker compose -f docker-compose.yml -f docker-compose.dev.yml up -d db
services:
  db:
    ports:
      - "127.0.0.1:5432:5432"

This file adds one thing to the main file. It publishes Postgres on 127.0.0.1:5432, so the backend on your laptop can reach it and nothing else can. Compose only reads it when you name it with -f, as in the command below. The main file publishes no port at all, and that is all the server reads later.

Port 5432 is taken

A local Postgres often uses 5432 already. Change the left side of the port, for example 127.0.0.1:5433:5432, and the port in DATABASE_URL to match.

Start it

docker compose -f docker-compose.yml -f docker-compose.dev.yml up -d db
docker compose ps

The db service shows the status healthy after a few seconds.

Add the database setting

Replace backend/app/config.py.

backend/app/config.py
from pathlib import Path

from pydantic_settings import BaseSettings, SettingsConfigDict


class Settings(BaseSettings):
    # Local runs read .env in the project root. In Docker, Compose passes the same values.
    model_config = SettingsConfigDict(env_file=Path(__file__).parents[2] / ".env", extra="ignore")

    company_name: str = "Pinewick Systems"
    database_url: str


settings = Settings()

database_url has no default, so the app refuses to start when .env is missing it. It starts with postgresql+psycopg://. The +psycopg part tells SQLAlchemy to use psycopg 3, the Postgres driver in pyproject.toml.

Write the model

backend/app/db.py
from datetime import datetime

from sqlalchemy import DateTime, create_engine, func
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column

from app.config import settings

engine = create_engine(settings.database_url)


class Base(DeclarativeBase):
    # Dicts and lists are stored as JSONB, datetimes with their time zone.
    type_annotation_map = {dict: JSONB, list: JSONB, datetime: DateTime(timezone=True)}


class Contract(Base):
    __tablename__ = "contracts"

    id: Mapped[int] = mapped_column(primary_key=True)
    title: Mapped[str]
    notes: Mapped[str]
    # pending, processing, needs_review, failed, drafted, sent, signed
    status: Mapped[str] = mapped_column(server_default="pending")
    reason: Mapped[str | None]  # why it needs review, or the error
    contract_type: Mapped[str | None]  # fixed_price, retainer, discovery, none
    fields: Mapped[dict | None]  # LLM step 1: client, price, dates
    sections: Mapped[list] = mapped_column(server_default="[]")  # LLM step 2: one dict each
    token: Mapped[str | None] = mapped_column(unique=True)  # the signing link
    content_hash: Mapped[str | None]  # SHA-256 of the document at Send
    sent_at: Mapped[datetime | None]
    signer: Mapped[dict | None]  # name, initials, user agent
    signed_at: Mapped[datetime | None]
    pdf: Mapped[bytes | None] = mapped_column(deferred=True)  # loaded only when asked for
    created_at: Mapped[datetime] = mapped_column(server_default=func.now())

Every attribute of Contract is a column. The type decides the column type, and | None makes a column nullable. type_annotation_map stores dicts and lists as JSONB and keeps the time zone on every timestamp. server_default gives Postgres the default, so a new contract starts as pending with no sections.

The status column follows a contract from upload to signature. It starts as pending, moves to processing, ends up drafted, needs_review, or failed, and after that becomes sent and signed. reason explains a review or an error in plain words.

pdf is deferred. Reading a contract leaves the PDF bytes in the database until code asks for them.

Create the table on startup

Replace backend/app/main.py.

backend/app/main.py
from contextlib import asynccontextmanager

from fastapi import FastAPI

from app.config import settings
from app.db import Base, engine


@asynccontextmanager
async def lifespan(app: FastAPI):
    Base.metadata.create_all(engine)  # Creates the table if it is missing. Never alters it.
    yield


app = FastAPI(title="Contract drafting", lifespan=lifespan)


@app.get("/health")
def health() -> dict:
    return {"status": "ok", "company": settings.company_name}

lifespan runs when FastAPI starts. create_all() creates every table that is missing and leaves existing tables alone. fastapi dev reloads when you save, so the table appears as soon as you save this file.

Check

From the project root, list the columns.

docker compose exec db psql -U postgres -c '\d contracts'

The output shows fields, sections, and signer as jsonb, pdf as bytea, and the timestamps with time zone. If the table is missing, check the terminal that runs fastapi dev for an error, and start it again if it stopped.

config.py
db.py
main.py
.env
docker-compose.dev.yml
docker-compose.yml

On this page