XU XUv0.16.0

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

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

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

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

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

示例代码 · API 声明

示例代码

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

31_standalone_mongodb/main.xu

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

Xu本地 SDK 示例
@main

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

fn verify_mongodb_hello() {
    println("--- 1. Testing MongoDB Hello Handshake ---")
    $client := mongodb.open("127.0.0.1:27017") >>> (err) {
        println("   [FAIL] Connect error: " + err.msg())
        <<
    }
    is_ok := client.hello()
    if is_ok {
        println("   [PASS] MongoDB hello handshake succeeded.")
    } else {
        println("   [FAIL] MongoDB hello handshake failed.")
    }
    client.close()
}

fn verify_mongodb_crud() {
    println("\n--- 2. Testing MongoDB Document CRUD ---")
    $client := mongodb.open("127.0.0.1:27017") >>> (err) {
        println("   [FAIL] Connect error: " + err.msg())
        <<
    }

    db_name := "xu_test_db"
    col_name := "users"

    // 1. Drop collection if exists
    println("   Cleaning up existing collection...")
    client.drop_collection(db_name + "", col_name + "")

    // 2. Insert document
    println("   Inserting document: name='Antigravity', role='AI Assistant'...")
    $doc := mongodb.bson_string("name", "Antigravity")
    doc = doc + mongodb.bson_string("role", "AI Assistant")
    doc = doc + mongodb.bson_int32("stars", 100)

    client.insert_one(db_name + "", col_name + "", doc) >>> (err) {
        println("   [FAIL] Insert failed: " + err.msg())
        client.close()
        <<
    }
    println("   [PASS] Document inserted.")

    // 3. Find first document string field
    println("   Querying document field 'role'...")
    role := client.find_first_string(db_name + "", col_name + "", "role") >>> (err) {
        println("   [FAIL] Query failed: " + err.msg())
        client.close()
        <<
    }
    println("   Retrieved role: " + role)
    if role == "AI Assistant" {
        println("   [PASS] Field value matches exactly!")
    } else {
        println("   [FAIL] Field mismatch: expected 'AI Assistant', got: " + role)
    }

    // 4. Clean up
    println("   Dropping collection...")
    client.drop_collection(db_name + "", col_name + "")
    println("   [PASS] Collection cleaned up.")

    client.close()
}

fn verify_mongodb_pool() {
    println("\n--- 3. Testing MongoDB Connection Pool ---")
    $p := mongodb.open_pool("127.0.0.1:27017", 5)

    // 1. Connection Reuse Test
    $c1 := p.get() >>> (err) {
        println("   [FAIL] Failed to get c1: " + err.msg())
        <<
    }
    fd1 := c1.fd
    println("   Borrow 1 fd: " + str(fd1))
    p.put(c1)

    $c2 := p.get() >>> (err) {
        println("   [FAIL] Failed to get c2: " + err.msg())
        <<
    }
    fd2 := c2.fd
    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
    $c3 := p.get() >>> (err) {
        println("   [FAIL] Failed to get c3: " + err.msg())
        <<
    }
    fd3 := c3.fd
    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(c2)
    p.put(c3)

    // 3. Delegated CRUD Operations via Pool
    println("   Testing delegated operations via pool...")
    p.drop_collection("xu_test_db", "pool_users")

    $doc := mongodb.bson_string("name", "PoolWorker")
    doc = doc + mongodb.bson_string("dept", "CoreEngine")
    p.insert_one("xu_test_db", "pool_users", doc) >>> (err) {
        println("   [FAIL] Pool insert_one error: " + err.msg())
        <<
    }
    println("   [PASS] Pool delegated insert_one succeeded.")

    dept := p.find_first_string("xu_test_db", "pool_users", "dept") >>> (err) {
        println("   [FAIL] Pool find_first_string error: " + err.msg())
        <<
    }
    println("   Retrieved dept via pool: " + dept)
    if dept == "CoreEngine" {
        println("   [PASS] Pool delegated query matched exactly!")
    } else {
        println("   [FAIL] Pool delegated query mismatch!")
    }

    p.drop_collection("xu_test_db", "pool_users")
    println("   [PASS] Pool delegated collection cleanup succeeded.")

    p.close()
    println("   [PASS] MongoDB Pool closed cleanly.")
}

fn main() {
    println("=== Xu MongoDB Document Database Native Driver Verification ===\n")
    verify_mongodb_hello()
    verify_mongodb_crud()
    verify_mongodb_pool()
    println("\n[MONGODB VERIFICATION 100% COMPLETED]")
}

API 声明

open

XuAPI
pub fn open(addr string) Client

用途

打开资源或建立网络连接。失败时抛出错误,调用方需处理或继续传播。

参数

addr string
地址(string)

返回值

Client — 该类型的值

查看用法示例

open_pool

XuAPI
pub fn open_pool(addr string, max_idle int) Pool

用途

执行 open pool 操作。

参数

addr string
地址(string)
max_idle int
max_idle(int)

返回值

Pool — 该类型的值

查看用法示例

encode_i32

XuAPI
pub fn encode_i32(v int) string

用途

编码 i32 数据。

参数

v int
值(int)

返回值

string — 结果字符串

encode_i64

XuAPI
pub fn encode_i64(v int) string

用途

编码 i64 数据。

参数

v int
值(int)

返回值

string — 结果字符串

decode_i32

XuAPI
pub fn decode_i32(s &string, off int) int

用途

解码 i32 数据。

参数

s &string
源字符串(只读借用,调用方仍持有原值;类型 &string)
off int
偏移(int)

返回值

int — 该类型的值

build_doc

XuAPI
pub fn build_doc(elements string) string

用途

执行 build doc 操作。

参数

elements string
elements(string)

返回值

string — 结果字符串

bson_string

XuAPI
pub fn bson_string(name string, val string) string

用途

执行 bson string 操作。

参数

name string
名字(string)
val string
值(string)

返回值

string — 结果字符串

查看用法示例

bson_int32

XuAPI
pub fn bson_int32(name string, val int) string

用途

执行 bson int32 操作。

参数

name string
名字(string)
val int
值(int)

返回值

string — 结果字符串

查看用法示例

bson_int64

XuAPI
pub fn bson_int64(name string, val int) string

用途

执行 bson int64 操作。

参数

name string
名字(string)
val int
值(int)

返回值

string — 结果字符串

bson_bool

XuAPI
pub fn bson_bool(name string, val bool) string

用途

执行 bson bool 操作。

参数

name string
名字(string)
val bool
值(bool)

返回值

string — 结果字符串

bson_doc

XuAPI
pub fn bson_doc(name string, doc_bytes string) string

用途

执行 bson doc 操作。

参数

name string
名字(string)
doc_bytes string
doc_bytes(string)

返回值

string — 结果字符串

bson_array

XuAPI
pub fn bson_array(name string, arr_bytes string) string

用途

执行 bson array 操作。

参数

name string
名字(string)
arr_bytes string
arr_bytes(string)

返回值

string — 结果字符串

bson_object_id

XuAPI
pub fn bson_object_id(name string, oid_bytes string) string

用途

执行 bson object id 操作。

参数

name string
名字(string)
oid_bytes string
oid_bytes(string)

返回值

string — 结果字符串

bson_utc_datetime

XuAPI
pub fn bson_utc_datetime(name string, millis int) string

用途

执行 bson utc datetime 操作。

参数

name string
名字(string)
millis int
millis(int)

返回值

string — 结果字符串

bson_null

XuAPI
pub fn bson_null(name string) string

用途

执行 bson null 操作。

参数

name string
名字(string)

返回值

string — 结果字符串

find_bson_string

XuAPI
pub fn find_bson_string(doc string, target_field string) string

用途

执行 find bson string 操作。

参数

doc string
doc(string)
target_field string
target_field(string)

返回值

string — 结果字符串

is_bson_ok

XuAPI
pub fn is_bson_ok(doc string) bool

用途

判断是否 bson ok。

参数

doc string
doc(string)

返回值

bool — 是否成立

struct Client

XuAPI
pub struct Client {
    pub fd int
    pub addr string
    pub next_req_id int
}

用途

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

公开字段

fd int
文件描述符
addr string
地址
next_req_id int
字段(int)

($&Client) write_exact

XuAPI
pub fn (c $&Client) write_exact(data string) int

用途

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

参数

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

返回值

int — 该类型的值

($&Client) read_exact

XuAPI
pub fn (c $&Client) read_exact(n int) string

用途

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

参数

c $&Client
本次调用使用的 Client 实例;以独占借用传入,方法可修改它,调用方仍持有实例。
n int
数量、长度或上限(int)

返回值

string — 结果字符串

($&Client) run_command

XuAPI
pub fn (c $&Client) run_command(db_name string, cmd_elements string) string

用途

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

参数

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

返回值

string — 结果字符串

connect

XuAPI
pub fn connect(addr string) Client

用途

执行 connect 处理。失败时抛出错误,调用方需处理或继续传播。

参数

addr string
地址(string)

返回值

Client — 该类型的值

($&Client) hello

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

用途

在 $&Client 上执行 hello 操作。

参数

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

返回值

bool — 是否成立

($&Client) insert_one

XuAPI
pub fn (c $&Client) insert_one(db_name string, col_name string, doc_bytes string) int

用途

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

参数

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

返回值

int — 该类型的值

($&Client) find_first_string

XuAPI
pub fn (c $&Client) find_first_string(db_name string, col_name string, target_field string) string

用途

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

参数

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

返回值

string — 结果字符串

($&Client) drop_collection

XuAPI
pub fn (c $&Client) drop_collection(db_name string, col_name string) bool

用途

$&Client 上的操作:执行 drop collection 操作。

参数

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

返回值

bool — 是否成立

($&Client) close

XuAPI
pub fn (c $&Client) close()

用途

$&Client 上的操作:关闭资源。

参数

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

返回值

不返回值。

struct Pool

XuAPI
pub struct Pool {
    pub addr string
    pub idle chan int
    pub max_idle int
}

用途

Mongodb 连接池管理器,并发安全地维护和调度复用套接字连接。

公开字段

addr string
地址
idle chan int
字段(通道;类型 chan int)
max_idle int
字段(int)

new_pool

XuAPI
pub fn new_pool(addr string, max_idle int) Pool

用途

构造 pool。

参数

addr string
地址(string)
max_idle int
max_idle(int)

返回值

Pool — 该类型的值

(&Pool) get

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

用途

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

参数

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

返回值

Client — 该类型的值

(&Pool) put_conn

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

用途

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

参数

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

返回值

不返回值。

(&Pool) put

XuAPI
pub fn (p &Pool) put(c Client)

用途

写入或更新指定键对应的值数据。

参数

p &Pool
本次调用使用的 Pool 实例;以只读借用传入,调用方仍持有实例。
c Client
字节或字符码(Client)

返回值

不返回值。

(&Pool) hello

XuAPI
pub fn (p &Pool) hello() bool

用途

在 &Pool 上执行 hello 操作。

参数

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

返回值

bool — 是否成立

(&Pool) insert_one

XuAPI
pub fn (p &Pool) insert_one(db_name string, col_name string, doc_bytes string) int

用途

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

参数

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

返回值

int — 该类型的值

(&Pool) find_first_string

XuAPI
pub fn (p &Pool) find_first_string(db_name string, col_name string, target_field string) string

用途

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

参数

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

返回值

string — 结果字符串

(&Pool) drop_collection

XuAPI
pub fn (p &Pool) drop_collection(db_name string, col_name string) bool

用途

&Pool 上的操作:执行 drop collection 操作。

参数

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

返回值

bool — 是否成立

(&Pool) close

XuAPI
pub fn (p &Pool) close()

用途

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

参数

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

返回值

不返回值。

encode_op_msg

XuAPI
pub fn encode_op_msg(request_id int, doc_bytes string) string

用途

编码 op msg 数据。

参数

request_id int
request_id(int)
doc_bytes string
doc_bytes(string)

返回值

string — 结果字符串

decode_op_msg_doc

XuAPI
pub fn decode_op_msg_doc(raw string) string

用途

解码 op msg doc 数据。失败时抛出错误,调用方需处理或继续传播。

参数

raw string
raw(string)

返回值

string — 结果字符串

struct TlsClient

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

用途

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

公开字段

conn transport.Conn
字段(transport.Conn)
host string
主机
port int
端口

tls_connect

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

用途

执行 tls connect 操作。失败时抛出错误,调用方需处理或继续传播。

参数

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

返回值

TlsClient — 该类型的值

tls_connect_config

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

用途

执行 tls connect config 操作。失败时抛出错误,调用方需处理或继续传播。

参数

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

返回值

TlsClient — 该类型的值

($&TlsClient) write_all

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

用途

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

参数

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

返回值

int — 该类型的值

($&TlsClient) read

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

用途

$&TlsClient 上的操作:读出最多 max 字节。失败时抛出错误,调用方需处理或继续传播。

参数

c $&TlsClient
本次调用使用的 TlsClient 实例;以独占借用传入,方法可修改它,调用方仍持有实例。
max int
上限(int)

返回值

string — 结果字符串

($&TlsClient) read_exact

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

用途

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

参数

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

返回值

string — 结果字符串

($&TlsClient) close

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

用途

$&TlsClient 上的操作:关闭资源。失败时抛出错误,调用方需处理或继续传播。

参数

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

返回值

int — 该类型的值

($&TlsClient) set_deadline

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

用途

$&TlsClient 上的操作:设置 deadline。失败时抛出错误,调用方需处理或继续传播。

参数

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

返回值

int — 该类型的值

($&TlsClient) set_read_deadline

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

用途

$&TlsClient 上的操作:设置 read deadline。失败时抛出错误,调用方需处理或继续传播。

参数

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

返回值

int — 该类型的值

($&TlsClient) set_write_deadline

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

用途

$&TlsClient 上的操作:设置 write deadline。失败时抛出错误,调用方需处理或继续传播。

参数

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

返回值

int — 该类型的值