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

# 适用于 Bun 的 chDB

> 如何在 Bun 运行时中安装和使用 chDB

chDB-bun 为 chDB 提供 Experimental 的 FFI (外部函数接口) 绑定，让您能够在 Bun 应用中直接运行 ClickHouse 查询，且无需任何外部依赖。

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

<div id="install-system-dependencies">
  ### 第 1 步：安装系统依赖
</div>

首先，安装所需的系统依赖：

<div id="install-libchdb">
  #### 安装 libchdb
</div>

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

<div id="install-build-tools">
  #### 安装构建工具
</div>

你的系统中需要安装 `gcc` 或 `clang` 之一：

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

```bash theme={null}
# 从 GitHub 仓库安装
bun add github:chdb-io/chdb-bun

# 或在本地克隆并构建
git clone https://github.com/chdb-io/chdb-bun.git
cd chdb-bun
bun install
bun run build
```

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

chDB-bun 支持两种查询模式：一种是用于一次性操作的临时查询，另一种是用于维护数据库状态的持久会话。

<div id="ephemeral-queries">
  ### 临时查询
</div>

对于无需持久状态的简单一次性查询：

```typescript theme={null}
import { query } from 'chdb-bun';

// 基本查询
const result = query("SELECT version()", "CSV");
console.log(result); // "23.10.1.1"

// 使用不同输出格式的查询
const jsonResult = query("SELECT 1 as id, 'Hello' as message", "JSON");
console.log(jsonResult);

// 带计算的查询
const mathResult = query("SELECT 2 + 2 as sum, pi() as pi_value", "Pretty");
console.log(mathResult);

// 查询系统信息
const systemInfo = query("SELECT * FROM system.functions LIMIT 5", "CSV");
console.log(systemInfo);
```

<div id="persistent-sessions">
  ### 持久会话
</div>

对于需要在多次查询之间保持状态的复杂操作：

```typescript theme={null}
import { Session } from 'chdb-bun';

// 创建一个具有持久化存储的会话
const sess = new Session('./chdb-bun-tmp');

try {
    // 创建数据库和表
    sess.query(`
        CREATE DATABASE IF NOT EXISTS mydb;
        CREATE TABLE IF NOT EXISTS mydb.users (
            id UInt32,
            name String,
            email String
        ) ENGINE = MergeTree() ORDER BY id
    `, "CSV");

    // 插入数据
    sess.query(`
        INSERT INTO mydb.users VALUES 
        (1, 'Alice', 'alice@example.com'),
        (2, 'Bob', 'bob@example.com'),
        (3, 'Charlie', 'charlie@example.com')
    `, "CSV");

    // 查询数据
    const users = sess.query("SELECT * FROM mydb.users ORDER BY id", "JSON");
    console.log("Users:", users);

    // 创建并使用自定义函数
    sess.query("CREATE FUNCTION IF NOT EXISTS hello AS () -> 'Hello chDB'", "CSV");
    const greeting = sess.query("SELECT hello() as message", "Pretty");
    console.log(greeting);

    // 聚合查询
    const stats = sess.query(`
        SELECT 
            COUNT(*) as total_users,
            MAX(id) as max_id,
            MIN(id) as min_id
        FROM mydb.users
    `, "JSON");
    console.log("Statistics:", stats);

} finally {
    // 务必清理会话以释放资源
    sess.cleanup(); // 这将删除数据库文件
}
```
