Connect to TiDB with 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.

TypeORM - 图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-typeorm-quickstart.git
  2. cd tidb-nodejs-typeorm-quickstart

Step 2: Install dependencies

Run the following command to install the required packages (including typeorm and mysql2) for the sample app:

  1. 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 the mysql 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.
  1. npm install typeorm mysql2 dotenv --save
  2. npm install @types/node ts-node typescript --save-dev

Step 3: Configure connection information

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 General.
    • 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 variables as follows, replace the corresponding placeholders {} with connection parameters on the connection dialog:

    1. TIDB_HOST={host}
    2. TIDB_PORT=4000
    3. TIDB_USER={user}
    4. TIDB_PASSWORD={password}
    5. TIDB_DATABASE=test
    6. TIDB_ENABLE_SSL=true

    TypeORM - 图2

    Note

    For TiDB Serverless, you MUST enable TLS connection via TIDB_ENABLE_SSL when using public endpoint.

  7. Save the .env file.

  8. Navigate to the Clusters page, and then click the name of your target cluster to go to its overview page.

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

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

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

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

    1. TIDB_HOST={host}
    2. TIDB_PORT=4000
    3. TIDB_USER={user}
    4. TIDB_PASSWORD={password}
    5. TIDB_DATABASE=test
    6. TIDB_ENABLE_SSL=true
    7. TIDB_CA_PATH={downloaded_ssl_ca_path}

    TypeORM - 图3

    Note

    For TiDB Dedicated, it is RECOMMENDED to enable TLS connection via TIDB_ENABLE_SSL when using public endpoint. When you set up TIDB_ENABLE_SSL=true, you MUST specify the path of the CA certificate downloaded from connection dialog via TIDB_CA_PATH=/path/to/ca.pem.

  13. Save the .env file.

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

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

    1. TIDB_HOST={host}
    2. TIDB_PORT=4000
    3. TIDB_USER=root
    4. TIDB_PASSWORD={password}
    5. TIDB_DATABASE=test

    If you are running TiDB locally, the default host address is 127.0.0.1, and the password is empty.

  16. Save the .env file.

Step 4: Initialize the database schema

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:

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

  1. query: SELECT VERSION() AS `version`
  2. query: SELECT * FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE `TABLE_SCHEMA` = 'test' AND `TABLE_NAME` = 'migrations'
  3. query: CREATE TABLE `migrations` (`id` int NOT NULL AUTO_INCREMENT, `timestamp` bigint NOT NULL, `name` varchar(255) NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB
  4. query: SELECT * FROM `test`.`migrations` `migrations` ORDER BY `id` DESC
  5. 0 migrations are already loaded in the database.
  6. 1 migrations were found in the source code.
  7. 1 migrations are new migrations must be executed.
  8. query: START TRANSACTION
  9. query: CREATE TABLE `profiles` (`player_id` int NOT NULL, `biography` text NOT NULL, PRIMARY KEY (`player_id`)) ENGINE=InnoDB
  10. 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
  11. 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
  12. query: INSERT INTO `test`.`migrations`(`timestamp`, `name`) VALUES (?, ?) -- PARAMETERS: [1693814724825,"Init1693814724825"]
  13. Migration Init1693814724825 has been executed successfully.
  14. 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.

Step 5: Run the code and check the result

Run the following command to execute the sample code:

  1. npm start

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-v7.1.5)
  2. 🆕 Created a new player with ID 2.
  3. ℹ️ Got Player 2: Player { id: 2, coins: 100, goods: 100 }
  4. 🔢 Added 50 coins and 50 goods to player 2, now player 2 has 100 coins and 150 goods.
  5. 🚮 Deleted 1 player data.

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-typeorm-quickstart repository.

Connect with connection options

The following code establishes a connection to TiDB with options defined in the environment variables:

  1. // src/dataSource.ts
  2. // Load environment variables from .env file to process.env.
  3. require('dotenv').config();
  4. export const AppDataSource = new DataSource({
  5. type: "mysql",
  6. host: process.env.TIDB_HOST || '127.0.0.1',
  7. port: process.env.TIDB_PORT ? Number(process.env.TIDB_PORT) : 4000,
  8. username: process.env.TIDB_USER || 'root',
  9. password: process.env.TIDB_PASSWORD || '',
  10. database: process.env.TIDB_DATABASE || 'test',
  11. ssl: process.env.TIDB_ENABLE_SSL === 'true' ? {
  12. minVersion: 'TLSv1.2',
  13. ca: process.env.TIDB_CA_PATH ? fs.readFileSync(process.env.TIDB_CA_PATH) : undefined
  14. } : null,
  15. synchronize: process.env.NODE_ENV === 'development',
  16. logging: false,
  17. entities: [Player, Profile],
  18. migrations: [__dirname + "/migrations/**/*{.ts,.js}"],
  19. });

TypeORM - 图4

Note

For TiDB 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 to true.

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

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 = new Player('Alice', 100, 100);
  2. await this.dataSource.manager.save(player);

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 = await this.dataSource.manager.findOneBy(Player, {
  2. id: id
  3. });

For more information, refer to Query data.

Update data

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

  1. const player = await this.dataSource.manager.findOneBy(Player, {
  2. id: 101
  3. });
  4. player.goods += 50;
  5. await this.dataSource.manager.save(player);

For more information, refer to Update data.

Delete data

The following query deletes the Player with ID 101:

  1. await this.dataSource.manager.delete(Player, {
  2. id: 101
  3. });

For more information, refer to Delete data.

Execute raw SQL queries

The following query executes a raw SQL statement (SELECT VERSION() AS tidb_version;) and returns the version of the TiDB cluster:

  1. const rows = await dataSource.query('SELECT VERSION() AS tidb_version;');
  2. console.log(rows[0]['tidb_version']);

For more information, refer to TypeORM: DataSource API.

Useful notes

Foreign key constraints

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

  1. @Entity()
  2. export class ActionLog {
  3. @PrimaryColumn()
  4. id: number
  5. @ManyToOne((type) => Person, {
  6. createForeignKeyConstraints: false,
  7. })
  8. person: Person
  9. }

For more information, refer to the TypeORM FAQ and Foreign key constraints.

Next steps

Need help?

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