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

# Go 版 chDB

> 如何安装并在 Go 中使用 chDB

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

## 安装

**1. 安装 libchdb**

首先，安装 chDB 库：

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

**2. 安装 chdb-go**

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

## 用法

### 命令行客户端

chDB-go 提供了一个命令行客户端，可用于快速执行查询：

```bash theme={null}
# Simple query
./chdb-go "SELECT 123"

# Interactive mode
./chdb-go

# Interactive mode with persistent storage
./chdb-go --path /tmp/chdb
```

### Go 库 - 快速入门

#### 无状态查询

对于简单的单次查询：

```go theme={null}
package main

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

func main() {
    // Execute a simple query
    result, err := chdb.Query("SELECT version()", "CSV")
    if err != nil {
        panic(err)
    }
    fmt.Println(result)
}
```

#### 使用会话的有状态查询

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

```go theme={null}
package main

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

func main() {
    // Create a session with persistent storage
    session, err := chdb.NewSession("/tmp/chdb-data")
    if err != nil {
        panic(err)
    }
    defer session.Cleanup()

    // Create database and table
    _, 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)
    }

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

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

#### SQL 驱动程序接口

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

```go theme={null}
package main

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

func main() {
    // Open database connection
    db, err := sql.Open("chdb", "")
    if err != nil {
        panic(err)
    }
    defer db.Close()

    // Query with standard database/sql interface
    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)
    }
}
```

#### 大型数据集的流式查询

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

```go theme={null}
package main

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

func main() {
    // Create a session for streaming queries
    session, err := chdb.NewSession("/tmp/chdb-stream")
    if err != nil {
        log.Fatal(err)
    }
    defer session.Cleanup()

    // Execute a streaming query for large dataset
    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
    
    // Process data in chunks
    for {
        chunk := streamResult.GetNext()
        if chunk == nil {
            // No more data
            break
        }
        
        // Check for streaming errors
        if err := streamResult.Error(); err != nil {
            log.Printf("Streaming error: %v", err)
            break
        }
        
        rowsRead := chunk.RowsRead()
        // You can process the chunk data here
        // For example, write to file, send over network, etc.
        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()` 检查错误

## API 文档

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)** - 适用于需要细粒度控制的高级用例

## 系统要求

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