open
pub fn open(addr string) Client用途
打开资源或建立网络连接。失败时抛出错误,调用方需处理或继续传播。
参数
addrstring- 地址(string)
返回值
Client — 该类型的值
#github.com/xulang-org/packages/mongodb扩展包 `mongodb #github.com/xulang-org/packages/mongodb`,由模块 github.com/xulang-org/packages 提供。
github.com/xulang-org/packages · 1.17.2 · 安装与使用
以下源码来自官方 examples 仓库,可复制或下载。请在完整工程中使用本地 Xu SDK 运行;网络、数据库和桌面示例需要对应的服务或资源。
31_standalone_mongodb/main.xu@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]")
}openpub fn open(addr string) Client打开资源或建立网络连接。失败时抛出错误,调用方需处理或继续传播。
addr stringClient — 该类型的值
open_poolpub fn open_pool(addr string, max_idle int) Pool执行 open pool 操作。
addr stringmax_idle intPool — 该类型的值
encode_i32pub fn encode_i32(v int) string编码 i32 数据。
v intstring — 结果字符串
encode_i64pub fn encode_i64(v int) string编码 i64 数据。
v intstring — 结果字符串
decode_i32pub fn decode_i32(s &string, off int) int解码 i32 数据。
s &stringoff intint — 该类型的值
build_docpub fn build_doc(elements string) string执行 build doc 操作。
elements stringstring — 结果字符串
bson_stringpub fn bson_string(name string, val string) string执行 bson string 操作。
name stringval stringstring — 结果字符串
bson_int32pub fn bson_int32(name string, val int) string执行 bson int32 操作。
name stringval intstring — 结果字符串
bson_int64pub fn bson_int64(name string, val int) string执行 bson int64 操作。
name stringval intstring — 结果字符串
bson_boolpub fn bson_bool(name string, val bool) string执行 bson bool 操作。
name stringval boolstring — 结果字符串
bson_docpub fn bson_doc(name string, doc_bytes string) string执行 bson doc 操作。
name stringdoc_bytes stringstring — 结果字符串
bson_arraypub fn bson_array(name string, arr_bytes string) string执行 bson array 操作。
name stringarr_bytes stringstring — 结果字符串
bson_object_idpub fn bson_object_id(name string, oid_bytes string) string执行 bson object id 操作。
name stringoid_bytes stringstring — 结果字符串
bson_utc_datetimepub fn bson_utc_datetime(name string, millis int) string执行 bson utc datetime 操作。
name stringmillis intstring — 结果字符串
bson_nullpub fn bson_null(name string) string执行 bson null 操作。
name stringstring — 结果字符串
find_bson_stringpub fn find_bson_string(doc string, target_field string) string执行 find bson string 操作。
doc stringtarget_field stringstring — 结果字符串
is_bson_okpub fn is_bson_ok(doc string) bool判断是否 bson ok。
doc stringbool — 是否成立
struct Clientpub struct Client {
pub fd int
pub addr string
pub next_req_id int
}Mongodb 客户端会话实例,维护与服务端的连接并提供操作接口。
fd intaddr stringnext_req_id int($&Client) write_exactpub fn (c $&Client) write_exact(data string) int$&Client 上的操作:执行 write exact 操作。失败时抛出错误,调用方需处理或继续传播。
c $&ClientClient 实例;以独占借用传入,方法可修改它,调用方仍持有实例。data stringint — 该类型的值
($&Client) read_exactpub fn (c $&Client) read_exact(n int) string$&Client 上的操作:执行 read exact 操作。失败时抛出错误,调用方需处理或继续传播。
c $&ClientClient 实例;以独占借用传入,方法可修改它,调用方仍持有实例。n intstring — 结果字符串
($&Client) run_commandpub fn (c $&Client) run_command(db_name string, cmd_elements string) string$&Client 上的操作:运行命令。失败时抛出错误,调用方需处理或继续传播。
c $&ClientClient 实例;以独占借用传入,方法可修改它,调用方仍持有实例。db_name stringcmd_elements stringstring — 结果字符串
connectpub fn connect(addr string) Client执行 connect 处理。失败时抛出错误,调用方需处理或继续传播。
addr stringClient — 该类型的值
($&Client) hellopub fn (c $&Client) hello() bool在 $&Client 上执行 hello 操作。
c $&ClientClient 实例;以独占借用传入,方法可修改它,调用方仍持有实例。bool — 是否成立
($&Client) insert_onepub fn (c $&Client) insert_one(db_name string, col_name string, doc_bytes string) int$&Client 上的操作:执行 insert one 操作。失败时抛出错误,调用方需处理或继续传播。
c $&ClientClient 实例;以独占借用传入,方法可修改它,调用方仍持有实例。db_name stringcol_name stringdoc_bytes stringint — 该类型的值
($&Client) find_first_stringpub fn (c $&Client) find_first_string(db_name string, col_name string, target_field string) string$&Client 上的操作:执行 find first string 操作。失败时抛出错误,调用方需处理或继续传播。
c $&ClientClient 实例;以独占借用传入,方法可修改它,调用方仍持有实例。db_name stringcol_name stringtarget_field stringstring — 结果字符串
($&Client) drop_collectionpub fn (c $&Client) drop_collection(db_name string, col_name string) bool$&Client 上的操作:执行 drop collection 操作。
c $&ClientClient 实例;以独占借用传入,方法可修改它,调用方仍持有实例。db_name stringcol_name stringbool — 是否成立
($&Client) closepub fn (c $&Client) close()$&Client 上的操作:关闭资源。
c $&ClientClient 实例;以独占借用传入,方法可修改它,调用方仍持有实例。不返回值。
struct Poolpub struct Pool {
pub addr string
pub idle chan int
pub max_idle int
}Mongodb 连接池管理器,并发安全地维护和调度复用套接字连接。
addr stringidle chan intmax_idle intnew_poolpub fn new_pool(addr string, max_idle int) Pool构造 pool。
addr stringmax_idle intPool — 该类型的值
(&Pool) getpub fn (p &Pool) get() Client在 &Pool 上执行 get 操作。失败时抛出错误,调用方需处理或继续传播。
p &PoolPool 实例;以只读借用传入,调用方仍持有实例。Client — 该类型的值
(&Pool) put_connpub fn (p &Pool) put_conn(fd int)&Pool 上的操作:执行 put conn 操作。
p &PoolPool 实例;以只读借用传入,调用方仍持有实例。fd int不返回值。
(&Pool) putpub fn (p &Pool) put(c Client)写入或更新指定键对应的值数据。
p &PoolPool 实例;以只读借用传入,调用方仍持有实例。c Client不返回值。
(&Pool) hellopub fn (p &Pool) hello() bool在 &Pool 上执行 hello 操作。
p &PoolPool 实例;以只读借用传入,调用方仍持有实例。bool — 是否成立
(&Pool) insert_onepub fn (p &Pool) insert_one(db_name string, col_name string, doc_bytes string) int&Pool 上的操作:执行 insert one 操作。失败时抛出错误,调用方需处理或继续传播。
p &PoolPool 实例;以只读借用传入,调用方仍持有实例。db_name stringcol_name stringdoc_bytes stringint — 该类型的值
(&Pool) find_first_stringpub fn (p &Pool) find_first_string(db_name string, col_name string, target_field string) string&Pool 上的操作:执行 find first string 操作。失败时抛出错误,调用方需处理或继续传播。
p &PoolPool 实例;以只读借用传入,调用方仍持有实例。db_name stringcol_name stringtarget_field stringstring — 结果字符串
(&Pool) drop_collectionpub fn (p &Pool) drop_collection(db_name string, col_name string) bool&Pool 上的操作:执行 drop collection 操作。
p &PoolPool 实例;以只读借用传入,调用方仍持有实例。db_name stringcol_name stringbool — 是否成立
(&Pool) closepub fn (p &Pool) close()&Pool 上的操作:关闭资源。
p &PoolPool 实例;以只读借用传入,调用方仍持有实例。不返回值。
encode_op_msgpub fn encode_op_msg(request_id int, doc_bytes string) string编码 op msg 数据。
request_id intdoc_bytes stringstring — 结果字符串
decode_op_msg_docpub fn decode_op_msg_doc(raw string) string解码 op msg doc 数据。失败时抛出错误,调用方需处理或继续传播。
raw stringstring — 结果字符串
struct TlsClientpub struct TlsClient {
pub conn transport.Conn
pub host string
pub port int
}Mongodb 客户端会话实例,维护与服务端的连接并提供操作接口。
conn transport.Connhost stringport inttls_connectpub fn tls_connect(endpoint string, default_port int) TlsClient执行 tls connect 操作。失败时抛出错误,调用方需处理或继续传播。
endpoint stringdefault_port intTlsClient — 该类型的值
tls_connect_configpub fn tls_connect_config(endpoint string, default_port int, cfg tls.Config) TlsClient执行 tls connect config 操作。失败时抛出错误,调用方需处理或继续传播。
endpoint stringdefault_port intcfg tls.ConfigTlsClient — 该类型的值
($&TlsClient) write_allpub fn (c $&TlsClient) write_all(data string) int$&TlsClient 上的操作:执行 write all 操作。失败时抛出错误,调用方需处理或继续传播。
c $&TlsClientTlsClient 实例;以独占借用传入,方法可修改它,调用方仍持有实例。data stringint — 该类型的值
($&TlsClient) readpub fn (c $&TlsClient) read(max int) string$&TlsClient 上的操作:读出最多 max 字节。失败时抛出错误,调用方需处理或继续传播。
c $&TlsClientTlsClient 实例;以独占借用传入,方法可修改它,调用方仍持有实例。max intstring — 结果字符串
($&TlsClient) read_exactpub fn (c $&TlsClient) read_exact(need int) string$&TlsClient 上的操作:执行 read exact 操作。失败时抛出错误,调用方需处理或继续传播。
c $&TlsClientTlsClient 实例;以独占借用传入,方法可修改它,调用方仍持有实例。need intstring — 结果字符串
($&TlsClient) closepub fn (c $&TlsClient) close() int$&TlsClient 上的操作:关闭资源。失败时抛出错误,调用方需处理或继续传播。
c $&TlsClientTlsClient 实例;以独占借用传入,方法可修改它,调用方仍持有实例。int — 该类型的值
($&TlsClient) set_deadlinepub fn (c $&TlsClient) set_deadline(t_ns int) int$&TlsClient 上的操作:设置 deadline。失败时抛出错误,调用方需处理或继续传播。
c $&TlsClientTlsClient 实例;以独占借用传入,方法可修改它,调用方仍持有实例。t_ns intint — 该类型的值
($&TlsClient) set_read_deadlinepub fn (c $&TlsClient) set_read_deadline(t_ns int) int$&TlsClient 上的操作:设置 read deadline。失败时抛出错误,调用方需处理或继续传播。
c $&TlsClientTlsClient 实例;以独占借用传入,方法可修改它,调用方仍持有实例。t_ns intint — 该类型的值
($&TlsClient) set_write_deadlinepub fn (c $&TlsClient) set_write_deadline(t_ns int) int$&TlsClient 上的操作:设置 write deadline。失败时抛出错误,调用方需处理或继续传播。
c $&TlsClientTlsClient 实例;以独占借用传入,方法可修改它,调用方仍持有实例。t_ns intint — 该类型的值