forked from Oreoxmt/pingcap-docs-website-scaffold
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Preview PR pingcap/docs#14532 and this preview is triggered from commit
- Loading branch information
github-actions
committed
Aug 22, 2023
1 parent
3be338a
commit 5653302
Showing
2 changed files
with
129 additions
and
105 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,43 +1,43 @@ | ||
--- | ||
title: Connect to TiDB by using mysql2 in AWS Lambda Function | ||
title: Build a CRUD Application with TiDB and AWS Lambda Function | ||
summary: This article describes how to connect TiDB using mysql2 in AWS Lambda Function and provides a simple example code snippet. | ||
--- | ||
|
||
<!-- markdownlint-disable MD024 --> | ||
<!-- markdownlint-disable MD029 --> | ||
|
||
# Connect to TiDB by using mysql2 in AWS Lambda Function | ||
# Build a CRUD Application with TiDB and mysql2 in AWS Lambda Function | ||
|
||
TiDB is a MySQL-compatible database. | ||
|
||
[mysql2](https://www.npmjs.com/package/mysql2) is one of the most popular open-source Node.js drivers. | ||
|
||
[AWS Lambda Function](https://aws.amazon.com/lambda/) is a serverless computing service provided by AWS. | ||
|
||
This document shows you how to use TiDB and mysql2 to build a simple CRUD application. | ||
This guide demonstrates how to use TiDB, a MySQL-compatible database, and [mysql2](https://www.npmjs.com/package/mysql2), a popular open-source Node.js driver, in an [AWS Lambda Function](https://aws.amazon.com/lambda/) to build a simple CRUD application. | ||
|
||
## Prerequisites | ||
|
||
Ensure you have the following installed and set up: | ||
|
||
- [Node.js **18**](https://nodejs.org/en/download/) or later. | ||
- [Git](https://git-scm.com/downloads). | ||
- A TiDB cluster running | ||
- A running TiDB cluster. | ||
- An [AWS account](https://repost.aws/knowledge-center/create-and-activate-aws-account). | ||
- An AWS user can access the Lambda function. | ||
- An AWS user with access to the Lambda function. | ||
|
||
**If you don't have a TiDB cluster yet, please create one with one of the following methods:** | ||
If you don't have a TiDB cluster yet, you can create one using one of the following methods: | ||
|
||
- (Recommended) Refer to [Create a TiDB Serverless cluster](/develop/dev-guide-build-cluster-in-cloud.md) to create your own TiDB Cloud cluster. | ||
- Refer to [Deploy a local test TiDB cluster](/quick-start-with-tidb.md) or [Deploy a formal TiDB cluster](/production-deployment-using-tiup.md) to create a local cluster. | ||
|
||
**If you don't have an AWS account and user, you can create them by following the steps in the [Getting started with Lambda](https://docs.aws.amazon.com/lambda/latest/dg/getting-started.html) guide.** | ||
If you don't have an AWS account and user, you can create them by following the steps in the [Getting started with Lambda](https://docs.aws.amazon.com/lambda/latest/dg/getting-started.html) guide. | ||
|
||
## Run the sample application | ||
|
||
This section shows you how to run the sample application code and connect to TiDB. | ||
|
||
> **Note:** Complete code snippets and how to run them, see [tidb-aws-lambda-quickstart](https://github.com/tidb-samples/tidb-aws-lambda-quickstart) GitHub repository. | ||
> **Note:** | ||
> | ||
> For complete code snippets and running instructions, refer to the[tidb-aws-lambda-quickstart](https://github.com/tidb-samples/tidb-aws-lambda-quickstart) GitHub repository. | ||
### Step 1: Clone the sample application repository | ||
|
||
### Step 1: Clone the sample application repository to your local machine | ||
Clone the repository to your local machine: | ||
|
||
```bash | ||
git clone [email protected]:tidb-samples/tidb-aws-lambda-quickstart.git | ||
|
@@ -46,13 +46,15 @@ cd tidb-aws-lambda-quickstart | |
|
||
### Step 2: Install dependencies | ||
|
||
Install the necessary dependencies: | ||
|
||
```bash | ||
npm install | ||
``` | ||
|
||
### Step 3: Configure the connection string | ||
|
||
Depending on the way you deploy TiDB, use different methods to connect to the TiDB cluster. | ||
The method to connect to the TiDB cluster varies based on your deployment method. | ||
|
||
<SimpleTab> | ||
|
||
|
@@ -62,36 +64,42 @@ Depending on the way you deploy TiDB, use different methods to connect to the Ti | |
|
||
2. In the connection dialog, select `General` from the **Connect With** dropdown and keep the default setting of the **Endpoint Type** as `Public`. | ||
|
||
> **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](https://wiki.mozilla.org/CA/Included_Certificates) by default when establishing the TLS (SSL) connection. | ||
> **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](https://wiki.mozilla.org/CA/Included_Certificates) by default when establishing the TLS (SSL) connection. | ||
3. If you have not set a password yet, click **Create password** to generate a random password. | ||
|
||
<Tip>If you have generated a password before, you can use the original password directly, or click **Reset password** to generate a new password.</Tip> | ||
|
||
4. Copy and paste the corresponding connection string to `env.json`. The following is an example: | ||
|
||
```json | ||
{ | ||
"Parameters": { | ||
"TIDB_HOST": "{gateway-region}.aws.tidbcloud.com", | ||
"TIDB_PORT": "4000", | ||
"TIDB_USER": "{prefix}.root", | ||
"TIDB_PASSWORD": "{password}" | ||
} | ||
} | ||
``` | ||
<Tip> | ||
|
||
If you have generated a password before, you can use the original password directly, or click **Reset password** to generate a new password. | ||
|
||
</Tip> | ||
|
||
4. Copy and paste the corresponding connection string into `env.json`. The following is an example: | ||
|
||
```json | ||
{ | ||
"Parameters": { | ||
"TIDB_HOST": "{gateway-region}.aws.tidbcloud.com", | ||
"TIDB_PORT": "4000", | ||
"TIDB_USER": "{prefix}.root", | ||
"TIDB_PASSWORD": "{password}" | ||
} | ||
} | ||
``` | ||
|
||
Replace the placeholders in `{}` with the values obtained in the connection dialog. | ||
Replace the placeholders in `{}` with the values obtained in the connection dialog. | ||
|
||
5. [Copy and configure the corresponding connection string](https://docs.aws.amazon.com/lambda/latest/dg/configuration-envvars.html) in Lambda Function. | ||
|
||
![quickstart-lambda-env](/media/develop/quickstart-lambda-env.png) | ||
![quickstart-lambda-env](/media/develop/quickstart-lambda-env.png) | ||
|
||
</div> | ||
|
||
<div label="TiDB Self-Hosted"> | ||
|
||
1. Copy and paste the corresponding connection string to `env.json`. The following is an example: | ||
1. Copy and paste the corresponding connection string into `env.json`. The following is an example: | ||
|
||
```json | ||
{ | ||
|
@@ -118,7 +126,7 @@ Depending on the way you deploy TiDB, use different methods to connect to the Ti | |
|
||
1. Install the [AWS SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/install-sam-cli.html). | ||
|
||
2. Run the following command to invoke the sample Lambda function: | ||
2. Invoke the sample Lambda function: | ||
|
||
```bash | ||
sam local invoke --env-vars env.json -e event.json "tidbHelloWorldFunction" | ||
|
@@ -130,7 +138,7 @@ Depending on the way you deploy TiDB, use different methods to connect to the Ti | |
{"statusCode":200,"body":"{\"results\":[{\"Hello World\":\"Hello World\"}]}"} | ||
``` | ||
|
||
## Example codes | ||
## Example code | ||
|
||
Complete code snippets are available in the [tidb-aws-lambda-quickstart](https://github.com/tidb-samples/tidb-aws-lambda-quickstart) GitHub repository. | ||
|
||
|
@@ -141,20 +149,35 @@ You can refer to the following key code snippets to complete your application de | |
```typescript | ||
import mysql from 'mysql2'; | ||
|
||
const pool = mysql.createPool({ | ||
host, // TiDB host, for example: {gateway-region}.aws.tidbcloud.com | ||
port, // TiDB port, default: 4000 | ||
user, // TiDB user, for example: {prefix}.root | ||
password, // TiDB password | ||
database, // TiDB database name, default: test | ||
ssl: { | ||
minVersion: 'TLSv1.2', | ||
rejectUnauthorized: true, | ||
}, | ||
connectionLimit: 1, | ||
maxIdle: 1, // max idle connections, the default value is the same as `connectionLimit` | ||
enableKeepAlive: true | ||
}); | ||
let pool: mysql.Pool; | ||
|
||
function connect() { | ||
pool = mysql.createPool({ | ||
host: process.env.TIDB_HOST, // TiDB host, for example: {gateway-region}.aws.tidbcloud.com | ||
port: process.env.TIDB_PORT || 4000, // TiDB port, default: 4000 | ||
user: process.env.TIDB_USER, // TiDB user, for example: {prefix}.root | ||
password: process.env.TIDB_PASSWORD, // TiDB password | ||
database: process.env.TIDB_DATABASE || 'test', // TiDB database name, default: test | ||
ssl: { | ||
minVersion: 'TLSv1.2', | ||
rejectUnauthorized: true, | ||
}, | ||
connectionLimit: 1, // Setting connectionLimit to "1" in a serverless function environment optimizes resource usage, reduces costs, ensures connection stability, and enables seamless scalability. | ||
maxIdle: 1, // max idle connections, the default value is the same as `connectionLimit` | ||
enableKeepAlive: true | ||
}); | ||
} | ||
|
||
export async function handler(event: any) { | ||
if (!pool) { | ||
connect(); | ||
} | ||
const results = await pool.execute('SELECT "Hello World"'); | ||
return { | ||
statusCode: 200, | ||
body: JSON.stringify({ results }), | ||
}; | ||
} | ||
``` | ||
|
||
### Insert data | ||
|
@@ -171,8 +194,8 @@ Refer to [Insert data](/develop/dev-guide-insert-data.md) for more information. | |
### Query data | ||
|
||
```typescript | ||
const results = await pool.execute('SELECT count(*) FROM player'); | ||
console.log(results); | ||
const [rows] = await pool.execute('SELECT count(*) AS cnt FROM player'); | ||
console.log(rows[0]['cnt']); | ||
``` | ||
|
||
Refer to [Query data](/develop/dev-guide-get-data-from-single-table.md) for more information. | ||
|
@@ -198,11 +221,7 @@ Refer to [Delete data](/develop/dev-guide-delete-data.md) for more information. | |
|
||
## Considerations | ||
|
||
- The driver lacks high encapsulation, resulting in visible SQL statements throughout the program. | ||
- Unlike ORM, `mysql2` represents the query object with a separate object instead of a data object. | ||
- While the Node.js driver is convenient, it requires manual control of transaction characteristics due to the absence of shielding the underlying implementation. | ||
- If SQL usage is not mandatory, it is advisable to utilize ORM for program development. | ||
- This approach(ORM) can reduce program coupling and enhance code maintainability. | ||
- It's recommended that using ORM frameworks to improve development efficiency in scenarios without a lot of complex SQL, such as [Sequelize](https://sequelize.org/), [Prisma](https://www.prisma.io/) and [TypeORM](https://typeorm.io/). | ||
|
||
## What's next | ||
|
||
|
Oops, something went wrong.