rembrembdocs

Prisma ORM is a next-generation Node.js and TypeScript ORM that provides type-safe database access, migrations, and a visual data editor.

Prisma ORM is open-source and consists of:

Prisma Client works with any Node.js or TypeScript backend, whether you're deploying to traditional servers, serverless functions, or microservices.

Traditional database tools force a tradeoff between productivity and control. Raw SQL gives full control but is error-prone and lacks type safety. Traditional ORMs improve productivity but abstract too much, leading to the object-relational impedance mismatch and performance pitfalls like the n+1 problem.

Prisma takes a different approach:

Prisma is a good fit if you:

Consider alternatives if you:

1. Define your schema

The Prisma schema defines your data models and database connection:

datasource db {
  provider = "postgresql"
}

generator client {
  provider = "prisma-client"
  output   = "./generated"
}

model User {
  id    Int     @id @default(autoincrement())
  email String  @unique
  name  String?
  posts Post[]
}

model Post {
  id        Int     @id @default(autoincrement())
  title     String
  published Boolean @default(false)
  author    User?   @relation(fields: [authorId], references: [id])
  authorId  Int?
}

2. Configure your connection

Create a prisma.config.ts file in your project root:

prisma.config.ts

import "dotenv/config";
import { defineConfig, env } from "prisma/config";

export default defineConfig({
  schema: "prisma/schema.prisma",
  migrations: {
    path: "prisma/migrations",
  },
  datasource: {
    url: env("DATABASE_URL"),
  },
});

3. Run migrations

Use Prisma Migrate to create and apply migrations:

Or introspect an existing database:

4. Query with Prisma Client

Generate and use the type-safe client:

import { PrismaClient } from "./generated/client";

const prisma = new PrismaClient();

// Find all users with their posts
const users = await prisma.user.findMany({
  include: { posts: true },
});

// Create a user with a post
const user = await prisma.user.create({
  data: {
    email: "alice@prisma.io",
    posts: {
      create: { title: "Hello World" },
    },
  },
});