Connect to TiDB with Prisma

TiDB is a MySQL-compatible database, and Prisma is a popular open-source ORM framework for Node.js.

In this tutorial, you can learn how to use TiDB and Prisma to accomplish the following tasks:

  • Set up your environment.
  • Connect to your TiDB cluster using Prisma.
  • Build and run your application. Optionally, you can find sample code snippets for basic CRUD operations.

Prerequisites

To complete this tutorial, you need:

  • Node.js >= 16.x installed on your machine.
  • Git installed on your machine.
  • A TiDB cluster running.

If you don't have a TiDB cluster, you can create one as follows:

Run the sample app to connect to TiDB

This section demonstrates how to run the sample application code and connect to TiDB.

Step 1: Clone the sample app repository

Run the following commands in your terminal window to clone the sample code repository:

git clone https://github.com/tidb-samples/tidb-nodejs-prisma-quickstart.git cd tidb-nodejs-prisma-quickstart

Step 2: Install dependencies

Run the following command to install the required packages (including prisma) for the sample app:

npm install
Install dependencies to existing project

For your existing project, run the following command to install the packages:

npm install prisma typescript ts-node @types/node --save-dev

Step 3: Provide connection Parameters

Connect to your TiDB cluster depending on the TiDB deployment option you've selected.

  • TiDB Cloud Serverless
  • TiDB Cloud Dedicated
  • TiDB Self-Managed
  1. Navigate to the Clusters page, and then click the name of your target cluster to go to its overview page.

  2. Click Connect in the upper-right corner. A connection dialog is displayed.

  3. Ensure the configurations in the connection dialog match your operating environment.

    • Connection Type is set to Public.
    • Branch is set to main.
    • Connect With is set to Prisma.
    • Operating System matches the operating system where you run the application.
  4. If you have not set a password yet, click Generate Password to generate a random password.

  5. Run the following command to copy .env.example and rename it to .env:

    cp .env.example .env
  6. Edit the .env file, set up the environment variable DATABASE_URL as follows, and replace the corresponding placeholders {} with the connection string in the connection dialog:

    DATABASE_URL='{connection_string}'
  7. Save the .env file.

  8. In the prisma/schema.prisma, set up mysql as the connection provider and env("DATABASE_URL") as the connection URL:

    datasource db { provider = "mysql" url = env("DATABASE_URL") }
  1. Navigate to the Clusters page, and then click the name of your target cluster to go to its overview page.

  2. Click Connect in the upper-right corner. A connection dialog is displayed.

  3. In the connection dialog, select Public from the Connection Type drop-down list, and then click CA cert to download the CA certificate.

    If you have not configured the IP access list, click Configure IP Access List or follow the steps in Configure an IP Access List to configure it before your first connection.

    In addition to the Public connection type, TiDB Dedicated supports Private Endpoint and VPC Peering connection types. For more information, see Connect to Your TiDB Dedicated Cluster.

  4. Run the following command to copy .env.example and rename it to .env:

    cp .env.example .env
  5. Edit the .env file, set up the environment variable DATABASE_URL as follows, replace the corresponding placeholders {} with connection parameters on the connection dialog:

    DATABASE_URL='mysql://{user}:{password}@{host}:4000/test?sslaccept=strict&sslcert={downloaded_ssl_ca_path}'
  6. Save the .env file.

  7. In the prisma/schema.prisma, set up mysql as the connection provider and env("DATABASE_URL") as the connection URL:

    datasource db { provider = "mysql" url = env("DATABASE_URL") }
  1. Run the following command to copy .env.example and rename it to .env:

    cp .env.example .env
  2. Edit the .env file, set up the environment variable DATABASE_URL as follows, replace the corresponding placeholders {} with connection parameters of your TiDB cluster:

    DATABASE_URL='mysql://{user}:{password}@{host}:4000/test'

    If you are running TiDB locally, the default host address is 127.0.0.1, and the password is empty.

  3. Save the .env file.

  4. In the prisma/schema.prisma, set up mysql as the connection provider and env("DATABASE_URL") as the connection URL:

    datasource db { provider = "mysql" url = env("DATABASE_URL") }

Step 4. Initialize the database schema

Run following command to invoke Prisma Migrate to initialize the database with the data models defined in prisma/prisma.schema.

npx prisma migrate dev

Data models defined in prisma.schema:

// Define a Player model, which represents the `players` table. model Player { id Int @id @default(autoincrement()) name String @unique(map: "uk_player_on_name") @db.VarChar(50) coins Decimal @default(0) goods Int @default(0) createdAt DateTime @default(now()) @map("created_at") profile Profile? @@map("players") } // Define a Profile model, which represents the `profiles` table. model Profile { playerId Int @id @map("player_id") biography String @db.Text // Define a 1:1 relation between the `Player` and `Profile` models with foreign key. player Player @relation(fields: [playerId], references: [id], onDelete: Cascade, map: "fk_profile_on_player_id") @@map("profiles") }

To learn how to define data models in Prisma, please check the Data model documentation.

Expected execution output:

Your database is now in sync with your schema. ✔ Generated Prisma Client (5.1.1 | library) to ./node_modules/@prisma/client in 54ms

This command will also generate Prisma Client for TiDB database accessing based on the prisma/prisma.schema.

Step 5: Run the code

Run the following command to execute the sample code:

npm start

Main logic in the sample code:

// Step 1. Import the auto-generated `@prisma/client` package. import {Player, PrismaClient} from '@prisma/client'; async function main(): Promise<void> { // Step 2. Create a new `PrismaClient` instance. const prisma = new PrismaClient(); try { // Step 3. Perform some CRUD operations with Prisma Client ... } finally { // Step 4. Disconnect Prisma Client. await prisma.$disconnect(); } } void main();

Expected execution output:

If the connection is successful, the terminal will output the version of the TiDB cluster as follows:

🔌 Connected to TiDB cluster! (TiDB version: 8.0.11-TiDB-v8.1.1) 🆕 Created a new player with ID 1. ℹ️ Got Player 1: Player { id: 1, coins: 100, goods: 100 } 🔢 Added 50 coins and 50 goods to player 1, now player 1 has 150 coins and 150 goods. 🚮 Player 1 has been deleted.

Sample code snippets

You can refer to the following sample code snippets to complete your own application development.

For complete sample code and how to run it, check out the tidb-samples/tidb-nodejs-prisma-quickstart repository.

Insert data

The following query creates a single Player record, and returns the created Player object, which contains the id field generated by TiDB:

const player: Player = await prisma.player.create({ data: { name: 'Alice', coins: 100, goods: 200, createdAt: new Date(), } });

For more information, refer to Insert data.

Query data

The following query returns a single Player object with ID 101 or null if no record is found:

const player: Player | null = prisma.player.findUnique({ where: { id: 101, } });

For more information, refer to Query data.

Update data

The following query adds 50 coins and 50 goods to the Player with ID 101:

await prisma.player.update({ where: { id: 101, }, data: { coins: { increment: 50, }, goods: { increment: 50, }, } });

For more information, refer to Update data.

Delete data

The following query deletes the Player with ID 101:

await prisma.player.delete({ where: { id: 101, } });

For more information, refer to Delete data.

Useful notes

Foreign key constraints vs Prisma relation mode

To check referential integrity, you can use foreign key constraints or Prisma relation mode:

  • Foreign key is an experimental feature supported starting from TiDB v6.6.0, which allows cross-table referencing of related data, and foreign key constraints to maintain data consistency.

  • Prisma relation mode is the emulation of referential integrity in Prisma Client side. However, it should be noted that there are performance implications, as it requires additional database queries to maintain referential integrity.

Next steps

Need help?

Ask questions on TiDB Community, or create a support ticket.

Was this page helpful?