XU XUv0.16.0

#context

导入方式: #context

公开 API: 9 函数, 2 方法, 2 类型, 0 常量, 0 方法集

在任务间传递取消信号、截止时间和字符串键值。通过 Context.done 等待取消;需要主动结束任务时,保留构造函数返回的 Cancel 并调用 cancel。

示例代码 · API 声明

示例代码

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

34_standalone_postgres/main.xu

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

Xu本地 SDK 示例
@main

postgres #github.com/xulang-org/packages/postgres
#database/sql/driver
#context

fn verify_postgres_live() {
    println("--- Testing Native Postgres Driver Wire Protocol ---")
    dsn := "postgres://zicq:zicq@127.0.0.1:5432/xu_demo?sslmode=disable"
    $conn := postgres.open(dsn)

    // 1. Ping
    err := conn.ping()
    if err.len > 0 {
        println("   [FAIL] Ping failed: " + err)
        conn.close()
        <<
    }
    println("   [PASS] Postgres Ping succeeded.")

    // 2. Exec DDL
    r1 := conn.exec("DROP TABLE IF EXISTS xu_heroes;", []driver.NamedValue{})
    if r1.err.len > 0 {
        println("   [FAIL] Drop table error: " + r1.err)
        conn.close()
        <<
    }
    r2 := conn.exec("CREATE TABLE xu_heroes (id INTEGER PRIMARY KEY, name VARCHAR(50), power INTEGER);", []driver.NamedValue{})
    if r2.err.len > 0 {
        println("   [FAIL] Create table error: " + r2.err)
        conn.close()
        <<
    }
    println("   [PASS] Table 'xu_heroes' created.")

    // 3. Exec DML Insert
    $args1 := []driver.NamedValue{}
    args1.push(driver.NamedValue{ordinal: 1, name: "", value: 1})
    args1.push(driver.NamedValue{ordinal: 2, name: "", value: "Ironman"})
    args1.push(driver.NamedValue{ordinal: 3, name: "", value: 100})
    r3 := conn.exec("INSERT INTO xu_heroes (id, name, power) VALUES ($$1, $$2, $$3);", args1)
    if r3.err.len > 0 {
        println("   [FAIL] Insert error: " + r3.err)
        conn.close()
        <<
    }
    println("   [PASS] Hero inserted (rows=" + str(r3.rows_affected) + ").")

    // 4. Query
    $q_args := []driver.NamedValue{}
    q_args.push(driver.NamedValue{ordinal: 1, name: "", value: 1})
    rows := conn.query("SELECT id, name, power FROM xu_heroes WHERE id = $$1;", q_args)
    if rows.err.len > 0 {
        println("   [FAIL] Query error: " + rows.err)
        conn.close()
        <<
    }
    println("   [PASS] Query executed, columns count: " + str(rows.columns.len))
    $i := 0
    while i < rows.columns.len {
        println("      Col[" + str(i) + "]: " + rows.columns[i])
        i = i + 1
    }
    println("   Total cells retrieved: " + str(rows.cells.len))
    $j := 0
    while j < rows.cells.len {
        println("      Cell[" + str(j) + "]: " + rows.cells[j])
        j = j + 1
    }

    // 5. Transaction
    println("   Testing Transaction Commit...")
    $tx := conn.begin()
    $args2 := []driver.NamedValue{}
    args2.push(driver.NamedValue{ordinal: 1, name: "", value: 2})
    args2.push(driver.NamedValue{ordinal: 2, name: "", value: "Thor"})
    args2.push(driver.NamedValue{ordinal: 3, name: "", value: 200})
    tx_res := conn.exec("INSERT INTO xu_heroes (id, name, power) VALUES ($$1, $$2, $$3);", args2)
    if tx_res.err.len > 0 {
        println("   [FAIL] Tx insert error: " + tx_res.err)
    }
    tx_err := tx.commit()
    if tx_err.len > 0 {
        println("   [FAIL] Tx commit error: " + tx_err)
    } else {
        println("   [PASS] Transaction committed.")
    }

    // 6. Reset session
    ctx := context.background()
    reset_err := conn.reset_session(&ctx)
    if reset_err.len > 0 {
        println("   [FAIL] Reset session error: " + reset_err)
    } else {
        println("   [PASS] Reset session completed.")
    }

    // 7. Close
    close_err := conn.close()
    if close_err.len > 0 {
        println("   [FAIL] Close error: " + close_err)
    } else {
        println("   [PASS] Connection closed cleanly.")
    }
}

fn verify_postgres_pool() {
    println("\n--- Testing Native Postgres Connection Pool ---")
    dsn := "postgres://zicq:zicq@127.0.0.1:5432/xu_demo?sslmode=disable"
    $pool := postgres.open_pool(dsn + "", 5, 2)

    pool.ping() >>> (err) {
        println("   [FAIL] Pool ping error: " + err.msg())
        <<
    }
    println("   [PASS] Postgres Pool ping succeeded.")

    // 1. DDL
    pool.exec("DROP TABLE IF EXISTS xu_pool_users;") >>> (err) {
        println("   [FAIL] Drop table error: " + err.msg())
        <<
    }
    pool.exec("CREATE TABLE xu_pool_users (id INTEGER PRIMARY KEY, name VARCHAR(50), balance INTEGER);") >>> (err) {
        println("   [FAIL] Create table error: " + err.msg())
        <<
    }
    println("   [PASS] Pool created table xu_pool_users.")

    // 2. Concurrency / multiple inserts
    $i := 1
    while i <= 5 {
        pool.exec("INSERT INTO xu_pool_users (id, name, balance) VALUES ($$1, $$2, $$3);", i, "User_" + str(i), i * 100) >>> (err) {
            println("   [FAIL] Insert row error: " + err.msg())
            <<
        }
        i = i + 1
    }
    println("   [PASS] Concurrently inserted 5 rows across pooled connections.")

    // 3. Query
    $rows := pool.query("SELECT id, name, balance FROM xu_pool_users ORDER BY id;") >>> (err) {
        println("   [FAIL] Pool query error: " + err.msg())
        <<
    }
    $count := 0
    while rows.next() {
        vals := rows.take() >>> (err) {
            println("   [FAIL] rows.take error: " + err.msg())
            <<
        }
        uid := vals[0] as int
        uname := vals[1] as string
        ubal := vals[2] as int
        println("      Row[" + str(count) + "]: id=" + str(uid) + ", name=" + uname + ", bal=" + str(ubal))
        count = count + 1
    }
    rows.close()
    if count == 5 {
        println("   [PASS] Pool query verified 5 rows.")
    } else {
        println("   [FAIL] Row count mismatch: " + str(count))
    }

    // 4. Transaction via Pool
    $tx := pool.begin() >>> (err) {
        println("   [FAIL] Pool begin tx error: " + err.msg())
        <<
    }
    tx.exec("INSERT INTO xu_pool_users (id, name, balance) VALUES ($$1, $$2, $$3);", 6, "User_6", 600) >>> (err) {
        println("   [FAIL] Tx insert error: " + err.msg())
        <<
    }
    tx.commit() >>> (err) {
        println("   [FAIL] Tx commit error: " + err.msg())
        <<
    }
    println("   [PASS] Transaction committed via pool.")

    // 5. Cleanup & Close
    pool.exec("DROP TABLE IF EXISTS xu_pool_users;") >>> (err) {
        println("   [FAIL] Cleanup table error: " + err.msg())
        <<
    }
    pool.close() >>> (err) {
        println("   [FAIL] Pool close error: " + err.msg())
        <<
    }
    println("   [PASS] Postgres Pool closed cleanly.")
}

fn main() {
    println("=== Xu PostgreSQL Native Driver Verification ===\n")
    verify_postgres_live()
    verify_postgres_pool()
    println("\n[POSTGRES VERIFICATION 100% COMPLETED]")
}
35_standalone_mysql/main.xu

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

Xu本地 SDK 示例
@main

mysql #github.com/xulang-org/packages/mysql
#database/sql/driver
#context

fn verify_mysql_live() {
    println("--- Testing Native MySQL/MariaDB Driver Wire Protocol ---")
    dsn := "root:root@tcp(127.0.0.1:3306)/xu_demo?tls=false"
    $conn := mysql.open(dsn)

    // 1. Ping
    err := conn.ping()
    if err.len > 0 {
        println("   [FAIL] Ping failed: " + err)
        conn.close()
        <<
    }
    println("   [PASS] MySQL/MariaDB Ping succeeded.")

    // 2. Exec DDL
    r1 := conn.exec("DROP TABLE IF EXISTS xu_developers;", []driver.NamedValue{})
    if r1.err.len > 0 {
        println("   [FAIL] Drop table error: " + r1.err)
        conn.close()
        <<
    }
    r2 := conn.exec("CREATE TABLE xu_developers (id INT PRIMARY KEY, name VARCHAR(50), commits INT);", []driver.NamedValue{})
    if r2.err.len > 0 {
        println("   [FAIL] Create table error: " + r2.err)
        conn.close()
        <<
    }
    println("   [PASS] Table 'xu_developers' created.")

    // 3. Exec DML Insert
    $args1 := []driver.NamedValue{}
    args1.push(driver.NamedValue{ordinal: 1, name: "", value: 1})
    args1.push(driver.NamedValue{ordinal: 2, name: "", value: "Antigravity"})
    args1.push(driver.NamedValue{ordinal: 3, name: "", value: 500})
    r3 := conn.exec("INSERT INTO xu_developers (id, name, commits) VALUES (?, ?, ?);", args1)
    if r3.err.len > 0 {
        println("   [FAIL] Insert error: " + r3.err)
        conn.close()
        <<
    }
    println("   [PASS] Developer inserted (rows=" + str(r3.rows_affected) + ").")

    // 4. Query
    $q_args := []driver.NamedValue{}
    q_args.push(driver.NamedValue{ordinal: 1, name: "", value: 1})
    rows := conn.query("SELECT id, name, commits FROM xu_developers WHERE id = ?;", q_args)
    if rows.err.len > 0 {
        println("   [FAIL] Query error: " + rows.err)
        conn.close()
        <<
    }
    println("   [PASS] Query executed, columns count: " + str(rows.columns.len))
    $i := 0
    while i < rows.columns.len {
        println("      Col[" + str(i) + "]: " + rows.columns[i])
        i = i + 1
    }
    println("   Total cells retrieved: " + str(rows.cells.len))
    $j := 0
    while j < rows.cells.len {
        println("      Cell[" + str(j) + "]: " + rows.cells[j])
        j = j + 1
    }

    // 5. Transaction
    println("   Testing Transaction Commit...")
    $tx := conn.begin()
    $args2 := []driver.NamedValue{}
    args2.push(driver.NamedValue{ordinal: 1, name: "", value: 2})
    args2.push(driver.NamedValue{ordinal: 2, name: "", value: "XuArchitect"})
    args2.push(driver.NamedValue{ordinal: 3, name: "", value: 1000})
    tx_res := conn.exec("INSERT INTO xu_developers (id, name, commits) VALUES (?, ?, ?);", args2)
    if tx_res.err.len > 0 {
        println("   [FAIL] Tx insert error: " + tx_res.err)
    }
    tx_err := tx.commit()
    if tx_err.len > 0 {
        println("   [FAIL] Tx commit error: " + tx_err)
    } else {
        println("   [PASS] Transaction committed.")
    }

    // 6. Reset session
    ctx := context.background()
    reset_err := conn.reset_session(&ctx)
    if reset_err.len > 0 {
        println("   [FAIL] Reset session error: " + reset_err)
    } else {
        println("   [PASS] Reset session completed.")
    }

    // 7. Close
    close_err := conn.close()
    if close_err.len > 0 {
        println("   [FAIL] Close error: " + close_err)
    } else {
        println("   [PASS] Connection closed cleanly.")
    }
}

fn verify_mysql_pool() {
    println("\n--- Testing Native MySQL/MariaDB Connection Pool ---")
    dsn := "root:root@tcp(127.0.0.1:3306)/xu_demo?tls=false"
    $pool := mysql.open_pool(dsn + "", 5, 2)

    pool.ping() >>> (err) {
        println("   [FAIL] Pool ping error: " + err.msg())
        <<
    }
    println("   [PASS] MySQL Pool ping succeeded.")

    // 1. DDL
    pool.exec("DROP TABLE IF EXISTS xu_pool_orders;") >>> (err) {
        println("   [FAIL] Drop table error: " + err.msg())
        <<
    }
    pool.exec("CREATE TABLE xu_pool_orders (id INT PRIMARY KEY, title VARCHAR(50), amount INT);") >>> (err) {
        println("   [FAIL] Create table error: " + err.msg())
        <<
    }
    println("   [PASS] Pool created table xu_pool_orders.")

    // 2. Concurrency / multiple inserts
    $i := 1
    while i <= 5 {
        pool.exec("INSERT INTO xu_pool_orders (id, title, amount) VALUES (?, ?, ?);", i, "Order_" + str(i), i * 150) >>> (err) {
            println("   [FAIL] Insert row error: " + err.msg())
            <<
        }
        i = i + 1
    }
    println("   [PASS] Concurrently inserted 5 rows across pooled connections.")

    // 3. Query
    $rows := pool.query("SELECT id, title, amount FROM xu_pool_orders ORDER BY id;") >>> (err) {
        println("   [FAIL] Pool query error: " + err.msg())
        <<
    }
    $count := 0
    while rows.next() {
        vals := rows.take() >>> (err) {
            println("   [FAIL] rows.take error: " + err.msg())
            <<
        }
        oid := vals[0] as int
        otitle := vals[1] as string
        oamt := vals[2] as int
        println("      Row[" + str(count) + "]: id=" + str(oid) + ", title=" + otitle + ", amount=" + str(oamt))
        count = count + 1
    }
    rows.close()
    if count == 5 {
        println("   [PASS] Pool query verified 5 rows.")
    } else {
        println("   [FAIL] Row count mismatch: " + str(count))
    }

    // 4. Transaction via Pool
    $tx := pool.begin() >>> (err) {
        println("   [FAIL] Pool begin tx error: " + err.msg())
        <<
    }
    tx.exec("INSERT INTO xu_pool_orders (id, title, amount) VALUES (?, ?, ?);", 6, "Order_6", 900) >>> (err) {
        println("   [FAIL] Tx insert error: " + err.msg())
        <<
    }
    tx.commit() >>> (err) {
        println("   [FAIL] Tx commit error: " + err.msg())
        <<
    }
    println("   [PASS] Transaction committed via pool.")

    // 5. Cleanup & Close
    pool.exec("DROP TABLE IF EXISTS xu_pool_orders;") >>> (err) {
        println("   [FAIL] Cleanup table error: " + err.msg())
        <<
    }
    pool.close() >>> (err) {
        println("   [FAIL] Pool close error: " + err.msg())
        <<
    }
    println("   [PASS] MySQL Pool closed cleanly.")
}

fn main() {
    println("=== Xu MySQL / MariaDB Native Driver Verification ===\n")
    verify_mysql_live()
    verify_mysql_pool()
    println("\n[MYSQL VERIFICATION 100% COMPLETED]")
}

API 声明

struct Context

XuAPI
pub struct Context {
    pub done chan int
    pub deadline_ns int
    pub keys []string
    pub vals []string
}

用途

承载 done、deadline_ns、keys、vals 等属性的结构体。

公开字段

done chan int
字段(通道;类型 chan int)
deadline_ns int
字段(int)
keys []string
字段([]string)
vals []string
字段([]string)

struct Cancel

XuAPI
pub struct Cancel {
    pub ctx Context
}

用途

承载 ctx 等属性的结构体。

公开字段

ctx Context
字段(Context)

background

XuAPI
pub fn background() Context

用途

创建没有截止时间、不会自动取消的基础上下文,作为独立任务的起点。

参数

无需传入参数。

返回值

新的 Context;deadline_ns 为 0,键值为空,done 等待取消。

查看用法示例

with_cancel

XuAPI
pub fn with_cancel() Cancel

用途

创建可以主动取消的独立上下文;保留返回的控制句柄,在任务结束或需要中止时调用 cancel。

参数

无需传入参数。

返回值

包含上下文 ctx 和取消能力的 Cancel;不接收或继承父上下文。

($&Cancel) cancel

XuAPI
pub fn (c $&Cancel) cancel()

用途

发出取消信号,关闭此句柄的 ctx.done,让等待该通道的任务结束等待。

参数

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

返回值

不返回值;重复调用不会重复关闭通道。

with_cancel_parent

XuAPI
pub fn with_cancel_parent(parent &Context) Cancel

用途

从父上下文派生可取消的子任务;父任务取消时会把取消信号传给子任务。

参数

parent &Context
父上下文;复制其字符串键值和截止时间,并监听它的取消通道。

返回值

控制子上下文的 Cancel。主动取消子任务不会取消父任务。

with_timeout

XuAPI
pub fn with_timeout(timeout_ns int) Cancel

用途

创建在指定时长后自动取消的独立上下文,也可在超时前主动取消。

参数

timeout_ns int
从现在开始等待的纳秒数;1_000_000_000 表示一秒,负数按 0 处理。

返回值

包含截止时间和取消句柄的 Cancel。

使用时注意

  • 超时信号由协程发送;时长为 0 不表示返回时通道一定已经关闭。

with_deadline

XuAPI
pub fn with_deadline(deadline_ns int) Cancel

用途

创建到指定绝对时间后自动取消的独立上下文。

参数

deadline_ns int
与 now_ns() 使用相同时间基准的绝对纳秒时间;不是从现在起等待的时长。

返回值

带此截止时间的 Cancel;过去的时间会安排立即取消。

(Context) deadline

XuAPI
pub fn (c Context) deadline() int

用途

读取此上下文保存的截止时间,不等待超时,也不改变取消状态。

参数

c Context
本次调用使用的 Context 实例;按值接收。

返回值

绝对纳秒时间;background 或 without_cancel 上下文返回 0。

err

XuAPI
pub fn err(c &Context) int

用途

检查上下文是否已经取消或超时;通过正常返回或抛错让调用方决定是否继续工作。

参数

c &Context
要检查的上下文。

返回值

仍有效时返回 0;取消或超时时抛错,不以返回码表示原因。

错误处理

  • 取消时抛出 context canceled;截止时间已到时抛出 context deadline exceeded。

with_value

XuAPI
pub fn with_value(parent &Context, key string, val string) Context

用途

为上下文附加一个字符串键值,适合向子调用传递请求标识等轻量信息。

参数

parent &Context
继承其取消通道、截止时间和已有键值;本调用不修改父上下文。
key string
区分大小写的字符串键;同名键的新值覆盖查找结果。
val string
要保存的字符串值。

返回值

包含新增键值的新 Context,与父上下文共享取消信号。

value

XuAPI
pub fn value(c &Context, key string) string

用途

读取上下文中指定键的字符串值;有多次同名设置时取最近添加的一次。

参数

c &Context
包含键值的上下文。
key string
要查找的完整键名,区分大小写。

返回值

找到的字符串;已存储的空字符串也正常返回。

错误处理

  • 键不存在时抛出 context: no value;需要区分缺失值与空值时应处理此错误。

调用示例

区分缺少键和正常取值

Xu本机 SDK 示例
@main
#context

fn main() {
    base := context.background()
    request := context.with_value(&base, "request_id", "req-42")
    value := context.value(&request, "request_id") >>> (err) {
        println(err.msg())
        <<
    }
    println(value)
    _ := context.value(&request, "missing") >>> (err) {
        println(err.msg())
        <<
    }
}

预期输出:

req-42
context: no value

without_cancel

XuAPI
pub fn without_cancel(parent &Context) Context

用途

复制上下文中的字符串键值,创建可以独立于父任务取消和超时继续工作的上下文。

参数

parent &Context
只复制键值;其取消通道和截止时间不会传给结果。

返回值

新的 Context,截止时间为 0,具有独立的取消通道。