Database
ClayDiary uses one PostgreSQL database for three kinds of data:
- Structured data such as pottery pieces, stages, locations, ratings, users, and timestamps.
- Unstructured data such as pottery notes and conversation history.
- Vector data: numerical embeddings generated from pottery-event content and used for semantic search.
Keeping these forms of data together is a deliberate architectural decision. A pottery event, the text prepared from it, and its embedding remain in the same row. Relational filters, keyword search, vector similarity, and row-level security can therefore operate over one source of truth. ClayDiary does not need a separate vector database or a synchronization process to keep a search store consistent with PostgreSQL.
PostgreSQL and its extensions
PostgreSQL provides the relational foundation, while extensions add the search and identifier capabilities needed by the application.
| Extension | Capability | Use in ClayDiary |
|---|---|---|
pgvector | Vector column types and distance operations | Stores 1,536-dimensional event embeddings and compares them with embedded questions |
vectorscale | StreamingDiskANN vector index | Accelerates approximate semantic similarity search |
pg_textsearch | BM25 index and query operators | Finds events through exact terms and keywords |
pg_uuidv7 | Time-ordered UUID generation | Generates database identifiers with insertion-friendly ordering |
pg_trgm | Trigram text indexes | Supports text lookup over piece titles and clay bodies |
pgvector and vectorscale have separate responsibilities. pgvector
provides the vector data type and similarity operations. vectorscale, the
SQL extension supplied by the pgvectorscale project, provides the
StreamingDiskANN index used over that vector column.
ClayDiary runs PostgreSQL in its own timescale/timescaledb-ha:pg18 Docker
container, which bundles the extensions above. A named Docker volume persists
the database independently of the container lifecycle. The image also includes
TimescaleDB, although the current events table is an ordinary PostgreSQL
table rather than a hypertable.
Data model
The main tables separate current domain state, historical observations, user identity, and conversations.
profiles
|
+--- pieces 1 ----- * events
|
+--- chat
log (standalone; not linked to the other tables)Profiles
profiles maps a Clerk user identifier to a database role. Authorization is
resolved from this table rather than trusted from a long-lived role claim in a
client token.
Pieces
pieces stores the identity and current state of a pottery piece: its title,
description, clay body, tags, current stage, current location, owner, and
timestamps.
The current stage and location are denormalized intentionally. The interface and the text-to-SQL path frequently need to answer questions such as "Where is this piece now?" without first reconstructing the latest state from the complete event history.
Events
events records what happened to a piece over time. An event can contain its
stage, location, note, glazes, photos, outcome rating, and event timestamp. It
also contains two retrieval-specific fields:
embedded_text: the textual representation prepared for search;embedding: the vector generated from that representation.
Both fields are populated during the insert itself, not by a separate offline
indexing pipeline: the backend builds embedded_text from the piece and event,
requests its embedding from the configured model, and writes the structured
fields, text, and vector together in one transaction. If embedding generation
fails, the event is not inserted, so an event can never enter the corpus
without the vector that semantic retrieval depends on.
Each event belongs to a piece and an owner. Deleting a piece cascades to its events. PostgreSQL enums constrain stages and locations, while a check constraint limits outcome ratings to values from one to five.
The application treats events as a historical log: a correction is represented by another event rather than by rewriting history. An insert trigger copies the newest event's stage and location to the parent piece and updates its modification time in the same transaction. This append-only behavior is currently an application convention; the database role is not prohibited from updating or deleting an event.
Chat
chat stores conversations belonging to a user. It keeps both a clean message
history used by the application and a raw transcript retained for audit and
diagnosis.
Log
log is a generic table inherited from the original scaffold. It is not
currently connected to application behavior and is not part of the principal
data flow.
Search indexes
The indexes are schema objects created by Alembic migrations. The application does not create an index when it inserts an event.
StreamingDiskANN for semantic search
The semantic index is defined over events.embedding:
CREATE INDEX ON events USING diskann (embedding);At retrieval time, ClayDiary embeds the user's question and orders events by cosine distance from that query vector. StreamingDiskANN provides approximate nearest-neighbour search without requiring a full scan of every stored vector.
BM25 for keyword search
The keyword index is defined over the same text used to create the embedding:
CREATE INDEX events_embedded_text_idx
ON events USING bm25 (embedded_text)
WITH (text_config = 'english');BM25 complements semantic search. Vector similarity can recognize paraphrases, while BM25 is effective for exact glaze names, identifiers, and specialist terms whose spelling matters.
Ordinary inserts update the BM25 index automatically. ClayDiary also performs a
separate REINDEX operation during API-container startup. This is a recovery
measure for observed pg_textsearch behavior: after a database restart, stored
documents could remain present while the in-memory corpus statistics required
for scoring were reset. Reindexing restores those statistics. It runs per index,
uses an autocommit migration connection, and fails open so an individual BM25
problem does not prevent the API from starting.
Relational indexes
Conventional indexes support the application's non-vector access patterns:
events.piece_idfor loading a piece's history;events.user_idfor tenant-scoped access;events.stageandevents.timestampfor lifecycle queries;pieces.current_stagefor current-state filtering;- trigram GIN indexes on piece titles and clay bodies for text matching.
Backend access and encapsulation
The request path looks the same for every endpoint:
FastAPI route
|
Authenticated, user-scoped session dependency
|
Repository or specialised retrieval service
|
Async SQLAlchemy session
|
PostgreSQLNo route talks to SQL directly. Every request follows the same narrow path: a route picks up a user-scoped session, hands the actual work to either a generic repository (for plain CRUD) or a dedicated retrieval class (for hybrid search), and lets SQLAlchemy talk to Postgres.
That split is deliberate. Most of the app's persistence is unremarkable — create a piece, fetch an event, list a user's chats — so one small reusable repository handles it instead of repeating the same boilerplate per model. Retrieval is the opposite: it's the one place where the database does genuinely interesting work (vector similarity, full-text ranking, fusing the two), so it gets its own class and isn't shy about writing raw SQL where the ORM would only get in the way.
Two choices worth calling out. First, writes commit only once, at the end of the request: an event insert and the trigger that updates its parent piece's current state either both happen or neither does. Second, generating an event's embedding happens inside that same transaction, before the commit — an event can never exist without its embedding, at the cost of holding a database connection open during a network call to the embedding API. That's a deliberate trade-off for the project's current scale, not an oversight.
Alembic owns schema evolution. Routine table changes can use autogeneration, while extension creation, specialised indexes, roles, RLS policies, and trigger functions use handwritten SQL migrations. This keeps database-specific behavior versioned and reproducible rather than embedding schema setup in application startup code.
Row-level security
ClayDiary enforces tenant isolation in PostgreSQL instead of relying on every
query author to remember a WHERE user_id = ... predicate.
For each authenticated request, the backend stores two transaction-local values in the database session:
app.current_user_id
app.user_roleRLS policies on pieces, events, chat, and profiles use those values to
control which rows may be read or written. This is why the route that lists
pieces does not contain an explicit owner filter: a non-admin connection cannot
see another user's rows in the first place.
Three database roles separate responsibilities:
- The migration role owns schema changes and uses elevated privileges.
- The application role is a non-superuser subject to RLS.
- The SQL-agent role has
SELECTprivileges only and is explicitly unable to bypass RLS.
The text-to-SQL path uses the read-only role, while ordinary API requests use the application role. Both sessions receive the same user and role context. Even if generated SQL omits an owner predicate, PostgreSQL still limits its result set.
Keeping relational fields, text, and embeddings in the same protected rows is important here. RLS applies consistently to ordinary ORM queries, vector search, BM25 search, and LLM-generated SQL. A separate vector store would require a second tenant-isolation mechanism and a way to prove that it remained consistent with PostgreSQL.