open
pub fn open(addr string) ClientPurpose
Open resource or establish connection. Throws on failure; handle the error or propagate it to the caller.
Parameters
addrstring- address (string)
Returns
Client — a value of this type
#github.com/xulang-org/packages/mongodbMongoDB Document Database Native Driver for Xu Features Pure native MongoDB Wire Protocol (OP_MSG opcode 2012) implementation. Lightweight BSON encoding and decoding without external dependencies. Full session handshake (hello). Document CRUD: insert_one, find, drop_collection, run_command. Connection pooling via reusable TCP socket channels.
github.com/xulang-org/packages · 1.17.2 · Install and use
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.
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) ClientOpen resource or establish connection. Throws on failure; handle the error or propagate it to the caller.
addr stringClient — a value of this type
open_poolpub fn open_pool(addr string, max_idle int) PoolOpen pool.
addr stringmax_idle intPool — a value of this type
encode_i32pub fn encode_i32(v int) stringEncode i32 data.
v intstring — result string
encode_i64pub fn encode_i64(v int) stringEncode i64 data.
v intstring — result string
decode_i32pub fn decode_i32(s &string, off int) intDecode i32 data.
s &stringoff intint — a value of this type
build_docpub fn build_doc(elements string) stringBuild doc.
elements stringstring — result string
bson_stringpub fn bson_string(name string, val string) stringBson string.
name stringval stringstring — result string
bson_int32pub fn bson_int32(name string, val int) stringBson int32.
name stringval intstring — result string
bson_int64pub fn bson_int64(name string, val int) stringBson int64.
name stringval intstring — result string
bson_boolpub fn bson_bool(name string, val bool) stringBson bool.
name stringval boolstring — result string
bson_docpub fn bson_doc(name string, doc_bytes string) stringBson doc.
name stringdoc_bytes stringstring — result string
bson_arraypub fn bson_array(name string, arr_bytes string) stringBson array.
name stringarr_bytes stringstring — result string
bson_object_idpub fn bson_object_id(name string, oid_bytes string) stringBson object id.
name stringoid_bytes stringstring — result string
bson_utc_datetimepub fn bson_utc_datetime(name string, millis int) stringBson utc datetime.
name stringmillis intstring — result string
bson_nullpub fn bson_null(name string) stringBson null.
name stringstring — result string
find_bson_stringpub fn find_bson_string(doc string, target_field string) stringFind bson string.
doc stringtarget_field stringstring — result string
is_bson_okpub fn is_bson_ok(doc string) boolWhether it is bson ok.
doc stringbool — true or false
struct Clientpub struct Client {
pub fd int
pub addr string
pub next_req_id int
}Mongodb Client session maintaining connection and operations.
fd intaddr stringnext_req_id int($&Client) write_exactpub fn (c $&Client) write_exact(data string) intOperation on $&Client: write exact. Throws on failure; handle the error or propagate it to the caller.
c $&ClientClient instance used by this call (exclusive borrow).data stringint — a value of this type
($&Client) read_exactpub fn (c $&Client) read_exact(n int) stringOperation on $&Client: read exact. Throws on failure; handle the error or propagate it to the caller.
c $&ClientClient instance used by this call (exclusive borrow).n intstring — result string
($&Client) run_commandpub fn (c $&Client) run_command(db_name string, cmd_elements string) stringOperation on $&Client: run command. Throws on failure; handle the error or propagate it to the caller.
c $&ClientClient instance used by this call (exclusive borrow).db_name stringcmd_elements stringstring — result string
connectpub fn connect(addr string) ClientExecute connect. Throws on failure; handle the error or propagate it to the caller.
addr stringClient — a value of this type
($&Client) hellopub fn (c $&Client) hello() boolExecute hello on $&Client.
c $&ClientClient instance used by this call (exclusive borrow).bool — true or false
($&Client) insert_onepub fn (c $&Client) insert_one(db_name string, col_name string, doc_bytes string) intOperation on $&Client: insert one. Throws on failure; handle the error or propagate it to the caller.
c $&ClientClient instance used by this call (exclusive borrow).db_name stringcol_name stringdoc_bytes stringint — a value of this type
($&Client) find_first_stringpub fn (c $&Client) find_first_string(db_name string, col_name string, target_field string) stringOperation on $&Client: find first string. Throws on failure; handle the error or propagate it to the caller.
c $&ClientClient instance used by this call (exclusive borrow).db_name stringcol_name stringtarget_field stringstring — result string
($&Client) drop_collectionpub fn (c $&Client) drop_collection(db_name string, col_name string) boolOperation on $&Client: drop collection.
c $&ClientClient instance used by this call (exclusive borrow).db_name stringcol_name stringbool — true or false
($&Client) closepub fn (c $&Client) close()Operation on $&Client: close the resource.
c $&ClientClient instance used by this call (exclusive borrow).This call does not return a value.
struct Poolpub struct Pool {
pub addr string
pub idle chan int
pub max_idle int
}Connection Pool for MongoDB. Uses channel of socket file descriptors for lightweight and high-throughput pooling.
addr stringidle chan intmax_idle intnew_poolpub fn new_pool(addr string, max_idle int) PoolConstruct pool.
addr stringmax_idle intPool — a value of this type
(&Pool) getpub fn (p &Pool) get() ClientExecute get on &Pool. Throws on failure; handle the error or propagate it to the caller.
p &PoolPool instance used by this call (borrow).Client — a value of this type
(&Pool) put_connpub fn (p &Pool) put_conn(fd int)Operation on &Pool: put connection.
p &PoolPool instance used by this call (borrow).fd intThis call does not return a value.
(&Pool) putpub fn (p &Pool) put(c Client)Store or update the value associated with the specified key.
p &PoolPool instance used by this call (borrow).c ClientThis call does not return a value.
(&Pool) hellopub fn (p &Pool) hello() boolExecute hello on &Pool.
p &PoolPool instance used by this call (borrow).bool — true or false
(&Pool) insert_onepub fn (p &Pool) insert_one(db_name string, col_name string, doc_bytes string) intOperation on &Pool: insert one. Throws on failure; handle the error or propagate it to the caller.
p &PoolPool instance used by this call (borrow).db_name stringcol_name stringdoc_bytes stringint — a value of this type
(&Pool) find_first_stringpub fn (p &Pool) find_first_string(db_name string, col_name string, target_field string) stringOperation on &Pool: find first string. Throws on failure; handle the error or propagate it to the caller.
p &PoolPool instance used by this call (borrow).db_name stringcol_name stringtarget_field stringstring — result string
(&Pool) drop_collectionpub fn (p &Pool) drop_collection(db_name string, col_name string) boolOperation on &Pool: drop collection.
p &PoolPool instance used by this call (borrow).db_name stringcol_name stringbool — true or false
(&Pool) closepub fn (p &Pool) close()Operation on &Pool: close the resource.
p &PoolPool instance used by this call (borrow).This call does not return a value.
encode_op_msgpub fn encode_op_msg(request_id int, doc_bytes string) stringEncode op msg data.
request_id intdoc_bytes stringstring — result string
decode_op_msg_docpub fn decode_op_msg_doc(raw string) stringDecode op msg doc data. Throws on failure; handle the error or propagate it to the caller.
raw stringstring — result string
struct TlsClientpub struct TlsClient {
pub conn transport.Conn
pub host string
pub port int
}Mongodb Client session maintaining connection and operations.
conn transport.Connhost stringport inttls_connectpub fn tls_connect(endpoint string, default_port int) TlsClientTls connect. Throws on failure; handle the error or propagate it to the caller.
endpoint stringdefault_port intTlsClient — a value of this type
tls_connect_configpub fn tls_connect_config(endpoint string, default_port int, cfg tls.Config) TlsClientTls connect config. Throws on failure; handle the error or propagate it to the caller.
endpoint stringdefault_port intcfg tls.ConfigTlsClient — a value of this type
($&TlsClient) write_allpub fn (c $&TlsClient) write_all(data string) intOperation on $&TlsClient: write all. Throws on failure; handle the error or propagate it to the caller.
c $&TlsClientTlsClient instance used by this call (exclusive borrow).data stringint — a value of this type
($&TlsClient) readpub fn (c $&TlsClient) read(max int) stringOperation on $&TlsClient: read up to max bytes. Throws on failure; handle the error or propagate it to the caller.
c $&TlsClientTlsClient instance used by this call (exclusive borrow).max intstring — result string
($&TlsClient) read_exactpub fn (c $&TlsClient) read_exact(need int) stringOperation on $&TlsClient: read exact. Throws on failure; handle the error or propagate it to the caller.
c $&TlsClientTlsClient instance used by this call (exclusive borrow).need intstring — result string
($&TlsClient) closepub fn (c $&TlsClient) close() intOperation on $&TlsClient: close the resource. Throws on failure; handle the error or propagate it to the caller.
c $&TlsClientTlsClient instance used by this call (exclusive borrow).int — a value of this type
($&TlsClient) set_deadlinepub fn (c $&TlsClient) set_deadline(t_ns int) intOperation on $&TlsClient: set deadline. Throws on failure; handle the error or propagate it to the caller.
c $&TlsClientTlsClient instance used by this call (exclusive borrow).t_ns intint — a value of this type
($&TlsClient) set_read_deadlinepub fn (c $&TlsClient) set_read_deadline(t_ns int) intOperation on $&TlsClient: set read deadline. Throws on failure; handle the error or propagate it to the caller.
c $&TlsClientTlsClient instance used by this call (exclusive borrow).t_ns intint — a value of this type
($&TlsClient) set_write_deadlinepub fn (c $&TlsClient) set_write_deadline(t_ns int) intOperation on $&TlsClient: set write deadline. Throws on failure; handle the error or propagate it to the caller.
c $&TlsClientTlsClient instance used by this call (exclusive borrow).t_ns intint — a value of this type