# Database setup and reference

`adios kit deploy` creates and configures your database for you. Use this reference when setting up local development, administering modules directly, or adding tables with your coding agent.

## Manual setup

Use a dedicated PostgreSQL 17+ database and a machine that can reach it. An Adios private database requires access from its permitted network. Booking also requires PostgreSQL's `btree_gist` extension.

Install psql and an Adios CLI build containing `adios kit` (currently available in the updated CLI source, pending release). Check `adios kit --help`. Run commands from the kit folder, or pass `--path /path/to/saas-kit`.

Set `KIT_DATABASE_URL` through your administration shell or secret manager to the database owner's connection URL. The CLI does not load `.env` automatically. Keep that connection out of the web app's environment.

```sh
adios kit validate
adios kit init
adios kit enable crm
adios kit status
```

Use your database administration tools to create three separate login roles: `saas_runtime`, `saas_auth`, and `saas_billing`. Give them unique passwords, no superuser, BYPASSRLS, or CREATEROLE privileges, and no ownership of or inherited owner access to kit tables. Then grant their application permissions:

```sh
adios kit grant-runtime saas_runtime
adios kit grant-service auth saas_auth
adios kit grant-service billing saas_billing
```

Use the three role connections as `DATABASE_URL`, `AUTH_DATABASE_URL`, and `BILLING_DATABASE_URL` in [local development](local-development.md). Rerun runtime grants after adding a module. These commands grant permissions; they do not create roles or passwords.

Repeated `init` and `enable` commands skip unchanged applied migrations. Existing kit databases use the same migration ledger. For a local database, `adios --offline kit init` restricts connections to local/private addresses or Unix sockets.

## Network and connection settings

Use provider-required TLS for remote database connections. The current deployment command connects its app to PostgreSQL over the team's private Adios network using the single-node transport's `sslmode=disable` setting. It does not expose that database publicly. A database requiring transport TLS needs a separately supported configuration.

## One schema history

Use the same SQL migrations in all language variants. The Adios CLI's `adios kit` commands manage the database; the application backend can be JavaScript, Python, or Go. UUID keys and UTC-aware timestamptz values are the common storage representation. Monetary amounts use integer minor units and currency codes; usage uses an idempotent event ledger.

## Core records

| Tables | Purpose |
| --- | --- |
| users, identities | Application-wide people and external identity mappings; privileged access only |
| workspaces, memberships, invitations | Personal/team customer accounts and access |
| billing_accounts, subscriptions, entitlements | Stripe references and local authorization state; trusted billing service writes only |
| usage_events | Deduplicated metering events; aggregation and Stripe reporting pending |
| audit_events | Workspace-scoped action history; avoid storing secrets or full documents |
| outbox | Durable events for future workers; idempotency key scoped to workspace and module |
| agent_runs | Local references to future Adios agent executions |
| webhook_receipts | Privileged provider event deduplication |

The JavaScript runtime now includes checkout, portal sessions, signature verification, deduplication, and current-state subscription reconciliation, using a dedicated billing role. Real Stripe validation and usage delivery remain release work. See [the runtime guide](crm-runtime.md).

Invitations store token hashes, expiry, acceptance/revocation timestamps, and the inviting user. The auth service performs membership management within a workspace transaction; it never exposes token hashes in roster responses. The application enforces last-owner protection and role permissions while holding a shared workspace lock. See [teams and invitations](crm-runtime.md) for the runtime behavior.

## Isolation and authorization

Every customer domain table has workspace_id. A relationship between workspace-owned rows includes both workspace_id and the target ID. Policies use core.workspace_id(), which reads a transaction-local setting. No workspace context means no visible customer rows. Module policies additionally require the module to be enabled.

Use the runtime role for application queries. Superusers and BYPASSRLS roles bypass row-level security; FORCE ROW LEVEL SECURITY does not change that. The migration owner must not be used by a web application. Runtime grants intentionally exclude global identities and module administration.

Row-level security is defense in depth for a trusted backend, not authentication. A database client able to set its own workspace context must not be exposed directly to customers. The backend verifies identity and membership before querying domain tables. Action-level permissions remain a separate check.

```sql
BEGIN;
SELECT set_config('app.workspace_id', $1, true);
SELECT role FROM core.memberships WHERE workspace_id = $1 AND user_id = $2;
-- Continue only for an authenticated member with permission for this action.
SELECT id, name FROM contacts.contacts WHERE workspace_id = $1;
COMMIT;
```

The placeholders above are driver parameters. Do not interpolate request values into SQL. SET LOCAL / set_config(..., true) prevents a pooled connection from retaining a workspace after commit or rollback.

## Domain constraints

Booking prevents overlapping confirmed appointments per resource with a GiST exclusion constraint. Slots are half-open, so adjacent appointments are allowed. Availability matching, service duration, timezone validation, multi-resource jobs, payments, and rescheduling rules need API-level implementation.

CMS publications reference an exact revision belonging to the same entry and workspace. Published content delivery will need a separate, deliberately restricted query path; do not make the authoring tables anonymously readable.

Document extraction records retain versions, model provenance, and optional confidence. A review references the extraction it reviewed. File scanning, extraction orchestration, and review transition authorization are pending.

## Migrations and lifecycle

The CLI wraps each install in a single transaction and an advisory lock. It records SHA-256 checksums, skips unchanged applied migrations, and fails on drift. New changes use new migration files. Failed installs roll back both schema changes and module registration.

Module disable changes enabled state; it does not delete tables. Active direct dependents block disable, which protects the dependency chain. Runtime table queries are gated by RLS. Future routes, navigation, workers, scheduled jobs, and cached responses must consult module state as well; database gating alone does not cancel an external operation already in flight.

There is no automated destructive rollback or purge. Back up before production migrations, test restoration, and use forward repairs. Breaking changes require expand/backfill/contract releases.

References: [PostgreSQL row security](https://www.postgresql.org/docs/17/ddl-rowsecurity.html), [constraints](https://www.postgresql.org/docs/17/ddl-constraints.html), [psql](https://www.postgresql.org/docs/17/app-psql.html).
