Prisma ORM

VérifiéSûr

ORM type-safe pour opérations de base de données avec PostgreSQL. Remplace les requêtes SQL brutes par des modèles déclaratifs avec génération automatique de types.

Spar Skills Guide Bot
DeveloppementIntermédiaire
5002/06/2026
Claude Code
#prisma#orm#postgresql#type-safe#migrations

Recommandé pour

Notre avis

Cette compétence permet d'utiliser Prisma ORM pour des opérations de base de données typées avec PostgreSQL, en remplacement du SQL brut.

Points forts

  • Génération automatique des types TypeScript à partir du schéma.
  • Gestion déclarative des migrations de base de données.
  • Élimination des risques d'injection SQL via des requêtes typées.
  • Mapping automatique entre les objets et les tables sans code manuel.

Limites

  • Courbe d'apprentissage pour les développeurs non familiers avec les ORM.
  • Performances parfois inférieures au SQL brut pour des requêtes très complexes.
  • Dépendance à un outil externe supplémentaire dans la stack.
Quand l'utiliser

Utilisez cette compétence lorsque vous souhaitez bénéficier d'un accès typé et sécurisé à la base de données avec des migrations automatisées dans un projet Node.js/TypeScript.

Quand l'éviter

Évitez-la si vous avez besoin de performances maximales pour des requêtes SQL complexes ou si vous devez intégrer une base existante fortement dépendante du SQL brut.

Analyse de sécurité

Sûr
Score qualité90/100

The skill describes standard Prisma ORM setup and usage, including npm install and schema generation. No destructive, exfiltration, or obfuscated actions. The Bash tool is used for legitimate package management and CLI commands.

Aucun point d'attention détecté

Exemples

Set up Prisma with initial schema
Set up Prisma ORM in our Node.js project with PostgreSQL. Install dependencies, run prisma init, define a User model with id, email, and name fields, and generate the Prisma client.
Create a migration for an existing table
Create a Prisma schema that matches the existing products table in our PostgreSQL database, including the product_translations relationship. Then generate a migration to sync the schema.
Write a type-safe query with translation fallback
Write a Prisma query to fetch a product by ID and include its translations for a given language code, falling back to the default product name and description if no translation exists.

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
Skills similaires