This example shows how to:
- Connect Prisma to a CockroachDB database
- Create the database schema with raw SQL
- Populate the Prisma schema using
prisma db pull - Read and write data to the database using Prisma Client
Note: CockroachDB support in Prisma is currently in Preview, and Prisma Migrate isn't supported for now. For this reason, you will create the database schema with raw SQL.
The example consists of two parts:
tests/prisma.test.ts: Jest test (in TypeScript) with a variety of Prisma Client queries and assertions to showcase access patternssrc/script.ts: Node.js script with queries similar to the ones in the test.
- Node.js installed.
- Docker installed
Note: You can also connect to a free CockroachDB Serverless Cluster.
Download this example:
curl https://codeload.github.com/prisma/prisma-examples/tar.gz/latest | tar -xz --strip=2 prisma-examples-latest/databases/cockroachdb
Install npm dependencies:
cd cockroachdb
npm install
Alternative:Clone this repository
Clone this repository:
git clone git@github.com:prisma/prisma-examples.git --depth=1
Install npm dependencies:
cd prisma-examples/databases/cockroachdb
npm install
There are two approaches to setting up a CockroachDB database:
- Locally with Docker using the included
docker-compose.ymlfile. - Using a free hosted CockroachDB Serverless.
Run the following command from the cockroachdb folder to start a CockroachDB Docker container:
docker compose up -dFollow the following guide to create a free CockroachDB Serverless cluster.
Prisma uses the DATABASE_URL environment variable in .env in the cockroachdb folder to connect to the database.
Create the file:
touch .envThen add the following line:
DATABASE_URL="postgresql://root@localhost:26257/prisma?sslmode=disable"
Note: If you're using CockroachDB Serverless, see
.env.examplefor more information on howDATABASE_URLshould look like with the cluster configruation.
Now that you have defined the DATABASE_URL in .env, you will use Prisma Migrate to create a migration file with the SQL necessary to create the database schema.
Run the following command from the cockroachdb folder:
npx prisma migrate dev --name init
You should see the following output:
Your database is now in sync with your schema.
Note: The
prisma migrate devcommand will automatically generate Prisma Client for use inscript.ts.
To run the test in tests/prisma.test.ts, run the following command:
npm run test
To run the script src/script.ts, run the following command:
npm run start
As a next step, explore the script.ts file to see how to use Prisma Client to read and write data in the database.
- Check out the Prisma docs
- Join our community on Discord to share feedback and interact with other users.
- Subscribe to our YouTube channel for live demos and video tutorials.
- Follow us on X for the latest updates.
- Report issues or ask questions on GitHub.