Skip to content

Latest commit

 

History

History
383 lines (260 loc) · 13 KB

dev-guide-sample-application-nodejs-prisma.md

File metadata and controls

383 lines (260 loc) · 13 KB
title summary
Connect to TiDB with Prisma
Learn how to connect to TiDB using Prisma. This tutorial gives Node.js sample code snippets that work with TiDB using Prisma.

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.

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:

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.

  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:

    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}'

    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:

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

  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}'

    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.

  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: 5.7.25-TiDB-v6.6.0-serverless)
🆕 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.

    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.