SkybuDocs

Ferdigheter · Databaser

Use the database

Create a project's Postgres database, connect an app to it, choose the pooler when it fits, run migrations as a release command, and reach it from a laptop.

skill://databases/use-the-databaseAgenter leser den med resources/read eller skills_read. Den er skrevet på engelsk, for agentene.

A Skybu database is its own Postgres 17 cluster (CloudNativePG) with pgvector, inside a project. Apps in the same project get its address as environment variables; nothing outside the project can reach it over the network. The database inside the cluster is called app, and three roles with different rights connect to it.

In short

  1. list_projects to see whether the project already has a database. If not, create_database, named main.
  2. Wait until its status is ready (about a minute). The project's apps restart with DATABASE_URL set.
  3. Have the app connect with DATABASE_URL (straight to Postgres) and a small pool. Use DATABASE_URL_POOLED (through PgBouncer) instead only when the app opens many short connections and keeps no session state (below).
  4. Run schema changes as the app's release command (set_app_hosting with releaseCommand, such as npx prisma migrate deploy): it runs as the owner role before each new version gets traffic, after a restore point.

Step 1: create it

{ "name": "create_database", "arguments": { "projectId": "<project id>", "name": "main" } }

The name is 2–31 characters: a lowercase letter, then lowercase letters, digits and hyphens. The answer has the id and "status": "provisioning". Follow it with list_projects, which lists each project's databases with their status and the project's wiredDatabaseId.

StatusMeaning
provisioningBeing created, or applying new passwords.
readyIn use.
restoringBeing restored to an earlier time.
suspendedThe organisation is suspended; the cluster is hibernated and its data kept.
recovery_incompleteA recovery stopped early. Apps get no DATABASE_URL. Tell the user to contact Skybu.

An organisation may have 2 databases unless Skybu has given it more (db_quota_reached). Each has 1 GB of storage. For an import from Supabase, create it with the supabase argument instead (skill://playbooks/leave-supabase).

Step 2: what apps get

Only one database per project is wired to apps: the ready one named main, otherwise the oldest ready one.

VariableRoleRightsProductionPreviews
DATABASE_URLapp_rw, straight to PostgresRead and write rows; cannot create, change or drop tablesyesyes (own database)
DATABASE_URL_POOLEDapp_rw, through PgBouncerAs above, in transaction mode (below); set once the pooler answersyesyes
DATABASE_URL_UNPOOLEDapp_rw, straight to PostgresThe same as DATABASE_URL, kept for apps that already use ityesyes
DATABASE_URL_READONLYapp_roRead onlyyesno
DATABASE_URL_DIRECTapp_ownerOwns the schema; for migrationsonly in the release commandyes

DATABASE_URL* names are reserved, so set_env_vars refuses them. Each pull request preview gets its own empty database, never production's (skill://apps/previews-and-approval).

TLS

Postgres accepts only TLS connections with SCRAM passwords. The URLs carry sslmode=require. The app also gets the database's CA certificate at /etc/skybu/postgres/ca.crt, with NODE_EXTRA_CA_CERTS and PGSSLROOTCERT pointing at it, so node-postgres and libpq verify the server without extra code. Pass the URL as is; do not turn verification off.

import pg from "pg";
export const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL, max: 5 });

Limits per role

RoleConnectionsstatement_timeout
app_owner105 min
app_rw3030 s
app_ro1030 s

A role's limit is shared by every app and pod in the project, and old and new versions overlap during a deploy, so keep pools small.

The pooler

Each database has a PgBouncer in front of it, in transaction mode. It is opt-in: DATABASE_URL always goes straight to Postgres, and the app uses the pooler only if it connects with DATABASE_URL_POOLED. Through the pooler, many short connections from apps, workers, jobs and previews share a few to Postgres; a connection is the app's only for one transaction at a time.

Use DATABASE_URL_POOLED when the app opens many connections (serverless-style handlers, many workers or jobs, a large pool) and every request is a plain query or transaction. Keep DATABASE_URL when the app needs any of this, which transaction mode cannot give:

  • Session state. SET without LOCAL, set_config(..., false), session advisory locks, LISTEN/NOTIFY, temporary tables kept between transactions and WITH HOLD cursors. The next transaction may run on another server connection.
  • Custom startup parameters. Settings sent when the connection opens, such as postgres.js's connection: { "app.crypt_key": … } or libpq's options=-c …, are refused (unsupported startup parameter) or ignored. PgBouncer passes on only client_encoding, DateStyle, TimeZone, standard_conforming_strings and application_name, and ignores extra_float_digits, options and search_path. Set such values per transaction with SET LOCAL instead, or stay on DATABASE_URL.
  • Prepared statements beyond the pooler's cache. Named prepared statements work (node-postgres, postgres.js, Prisma and Drizzle need nothing extra), up to 200 per server connection; more are prepared again as needed.

Two ways to switch an app that reads DATABASE_URL and cannot be changed: a start command that sets it (set_app_hosting with command DATABASE_URL=$DATABASE_URL_POOLED node server.js), or code that prefers it (process.env.DATABASE_URL_POOLED ?? process.env.DATABASE_URL). DATABASE_URL_POOLED appears once the pooler answers (about a minute after the database is created), and the apps restart once when it does.

When Skybu changes an app's variables itself (a new database, new passwords, DATABASE_URL_POOLED appearing), the new version must start before the old one stops. If it does not, Skybu keeps the old version serving and holds the change back: get_app shows it as heldChange with the variables and the app's last lines, and the dashboard shows it on the app. The change is tried again with the next deploy or change to the app.

Step 3: schema changes

A production app's DATABASE_URL role cannot create tables. Run migrations as the app's release command: a command run once from each new version's image, after the build and before the version gets traffic.

{ "name": "set_app_hosting", "arguments": { "appId": "<app id>", "releaseCommand": "npx prisma migrate deploy" } }
  • It gets the app's variables plus DATABASE_URL_DIRECT (app_owner, straight to Postgres). Point the migration tool at that: Prisma's directUrl = env("DATABASE_URL_DIRECT"), Drizzle's dbCredentials.url process.env.DATABASE_URL_DIRECT. The tool must be in the built image (a dependency, not only a dev dependency, when the image is pruned).
  • In production, Skybu marks a restore point named release #<number> on the database first, so a bad migration can be undone (skill://databases/restore-a-database).
  • If it exits with anything but 0, runs out of memory or takes more than 10 minutes, the new version is not started and the live one keeps serving. The deployment fails with "The release command failed" and its log has the command's output (get_deployment).
  • Previews run it too, against their own database. A rollback does not run it again.
  • Write migrations that the version still running can live with for a moment: add columns before code uses them, drop them a version after code stops using them.

Other ways, when a release command does not fit:

  • From the user's machine. The CLI opens a tunnel through Skybu (a CLI key is needed; agents connected over OAuth cannot open it):

    skybu db connect shop/main --role owner     # tunnel on 127.0.0.1:6543 and a psql URL to use

    Then point the migration tool (prisma migrate deploy, drizzle-kit migrate, …) at the printed URL. If you have a shell where the user's skybu is logged in, you can do this yourself; otherwise give the user the commands.

  • In previews, DATABASE_URL_DIRECT is set in the app too, so an app can migrate itself at start. Prefer the release command, which does the same in production.

Create tables as app_owner in the public schema. Default privileges then give app_rw read and write and app_ro read on them. In another schema, grant USAGE and the table rights to app_rw and app_ro yourself.

Extensions

vector (pgvector) is installed in public. The owner can create trusted extensions such as pgcrypto. Extensions that need a superuser are refused (file_fdw, for example); there is no superuser login.

Credentials and local work

{ "name": "get_database_credentials", "arguments": { "databaseId": "<database id>" } }

Returns the three roles and their URLs. It needs secrets:read, is audited, and the organisation's owners get an email when an agent reads it. The host is inside the cluster, so the URLs work only from the project's apps; from a laptop, use skybu db connect <db> [--role app|owner|readonly]. Never put the passwords in chat or code.

{ "name": "rotate_database_passwords", "arguments": { "databaseId": "<database id>" } }

New passwords for all three roles; the old ones stop working. The status is provisioning until they are applied, then the apps restart with the new URLs. Use it when a password may have leaked.

Things to know

  • Do not copy the owner URL into an app variable of another name to migrate in production. The app would run with schema rights, and the next rotation breaks it. Use the release command.
  • Agents cannot delete a database. The user does it in the dashboard (https://platform.skybu.no) or with skybu db delete; its backups are kept for 30 days.
  • To look at the data without seeing who it is about, use query_database (skill://data/query-data-safely).