Prisma ORM Introduction - Type-Safe Database Operations

intermediate | 55 min read | 2024.12.22

What You’ll Learn in This Tutorial

✓ Prisma setup
✓ Schema definition
✓ Migrations
✓ CRUD operations
✓ Relations
✓ Transactions

Step 1: Setup

npm init -y
npm install prisma @prisma/client
npm install -D typescript ts-node @types/node
npx prisma init

Step 2: Schema Definition

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

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

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

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

Step 3: Migrations

# Create and run migration
npx prisma migrate dev --name init

# Generate Prisma Client
npx prisma generate

# View database
npx prisma studio

Step 4: CRUD Operations

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

const prisma = new PrismaClient();

async function main() {
  // Create
  const user = await prisma.user.create({
    data: {
      email: 'alice@example.com',
      name: 'Alice',
      posts: {
        create: { title: 'My first post' }
      }
    },
    include: { posts: true }
  });

  // Read
  const users = await prisma.user.findMany({
    include: { posts: true }
  });

  // Update
  const updated = await prisma.user.update({
    where: { id: 1 },
    data: { name: 'Alice Updated' }
  });

  // Delete
  await prisma.post.delete({
    where: { id: 1 }
  });
}

main()
  .catch(console.error)
  .finally(() => prisma.$disconnect());

Step 5: Advanced Queries

// Filtering
const posts = await prisma.post.findMany({
  where: {
    OR: [
      { title: { contains: 'Prisma' } },
      { content: { contains: 'database' } }
    ],
    published: true
  },
  orderBy: { createdAt: 'desc' },
  take: 10,
  skip: 0
});

// Transaction
const [user, post] = await prisma.$transaction([
  prisma.user.create({ data: { email: 'bob@example.com' } }),
  prisma.post.create({ data: { title: 'New Post', authorId: 1 } })
]);

Summary

Prisma is a type-safe ORM that provides a consistent development experience from schema definition to queries.

← Back to list