# Database

An app with its own server can have a Postgres database. Each app gets its own, never shared with other apps: Postgres 17 with pgvector. It's backed up nightly, and it counts towards your account's storage.

## Getting one
If your app already uses Postgres, `toupas live` sees it and creates the live database the first time. It asks whether the live app starts with a copy of the data on your computer or starts empty (`--copy-local-data` or `--start-empty` answer ahead). To add one later: `toupas db create`.

The app gets `DATABASE_URL`, and `PGHOST`, `PGPORT`, `PGUSER`, `PGPASSWORD` and `PGDATABASE`. Read them from the environment; don't write them into the code. Toupas manages these settings, so `toupas env` can't change them.

An app that keeps its data in SQLite or other files next to its code loses it on every update, because live apps can only write to `/tmp`. `toupas live` stops and says so; switch the app to Postgres first. If the app sets its own `DATABASE_URL` to a database elsewhere, Toupas leaves it alone.

## On your computer
```
toupas dev db
```
Starts a Postgres on your computer that matches the live one (in Docker) and writes its `DATABASE_URL` to `.env`. `--stop` stops it and `--reset` empties it.

## Looking at live data
| Command | What it does |
|---|---|
| `toupas db info` | Its size, tables, open connections, extensions and connection string. `--reveal` shows the password |
| `toupas db query "SELECT …"` | Run one query. Read-only unless you add `--write`. At most 30 seconds and 1,000 rows |
| `toupas db shell` | psql on the live database |
| `toupas db tunnel` | The live database on a port on your computer (`--port 5433`), for a database app such as TablePlus or DBeaver. Closes after 30 minutes unused |

Opening the live database from your computer (`db shell`, `db tunnel`, `db query --write`, `--reveal`) is off at first. An account owner or admin turns it on in the Toupas panel, for an hour, a day, a week or until turned off. Each uses a temporary login that lasts at most an hour.

## Copies in and out
| Command | What it does |
|---|---|
| `toupas db export [file]` | Save a copy of the live database in pg_dump's custom format |
| `toupas db import <file> --yes` | Copy a `pg_dump --format=custom` file into the live database, all or nothing |

## Extensions
`toupas db extensions enable <name>` adds one of: `vector`, `pgcrypto`, `uuid-ossp`, `citext`, `pg_trgm`, `hstore`, `unaccent`, `btree_gin`, `btree_gist`, `fuzzystrmatch`. `vector` is pgvector.

## Limits
- 10 connections at once per app: use a small pool.
- `toupas db rotate-password` gives the database a new password, and the app the new settings.
- When an app stops because its trial ended or a payment failed, its data is kept for 30 days.
