Photo by Artem Artemov on Unsplash
Demystifying Prisma: A Beginner-Friendly Primer
ORM Tools for Better Development
Table of contents
👋Introduction
Prisma is a popular, open-source ORM(Object Relational Mapping) tool that gained popularity in the dev community for building scalable and efficient databases using JavaScript and TypeScript. Prisma allows you to write your database schema and use Prisma Client to interact with the database provided by you. Prisma can be used with multiple databases including, MySQL, PostgreSQL, SQLite, and MongoDB.
🔍Getting Started with Prisma
To get started with Prisma let's create a simple Node.js project by typing,
npm init -y
After that, we need to install Prisma CLI as a development dependency on our project. We can do that by typing,
npm install prisma --save-dev
Nest, we need to initialize Prisma to create a new Prisma project.
npx prisma init
Since we will be using PostgreSQL for this project, we can add a --datasource-provider
flag and create our Prisma project compatible with PostgreSQL as well.
npx prisma init --datasource-provider postgresql
This command will create a .env
file and a directory named prisma
with a file named schema.prisma
inside it. The .env
file includes our environmental variables and we can configure our DATABASE_URL
like this,
DATABASE_URL="postgresql://postgres:<password>@localhost:<postgres_port>/<database_name>?schema=public"
And we can define our database schema in the schema.prisma
file. A sample schema is shown below. You can find more details on what datatypes and what annotations you can use in schema.prisma
in the official documentation.
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
}
model User {
id Int @id @default(autoincrement())
name String
posts Post[]
}
model Post {
id Int @id @default(autoincrement())
title String
content String
author User @relation(fields: [authorId], references: [id])
authorId Int
}
In this schema, we define a data source that points to our PostgreSQL database, a generator that generates the code via Prisma Client, and User and Post Models which represent the tables of our database. The @id
directive is used to mark the primary key, and @default(autoincrement())
directive makes that an autoincrement primary key. The @relation
annotation denotes the relationship between the User and Post tables and it creates a foreign key constraint between the authorId
column in the Post table and the id
column in the User table.
After defining the schema, the Prisma Client code can be generated by running the following command.
npx prisma generate
🔧Usage
Now, we use Prisma to interact with our database using this generated code. For example, to create a user and post we can simply use the below code.
const { PrismaClient } = require('@prisma/client')
const prisma = new PrismaClient()
const createUserPost = () => {
const user= await prisma.user.create({
data: {
name: 'Rachel',
posts: {
create: {
title: 'Hello World!',
content: 'Hi!👋 I am Rachel',
},
},
},
})
console.log(`Created user with name: ${user.name}`)
const allUsers = await prisma.user.findMany({
include: { posts: true },
})
console.log(`All users: ${JSON.stringify(allUsers, null, 2)}`)
}
createUserPost()
.catch((e) => console.error(e))
.finally(() => prisma.$disconnect())
As you can see, Prisma helps developers interact with databases simply and intuitively as an ORM tool. Therefore using Prisma as your ORM tool for your next JavaScript or TypeScript project can increase your efficiency in development.