Prisma- Next generation ORM

Gnanabillian
YavarTechWorks
Published in
7 min readJul 25, 2022

Hi friends, In this post, you’ll learn how to get started with Prisma. It covers data modeling and migrations.

what is Prisma?

Prisma is a next-generation ORM that makes working with databases easy for application developers.

  • Object-relational mapper
  • A way to interact with our database
  • Completely type safe

features the following tools:

  • Prisma Client: Auto-generated and type-safe database client for use in your application.
  • Prisma Migrate: Migration system
  • Prisma Studio: GUI to view and edit data in your database

Prisma schema:

Every project that uses a tool from the Prisma toolkit starts with a Prisma schema file. The Prisma schema allows developers to define their application models in a data modeling language. It also contains the connection to a database and defines a generator.

The Prisma schema has powerful data modeling features. For example, it allows you to define the “Prisma-level” relation field which will make it easier to work with relations in Prisma client API.

In this schema, you configure three things:

  • Data source: Specifies your database connection (via an environment variable)
  • Generator: Indicates that you want to generate Prisma Client
  • Data model: Defines your application models

Prerequisites:

This blog is going to show you the following things:

  • The Prisma schema file
  • Installing Prisma
  • Migrating our database using Prisma migrate
  • Seeding an initial database with an initial value
  • Seeding values with Prisma client
  • Visualizing data UI using Prisma studio

And because of this, it is important that you’ve some basic knowledge about Node.js and npm.

Prisma tutorial: Getting started

First, we need to install prisma as a dev dependency. After initializing the project directory with npm, install prisma as a developer dependency by typing the following command into the terminal:

$ npm install -D prisma

Go ahead and type the following in the terminal to initialize a prisma project in the directory:

$ npx prisma init

By typing npx prisma init, a new schema.prisma the file is created inside the prisma directory.

Prisma schema file

Now, you should see a folder named prisma/ created in the parent directory and inside the prisma directory, you’ll find a file called schema.prisma.

Go ahead and open it. It should have the following contents:

The schema.prisma file contains the data model as well as the configuration options. Let’s break it down:

The data source block

The datasource the block is used to specify the connection to the database. We set the provider field to postgresql. PostgreSQL is a powerful, open source object-relational database system that uses and extends the SQL language combined with many features that safely store and scale the most complicated data workloads.

The url the field contains the connection string to our database. In our case, the database URL will be declared in .envfile with the name DATABASE_ URL .

DATABASE_URL=”postgresql://madhusha:1234@localhost:5432/mydb?schema=public”

The generator block

By adding the generator block, we specify that we want to generate Prisma’s database client.

The client is generated by running the prisma generate command and will be located in node_modules/@prisma. It can be imported into our code as import { PrismaClient } from '@prisma/client'.

The model block

Here, we define the User data model using the model block. Models represent the entities of our application domain. On a technical level, a model maps to the underlying structures of the data source.

For example, in relational databases — such as SQL, SQLite, and PostgreSQL — a model maps to a table, whereas in non-relational databases — like MongoDB — it would map to a collection. We have four attributes inside our User model id, email,name, and mobile.

  1. The id field is a primary key of type Int with a default value of autoIncrement(). To determine which field of a model is the ID field, we can annotate it with the @id attribute. In relational databases like SQL, SQLite, and PostgreSQL, a unique ID corresponds to a column with a primary key constraint
  2. The email and name field is of type String
  3. The Book field is of type Book, which contains a type modifier [] that makes the field a list so we can store a list of todos in our User data model

The Book data model

Finally, we define the Book data model. The Book data model contains the following fields:

  1. id: this is, again, a primary key of type Int with a default value of autoIncrement()
  2. name: this is a type of String
  3. author: this is a type of String
  4. description: this is a type of String
  5. amount: this is a type of Decimal
  6. is_read: this is a type of Boolean
  7. created_by: this is a type of Int
  8. createdAt: this is a type of DateTimewith a default value of now()
  9. updatedAt: this is a type of DateTimewith a @updatedAt
  10. deleted: this is a type of DateTime

Installing Prisma/Client

Now add Prisma Client to the project by installing @prisma/client using npm as follows:

$ npm install @prisma/client

Go ahead and generate Prisma Client by typing the following command:

$ npx prisma generate

The generated client will be located in node_modules/@prisma, thus allowing us to import Prisma Client into our code as import { PrismaClient } from '@prisma/client'.

Migrating our database using Prisma migrate

Now let’s migrate our database to create empty tables. The following command will create and apply migrations.

$ npx prisma migrate dev

Running this command will ask you to name the migration. Giving the migration a name will generate the SQLite database.

How do I seed a Prisma database with initial values?

Go ahead and create a file named seed.js inside of a prisma/ folder:

$ touch prisma/seed.js

Now, open up a seed.js file and start by importing Prisma Client:

First, we’ve imported PrismaClient from the @prisma/client package, which was generated from our schema.prisma file when we ran npx prisma generate. Next, we create a constant called prisma, which is an instance of PrismaClient.

We have an async function called main. When calling the main function, if any error occurs, the catch block will catch the errors and will display them with the console.error, and whether an error happens or not after running the main function, the code block inside the finally will run.

The finally() function itself contains a async callback, which disconnects from the Prisma database so as to not keep it running as we are just seeding the database.

Now open up main() function and paste the following:

If you type the above code, you will find autocompletion support thanks to TypeScript. The above code will create a user with a name John , email john@gmail.com and a mobile9988774455.

Go ahead and run the seed.js file by typing the following in the terminal:

$ node prisma/seed

Now, below that, let’s create Book, fifty shades of grey, by the user idJohn

Go ahead and run the seed.js file by typing the following in the terminal:

$ node prisma/seed

Visualizing data using the Prisma studio

Prisma Studio allows us to visualize data using a beautiful Admin UI. It also allows us to perform CRUD operations on our data. To open up Prisma Studio, type the following in the terminal:

$ npx prisma studio

Prisma studio will open on http://localhost:5555 and you’ll be able to see the Admin UI.

Using Admin UI, we can quickly sort the data, filter it, and even perform queries without having to write them in our script file.

The following are some screenshots of the Admin UI:

User table view

Book table view

Conclusion

In this article, we learned the basics of Prisma. It has three major tools, namely: Prisma Client, Prisma Migrate, and Prisma Studio.

We used Prisma Client to seed values into our database and query data from it. We also used Prisma Migrate to create the initial migrations. Finally, we used Prisma Studio to visualize our data using a beautiful Admin UI.

--

--

Gnanabillian
YavarTechWorks

Software Engineer | Node.js | Javascript | Typescript | Fastify | NestJS | Sequelize | Prisma | PostgreSQL, I love open source and startups.