"Mastering Prisma: A Comprehensive Guide on How to Use Prisma"
Getting Started with Prisma: A Comprehensive Guide
Prisma is an open-source database toolkit that provides a type-safe, ORM-like layer for your database. It's designed to make working with databases more enjoyable and productive. This guide will walk you through the process of using Prisma, from installation to querying your database.
Prerequisites
Before we dive in, ensure you have the following prerequisites installed:
- Node.js and npm (Node Package Manager)
- A database system (PostgreSQL, MySQL, SQLite, or MongoDB)
Installation
First, initialize a new Node.js project and install Prisma:
mkdir prisma-tutorial
cd prisma-tutorial
npm init -y
npm install prisma @prisma/client
Setting Up the Database
Next, set up your database. For this tutorial, we'll use SQLite. Create a new file named `.env` in your project root and add the following line:
DATABASE_URL="file:./dev.db"
Generating the Prisma Client
Prisma uses schema files to define your data model. Create a new file named `schema.prisma` in your project root and define a simple model:
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())
updatedAt DateTime @updatedAt
}
model Post {
id Int @id @default(autoincrement())
title String
content String
author User @relation(fields: [authorId], references: [id])
authorId Int
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
Now, run the following command to generate the Prisma Client:
npx prisma generate
Migrating the Database
Prisma uses migrations to keep your database schema in sync with your Prisma schema. Run the following commands to create and apply a migration:
npx prisma migrate dev --name init
npx prisma db push
Querying the Database
Now that your database is set up, you can start querying it using the Prisma Client. Here's how you can fetch all users:
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
async function main() {
const users = await prisma.user.findMany()
console.log(users)
}
main()
.catch((e) => {
throw e
})
.finally(async () => {
await prisma.$disconnect()
})
Creating, Updating, and Deleting Records
Prisma also allows you to create, update, and delete records. Here's how you can create a new user:
async function createUser(name: string, email: string) {
const user = await prisma.user.create({
data: {
name,
email,
},
})
console.log(user)
}
createUser('John Doe', 'john.doe@example.com')
.catch((e) => {
throw e
})
.finally(async () => {
await prisma.$disconnect()
})
You can find more examples and detailed documentation on the official Prisma website.