Back to blog overview

December 2, 2022

How to use Redwood with Prisma

Natalia Diaz

&

&

Software Engineer
Chula Vista, CA

# What is Prisma? How to use Redwood with Prisma.

Have you been thinking about how your application is accessing its data? ORM's, or object relational mapping is a software technique to help a developer query and shape a database. An ORM is a bridge between a relational database and an object-oriented programming language. Benefits of using ORM's include: CRUD, query, and migration operations are easily accessible, a quickened development process, and simplified code.

Prisma is a Node.js and TypeScript ORM simplifying interactions with your application’s database. Prisma integrates with frameworks making the development process hassle free to update, migrate, and view a GUI of your database. Compared to other popular ORM’s like Rails Active Record, Prisma is made up of new features designed to ease the development process.

## Why Prisma?

Prisma is an ORM or object relational mapping system simplifying the database modeling, migrations, and data associations. There are three main components to Prisma: the client, migrations, and studio. These components of Prisma are designed to make the layered interaction with your database straightforward.

### Prisma Client

The Prisma client is a query builder that connects to your API. The client auto-generates when a change to your Prisma data-model occurs, keeping up to date on data structures and API operations.

### Prisma Migration

The Prisma migration is a database schema migration tool that aligns your database schema with your Prisma schema. The migrations are documented, accessible to reference the changes.

### Prisma Studio

The Prisma studio is a GUI for your database. In the studio you can view and edit data set in your database. All models you create will be available to interact with.

## Adding Prisma to your Project

To start Prisma in your full-stack project you’ll first need Node.js installed, the project to be a Node.js project with a package.json, and for instance, a PostgreSQL database server running. Prisma is compatible with an array of databases such as: SQLite, PostgreSQL, MySQL, MongoDB, CockroachDB, and Supabase.

Run the following commands to: Add Prisma CLI, Prefix your Prisma CLI, Set Prisma directory, schema file, and create the .env file for defining environment variables
```bash
$ npm install prisma --save-dev
$ npx prisma
$ npx prisma init
```
Now to connect your database to Prisma in the prisma/schema.prisma file your data source will reflect the following to connect the database url:

```javascript
datasource db { provider = "postgresql" url = env("DATABASE_URL") }
```

Secondly in your .env file you’ll define the database URL like the following:

```text
DATABASE_URL="postgresql://foobar:example@localhost:5432/mydb?schema=public"

```

To update your data model in your Prisma schema run the following command:

```bash
$ npx prisma db pull
```

Now it is time to run the Prisma migrations into your database. Create a migrations directory and file with the following:

```bash
$ mkdir -p prisma/migrations/init
$ npx prisma migrate diff --from-empty --to-schema-datamodel prisma/schema.prisma --script > prisma/migrations/init/migration.sql

```

Running the setup migrations:

```bash
$ npx prisma migrate resolve --applied init
```

Now we'll look at installing the Prisma client. To install run:
```bash
$ npm install @prisma/client
```

You want to run migrations after each change to the schema, to run migrations run the following:

```bash
$ npx prisma migrate dev
```

Huzza, Prisma is integrated into your project! Enjoy what Prisma has to offer.

## Prisma in RedwoodJS

Thinking about Prisma and explaining the process would be easiest in the context of a real application. Starting a project in [RedwoodJS](https://redwoodjs.com/), Prisma is integrated off the bat. No commands are needed to add the ORM. In the application, Prisma is integrating all pieces mentioned earlier: the client, migrations, and studio. In your new project to start structuring the database, you’ll first look at the file api/db/schema.prisma. This schema will be prefilled with an example model. Replace the example with the model and elements you’d like to include.

```javascript
model Books {
  id     String @id default(uuid()) @db.Uuid
  name   String
}

```

After completing, to migrate to your database simply run the following command:

```bash
yarn rw prisma migrate dev

```

You will be prompted to name the migration. This will create a new folder under api/db/migrations. This folder will hold each migration in ascending order with the timestamp and migration name. The migrations folder tracks any modification made, and if needed is a way to reset the schema at a particular point.

It is that simple to set up your database.

### Working with the Data

Next, we will go through [CRUD](https://www.educative.io/blog/crud-operations) operations. Redwood helps to generate the necessary files to start this process. Simply use the following command:

```bash
yarn rw g scaffold book
```

This command accomplishes two goals: one, it builds our api files to establish CRUD operations and two, it creates a layout and several pages on the web portion to build out the application’s interface.

In your Redwood application under api/src/services/books/books.ts is where we will set up the commands.

```javascript
export const books = () => {
 return db.book.findMany()
}

export const book = ({ id }) => {
 return db.book.findUnique({
   where: { id },
 })
}

export const createBook = ({ input }) => {
 return db.book.create({
   data: input,
 })
}

export const updateBook = ({ id, input }) => {
 return db.book.update({
   data: input,
   where: { id },
 })
}

export const deleteBook = ({ id }) => {
 return db.book.delete({
   where: { id },
 })
}

```

In these commands we are establishing the function, setting a parameter, querying to the intended model, and operating on that query in some way. In the query, by default the model name will be lowercase followed by the [CRUD operation](https://www.prisma.io/docs/concepts/components/prisma-schema/data-model#models-in-prisma-client) needed to complete that command.

### Visualizing the Data

Now CRUD actions can be operated on data. When you have populated your database with new information you can access the studio to view and edit the data. To access, simply run the following command:

```bash
yarn rw prisma studio
```

A new browser will open on [http://localhost:5555/](http://localhost:5555/)

All models made within the schema will be accessible. When a model is chosen, a table will be visible headed by its model’s elements. To present specific information, use the filter option or fields option to readjust the data shown. In the studio, you are able to create a new entry by adding a record, read all existing data laid out, update a section directly in the data row and save the change, and checkmark and confirm to delete an entry.


Explore the studio, and enjoy seeing your database.

## How does Prisma Compare?

A way to think of how intuitive and streamlined Prisma is, is by comparing it to another popularly used ORM. Active Record is the ORM for Rails applications. Active Record has core abilities in common with Prisma. The purpose of the ORM is to represent the models and data within them, show associations between models, and perform database operations.

The first difference to go over is the naming conventions used. Something simple, but when referencing through the application it can become complicated. In rails, when searching in your class names, the database table will pluralize them. When a class is composed of two or more words the model class is referenced using pascal case, whereas the database table reference will be using snake case. Prisma references the models in the application and database how it was established in the schema, typically using pascal case. Moving from one aspect of the application or database, the model/table is referenced in the same manner.

Another difference is the visual representation of your database. In rails, to access your database, the queries will be through your Ruby terminal. In your ruby terminal, you can interact with your database, going through the CRUD operations. Some operations will look like the following:

Create:  
```ruby
# book = Book.create(name: "Harry Potter", email: "books@bookstore.com")
```

Read:

```ruby
# bookquery = Book.find_by(name: 'Harry Potter')
```

Update:

``` ruby
# bookquery = Book.find_by(name: 'Harry Potter')
# bookquery.name = 'Potter'
# bookquery.save

```

Delete

```ruby
# bookquery = Book.find_by(name: 'Potter')
# bookquery.destroy
```

Going through these CRUD operations is lengthy in Active Record in comparison to Prisma Studio. In our work earlier navigating to the Prisma Studio required one command, and viewing and updating the data were mere clicks away.

### Finale

As a recent coding boot-camp grad, my first interaction with an ORM was Rails Active Record. At that time the whole development process was new to me. I learned how to access my database and navigate through the CRUD operations to complete the goals for myself in my application. I thought overall working in Active Record was straightforward. After that, I was exposed to RedwoodJS and therefore Prisma. I found my interactions with the database were smoother. After learning the make-ups of Prisma, what really won me over was the GUI for my database and migrations tracks.

All in all, both Prisma and Active Record are high-performance systems and aid in the development process. However, the ease and integration Prisma offers has an advantage.

Photo by Michael Dziedzic on Unsplash

Let's Chat

Are you ready to build something brilliant? We're ready to help.

Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
RedwoodJS Logo
RedwoodJS
Conference

conference
for builders

Grants Pass, Oregon • September 26 - 29, 2023
View All