Prisma ORM - Type-safe Database Operations

VerifiedSafe

Prisma ORM for type-safe database operations with PostgreSQL. Replace raw SQL queries with declarative schema modeling, automatic migrations, and type generation.

Sby Skills Guide Bot
DevelopmentIntermediate
406/2/2026
Claude CodeCursorWindsurfCopilotCodex
#prisma#orm#database#postgresql#type-safe

Recommended for

Our review

This skill enables using Prisma ORM for type-safe database operations with PostgreSQL, replacing raw SQL with declarative schema modeling and automatic type generation.

Strengths

  • Automatic TypeScript type generation from schema, eliminating manual row mapping.
  • Simplified migration management and relation modeling with declarative syntax.
  • Protection against SQL injection through a safe API.
  • Support for atomic transactions and advanced query patterns (include, where, etc.).

Limitations

  • May be less performant than hand-optimized SQL for very complex queries.
  • Requires a learning curve for developers accustomed to raw SQL.
  • Auto-migrations can be tricky in production and need careful review.
When to use it

Use this skill for any new database access functionality to leverage the safety and productivity of the ORM.

When not to use it

Avoid it for extremely complex queries or fine-grained performance optimizations where raw SQL would be more suitable.

Security analysis

Safe
Quality score90/100

The skill provides guidance on using Prisma ORM with safe installation commands and type-safe patterns. No destructive, exfiltration, or obfuscation instructions are present.

No concerns found

Examples

Define Prisma schema for a Product model
Create a Prisma schema for a Product model with fields: id (auto-increment), name, shortDescription (mapped to short_description), description, price (Decimal), salePrice (optional), imageUrl, inventory (default 0), categories (JSON), highlights (optional JSON), usage (optional), isNew (default false), isFeatured (default false), salesCount (default 0), and timestamps. Also add a related ProductTranslation model with a composite unique constraint on (productId, languageCode). Map models to 'products' and 'product_translations' tables respectively.
Fetch product with translation fallback
Using Prisma, write a function to fetch a product by ID including its translations filtered by a given language code. If no translation is found, fall back to the base product's name and description.
Run a transaction to create an order
Write a Prisma transaction that creates an order with multiple line items, decreases inventory for each product, and updates the sales count. Ensure atomicity so that if any step fails, all changes are rolled back.

name: prisma description: | Prisma ORM for type-safe database operations with PostgreSQL. Use when: Defining schemas, writing type-safe queries, creating migrations, modeling relations, or replacing raw SQL with ORM patterns. allowed-tools: Read, Edit, Write, Glob, Grep, Bash

Prisma Skill

Provides type-safe database operations as an alternative to raw SQL. This codebase currently uses the pg library with raw SQL queries. Prisma offers automatic type generation, declarative schema modeling, and migration management - eliminating the manual row mapping and SQL injection risks present in raw SQL approaches.

Quick Start

Install and Initialize

cd backend
npm install prisma @prisma/client
npx prisma init

Schema Definition

// prisma/schema.prisma
generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

model Product {
  id               Int                    @id @default(autoincrement())
  name             String
  shortDescription String                 @map("short_description")
  description      String
  price            Decimal                @db.Decimal(10, 2)
  salePrice        Decimal?               @map("sale_price") @db.Decimal(10, 2)
  imageUrl         String                 @map("image_url")
  inventory        Int                    @default(0)
  categories       Json
  highlights       Json?
  usage            String?
  isNew            Boolean                @default(false) @map("is_new")
  isFeatured       Boolean                @default(false) @map("is_featured")
  salesCount       Int                    @default(0) @map("sales_count")
  createdAt        DateTime               @default(now()) @map("created_at")
  updatedAt        DateTime               @updatedAt @map("updated_at")
  translations     ProductTranslation[]
  orderItems       OrderItem[]
  variants         ProductVariant[]

  @@map("products")
}

model ProductTranslation {
  id              Int      @id @default(autoincrement())
  productId       Int      @map("product_id")
  languageCode    String   @map("language_code") @db.VarChar(10)
  name            String   @db.VarChar(255)
  shortDescription String  @map("short_description")
  description     String
  highlights      Json?
  usage           String?
  slug            String?  @db.VarChar(255)
  createdAt       DateTime @default(now()) @map("created_at")
  updatedAt       DateTime @updatedAt @map("updated_at")
  product         Product  @relation(fields: [productId], references: [id], onDelete: Cascade)
  language        Language @relation(fields: [languageCode], references: [code], onDelete: Cascade)

  @@unique([productId, languageCode])
  @@map("product_translations")
}

Client Usage

// backend/src/db/prisma.ts
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient({
  log: process.env.NODE_ENV === 'development' ? ['query', 'warn', 'error'] : ['error'],
});

export { prisma };

Key Concepts

| Concept | Usage | Example | |---------|-------|---------| | @map | Map field to snake_case column | @map("created_at") | | @@map | Map model to table name | @@map("products") | | Relations | Define FK relationships | product Product @relation(...) | | @db.Decimal | Specify PostgreSQL types | @db.Decimal(10, 2) | | @@unique | Composite unique constraints | @@unique([productId, languageCode]) | | Transactions | Atomic operations | prisma.$transaction([...]) |

Common Patterns

Fetching with Translation Fallback

When: Getting localized content with English fallback

const product = await prisma.product.findUnique({
  where: { id: productId },
  include: {
    translations: {
      where: { languageCode: lang },
    },
  },
});

// Apply translation or fallback to base
const name = product.translations[0]?.name ?? product.name;

Transactions for Orders

When: Creating orders with inventory updates

await prisma.$transaction(async (tx) => {
  const order = await tx.order.create({ data: orderData });
  
  for (const item of items) {
    await tx.orderItem.create({
      data: { orderId: order.id, ...item },
    });
    await tx.product.update({
      where: { id: item.productId },
      data: { inventory: { decrement: item.quantity } },
    });
  }
  
  return order;
});

See Also

  • patterns - Query patterns and model design
  • workflows - Migrations and schema management

Related Skills

  • See the postgresql skill for raw SQL patterns and PostgreSQL-specific features
  • See the typescript skill for type inference patterns with Prisma
  • See the zod skill for runtime validation of Prisma inputs
Related skills