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.
Note
This tutorial works with TiDB Serverless, TiDB Dedicated, and TiDB Self-Hosted.
Prerequisites
To complete this tutorial, you need:
- Node.js 18 or later.
- Git.
- A TiDB cluster.
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.
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.
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:
git clone git@github.com:tidb-samples/tidb-nodejs-sequelize-quickstart.git
cd tidb-nodejs-sequelize-quickstart
Step 2: Install dependencies
Run the following command to install the required packages (including sequelize
) for the sample app:
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
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
- Branch is set to
main
- Connect With is set to
General
- Operating System matches your environment.
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.
- Endpoint Type is set to
Click Generate Password to create a random password.
Tip
If you have generated a password before, you can either use the original password or click Reset Password to generate a new one.
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_DB_NAME='test'
TIDB_ENABLE_SSL='true'
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.
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 .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_DB_NAME='test'
TIDB_ENABLE_SSL='true'
TIDB_CA_PATH='{path/to/ca}'
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 on the connection dialog:TIDB_HOST='{host}'
TIDB_PORT='4000'
TIDB_USER='root'
TIDB_PASSWORD='{password}'
TIDB_DB_NAME='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.
Step 4: Run the sample app
Run the following command to execute the sample code:
npm start
**Expected output(partial):**
INFO (app/10117): Getting sequelize instance...
Executing (default): SELECT 1+1 AS result
Executing (default): DROP TABLE IF EXISTS `players`;
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;
Executing (default): SHOW INDEX FROM `players`
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');
Executing (default): SELECT `id`, `coins`, `goods`, `createdAt`, `updatedAt` FROM `players` AS `players` WHERE `players`.`coins` > 300;
Executing (default): UPDATE `players` SET `coins`=?,`goods`=?,`updatedAt`=? WHERE `id` = ?
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:
// src/lib/tidb.ts
import { Sequelize } from 'sequelize';
export function initSequelize() {
return new Sequelize({
dialect: 'mysql',
host: process.env.TIDB_HOST || 'localhost', // TiDB host, for example: {gateway-region}.aws.tidbcloud.com
port: Number(process.env.TIDB_PORT) || 4000, // TiDB port, default: 4000
username: process.env.TIDB_USER || 'root', // TiDB user, for example: {prefix}.root
password: process.env.TIDB_PASSWORD || 'root', // TiDB password
database: process.env.TIDB_DB_NAME || 'test', // TiDB database name, default: test
dialectOptions: {
ssl:
process.env?.TIDB_ENABLE_SSL === 'true' // (Optional) Enable SSL
? {
minVersion: 'TLSv1.2',
rejectUnauthorized: true,
ca: process.env.TIDB_CA_PATH // (Optional) Path to the custom CA certificate
? readFileSync(process.env.TIDB_CA_PATH)
: undefined,
}
: null,
},
}
export async function getSequelize() {
if (!sequelize) {
sequelize = initSequelize();
try {
await sequelize.authenticate();
logger.info('Connection has been established successfully.');
} catch (error) {
logger.error('Unable to connect to the database:');
logger.error(error);
throw error;
}
}
return sequelize;
}
Insert data
The following query creates a single Players
record and returns a Players
object:
logger.info('Creating a new player...');
const newPlayer = await playersModel.create({
id: 6,
coins: 600,
goods: 600,
});
logger.info('Created a new player.');
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
:
logger.info('Reading all players with coins > 300...');
const allPlayersWithCoinsGreaterThan300 = await playersModel.findAll({
where: {
coins: {
[Op.gt]: 300,
},
},
});
logger.info('Read all players with coins > 300.');
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:
logger.info('Updating the new player...');
await newPlayer.update({ coins: 700, goods: 700 });
logger.info('Updated the new player.');
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:
logger.info('Deleting the new player...');
await newPlayer.destroy();
const deletedNewPlayer = await playersModel.findByPk(6);
logger.info('Deleted the new player.');
logger.info(deletedNewPlayer?.toJSON());
For more information, refer to Delete data.
Next steps
- Learn more usage of the ORM framework Sequelize driver from the documentation of Sequelize.
- Learn the best practices for TiDB application development with the chapters in the Developer guide, such as Insert data, Update data, Delete data, Single table reading, Transactions, and SQL performance optimization.
- Learn through the professional TiDB developer courses and earn TiDB certifications after passing the exam.
Need help?
Ask questions on the Discord, or create a support ticket.