Skip to content

Commit 06bc52a

Browse files
authored
develop guide: add sample applications - sequelize (#14705) (#14922)
1 parent 3a5f614 commit 06bc52a

File tree

3 files changed

+327
-0
lines changed

3 files changed

+327
-0
lines changed

TOC-tidb-cloud.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@
4343
- [node-mysql2](/develop/dev-guide-sample-application-nodejs-mysql2.md)
4444
- [mysql.js](/develop/dev-guide-sample-application-nodejs-mysqljs.md)
4545
- [Prisma](/develop/dev-guide-sample-application-nodejs-prisma.md)
46+
- [Sequelize](/develop/dev-guide-sample-application-nodejs-sequelize.md)
4647
- [TypeORM](/develop/dev-guide-sample-application-nodejs-typeorm.md)
4748
- [Next.js](/develop/dev-guide-sample-application-nextjs.md)
4849
- [AWS Lambda](/develop/dev-guide-sample-application-aws-lambda.md)

TOC.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@
4141
- [node-mysql2](/develop/dev-guide-sample-application-nodejs-mysql2.md)
4242
- [mysql.js](/develop/dev-guide-sample-application-nodejs-mysqljs.md)
4343
- [Prisma](/develop/dev-guide-sample-application-nodejs-prisma.md)
44+
- [Sequelize](/develop/dev-guide-sample-application-nodejs-sequelize.md)
4445
- [TypeORM](/develop/dev-guide-sample-application-nodejs-typeorm.md)
4546
- [Next.js](/develop/dev-guide-sample-application-nextjs.md)
4647
- [AWS Lambda](/develop/dev-guide-sample-application-aws-lambda.md)
Lines changed: 325 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,325 @@
1+
---
2+
title: Connect to TiDB with Sequelize
3+
summary: Learn how to connect to TiDB using Sequelize. This tutorial gives Node.js sample code snippets that work with TiDB using Sequelize.
4+
---
5+
6+
# Connect to TiDB with Sequelize
7+
8+
TiDB is a MySQL-compatible database, and [Sequelize](https://sequelize.org/) is a popular ORM framework for Node.js.
9+
10+
In this tutorial, you can learn how to use TiDB and Sequelize to accomplish the following tasks:
11+
12+
- Set up your environment.
13+
- Connect to your TiDB cluster using Sequelize.
14+
- Build and run your application. Optionally, you can find [sample code snippets](#sample-code-snippets) for basic CRUD operations.
15+
16+
> **Note**
17+
>
18+
> This tutorial works with TiDB Serverless, TiDB Dedicated, and TiDB Self-Hosted.
19+
20+
## Prerequisites
21+
22+
To complete this tutorial, you need:
23+
24+
- [Node.js **18**](https://nodejs.org/en/download/) or later.
25+
- [Git](https://git-scm.com/downloads).
26+
- A TiDB cluster.
27+
28+
<CustomContent platform="tidb">
29+
30+
**If you don't have a TiDB cluster, you can create one as follows:**
31+
32+
- (Recommended) Follow [Creating a TiDB Serverless cluster](/develop/dev-guide-build-cluster-in-cloud.md) to create your own TiDB Cloud cluster.
33+
- Follow [Deploy a local test TiDB cluster](/quick-start-with-tidb.md#deploy-a-local-test-cluster) or [Deploy a production TiDB cluster](/production-deployment-using-tiup.md) to create a local cluster.
34+
35+
</CustomContent>
36+
<CustomContent platform="tidb-cloud">
37+
38+
**If you don't have a TiDB cluster, you can create one as follows:**
39+
40+
- (Recommended) Follow [Creating a TiDB Serverless cluster](/develop/dev-guide-build-cluster-in-cloud.md) to create your own TiDB Cloud cluster.
41+
- Follow [Deploy a local test TiDB cluster](https://docs.pingcap.com/tidb/stable/quick-start-with-tidb#deploy-a-local-test-cluster) or [Deploy a production TiDB cluster](https://docs.pingcap.com/tidb/stable/production-deployment-using-tiup) to create a local cluster.
42+
43+
</CustomContent>
44+
45+
## Run the sample app to connect to TiDB
46+
47+
This section demonstrates how to run the sample application code and connect to TiDB.
48+
49+
> **Note**
50+
>
51+
> For complete code snippets and running instructions, refer to the [tidb-samples/tidb-nodejs-sequelize-quickstart](https://github.com/tidb-samples/tidb-nodejs-sequelize-quickstart) GitHub repository.
52+
53+
### Step 1: Clone the sample app repository
54+
55+
Run the following commands in your terminal window to clone the sample code repository:
56+
57+
```bash
58+
git clone [email protected]:tidb-samples/tidb-nodejs-sequelize-quickstart.git
59+
cd tidb-nodejs-sequelize-quickstart
60+
```
61+
62+
### Step 2: Install dependencies
63+
64+
Run the following command to install the required packages (including `sequelize`) for the sample app:
65+
66+
```bash
67+
npm install
68+
```
69+
70+
### Step 3: Configure connection information
71+
72+
Connect to your TiDB cluster depending on the TiDB deployment option you've selected.
73+
74+
<SimpleTab>
75+
76+
<div label="TiDB Serverless">
77+
78+
1. Navigate to the [**Clusters**](https://tidbcloud.com/console/clusters) page, and then click the name of your target cluster to go to its overview page.
79+
80+
2. Click **Connect** in the upper-right corner. A connection dialog is displayed.
81+
82+
3. Ensure the configurations in the connection dialog match your operating environment.
83+
84+
- **Endpoint Type** is set to `Public`
85+
- **Connect With** is set to `General`
86+
- **Operating System** matches your environment.
87+
88+
> **Note**
89+
>
90+
> In Node.js applications, you don't have to provide an SSL CA certificate, because Node.js uses the built-in [Mozilla CA certificate](https://wiki.mozilla.org/CA/Included_Certificates) by default when establishing the TLS (SSL) connection.
91+
92+
4. Click **Create password** to create a random password.
93+
94+
> **Tip**
95+
>
96+
> If you have generated a password before, you can either use the original password or click **Reset password** to generate a new one.
97+
98+
5. Run the following command to copy `.env.example` and rename it to `.env`:
99+
100+
```shell
101+
cp .env.example .env
102+
```
103+
104+
6. Edit the `.env` file, set up the environment variables as follows, replace the corresponding placeholders `{}` with connection parameters on the connection dialog:
105+
106+
```dotenv
107+
TIDB_HOST='{host}'
108+
TIDB_PORT='4000'
109+
TIDB_USER='{user}'
110+
TIDB_PASSWORD='{password}'
111+
TIDB_DB_NAME='test'
112+
TIDB_ENABLE_SSL='true'
113+
```
114+
115+
7. Save the `.env` file.
116+
117+
</div>
118+
119+
<div label="TiDB Dedicated">
120+
121+
1. Navigate to the [**Clusters**](https://tidbcloud.com/console/clusters) page, and then click the name of your target cluster to go to its overview page.
122+
123+
2. Click **Connect** in the upper-right corner. A connection dialog is displayed.
124+
125+
3. Click **Allow Access from Anywhere** and then click **Download TiDB cluster CA** to download the CA certificate.
126+
127+
For more details about how to obtain the connection string, refer to [TiDB Dedicated standard connection](https://docs.pingcap.com/tidbcloud/connect-via-standard-connection).
128+
129+
4. Run the following command to copy `.env.example` and rename it to `.env`:
130+
131+
```shell
132+
cp .env.example .env
133+
```
134+
135+
5. Edit the `.env` file, set up the environment variables as follows, replace the corresponding placeholders `{}` with connection parameters on the connection dialog:
136+
137+
```shell
138+
TIDB_HOST='{host}'
139+
TIDB_PORT='4000'
140+
TIDB_USER='{user}'
141+
TIDB_PASSWORD='{password}'
142+
TIDB_DB_NAME='test'
143+
TIDB_ENABLE_SSL='true'
144+
TIDB_CA_PATH='{path/to/ca}'
145+
```
146+
147+
6. Save the `.env` file.
148+
149+
</div>
150+
151+
<div label="TiDB Self-Hosted">
152+
153+
1. Run the following command to copy `.env.example` and rename it to `.env`:
154+
155+
```shell
156+
cp .env.example .env
157+
```
158+
159+
2. Edit the `.env` file, set up the environment variables as follows, replace the corresponding placeholders `{}` with connection parameters on the connection dialog:
160+
161+
```shell
162+
TIDB_HOST='{host}'
163+
TIDB_PORT='4000'
164+
TIDB_USER='root'
165+
TIDB_PASSWORD='{password}'
166+
TIDB_DB_NAME='test'
167+
```
168+
169+
If you are running TiDB locally, the default host address is `127.0.0.1`, and the password is empty.
170+
171+
3. Save the `.env` file.
172+
173+
</div>
174+
175+
</SimpleTab>
176+
177+
### Step 4: Run the sample app
178+
179+
Run the following command to execute the sample code:
180+
181+
```shell
182+
npm start
183+
```
184+
185+
<details>
186+
<summary>**Expected output(partial):**</summary>
187+
188+
```shell
189+
INFO (app/10117): Getting sequelize instance...
190+
Executing (default): SELECT 1+1 AS result
191+
Executing (default): DROP TABLE IF EXISTS `players`;
192+
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;
193+
Executing (default): SHOW INDEX FROM `players`
194+
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');
195+
Executing (default): SELECT `id`, `coins`, `goods`, `createdAt`, `updatedAt` FROM `players` AS `players` WHERE `players`.`coins` > 300;
196+
Executing (default): UPDATE `players` SET `coins`=?,`goods`=?,`updatedAt`=? WHERE `id` = ?
197+
Executing (default): DELETE FROM `players` WHERE `id` = 6
198+
```
199+
200+
</details>
201+
202+
## Sample code snippets
203+
204+
You can refer to the following sample code snippets to complete your own application development.
205+
206+
For complete sample code and how to run it, check out the [tidb-samples/tidb-nodejs-sequelize-quickstart](https://github.com/tidb-samples/tidb-nodejs-sequelize-quickstart) repository.
207+
208+
### Connect to TiDB
209+
210+
The following code establish a connection to TiDB with options defined in the environment variables:
211+
212+
```typescript
213+
// src/lib/tidb.ts
214+
import { Sequelize } from 'sequelize';
215+
216+
export function initSequelize() {
217+
return new Sequelize({
218+
dialect: 'mysql',
219+
host: process.env.TIDB_HOST || 'localhost', // TiDB host, for example: {gateway-region}.aws.tidbcloud.com
220+
port: Number(process.env.TIDB_PORT) || 4000, // TiDB port, default: 4000
221+
username: process.env.TIDB_USER || 'root', // TiDB user, for example: {prefix}.root
222+
password: process.env.TIDB_PASSWORD || 'root', // TiDB password
223+
database: process.env.TIDB_DB_NAME || 'test', // TiDB database name, default: test
224+
dialectOptions: {
225+
ssl:
226+
process.env?.TIDB_ENABLE_SSL === 'true' // (Optional) Enable SSL
227+
? {
228+
minVersion: 'TLSv1.2',
229+
rejectUnauthorized: true,
230+
ca: process.env.TIDB_CA_PATH // (Optional) Path to the custom CA certificate
231+
? readFileSync(process.env.TIDB_CA_PATH)
232+
: undefined,
233+
}
234+
: null,
235+
},
236+
}
237+
238+
export async function getSequelize() {
239+
if (!sequelize) {
240+
sequelize = initSequelize();
241+
try {
242+
await sequelize.authenticate();
243+
logger.info('Connection has been established successfully.');
244+
} catch (error) {
245+
logger.error('Unable to connect to the database:');
246+
logger.error(error);
247+
throw error;
248+
}
249+
}
250+
return sequelize;
251+
}
252+
```
253+
254+
### Insert data
255+
256+
The following query creates a single `Players` record and returns a `Players` object:
257+
258+
```typescript
259+
logger.info('Creating a new player...');
260+
const newPlayer = await playersModel.create({
261+
id: 6,
262+
coins: 600,
263+
goods: 600,
264+
});
265+
logger.info('Created a new player.');
266+
logger.info(newPlayer.toJSON());
267+
```
268+
269+
For more information, refer to [Insert data](/develop/dev-guide-insert-data.md).
270+
271+
### Query data
272+
273+
The following query returns a single `Players` record those coins are greater than `300`:
274+
275+
```typescript
276+
logger.info('Reading all players with coins > 300...');
277+
const allPlayersWithCoinsGreaterThan300 = await playersModel.findAll({
278+
where: {
279+
coins: {
280+
[Op.gt]: 300,
281+
},
282+
},
283+
});
284+
logger.info('Read all players with coins > 300.');
285+
logger.info(allPlayersWithCoinsGreaterThan300.map((p) => p.toJSON()));
286+
```
287+
288+
For more information, refer to [Query data](/develop/dev-guide-get-data-from-single-table.md).
289+
290+
### Update data
291+
292+
The following query set `700` coins and `700` goods to the `Players` with ID `6` that was created in the [Insert data](#insert-data) section:
293+
294+
```typescript
295+
logger.info('Updating the new player...');
296+
await newPlayer.update({ coins: 700, goods: 700 });
297+
logger.info('Updated the new player.');
298+
logger.info(newPlayer.toJSON());
299+
```
300+
301+
For more information, refer to [Update data](/develop/dev-guide-update-data.md).
302+
303+
### Delete data
304+
305+
The following query deletes the `Player` record with ID `6` that was created in the [Insert data](#insert-data) section:
306+
307+
```typescript
308+
logger.info('Deleting the new player...');
309+
await newPlayer.destroy();
310+
const deletedNewPlayer = await playersModel.findByPk(6);
311+
logger.info('Deleted the new player.');
312+
logger.info(deletedNewPlayer?.toJSON());
313+
```
314+
315+
For more information, refer to [Delete data](/develop/dev-guide-delete-data.md).
316+
317+
## Next steps
318+
319+
- Learn more usage of the ORM framework Sequelize driver from [the documentation of Sequelize](https://sequelize.org/).
320+
- Learn the best practices for TiDB application development with the chapters in the [Developer guide](/develop/dev-guide-overview.md), such as [Insert data](/develop/dev-guide-insert-data.md), [Update data](/develop/dev-guide-update-data.md), [Delete data](/develop/dev-guide-delete-data.md), [Single table reading](/develop/dev-guide-get-data-from-single-table.md), [Transactions](/develop/dev-guide-transaction-overview.md), and [SQL performance optimization](/develop/dev-guide-optimize-sql-overview.md).
321+
- Learn through the professional [TiDB developer courses](https://www.pingcap.com/education/) and earn [TiDB certifications](https://www.pingcap.com/education/certification/) after passing the exam.
322+
323+
## Need help?
324+
325+
Ask questions on the [Discord](https://discord.gg/DQZ2dy3cuc?utm_source=doc), or [create a support ticket](https://support.pingcap.com/).

0 commit comments

Comments
 (0)