|
| 1 | +--- |
| 2 | +title: TiDB Cloud Serverless Driver Kysely Tutorial |
| 3 | +summary: Learn how to use TiDB Cloud serverless driver with Kysely. |
| 4 | +--- |
| 5 | + |
| 6 | +# TiDB Cloud Serverless Driver Kysely Tutorial |
| 7 | + |
| 8 | +[Kysely](https://kysely.dev/docs/intro) is a type-safe and autocompletion-friendly TypeScript SQL query builder. TiDB Cloud offers [@tidbcloud/kysely](https://github.com/tidbcloud/kysely), enabling you to use Kysely over HTTPS with [TiDB Cloud serverless driver](/tidb-cloud/serverless-driver.md). Compared with the traditional TCP way, [@tidbcloud/kysely](https://github.com/tidbcloud/kysely) brings the following benefits: |
| 9 | + |
| 10 | +- Better performance in serverless environments. |
| 11 | +- Ability to use Kysely in edge environments. |
| 12 | + |
| 13 | +This tutorial describes how to use TiDB Cloud serverless driver with Kysely in Node.js environments and edge environments. |
| 14 | + |
| 15 | +## Use TiDB Cloud Kysely dialect in Node.js environments |
| 16 | + |
| 17 | +This section describes how to use TiDB Cloud serverless driver with Kysely in Node.js environments. |
| 18 | + |
| 19 | +### Before you begin |
| 20 | + |
| 21 | +To complete this tutorial, you need the following: |
| 22 | + |
| 23 | +- [Node.js](https://nodejs.org/en) >= 18.0.0. |
| 24 | +- [npm](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm) or your preferred package manager. |
| 25 | +- A TiDB Serverless cluster. If you don't have any, you can [create a TiDB Serverless cluster](/develop/dev-guide-build-cluster-in-cloud.md). |
| 26 | + |
| 27 | +### Step 1. Create a project |
| 28 | + |
| 29 | +1. Create a project named `kysely-node-example`: |
| 30 | + |
| 31 | + ``` |
| 32 | + mkdir kysely-node-example |
| 33 | + cd kysely-node-example |
| 34 | + ``` |
| 35 | +
|
| 36 | +2. Install the `kysely`, `@tidbcloud/kysely`, and `@tidbcloud/serverless` packages: |
| 37 | +
|
| 38 | + ``` |
| 39 | + npm install kysely @tidbcloud/kysely @tidbcloud/serverless |
| 40 | + ``` |
| 41 | +
|
| 42 | +3. In the root directory of your project, locate the `package.json` file, and then specify the ES module by adding `type: "module"` to the file: |
| 43 | +
|
| 44 | + ```json |
| 45 | + { |
| 46 | + "type": "module", |
| 47 | + "dependencies": { |
| 48 | + "@tidbcloud/kysely": "^0.0.4", |
| 49 | + "@tidbcloud/serverless": "^0.0.7", |
| 50 | + "kysely": "^0.26.3", |
| 51 | + } |
| 52 | + } |
| 53 | + ``` |
| 54 | + |
| 55 | +4. In the root directory of your project, add a `tsconfig.json` file to define the TypeScript compiler options. Here is an example file: |
| 56 | + |
| 57 | + ```json |
| 58 | + { |
| 59 | + "compilerOptions": { |
| 60 | + "module": "ES2022", |
| 61 | + "target": "ES2022", |
| 62 | + "moduleResolution": "node", |
| 63 | + "strict": false, |
| 64 | + "declaration": true, |
| 65 | + "outDir": "dist", |
| 66 | + "removeComments": true, |
| 67 | + "allowJs": true, |
| 68 | + "esModuleInterop": true, |
| 69 | + "resolveJsonModule": true |
| 70 | + } |
| 71 | + } |
| 72 | + ``` |
| 73 | + |
| 74 | +### Step 2. Set the environment |
| 75 | + |
| 76 | +1. On the overview page of your TiDB Serverless cluster, click **Connect** in the upper-right corner, and then get the connection string for your database from the displayed dialog. The connection string looks like this: |
| 77 | + |
| 78 | + ``` |
| 79 | + mysql://[username]:[password]@[host]/[database] |
| 80 | + ``` |
| 81 | +
|
| 82 | +2. Set the environment variable `DATABASE_URL` in your local environment. For example, in Linux or macOS, you can run the following command: |
| 83 | +
|
| 84 | + ```bash |
| 85 | + export DATABASE_URL='mysql://[username]:[password]@[host]/[database]' |
| 86 | + ``` |
| 87 | + |
| 88 | +### Step 3. Use Kysely to query data |
| 89 | +
|
| 90 | +1. Create a table in your TiDB Serverless cluster and insert some data. |
| 91 | +
|
| 92 | + You can use [Chat2Query in the TiDB Cloud console](/tidb-cloud/explore-data-with-chat2query.md) to execute SQL statements. Here is an example: |
| 93 | +
|
| 94 | + ```sql |
| 95 | + CREATE TABLE `test`.`person` ( |
| 96 | + `id` int(11) NOT NULL AUTO_INCREMENT, |
| 97 | + `name` varchar(255) NULL DEFAULT NULL, |
| 98 | + `gender` enum('male','female') NULL DEFAULT NULL, |
| 99 | + PRIMARY KEY (`id`) USING BTREE |
| 100 | + ); |
| 101 | + |
| 102 | + insert into test.person values (1,'pingcap','male') |
| 103 | + ``` |
| 104 | + |
| 105 | +2. In the root directory of your project, create a file named `hello-word.ts` and add the following code: |
| 106 | + |
| 107 | + ```ts |
| 108 | + import { Kysely,GeneratedAlways,Selectable } from 'kysely' |
| 109 | + import { TiDBServerlessDialect } from '@tidbcloud/kysely' |
| 110 | + |
| 111 | + // Types |
| 112 | + interface Database { |
| 113 | + person: PersonTable |
| 114 | + } |
| 115 | + |
| 116 | + interface PersonTable { |
| 117 | + id: GeneratedAlways<number> |
| 118 | + name: string |
| 119 | + gender: "male" | "female" |
| 120 | + } |
| 121 | + |
| 122 | + // Dialect |
| 123 | + const db = new Kysely<Database>({ |
| 124 | + dialect: new TiDBServerlessDialect({ |
| 125 | + url: process.env.DATABASE_URL |
| 126 | + }), |
| 127 | + }) |
| 128 | + |
| 129 | + // Simple Querying |
| 130 | + type Person = Selectable<PersonTable> |
| 131 | + export async function findPeople(criteria: Partial<Person> = {}) { |
| 132 | + let query = db.selectFrom('person') |
| 133 | + |
| 134 | + if (criteria.name){ |
| 135 | + query = query.where('name', '=', criteria.name) |
| 136 | + } |
| 137 | + |
| 138 | + return await query.selectAll().execute() |
| 139 | + } |
| 140 | + |
| 141 | + console.log(await findPeople()) |
| 142 | + ``` |
| 143 | + |
| 144 | +### Step 4. Run the Typescript code |
| 145 | + |
| 146 | +1. Install `ts-node` to transform TypeScript into JavaScript, and then install `@types/node` to provide TypeScript type definitions for Node.js. |
| 147 | + |
| 148 | + ``` |
| 149 | + npm install -g ts-node |
| 150 | + npm i --save-dev @types/node |
| 151 | + ``` |
| 152 | + |
| 153 | +2. Run the Typescript code with the following command: |
| 154 | + |
| 155 | + ``` |
| 156 | + ts-node --esm hello-world.ts |
| 157 | + ``` |
| 158 | + |
| 159 | +## Use TiDB Cloud Kysely dialect in edge environments |
| 160 | + |
| 161 | +This section takes the TiDB Cloud Kysely dialect in Vercel Edge Function as an example. |
| 162 | + |
| 163 | +### Before you begin |
| 164 | + |
| 165 | +To complete this tutorial, you need the following: |
| 166 | + |
| 167 | +- A [Vercel](https://vercel.com/docs) account that provides edge environment. |
| 168 | +- [npm](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm) or your preferred package manager. |
| 169 | +- A TiDB Serverless cluster. If you don't have any, you can [create a TiDB Serverless cluster](/develop/dev-guide-build-cluster-in-cloud.md). |
| 170 | + |
| 171 | +### Step 1. Create a project |
| 172 | + |
| 173 | +1. Install the Vercel CLI: |
| 174 | + |
| 175 | + ``` |
| 176 | + npm i -g vercel@latest |
| 177 | + ``` |
| 178 | +
|
| 179 | +2. Create a [Next.js](https://nextjs.org/) project called `kysely-example` using the following terminal commands: |
| 180 | +
|
| 181 | + ``` |
| 182 | + npx create-next-app@latest kysely-example --ts --no-eslint --tailwind --no-src-dir --app --import-alias "@/*" |
| 183 | + cd kysely-example |
| 184 | + ``` |
| 185 | + |
| 186 | +3. Install the `kysely`, `@tidbcloud/kysely`, and `@tidbcloud/serverless` packages: |
| 187 | +
|
| 188 | + ``` |
| 189 | + npm install kysely @tidbcloud/kysely @tidbcloud/serverless |
| 190 | + ``` |
| 191 | +
|
| 192 | +### Step 2. Set the environment |
| 193 | +
|
| 194 | +On the overview page of your TiDB Serverless cluster, click **Connect** in the upper-right corner, and then get the connection string for your database from the displayed dialog. The connection string looks like this: |
| 195 | +
|
| 196 | +``` |
| 197 | +mysql://[username]:[password]@[host]/[database] |
| 198 | +``` |
| 199 | +
|
| 200 | +### Step 3. Create an edge function |
| 201 | +
|
| 202 | +1. Create a table in your TiDB Serverless cluster and insert some data. |
| 203 | +
|
| 204 | + You can use [Chat2Query in the TiDB Cloud console](/tidb-cloud/explore-data-with-chat2query.md) to execute SQL statements. Here is an example: |
| 205 | +
|
| 206 | + ```sql |
| 207 | + CREATE TABLE `test`.`person` ( |
| 208 | + `id` int(11) NOT NULL AUTO_INCREMENT, |
| 209 | + `name` varchar(255) NULL DEFAULT NULL, |
| 210 | + `gender` enum('male','female') NULL DEFAULT NULL, |
| 211 | + PRIMARY KEY (`id`) USING BTREE |
| 212 | + ); |
| 213 | + |
| 214 | + insert into test.person values (1,'pingcap','male') |
| 215 | + ``` |
| 216 | + |
| 217 | +2. In the `app` directory of your project, create a file `/api/edge-function-example/route.ts` and add the following code: |
| 218 | + |
| 219 | + ```ts |
| 220 | + import { NextResponse } from 'next/server'; |
| 221 | + import type { NextRequest } from 'next/server'; |
| 222 | + import { Kysely,GeneratedAlways,Selectable } from 'kysely' |
| 223 | + import { TiDBServerlessDialect } from '@tidbcloud/kysely' |
| 224 | + |
| 225 | + export const runtime = 'edge'; |
| 226 | + |
| 227 | + // Types |
| 228 | + interface Database { |
| 229 | + person: PersonTable |
| 230 | + } |
| 231 | + |
| 232 | + interface PersonTable { |
| 233 | + id: GeneratedAlways<number> |
| 234 | + name: string |
| 235 | + gender: "male" | "female" | "other" |
| 236 | + } |
| 237 | + |
| 238 | + // Dialect |
| 239 | + const db = new Kysely<Database>({ |
| 240 | + dialect: new TiDBServerlessDialect({ |
| 241 | + url: process.env.DATABASE_URL |
| 242 | + }), |
| 243 | + }) |
| 244 | + |
| 245 | + // Query |
| 246 | + type Person = Selectable<PersonTable> |
| 247 | + async function findPeople(criteria: Partial<Person> = {}) { |
| 248 | + let query = db.selectFrom('person') |
| 249 | + |
| 250 | + if (criteria.name){ |
| 251 | + query = query.where('name', '=', criteria.name) |
| 252 | + } |
| 253 | + |
| 254 | + return await query.selectAll().execute() |
| 255 | + } |
| 256 | + |
| 257 | + export async function GET(request: NextRequest) { |
| 258 | + |
| 259 | + const searchParams = request.nextUrl.searchParams |
| 260 | + const query = searchParams.get('query') |
| 261 | + |
| 262 | + let response = null; |
| 263 | + if (query) { |
| 264 | + response = await findPeople({name: query}) |
| 265 | + } else { |
| 266 | + response = await findPeople() |
| 267 | + } |
| 268 | + |
| 269 | + return NextResponse.json(response); |
| 270 | + } |
| 271 | + ``` |
| 272 | + |
| 273 | + The preceding code accepts a query parameter `query` and returns the result of the query. If the query parameter is not provided, it returns all records in the `person` table. |
| 274 | + |
| 275 | +3. Test your code locally: |
| 276 | + |
| 277 | + ``` |
| 278 | + export DATABASE_URL='mysql://[username]:[password]@[host]/[database]' |
| 279 | + next dev |
| 280 | + ``` |
| 281 | + |
| 282 | +4. Navigate to `http://localhost:3000/api/edge-function-example` to get the response from your route. |
| 283 | + |
| 284 | +### Step 4. Deploy your code to Vercel |
| 285 | + |
| 286 | +1. Deploy your code to Vercel with the `DATABASE_URL` environment variable: |
| 287 | + |
| 288 | + ``` |
| 289 | + vercel -e DATABASE_URL='mysql://[username]:[password]@[host]/[database]' --prod |
| 290 | + ``` |
| 291 | + |
| 292 | + After the deployment is complete, you will get the URL of your project. |
| 293 | + |
| 294 | +2. Navigate to the `${Your-URL}/api/edge-function-example` page to get the response from your route. |
| 295 | + |
| 296 | +## What's next |
| 297 | + |
| 298 | +- Learn more about [Kysely](https://kysely.dev/docs/intro) and [@tidbcloud/kysely](https://github.com/tidbcloud/kysely) |
| 299 | +- Learn how to [integrate TiDB Cloud with Vercel](/tidb-cloud/integrate-tidbcloud-with-vercel.md) |
0 commit comments