Prisma ORM 8 is here.Read the docs
V7Quickstart

CockroachDB

Prisma ORM v7

Create a new TypeScript project from scratch by connecting Prisma ORM to CockroachDB and generating a Prisma Client for database access

CockroachDB is a distributed SQL database built for cloud applications. In this guide, you will learn how to set up a new TypeScript project from scratch, connect it to CockroachDB using Prisma ORM, and generate a Prisma Client for type-safe access to your database.

Prerequisites

You also need:

  • A CockroachDB database
  • Database connection string from CockroachDB

1. Create a new project

mkdir hello-prisma
cd hello-prisma

Initialize a TypeScript project:

bun init
bun add typescript tsx @types/node --dev
bunx tsc --init

2. Install required dependencies

Install the packages needed for this quickstart:

bun add prisma@7.10.0 @types/pg --dev
bun add @prisma/client@7.10.0 @prisma/adapter-pg pg dotenv

Here's what each package does:

  • prisma - The Prisma CLI for running commands like prisma init, prisma migrate, 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-postgres
  • dotenv - Loads environment variables from your .env file

3. Configure ESM support

Update tsconfig.json for ESM compatibility:

tsconfig.json
{
  "compilerOptions": {
    "module": "ESNext",
    "moduleResolution": "bundler",
    "target": "ES2023",
    "strict": true,
    "esModuleInterop": true,
    "ignoreDeprecations": "6.0"
  }
}

Update package.json to enable ESM:

package.json
{
  "type": "module"
}

4. Initialize Prisma ORM

You can now run Prisma CLI commands using your package manager:

bunx prisma

Next, set up your Prisma ORM project by creating your Prisma Schema file with the following command:

bunx --bun prisma init --datasource-provider cockroachdb --output ../generated/prisma

This command does a few things:

  • Creates a prisma/ directory with a schema.prisma file containing your database connection and schema models
  • Creates a .env file in the root directory for environment variables
  • Creates a prisma.config.ts file for Prisma configuration

The generated prisma.config.ts file looks like this:

prisma.config.ts
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:

prisma/schema.prisma
generator client {
  provider = "prisma-client"
  output   = "../generated/prisma"
}

datasource db {
  provider = "cockroachdb"
}

Update your .env file with your CockroachDB connection string:

.env
DATABASE_URL="postgresql://username:password@host:26257/mydb?sslmode=require"

Replace with your actual CockroachDB connection string from your cluster dashboard.

5. Define your data model

Open prisma/schema.prisma and add the following models:

prisma/schema.prisma
generator client {
  provider = "prisma-client"
  output   = "../generated/prisma"
}

datasource db {
  provider = "cockroachdb"
}

model User { 
  id    Int     @id @default(autoincrement()) 
  email String  @unique
  name  String?
  posts Post[]
} 

model Post { 
  id        Int     @id @default(autoincrement()) 
  title     String
  content   String?
  published Boolean @default(false) 
  author    User    @relation(fields: [authorId], references: [id]) 
  authorId  Int
} 

6. Create and apply your first migration

Create your first migration to set up the database tables:

bunx prisma migrate dev --name init

This command creates the database tables based on your schema.

Now run the following command to generate the Prisma Client:

bunx prisma generate

7. Instantiate Prisma Client

Now that you have all the dependencies installed, you can instantiate Prisma Client. You need to pass an instance of the Prisma ORM driver adapter adapter to the PrismaClient constructor:

lib/prisma.ts
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 };

8. Write your first query

Create a script.ts file to test your setup:

script.ts
import { prisma } from "./lib/prisma";

async function main() {
  // Create a new user with a post
  const user = await prisma.user.create({
    data: {
      name: "Alice",
      email: "alice@prisma.io",
      posts: {
        create: {
          title: "Hello World",
          content: "This is my first post!",
          published: true,
        },
      },
    },
    include: {
      posts: true,
    },
  });
  console.log("Created user:", user);

  // Fetch all users with their posts
  const allUsers = await prisma.user.findMany({
    include: {
      posts: true,
    },
  });
  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:

bunx tsx script.ts

You should see the created user and all users printed to the console.

9. Explore your data

Explore the options suggested by CockroachDB to view and manage your data.

Next steps

Prisma ORM is set up. These are the pages you are most likely to need next:

  • Learn more about Prisma Client: Explore the Prisma Client API for advanced querying, filtering, and relations
  • Database migrations: Learn about Prisma Migrate for evolving your database schema
  • Performance optimization: Discover query optimization techniques
  • Build a full application: Check out our framework guides to integrate Prisma ORM with Next.js, Express, and more
  • Join the community: Connect with other developers on Discord

More info

On this page