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 相容,請使用相容模組:
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]
在 URL 後方附加
/v2/pipeline再繼續。
2. 建立資料庫驗證權杖
使用 Turso CLI 或 Platform API,為你的資料庫建立新的驗證權杖:
turso db tokens create <database-name>
3. 建立 JSON 請求承載內容
我們將以 JSON 傳送查詢,因此先建立一個會執行 SQL 陳述式並立即關閉連線的 JSON 承載內容:
{
"requests": [
{ "type": "execute", "stmt": { "sql": "SELECT * FROM users" } },
{ "type": "close" }
]
}
[!NOTE]
請務必將
stmt.sql更新為從你已經擁有的資料表進行查詢。綁定參數的範例收錄於參考頁面。
4. 執行 HTTP 請求
視你使用的語言而定,你可以使用 HTTP 用戶端函式庫,將請求傳送至你建立的 URL,並將 Authorization 標頭設為你建立的權杖,請求主體則以 JSON 攜帶你的 SQL 陳述式。
你必須在基底 URL 後方附加實際接受請求的 pipeline URL — /v2/pipeline。
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] 回應
回應會是一個 JSON 物件,其中包含
results陣列,內含你查詢的結果,看起來大致如下:{ "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 位元浮點數。