Prisma

TypeScript ORM der naechsten Generation - typsichere Abfragen, Migrationen, Prisma Studio

TL;DR

Was: Ein Next-Generation ORM für Node.js und TypeScript.

Warum: Typsichere Abfragen, auto-generierter Client, visueller Datenbank-Browser, Migrationen.

Quick Start

Installieren:

npm install prisma --save-dev
npm install @prisma/client
npx prisma init

Schema definieren (prisma/schema.prisma):

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

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

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

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

Migrationen ausführen:

npx prisma migrate dev --name init

Cheatsheet

BefehlBeschreibung
npx prisma initPrisma initialisieren
npx prisma migrate devMigration erstellen
npx prisma generateClient generieren
npx prisma studioDatenbank-Browser öffnen
npx prisma db pushSchema pushen (ohne Migration)
npx prisma db pullSchema aus DB ziehen

Gotchas

CRUD-Operationen

import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()

// Create
const user = await prisma.user.create({
  data: { email: '[email protected]', name: 'John' }
})

// Read
const users = await prisma.user.findMany()
const user = await prisma.user.findUnique({ where: { id: 1 } })

// Update
await prisma.user.update({
  where: { id: 1 },
  data: { name: 'Johnny' }
})

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

Relationen

// Create with relation
await prisma.post.create({
  data: {
    title: 'Hello',
    author: { connect: { id: 1 } }
  }
})

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

Filterung

const users = await prisma.user.findMany({
  where: {
    email: { contains: '@example.com' },
    name: { not: null },
    posts: { some: { title: { startsWith: 'Hello' } } }
  },
  orderBy: { name: 'asc' },
  take: 10,
  skip: 0
})

Next Steps