← Back to the Build Your Homepage series
💾
EPISODE 05
schema · migrate · client · type-safe queries

Prisma ORM

Stop writing raw SQL strings. Prisma gives you a schema file, automatic migrations, and a fully typed client — works with SQLite, PostgreSQL, and more.

PrismaORMmigrationtype-safe
Duration
About 2.5 hours
Level
📊 Intermediate
Prerequisite
🎯 db-04
OUTCOME
A type-safe data layer with auto-generated client and migrations

What you'll learn

  • 1Define a Prisma schema
  • 2Run prisma migrate to evolve the database
  • 3Use the auto-generated PrismaClient with full typing
  • 4Model 1-to-many and many-to-many relations

1. Setup

bash
npm install prisma @prisma/client
npx prisma init --datasource-provider sqlite
prisma
// prisma/schema.prisma
datasource db {
  provider = "sqlite"
  url      = env("DATABASE_URL")
}

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

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)
  authorId  Int
  author    User     @relation(fields: [authorId], references: [id])
}

2. Migrate

bash
npx prisma migrate dev --name init
# Generates SQL, applies it, regenerates the client

3. Use the Client

javascript
import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient();

// Create
const user = await prisma.user.create({
  data: {
    email: "alice@example.com",
    name: "Alice",
    posts: { create: { title: "Hello" } },
  },
  include: { posts: true },
});

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

// Update
await prisma.post.update({ where: { id: 1 }, data: { published: true } });

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

Every query result is fully typed — if you ask for { posts: true }, TypeScript knows the result includes a posts array.

4. Prisma Studio

bash
npx prisma studio   # GUI to browse and edit your data
Example code / lecture materials

All lecture materials and example code are openly available on GitHub.

View on GitHub ↗