PostgreSQL & Prisma
PostgreSQL is a powerful, open-source relational database system known for its standards compliance, extensibility, and rock-solid data integrity. If MongoDB is a flexible filing cabinet, PostgreSQL is a meticulously designed spreadsheet where every column type, constraint, and relationship is enforced by the system itself.
Prisma is a next-generation ORM (Object-Relational Mapper) that consists of three tools: the Prisma Client (a type-safe query builder auto-generated from your schema), Prisma Migrate (a migration system that keeps your database schema in sync with your code), and Prisma Studio (a visual database browser). Unlike traditional ORMs that map classes to tables, Prisma takes a schema-first approach — you define your data model in a .prisma file, and it generates everything else.
Setup
-
Install Prisma CLI as a dev dependency:
-
Initialize Prisma:
This creates a
prisma directory with schema.prisma and creates a .env file.
-
Update
.env with your PostgreSQL connection string:
Defining the Schema
Edit prisma/schema.prisma to define your data model.
Migrations
Migrations are versioned SQL scripts that evolve your database schema over time. Think of them as git commits for your database structure — each migration captures the exact changes needed to go from one schema version to the next, and they can be replayed in order on any database to arrive at the same state.
This creates the SQL tables and generates the Prisma Client. Each migration lives as a .sql file inside prisma/migrations/, giving you a full audit trail of every schema change.
Using Prisma Client
Install the client:
Use it in your code:
Common mistake: Creating a new PrismaClient() on every request or in every file. Each instance opens its own connection pool, so spawning many instances will exhaust your database connections. Always use a singleton pattern (see Best Practices at the bottom of this chapter).
CRUD Operations
Create
Read
Update
Delete
Summary
- Prisma provides a type-safe database client
- schema.prisma is the single source of truth for your data model
- Migrations keep your database schema in sync
- Prisma Client’s auto-completion makes queries easy and less error-prone
Advanced Schema Features
Advanced Queries
Transactions
Middleware
Prisma middleware intercepts every database operation before and after it executes. This is the same concept as Express middleware, but for database queries instead of HTTP requests. You can use them for logging, soft deletes, automatic auditing, or transforming results.
Prisma Studio
Prisma provides a visual database browser:
This opens a web interface at http://localhost:5555 to browse and edit data.
Best Practices
Prisma vs Mongoose:
- Use Prisma for PostgreSQL/MySQL with TypeScript (better type safety)
- Use Mongoose for MongoDB with flexible schemas
- Both are excellent choices for their respective databases