AAnvio
Database

Migrations

How the Postgres schema is generated, versioned, and applied using Drizzle Kit.

4 min read

Level 3+ only. At Level 1 (the default), there's nothing to migrate — the filesystem workspace has no schema versioning; you just copy the workspace/ directory. See Progressive Enhancement.

Anvio uses Drizzle Kit for schema migrations against PostgreSQL. Everything lives in packages/db.

Configuration

// packages/db/drizzle.config.ts
import { defineConfig } from 'drizzle-kit';

export default defineConfig({
  schema: './src/schema.ts',
  out: './drizzle',
  dialect: 'postgresql',
  dbCredentials: {
    url: process.env.DATABASE_URL ?? 'postgresql://anvio:anvio@localhost:5432/anvio',
  },
});
  • Schema source: packages/db/src/schema.ts (the Drizzle table definitions — see ERD and Tables)
  • Migration output: packages/db/drizzle/
  • Falls back to a local dev connection string if DATABASE_URL isn't set.

Current migration state

As of this writing there is exactly one migration:

packages/db/drizzle/
├── 0000_initial.sql
└── meta/
    └── _journal.json

meta/_journal.json:

{
  "version": "7",
  "dialect": "postgresql",
  "entries": [
    { "idx": 0, "version": "7", "when": 1718800000000, "tag": "0000_initial", "breakpoints": true }
  ]
}

0000_initial.sql creates all 9 tables (users, personas, skills, agents, agent_skills, sessions, session_messages, memory_entries, tool_executions) in a single file, each with CREATE TABLE IF NOT EXISTS.

There's only ever been one migration generated so far — the schema hasn't diverged from its initial version. If you add or change a table in schema.ts, drizzle-kit generate will produce 0001_<name>.sql next, not modify 0000_initial.sql.

npm scripts

Defined in packages/db/package.json:

ScriptCommandPurpose
db:generatedrizzle-kit generateDiffs schema.ts against the last migration and writes a new NNNN_*.sql file to drizzle/
db:migratetsx src/migrate.tsApplies all pending migrations against DATABASE_URL
db:seedtsx src/seed.tsSeeds an admin user + personas/skills/agents from configs/ YAML

Run them from packages/db:

cd packages/db
pnpm db:generate   # after editing schema.ts
pnpm db:migrate     # apply to DATABASE_URL
pnpm db:seed        # optional — bootstrap data

What db:migrate actually does

// packages/db/src/migrate.ts
const connectionString = process.env.DATABASE_URL;
if (!connectionString) {
  console.error('DATABASE_URL is required');
  process.exit(1);
}

const client = postgres(connectionString, { max: 1 });
const db = drizzle(client);

await migrate(db, { migrationsFolder: path.join(__dirname, '../drizzle') });

This uses drizzle-orm/postgres-js/migrator's migrate() function, which tracks applied migrations in a Drizzle-managed metadata table inside your target database (separate from the meta/_journal.json file, which just tracks what's been generated locally). It requires DATABASE_URL to be set — there is no default connection fallback in migrate.ts (unlike drizzle.config.ts, which does fall back for local dev tooling).

What db:seed does

// packages/db/src/seed.ts (abridged)
const existingUser = await db.select().from(users).where(eq(users.email, 'admin@anvio.local'));
if (existingUser.length === 0) {
  await db.insert(users).values({
    email: 'admin@anvio.local',
    passwordHash: await bcrypt.hash('admin123', 10),
    roles: ['admin', 'user'],
  });
}

The seed script is idempotent (checks for existing rows before inserting) and does three things in order:

  1. Creates admin@anvio.local / admin123 if it doesn't exist yet.
  2. Loads persona YAML files from configs/personas/, inserting any not already present by slug.
  3. Loads skill YAML files from configs/skills/, then agent YAML files from configs/agents/, wiring agent_skills join rows for each agent's declared skills.

The seeded admin password is the literal string admin123. This is a development convenience, not a production credential. Rotate it immediately in any real deployment, or remove the seed step from your production bootstrap process.

Running migrations end to end

# 1. Start Postgres (Level 3 setup)
docker run -d --name anvio-pg -e POSTGRES_USER=anvio -e POSTGRES_PASSWORD=anvio \
  -e POSTGRES_DB=anvio -p 5432:5432 postgres:16

# 2. Set the connection string
export DATABASE_URL=postgresql://anvio:anvio@localhost:5432/anvio

# 3. Apply migrations
cd packages/db && pnpm db:migrate

# 4. (Optional) seed baseline data
pnpm db:seed

See Environment Variables for the full DATABASE_URL reference and how it interacts with ANVIO_WORKSPACE and other Level 3 settings.

Generating a new migration

If you add a column or table to packages/db/src/schema.ts:

cd packages/db
pnpm db:generate   # writes drizzle/0001_<auto-name>.sql + updates meta/_journal.json
pnpm db:migrate    # applies it

Drizzle Kit diffs the TypeScript schema against its recorded snapshot in drizzle/meta/, not against the live database — always run db:generate after every schema edit, and commit the generated .sql file alongside the schema.ts change.

Edit on GitHub

Last updated on

On this page