TiDBTiDB Docs Dash 2024

Jan 9 - Jan 12 (UTC)
Join us to improve docs and win a prize!
Sign InTry Free

TiDB Cloud Serverless Driver (Beta)

TiDB Cloud serverless driver (Beta) for JavaScript allows you to connect to your TiDB Serverless cluster over HTTPS. It is particularly useful in edge environments where TCP connections are limited, such as Vercel Edge Functions and Cloudflare Workers.

Install the serverless driver

You can install the driver with npm:

npm install @tidbcloud/serverless

Use the serverless driver

You can use the serverless driver to query data of a TiDB Serverless cluster or perform interactive transactions.

Query

To query data from a TiDB Serverless cluster, you need to create a connection first. Then you can use the connection to execute raw SQL queries. For example:

import { connect } from '@tidbcloud/serverless' const conn = connect({url: 'mysql://[username]:[password]@[host]/[database]'}) const results = await conn.execute('select * from test where id = ?',[1])

Transaction (experimental)

You can also perform interactive transactions with the serverless driver. For example:

import { connect } from '@tidbcloud/serverless' const conn = connect({url: 'mysql://[username]:[password]@[host]/[database]'}) const tx = await conn.begin() try { await tx.execute('insert into test values (1)') await tx.execute('select * from test') await tx.commit() }catch (err) { await tx.rollback() throw err }

Edge examples

Here are some examples of using the serverless driver in edge environments. For a complete example, you can also try this live demo.

  • Vercel Edge Function
  • Cloudflare Workers
  • Netlify Edge Function
  • Deno
  • Bun
import { NextResponse } from 'next/server'; import type { NextRequest } from 'next/server'; import { connect } from '@tidbcloud/serverless' export const runtime = 'edge' export async function GET(request: NextRequest) { const conn = connect({url: process.env.DATABASE_URL}) const result = await conn.execute('show tables') return NextResponse.json({result}); }

Learn more about using TiDB Cloud serverless driver in Vercel.

import { connect } from '@tidbcloud/serverless' export interface Env { DATABASE_URL: string; } export default { async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> { const conn = connect({url: env.DATABASE_URL}) const result = await conn.execute('show tables') return new Response(JSON.stringify(result)); }, };

Learn more about using TiDB Cloud serverless driver in Cloudflare Workers.

import { connect } from 'https://esm.sh/@tidbcloud/serverless' export default async () => { const conn = connect({url: Netlify.env.get('DATABASE_URL')}) const result = await conn.execute('show tables') return new Response(JSON.stringify(result)); }

Learn more about using TiDB Cloud serverless driver in Netlify.

import { connect } from "npm:@tidbcloud/serverless-js" const conn = connect({url: Deno.env.get('DATABASE_URL')}) const result = await conn.execute('show tables')
import { connect } from "@tidbcloud/serverless-js" const conn = connect({url: Bun.env.DATABASE_URL}) const result = await conn.execute('show tables')

Configure the serverless driver

You can configure TiDB Cloud serverless driver at both the connection level and the SQL level.

Connection level configurations

At the connection level, you can make the following configurations:

NameTypeDefault valueDescription
usernamestringN/AUsername of TiDB Serverless
passwordstringN/APassword of TiDB Serverless
hoststringN/AHostname of TiDB Serverless
databasestringtestDatabase of TiDB Serverless
urlstringN/AThe URL for the database, in the mysql://[username]:[password]@[host]/[database] format, where database can be skipped if you intend to connect to the default database.
fetchfunctionglobal fetchCustom fetch function. For example, you can use the undici fetch in node.js.
arrayModeboolfalseWhether to return results as arrays instead of objects. To get better performance, set it to true.
fullResultboolfalseWhether to return full result object instead of just rows. To get more detailed results, set it to true.

Database URL

When url is configured, there is no need to configure host, username, password, and database separately. The following codes are equivalent:

const config = { host: '<host>', username: '<user>', password: '<password>', database: '<database>', arrayMode: true, } const conn = connect(config)
const config = { url: process.env['DATABASE_URL'] || 'mysql://[username]:[password]@[host]/[database]', arrayMode: true } const conn = connect(config)

SQL level options

At the SQL level, you can configure the following options:

OptionTypeDefault valueDescription
arrayModeboolfalseWhether to return results as arrays instead of objects. To get better performance, set it to true.
fullResultboolfalseWhether to return full result object instead of just rows. To get more detailed results, set it to true.

For example:

const conn = connect({url: process.env['DATABASE_URL'] || 'mysql://[username]:[password]@[host]/[database]'}) const results = await conn.execute('select * from test',null,{arrayMode:true,fullResult:true})

Starting from TiDB Cloud serverless driver v0.0.7, you can also configure the following SQL level option when you use transactions:

OptionTypeDefault valueDescription
isolationstringREPEATABLE READThe transaction isolation level, which can be set to READ COMMITTED or REPEATABLE READ.

The isolation option can only be used in the begin function. Here is an example:

const conn = connect({url: 'mysql://[username]:[password]@[host]/[database]'}) const tx = await conn.begin({isolation:"READ COMMITTED"})

Features

Supported SQL statements

DDL is supported and the following SQL statements are supported: SELECT, SHOW, EXPLAIN, USE, INSERT, UPDATE, DELETE, BEGIN, COMMIT, ROLLBACK, and SET.

Data type mapping

The type mapping between TiDB Serverless and Javascript is as follows:

TiDB Serverless typeJavascript type
TINYINTnumber
UNSIGNED TINYINTnumber
BOOLnumber
SMALLINTnumber
UNSIGNED SMALLINTnumber
MEDIUMINTnumber
INTnumber
UNSIGNED INTnumber
YEARnumber
FLOATnumber
DOUBLEnumber
BIGINTstring
UNSIGNED BIGINTstring
DECIMALstring
CHARstring
VARCHARstring
BINARYstring
VARBINARYstring
TINYTEXTstring
TEXTstring
MEDIUMTEXTstring
LONGTEXTstring
TINYBLOBstring
BLOBstring
MEDIUMBLOBstring
LONGBLOBstring
DATEstring
TIMEstring
DATETIMEstring
TIMESTAMPstring
ENUMstring
SETstring
BITstring
JSONobject
NULLnull
Othersstring

ORM integrations

TiDB Cloud serverless driver has been integrated with the following ORMs:

Pricing

The serverless driver itself is free, but accessing data with the driver generates Request Units (RUs) and storage usage. The pricing follows the TiDB Serverless pricing model.

Limitations

Currently, using serverless driver has the following limitations:

  • Up to 10,000 rows can be fetched in a single query.
  • You can execute only a single SQL statement at a time. Multiple SQL statements in one query are not supported yet.
  • Connection with private endpoints is not supported yet.

What's next

Was this page helpful?

Download PDFRequest docs changesAsk questions on Discord
Playground
New
One-stop & interactive experience of TiDB's capabilities WITHOUT registration.
Products
TiDB
TiDB Dedicated
TiDB Serverless
Pricing
Get Demo
Get Started
© 2024 PingCAP. All Rights Reserved.
Privacy Policy.