> ## Documentation Index
> Fetch the complete documentation index at: https://docs.blockdb.chaintable.com/llms.txt
> Use this file to discover all available pages before exploring further.

# API 总览

> BlockDB gRPC 服务与方法，以 protobuf、JSON 载荷与 grpcurl 调用形式描述。

# API 总览

BlockDB 通过一组 gRPC 服务对外提供能力。所有服务都是纯 gRPC（无 REST 网关），且**已开启 gRPC server reflection**，因此你可以直接用 `grpcurl` 检视并调用每个方法，无需准备 proto 文件。默认服务地址为 `localhost:19002`。

## JSON 映射约定

在构造请求前，先了解 proto3 消息如何映射到 JSON：

* **`Value` 是一个 oneof**：JSON 中只出现被设置的那个字段，使用 camelCase 名称——`"stringValue"`、`"intValue"`、`"doubleValue"`、`"boolValue"`。NULL 通过省略 `kind`（空 `{}`）表示。

  ```json theme={null}
  { "stringValue": "0xabc..." }   // STRING / HASH / ADDRESS / TXID / ...
  { "intValue": "18000000" }      // BIGINT / BLOCKHEIGHT
  { "doubleValue": 3.14 }          // DOUBLE
  { "boolValue": true }            // BOOLEAN
  ```

* **`int64` 字段编码为 JSON 字符串**（proto3 规范），例如 `height`、`limit`、`affected_rows` 都以字符串呈现。

* **字段名风格**：proto3 JSON *输出* lowerCamelCase（`tableId` 而非 `table_id`），但*输入时*同时接受 camelCase 与原始的 snake\_case。

* **读响应**采用**schema + 位置数组**的结构：`ResultSet { columns: ColumnMeta[], rows: Row[] }`，每个 `Row.values` 是与 `columns` 对齐的位置 `Value[]`。

* **写请求**采用**自描述 map**：`WriteRow.fields` 是 `map<string, Value>`。

```
ResultSet: {
  "columns": [ { "name": "id", "logicalType": "ADDRESS" }, ... ],
  "rows":    [ { "values": [ { "stringValue": "0x..." }, ... ] } ]
}
```

权威定义位于 `proto/blockdb/v1/`（`common.proto`、`table.proto`、`block.proto`、`time.proto`、`batch.proto`）。

## 普通表服务

### `TableReadService`

| 方法 | 说明 |
| - | - |
| `GetRow` | 按业务主键读取单行 |
| `BatchGetRows` | 按多个主键批量读取 |
| `FilterRows` | 按条件筛选，支持排序与分页 |

#### GetRow

读取单行。

**Proto**

```protobuf theme={null}
message GetRowRequest {
  string table_id = 1;
  Value  row_id   = 2;
}
```

**调用**

```bash theme={null}
grpcurl -plaintext -d '{
  "tableId": "demo.event_log",
  "rowId":   { "stringValue": "evt_001" }
}' localhost:19002 blockdb.v1.TableReadService/GetRow
```

**响应**

```json theme={null}
{
  "result": {
    "columns": [ { "name": "id", "logicalType": "STRING" }, { "name": "value", "logicalType": "INT" } ],
    "rows": [ { "values": [ { "stringValue": "evt_001" }, { "intValue": "1" } ] } ]
  }
}
```

#### BatchGetRows

一次读取多个主键。

**Proto**

```protobuf theme={null}
message BatchGetRowsRequest {
  string         table_id = 1;
  repeated Value row_ids  = 2;
}
```

**调用**

```bash theme={null}
grpcurl -plaintext -d '{
  "tableId": "demo.event_log",
  "rowIds":  [ { "stringValue": "evt_001" }, { "stringValue": "evt_002" } ]
}' localhost:19002 blockdb.v1.TableReadService/BatchGetRows
```

#### FilterRows

按条件字符串筛选，支持排序与分页。

**Proto**

```protobuf theme={null}
message FilterRowsRequest {
  string table_id = 1;
  string filters  = 2;
  string order_by = 3;
  int64  limit    = 4;
  int64  offset   = 5;
}
```

**调用**

```bash theme={null}
grpcurl -plaintext -d '{
  "tableId": "demo.event_log",
  "filters": "value > 0",
  "orderBy": "value desc",
  "limit":   "100"
}' localhost:19002 blockdb.v1.TableReadService/FilterRows
```

### `TableWriteService`

| 方法 | 说明 |
| - | - |
| `UpsertRows` | 批量插入或更新，支持条件更新与部分更新 |
| `DeleteRows` | 批量删除 |

#### UpsertRows

请求使用自描述的 `WriteRow` map，因此只更新请求中出现的列（部分更新）。可选 `condition` 支持 `UPDATE_IF_SMALLER` / `UPDATE_IF_LARGER`。

**Proto**

```protobuf theme={null}
message UpsertRowsRequest {
  string                    table_id  = 1;
  repeated WriteRow         rows      = 2;
  optional UpsertCondition  condition = 3;
  bool                      sync      = 4;
}
```

**调用**

```bash theme={null}
grpcurl -plaintext -d '{
  "tableId": "demo.event_log",
  "rows": [
    {
      "fields": {
        "id":    { "stringValue": "evt_001" },
        "name":  { "stringValue": "login" },
        "value": { "intValue": "1" }
      }
    }
  ]
}' localhost:19002 blockdb.v1.TableWriteService/UpsertRows
```

**响应**

```json theme={null}
{ "result": { "affectedRows": "1", "jobId": "..." } }
```

#### DeleteRows

**调用**

```bash theme={null}
grpcurl -plaintext -d '{
  "tableId": "demo.event_log",
  "rowIds": [ { "stringValue": "evt_001" } ]
}' localhost:19002 blockdb.v1.TableWriteService/DeleteRows
```

### `TableScanService`

#### Scan（服务端流式）

**Proto**

```protobuf theme={null}
message ScanRequest { string sql = 1; }
message ScanResponse { ResultSet result = 1; }
```

**调用**

```bash theme={null}
grpcurl -plaintext -d '{"sql": "SELECT * FROM demo.event_log WHERE value > 0"}' \
  localhost:19002 blockdb.v1.TableScanService/Scan
```

## Block 表服务

### `BlockReadService`

| 方法 | 说明 |
| - | - |
| `GetEvent` | 按区块锚点读取事件 |
| `GetState` | 按区块锚点读取状态快照 |
| `GetConsensusHeight` | 获取表的共识高度 |
| `GetBlockRows` | 获取某区块高度的全部数据行（`L2BlockReadService`） |

#### GetState

按区块锚点读取状态快照。`current_block` 注入 `height ≤ 目标高度`；省略时读取最新。

**Proto**

```protobuf theme={null}
message Block {
  string block_id = 1;
  int64  height   = 2;
  string timestamp = 3;
}

message GetStateRequest {
  string table_id      = 1;
  Value  state_id      = 2;
  Block  current_block = 3;
}
```

**调用**

```bash theme={null}
grpcurl -plaintext -d '{
  "tableId": "token.token.eth",
  "stateId": { "stringValue": "acct_1" },
  "currentBlock": {
    "blockId": "0x0c76...",
    "height":  "18000000",
    "timestamp": "2024-06-08T00:00:00Z"
  }
}' localhost:19002 blockdb.v1.BlockReadService/GetState
```

### `BlockWriteService`

| 方法 | 说明 |
| - | - |
| `UpsertBlock` | 按区块粒度原子写入 |

#### UpsertBlock

**Proto**

```protobuf theme={null}
message UpsertBlockRequest {
  string           table_id = 1;
  Block            block    = 2;
  repeated WriteRow rows     = 3;
  optional bool    sync     = 5;
}
```

**调用**

```bash theme={null}
grpcurl -plaintext -d '{
  "tableId": "token.token.eth",
  "block": {
    "blockId": "0x0c76...",
    "height":  "18000000",
    "timestamp": "2024-06-08T00:00:00Z"
  },
  "rows": [
    { "fields": { "id": { "stringValue": "acct_1" }, "balance": { "intValue": "1000" } } }
  ]
}' localhost:19002 blockdb.v1.BlockWriteService/UpsertBlock
```

### `BlockSubscribeService`

#### Subscribe（服务端流式）

**Proto**

```protobuf theme={null}
message BlockSubscribeRequest {
  repeated string table_ids      = 1;
  optional int64  start_timestamp = 2;
}
message BlockSubscribeEvent {
  string table_id  = 1;
  Block  block     = 2;
  int64  created_at = 3;
}
```

**调用**

```bash theme={null}
grpcurl -plaintext -d '{"tableIds": ["token.token.eth"]}' \
  localhost:19002 blockdb.v1.BlockSubscribeService/Subscribe
```

## Time 表服务

### `TimeReadService` — `GetValue`

**Proto**

```protobuf theme={null}
message GetValueRequest {
  string table_id = 1;
  string row_id   = 2;
  string time_at  = 3;
}
```

**调用**

```bash theme={null}
grpcurl -plaintext -d '{
  "tableId": "token_time_demo",
  "rowId":   "0xabc...",
  "timeAt":  "2026-05-18 17:04:00"
}' localhost:19002 blockdb.v1.TimeReadService/GetValue
```

### `TimeWriteService` — `UpsertTimeRows`

**Proto**

```protobuf theme={null}
message UpsertTimeRowsRequest {
  string           table_id = 1;
  string           time_at  = 2;
  repeated WriteRow rows     = 3;
  optional bool    sync     = 5;
}
```

**调用**

```bash theme={null}
grpcurl -plaintext -d '{
  "tableId": "token_time_demo",
  "timeAt":  "2026-05-18 17:04:00",
  "rows": [ { "fields": { "id": { "stringValue": "0xabc..." }, "value": { "doubleValue": 2543.12 } } } ]
}' localhost:19002 blockdb.v1.TimeWriteService/UpsertTimeRows
```

时间桶对齐（把 `17:04:35` 进位到 `17:05:00` 桶）发生在 SDK 侧，因此直接 gRPC 调用会原样接收你传入的 `time_at`。

## 批量写服务 — `BatchWriteService`

| 方法 | 说明 |
| - | - |
| `InitWriteJob` | 初始化写入任务，返回 S3 presigned 上传 URL 与任务 ID |
| `CommitWriteJob` | 提交任务，触发后台处理 |
| `CancelWriteJob` | 取消一个排队中的任务 |

**InitWriteJob**

```bash theme={null}
grpcurl -plaintext -d '{
  "tableId": "demo.event_log",
  "normalUpsert": { }
}' localhost:19002 blockdb.v1.BatchWriteService/InitWriteJob
```

## 串联示例

一条完整的"读一行"调用：

```bash theme={null}
# 列出服务（reflection 已开启）
grpcurl -plaintext localhost:19002 list

# 列出 TableReadService 的方法
grpcurl -plaintext localhost:19002 list blockdb.v1.TableReadService

# 读取一行
grpcurl -plaintext -d '{"tableId":"demo.event_log","rowId":{"stringValue":"evt_001"}}' \
  localhost:19002 blockdb.v1.TableReadService/GetRow
```

## 相关阅读

* [逻辑类型](/zh/reference/value-types)
* [错误码](/zh/reference/errors)
* [写入架构](/zh/architecture/batch-write)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.