# SQL over HTTP 參考

> SQL over HTTP 參考 — Turso 文件。
> Canonical HTML: https://tursodb.cn/zh-tw/docs/sdk/http/reference/
> Upstream Source (MIT): https://docs.turso.tech/sdk/http/reference
> Language: zh-TW

---
Turso 資料庫可透過 HTTP 存取。此 API 讓開發人員能夠使用 [SQL over HTTP](https://github.com/tursodatabase/libsql/blob/main/docs/HTTP_V2_SPEC.md) 執行 SQL 操作、擷取伺服器版本資訊，並監控健康狀態。

<div class="doc-callout doc-callout-info"><div class="doc-callout-title">注意</div><div class="doc-callout-body">

建議您使用[原生 SDK](https://docs.turso.tech/sdk)。

</div></div>


## 基底 URL

只需將資料庫 URL 的通訊協定（Turso 資料庫為 `turso://`，libSQL 資料庫為 `libsql://`）替換為 `https://`：

```bash
https://[databaseName]-[organizationSlug].turso.io
```

您可以透過 Turso CLI 取得資料庫的基底 URL：

<details class="doc-accordion"><summary>使用 Turso CLI 取得 HTTP URL</summary><div class="doc-accordion-body">

```bash
turso db show <database-name> --http-url
```

</div></details>


## 驗證

Turso 使用 Bearer 驗證，並要求在所有受保護的請求中，透過 `Authorization` 標頭傳遞您的 API 權杖：

```bash
Authorization: Bearer TOKEN
```

<details class="doc-accordion"><summary>使用 Turso CLI 建立權杖</summary><div class="doc-accordion-body">

```bash
turso db tokens create <database-name>
```

</div></details>


## 端點

您的資料庫提供下列端點：

### `POST /v2/pipeline`

您可以使用 `/v2/pipeline` 端點查詢資料庫。此端點接受一系列要對資料庫連線執行的操作。支援的操作類型如下：

* `execute`：在連線上執行陳述式。
* `close`：關閉連線。

#### 簡單查詢

```json Request
{
  "requests": [
    { "type": "execute", "stmt": { "sql": "CREATE TABLE users (name)" } },
    { "type": "close" }
  ]
}
```

```json Response
{
  "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"
      }
    }
  ]
}
```

<div class="doc-callout doc-callout-info"><div class="doc-callout-title">注意</div><div class="doc-callout-body">

除非您在請求中明確關閉連線（如上所示），否則連線會保持開啟直到逾時。每次在連線上發出請求都會延長逾時時間。不再需要連線時，您應將其關閉。

</div></div>


#### 參數綁定

帶有綁定參數的查詢分為兩種類型：

1. 位置查詢參數，依其在參數清單中的位置綁定，並以 `?` 為前置符號。若查詢使用位置參數，值應以陣列形式提供給 `args` 欄位。

```json Request
{
  "requests": [
    {
      "type": "execute",
      "stmt": {
        "sql": "SELECT * FROM users WHERE name = ?",
        "args": [
          {
            "type": "text",
            "value": "Turso"
          }
        ]
      }
    },
    {
      "type": "close"
    }
  ]
}
```

```json Response
{
  "baton": null,
  "base_url": null,
  "results": [
    {
      "type": "ok",
      "response": {
        "type": "execute",
        "result": {
          "cols": [
            {
              "name": "name",
              "decltype": "TEXT"
            }
          ],
          "rows": [
            [
              {
                "type": "text",
                "value": "Turso"
              }
            ]
          ],
          "affected_row_count": 0,
          "last_insert_rowid": null
        }
      }
    },
    {
      "type": "ok",
      "response": {
        "type": "close"
      }
    }
  ]
}
```

2. 具名綁定參數，參數以名稱表示，並以 `:`、`@` 或 `$` 為前置符號。若查詢使用具名參數，則查詢的 `named_args` 欄位應為物件陣列，將參數對應至其值。

```json Request
{
  "requests": [
    {
      "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"
            }
          }
        ]
      }
    },
    {
      "type": "close"
    }
  ]
}
```

```json Response
{
  "baton": null,
  "base_url": null,
  "results": [
    {
      "type": "ok",
      "response": {
        "type": "execute",
        "result": {
          "cols": [
            {
              "name": "name",
              "decltype": "TEXT"
            }
          ],
          "rows": [
            [
              {
                "type": "text",
                "value": "Turso"
              }
            ]
          ],
          "affected_row_count": 0,
          "last_insert_rowid": null
        }
      }
    },
    {
      "type": "ok",
      "response": {
        "type": "close"
      }
    }
  ]
}
```

<div class="doc-callout doc-callout-info"><div class="doc-callout-title">注意</div><div class="doc-callout-body">

每個 `named_args` 的 `name` 屬性可以包含前置符號，也可以省略前置符號。上述範例省略了前置符號，但兩種寫法皆有效。

每個引數內的 `type` 欄位對應欄位資料類型，可為下列其中之一：`null`、`integer`、`float`、`text` 或 `blob`。

</div></div>


<div class="doc-callout doc-callout-info"><div class="doc-callout-title">注意</div><div class="doc-callout-body">

若使用 `blob` 類型，請將 `value` 屬性替換為 `base64`，並在傳送請求前將引數編碼為 `base64`。

</div></div>


<div class="doc-callout doc-callout-info"><div class="doc-callout-title">注意</div><div class="doc-callout-body">

在 JSON 中，`value` 是 `String`，以避免失去精度，因為某些 JSON 實作會將所有數字視為 64 位元浮點數。

</div></div>


#### 互動式查詢

有時可能需要在同一個連線上透過多次往返執行多個操作。我們可以不要立即關閉連線來達成：

```json Body
{
  "requests": [{ "type": "execute", "stmt": { "sql": "BEGIN" } }]
}
```

```json Response
{
  "baton": "m7lVVgEvknpf1P1irxHsHqrAqH7BLiwO4DQIAwr93PdZWGvdBNugLSokSsCZNkry",
  "base_url": null,
  "results": [
    {
      "type": "ok",
      "response": {
        "type": "execute",
        "result": {
          "cols": [],
          "rows": [],
          "affected_row_count": 0,
          "last_insert_rowid": null,
          "replication_index": "1"
        }
      }
    }
  ]
}
```

可以看到我們收到了傳回的 `baton`。這是因為我們尚未關閉連線。現在我們可以使用這個 baton 在同一個連線上執行更多查詢：

```json Body
{
  "baton": "m7lVVgEvknpf1P1irxHsHqrAqH7BLiwO4DQIAwr93PdZWGvdBNugLSokSsCZNkry",
  "requests": [
    { "type": "execute", "stmt": { "sql": "CREATE TABLE users (name)" } },
    {
      "type": "execute",
      "stmt": { "sql": "INSERT INTO users VALUES (\"iku\")" }
    },
    { "type": "execute", "stmt": { "sql": "COMMIT" } },
    { "type": "close" }
  ]
}
```

<div class="doc-callout doc-callout-info"><div class="doc-callout-title">注意</div><div class="doc-callout-body">

請注意，交易與連線都有逾時限制。交易必須在 5 秒內完成，而連線在閒置 10 秒後會關閉。

</div></div>


#### 回應類型

回應包含下列欄位：

| 欄位 | 類型 | 說明 |
| - | - | - |
| `baton` | string | baton 用於識別與伺服器之間的連線，以便重複使用。 |
| `base_url` | string | 處理請求之伺服器的基底 URL。此 URL 可用於後續請求，以強制將請求路由至該伺服器。 |
| `results` | array | 管道中每個請求的結果。 |

`results` 陣列包含管道中每個請求的結果。每個結果包含下列欄位：

| 欄位 | 類型 | 說明 |
| - | - | - |
| `cols` | array | 傳回資料列的欄位清單。 |
| `rows` | array | 查詢傳回的資料列。 |
| `affected_row_count` | integer | 查詢影響的資料列數。 |
| `last_insert_rowid` | integer | 最後插入資料列的 ID。 |
| `replication_index` | string | 執行此查詢時的複寫時間戳記。 |
| `rows_read` | integer | 查詢讀取的資料列數。 |
| `rows_written` | integer | 查詢寫入的資料列數。 |
| `query_duration_ms` | float | 查詢持續時間（毫秒）。 |

### `GET /version`

若要取得執行您資料庫之伺服器的目前版本，您可以使用 `/version` 端點：

```bash Request
curl -L -X GET 'https://[databaseName]-[organizationSlug].turso.io/version' \
  -H 'Authorization: Bearer TOKEN'
```

```plaintext 200
sqld 0.21.9 (67f3ea5d 2023-10-26)
```

### `GET /health`

若要檢查資料庫的健康狀態，您可以使用 `/health` 端點，它會傳回空白內容並附帶 HTTP 狀態碼：

```bash Request
curl -L -X GET 'https://[databaseName]-[organizationSlug].turso.io/health' \
  -H 'Authorization: Bearer TOKEN'
```

```plaintext 200
This response has no body data.
```

### `GET /dump`

您可以使用 `/dump` 端點傾印資料庫：

```bash Request
curl -L -X GET 'https://[databaseName]-[organizationSlug].turso.io/dump' \
  -H 'Authorization: Bearer TOKEN'
```

```plaintext 200
PRAGMA foreign_keys=OFF;
BEGIN TRANSACTION;
CREATE TABLE IF NOT EXISTS mytable (
content TEXT,
embedding FLOAT32(1536)
);
CREATE TABLE IF NOT EXISTS libsql_vector_index (type TEXT, name TEXT, vector_type TEXT, block_size INTEGER, dims INTEGER, distance_ops TEXT);
INSERT INTO libsql_vector_index VALUES('diskann','mytable_idx','float32',128,1536,'cosine');
CREATE INDEX mytable_idx USING diskann_cosine_ops ON mytable (embedding);
COMMIT;
```

如果您使用 [multi-db schemas](/zh-tw/docs/features/multi-db-schemas/) 或向量資料庫，您會看到代表內部管理資料表的陳述式。

## 結構描述遷移狀態

Turso 提供受管的多租戶結構描述系統——[Multi-DB Schemas](/zh-tw/docs/features/multi-db-schemas/)。此功能可讓您建立單一資料庫，並自動與任何相關的子資料庫共用其結構描述。父資料庫的變更會自動傳播至相關資料庫。

`/v1/jobs` 端點可讓您監控結構描述遷移的狀態。

<div class="doc-callout doc-callout-warning"><div class="doc-callout-title">警告</div><div class="doc-callout-body">

目前 AWS 上的 Free、Developer 與 Scaler 方案不提供此功能。

</div></div>


### `GET /v1/jobs`

傳回某個結構描述中所有遷移工作的摘要：

```bash Request
curl -X GET 'https://[databaseName]-[organizationSlug].turso.io/v1/jobs' \
     -H 'Authorization: Bearer TOKEN'
```

```json Example Response
{
  "schema_version": 4,
  "migrations": [
    {
      "job_id": 43,
      "status": "RunSuccess"
    },
    {
      "job_id": 42,
      "status": "RunSuccess"
    },
    {
      "job_id": 39,
      "status": "RunSuccess"
    }
  ]
}
```

#### 回應欄位

**schema\_version** `number`

結構描述的目前版本。

**migrations** `array`

遷移工作清單

**遷移物件**

**job\_id** `number`

遷移工作的唯一 ID。

**status** `string`

工作的目前狀態。可能值：`WaitingDryRun`、`DryRunSuccess`、`DryRunFailure`、`WaitingRun`、`RunSuccess`、`RunFailure`

### `GET /v1/jobs/:id`

傳回特定遷移工作的詳細資訊。

```bash Request
curl -X GET 'https://[databaseName]-[organizationSlug].turso.io/v1/jobs/:id' \
     -H 'Authorization: Bearer TOKEN'
```

```json Example Response
{
  "job_id": 1,
  "status": "RunSuccess",
  "error": null,
  "progress": [
    {
      "namespace": "db1",
      "status": "Success",
      "error": null
    },
    {
      "namespace": "db2",
      "status": "Failure",
      "error": "Connection lost"
    }
  ]
}
```

#### 路徑參數

**id** `number` *必填*

遷移工作的 ID。

#### 回應欄位

**job\_id** `number`

遷移工作的唯一 ID。

**status** `string`

工作的整體狀態。可能值與 `/v1/jobs` 端點相同。

**error** `string`

工作失敗時的錯誤訊息，否則為 null。

**progress** `array`

個別資料庫的遷移狀態清單。

**進度物件**

**namespace** `string`

資料庫名稱。

**status** `string`

此資料庫的遷移狀態。可能值：`Enqueued`、`DryRunSuccess`、`DryRunFailure`、`Run`、`Success`、`Failure`

**error** `string`

此資料庫遷移失敗時的錯誤訊息，否則為 null。

## 監聽變更

您可以使用 `/beta/listen` 端點監聽提交至資料庫的變更：

<div class="doc-callout doc-callout-warning"><div class="doc-callout-title">警告</div><div class="doc-callout-body">

此功能目前處於技術預覽階段。歡迎[在 Discord 上加入我們](https://tur.so/discord)回報任何問題。

</div></div>

<div class="doc-callout doc-callout-warning"><div class="doc-callout-title">警告</div><div class="doc-callout-body">

目前 AWS 上的 Free、Developer 與 Scaler 方案不提供此功能。

</div></div>


<div class="doc-callout doc-callout-info"><div class="doc-callout-title">注意</div><div class="doc-callout-body">

您的資料庫群組必須使用 `v0.24.18` 或更新版本——`turso group update <group-name> --version latest`

</div></div>


### `GET /beta/listen`

```bash Request
curl -L 'https://[primary-instance-id]-[databaseName]-[organizationSlug].turso.io/beta/listen?table=TABLE_NAME' \
-H 'Authorization: Bearer TOKEN'
```

#### 查詢參數

**table** `string` *必填*

要監聽的資料表名稱。

**action** `string` *必填*

要監聽的動作名稱——`insert`、`update` 或 `delete`。
