apps/docs/content/docs/(index)/prisma-orm/add-to-existing-project/cockroachdb.mdx
CockroachDB is a distributed SQL database designed for cloud applications, offering horizontal scalability, strong consistency, and high availability. In this guide, you will learn how to add Prisma ORM to an existing TypeScript project, connect it to CockroachDB, 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 like prisma init, prisma db pull, and prisma generate@prisma/client - The Prisma Client library for querying your database@prisma/adapter-pg - The node-postgres driver adapter that connects Prisma Client to your database (CockroachDB is PostgreSQL-compatible)pg - The node-postgres database driver@types/pg - TypeScript type definitions for node-postgresdotenv - Loads environment variables from your .env fileSet up your Prisma ORM project by creating your Prisma Schema file with the following command:
npx prisma init --datasource-provider cockroachdb --output ../generated/prisma
This command does a few things:
prisma/ directory with a schema.prisma file containing your database connection configuration.env file in the root directory for environment variablesprisma.config.ts file for Prisma configurationThe generated prisma.config.ts file looks like this:
import "dotenv/config";
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 = "cockroachdb"
}
Update the .env file with your CockroachDB connection URL:
DATABASE_URL="postgresql://user:password@host:26257/mydb?sslmode=require"
The format of the connection URL for CockroachDB looks as follows:
postgresql://USER:PASSWORD@HOST:PORT/DATABASE?sslmode=require
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 the Prisma ORM driver adapter 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:
model Post { // [!code ++]
id Int @id @default(autoincrement()) // [!code ++]
title String // [!code ++]
content String? // [!code ++]
published Boolean @default(false) // [!code ++]
authorId Int // [!code ++]
author User @relation(fields: [authorId], references: [id]) // [!code ++]
} // [!code ++]
model User { // [!code ++]
id Int @id @default(autoincrement()) // [!code ++]
email String @unique // [!code ++]
name String? // [!code ++]
posts Post[] // [!code ++]
} // [!code ++]
npx prisma migrate dev --name your_migration_name
This command will:
Explore the options suggested by CockroachDB to view and manage your data.
:::warning
Prisma Studio does not currently support CockroachDB. Support may be added in a future release. See Databases supported by Prisma Studio for more information.
:::
You've successfully set up Prisma ORM. Here's what you can explore next: