Database and migrations
The database is the durable store for AMA sessions, the private media library, request limits, and the older subscriber and newsletter data. Drizzle defines the current PostgreSQL shape, shared repositories apply business changes through one database client, and numbered SQL migrations move production databases forward without rewriting applied history. See Platform foundations for the wider platform view and Runtime security and delivery for the request and deployment controls that use this data.
Persistence model
Drizzle schema
The Drizzle schema at db/schema.ts is the typed model of the PostgreSQL tables that the application can read and change. It groups data by product area and uses keys, links, unique rules, and database checks to keep important state valid even when more than one request acts at the same time.
The schema protects product boundaries in a few important ways:
| Data area | Persistence role |
|---|---|
| AMA | Stores owner access, recurring availability, date overrides, calendar connection state, booking holds, paid bookings, provider events, recovery work, and alternate-time requests. |
| Media | Stores upload intents, Media Assets, Renditions, photo selection drafts, immutable published snapshots, archive actions, and purge progress. |
| Rate limits | Stores a time window for each scope and hashed request key. The raw private key is not stored. |
| Legacy site data | Keeps the subscribers and newsletters tables mapped to their existing production shape. AMA migrations do not recreate or alter them. |
Many state fields are paired with database checks. For example, a held AMA claim must have an expiry, a completed purge must have no remaining object key, and a published photo snapshot must have complete bilingual Alt Text. These checks make the database a last line of defense for product rules.
References: db/schema.ts• L23-87 db/schema.ts• L89-233 db/schema.ts• L235-418 db/schema.ts• L420-792 db/schema.ts• L804-1154
Database access layer
The database access layer creates one lazy shared Drizzle client for server code. It reads the runtime DATABASE_URL, uses a PostgreSQL connection pool, and attaches that pool to the Vercel runtime so connections can be reused safely across requests.
Domain repositories use this client together with the typed tables from the schema. The repositories own query shape and transaction boundaries for a product area, while the database module owns connection setup. This keeps AMA, media, and rate-limit code on the same persistence contract without making each area create its own pool.
Repositories accept a database provider in their factory shape. Production passes the shared client provider, while tests can pass a local test client. This separation lets a repository test real SQL behavior without connecting to production data.
References: db/index.ts• L1-20 db/index.test.ts• L3-49 lib/…/repository.ts• L3-42 lib/…/repository.ts• L17-31 lib/…/repository.ts• L3-24 lib/…/repository.ts• L5-18
Product persistence
AMA persistence
AMA persistence turns availability and payment actions into durable booking state. Schedule data describes recurring windows and date-specific replacements. Booking data then links a temporary Slot Hold to a Booking Intent and, after payment, to a paid Booking and its event history.
The database also records the state needed to recover from external service failures. Provider events are unique by provider and event ID. Durable operations use a unique dedupe key and retry state. Active claims use a PostgreSQL exclusion rule over a buffered time range, so two active claims cannot overlap the 15-minute policy buffer.
The main relationships are:
flowchart LR
S[Availability data] --> H[Slot Hold]
H --> I[Booking Intent]
I --> B[Booking]
B --> E[Booking events]
B --> P[Provider events]
B --> O[Durable operations]
B --> M[Meeting and payment results]
This model supports the public booking flow and the owner recovery tools. It also keeps guest-facing management state separate from owner authentication and external provider state.
References: db/schema.ts• L43-233 db/schema.ts• L804-1137 db/…/0011_ama_booking_system.sql• L1-177 lib/…/repository.ts• L34-80 lib/…/repository.ts• L17-70
Media persistence
Media persistence separates the transfer of an Original from the reusable Media Asset that becomes visible in the library. An upload intent records expected ownership and content before transfer. A Media Asset records verified source data and processing state. Renditions record the public image versions made from that source.
Photo curation uses a second layer of data. The owner edits a Draft Photo Selection. Publishing creates an immutable Published Photo Selection snapshot, and one singleton record identifies which snapshot is active for public delivery. Archive and purge records preserve enough progress and history to finish cleanup or support a short undo period without changing unrelated draft work.
The persistence relationships are:
flowchart LR
U[Upload Intent] --> A[Media Asset]
A --> R[Renditions]
A --> D[Draft Photo Selection]
D --> Q[Published Photo Selection snapshot]
Q --> X[Active publication]
A --> G[Archive operation]
A --> P[Purge job]
The database keeps the protected Original and public Renditions distinct. Published snapshots also keep their own descriptive data and object references, so a later catalog purge does not change past publication records.
References: db/schema.ts• L235-418 db/schema.ts• L420-792 db/schema.ts• L1139-1154 db/…/0005_media_catalog.sql• L1-110 db/…/0006_photo_selection.sql• L1-110 db/…/0008_media_purge_progress.sql• L1-31 lib/…/repository.ts• L47-70
Rate-limit persistence
Rate-limit persistence gives all application instances a shared view of recent requests. Each policy maps to a scope and each caller maps to a SHA-256 key hash. The row stores request times inside the active window and expires as a unit, so the limit does not depend on local process memory.
An insert-or-update operation trims old request times and adds the current request only while the policy still allows it. The compound key prevents two rows for the same scope and caller. The runtime security and delivery page explains which request paths use these limits.
References: db/schema.ts• L67-87 db/…/0010_rate_limit_windows.sql• L1-10 lib/…/repository.ts• L14-69
Migration history
Migration sequence
Production changes are append-only SQL files in db/migrations. Drizzle Kit compares db/schema.ts with the migration state and writes the next numbered change. The migration journal records the applied order and the snapshots record the schema state after each step.
The history follows the product's growth:
| Migration range | Product change |
|---|---|
0000 | Preserves the original site tables and indexes. |
0001–0004 | Adds AMA owner access, recurring availability, Google Calendar connection state, and Google OAuth attempt state. |
0005–0009 | Adds the media catalog and photo selection model, then adds publication revisions, purge progress, and the catalog_state name. |
0010 | Adds shared PostgreSQL rate-limit windows. |
0011 | Adds paid AMA holds, bookings, payment and provider events, durable recovery work, and alternate-time requests. |
0012–0013 | Adds the 2560 Rendition profile and media archive, withdrawal, and discard progress. |
0014–0015 | Adds AMA schedule time-zone and date overrides, then explicit recurring weekday state. |
Migration names describe the product change, but the SQL files remain the record of what was applied. A schema edit is not complete until its matching migration exists and both current code and a new database can use the same shape.
References: db/…/_journal.json• L1-111 db/…/0000_shallow_iron_fist.sql• L1-39 db/…/0005_media_catalog.sql• L1-110 db/…/0006_photo_selection.sql• L1-110 db/…/0007_photo_publication_revision.sql• L1 db/…/0008_media_purge_progress.sql• L1-31 db/…/0009_media_catalog_state.sql• L1-2 db/…/0010_rate_limit_windows.sql• L1-10 db/…/0011_ama_booking_system.sql• L1-177 db/…/0012_high_fidelity_photo_renditions.sql• L1-8 db/…/0013_brief_yellowjacket.sql• L1-30 db/…/0014_ama_availability_overrides.sql• L1-31 db/…/0015_ama_availability_weekdays.sql• L1-7
Migration safety
Production migration checks protect the database contract before release. Applied migration files are immutable. A release may add a migration file, but it may not modify or delete an existing one. The checker also scans every migration that is still present, not only the files in the latest change.
New production migrations follow an expand-only rule. Safe additions can create objects or add columns with a safe default. Destructive operations, unsafe defaults, table renames, type changes, and unreviewed constraints are rejected because they can break an older application version or remove live data.
The older subscriber and newsletter tables are a special compatibility boundary. AMA migration checks verify that AMA history does not create, change, delete, or write those tables.
References: drizzle.config.ts• L1-8 scripts/check-production-migrations.mjs• L6-71 scripts/check-production-migrations.mjs• L355-519 scripts/check-production-migrations.mjs• L522-591 scripts/ama-migrations.test.mjs• L29-36 scripts/ama-migrations.test.mjs• L149-166
Testing model
PGlite database tests
Database-facing tests use PGlite, a PostgreSQL-compatible test client that runs locally through WebAssembly. usePGliteTestClient applies the migration files selected by a test file before the tests start, then shares one client for that file to avoid repeated WebAssembly startup.
Before each test, the helper truncates public tables, restarts identities, and restores any rows that the migrations seeded. This gives each test the same post-migration state while still checking real SQL constraints, indexes, foreign keys, and transaction behavior.
Repositories use this helper for focused AMA, media, and rate-limit tests. The database client test separately checks that the shared production client exposes transactions and that its pool is attached to the runtime.
References: db/…/pglite.ts• L1-79 db/…/pglite.test.ts• L1-44 db/…/seeded-migration.sql• L1-13 db/index.test.ts• L42-49 lib/…/repository.test.ts• L1-12 lib/…/repository.test.ts• L1-12 lib/…/repository.test.ts• L1-12
Migration contract tests
Migration contract tests read migration SQL as text and check the guarantees that are easy to lose during schema work. They cover additive AMA tables, bounded availability values, protected OAuth material, hashed rate-limit keys, booking overlap and dedupe rules, media publication behavior, and protection of the legacy tables.
The production checker tests the release rule itself. Together, these tests verify both sides of migration safety: the SQL must create the intended product contract, and future changes must not silently rewrite or weaken the applied history.
The main commands are:
| Command | Purpose |
|---|---|
pnpm db:generate | Create a new Drizzle migration from a schema change. |
pnpm db:migrate | Apply migrations using MIGRATION_DATABASE_URL. |
pnpm db:validate | Run AMA migration contract checks. |
pnpm test:ama | Run AMA tests and then migration validation. |
pnpm test:unit | Run unit tests for database and application areas. |
References: package.json• L17-50 scripts/ama-migrations.test.mjs• L5-166 scripts/check-production-migrations.test.mjs• L13-228
Change checklist
When these files or sections are changed, remember to consider these:
- When a table, field, state value, or constraint changes in db/schema.ts, add the matching numbered SQL migration and check both repository queries and PGlite migration lists.
- When a migration has been applied, preserve its file bytes and add a later migration for any correction or extension.
- When a state rule changes, update both the Drizzle check and any hand-written SQL that Drizzle cannot express, such as the AMA claim exclusion rule.
- When media publication or purge data changes, verify that foreign-key delete behavior still preserves immutable snapshots and retryable cleanup progress.
- When rate-limit scope or key behavior changes, preserve the compound scope/key contract and the rule that raw request keys do not enter the database.
- When a migration seeds rows, update the test reset assumptions so seeded state is restored after each test.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| An applied migration file is edited or deleted | Production migration verification rejects the release because deployed history no longer matches the reviewed history. | Add a new migration. Keep old SQL files unchanged. |
| A migration drops data or uses an unsafe default or type change | A release can break old application code or fail on live rows. | The production checker rejects destructive and unsafe operations. |
| Two active AMA claims overlap their buffered time ranges | The database rejects the second claim instead of allowing an overbooked time. | The ama_slot_claims exclusion constraint checks active ranges. |
| A published media snapshot is changed after publication | Public history can disagree with the stored publication record. | Database triggers reject updates and deletes on published selection snapshots. |
| A test changes a shared PGlite database without reset | Later tests can pass or fail based on test order. | The PGlite helper truncates tables, restarts identities, and restores migration seeds before each test. |
Key files
| File | Why to read it |
|---|---|
| db/schema.ts | The current typed persistence contract for AMA, media, rate limits, and legacy tables. |
| db/index.ts | The server database boundary and shared PostgreSQL client setup. |
| db/…/pglite.ts | The test database lifecycle and post-migration reset model. |
| db/…/_journal.json | The ordered list of migrations known to Drizzle. |
| db/…/0005_media_catalog.sql | The first media catalog and Rendition persistence model. |
| db/…/0006_photo_selection.sql | The draft, published snapshot, and active publication model. |
| db/…/0010_rate_limit_windows.sql | The shared request-window persistence contract. |
| db/…/0011_ama_booking_system.sql | The core paid AMA booking and recovery persistence model. |
| scripts/check-production-migrations.mjs | The production rule that keeps migration history append-only and expand-only. |
| scripts/ama-migrations.test.mjs | The product-level checks for AMA, media compatibility, and rate-limit migration guarantees. |
| scripts/check-production-migrations.test.mjs | The tests for migration safety and release-diff rules. |