DEV Community

Cover image for Prisma ORM
allyn
allyn

Posted on

Prisma ORM

Introduction

Prisma ORM is an open-source ORM made up of 3 parts: Prisma Client, Prisma Migrate, and Prisma Studio. Prisma Client is an auto-generated, type-safe database client for Node.js and TypeScript. Prisma Migrate is a migration system, and Prisma Studio is an interface to view and manipulate data in the database. As an ORM, Prisma ORM supports databases like MongoDB, PostreSQL, MySQL, and many more. Upon installation of Prisma, you have access to the Prisma CLI, which is how you will mainly interact with your Prisma project. All Prisma projects start off with a schema before any of the main components are utilized, so let's start with the Prisma schema.

Prisma Schema

We know that Prisma is not a database, but an ORM, which is a tool to "translate" the data in the database to the developer. We also know that Prisma supports many different databases, which vary in syntax and structure/architecture. This is where the Prisma schema comes in.

Your Prisma schema, made up of models, reflects your database schema and acts as a proxy database. These schemas are written inside a schema.prisma file and contain a connection to the database via datasource and a generator that 'indicates that you want to generate a Prisma Client'. Data models take up the most space in the Prisma schema because they represent the tables or collections in databases, and they act as the base of the Prisma Client. Prisma gives you 2 workflows to create these models: Prisma Migrate and introspection.

Introspection

Introspection is defined as a "program's ability to examine the type or properties at run time". In the context of Prisma, introspection is when the program reads your database schema and generates your Prisma schema based on your database schema. Introspection is commonly used for an initial version of the Prisma schema, however, it can be used repeatedly, mainly when Prisma Migrate is not being used. If there are any changes to either schema, you can use introspection to ensure that both your database schema and Prisma schema are congruent. The workflow using introspection uses commands like prisma db pull and prisma db push that allow for said congruency in your project.

The workflow for introspection will follow, per Prisma's documentation.
Image description

Prisma Migrate

Prisma Migrate is used to synchronize your Prisma schema and database schema as either one evolves. One of the main uses of Prisma Migrate is to ensure updates to your Prisma schema are reflected in your database schema, and this is done by using the migrate commands from the Prisma CLI. The objective of the commands under the Prisma Migrate umbrella of the Prisma CLI is to apply and resolve migrations, or updates, to the Prisma schema. Also as a result of creating a migration, SQL migration files are generated which act as a documented history of changes to the schema.

Let's look at the prisma migrate dev command which will be one of the main prisma migrate commands.

The prisma migrate dev command will rerun the existing migration history on a "shadow database" to detect schema drift, which are changes and deletions of migration files or changes made directly to the database schema. The shadow database is a second, temporary database used to detect issues in your migrations. Shadow databases have a lifespan of however long the prisma migrate dev, meaning they are created every time the command is run and is deleted once the command is complete. Pending migrations are applied and thus generate a new migration file, documenting what changes were made to the database and warnings if applicable.

/*
  Warnings:

  - You are about to drop the column `artistId` on the `Album` table. All the data in the column will be lost.
  - You are about to drop the column `name` on the `Album` table. All the data in the column will be lost.
  - Added the required column `albumName` to the `Album` table without a default value. This is not possible if the table is not empty.
  - Added the required column `artistName` to the `Album` table without a default value. This is not possible if the table is not empty.

*/
-- DropForeignKey
ALTER TABLE `Album` DROP FOREIGN KEY `Album_artistId_fkey`;

-- AlterTable
ALTER TABLE `Album` DROP COLUMN `artistId`,
    DROP COLUMN `name`,
    ADD COLUMN `albumName` VARCHAR(191) NOT NULL,
    ADD COLUMN `artistName` VARCHAR(191) NOT NULL;

Enter fullscreen mode Exit fullscreen mode

The code block above is an example of what a migration file consists of when you make changes to your schema.

Once you're content with the state of your database and ready to add records to your database, you can move on to using Prisma Client.

Prisma Client

Prisma Client is your database client built on your Prisma schema and is how you make queries to your database. In order to use your Prisma Client, you must run the prisma generate command in your terminal. after you run prisma generate, you should see this in your terminal.

✔ Generated Prisma Client (v5.15.0) to ./node_modules/@prisma/client in 45ms

Start using Prisma Client in Node.js (See: https://pris.ly/d/client)

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

Enter fullscreen mode Exit fullscreen mode

You will receive a block of code you can copy and paste into whichever files you will be making queries to your database. This also shows a peek into how user-friendly Prisma is. The prisma generate command can also be used to solidify changes made to your database since this is how you'll interact with the data inside the database.

This will be put at the top of your file where you'll be making queries, with the rest of the import statements.

server/index.ts
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
Enter fullscreen mode Exit fullscreen mode

Once you import your Prisma Client, you can now make queries with the prisma variable. The syntax for making queries is as follows:

prisma.<model>.<queryMethod>({})
Enter fullscreen mode Exit fullscreen mode

According to Prisma's documentation, "all Prisma Client queries return plain old JavaScript objects", but these queries can be made asynchronous with async/await or using Promise methods like .then() and .catch().

Prisma Studio.

Prisma Studio is a "graphical user interface for you to view and edit your database" in the browser. It's important to note that Prisma Studio is not open-source.

Conclusion

Prisma ORM is a highly flexible and type-safe tool that makes interacting with your data in the database more transparent and streamlined for developers.

Top comments (0)