SkybuDocs

Ferdigheter · Oppskrifter

Build an app with a database

Go from an empty folder to a deployed Node app with its own Postgres database, schema migrations, and a restore point before each later schema change.

skill://playbooks/app-with-a-databaseAgenter leser den med resources/read eller skills_read. Den er skrevet på engelsk, for agentene.

This playbook takes an app from an empty folder to a running address with a Postgres database behind it. The app uses Drizzle on top of pg, reads DATABASE_URL for its queries and keeps its schema in migration files. Skybu creates the database and hands the app its address; it does not run migrations for you. In production the schema is changed by app_owner through a tunnel from a machine with the Skybu CLI; in previews the app migrates its own empty database at start.

In short

  1. list_projects, or create_project.
  2. Ask the user for the app's data class (and department, if list_departments returns any).
  3. create_database named main, and wait until it is ready.
  4. Write the app: queries on DATABASE_URL, a migrate script on DATABASE_URL_DIRECT.
  5. Generate the first migration and run it as app_owner through skybu db connect.
  6. Deploy with deploy_files and follow get_deployment until live.
  7. Check it with get_app_logs and query_database.
  8. Before every later migration: create_restore_point, wait for ready, migrate, then deploy.

Step 1–3: project, data class, database

{ "name": "create_project", "arguments": { "name": "notater" } }

Ask the user what data the app will hold. Notes about customers are personal, not internal; the classes are in skill://apps/deploy-an-app. Never pick one yourself.

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

Poll list_projects until the database's status is ready (about a minute). Name it main: when a project has several databases, apps get the one named main. What each variable gives, the limits per role and TLS are in skill://databases/use-the-database. The short version:

VariableRoleProductionPreviews
DATABASE_URLrows only, no schema changesyesyes, its own empty database
DATABASE_URL_READONLYread onlyyesno
DATABASE_URL_DIRECTowner, for migrationsnoyes

Step 4: the app

Node 24 runs TypeScript files directly, so there is no build step. The versions are the ones Skybu itself uses.

package.json:

{
  "name": "notater",
  "private": true,
  "type": "module",
  "engines": { "node": ">=24" },
  "scripts": {
    "start": "node src/migrate.ts && node src/server.ts",
    "generate": "drizzle-kit generate"
  },
  "dependencies": { "drizzle-orm": "0.45.4", "pg": "8.16.3" },
  "devDependencies": { "drizzle-kit": "0.31.11", "@types/pg": "^8" }
}

drizzle.config.ts:

import { defineConfig } from "drizzle-kit";

export default defineConfig({ dialect: "postgresql", schema: "./src/db/schema.ts", out: "./drizzle" });

src/db/schema.ts:

import { pgTable, text, timestamp, uuid } from "drizzle-orm/pg-core";

export const notes = pgTable("notes", {
  id: uuid("id").primaryKey().defaultRandom(),
  body: text("body").notNull(),
  createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
});

src/db.ts. Keep the pool small: every app and pod in the project shares the role's 30 connections.

import { drizzle } from "drizzle-orm/node-postgres";
import pg from "pg";
import * as schema from "./db/schema.ts";

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

src/migrate.ts. It runs only where DATABASE_URL_DIRECT is set, which on Skybu means previews:

import { drizzle } from "drizzle-orm/node-postgres";
import { migrate } from "drizzle-orm/node-postgres/migrator";
import pg from "pg";

const url = process.env.DATABASE_URL_DIRECT;
if (!url) {
  console.log("DATABASE_URL_DIRECT is not set; not migrating");
} else {
  const pool = new pg.Pool({ connectionString: url, max: 1 });
  await migrate(drizzle(pool), { migrationsFolder: "./drizzle" });
  await pool.end();
}

src/server.ts:

import { createServer } from "node:http";
import { desc } from "drizzle-orm";
import { db } from "./db.ts";
import { notes } from "./db/schema.ts";

createServer(async (req, res) => {
  try {
    if (req.method === "POST" && req.url === "/notes") {
      let body = "";
      for await (const chunk of req) body += chunk;
      const [note] = await db.insert(notes).values({ body: JSON.parse(body).body }).returning();
      return res.writeHead(201, { "content-type": "application/json" }).end(JSON.stringify(note));
    }
    const rows = await db.select().from(notes).orderBy(desc(notes.createdAt)).limit(50);
    res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify(rows));
  } catch (error) {
    console.error(error);
    res.writeHead(500).end("Something went wrong");
  }
}).listen(Number(process.env.PORT ?? 8080));

Plain pg without Drizzle works the same way (pool.query("select …")); keep the migrate step either way.

Step 5: the first migration

npm install                 # writes package-lock.json, which the build needs
npm run generate            # writes drizzle/0000_….sql and drizzle/meta/ from the schema

Production apps cannot change the schema, so run the migration as app_owner through a tunnel. This needs a shell where skybu is logged in with a CLI token; an agent connected only over MCP cannot open the tunnel. Ask the user before you change a production schema.

skybu db connect notater/main --role owner   # keeps running; prints a URL on 127.0.0.1:6543

In a second shell, give the printed URL to the migrate script, with sslmode=require replaced by uselibpqcompat=true&sslmode=require. node-postgres reads plain sslmode=require as "verify the certificate", and your machine does not have the database's CA; the libpq-compatible mode encrypts without verifying, as psql does.

DATABASE_URL_DIRECT='postgres://app_owner:…@127.0.0.1:6543/app?uselibpqcompat=true&sslmode=require' node src/migrate.ts

Stop the tunnel afterwards. Do not paste the password into chat, files or commits. If you have no shell with the CLI, give the user these commands and wait for them to report back.

Tables that app_owner creates in public are readable and writable for the app automatically. In another schema, add GRANT statements to the migration (skill://databases/use-the-database).

Step 6: deploy

Send every file the app needs, including the drizzle/ folder with drizzle/meta/_journal.json, which the migrator reads, and the lockfile. Leave out node_modules.

{
  "name": "deploy_files",
  "arguments": {
    "projectId": "<project id>",
    "name": "notater",
    "dataClass": "personal",
    "files": [
      { "path": "package.json", "content": "…" },
      { "path": "package-lock.json", "content": "…" },
      { "path": "drizzle.config.ts", "content": "…" },
      { "path": "src/server.ts", "content": "…" },
      { "path": "src/db.ts", "content": "…" },
      { "path": "src/db/schema.ts", "content": "…" },
      { "path": "src/migrate.ts", "content": "…" },
      { "path": "drizzle/0000_initial.sql", "content": "…" },
      { "path": "drizzle/meta/_journal.json", "content": "…" },
      { "path": "drizzle/meta/0000_snapshot.json", "content": "…" }
    ]
  }
}

Follow it with get_deployment until live, as in skill://apps/deploy-an-app. A failed build or start is covered by skill://apps/fix-a-failed-deploy.

Step 7: check it

Open the address, add a note with a POST /notes, and read the app's log:

{ "name": "get_app_logs", "arguments": { "appId": "<app id>" } }

relation "notes" does not exist means the migration has not run against this database. To see that rows arrive without reading them:

{ "name": "query_database", "arguments": { "databaseId": "<database id>", "sql": "select count(*) from notes" } }

Counts come back as numbers; text in untagged columns is hidden (skill://data/query-data-safely).

Step 8: later schema changes

For every change to the schema:

  1. Change src/db/schema.ts and run npm run generate. Read the generated SQL before it runs.
  2. Mark the moment, so the user can take the database back if the migration goes wrong:

    ``jsonc { "name": "create_restore_point", "arguments": { "databaseId": "<database id>", "name": "before adding notes.title" } } ``

    The point is the moment it was made, so you can migrate right away. list_restore_points shows it pending, then ready within a few minutes; only a ready point can be restored to, so check it before you tell the user the change is safe.

  3. Run the migration through the tunnel as in Step 5.
  4. Deploy the new code.

The version that is running keeps serving while you migrate, and during the deploy old and new run side by side. Write changes that both can live with: add a nullable column or a new table first, start using it in the next deploy, and drop the old column in a later one. rollback_app puts back the old code but never the old schema.

If a migration damages data, only a person can restore the database; see skill://databases/restore-a-database.

Things to know

  • The database starts with vector (pgvector) installed. Extensions that need a superuser are refused.
  • Pull request previews get their own empty database and DATABASE_URL_DIRECT, so npm start migrates them. Seed test data there, never production data (skill://apps/previews-and-approval).
  • When the organisation requires approval for production, a deploy waits in awaiting_approval; the migration you ran is already live by then, which is one more reason to keep it compatible with the running version.
  • Do not copy the owner URL into an app variable under another name to migrate in production.
  • get_database_credentials is not needed for any of this: the app gets its URLs by itself, and the addresses work only from inside the project.