| title | sidebar_title | metaTitle | metaDescription |
|---|---|---|---|
Add Prisma ORM to an existing PostgreSQL project |
PostgreSQL |
How to add Prisma ORM to an existing project using PostgreSQL (15 min) |
Add Prisma ORM to an existing TypeScript project with PostgreSQL and learn database introspection, baselining, and querying. |
import Prerequisites from '../../_components/_prerequisites.mdx' import ExploreData from '../../_components/_explore-data.mdx' import NextSteps from '../../_components/_next-steps.mdx'
PostgreSQL is a popular open-source relational database known for its reliability, feature robustness, and performance. In this guide, you will learn how to add Prisma ORM to an existing TypeScript project, connect it to PostgreSQL, introspect your existing database schema, and start querying with type-safe Prisma Client.
Navigate to your existing project directory and install the required dependencies:
npm install prisma @types/node @types/pg --save-dev
npm install @prisma/client @prisma/adapter-pg pg dotenv
Here's what each package does:
prisma- The Prisma CLI for running commands likeprisma init,prisma db pull, andprisma generate@prisma/client- The Prisma Client library for querying your database@prisma/adapter-pg- Thenode-postgresdriver adapter that connects Prisma Client to your databasepg- The node-postgres database driver@types/pg- TypeScript type definitions for node-postgresdotenv- Loads environment variables from your.envfile
Set up your Prisma ORM project by creating your Prisma Schema file with the following command:
npx prisma init --datasource-provider postgresql --output ../generated/prisma
This command does a few things:
- Creates a
prisma/directory with aschema.prismafile containing your database connection configuration - Creates a
.envfile in the root directory for environment variables - Creates a
prisma.config.tsfile for Prisma configuration
The generated prisma.config.ts file looks like this:
import { defineConfig, env } from 'prisma/config'
export default defineConfig({
schema: 'prisma/schema.prisma',
migrations: {
path: 'prisma/migrations',
},
datasource: {
url: env('DATABASE_URL'),
},
})Add dotenv to prisma.config.ts so that Prisma can load environment variables from your .env file:
// add-start
import 'dotenv/config'
// add-end
import { defineConfig, env } from 'prisma/config'
export default defineConfig({
schema: 'prisma/schema.prisma',
migrations: {
path: 'prisma/migrations',
},
datasource: {
url: env('DATABASE_URL'),
},
})The generated schema uses the ESM-first prisma-client generator with a custom output path:
generator client {
provider = "prisma-client"
output = "../generated/prisma"
}
datasource db {
provider = "postgresql"
}Update the .env file with your PostgreSQL connection URL:
DATABASE_URL="postgresql://user:password@localhost:5432/mydb?schema=public"The format of the connection URL for PostgreSQL looks as follows:
postgresql://USER:PASSWORD@HOST:PORT/DATABASE?schema=SCHEMA
Run the following command to introspect your existing database:
npx prisma db pull
This command reads the DATABASE_URL environment variable, connects to your database, and introspects the database schema. It then translates the database schema from SQL into a data model in your Prisma schema.
After introspection, your Prisma schema will contain models that represent your existing database tables.
To use Prisma Migrate with your existing database, you need to baseline your database.
First, create a migrations directory:
mkdir -p prisma/migrations/0_init
Next, generate the migration file with prisma migrate diff:
npx prisma migrate diff --from-empty --to-schema prisma/schema.prisma --script > prisma/migrations/0_init/migration.sql
Review the generated migration file to ensure it matches your database schema.
Then, mark the migration as applied:
npx prisma migrate resolve --applied 0_init
You now have a baseline for your current database schema.
Generate Prisma Client based on your introspected schema:
npx prisma generate
This creates a type-safe Prisma Client tailored to your database schema in the generated/prisma directory.
Create a utility file to instantiate Prisma Client. You need to pass an instance of Prisma ORM's driver adapter to the PrismaClient constructor:
import "dotenv/config";
import { PrismaPg } from '@prisma/adapter-pg'
import { PrismaClient } from '../generated/prisma/client'
const connectionString = `${process.env.DATABASE_URL}`
const adapter = new PrismaPg({ connectionString })
const prisma = new PrismaClient({ adapter })
export { prisma }Now you can use Prisma Client to query your database. Create a script.ts file:
import { prisma } from './lib/prisma'
async function main() {
// Example: Fetch all records from a table
// Replace 'user' with your actual model name
const allUsers = await prisma.user.findMany()
console.log('All users:', JSON.stringify(allUsers, null, 2))
}
main()
.then(async () => {
await prisma.$disconnect()
})
.catch(async (e) => {
console.error(e)
await prisma.$disconnect()
process.exit(1)
})Run the script:
npx tsx script.ts
To make changes to your database schema:
Update your Prisma schema file to reflect the changes you want to make to your database schema. For example, add a new model:
// add-start
model Post {
id Int @id @default(autoincrement())
title String
content String?
published Boolean @default(false)
authorId Int
author User @relation(fields: [authorId], references: [id])
}
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
posts Post[]
}
// add-endnpx prisma migrate dev --name your_migration_name
This command will:
- Create a new SQL migration file
- Apply the migration to your database
- Regenerate Prisma Client
