thelastapi
Get started free

Run database migrations safely with an AI agent

Run safe database migrations with an AI agent by using isolated development branches with schema-only clones and scoped Limited API keys.

On this page 10 sections

AI agents should never run schema migrations directly against a live database; instead, give the agent access to an isolated development branch that contains your schema without any production rows. thelastapi provides a serverless Postgres database with dedicated development environments designed specifically for AI agents and local development. This setup preserves your migration ledgers while keeping live user data completely protected from accidental modification or exposure.

When letting agents like Claude Code, Cursor, or Codex write and test schema changes, security boundaries matter. This guide covers how to set up an isolated database branch, run migrations safely with common ORMs, and promote changes without exposing production data.

Why agents should not touch live databases directly

Letting an autonomous coding agent connect directly to a live database introduces two distinct risks:

  1. Accidental data loss or schema corruption. An agent generating and applying a migration can drop columns, truncate tables, or cause lock contention without human review.
  2. Data exposure. Real databases contain user records, email addresses, and session tokens. If an agent holds full production credentials, those rows can easily end up inside model context windows and external logs. As detailed in our guide on why agents should never touch production rows, strict separation between schema structure and user data is necessary.

thelastapi handles this through built-in environment separation. Every project includes two environments: production and development. In development, you get a clean branch of your Postgres database that retains all your tables and schema structure, but empties every row. Migration ledgers from tools like Drizzle and Prisma are preserved so that your migrations run cleanly without re-running existing steps.

The safety model: Full vs. Limited keys

thelastapi controls access using API keys scoped by environment and permissions. You can inspect key types and scopes in Keys and environments.

  • Full-access key (access: owner): Created by the project owner. It can access production secrets, manage billing, rotate live keys, and run actions across both environments.
  • Limited key (access: agent): Built for automated agents. It defaults to the development environment, creates and tests migrations, and reads development database tables. It can never read production rows or view live production connection strings.
Key typeDevelopment DATABASE_URLProduction DATABASE_URLList and read dev tablesRead production rows
Full-access keyYesYesYesYes
Limited keyYesNo (403 owner_only)YesNo (403 owner_only)

To create a Limited key for your AI agent, run:

Terminal
vibiz keys create migration-agent --limited

If an agent holding a Limited key attempts to access production database secrets, the API returns a 403 forbidden error with details.reason: "owner_only" and provides a details.grant_url link where the human owner can review the request.

Step 1: Set up the development branch

When an agent needs to test a new migration, generate the development environment using the CLI:

Terminal
vibiz dev

This command branches the schema from production, cleans out all application rows (as well as sign-in users and sessions), verifies the structure, and outputs your DATABASE_URL into .env.development.local. Migration ledgers remain intact. If you want to run a migration command without writing variables to a file on disk, pass it directly:

Terminal
vibiz dev -- npx drizzle-kit migrate

If you ever need to reset the branch back to a fresh mirror of the production schema, use the --reset flag:

Terminal
vibiz dev --reset

The next run of vibiz dev will branch the production schema again from scratch.

Step 2: Let the agent write and test migrations

With a development database ready, your agent can inspect the existing schema, modify migration files, and execute them safely against the branch.

Inspecting schemas without an external client

You or your agent can view schemas, table lists, and row count estimates over HTTP:

Terminal
curl "https://thelastapi.dev/v1/projects/prj_123/database?env=development" \
  -H "Authorization: Bearer $VIBIZ_API_KEY"

The agent can also run read-only queries against the development database:

Terminal
curl https://thelastapi.dev/v1/projects/prj_123/database/query \
  -H "Authorization: Bearer $VIBIZ_API_KEY" \
  -H 'content-type: application/json' \
  -d '{"sql":"select table_name from information_schema.tables where table_schema = '\''public'\''","env":"development"}'

The database query endpoint allows a single SELECT, WITH, TABLE, VALUES, EXPLAIN, or SHOW statement up to 20,000 characters and runs for at most 5 seconds, returning up to 500 rows. Any statement that attempts to write via the query endpoint returns a 400 invalid_request error. To write or run DDL statements, use your standard migration tools with the development DATABASE_URL.

Running Drizzle or Prisma

Your agent can use standard migration tooling directly against the development database URL. Read our walkthrough on how to use Postgres from Next.js with Drizzle or Prisma for full configuration details.

Terminal
# Apply migrations to the development copy
npx drizzle-kit migrate

# Or with Prisma
npx prisma migrate dev

You can test connections directly in code using standard Postgres drivers:

TypeScript
import postgres from 'postgres';

const sql = postgres(process.env.DATABASE_URL!);
const rows = await sql`select table_name from information_schema.tables where table_schema = 'public' limit 10`;
console.log(rows);

Step 3: Back up before applying to production

Before applying newly generated migrations to your live production database, create a full backup using the export command:

Terminal
vibiz export --db

This exports your database as a gzip-compressed SQL snapshot (<slug>-<env>-database.sql.gz). It contains all schemas, tables, rows, keys, indexes, views, and sequence positions. Because the dump omits custom role ownerships and grants, it can be restored directly into any Postgres instance (version 15 or newer) using standard tools:

Terminal
gunzip -c shop-production-database.sql.gz | psql "$NEW_DATABASE_URL"

Only full-access keys held by project owners can export the production database. Limited keys used by agents default to exporting the development database; attempting to export production rows with a Limited key returns a 403 owner_only error. For more details on backup archives, see the Export documentation.

Step 4: Apply to production

Once you have verified the migration on the development branch and taken a backup, apply the migration to production using your full-access key:

Terminal
# Run migrations against the production environment
vibiz env -- npx drizzle-kit migrate

Alternatively, if your application runs on an external server or platform, load the production credentials at runtime using @vibiz/app and VIBIZ_APP_KEY:

TypeScript
import { vibiz } from '@vibiz/app';

// Injects DATABASE_URL and other secrets into process.env
await vibiz.loadEnv();

For applications hosted outside the platform, see our guide on how to use one service.

Development vs. production database features

FeatureDevelopment BranchProduction Database
Row DataEmptied / schema-onlyLive production rows
Migration LedgersPreservedPreserved
Default Access KeyLimited key (access: agent)Full-access key (access: owner)
Agent CLI Accessvibiz devBlocked (403 owner_only)
Read Query EndpointAvailableRequires owner permissions
Export AccessAvailable to Limited keysOwners only

Pricing and resource limits

Postgres resources on thelastapi follow these specifications:

  • Database Pricing: Usage records each ready database at an estimated $0.02 a day of cost, billed with the default margin (+20% today, tracked as billed_usd in usage reports).
  • Database Limits: One database per project, with one development branch per project.
  • Query Limits: Read views are restricted to 20,000 characters and 5 seconds execution time, returning up to 500 rows (truncated: true if exceeded). Table view pages return up to 200 rows.
  • Export Limits: One active export run per project at a time, up to 10 exports per day. Maximum uncompressed export sizes are 1 GB for application code and 2 GB for database dumps.

Next steps

To manage your database alongside other resources using a single credential, read one API key for an AI agent: hosting, database, email, payments and models. For instructions on configuring standalone databases for smaller projects, visit our guide on serverless Postgres for side projects: one database per project, or refer to the official Database documentation.

Frequently asked questions

Can an AI agent run destructive database migrations directly on production?

No. Limited keys assigned to agents cannot view production connection strings or read production rows, and commands targeting production return a 403 forbidden error with owner_only.

How does the development branch retain existing migration history without production data?

The development branch clones the production schema and migration ledgers (such as those used by Drizzle or Prisma) while emptying all user, session, and application table rows.

How do I back up my production database before running a schema migration?

Run vibiz export --db with a full-access key to download a gzipped SQL snapshot that can be restored into any Postgres 15+ database using psql.