Turso 快速入门(通过 HTTP 的 SQL)
通过几个简单步骤,开始使用 Turso 的 SQL over HTTP。
在本快速入门中,我们将学习如何:
- 连接到远程 Turso 数据库
- 使用 SQL over HTTP 执行 SQL 查询
@tursodatabase/serverless |
@libsql/client |
原始 HTTP | |
|---|---|---|---|
| 适用场景 | Turso 数据库 | libSQL 数据库 | 任意数据库 |
| 依赖项 | 仅使用 fetch — 零原生依赖 |
需要 Node.js 或 /web 子路径 |
无(任意 HTTP 客户端) |
| ORM 支持 | 尚不支持 | Drizzle、Prisma 等 | 不适用 |
请根据数据库引擎选择驱动:Turso 数据库使用 @tursodatabase/serverless,libSQL 数据库使用 @libsql/client。
@tursodatabase/serverless 包仅使用 fetch API 连接 Turso——没有原生依赖,使其成为边缘和无服务器运行时中最小的选项。
1. 安装
npm install @tursodatabase/serverless
2. 连接并查询
import { connect } from "@tursodatabase/serverless";
const conn = connect({
url: process.env.TURSO_DATABASE_URL,
authToken: process.env.TURSO_AUTH_TOKEN,
});
const stmt = await conn.prepare("SELECT * FROM users WHERE id = ?");
const row = await stmt.get([123]);
为了与 libSQL 客户端 API 兼容,请使用 compat 模块:
import { createClient } from "@tursodatabase/serverless/compat";
const client = createClient({
url: process.env.TURSO_DATABASE_URL,
authToken: process.env.TURSO_AUTH_TOKEN,
});
const result = await client.execute("SELECT * FROM users WHERE id = ?", [123]);
@libsql/client 包是 Turso 生态中广泛使用的生产级 libSQL 驱动。在无服务器和边缘运行时中使用 /web 导入。
1. 安装
npm install @libsql/client
2. 连接并查询
import { createClient } from "@libsql/client/web";
const client = createClient({
url: process.env.TURSO_DATABASE_URL!,
authToken: process.env.TURSO_AUTH_TOKEN!,
});
const result = await client.execute({
sql: "SELECT * FROM users WHERE id = ?",
args: [123],
});
[!NOTE]
在边缘和无服务器运行时中,请使用
@libsql/client/web而不是@libsql/client。/web导入使用 HTTP 协议。
你也可以使用任意 HTTP 客户端直接通过 HTTP 发送查询。
1. 创建 HTTP 数据库 URL
使用 Turso CLI 或 Platform API 获取数据库 URL:
turso db show <database-name> --http-url
[!NOTE]
将
/v2/pipeline追加到 URL 后继续。
2. 创建数据库认证令牌
使用 Turso CLI 或 Platform API 为数据库创建新的认证令牌:
turso db tokens create <database-name>
3. 创建 JSON 请求负载
我们将使用 JSON 发送查询,因此先创建一个 JSON 负载,用于执行 SQL 语句并立即关闭连接:
{
"requests": [
{ "type": "execute", "stmt": { "sql": "SELECT * FROM users" } },
{ "type": "close" }
]
}
[!NOTE]
请确保更新
stmt.sql,从你已有的表中选择数据。绑定参数示例见参考页面,
4. 执行 HTTP 请求
根据你使用的语言,可以使用 HTTP 客户端库将请求发送到已创建的 URL,并将 Authorization 请求头设置为已创建的令牌,同时将包含 SQL 语句的 JSON 作为请求体。
必须将实际接受请求的 pipeline URL——/v2/pipeline——追加到基础 URL 后面。
const url = "https://[databaseName]-[organizationSlug].turso.io/v2/pipeline";
const authToken = "...";
fetch(url, {
method: "POST",
headers: {
Authorization: `Bearer ${authToken}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
requests: [
{ type: "execute", stmt: { sql: "SELECT * FROM users" } },
{ type: "close" },
],
}),
})
.then((res) => res.json())
.then((data) => console.log(data))
.catch((err) => console.log(err));
require 'net/http'
require 'json'
require 'uri'
url = "https://[databaseName]-[organizationSlug].turso.io/v2/pipeline"
auth_token = "..."
uri = URI(url)
request = Net::HTTP::Post.new(uri)
request["Authorization"] = "Bearer #{auth_token}"
request["Content-Type"] = "application/json"
request.body = JSON.generate({
"requests": [
{ "type": "execute", "stmt": { "sql": "SELECT * FROM users" } },
{ "type": "close" }
]
})
begin
response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http|
http.request(request)
end
puts JSON.parse(response.body)
rescue => e
puts e.message
end
[accordion] 响应
响应将是一个包含
results数组的 JSON 对象,其中包含查询结果,类似如下:{ "baton": null, "base_url": null, "results": [ { "type": "ok", "response": { "type": "execute", "result": { "cols": [], "rows": [], "affected_row_count": 0, "last_insert_rowid": null, "replication_index": "1" } } }, { "type": "ok", "response": { "type": "close" } } ] }
如果需要为值使用占位符,可以这样做:
{
"type": "execute",
"stmt": {
"sql": "SELECT * FROM users WHERE id = ?",
"args": [
{
"type": "integer",
"value": "1"
}
]
}
}
{
"type": "execute",
"stmt": {
"sql": "SELECT * FROM users WHERE name = :name OR name = $second_name OR name = @third_name",
"named_args": [
{
"name": "name",
"value": {
"type": "text",
"value": "Turso"
}
},
{
"name": "second_name",
"value": {
"type": "text",
"value": "Not Turso"
}
},
{
"name": "third_name",
"value": {
"type": "text",
"value": "Maybe Turso"
}
}
]
}
}
[!NOTE]
每个 arg 中的
type字段对应列数据类型,可以是以下之一:null、integer、float、text或blob。
[!NOTE]
在 JSON 中,
value是String,以避免精度丢失,因为某些 JSON 实现将所有数字视为 64 位浮点数。