Objectives
Discover the process of utilizing Prisma to interact with PostgreSQL.
Background
Having previously enjoyed using SQLAlchemy, a Python ORM, I am now delving into the world of Prisma, a TypeScript ORM, as I find TypeScript fascinating. In this blog, I aim to explore Prisma's capabilities and share my experience. Hope you enjoy!
Tech Stack
Setup Prisma
mkdir prisma-postgres
cd prisma-postgres
npm init -y
npm install typescript ts-node @types/node --save-dev
npx tsc --init
npm install prisma --save-dev
npx prisma init --datasource-provider postgresql
Create a PostgreSQL database using Supabase
Log into Supabase and create a new project
Get the connection string from the project settings
Choose Node.js
Swap the DATABASE_URL in .env to your own connection string
DATABASE_URL="YOUR_CONNECTION_STRING"
Model data in the Prisma schema
Prisma schema provides an intuitive way to model data. Add your own Prisma data model to your Prisma schema in prisma/schema.prisma:
Add your own data model
The data model I provided below represents a system for managing news articles (News) about athletes (Athlete) and their profiles (Profile). An athlete can have multiple news articles associated with them, and each athlete has a profile containing various details such as bio, age, team, height, weight, college, and draft information.
The final schema.prisma file would look something like this
To map your data model to the database schema, you need to use the prisma migrate CLI commands:npx prisma migrate dev --name init
If you have successfully connected, you will receive a message stating, "Your database is now synchronized with your schema."
In this case, you should see three data tables (Athlete, News, Profile) generated on Supabase.
Checkout more detail on Prisma schema documentation
Install and generate Prisma Client
Install the @prisma/client package using npm
npm install @prisma/client
Quering your database with Prisma Client
Write your first query
Add the content of the main function to read all Athlete records from the database and print the result
Let's walk through the code:
Execute query.ts
npx ts-node query.ts // Output: [], Since there's nothing in the database
Write data into database
Here, we swap out the previous query and try to write data into database.
Let's walk through the code:
Execute the code and the output should look similar to this:
Hooray! You can also check the data on supabase 🎉
Conclusion
Prisma provides developers with an effortless yet powerful approach to interact with databases. Its type-safe queries enable catching errors at compile-time, enhancing code reliability, while its automated schema migrations simplify managing database changes and updates. These advantages, along with seamless database interaction, data modeling, and multi-database support, make Prisma a powerful tool for building robust and efficient applications!
This post is also on Medium
Source