XU XUv0.16.0

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

import: postgres #github.com/xulang-org/packages/postgres

counts: 17 functions, 7 methods, 4 types, 0 constants, 0 method sets

PostgreSQL database/sql driver. This is a small, dependency-free wire driver. It deliberately uses the extended query protocol for arguments (parameters never get interpolated into SQL) and supports the authentication methods that PostgreSQL servers commonly advertise: trust, cleartext, MD5 and SCRAM-SHA-256. TLS upgrades use PostgreSQL's SSLRequest and preserve the same connection for startup. DSNs accepted by parse_dsn/open postgres://user:password@host:5432/database?sslmode=disable host=127.0.0.1 port=5432 user=postgres password=secret dbname=postgres Defaults are host=127.0.0.1, port=5432, database=user, sslmode=disable.

github.com/xulang-org/packages · 1.17.2 · Install and use

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.

17_database_postgres/main.xu

Required SDK: Xu 0.8.3 · Complete project · Download source

XuLocal SDK example
@main

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

// PostgreSQL:XU_POSTGRES_DSN 可覆盖本地开发默认值。
// 驱动是普通 XU 包,通过 database/sql 接口使用,不依赖编译器内建。

fn main() int {
    $dsn := os.getenv("XU_POSTGRES_DSN")
    if dsn.len == 0 {
        dsn = "postgres://postgres:postgres@127.0.0.1:5432/xu_demo?sslmode=disable"
    }

    $db := sql.open(postgres.driver(), dsn)
    db.ping() >>> (err) {
        println("PostgreSQL ping failed")
        println(err.msg())
        << 1
    }

    db.exec("DROP TABLE IF EXISTS xu_people") >>> (err) {
        println(err.msg())
        << 1
    }
    db.exec("CREATE TABLE xu_people (id INTEGER PRIMARY KEY, name VARCHAR(100) NOT NULL, active BOOLEAN NOT NULL)") >>> (err) {
        println(err.msg())
        << 1
    }

    first := db.exec(
        "INSERT INTO xu_people (id, name, active) VALUES ($$1, $$2, $$3)",
        1,
        "Ada",
        true
    ) >>> (err) {
        println(err.msg())
        << 1
    }
    println("inserted=" + str(first.rows_affected()))

    $insert_person := db.prepare(
        "INSERT INTO xu_people (id, name, active) VALUES ($$1, $$2, $$3)"
    )
    insert_person.exec(2, "Lin", true) >>> (err) {
        println(err.msg())
        << 1
    }
    insert_person.close()

    $tx := db.begin() >>> (err) {
        println(err.msg())
        << 1
    }
    tx.exec(
        "INSERT INTO xu_people (id, name, active) VALUES ($$1, $$2, $$3)",
        3,
        "Grace",
        true
    ) >>> (err) {
        println(err.msg())
        << 1
    }
    tx.commit() >>> (err) {
        println(err.msg())
        << 1
    }

    $rows := db.query("SELECT id, name FROM xu_people ORDER BY id") >>> (err) {
        println(err.msg())
        << 1
    }
    while rows.next() {
        values := rows.take() >>> (err) {
            println(err.msg())
            << 1
        }
        id := values[0] as int
        name := values[1] as string
        println(str(id) + ": " + name)
    }
    if rows.err().len > 0 {
        println(rows.err())
        << 1
    }
    rows.close()

    $qrows := db.query("SELECT name FROM xu_people WHERE id = $$1", 2) >>> (err) {
        println(err.msg())
        << 1
    }
    if qrows.next() {
        vals := qrows.take() >>> (err) {
            println(err.msg())
            << 1
        }
        println("selected=" + (vals[0] as string))
    }
    qrows.close()

    db.close() >>> (err) {
        println(err.msg())
        << 1
    }
    << 0
}
34_standalone_postgres/main.xu

Required SDK: Xu 0.8.3 · Complete project · Download source

XuLocal SDK example
@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]")
}

API declarations

driver

XuAPI
pub fn driver() driver.Driver

Purpose

Return the database driver instance implementing driver.Driver.

Parameters

No arguments are required.

Returns

driver.Driver — a value of this type

See usage example

open

XuAPI
pub fn open(dsn string) driver.Conn

Purpose

Open resource or establish connection.

Parameters

dsn string
dsn (string)

Returns

driver.Conn — a value of this type

See usage example

struct Config

XuAPI
pub struct Config {
    pub host string
    pub port int
    pub user string
    pub password string
    pub database string
    pub ssl_mode string
    pub root_cert_file string
}

Purpose

Postgres Configuration parameters and options set.

Public fields

host string
host
port int
port
user string
field (string)
password string
field (string)
database string
field (string)
ssl_mode string
field (string)
root_cert_file string
field (string)

new_config

XuAPI
pub fn new_config() Config

Purpose

Construct config.

Parameters

No arguments are required.

Returns

Config — a value of this type

parse_dsn

XuAPI
pub fn parse_dsn(dsn string) Config

Purpose

Parse as dsn. Throws on failure; handle the error or propagate it to the caller.

Parameters

dsn string
dsn (string)

Returns

Config — a value of this type

struct PostgresDriver

XuAPI
pub struct PostgresDriver {
    pub tag int
    pub dsn string
}

Purpose

Structure encapsulating tag, dsn.

Public fields

tag int
field (int)
dsn string
field (string)

vector_encode

XuAPI
pub fn vector_encode(v &[]f32) string

Purpose

Vector encode.

Parameters

v &[]f32
value (read-only borrow; caller keeps the original; type &[]f32)

Returns

string — result string

vector_encode_f64

XuAPI
pub fn vector_encode_f64(v &[]f64) string

Purpose

Vector encode f64.

Parameters

v &[]f64
value (read-only borrow; caller keeps the original; type &[]f64)

Returns

string — result string

vector_decode

XuAPI
pub fn vector_decode(raw &string) []f32

Purpose

Vector decode. Throws on failure; handle the error or propagate it to the caller.

Parameters

raw &string
raw (read-only borrow; caller keeps the original; type &string)

Returns

[]f32 — slice result

pgvector_distance_op

XuAPI
pub fn pgvector_distance_op(metric string) string

Purpose

Pgvector distance op. Throws on failure; handle the error or propagate it to the caller.

Parameters

metric string
metric (string)

Returns

string — result string

pgvector_create_extension_sql

XuAPI
pub fn pgvector_create_extension_sql() string

Purpose

Pgvector create extension sql.

Parameters

No arguments are required.

Returns

string — result string

pgvector_create_index_sql

XuAPI
pub fn pgvector_create_index_sql(table string, column string, index_name string, method string, metric string) string

Purpose

Pgvector create index sql. Throws on failure; handle the error or propagate it to the caller.

Parameters

table string
table (string)
column string
column (string)
index_name string
index_name (string)
method string
method (string)
metric string
metric (string)

Returns

string — result string

pgvector_search_sql

XuAPI
pub fn pgvector_search_sql(table string, id_col string, text_col string, vec_col string, metric string, limit int) string

Purpose

Pgvector binary search sql. Throws on failure; handle the error or propagate it to the caller.

Parameters

table string
table (string)
id_col string
id_col (string)
text_col string
text_col (string)
vec_col string
vec_col (string)
metric string
metric (string)
limit int
limit (int)

Returns

string — result string

open_db

XuAPI
pub fn open_db(dsn string) sql.DB

Purpose

Open db.

Parameters

dsn string
dsn (string)

Returns

sql.DB — a value of this type

open_pool

XuAPI
pub fn open_pool(dsn string, max_open int, max_idle int) sql.DB

Purpose

Open pool.

Parameters

dsn string
dsn (string)
max_open int
max_open (int)
max_idle int
max_idle (int)

Returns

sql.DB — a value of this type

See usage example

struct TlsClient

XuAPI
pub struct TlsClient {
    pub conn transport.Conn
    pub host string
    pub port int
}

Purpose

Postgres Client session maintaining connection and operations.

Public fields

conn transport.Conn
field (transport.Conn)
host string
host
port int
port

tls_connect

XuAPI
pub fn tls_connect(endpoint string, default_port int) TlsClient

Purpose

Tls connect. Throws on failure; handle the error or propagate it to the caller.

Parameters

endpoint string
endpoint (string)
default_port int
default_port (int)

Returns

TlsClient — a value of this type

tls_connect_config

XuAPI
pub fn tls_connect_config(endpoint string, default_port int, cfg tls.Config) TlsClient

Purpose

Tls connect config. Throws on failure; handle the error or propagate it to the caller.

Parameters

endpoint string
endpoint (string)
default_port int
default_port (int)
cfg tls.Config
cfg (tls.Config)

Returns

TlsClient — a value of this type

($&TlsClient) write_all

XuAPI
pub fn (c $&TlsClient) write_all(data string) int

Purpose

Operation on $&TlsClient: write all. Throws on failure; handle the error or propagate it to the caller.

Parameters

c $&TlsClient
The TlsClient instance used by this call (exclusive borrow).
data string
data (string)

Returns

int — a value of this type

($&TlsClient) read

XuAPI
pub fn (c $&TlsClient) read(max int) string

Purpose

Operation on $&TlsClient: read up to max bytes. Throws on failure; handle the error or propagate it to the caller.

Parameters

c $&TlsClient
The TlsClient instance used by this call (exclusive borrow).
max int
maximum (int)

Returns

string — result string

($&TlsClient) read_exact

XuAPI
pub fn (c $&TlsClient) read_exact(need int) string

Purpose

Operation on $&TlsClient: read exact. Throws on failure; handle the error or propagate it to the caller.

Parameters

c $&TlsClient
The TlsClient instance used by this call (exclusive borrow).
need int
need (int)

Returns

string — result string

($&TlsClient) close

XuAPI
pub fn (c $&TlsClient) close() int

Purpose

Operation on $&TlsClient: close the resource. Throws on failure; handle the error or propagate it to the caller.

Parameters

c $&TlsClient
The TlsClient instance used by this call (exclusive borrow).

Returns

int — a value of this type

($&TlsClient) set_deadline

XuAPI
pub fn (c $&TlsClient) set_deadline(t_ns int) int

Purpose

Operation on $&TlsClient: set deadline. Throws on failure; handle the error or propagate it to the caller.

Parameters

c $&TlsClient
The TlsClient instance used by this call (exclusive borrow).
t_ns int
t_ns (int)

Returns

int — a value of this type

($&TlsClient) set_read_deadline

XuAPI
pub fn (c $&TlsClient) set_read_deadline(t_ns int) int

Purpose

Operation on $&TlsClient: set read deadline. Throws on failure; handle the error or propagate it to the caller.

Parameters

c $&TlsClient
The TlsClient instance used by this call (exclusive borrow).
t_ns int
t_ns (int)

Returns

int — a value of this type

($&TlsClient) set_write_deadline

XuAPI
pub fn (c $&TlsClient) set_write_deadline(t_ns int) int

Purpose

Operation on $&TlsClient: set write deadline. Throws on failure; handle the error or propagate it to the caller.

Parameters

c $&TlsClient
The TlsClient instance used by this call (exclusive borrow).
t_ns int
t_ns (int)

Returns

int — a value of this type

struct WireResult

XuAPI
pub struct WireResult {
    pub columns []string
    pub cells []string
    pub ncols int
    pub rows_affected int
    pub err string
}

Purpose

Structure encapsulating columns, cells, ncols, rows_affected, err.

Public fields

columns []string
field ([]string)
cells []string
field ([]string)
ncols int
field (int)
rows_affected int
field (int)
err string
error

query_sql

XuAPI
pub fn query_sql(dsn string, q string) WireResult

Purpose

Query sql.

Parameters

dsn string
dsn (string)
q string
q (string)

Returns

WireResult — a value of this type

exec_sql

XuAPI
pub fn exec_sql(dsn string, q string) WireResult

Purpose

Exec sql.

Parameters

dsn string
dsn (string)
q string
q (string)

Returns

WireResult — a value of this type