# PostgreSQL

> Managed PostgreSQL on Sysnee: creating, connecting with SSL, pooling, Prisma, Drizzle, lifecycle and use by coding agents.

## What it is

Each Sysnee database is its own PostgreSQL instance, in an isolated container. It is not a schema on a shared server.

| Item | Value |
|---|---|
| Versions | PostgreSQL 16, 17 or 18 (default: 18) |
| Region | `br-sp-1` (São Paulo). It is the only region. |
| Port | `5432` |
| Default database | `postgres` |
| User | `app_owner` |
| SSL | Required |

### Sizes

| Size | Console | CPU | Memory |
|---|---|---|---|
| `low` | Low | 0.5 vCPU | 256 MB |
| `medium` | Medium | 1 vCPU | 1 GB |
| `high` | High | 1.5 vCPU | 2 GB |

### Purpose and storage

| Purpose | Sizes in the console | Storage |
|---|---|---|
| `development` | `low` | 2 GB, fixed |
| `staging` | `low`, `medium`, `high` | 2 to 1024 GB |
| `production` | `medium`, `high` | 2 to 1024 GB |

The console enforces these size combinations. The API, the CLI and MCP only refuse more than 2 GB of storage for `development`.

Storage is billed by what is allocated, not by what is used. Version, size, storage and network access are chosen at creation and do not change later. Prices are in [Pricing](https://docs.sysnee.com/en/pricing.md).

### The `app_owner` user

`app_owner` owns the `postgres` database and can create databases, roles and trusted extensions (for example `pgcrypto`, `uuid-ossp`, `citext`, `hstore`). It is not a superuser: `COPY ... PROGRAM`, reading server files and untrusted extensions (`pg_stat_statements`, `dblink`, `postgres_fdw`) are not available.

## Host

```text
<slug>.pgs.br-sp-1.sysnee.com
```

The `slug` is the name you gave the database plus a random 6-character suffix. A database named `shop` lives at, for example, `shop-k3x9qa.pgs.br-sp-1.sysnee.com`. The host is shown in the console, by `sysnee db info` and by the MCP tool `get_database`.

The name starts with a letter, uses only lowercase letters, digits and hyphens, and has up to 56 characters.

## Password

Sysnee does not keep the password. The database server only receives its SCRAM-SHA-256 verifier. There is no password recovery in the console.

Rules: 14 to 128 characters, printable ASCII only (no accented letters).

| Where the database is created | Who generates the password | Where it shows up |
|---|---|---|
| Console | You type it or click **Generate** | Only on the create screen. Copy it before you submit. |
| CLI (`sysnee db create`) | The CLI, on your machine | Written as `DATABASE_URL` into the `--dotenv` file. Never printed. |
| MCP (`create_database`) | Sysnee | Behind a reveal link in the console. The agent never sees the password. |

The MCP reveal link is valid for 15 minutes and opens once, only for the user who authorized the agent, signed in to the console.

## Connecting

### Connection string

```text
postgresql://app_owner:<PASSWORD>@<slug>.pgs.br-sp-1.sysnee.com:5432/postgres?sslmode=require
```

If the password has URL-special characters (`@`, `:`, `/`, `?`, `#`, `%`), percent-encode it. The CLI does this when it writes the `.env`.

### SSL and SNI

Every database sits behind a proxy on port 5432. The proxy picks the database by the host name sent in the TLS handshake (SNI). So:

- Connections without SSL never reach the database. Use `sslmode=require` or stricter.
- The client must send SNI. libpq sends it by default since version 14 (`sslsni=1`). Do not turn it off.
- Connect by host name, never by IP. An IP carries no SNI.
- The proxy offers the `postgresql` ALPN, which libpq 17 and later require.

The certificate is a wildcard for `*.pgs.br-sp-1.sysnee.com`.

### psql

```bash
psql "postgresql://app_owner:<PASSWORD>@shop-k3x9qa.pgs.br-sp-1.sysnee.com:5432/postgres?sslmode=require"
```

With the URL in `.env`, without putting the password in shell history:

```bash
set -a; . ./.env; set +a
psql "$DATABASE_URL"
```

### Node.js (`pg`)

```js
import pg from 'pg';

const pool = new pg.Pool({
  connectionString: process.env.DATABASE_URL,
  max: 10,
});

const { rows } = await pool.query('select version()');
console.log(rows[0].version);
```

`pg` sends SNI when the host is a name. With `sslmode=require` in the URL, recent versions of `pg` also verify the certificate.

### GUI clients (DBeaver, TablePlus, pgAdmin)

| Field | Value |
|---|---|
| Host | `<slug>.pgs.br-sp-1.sysnee.com` |
| Port | `5432` |
| Database | `postgres` |
| User | `app_owner` |
| SSL | On, mode `require` |

### Network access

At creation you pick one:

- **Public:** any IP may try to connect. The password is the protection.
- **Restricted:** one IPv4 range in CIDR notation only, for example `203.0.113.0/24`. Other IPs are refused at the proxy.

With restricted access, the machine that runs migrations must be in the range too.

## Connections and pooling

There is no built-in pooler (no PgBouncer). Every connection goes straight to PostgreSQL.

The limit is PostgreSQL's default: `max_connections = 100`, with a few reserved for the platform's superuser. On `low` (256 MB) each connection also takes memory.

- Use a pool in the app and keep it small (5 to 10 per process).
- Add up the pools of every process and replica. The total must stay below the limit.
- In serverless functions, create the pool outside the handler so invocations reuse it, and keep `max` low (1 to 2). Many concurrent instances can use up the connections.
- Close idle connections (`idleTimeoutMillis` in `pg`).

## Prisma

`.env`:

```bash
DATABASE_URL="postgresql://app_owner:<PASSWORD>@shop-k3x9qa.pgs.br-sp-1.sysnee.com:5432/postgres?sslmode=require"
```

Prisma 6 or earlier, in `prisma/schema.prisma`:

```prisma
datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}
```

Prisma 7, in `prisma.config.ts`:

```ts
import 'dotenv/config';
import { defineConfig, env } from 'prisma/config';

export default defineConfig({
  schema: 'prisma/schema.prisma',
  migrations: { path: 'prisma/migrations' },
  datasource: { url: env('DATABASE_URL') },
});
```

Do not use `directUrl`: there is no pooler, so the direct URL is the only one.

Migrations from your machine or CI:

```bash
npx prisma migrate dev --name init   # development
npx prisma migrate deploy            # apply existing migrations
```

`prisma migrate dev` creates a temporary shadow database. `app_owner` has `CREATEDB`, so this works on the same server.

## Drizzle

`node-postgres` driver:

```bash
npm install drizzle-orm pg
npm install -D drizzle-kit
```

`src/db.ts`:

```ts
import { drizzle } from 'drizzle-orm/node-postgres';
import { Pool } from 'pg';

const pool = new Pool({ connectionString: process.env.DATABASE_URL, max: 10 });
export const db = drizzle(pool);
```

`drizzle.config.ts`:

```ts
import 'dotenv/config';
import { defineConfig } from 'drizzle-kit';

export default defineConfig({
  dialect: 'postgresql',
  schema: './src/schema.ts',
  out: './drizzle',
  dbCredentials: { url: process.env.DATABASE_URL! },
});
```

Migrations:

```bash
npx drizzle-kit generate
npx drizzle-kit migrate
```

## Lifecycle

### States

| State | Meaning |
|---|---|
| `starting` | Being created or started. Creation takes a minute or two. |
| `running` | Accepting connections. |
| `stopping` | Stopping. |
| `stopped` | Stopped. Data kept. |
| `deleting` | Being deleted. |

In the console, a database that never came up shows as failed. There is nothing to start; delete it and create another.

### Stop and start

- Stopping closes open connections. Compute stops being billed. Storage is still billed and the data is kept.
- Starting bills compute again. The creation rules apply: a suspended account, an overdue invoice or a reached spend limit block the start.
- You can only stop a `running` database and only start a `stopped` one.

### Delete

Deleting removes the container and the data volume. It cannot be undone.

- **In the console:** the organization owner deletes it and confirms in the confirmation dialog.
- **With a token (CLI, MCP, API):** nothing is deleted directly. The token files a deletion request and gets a link. The same person opens the link in the console within 30 minutes, types the database name and passes two-step verification.

### Backups

There are no automatic backups. Make your own with `pg_dump` (use a `pg_dump` of the server's major version or newer):

```bash
pg_dump "$DATABASE_URL" --format=custom --file=backup.dump
pg_restore --dbname="$DATABASE_URL" --no-owner backup.dump
```

### Who can do what

- Every organization member sees the databases.
- Creating, stopping, starting and deleting are for the organization owner only.

### Account requirements

Creating databases needs account level 3:

1. Verified email.
2. A second factor: an authenticator app or a passkey. Google sign-in does not count as a second factor.
3. A verified billing account: complete profile, a saved card and no overdue invoice.

Current limits: 10 databases created per day per organization (day in Brasília time) and 10 creations per hour per user, sites and databases together. When a limit is hit, the response lists the missing steps.

## For agents

### CLI

| Command | What it does |
|---|---|
| `sysnee db list [--project <id>]` | Lists databases |
| `sysnee db info <database>` | Details and connection string with `<PASSWORD>` in place of the password |
| `sysnee db create <name> --dotenv .env` | Creates the database and writes `DATABASE_URL` into `.env` |
| `sysnee db stop <database>` | Stops the database |
| `sysnee db start <database>` | Starts the database |
| `sysnee db delete <database>` | Files a deletion request and exits with code 2 |

`<database>` takes the name, the slug or the id (UUID).

`db create` options:

| Option | Default | Values |
|---|---|---|
| `--size` | `low` | `low`, `medium`, `high` |
| `--storage` | `2` | GB, 2 to 1024 |
| `--purpose` | `development` | `development`, `staging`, `production` |
| `--pg-version` | `18` | `16`, `17`, `18` |
| `--allow` | public | one IPv4 CIDR range |
| `--dotenv` | | `.env` file that receives the URL |
| `--env-key` | `DATABASE_URL` | variable name |
| `--yes` | | replace an existing variable without asking |
| `--show-password` | | print the password. Do not use when an agent runs the command. |

Storage above 2 GB needs `--purpose staging` or `--purpose production`.

```bash
sysnee db create shop --dotenv .env --json
sysnee db create shop-prod --purpose production --size medium --storage 20 --dotenv .env --json
```

The CLI generates the password locally, writes the URL to the file with mode `0600` and warns when the file is not in `.gitignore`. Without `--dotenv` or `--show-password`, the command refuses and exits with code 2.

`sysnee db delete` needs the `databases:delete` scope, which the default login does not ask for:

```bash
sysnee login --scopes "account:read databases:read databases:write databases:delete"
```

Exit codes: `0` ok, `1` error, `2` a person must confirm (nothing was done), `3` sign-in needed. `sysnee schema` prints every command as JSON. See [CLI](https://docs.sysnee.com/en/cli.md).

### MCP

| Tool | Scope | What it does |
|---|---|---|
| `list_databases` | `databases:read` | Lists databases, without passwords |
| `get_database` | `databases:read` | State, host, port, database, user and connection string with `<PASSWORD>` |
| `create_database` | `databases:write` | Creates the database and returns a `reveal_url` for the person |
| `stop_database` | `databases:write` | Stops the database |
| `start_database` | `databases:write` | Starts the database |
| `request_deletion` | `databases:delete` | With `resource_type: "database"`, files a deletion request and returns a `confirm_url` |

`create_database` requires `project_id`, `name`, `size` and `storage_gb`. `purpose` (default `development`), `version` (default `18`) and `allowed_cidr` are optional. After creating, poll `get_database` until the state is `running`. See [MCP](https://docs.sysnee.com/en/mcp.md) and [Tokens](https://docs.sysnee.com/en/tokens.md).

### Password rules

- Never print, log or paste the password into the chat.
- Never commit the password or the `.env`. Keep `.env` in `.gitignore`:

```bash
grep -qxF '.env' .gitignore 2>/dev/null || echo '.env' >> .gitignore
```

- With the CLI, use `--dotenv`. With MCP, give the `reveal_url` to the person and ask them to put the password into `.env`.
- To connect, read `DATABASE_URL` from the environment. Do not copy the URL into code.
