DA

database-schema

Prevents database errors by forcing the AI to read schema definitions, migrations, or models before generating SQL or ORM queries.

Install

mkdir -p .claude/skills/database-schema && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/5004" && unzip -o skill.zip -d .claude/skills/database-schema && rm skill.zip

Installs to .claude/skills/database-schema

Activation

This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.

Schema awareness - read before coding, type generation, prevent column errors
77 charsno explicit “when” trigger
Intermediate

Key capabilities

  • Reads schema files to verify column names and types
  • Generates type definitions for database models
  • Prevents runtime errors by validating schema before coding
  • Maintains a schema reference file for quick lookup

How it works

The skill mandates reading the schema file and completing a verification checklist before writing any code that interacts with the database.

Inputs & outputs

You give it
Database query or model modification
You get back
Verified schema-compliant code

When to use database-schema

  • Check column names before writing a SQL query
  • Verify data model fields before updating a service class
  • Generate type definitions based on existing schema files
  • Review migration history to identify current table states

About this skill

Database Schema Awareness Skill

Problem: Claude forgets schema details mid-session - wrong column names, missing fields, incorrect types. TDD catches this at runtime, but we can prevent it earlier.


Core Rule: Read Schema Before Writing Database Code

MANDATORY: Before writing ANY code that touches the database:

┌─────────────────────────────────────────────────────────────┐
│  1. READ the schema file (see locations below)              │
│  2. VERIFY columns/types you're about to use exist          │
│  3. REFERENCE schema in your response when writing queries  │
│  4. TYPE-CHECK using generated types (Drizzle/Prisma/etc)   │
└─────────────────────────────────────────────────────────────┘

If schema file doesn't exist → CREATE IT before proceeding.


Schema File Locations (By Stack)

StackSchema LocationType Generation
Drizzlesrc/db/schema.ts or drizzle/schema.tsBuilt-in TypeScript
Prismaprisma/schema.prismanpx prisma generate
Supabasesupabase/migrations/*.sql + typessupabase gen types typescript
SQLAlchemyapp/models/*.py or src/models.pyPydantic models
TypeORMsrc/entities/*.tsDecorators = types
Raw SQLschema.sql or migrations/Manual types required

Schema Reference File (Recommended)

Create _project_specs/schema-reference.md for quick lookup:

# Database Schema Reference

*Auto-generated or manually maintained. Claude: READ THIS before database work.*

## Tables

### users
| Column | Type | Nullable | Default | Notes |
|--------|------|----------|---------|-------|
| id | uuid | NO | gen_random_uuid() | PK |
| email | text | NO | - | Unique |
| name | text | YES | - | Display name |
| created_at | timestamptz | NO | now() | - |
| updated_at | timestamptz | NO | now() | - |

### orders
| Column | Type | Nullable | Default | Notes |
|--------|------|----------|---------|-------|
| id | uuid | NO | gen_random_uuid() | PK |
| user_id | uuid | NO | - | FK → users.id |
| status | text | NO | 'pending' | enum: pending/paid/shipped/delivered |
| total_cents | integer | NO | - | Amount in cents |
| created_at | timestamptz | NO | now() | - |

## Relationships
- users 1:N orders (user_id)

## Enums
- order_status: pending, paid, shipped, delivered

Pre-Code Checklist (Database Work)

Before writing any database code, Claude MUST:

### Schema Verification Checklist
- [ ] Read schema file: `[path to schema]`
- [ ] Columns I'm using exist: [list columns]
- [ ] Types match my code: [list type mappings]
- [ ] Relationships are correct: [list FKs]
- [ ] Nullable fields handled: [list nullable columns]

Example in practice:

### Schema Verification for TODO-042 (Add order history endpoint)

- [x] Read schema: `src/db/schema.ts`
- [x] Columns exist: orders.id, orders.user_id, orders.status, orders.total_cents, orders.created_at
- [x] Types: id=uuid→string, total_cents=integer→number, status=text→OrderStatus enum
- [x] Relationships: orders.user_id → users.id (many-to-one)
- [x] Nullable: none of these columns are nullable

Type Generation Commands

Drizzle (TypeScript)

// Schema defines types automatically
// src/db/schema.ts
import { pgTable, uuid, text, integer, timestamp } from 'drizzle-orm/pg-core';

export const users = pgTable('users', {
  id: uuid('id').primaryKey().defaultRandom(),
  email: text('email').notNull().unique(),
  name: text('name'),
  createdAt: timestamp('created_at').notNull().defaultNow(),
});

export const orders = pgTable('orders', {
  id: uuid('id').primaryKey().defaultRandom(),
  userId: uuid('user_id').notNull().references(() => users.id),
  status: text('status').notNull().default('pending'),
  totalCents: integer('total_cents').notNull(),
  createdAt: timestamp('created_at').notNull().defaultNow(),
});

// Inferred types - USE THESE
export type User = typeof users.$inferSelect;
export type NewUser = typeof users.$inferInsert;
export type Order = typeof orders.$inferSelect;
export type NewOrder = typeof orders.$inferInsert;

Prisma

// prisma/schema.prisma
model User {
  id        String   @id @default(uuid())
  email     String   @unique
  name      String?
  orders    Order[]
  createdAt DateTime @default(now()) @map("created_at")

  @@map("users")
}

model Order {
  id         String   @id @default(uuid())
  userId     String   @map("user_id")
  user       User     @relation(fields: [userId], references: [id])
  status     String   @default("pending")
  totalCents Int      @map("total_cents")
  createdAt  DateTime @default(now()) @map("created_at")

  @@map("orders")
}
# Generate types after schema changes
npx prisma generate

Supabase

# Generate TypeScript types from live database
supabase gen types typescript --local > src/types/database.ts

# Or from remote
supabase gen types typescript --project-id your-project-id > src/types/database.ts
// Use generated types
import { Database } from '@/types/database';

type User = Database['public']['Tables']['users']['Row'];
type NewUser = Database['public']['Tables']['users']['Insert'];
type Order = Database['public']['Tables']['orders']['Row'];

SQLAlchemy (Python)

# app/models/user.py
from sqlalchemy import Column, String, DateTime
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.sql import func
from app.db import Base
import uuid

class User(Base):
    __tablename__ = "users"

    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    email = Column(String, nullable=False, unique=True)
    name = Column(String, nullable=True)
    created_at = Column(DateTime(timezone=True), server_default=func.now())

    # Relationships
    orders = relationship("Order", back_populates="user")
# app/schemas/user.py - Pydantic for API validation
from pydantic import BaseModel, EmailStr
from uuid import UUID
from datetime import datetime

class UserBase(BaseModel):
    email: EmailStr
    name: str | None = None

class UserCreate(UserBase):
    pass

class User(UserBase):
    id: UUID
    created_at: datetime

    class Config:
        from_attributes = True

Schema-Aware TDD Workflow

Extend the standard TDD workflow for database work:

┌─────────────────────────────────────────────────────────────┐
│  0. SCHEMA: Read and verify schema before anything else     │
│     └─ Read schema file                                     │
│     └─ Complete Schema Verification Checklist               │
│     └─ Note any missing columns/tables needed               │
├─────────────────────────────────────────────────────────────┤
│  1. RED: Write tests that use correct column names          │
│     └─ Import generated types                               │
│     └─ Use type-safe queries in tests                       │
│     └─ Tests should fail on logic, NOT schema errors        │
├─────────────────────────────────────────────────────────────┤
│  2. GREEN: Implement with type-safe queries                 │
│     └─ Use ORM types, not raw strings                       │
│     └─ TypeScript/mypy catches column mismatches            │
├─────────────────────────────────────────────────────────────┤
│  3. VALIDATE: Type check catches schema drift               │
│     └─ tsc --noEmit / mypy catches wrong columns            │
│     └─ Tests validate runtime behavior                      │
└─────────────────────────────────────────────────────────────┘

Common Schema Mistakes (And How to Prevent)

MistakeExamplePrevention
Wrong column nameuser.userName vs user.nameRead schema, use generated types
Wrong typetotalCents as stringType generation catches this
Missing nullable checkuser.name! when nullableSchema shows nullable fields
Wrong FK relationshiporder.userId vs order.user_idCheck schema column names
Missing columnUsing user.avatar that doesn't existRead schema before coding
Wrong enum valuestatus: 'complete' vs 'completed'Document enums in schema reference

Type-Safe Query Examples

Drizzle (catches errors at compile time):

// ✅ Correct - uses schema-defined columns
const user = await db.select().from(users).where(eq(users.email, email));

// ❌ Wrong - TypeScript error: 'userName' doesn't exist
const user = await db.select().from(users).where(eq(users.userName, email));

Prisma (catches errors at compile time):

// ✅ Correct
const user = await prisma.user.findUnique({ where: { email } });

// ❌ Wrong - TypeScript error
const user = await prisma.user.findUnique({ where: { userName: email } });

Raw SQL (NO protection - avoid):

// ❌ Dangerous - no type checking, easy to get wrong
const result = await db.query('SELECT * FROM users WHERE user_name = $1', [email]);
// Should be 'email' not 'user_name' - won't catch until runtime

Migration Workflow

When schema changes are needed:

┌─────────────────────────────────────────────────────────────┐
│  1. Update schema file (Drizzle/Prisma/SQLAlchemy)          │
├─────────────────────────────────────────────────────────────┤
│  2. Generate migration                                       │
│     └─ Drizzle: npx drizzle-kit generate                    │
│     └─ Prisma: npx prisma migrate dev --name add_column     │
│     └─ Supabase: supabase migration new add_column          │
├─────────────────────────────────────────────────────────────┤
│  3. Regenerate types                                         │
│     └─ Prisma: npx prisma generate                          │
│     └─ Supabase: supabase gen types typescript              │
├─────────────────────────────────────────────────────────────┤
│  

---

*Content truncated.*

When not to use it

  • Projects without a defined database schema
  • Rapid prototyping where schema changes are constant

Prerequisites

Defined schema file (Drizzle, Prisma, Supabase, etc.)

Limitations

  • Requires manual maintenance of schema reference files
  • Dependent on the existence of schema files

How it compares

It forces a pre-coding verification step to catch schema drift, whereas standard development relies on runtime error detection.

Compared to similar skills

database-schema side by side with the closest alternatives in the catalog.

SkillInstallsUpdatedSafetyDifficulty
database-schema (this skill)14moReviewIntermediate
database-design66moReviewIntermediate
database-schema-designer66moNo flagsIntermediate
databases19moReviewIntermediate

Try saying

Example prompts that trigger this skill in your AI assistant.

You might also like

database-design

davila7

Database design principles and decision-making. Schema design, indexing strategy, ORM selection, serverless databases.

648

database-schema-designer

davila7

Design robust, scalable database schemas for SQL and NoSQL databases. Provides normalization guidelines, indexing strategies, migration patterns, constraint design, and performance optimization. Ensures data integrity, query performance, and maintainable data models.

628

databases

mrgoonie

Work with MongoDB (document database, BSON documents, aggregation pipelines, Atlas cloud) and PostgreSQL (relational database, SQL queries, psql CLI, pgAdmin). Use when designing database schemas, writing queries and aggregations, optimizing indexes for performance, performing database migrations, configuring replication and sharding, implementing backup and restore strategies, managing database users and permissions, analyzing query performance, or administering production databases.

16

database-patterns

jacexh

Use when designing database schemas, implementing repository patterns, writing optimized queries, managing migrations, or working with indexes and transactions for SQL/NoSQL databases.

00

prisma-database

slashwhy

Prisma schema conventions, migrations, seeding, and query patterns. Use when modifying database schema, creating migrations, or writing complex queries.

00

database-specialist

FelipeArruda

Use this skill when the task centers on database design or behavior: schema modeling, SQL, indexes, constraints, migrations, query tuning, data integrity, transactional logic, or tradeoffs across engines such as SQLite, PostgreSQL, and MySQL.

00

Search skills

Search the agent skills registry