title | summary |
---|---|
Connect to TiDB with TypeORM |
Learn how to connect to TiDB using TypeORM. This tutorial gives Node.js sample code snippets that work with TiDB using TypeORM. |
TiDB is a MySQL-compatible database, and TypeORM is a popular open-source ORM framework for Node.js.
In this tutorial, you can learn how to use TiDB and TypeORM to accomplish the following tasks:
- Set up your environment.
- Connect to your TiDB cluster using TypeORM.
- Build and run your application. Optionally, you can find sample code snippets for basic CRUD operations.
Note
This tutorial works with TiDB Cloud Serverless, 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 TiDB Cloud 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.
- (Recommended) Follow Creating a TiDB Cloud 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.
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-typeorm-quickstart.git
cd tidb-nodejs-typeorm-quickstart
Run the following command to install the required packages (including typeorm
and mysql2
) for the sample app:
npm install
Install dependencies to an existing project
For your existing project, run the following command to install the packages:
typeorm
: the ORM framework for Node.js.mysql2
: the MySQL driver for Node.js. You can also use themysql
driver.dotenv
: loads environment variables from the.env
file.typescript
: compiles TypeScript code to JavaScript.ts-node
: runs TypeScript code directly without compiling.@types/node
: provides TypeScript type definitions for Node.js.
npm install typeorm mysql2 dotenv --save
npm install @types/node ts-node typescript --save-dev
Connect 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
General
. - 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.example
and rename it to.env
:cp .env.example .env
-
Edit the
.env
file, set up the environment variables as follows, replace the corresponding placeholders{}
with connection parameters on the connection dialog:TIDB_HOST={host} TIDB_PORT=4000 TIDB_USER={user} TIDB_PASSWORD={password} TIDB_DATABASE=test TIDB_ENABLE_SSL=true
Note
For TiDB Cloud Serverless, you MUST enable TLS connection via
TIDB_ENABLE_SSL
when using public endpoint. -
Save the
.env
file.
-
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 Dedicated supports Private Endpoint and VPC Peering connection types. For more information, see Connect to Your TiDB Dedicated Cluster.
-
Run the following command to copy
.env.example
and rename it to.env
:cp .env.example .env
-
Edit the
.env
file, set up the environment variables as follows, replace the corresponding placeholders{}
with connection parameters on the connection dialog:TIDB_HOST={host} TIDB_PORT=4000 TIDB_USER={user} TIDB_PASSWORD={password} TIDB_DATABASE=test TIDB_ENABLE_SSL=true TIDB_CA_PATH={downloaded_ssl_ca_path}
Note
For TiDB Cloud Dedicated, it is RECOMMENDED to enable TLS connection via
TIDB_ENABLE_SSL
when using public endpoint. When you set upTIDB_ENABLE_SSL=true
, you MUST specify the path of the CA certificate downloaded from connection dialog viaTIDB_CA_PATH=/path/to/ca.pem
. -
Save the
.env
file.
-
Run the following command to copy
.env.example
and rename it to.env
:cp .env.example .env
-
Edit the
.env
file, set up the environment variables as follows, replace the corresponding placeholders{}
with connection parameters of your TiDB cluster:TIDB_HOST={host} TIDB_PORT=4000 TIDB_USER=root TIDB_PASSWORD={password} TIDB_DATABASE=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.
Run the following command to invoke TypeORM CLI to initialize the database with the SQL statements written in the migration files in the src/migrations
folder:
npm run migration:run
Expected execution output
The following SQL statements create a players
table and a profiles
table, and the two tables are associated through foreign keys.
query: SELECT VERSION() AS `version`
query: SELECT * FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE `TABLE_SCHEMA` = 'test' AND `TABLE_NAME` = 'migrations'
query: CREATE TABLE `migrations` (`id` int NOT NULL AUTO_INCREMENT, `timestamp` bigint NOT NULL, `name` varchar(255) NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB
query: SELECT * FROM `test`.`migrations` `migrations` ORDER BY `id` DESC
0 migrations are already loaded in the database.
1 migrations were found in the source code.
1 migrations are new migrations must be executed.
query: START TRANSACTION
query: CREATE TABLE `profiles` (`player_id` int NOT NULL, `biography` text NOT NULL, PRIMARY KEY (`player_id`)) ENGINE=InnoDB
query: CREATE TABLE `players` (`id` int NOT NULL AUTO_INCREMENT, `name` varchar(50) NOT NULL, `coins` decimal NOT NULL, `goods` int NOT NULL, `created_at` datetime NOT NULL, `profilePlayerId` int NULL, UNIQUE INDEX `uk_players_on_name` (`name`), UNIQUE INDEX `REL_b9666644b90ccc5065993425ef` (`profilePlayerId`), PRIMARY KEY (`id`)) ENGINE=InnoDB
query: ALTER TABLE `players` ADD CONSTRAINT `fk_profiles_on_player_id` FOREIGN KEY (`profilePlayerId`) REFERENCES `profiles`(`player_id`) ON DELETE NO ACTION ON UPDATE NO ACTION
query: INSERT INTO `test`.`migrations`(`timestamp`, `name`) VALUES (?, ?) -- PARAMETERS: [1693814724825,"Init1693814724825"]
Migration Init1693814724825 has been executed successfully.
query: COMMIT
Migration files are generated from the entities defined in the src/entities
folder. To learn how to define entities in TypeORM, refer to TypeORM: Entities.
Run the following command to execute the sample code:
npm start
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.3.0)
๐ Created a new player with ID 2.
โน๏ธ Got Player 2: Player { id: 2, coins: 100, goods: 100 }
๐ข Added 50 coins and 50 goods to player 2, now player 2 has 100 coins and 150 goods.
๐ฎ Deleted 1 player data.
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-typeorm-quickstart repository.
The following code establishes a connection to TiDB with options defined in the environment variables:
// src/dataSource.ts
// Load environment variables from .env file to process.env.
require('dotenv').config();
export const AppDataSource = new DataSource({
type: "mysql",
host: process.env.TIDB_HOST || '127.0.0.1',
port: process.env.TIDB_PORT ? Number(process.env.TIDB_PORT) : 4000,
username: process.env.TIDB_USER || 'root',
password: process.env.TIDB_PASSWORD || '',
database: process.env.TIDB_DATABASE || 'test',
ssl: process.env.TIDB_ENABLE_SSL === 'true' ? {
minVersion: 'TLSv1.2',
ca: process.env.TIDB_CA_PATH ? fs.readFileSync(process.env.TIDB_CA_PATH) : undefined
} : null,
synchronize: process.env.NODE_ENV === 'development',
logging: false,
entities: [Player, Profile],
migrations: [__dirname + "/migrations/**/*{.ts,.js}"],
});
Note
For TiDB Cloud Serverless, you MUST enable TLS connection when using public endpoint. In this sample code, please set up the environment variable
TIDB_ENABLE_SSL
in the.env
file totrue
.However, you don't have to specify an SSL CA certificate via
TIDB_CA_PATH
, because Node.js uses the built-in Mozilla CA certificate by default, which is trusted by TiDB Cloud Serverless.
The following query creates a single Player
record, and returns the created Player
object, which contains the id
field generated by TiDB:
const player = new Player('Alice', 100, 100);
await this.dataSource.manager.save(player);
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 = await this.dataSource.manager.findOneBy(Player, {
id: id
});
For more information, refer to Query data.
The following query adds 50
goods to the Player
with ID 101
:
const player = await this.dataSource.manager.findOneBy(Player, {
id: 101
});
player.goods += 50;
await this.dataSource.manager.save(player);
For more information, refer to Update data.
The following query deletes the Player
with ID 101
:
await this.dataSource.manager.delete(Player, {
id: 101
});
For more information, refer to Delete data.
The following query executes a raw SQL statement (SELECT VERSION() AS tidb_version;
) and returns the version of the TiDB cluster:
const rows = await dataSource.query('SELECT VERSION() AS tidb_version;');
console.log(rows[0]['tidb_version']);
For more information, refer to TypeORM: DataSource API.
Using foreign key constraints (experimental) ensures the referential integrity of data by adding checks on the database side. However, this might lead to serious performance issues in scenarios with large data volumes.
You can control whether foreign key constraints are created when constructing relationships between entities by using the createForeignKeyConstraints
option (default value is true
).
@Entity()
export class ActionLog {
@PrimaryColumn()
id: number
@ManyToOne((type) => Person, {
createForeignKeyConstraints: false,
})
person: Person
}
For more information, refer to the TypeORM FAQ and Foreign key constraints.
- Learn more usage of TypeORM from the documentation of TypeORM.
- 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 questions on TiDB Community, or create a support ticket.
Ask questions on TiDB Community, or create a support ticket.