Connect to TiDB with Sequelize

TiDB is a MySQL-compatible database, and Sequelize is a popular ORM framework for Node.js.

In this tutorial, you can learn how to use TiDB and Sequelize to accomplish the following tasks:

  • Set up your environment.
  • Connect to your TiDB cluster using Sequelize.
  • Build and run your application. Optionally, you can find sample code snippets for basic CRUD operations.

Sequelize - 图1

Note

This tutorial works with TiDB Serverless, TiDB Dedicated, and TiDB Self-Hosted.

Prerequisites

To complete this tutorial, you need:

If you don’t have a TiDB cluster, you can create one as follows:

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.

Sequelize - 图2

Note

For complete code snippets and running instructions, refer to the tidb-samples/tidb-nodejs-sequelize-quickstart GitHub repository.

Step 1: Clone the sample app repository

Run the following commands in your terminal window to clone the sample code repository:

  1. git clone git@github.com:tidb-samples/tidb-nodejs-sequelize-quickstart.git
  2. cd tidb-nodejs-sequelize-quickstart

Step 2: Install dependencies

Run the following command to install the required packages (including sequelize) for the sample app:

  1. npm install

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

    Sequelize - 图3

    Note

    In Node.js applications, you don’t have to provide an SSL CA certificate, because Node.js uses the built-in Mozilla CA certificate by default when establishing the TLS (SSL) connection.

  4. Click Generate Password to create a random password.

    Sequelize - 图4

    Tip

    If you have generated a password before, you can either use the original password or click Reset Password to generate a new one.

  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_DB_NAME='test'
    6. TIDB_ENABLE_SSL='true'
  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_DB_NAME='test'
    6. TIDB_ENABLE_SSL='true'
    7. TIDB_CA_PATH='{path/to/ca}'
  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 on the connection dialog:

    1. TIDB_HOST='{host}'
    2. TIDB_PORT='4000'
    3. TIDB_USER='root'
    4. TIDB_PASSWORD='{password}'
    5. TIDB_DB_NAME='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: Run the sample app

Run the following command to execute the sample code:

  1. npm start

**Expected output(partial):**

  1. INFO (app/10117): Getting sequelize instance...
  2. Executing (default): SELECT 1+1 AS result
  3. Executing (default): DROP TABLE IF EXISTS `players`;
  4. Executing (default): CREATE TABLE IF NOT EXISTS `players` (`id` INTEGER NOT NULL auto_increment COMMENT 'The unique ID of the player.', `coins` INTEGER NOT NULL COMMENT 'The number of coins that the player had.', `goods` INTEGER NOT NULL COMMENT 'The number of goods that the player had.', `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB;
  5. Executing (default): SHOW INDEX FROM `players`
  6. Executing (default): INSERT INTO `players` (`id`,`coins`,`goods`,`createdAt`,`updatedAt`) VALUES (1,100,100,'2023-08-31 09:10:11','2023-08-31 09:10:11'),(2,200,200,'2023-08-31 09:10:11','2023-08-31 09:10:11'),(3,300,300,'2023-08-31 09:10:11','2023-08-31 09:10:11'),(4,400,400,'2023-08-31 09:10:11','2023-08-31 09:10:11'),(5,500,500,'2023-08-31 09:10:11','2023-08-31 09:10:11');
  7. Executing (default): SELECT `id`, `coins`, `goods`, `createdAt`, `updatedAt` FROM `players` AS `players` WHERE `players`.`coins` > 300;
  8. Executing (default): UPDATE `players` SET `coins`=?,`goods`=?,`updatedAt`=? WHERE `id` = ?
  9. Executing (default): DELETE FROM `players` WHERE `id` = 6

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

Connect to TiDB

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

  1. // src/lib/tidb.ts
  2. import { Sequelize } from 'sequelize';
  3. export function initSequelize() {
  4. return new Sequelize({
  5. dialect: 'mysql',
  6. host: process.env.TIDB_HOST || 'localhost', // TiDB host, for example: {gateway-region}.aws.tidbcloud.com
  7. port: Number(process.env.TIDB_PORT) || 4000, // TiDB port, default: 4000
  8. username: process.env.TIDB_USER || 'root', // TiDB user, for example: {prefix}.root
  9. password: process.env.TIDB_PASSWORD || 'root', // TiDB password
  10. database: process.env.TIDB_DB_NAME || 'test', // TiDB database name, default: test
  11. dialectOptions: {
  12. ssl:
  13. process.env?.TIDB_ENABLE_SSL === 'true' // (Optional) Enable SSL
  14. ? {
  15. minVersion: 'TLSv1.2',
  16. rejectUnauthorized: true,
  17. ca: process.env.TIDB_CA_PATH // (Optional) Path to the custom CA certificate
  18. ? readFileSync(process.env.TIDB_CA_PATH)
  19. : undefined,
  20. }
  21. : null,
  22. },
  23. }
  24. export async function getSequelize() {
  25. if (!sequelize) {
  26. sequelize = initSequelize();
  27. try {
  28. await sequelize.authenticate();
  29. logger.info('Connection has been established successfully.');
  30. } catch (error) {
  31. logger.error('Unable to connect to the database:');
  32. logger.error(error);
  33. throw error;
  34. }
  35. }
  36. return sequelize;
  37. }

Insert data

The following query creates a single Players record and returns a Players object:

  1. logger.info('Creating a new player...');
  2. const newPlayer = await playersModel.create({
  3. id: 6,
  4. coins: 600,
  5. goods: 600,
  6. });
  7. logger.info('Created a new player.');
  8. logger.info(newPlayer.toJSON());

For more information, refer to Insert data.

Query data

The following query returns a single Players record those coins are greater than 300:

  1. logger.info('Reading all players with coins > 300...');
  2. const allPlayersWithCoinsGreaterThan300 = await playersModel.findAll({
  3. where: {
  4. coins: {
  5. [Op.gt]: 300,
  6. },
  7. },
  8. });
  9. logger.info('Read all players with coins > 300.');
  10. logger.info(allPlayersWithCoinsGreaterThan300.map((p) => p.toJSON()));

For more information, refer to Query data.

Update data

The following query set 700 coins and 700 goods to the Players with ID 6 that was created in the Insert data section:

  1. logger.info('Updating the new player...');
  2. await newPlayer.update({ coins: 700, goods: 700 });
  3. logger.info('Updated the new player.');
  4. logger.info(newPlayer.toJSON());

For more information, refer to Update data.

Delete data

The following query deletes the Player record with ID 6 that was created in the Insert data section:

  1. logger.info('Deleting the new player...');
  2. await newPlayer.destroy();
  3. const deletedNewPlayer = await playersModel.findByPk(6);
  4. logger.info('Deleted the new player.');
  5. logger.info(deletedNewPlayer?.toJSON());

For more information, refer to Delete data.

Next steps

Need help?

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

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