XU XUv0.16.0

#github.com/xulang-org/packages/clickhouse

导入方式: clickhouse #github.com/xulang-org/packages/clickhouse

公开 API: 5 函数, 15 方法, 3 类型, 0 常量, 0 方法集

扩展包 `clickhouse #github.com/xulang-org/packages/clickhouse`,由模块 github.com/xulang-org/packages 提供。

github.com/xulang-org/packages · 1.17.2 · 安装与使用

示例代码 · API 声明

示例代码

以下源码来自官方 examples 仓库,可复制或下载。请在完整工程中使用本地 Xu SDK 运行;网络、数据库和桌面示例需要对应的服务或资源。

29_standalone_clickhouse/main.xu

所需 SDK:Xu 0.8.3 · 完整工程 · 下载源码

Xu本地 SDK 示例
@main

clickhouse #github.com/xulang-org/packages/clickhouse
#errors

fn verify_clickhouse_basic() {
    println("--- 1. Testing ClickHouse Client & Basic SQL ---")
    $ch := clickhouse.open("http://127.0.0.1:8123", "default", "secret", "default")

    // Ping check
    pong := ch.ping()
    println("   ClickHouse ping: " + str(pong))

    // DDL: Create table
    println("   Creating table 'xu_metrics'...")
    ch.exec("CREATE TABLE IF NOT EXISTS xu_metrics (id UInt64, service String, latency Float64) ENGINE = Memory") >>> (err) {
        println("   [FAIL] Create table error: " + err.msg())
        <<
    }
    println("   [PASS] Table created.")

    // DML: Insert records
    println("   Inserting records...")
    ch.insert("xu_metrics", "(1, 'order_service', 24.5), (2, 'user_service', 12.0), (3, 'order_service', 35.5)") >>> (err) {
        println("   [FAIL] Insert error: " + err.msg())
        <<
    }
    println("   [PASS] 3 rows inserted.")

    // Query: Aggregation
    println("   Running aggregation query...")
    res := ch.query("SELECT service, count(), avg(latency) FROM xu_metrics GROUP BY service ORDER BY service") >>> (err) {
        println("   [FAIL] Query error: " + err.msg())
        <<
    }
    println("   Query Results (TSV):\n" + res)

    // Cleanup: Drop table
    ch.exec("DROP TABLE IF EXISTS xu_metrics") >>> (err) {
        println("   [FAIL] Drop table error: " + err.msg())
        <<
    }
    println("   [PASS] Table dropped successfully.")
}

fn verify_clickhouse_pool() {
    println("\n--- 2. Testing ClickHouse Connection Pool ---")
    $p := clickhouse.open_pool("http://127.0.0.1:8123", "default", "secret", "default", 5)

    // 1. Connection Reuse Test
    fd1 := p.get_conn()
    println("   Borrow 1 fd: " + str(fd1))
    p.put_conn(fd1)

    fd2 := p.get_conn()
    println("   Borrow 2 (after return) fd: " + str(fd2))
    if fd1 == fd2 {
        println("   [PASS] Connection reused successfully (fd " + str(fd1) + " == " + str(fd2) + ")")
    } else {
        println("   [WARN] Different fd allocated: " + str(fd1) + " vs " + str(fd2))
    }

    // 2. Multi-connection concurrent borrow
    fd3 := p.get_conn()
    println("   Borrow 3 (concurrently) fd: " + str(fd3))
    if fd2 != fd3 {
        println("   [PASS] Concurrently allocated distinct fds (" + str(fd2) + " != " + str(fd3) + ")")
    } else {
        println("   [FAIL] Expected distinct fds for concurrent connections!")
    }
    p.put_conn(fd2)
    p.put_conn(fd3)

    // 3. Delegated Queries & Execution via Pool
    println("   Testing delegated operations via pool...")
    p.exec("CREATE TABLE IF NOT EXISTS xu_pool_events (id UInt64, name String) ENGINE = Memory") >>> (err) {
        println("   [FAIL] Pool create table error: " + err.msg())
        <<
    }
    p.exec("INSERT INTO xu_pool_events VALUES (101, 'login'), (102, 'checkout')") >>> (err) {
        println("   [FAIL] Pool insert error: " + err.msg())
        <<
    }
    rows := p.query_tsv("SELECT id, name FROM xu_pool_events ORDER BY id") >>> (err) {
        println("   [FAIL] Pool query_tsv error: " + err.msg())
        <<
    }
    println("   Retrieved rows count via pool: " + str(rows.len))
    if rows.len == 2 {
        println("   [PASS] Query TSV row count verified: 2 rows")
        println("   Row 0: id=" + rows[0][0] + ", name=" + rows[0][1])
        println("   Row 1: id=" + rows[1][0] + ", name=" + rows[1][1])
    } else {
        println("   [FAIL] Row count mismatch!")
    }

    p.exec("DROP TABLE IF EXISTS xu_pool_events") >>> (err) {
        println("   [FAIL] Pool drop table error: " + err.msg())
        <<
    }
    println("   [PASS] Pool drop table completed.")

    p.close()
    println("   [PASS] ClickHouse Pool closed and verified.")
}

fn main() {
    println("=== Xu ClickHouse Native Driver Verification ===\n")
    verify_clickhouse_basic()
    verify_clickhouse_pool()
    println("\n[CLICKHOUSE VERIFICATION 100% COMPLETED]")
}

API 声明

open

XuAPI
pub fn open(endpoint string, user string, password string, database string) Client

用途

打开资源或建立网络连接。

参数

endpoint string
endpoint(string)
user string
user(string)
password string
password(string)
database string
database(string)

返回值

Client — 该类型的值

查看用法示例

open_pool

XuAPI
pub fn open_pool(endpoint string, user string, password string, database string, max_idle int) Pool

用途

执行 open pool 操作。

参数

endpoint string
endpoint(string)
user string
user(string)
password string
password(string)
database string
database(string)
max_idle int
max_idle(int)

返回值

Pool — 该类型的值

查看用法示例

struct Response

XuAPI
pub struct Response {
    pub status_code int
    pub body string
}

用途

Clickhouse 服务端响应结果,包含状态码、响应头与正文数据。

公开字段

status_code int
字段(int)
body string
正文

struct Client

XuAPI
pub struct Client {
    pub host string
    pub port int
    pub secure bool
    pub user string
    pub password string
    pub database string
}

用途

Clickhouse 客户端会话实例,维护与服务端的连接并提供操作接口。

公开字段

host string
主机
port int
端口
secure bool
字段(bool)
user string
字段(string)
password string
字段(string)
database string
字段(string)

new_client

XuAPI
pub fn new_client(endpoint string, user string, password string, database string) Client

用途

构造 client。

参数

endpoint string
endpoint(string)
user string
user(string)
password string
password(string)
database string
database(string)

返回值

Client — 该类型的值

parse_tsv

XuAPI
pub fn parse_tsv(raw string) [][]string

用途

解析为 tsv。

参数

raw string
raw(string)

返回值

[][]string — 切片结果

($&Client) request

XuAPI
pub fn (c $&Client) request(sql_query string) Response

用途

$&Client 上的操作:请求。失败时抛出错误,调用方需处理或继续传播。

参数

c $&Client
本次调用使用的 Client 实例;以独占借用传入,方法可修改它,调用方仍持有实例。
sql_query string
sql_query(string)

返回值

Response — 该类型的值

struct Pool

XuAPI
pub struct Pool {
    pub host string
    pub port int
    pub secure bool
    pub user string
    pub password string
    pub database string
    pub state chan pool.State
    pub max_idle int
}

用途

ClickHouse 连接池管理器,维护复用 TCP 套接字连接。

公开字段

host string
主机
port int
端口
secure bool
字段(bool)
user string
字段(string)
password string
字段(string)
database string
字段(string)
state chan pool.State
字段(通道;类型 chan pool.State)
max_idle int
字段(int)

new_pool

XuAPI
pub fn new_pool(endpoint string, user string, password string, database string, max_idle int) Pool

用途

构造 pool。

参数

endpoint string
endpoint(string)
user string
user(string)
password string
password(string)
database string
database(string)
max_idle int
max_idle(int)

返回值

Pool — 该类型的值

(&Pool) get

XuAPI
pub fn (p &Pool) get() Client

用途

在 &Pool 上执行 get 操作。

参数

p &Pool
本次调用使用的 Pool 实例;以只读借用传入,调用方仍持有实例。

返回值

Client — 该类型的值

(&Pool) dup

XuAPI
pub fn (p &Pool) dup() Pool

用途

创建并返回持有独立状态或底层的副本对象。

参数

p &Pool
本次调用使用的 Pool 实例;以只读借用传入,调用方仍持有实例。

返回值

Pool — 该类型的值

(&Pool) get_conn

XuAPI
pub fn (p &Pool) get_conn() int

用途

&Pool 上的操作:读取 conn。

参数

p &Pool
本次调用使用的 Pool 实例;以只读借用传入,调用方仍持有实例。

返回值

int — 该类型的值

(&Pool) put_conn

XuAPI
pub fn (p &Pool) put_conn(fd int)

用途

&Pool 上的操作:执行 put conn 操作。

参数

p &Pool
本次调用使用的 Pool 实例;以只读借用传入,调用方仍持有实例。
fd int
文件描述符(int)

返回值

不返回值。

(&Pool) discard_conn

XuAPI
pub fn (p &Pool) discard_conn(fd int)

用途

&Pool 上的操作:丢弃连接。

参数

p &Pool
本次调用使用的 Pool 实例;以只读借用传入,调用方仍持有实例。
fd int
文件描述符(int)

返回值

不返回值。

(&Pool) exec

XuAPI
pub fn (p &Pool) exec(sql_query string) int

用途

执行 SQL 语句或服务命令,返回受影响行数或执行结果。失败时抛出错误,调用方需处理或继续传播。

参数

p &Pool
本次调用使用的 Pool 实例;以只读借用传入,调用方仍持有实例。
sql_query string
sql_query(string)

返回值

int — 该类型的值

(&Pool) query

XuAPI
pub fn (p &Pool) query(sql_query string) string

用途

&Pool 上的操作:查询串。失败时抛出错误,调用方需处理或继续传播。

参数

p &Pool
本次调用使用的 Pool 实例;以只读借用传入,调用方仍持有实例。
sql_query string
sql_query(string)

返回值

string — 结果字符串

(&Pool) query_tsv

XuAPI
pub fn (p &Pool) query_tsv(sql_query string) [][]string

用途

&Pool 上的操作:执行 query tsv 操作。失败时抛出错误,调用方需处理或继续传播。

参数

p &Pool
本次调用使用的 Pool 实例;以只读借用传入,调用方仍持有实例。
sql_query string
sql_query(string)

返回值

[][]string — 切片结果

(&Pool) close

XuAPI
pub fn (p &Pool) close()

用途

&Pool 上的操作:关闭资源。

参数

p &Pool
本次调用使用的 Pool 实例;以只读借用传入,调用方仍持有实例。

返回值

不返回值。

($&Client) exec

XuAPI
pub fn (c $&Client) exec(sql_query string) int

用途

执行 SQL 语句或服务命令,返回受影响行数或执行结果。失败时抛出错误,调用方需处理或继续传播。

参数

c $&Client
本次调用使用的 Client 实例;以独占借用传入,方法可修改它,调用方仍持有实例。
sql_query string
sql_query(string)

返回值

int — 该类型的值

($&Client) query

XuAPI
pub fn (c $&Client) query(sql_query string) string

用途

$&Client 上的操作:查询串。失败时抛出错误,调用方需处理或继续传播。

参数

c $&Client
本次调用使用的 Client 实例;以独占借用传入,方法可修改它,调用方仍持有实例。
sql_query string
sql_query(string)

返回值

string — 结果字符串

($&Client) query_tsv

XuAPI
pub fn (c $&Client) query_tsv(sql_query string) [][]string

用途

$&Client 上的操作:执行 query tsv 操作。失败时抛出错误,调用方需处理或继续传播。

参数

c $&Client
本次调用使用的 Client 实例;以独占借用传入,方法可修改它,调用方仍持有实例。
sql_query string
sql_query(string)

返回值

[][]string — 切片结果

($&Client) ping

XuAPI
pub fn (c $&Client) ping() bool

用途

发送心跳保活探测请求,检测连接活性与服务可用性。

参数

c $&Client
本次调用使用的 Client 实例;以独占借用传入,方法可修改它,调用方仍持有实例。

返回值

bool — 是否成立

($&Client) insert

XuAPI
pub fn (c $&Client) insert(table string, values_sql string) int

用途

$&Client 上的操作:插入。

参数

c $&Client
本次调用使用的 Client 实例;以独占借用传入,方法可修改它,调用方仍持有实例。
table string
table(string)
values_sql string
values_sql(string)

返回值

int — 该类型的值