With so many ORMs available, deciding which one to use for your JavaScript-based project can be difficult. You have a ton of options depending on your objectives or stack, including libraries like TypeORM, Sequelize, and Mongoose.
In this article, we'll be delving deeply into a different choice: one that provides a ton of fascinating features, a distinctive "ORM" experience, and a vibrant, committed team of developers supporting and working on it. It's called Prisma.
What is Prisma?
Prisma is a modern, open-source tool that enables developers to build scalable, high-performance data access layers with ease. Whether you're building a web or mobile application, Prisma has everything you need to connect to your databases and manage your data with confidence. It consists of the following parts:
Prisma Client: Auto-generated and type-safe query builder for Node.js & TypeScript
Prisma Migrate: Migration system
Prisma Studio: GUI to view and edit data in your database.
How does Prisma work?
Prisma makes use of a Prisma Schema File, which allows developers to define their application models in an intuitive data modeling language. It also contains the connection to a database and defines a generator.
// Relational Database
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
}
Let's briefly discuss on datasource db and Generator in the schema file
In Prisma, a "data source" refers to the database that you are connecting to in order to manage your data. This data source could be a relational database such as MySQL or PostgreSQL, or it could be a NoSQL database such as MongoDB or Cassandra. Prisma provides a unified API for connecting to and querying your data source, regardless of the type of database you are using.
The generator in Prisma is a tool that generates code based on your database schema. In other words, it creates code that corresponds to the structure of your database, including the tables, columns, and relationships between tables.
Auto-formatting
Prisma provides a dedicated extension that assists with code highlighting and code formatting automatically if you are using an IDE like vscode. Use your IDE's extension pane shortcut or the keyboard shortcut "ctrl+shift+X" to get there.
If you install this extension, your Prisma files should automatically format; otherwise, just complete the next step to set up auto-formatting.
File >> Preferences >> edit settings has JSON (top right corner)
// Copy and paste it into your settings.json
"[prisma]": {
"editor.defaultFormatter": "Prisma.prisma",
"editor.formatOnSave": true
},
With this change, Prisma will automatically format your code upon saving, which I find to be really helpful. And don't worry, Prisma has a built-in formatter if you are unable to do all of this.
npx prisma format
Jumping In
To get started with Prisma, the first step is to install it. Prisma provides a CLI that makes it easy to install and manage the various components of the platform. The installation process is straightforward and only takes a few minutes to complete. Simply run the following command in your terminal:
npm install -g prisma
// This will install prisma globally on your machine
Initialize
Once you have installed Prisma globally on your machine, you can then initialize it inside your project with the following command in your terminal:
npx prisma init
This command will create a schema folder in your project directory and a `.env
` file, which will be used to store the database URL. The schema folder will house the database structure or model, which is used to define the desired state of the database.
It is important to note that the `npx prisma init
` command sets up the necessary infrastructure for using Prisma in your project, including the creation of the schema folder and the .env file. By defining the database structure in the schema folder, you can effectively communicate the desired state of the database to the Prisma CLI, which can then be used to generate the necessary code for accessing and manipulating the database.
Migration
The migration system in Prisma is a key feature that allows you to make changes to your database schema over time. Prisma migrations ensure that your database stays in sync with your application's data model, making it easy to add, modify, or delete tables, columns, and relationships. For example, you can use the following code to create a table in your database:
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model User {
id String @id @default(uuid())
email String @unique
name String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
npx migrate dev --name init
The command above is used to create a new migration in your Prisma project. The migrate
sub-command is used to manage migrations for your project, and the dev
option specifies that the migration should be created in the development environment. The --name
option is used to specify a custom name for the migration, in this case init
.
When you run this command, Prisma will create a new migration in your project's migrations
directory with the specified name. This migration will contain a set of instructions for updating your database schema. You can then use the Prisma CLI to apply the migration to your database by using the npx prisma migrate up
command.
npx prisma migrate up
npx prisma migrate up
is a specific sub-command of the migrate
command. It is used to apply pending migrations to your database. When you run npx prisma migrate up
, Prisma will look at the migrations that have been created for your project and apply any that have not yet been executed in your database. This will update your database schema to reflect the changes you have made in your migrations
Prisma Client
The Prisma Client is an important component of the Prisma ecosystem and plays a critical role in the interaction between your application and database. It is a client library that provides a type-safe and convenient API for querying and managing your data in Node.js and TypeScript applications.
To install the Prisma client, you can run the following commands in your terminal:
npm i --save-dev prisma@latest
npm i @prisma/client@latest
The Prisma client is generated based on the data model defined in your Prisma schema and is always in sync with the structure of your database. This guarantees type safety and prevent runtime errors, making it easier to write and maintain your code.
Using the Prisma client in your application is straightforward. To get started, you can create an instance of the PrismaClient
class and use its methods to interact with your database.
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
async function getAllUsers() {
const allUsers = await prisma.user.findMany();
return allUsers;
}
getAllUsers().catch(err => console.error(err));
With a few lines of code, you can retrieve all the records from the User
table in your database and log the results.
The Prisma Client also provides a number of other methods for querying, updating, and managing your data, including methods for creating, updating, and deleting records and for working with transactions.
Prisma Studio
Prisma Studio is a graphical user interface (GUI) tool that provides a convenient and intuitive way to interact with your Prisma-powered database. With Prisma Studio, you can view and manage your data, run queries, and perform other database-related tasks, all from a user-friendly web interface.
npx prisma studio
This will start a local instance of Prisma Studio, which you can access by navigating to http://localhost:5555
in your web browser.
One of the key features of Prisma Studio is its visual data explorer, which provides an intuitive interface for querying and manipulating your data. You can easily view your data in a tabular format, run queries, and perform other data-related tasks, all from a single interface.
Relationships
Relationships are an essential aspect of most databases, and Prisma makes it easy to define and manage relationships between tables in your database. Relationships in Prisma can be one-to-one, one-to-many, or many-to-many, and are defined using the @relation
directive in your Prisma schema.
Let's update our schema a bit in other to grasp the concept around relationships and see how Prisma handles them
model User {
id String @id @default(uuid())
email String @unique
name String
posts Post[]
userPreferences userPreference?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
model Post {
id String @id @default(uuid())
title String
content String
authorId String
author User @relation(fields: [authorId], references: [id])
tags Tags[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
model Tags {
id String @id @default(uuid())
tags String
posts Post[]
}
model userPreference {
id String @id @default(uuid())
emailUpdate Boolean
userId String @unique
user User @relation(fields: [userId], references: [id])
}
I updated the schema with 3 extra models Post, Tags, UserPreference
User
and Post
: One-to-Many
The User
model has a one-to-many relationship with the Post
model. This relationship is established through the posts
field in the User
model and the author
field in the Post
model.
The posts
field in the User
model is an array of Post
records, representing the posts created by that user. On the other hand, the author
field in the Post
model is a single User
record representing the author of the post.
User
and UserPreference
: One-to-One
The User
model also has a one-to-one relationship with the UserPreference
model. This relationship is established through the userPreferences
field in the User
model and the user
field in the UserPreference
model.
The userPreferences
field in the User
model is a single UserPreference
record representing the preferences of the user. The user
field in the UserPreference
model is a single User
record representing the user that the preferences belong to.
Post
and Tags
: Many-to-Many
Finally, the Post
model has a many-to-many relationship with the Tags
model. This relationship is established through the tags
field in the Post
model and the posts
field in the Tags
model.
The tags
field in the Post
model is an array of Tags
records representing the tags associated with the post. The posts
field in the Tags
model is an array of Post
records representing the posts associated with the tag.
Wrapping Up
Prisma opens up a wealth of opportunities for creating and maintaining efficient and effective data structures. With its rich set of features and intuitive syntax, Prisma makes it easier than ever to connect, store, and manipulate data in a way that's both powerful and straightforward. If you want to dig deeper and expand on what we talked about, check out the Prisma Documentation.
Top comments (3)
Ok cool I liked this presentation! 😎
Glad you like it :)
Github repo can be found here