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.

Prisma - 图1

Note

This tutorial works with TiDB Serverless, TiDB Dedicated, and TiDB Self-Hosted.

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:

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

Step 2: Install dependencies

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

  1. npm install

Install dependencies to existing project

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

  1. 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 Serverless
  • TiDB Dedicated
  • TiDB Self-Hosted
  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.

    • Endpoint 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:

    1. 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:

    1. DATABASE_URL='{connection_string}'

    Prisma - 图2

    Note

    For TiDB Serverless, you MUST enable TLS connection by setting sslaccept=strict when using public endpoint.

  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:

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

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

  11. Click Allow Access from Anywhere and then click Download CA cert to download the CA certificate.

    For more details about how to obtain the connection string, refer to TiDB Dedicated standard connection.

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

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

    1. DATABASE_URL='mysql://{user}:{password}@{host}:4000/test?sslaccept=strict&sslcert={downloaded_ssl_ca_path}'

    Prisma - 图3

    Note

    For TiDB Serverless, It is RECOMMENDED to enable TLS connection by setting sslaccept=strict when using public endpoint. When you set up sslaccept=strict to enable TLS connection, you MUST specify the file path of the CA certificate downloaded from connection dialog via sslcert=/path/to/ca.pem.

  14. Save the .env file.

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

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

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

    1. 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.

  18. Save the .env file.

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

    1. datasource db {
    2. provider = "mysql"
    3. url = env("DATABASE_URL")
    4. }

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.

  1. npx prisma migrate dev

Data models defined in prisma.schema:

  1. // Define a Player model, which represents the `players` table.
  2. model Player {
  3. id Int @id @default(autoincrement())
  4. name String @unique(map: "uk_player_on_name") @db.VarChar(50)
  5. coins Decimal @default(0)
  6. goods Int @default(0)
  7. createdAt DateTime @default(now()) @map("created_at")
  8. profile Profile?
  9. @@map("players")
  10. }
  11. // Define a Profile model, which represents the `profiles` table.
  12. model Profile {
  13. playerId Int @id @map("player_id")
  14. biography String @db.Text
  15. // Define a 1:1 relation between the `Player` and `Profile` models with foreign key.
  16. player Player @relation(fields: [playerId], references: [id], onDelete: Cascade, map: "fk_profile_on_player_id")
  17. @@map("profiles")
  18. }

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

Expected execution output:

  1. Your database is now in sync with your schema.
  2. 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:

  1. npm start

Main logic in the sample code:

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

Expected execution output:

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

  1. 🔌 Connected to TiDB cluster! (TiDB version: 5.7.25-TiDB-v6.6.0-serverless)
  2. 🆕 Created a new player with ID 1.
  3. ℹ️ Got Player 1: Player { id: 1, coins: 100, goods: 100 }
  4. 🔢 Added 50 coins and 50 goods to player 1, now player 1 has 150 coins and 150 goods.
  5. 🚮 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:

  1. const player: Player = await prisma.player.create({
  2. data: {
  3. name: 'Alice',
  4. coins: 100,
  5. goods: 200,
  6. createdAt: new Date(),
  7. }
  8. });

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:

  1. const player: Player | null = prisma.player.findUnique({
  2. where: {
  3. id: 101,
  4. }
  5. });

For more information, refer to Query data.

Update data

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

  1. await prisma.player.update({
  2. where: {
  3. id: 101,
  4. },
  5. data: {
  6. coins: {
  7. increment: 50,
  8. },
  9. goods: {
  10. increment: 50,
  11. },
  12. }
  13. });

For more information, refer to Update data.

Delete data

The following query deletes the Player with ID 101:

  1. await prisma.player.delete({
  2. where: {
  3. id: 101,
  4. }
  5. });

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 - 图4

    Warning

    Foreign keys are suitable for small and medium-volumes data scenarios. Using foreign keys in large data volumes might lead to serious performance issues and could have unpredictable effects on the system. If you plan to use foreign keys, conduct thorough validation first and use them with caution.

  • 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 the Discord, or create a support ticket.

Ask questions on the Discord, or create a support ticket.