A Beginner's Guide to Setting Up Prisma with PostgreSQL ๐


Prisma Setup and Configuration ๐ ๏ธ
Initialize Prisma
Run this command:
npx prisma init
This creates a new folder called prisma
in your project's root directory. Inside this folder, youโll find:
schema.prisma
: This is where your database schema lives.- All your models (tables) will be defined here. โ๏ธ
Sample User Model ๐
Here's an example of how to define a user table:
generator client {
provider = "prisma-client-js"
output = "../src/generated/prisma"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model User {
id String @id @default(uuid())
name String?
email String @unique
image String?
password String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
Environment File (.env) ๐
In your root directory, create a file called .env
and add the following:
DATABASE_URL="postgresql://<username>:<password>@<host>:<port>/<database>"
โจ Fun Part: How do you get this
DATABASE_URL
? Let's find out!
Steps to Obtain the Database URL ๐
Step 1: Pull the PostgreSQL Docker Image ๐ณ
Run this command to download PostgreSQL:
docker pull postgres
Step 2: Run the PostgreSQL Container ๐
Start a new container with:
docker run --name my_postgres_container -e POSTGRES_USER=myuser -e POSTGRES_PASSWORD=mypassword -e POSTGRES_DB=mydatabase -p 5433:5432 -d postgres
What do these flags mean? ๐ง
--name my_postgres_container
: Name your container for easy reference.-e POSTGRES_USER=myuser
: Set the PostgreSQL username.-e POSTGRES_PASSWORD=mypassword
: Set the PostgreSQL password.-e POSTGRES_DB=mydatabase
: Create a database namedmydatabase
.-p 5433:5432
: Map port 5432 inside the container to port 5433 on your system.-d
: Run the container in detached mode (in the background).
This setup makes PostgreSQL accessible on your local machine at port 5433. ๐
Step 3: Construct the DATABASE_URL
๐
Your DATABASE_URL
will look like this:
DATABASE_URL=postgresql://myuser:mypassword@localhost:5433/mydatabase
Add this to your .env
file. โ
Prisma Client ๐ค
Prisma Client lets you interact with your database directly in your code. ๐ฏ
Create a generator block in the Prisma schema file.
Define your models (like the
User
model shown earlier).
Managing Your Database with Migrations ๐
Prisma migrations help you make changes to your database schema over time.
Create a Migration ๐ ๏ธ
npx prisma migrate dev
This generates a migration file and applies it to your database. ๐
Deploy Migrations ๐
npx prisma migrate deploy
This applies any pending migrations to your database. โก
Keep Your Schema Clean โจ
Format your Prisma schema file with:
npx prisma format
Subscribe to my newsletter
Read articles from Gaurav Maurya directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
