Prisma Orm

March 7, 2025 (3w ago)

Prisma is an open-source ORM (Object Relational Mapper) for Node.js and TypeScript that makes database access easy and intuitive. It helps developers interact with databases in a type-safe manner, ensuring a smooth developer experience and improved productivity. Here’s an overview of what you need to know when using Prisma, based on their documentation:


1. Prisma Setup

Install Prisma CLI: To start using Prisma, first, you need to install the Prisma CLI.

npm install prisma --save-dev
npx prisma init

This creates two things:

  • A prisma folder with a schema.prisma file.
  • A .env file for environment variables, like database credentials.

Install Database Client: Prisma uses a database client to interact with your database. You can install it using:

npm install @prisma/client

2. Prisma Schema

The core of Prisma’s configuration is the schema.prisma file.

Datasource Block: This is where you configure the connection to your database (PostgreSQL, MySQL, SQLite, etc.).

datasource db {
  provider = "postgresql"  // or mysql, sqlite, etc.
  url      = env("DATABASE_URL") // Connection string stored in .env
}

Generator Block: This configures the Prisma client, which is used in your code to interact with the database.

generator client {
  provider = "prisma-client-js"
}

Models: This is where you define the tables in your database (also called models). Each model corresponds to a database table, and each model field corresponds to a table column.

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

3. Prisma Migrations

Generate Migration Files: After defining your schema, you need to generate and apply database migrations to reflect changes to the database structure.

npx prisma migrate dev --name init

This command will:

  • Generate the SQL migration files based on the schema changes.
  • Apply the migration to your database.
  • Update your Prisma Client to reflect the new schema.

Apply Pending Migrations: If you have already generated migrations but need to apply them to a different environment (e.g., production):

npx prisma migrate deploy

4. Using Prisma Client

Prisma Client is an auto-generated query builder that allows you to interact with your database in a type-safe manner.

Basic Operations:

  • Create:

    const newUser = await prisma.user.create({
      data: {
        email: "test@example.com",
        name: "John Doe",
      },
    });
  • Read:

    const user = await prisma.user.findUnique({
      where: { email: "test@example.com" },
    });
  • Update:

    const updatedUser = await prisma.user.update({
      where: { id: 1 },
      data: { name: "Jane Doe" },
    });
  • Delete:

    const deletedUser = await prisma.user.delete({
      where: { id: 1 },
    });
  • Filtering and Pagination:

    const users = await prisma.user.findMany({
      where: { name: { contains: "Doe" } },
      take: 10, // Pagination
      skip: 10, // Skip first 10 results
    });

5. Relations & Nested Queries

Prisma supports complex relationships between tables and allows nested queries.

One-to-Many Relationship (User-Posts Example): You can fetch related posts when fetching a user:

const userWithPosts = await prisma.user.findUnique({
  where: { id: 1 },
  include: { posts: true },
});

Many-to-One Relationship: In the Post model, the author field establishes a many-to-one relationship between Post and User:

const postWithAuthor = await prisma.post.findUnique({
  where: { id: 1 },
  include: { author: true },
});

Nested Writes (Creating Related Records): You can create related records in one operation:

const newPost = await prisma.post.create({
  data: {
    title: "New Post",
    content: "This is the content of the post.",
    author: {
      connect: { id: 1 }, // Connect to an existing user
    },
  },
});

6. Transactions

Prisma supports transactions, allowing you to group multiple operations into a single unit.

Using prisma.$transaction:

const [newUser, newPost] = await prisma.$transaction([
  prisma.user.create({
    data: { email: "john@example.com", name: "John Doe" },
  }),
  prisma.post.create({
    data: { title: "Hello World", content: "My first post", authorId: 1 },
  }),
]);

7. Prisma Studio

Prisma Studio is a GUI that helps you view and interact with your database.

Launch Prisma Studio:

npx prisma studio

This will open a browser window where you can view your data, edit records, and perform queries.


8. Environment Variables

Prisma relies on environment variables for database connection and other configuration.

DATABASE_URL Example: In the .env file:

DATABASE_URL="postgresql://user:password@localhost:5432/mydb?schema=public"

9. Deployment

Generate Client for Production: Before deploying, always ensure your Prisma Client is generated and up-to-date:

npx prisma generate

Database Migration in Production: Apply migrations to the production database:

npx prisma migrate deploy

10. Prisma Ecosystem Tools

  • Prisma Data Proxy: A serverless solution for scaling Prisma in serverless environments (like Vercel or AWS Lambda).
  • Prisma Insights: Collect and analyze performance metrics from your database queries.
  • Prisma's Prisma Cloud: An advanced feature for managing and scaling databases.

Prisma has a rich set of features that support modern workflows for database access. The above topics cover the basic and advanced concepts from Prisma's documentation. You can find more in-depth guides and references on the Prisma Docs.