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:
If you don't have a TiDB cluster, you can create one as follows:
- (Recommended) Follow Creating a TiDB Serverless cluster to create your own TiDB Cloud cluster.
- Follow Deploy a local test TiDB cluster or Deploy a production TiDB cluster to create a local cluster.
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 Serverless
- TiDB Dedicated
- TiDB Self-Hosted
Navigate to the Clusters page, and then click the name of your target cluster to go to its overview page.
Click Connect in the upper-right corner. A connection dialog is displayed.
Ensure the configurations in the connection dialog match your operating environment.
- Endpoint Type is set to
Public
. - Connect With is set to
General
. - Operating System matches the operating system where you run the application.
- Endpoint Type is set to
If you have not set a password yet, click Create password to generate a random password.
Run the following command to copy
.env.example
and rename it to.env
:cp .env.example .envEdit the
.env
file, set up the environment variableDATABASE_URL
as follows, replace the corresponding placeholders{}
with connection parameters on the connection dialog:DATABASE_URL='{connection_string}'Save the
.env
file.In the
prisma/schema.prisma
, set upmysql
as the connection provider andenv("DATABASE_URL")
as the connection URL:datasource db { provider = "mysql" url = env("DATABASE_URL") }
Navigate to the Clusters page, and then click the name of your target cluster to go to its overview page.
Click Connect in the upper-right corner. A connection dialog is displayed.
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.
Run the following command to copy
.env.example
and rename it to.env
:cp .env.example .envEdit the
.env
file, set up the environment variableDATABASE_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}'Save the
.env
file.In the
prisma/schema.prisma
, set upmysql
as the connection provider andenv("DATABASE_URL")
as the connection URL:datasource db { provider = "mysql" url = env("DATABASE_URL") }
Run the following command to copy
.env.example
and rename it to.env
:cp .env.example .envEdit the
.env
file, set up the environment variableDATABASE_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.Save the
.env
file.In the
prisma/schema.prisma
, set upmysql
as the connection provider andenv("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
For TiDB v6.6.0 or later, it's recommended to use Foreign key constraints instead of Prisma relation mode for referential integrity checking.
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
- Learn more usage of the ORM framework Prisma driver from the documentation of Prisma.
- Learn the best practices for TiDB application development with the chapters in the Developer guide, such as: Insert data, Update data, Delete data, Query data, Transactions, SQL performance optimization.
- Learn through the professional TiDB developer courses and earn TiDB certifications after passing the exam.
Need help?
Ask questions on TiDB Community, or create a support ticket.