DEV Community

Yu Hamada
Yu Hamada

Posted on

Understanding prisma codes for beginners in 100 seconds

Table of Contents

  1. What is prisma?
  2. The benefit of using prisma
  3. Prisma commands
  4. Conclusion

What is prisma?

Prisma is a tool that helps developers work with databases.
For database beginners, writing SQL to create database is much challenging. Prisma helps to solve this problem.
It supports a variety of databases, including SQL and NoSQL, and can query and retrieve databases via and API.

The benefit of using prisma

Low learning cost

Prisma allows us to manipulate the database with method-based commands without needing deep SQL knowledge.

Unified data model management

We can easily define and manage our data structure with a schema file which describes database tables, columns, and relationships, providing a clear way to handle our data models.

Supports Multiple Databases

We can use our preferred database, including PostgreSQL, MySQL, MongoDB and more. This means we can start with one database and switch to another without significant code changes, giving us the flexibility to choose the best database for our needs as our project evolves.

GUI Tool Included

Visualize and edit our data in database using Prisma Studio.

Prisma commands and workflow

1. Install prisma

To install prisma, we can choose how we install it. There are two following options.

1-1. Install prisma

npm install prisma
Enter fullscreen mode Exit fullscreen mode

This command installs prisma as a regular dependency in our project.

1-2. Install prisma development dependencies

npm install -D prisma  // or npm install prisma —save-dev
Enter fullscreen mode Exit fullscreen mode

This command installs prisma as a development dependency in our project. Use this if we only need prisma during development.

2. Initialize prisma in our project

npx prisma init
Enter fullscreen mode Exit fullscreen mode

This command sets up prisma in our project by creating a prisma directory with a schema.prisma file and a .env file for environment variables.

3. Define our schema

Edit the schema.prisma file to define our data models like this.

// This is Prisma schema file (schema.prisma)
// It defines our data model and the database configuration.

generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "postgresql" // Use "mysql", "mongodb", or other supported providers as needed
  url      = env("DATABASE_URL") // Environment variable storing our database connection URL
}

// Define the User model
model User {
  id        Int      @id @default(autoincrement()) // Primary key, auto-incrementing
  name      String
  email     String   @unique // Unique constraint
  posts     Post[]   // One-to-many relationship with Post model
}

// Define the Post model
model Post {
  id        Int      @id @default(autoincrement()) // Primary key, auto-incrementing
  title     String
  content   String?
  published Boolean  @default(false)
  authorId  Int
  author    User     @relation(fields: [authorId], references: [id]) // Foreign key relationship
}

Enter fullscreen mode Exit fullscreen mode

4. Generate prisma client

npx prisma generate
Enter fullscreen mode Exit fullscreen mode

This command generates the Prisma Client based on our schema.prisma file. Prisma Client makes it easy and safe to perform database operations in JavaScript or TypeScript code. We need to run this command whenever we make changes to your schema.

5. Create and Apply Migrations

npx prisma migrate dev --name <migration-name>
Enter fullscreen mode Exit fullscreen mode

This command creates a new migration file based on the changes in our schema and applies it to our database. Replace with a descriptive name for the migration.

6. Use Prisma Client in our code

import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

async function main() {
  const user = await prisma.user.create({
    data: { name: 'Alice', email: 'alice@example.com' },
  });
  console.log(user);
}

main()
  .catch((e) => console.error(e))
  .finally(async () => {
    await prisma.$disconnect();
  });

Enter fullscreen mode Exit fullscreen mode

7. Open Prisma Studio

npx prisma studio
Enter fullscreen mode Exit fullscreen mode

This command opens Prisma Studio, a web-based GUI to interact with our database. We can view, edit, and manage our data visually

Conclusion

For those who are new to JavaScript or just starting full-stack application development, learning SQL and designing a database from scratch can be a hard working. Prisma solves this problem for us. By using Prisma, we can focus on developing our applications.

Top comments (0)