| 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. |
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 {{{ .starter }}}, {{{ .essential }}}, TiDB Cloud Dedicated, and TiDB Self-Managed.
To complete this tutorial, you need:
If you don't have a TiDB cluster, you can create one as follows:
- (Recommended) Follow Creating a {{{ .starter }}} 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.
- (Recommended) Follow Creating a {{{ .starter }}} 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.
This section demonstrates how to run the sample application code and connect to TiDB.
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-quickstartRun the following command to install the required packages (including prisma) for the sample app:
npm installInstall 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-devConnect to your TiDB cluster depending on the TiDB deployment option you've selected.
-
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.
- 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.
- Connection Type is set to
-
If you have not set a password yet, click Generate Password to generate a random password.
-
Run the following command to copy
.env.exampleand rename it to.env:cp .env.example .env
-
Edit the
.envfile, set up the environment variableDATABASE_URLas follows, and replace the corresponding placeholders{}with the connection string in the connection dialog:DATABASE_URL='{connection_string}'
Note
For {{{ .starter }}}, you MUST enable TLS connection by setting
sslaccept=strictwhen using public endpoint. -
Save the
.envfile. -
In the
prisma/schema.prisma, set upmysqlas 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.
-
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 Cloud Dedicated supports Private Endpoint and VPC Peering connection types. For more information, see Connect to Your TiDB Cloud Dedicated Cluster.
-
Run the following command to copy
.env.exampleand rename it to.env:cp .env.example .env
-
Edit the
.envfile, set up the environment variableDATABASE_URLas 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 {{{ .starter }}}, It is RECOMMENDED to enable TLS connection by setting
sslaccept=strictwhen using public endpoint. When you set upsslaccept=strictto enable TLS connection, you MUST specify the file path of the CA certificate downloaded from connection dialog viasslcert=/path/to/ca.pem. -
Save the
.envfile. -
In the
prisma/schema.prisma, set upmysqlas 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.exampleand rename it to.env:cp .env.example .env
-
Edit the
.envfile, set up the environment variableDATABASE_URLas 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
.envfile. -
In the
prisma/schema.prisma, set upmysqlas the connection provider andenv("DATABASE_URL")as the connection URL:datasource db { provider = "mysql" url = env("DATABASE_URL") }
Run following command to invoke Prisma Migrate to initialize the database with the data models defined in prisma/prisma.schema.
npx prisma migrate devData 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.
Run the following command to execute the sample code:
npm startMain 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.5.0)
🆕 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.
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.
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.
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.
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.
The following query deletes the Player with ID 101:
await prisma.player.delete({
where: {
id: 101,
}
});For more information, refer to Delete data.
To check referential integrity, you can use foreign key constraints or Prisma relation mode:
-
Foreign key is a feature supported starting from TiDB v6.6.0, and generally available starting from v8.5.0. Foreign keys allow cross-table references of related data, while foreign key constraints ensure the consistency of related data.
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.
- 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.
Ask the community on Discord or Slack, or submit a support ticket.
Ask the community on Discord or Slack, or submit a support ticket.