CAPYSQUASH

Prisma Integration

Auto-detect Prisma migration patterns and optimize schema files while preserving data models, relations, and introspection metadata

Prisma Integration

Zero-configuration Prisma pattern recognition—CAPYSQUASH automatically detects and optimizes Prisma migrations while preserving your data model

Prisma is TypeScript's most popular ORM with type-safe database access and declarative schema management. CAPYSQUASH understands Prisma's migration format and optimizes your files while maintaining perfect compatibility with Prisma's introspection and generation tools.

Zero Configuration Required

CAPYSQUASH automatically detects Prisma projects and activates specialized optimization rules. Models, relations, enums, and indexes are all preserved during consolidation.

AUTO-DETECTION IN ACTION

[plugins] Scanning migrations for patterns...
[plugins] Detected: Prisma ORM migration format
[plugins] Found 15 model definitions
[plugins] Identified 23 relations
[plugins] Preserving enum types and custom scalars
[plugins] Ready for optimization with Prisma support

No configuration needed! CAPYSQUASH recognizes Prisma migrations automatically.

WHAT GETS DETECTED

Prisma-Specific Patterns

CAPYSQUASH automatically recognizes:

SCHEMA PATTERNS

  • ► Model definitions and fields
  • ► @id, @default, @unique attributes
  • ► @relation directives
  • ► Enum type definitions
  • ► Custom scalar types
  • ► Composite types

MIGRATION FILES

  • ► Timestamp-based naming
  • ► migration.sql format
  • ► Up/down migration pairs
  • ► Schema drift detection
  • ► Introspection metadata
  • ► Custom migration scripts

Relationship Patterns

Prisma's relationship patterns are preserved exactly:

RELATION TYPES RECOGNIZED

ONE-TO-ONE

@relation with unique foreign keys

ONE-TO-MANY

Foreign key references with arrays

MANY-TO-MANY

Implicit and explicit join tables

COMMON PRISMA MIGRATION PATTERNS

Pattern 1: Model Evolution

Before Optimization (6 migrations):

-- 20250101120000_init/migration.sql
CREATE TABLE "User" (
    "id" TEXT NOT NULL,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY ("id")
);

-- 20250102120000_add_email/migration.sql
ALTER TABLE "User" ADD COLUMN "email" TEXT NOT NULL;

-- 20250103120000_unique_email/migration.sql
CREATE UNIQUE INDEX "User_email_key" ON "User"("email");

-- 20250104120000_add_name/migration.sql
ALTER TABLE "User" ADD COLUMN "name" TEXT;

-- 20250105120000_add_updated_at/migration.sql
ALTER TABLE "User" ADD COLUMN "updatedAt" TIMESTAMP(3) NOT NULL;

-- 20250106120000_add_profile_image/migration.sql
ALTER TABLE "User" ADD COLUMN "image" TEXT;

After Optimization (1 migration):

-- 20250101120000_create_user_complete/migration.sql
CREATE TABLE "User" (
    "id" TEXT NOT NULL,
    "email" TEXT NOT NULL,
    "name" TEXT,
    "image" TEXT,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,
    PRIMARY KEY ("id")
);

CREATE UNIQUE INDEX "User_email_key" ON "User"("email");

6 files → 1 file (83% reduction) with perfect Prisma compatibility


Pattern 2: Relations and Join Tables

Before Optimization (10 migrations):

-- 001: Create Post table
CREATE TABLE "Post" (
    "id" TEXT NOT NULL,
    "title" TEXT NOT NULL,
    PRIMARY KEY ("id")
);

-- 002: Add authorId
ALTER TABLE "Post" ADD COLUMN "authorId" TEXT NOT NULL;

-- 003: Add foreign key
ALTER TABLE "Post"
ADD CONSTRAINT "Post_authorId_fkey"
FOREIGN KEY ("authorId") REFERENCES "User"("id");

-- 004: Create Category table
CREATE TABLE "Category" (
    "id" TEXT NOT NULL,
    "name" TEXT NOT NULL,
    PRIMARY KEY ("id")
);

-- 005-010: Create join table and indexes
CREATE TABLE "_CategoryToPost" (
    "A" TEXT NOT NULL,
    "B" TEXT NOT NULL
);
-- ... more join table setup

After Optimization (2 migrations):

-- 001_create_posts_categories_complete/migration.sql
CREATE TABLE "Post" (
    "id" TEXT NOT NULL,
    "title" TEXT NOT NULL,
    "authorId" TEXT NOT NULL,
    PRIMARY KEY ("id")
);

CREATE TABLE "Category" (
    "id" TEXT NOT NULL,
    "name" TEXT NOT NULL,
    PRIMARY KEY ("id")
);

CREATE TABLE "_CategoryToPost" (
    "A" TEXT NOT NULL REFERENCES "Category"("id"),
    "B" TEXT NOT NULL REFERENCES "Post"("id")
);

ALTER TABLE "Post"
ADD CONSTRAINT "Post_authorId_fkey"
FOREIGN KEY ("authorId") REFERENCES "User"("id");

CREATE UNIQUE INDEX "_CategoryToPost_AB_unique" ON "_CategoryToPost"("A", "B");
CREATE INDEX "_CategoryToPost_B_index" ON "_CategoryToPost"("B");

10 files → 2 files (80% reduction) with all relations preserved


OPTIMIZATION STRATEGIES

Prisma Field Directives

CAPYSQUASH preserves all Prisma-specific SQL patterns:

ATTRIBUTE PRESERVATION

// Prisma schema directives map to SQL patterns:

model User {
  id        String   @id @default(cuid())
  // → PRIMARY KEY with cuid() default function

  email     String   @unique
  // → UNIQUE constraint preserved

  posts     Post[]
  // → Foreign key relationship maintained

  createdAt DateTime @default(now())
  // → DEFAULT CURRENT_TIMESTAMP

  updatedAt DateTime @updatedAt
  // → Trigger for automatic updates (preserved)
}

☑ All Prisma directives converted and preserved accurately

Enum Type Handling

ENUM CONSOLIDATION

-- Multiple migrations defining same enum
CREATE TYPE "Role" AS ENUM ('USER', 'ADMIN');
ALTER TYPE "Role" ADD VALUE 'MODERATOR';
ALTER TYPE "Role" ADD VALUE 'GUEST';

-- Optimized to single definition
CREATE TYPE "Role" AS ENUM ('USER', 'ADMIN', 'MODERATOR', 'GUEST');

Index Optimization

INDEX CONSOLIDATION

-- Before: Scattered index creation
CREATE INDEX "User_email_idx" ON "User"("email");
-- ... 10 migrations later ...
CREATE INDEX "User_name_idx" ON "User"("name");
-- ... 5 migrations later ...
CREATE INDEX "User_createdAt_idx" ON "User"("createdAt");

-- After: Consolidated index creation
CREATE INDEX "User_email_idx" ON "User"("email");
CREATE INDEX "User_name_idx" ON "User"("name");
CREATE INDEX "User_createdAt_idx" ON "User"("createdAt");

PRISMA WORKFLOW INTEGRATION

Development Workflow

Develop with Prisma

# Make schema changes
nano prisma/schema.prisma

# Create migration
npx prisma migrate dev --name add_user_fields

# Generated: prisma/migrations/20250119_add_user_fields/migration.sql

Optimize with CAPYSQUASH

After accumulating many migrations:

# Option 1: Platform (Recommended)
# Upload prisma/migrations/ folder to CAPYSQUASH
# Click "Optimize" → Download optimized files

# Option 2: CLI
capysquash analyze prisma/migrations/
capysquash squash --safety=standard

Use Optimized Migrations

# For fresh environments
# Replace prisma/migrations/ with optimized files
# Run: npx prisma migrate deploy

# For existing: Keep originals, use optimized for new envs

BEST PRACTICES

Prisma Schema Design

☑ DO THIS

  • ► Use descriptive model names (PascalCase)
  • ► Add @map for custom table names
  • ► Use @relation for clarity
  • ► Include createdAt/updatedAt
  • ► Group related models together
  • ► Use enums for fixed values

☒ AVOID THIS

  • ► Don't skip migration names
  • ► Don't manually edit migrations
  • ► Don't delete old migrations
  • ► Don't mix Prisma with raw SQL
  • ► Don't ignore schema drift
  • ► Don't use generic field names

Migration Naming

DESCRIPTIVE NAMES

# Good migration names
npx prisma migrate dev --name add_user_email
npx prisma migrate dev --name create_post_model
npx prisma migrate dev --name add_category_relations

# Avoid
npx prisma migrate dev --name migration
npx prisma migrate dev --name update
npx prisma migrate dev --name fix

PRISMA + OTHER TOOLS

Prisma + Supabase

COMBINED POWER

Use Prisma ORM with Supabase database:

// schema.prisma
datasource db {
  provider = "postgresql"
  url      = env("SUPABASE_DATABASE_URL")
}

model User {
  id        String   @id @default(cuid())
  email     String   @unique
  // Supabase auth schema handled separately
  posts     Post[]
}

💡 CAPYSQUASH detects both Prisma and Supabase patterns!

Prisma + Next.js

FULL-STACK OPTIMIZATION

  • ► Optimize Prisma migrations with CAPYSQUASH
  • ► Faster cold starts with fewer migration files
  • ► Reduced deployment time in Vercel/Netlify
  • ► Clean git history with consolidated files

ADVANCED: CUSTOM MIGRATION SCRIPTS

Handling Data Transformations

DATA MIGRATION PATTERNS

-- Prisma generates schema changes
-- Add custom data transformations safely

-- Example: Migrating data between columns
DO $$
BEGIN
  -- Transform old_column to new_column
  UPDATE "User"
  SET "newEmail" = LOWER(TRIM("oldEmail"))
  WHERE "oldEmail" IS NOT NULL;
END $$;

-- CAPYSQUASH preserves these custom scripts

☑ Custom migration logic is preserved and consolidated safely


TROUBLESHOOTING

Common Issues

⚠️ SCHEMA DRIFT

Problem: Database doesn't match schema.prisma

Solution: Run introspection before optimization:

# Pull current database state
npx prisma db pull

# Generate Prisma client
npx prisma generate

# Create baseline migration
npx prisma migrate dev --name baseline

# Then optimize with CAPYSQUASH

⚠️ MIGRATION CONFLICTS

Problem: Team members have different migration histories

Solution: Synchronize before optimization:

# Reset to clean state (dev only!)
npx prisma migrate reset

# Apply all migrations
npx prisma migrate deploy

# Now optimize with CAPYSQUASH

REAL-WORLD EXAMPLE

SaaS Application with Prisma

Starting point: 67 Prisma migration files over 6 months

MIGRATION HISTORY

prisma/migrations/
├── 20240701_init/
├── 20240702_add_user_email/
├── 20240703_create_post_model/
├── 20240704_add_post_author/
├── 20240705_create_category/
...
├── 20250115_add_final_indexes/
(67 total migrations)

CAPYSQUASH Analysis:

  • Detected Prisma migration format
  • Found 12 model definitions
  • Identified 28 foreign key relations
  • Recognized 5 enum types
  • Preserved all @relation directives

OPTIMIZED STRUCTURE

optimized_migrations/
├── 20240701_create_core_models/        (merged 1-20)
├── 20240715_add_relations/             (merged 21-35)
├── 20240801_add_features/              (merged 36-50)
├── 20240901_add_enums/                 (merged 51-60)
└── 20241001_add_indexes/               (merged 61-67)
(5 total migrations)

Results:

  • 📊 67 files → 5 files (92.5% reduction)
  • ⏱️ Deployment time: 12 min → 1.5 min (87.5% faster)
  • Perfect Prisma compatibility
  • 🔒 All relations and enums preserved
  • 📦 Git repository 2.1 MB smaller

VERIFICATION

Test Optimized Migrations

Fresh Database Test

# Create test database
createdb test_optimized

# Apply optimized migrations
DATABASE_URL="postgresql://localhost/test_optimized" \
npx prisma migrate deploy

# Verify schema
npx prisma db push --skip-generate

Generate Client

# Generate Prisma Client from optimized schema
npx prisma generate

# Run type check
npm run type-check

Compare Schemas

# Compare with original
pg_dump original_db --schema-only > original.sql
pg_dump optimized_db --schema-only > optimized.sql
diff original.sql optimized.sql

# Should show no meaningful differences

NEXT STEPS


Questions about Prisma integration? Check our troubleshooting guide or reach out to support@capysquash.dev

How is this guide?

On this page