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', '[email protected]'),
(2, 'Bob', '[email protected]'),
(3, 'Charlie', '[email protected]')
`, "CSV");
// 查询数据
const users = sess.query("SELECT * FROM mydb.users ORDER BY id", "JSON");
console.log("用户:", 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("统计信息:", stats);
} finally {
// 务必清理会话以释放资源
sess.cleanup(); // 此操作将删除数据库文件
}