> ## Documentation Index
> Fetch the complete documentation index at: https://private-7c7dfe99-fix-nav-issues.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# 适用于 Go 的 chDB

> 如何安装并使用适用于 Go 的 chDB

chDB-go 为 chDB 提供 Go 语言绑定，让您无需任何外部依赖，即可在 Go 应用程序中直接运行 ClickHouse 查询。

<div id="installation">
  ## 安装
</div>

<div id="install-libchdb">
  ### 步骤 1：安装 libchdb
</div>

首先，安装 chDB 库：

```bash theme={null}
curl -sL https://lib.chdb.io | bash
```

<div id="install-chdb-go">
  ### 第 2 步：安装 chdb-go
</div>

安装 Go 包：

```bash theme={null}
go install github.com/chdb-io/chdb-go@latest
```

或者将其添加到 `go.mod` 中：

```bash theme={null}
go get github.com/chdb-io/chdb-go
```

<div id="usage">
  ## 用法
</div>

<div id="cli">
  ### 命令行界面
</div>

chDB-go 内置了一个可用于快速查询的 CLI：

```bash theme={null}
# 简单查询
./chdb-go "SELECT 123"

# 交互模式
./chdb-go

# 带持久化存储的交互模式
./chdb-go --path /tmp/chdb
```

<div id="quick-start">
  ### Go 库 - 快速入门
</div>

<div id="stateless-queries">
  #### 无状态查询
</div>

对于简单的单次查询：

```go theme={null}
package main

import (
    "fmt"
    "github.com/chdb-io/chdb-go/chdb"
)

func main() {
    // 执行一个简单的查询
    result, err := chdb.Query("SELECT version()", "CSV")
    if err != nil {
        panic(err)
    }
    fmt.Println(result)
}
```

<div id="stateful-queries">
  #### 通过会话执行有状态查询
</div>

对于需要持久状态的复杂查询：

```go theme={null}
package main

import (
    "fmt"
    "github.com/chdb-io/chdb-go/chdb"
)

func main() {
    // 创建一个具有持久化存储的会话
    session, err := chdb.NewSession("/tmp/chdb-data")
    if err != nil {
        panic(err)
    }
    defer session.Cleanup()

    // 创建数据库和表
    _, err = session.Query(`
        CREATE DATABASE IF NOT EXISTS testdb;
        CREATE TABLE IF NOT EXISTS testdb.test_table (
            id UInt32,
            name String
        ) ENGINE = MergeTree() ORDER BY id
    `, "")
    
    if err != nil {
        panic(err)
    }

    // 插入数据
    _, err = session.Query(`
        INSERT INTO testdb.test_table VALUES 
        (1, 'Alice'), (2, 'Bob'), (3, 'Charlie')
    `, "")
    
    if err != nil {
        panic(err)
    }

    // 查询数据
    result, err := session.Query("SELECT * FROM testdb.test_table ORDER BY id", "Pretty")
    if err != nil {
        panic(err)
    }
    
    fmt.Println(result)
}
```

<div id="sql-driver">
  #### SQL 驱动程序接口
</div>

chDB-go 实现了 Go 的 `database/sql` 接口：

```go theme={null}
package main

import (
    "database/sql"
    "fmt"
    _ "github.com/chdb-io/chdb-go/chdb/driver"
)

func main() {
    // 打开数据库连接
    db, err := sql.Open("chdb", "")
    if err != nil {
        panic(err)
    }
    defer db.Close()

    // 使用标准 database/sql 接口进行查询
    rows, err := db.Query("SELECT COUNT(*) FROM url('https://datasets.clickhouse.com/hits/hits.parquet')")
    if err != nil {
        panic(err)
    }
    defer rows.Close()

    for rows.Next() {
        var count int
        err := rows.Scan(&count)
        if err != nil {
            panic(err)
        }
        fmt.Printf("Count: %d\n", count)
    }
}
```

<div id="query-streaming">
  #### 大型数据集的流式查询
</div>

对于无法装入内存的大型数据集，请使用流式查询：

```go theme={null}
package main

import (
    "fmt"
    "log"
    "github.com/chdb-io/chdb-go/chdb"
)

func main() {
    // 为流式查询创建会话
    session, err := chdb.NewSession("/tmp/chdb-stream")
    if err != nil {
        log.Fatal(err)
    }
    defer session.Cleanup()

    // 对大型数据集执行流式查询
    streamResult, err := session.QueryStreaming(
        "SELECT number, number * 2 as double FROM system.numbers LIMIT 1000000", 
        "CSV",
    )
    if err != nil {
        log.Fatal(err)
    }
    defer streamResult.Free()

    rowCount := 0
    
    // 分块处理数据
    for {
        chunk := streamResult.GetNext()
        if chunk == nil {
            // 没有更多数据
            break
        }
        
        // 检查流式传输错误
        if err := streamResult.Error(); err != nil {
            log.Printf("Streaming error: %v", err)
            break
        }
        
        rowsRead := chunk.RowsRead()
        // 可在此处处理分块数据
        // 例如，写入文件、通过网络发送等
        fmt.Printf("Processed chunk with %d rows\n", rowsRead)
        rowCount += int(rowsRead)
        if rowCount%100000 == 0 {
            fmt.Printf("Processed %d rows so far...\n", rowCount)
        }
    }
    
    fmt.Printf("Total rows processed: %d\n", rowCount)
}
```

**流式查询的优势：**

* **内存占用高效** - 无需将全部内容加载到内存中，即可处理大型数据集
* **实时处理** - 第一个数据块一到达，就能开始处理数据
* **支持取消** - 可使用 `Cancel()` 取消长时间运行的查询
* **错误处理** - 可在流式传输过程中使用 `Error()` 检查错误

<div id="api-documentation">
  ## API 文档
</div>

chDB-go 同时提供高级 API 和底层 API：

* **[高级 API 文档](https://github.com/chdb-io/chdb-go/blob/main/chdb.md)** - 推荐用于大多数场景
* **[底层 API 文档](https://github.com/chdb-io/chdb-go/blob/main/lowApi.md)** - 适用于需要细粒度控制的高级场景

<div id="requirements">
  ## 系统要求
</div>

* Go 1.21 或更高版本
* 兼容 Linux 和 macOS
