#context
Xu 0.16.0 API
import: #context
counts: 9 functions, 2 methods, 2 types, 0 constants, 0 method sets
Carry cancellation, deadlines and string key-value pairs between tasks. Wait on Context.done for cancellation; retain the returned Cancel and call cancel when a task must end early.
Examples · API declarations
Examples
These sources come from the official examples repository and can be copied or downloaded. Run them with a local Xu SDK in the complete project; network, database, and desktop examples require the corresponding services or assets.
34_standalone_postgres/main.xu
Required SDK: Xu 0.8.3 · Complete project · Download source
@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
Required SDK: Xu 0.8.3 · Complete project · Download source
@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 declarations
struct Context
pub struct Context {
pub done chan int
pub deadline_ns int
pub keys []string
pub vals []string
}
Purpose
Structure encapsulating done, deadline_ns, keys, vals.
Public fields
done chan int- field (channel; type chan int)
deadline_ns int- field (int)
keys []string- field ([]string)
vals []string- field ([]string)
struct Cancel
pub struct Cancel {
pub ctx Context
}
Purpose
Structure encapsulating ctx.
Public fields
ctx Context- field (Context)
background
pub fn background() Context
Purpose
Create an independent context with no deadline or automatic cancellation.
Parameters
No arguments are required.
Returns
A new Context with deadline 0, no values and an open done channel.
See usage example
with_cancel
pub fn with_cancel() Cancel
Purpose
Create an independent, manually cancellable context; retain the handle to cancel it when the task ends.
Parameters
No arguments are required.
Returns
A Cancel containing ctx and cancellation control; it takes no parent context.
($&Cancel) cancel
pub fn (c $&Cancel) cancel()
Purpose
Signal cancellation by closing this handle's ctx.done, releasing tasks waiting on that channel.
Parameters
c $&Cancel- The
Cancel instance used by this call (exclusive borrow).
Returns
No return value; repeated calls do not close the channel twice.
with_cancel_parent
pub fn with_cancel_parent(parent &Context) Cancel
Purpose
Derive a cancellable child whose cancellation follows its parent.
Parameters
parent &Context- Parent context; its string values and deadline are copied, and its cancellation channel is observed.
Returns
A Cancel controlling the child. Cancelling the child does not cancel its parent.
with_timeout
pub fn with_timeout(timeout_ns int) Cancel
Purpose
Create an independent context that cancels after a duration, or earlier through its cancel handle.
Parameters
timeout_ns int- Duration from now in nanoseconds;
1_000_000_000 is one second. Negative durations are treated as zero.
Returns
A Cancel containing the deadline and cancellation handle.
Usage notes
- A coroutine sends the timeout signal; a zero duration does not guarantee that the channel is already closed on return.
with_deadline
pub fn with_deadline(deadline_ns int) Cancel
Purpose
Create an independent context that cancels at an absolute deadline.
Parameters
deadline_ns int- Absolute nanosecond timestamp using the same clock as
now_ns(), not a duration from now.
Returns
A Cancel with this deadline; a past timestamp schedules immediate cancellation.
(Context) deadline
pub fn (c Context) deadline() int
Purpose
Read the stored deadline without waiting or changing cancellation state.
Parameters
c Context- The
Context instance used by this call (value receiver).
Returns
Absolute nanosecond deadline, or 0 for a background or without_cancel context.
err
pub fn err(c &Context) int
Purpose
Check cancellation and expiry, returning normally only while work may continue.
Parameters
c &Context- Context to check.
Returns
Returns 0 while active; cancellation and expiry throw instead of returning a status code.
Error handling
- Throws
context canceled on cancellation or context deadline exceeded after the deadline.
with_value
pub fn with_value(parent &Context, key string, val string) Context
Purpose
Attach a string key-value pair, such as a request identifier, for downstream calls.
Parameters
parent &Context- Parent whose cancellation channel, deadline and existing values are inherited without modifying it.
key string- Case-sensitive string key; a newer value shadows an existing key.
val string- String value to store.
Returns
A new Context with the added value and shared parent cancellation.
value
pub fn value(c &Context, key string) string
Purpose
Read a string value, choosing the most recently added value for a repeated key.
Parameters
c &Context- Context containing the values.
key string- Exact, case-sensitive key to find.
Returns
Stored string, including a legitimately empty string.
Error handling
- A missing key throws
context: no value; handle this to distinguish absence from an empty value.
Call example
Read a value and handle a missing key
@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())
<<
}
}
Expected output:
req-42
context: no value
without_cancel
pub fn without_cancel(parent &Context) Context
Purpose
Copy string values into a context independent of its parent's cancellation and deadline.
Parameters
parent &Context- Source of values; its cancellation channel and deadline are not carried into the result.
Returns
A new Context with deadline 0 and an independent open cancellation channel.