# SQL over HTTP 参考

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

---
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` 属性可以匹配前缀，也可以省略前缀。上面的示例中省略了前缀，但两种形式都有效。

每个 arg 中的 `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 | 处理请求的服务器的 base 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;
```

如果你使用[多数据库 schema](/zh-cn/docs/features/multi-db-schemas/)或向量数据库，将会看到表示内部管理表的语句。

## Schema 迁移状态

Turso 提供托管的[多租户 schema 系统](/zh-cn/docs/features/multi-db-schemas/)——多数据库 Schema。此功能允许你创建一个单一数据库，并自动与任何相关的子数据库共享其 schema。对父数据库的更改会自动传播到相关数据库。

`/v1/jobs` 端点可让你监控 schema 迁移的状态。

<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`

返回某个 schema 的所有迁移作业摘要：

```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`

Schema 的当前版本。

**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`。
