# Database architecture

Crown’s primary operational database is **SurrealDB**.

It sits at the center of the runtime architecture and is used by the Bun/Hono services as the canonical operational store.

## Main database characteristics

- primary runtime datastore for application state
- accessed over internal container networking
- exposed through a single `@crown/database` workspace package for schema, inferred types, roles, record IDs, and migrations
- backed by persistent storage in normal deployments
- switched to in-memory mode in the E2E override

## Database access pattern

The platform uses a layered approach:

1. **runtime services** connect to SurrealDB using environment-configured endpoints
2. **`@crown/db-adapter`** provides schema and database abstraction helpers
3. **`@crown/database`** is the canonical workspace package for:
   - schema and inferred database types
   - record ID helpers
   - role metadata and permission helpers
   - migration runner and migration types

## Migration model

Migrations live in:

- `packages/database/migrations/`

Characteristics:

- ordered by filename
- intended to be idempotent
- run via the `database-migrations` startup job, using the migrator inside `@crown/database`
- must complete successfully before dependent services start

This keeps schema evolution close to the repo and aligned with the application build.

## Runtime connection conventions

Common environment keys include:

- `DATABASE_URL`
- `SURREALDB_ENDPOINT`
- `SURREALDB_NAMESPACE`
- `SURREALDB_DATABASE`
- `SURREALDB_USERNAME`
- `SURREALDB_PASSWORD`

Typical patterns:

- **internal container access** uses service DNS such as `ws://surrealdb:8000/rpc`
- **local host access** uses the exposed local port such as `ws://localhost:8010/rpc`
- **frontend browser access** is the exception rather than the norm and should be treated carefully

## What to update when the database model changes

If you change data model shape, touchpoints usually include:

- migration files
- `@crown/database`
- `@crown/database/migrator`
- any service route or repository code using the changed records
- docs regeneration if the runtime topology or dependency graph changes

## Operational note

Because SurrealDB is the central state store, the deployment docs treat it as a first-class runtime concern. If you are planning backup, restore, or disaster-recovery work, start with the database volume before anything else.
