chDB-bun 为 chDB 提供 Experimental 的 FFI (外部函数接口) 绑定,让您无需任何外部依赖项,即可在 Bun 应用程序中直接运行 ClickHouse 查询。
安装
安装系统依赖项
首先,安装所需的系统依赖项:
安装 libchdb
curl -sL https://lib.chdb.io | bash安装构建工具
你的系统需要安装 gcc 或 clang 之一:
安装 chDB-bun
# 从 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用法
chDB-bun 支持两种查询模式:一种是用于一次性操作的临时查询,另一种是用于保持数据库状态的持久化会话。
临时查询
对于简单的一次性查询,如果不需要持久状态:
import { query } from 'chdb-bun';
// Basic query
const result = query("SELECT version()", "CSV");
console.log(result); // "23.10.1.1"
// Query with different output formats
const jsonResult = query("SELECT 1 as id, 'Hello' as message", "JSON");
console.log(jsonResult);
// Query with calculations
const mathResult = query("SELECT 2 + 2 as sum, pi() as pi_value", "Pretty");
console.log(mathResult);
// Query system information
const systemInfo = query("SELECT * FROM system.functions LIMIT 5", "CSV");
console.log(systemInfo);持久化会话
对于需要在多次查询之间保持状态的复杂操作:
import { Session } from 'chdb-bun';
// Create a session with persistent storage
const sess = new Session('./chdb-bun-tmp');
try {
// Create a database and table
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");
// Insert data
sess.query(`
INSERT INTO mydb.users VALUES
(1, 'Alice', 'alice@example.com'),
(2, 'Bob', 'bob@example.com'),
(3, 'Charlie', 'charlie@example.com')
`, "CSV");
// Query the data
const users = sess.query("SELECT * FROM mydb.users ORDER BY id", "JSON");
console.log("Users:", users);
// Create and use custom functions
sess.query("CREATE FUNCTION IF NOT EXISTS hello AS () -> 'Hello chDB'", "CSV");
const greeting = sess.query("SELECT hello() as message", "Pretty");
console.log(greeting);
// Aggregate queries
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 {
// Always cleanup the session to free resources
sess.cleanup(); // This deletes the database files
}