XU XUv0.16.0

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

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

counts: 23 functions, 23 methods, 3 types, 0 constants, 0 method sets

MongoDB 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

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.

31_standalone_mongodb/main.xu

Required SDK: Xu 0.8.3 · Complete project · Download source

XuLocal SDK example
@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 declarations

open

XuAPI
pub fn open(addr string) Client

Purpose

Open resource or establish connection. Throws on failure; handle the error or propagate it to the caller.

Parameters

addr string
address (string)

Returns

Client — a value of this type

See usage example

open_pool

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

Purpose

Open pool.

Parameters

addr string
address (string)
max_idle int
max_idle (int)

Returns

Pool — a value of this type

See usage example

encode_i32

XuAPI
pub fn encode_i32(v int) string

Purpose

Encode i32 data.

Parameters

v int
value (int)

Returns

string — result string

encode_i64

XuAPI
pub fn encode_i64(v int) string

Purpose

Encode i64 data.

Parameters

v int
value (int)

Returns

string — result string

decode_i32

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

Purpose

Decode i32 data.

Parameters

s &string
source string (read-only borrow; caller keeps the original; type &string)
off int
offset (int)

Returns

int — a value of this type

build_doc

XuAPI
pub fn build_doc(elements string) string

Purpose

Build doc.

Parameters

elements string
elements (string)

Returns

string — result string

bson_string

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

Purpose

Bson string.

Parameters

name string
name (string)
val string
value (string)

Returns

string — result string

See usage example

bson_int32

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

Purpose

Bson int32.

Parameters

name string
name (string)
val int
value (int)

Returns

string — result string

See usage example

bson_int64

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

Purpose

Bson int64.

Parameters

name string
name (string)
val int
value (int)

Returns

string — result string

bson_bool

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

Purpose

Bson bool.

Parameters

name string
name (string)
val bool
value (bool)

Returns

string — result string

bson_doc

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

Purpose

Bson doc.

Parameters

name string
name (string)
doc_bytes string
doc_bytes (string)

Returns

string — result string

bson_array

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

Purpose

Bson array.

Parameters

name string
name (string)
arr_bytes string
arr_bytes (string)

Returns

string — result string

bson_object_id

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

Purpose

Bson object id.

Parameters

name string
name (string)
oid_bytes string
oid_bytes (string)

Returns

string — result string

bson_utc_datetime

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

Purpose

Bson utc datetime.

Parameters

name string
name (string)
millis int
millis (int)

Returns

string — result string

bson_null

XuAPI
pub fn bson_null(name string) string

Purpose

Bson null.

Parameters

name string
name (string)

Returns

string — result string

find_bson_string

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

Purpose

Find bson string.

Parameters

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

Returns

string — result string

is_bson_ok

XuAPI
pub fn is_bson_ok(doc string) bool

Purpose

Whether it is bson ok.

Parameters

doc string
doc (string)

Returns

bool — true or false

struct Client

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

Purpose

Mongodb Client session maintaining connection and operations.

Public fields

fd int
file descriptor
addr string
address
next_req_id int
field (int)

($&Client) write_exact

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

Purpose

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

Parameters

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

Returns

int — a value of this type

($&Client) read_exact

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

Purpose

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

Parameters

c $&Client
The Client instance used by this call (exclusive borrow).
n int
count, length, or limit (int)

Returns

string — result string

($&Client) run_command

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

Purpose

Operation on $&Client: run command. Throws on failure; handle the error or propagate it to the caller.

Parameters

c $&Client
The Client instance used by this call (exclusive borrow).
db_name string
db_name (string)
cmd_elements string
cmd_elements (string)

Returns

string — result string

connect

XuAPI
pub fn connect(addr string) Client

Purpose

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

Parameters

addr string
address (string)

Returns

Client — a value of this type

($&Client) hello

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

Purpose

Execute hello on $&Client.

Parameters

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

Returns

bool — true or false

($&Client) insert_one

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

Purpose

Operation on $&Client: insert one. Throws on failure; handle the error or propagate it to the caller.

Parameters

c $&Client
The Client instance used by this call (exclusive borrow).
db_name string
db_name (string)
col_name string
col_name (string)
doc_bytes string
doc_bytes (string)

Returns

int — a value of this type

($&Client) find_first_string

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

Purpose

Operation on $&Client: find first string. Throws on failure; handle the error or propagate it to the caller.

Parameters

c $&Client
The Client instance used by this call (exclusive borrow).
db_name string
db_name (string)
col_name string
col_name (string)
target_field string
target_field (string)

Returns

string — result string

($&Client) drop_collection

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

Purpose

Operation on $&Client: drop collection.

Parameters

c $&Client
The Client instance used by this call (exclusive borrow).
db_name string
db_name (string)
col_name string
col_name (string)

Returns

bool — true or false

($&Client) close

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

Purpose

Operation on $&Client: close the resource.

Parameters

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

Returns

This call does not return a value.

struct Pool

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

Purpose

Connection Pool for MongoDB. Uses channel of socket file descriptors for lightweight and high-throughput pooling.

Public fields

addr string
address
idle chan int
field (channel; type chan int)
max_idle int
field (int)

new_pool

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

Purpose

Construct pool.

Parameters

addr string
address (string)
max_idle int
max_idle (int)

Returns

Pool — a value of this type

(&Pool) get

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

Purpose

Execute get on &Pool. Throws on failure; handle the error or propagate it to the caller.

Parameters

p &Pool
The Pool instance used by this call (borrow).

Returns

Client — a value of this type

(&Pool) put_conn

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

Purpose

Operation on &Pool: put connection.

Parameters

p &Pool
The Pool instance used by this call (borrow).
fd int
file descriptor (int)

Returns

This call does not return a value.

(&Pool) put

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

Purpose

Store or update the value associated with the specified key.

Parameters

p &Pool
The Pool instance used by this call (borrow).
c Client
byte or character code (Client)

Returns

This call does not return a value.

(&Pool) hello

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

Purpose

Execute hello on &Pool.

Parameters

p &Pool
The Pool instance used by this call (borrow).

Returns

bool — true or false

(&Pool) insert_one

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

Purpose

Operation on &Pool: insert one. Throws on failure; handle the error or propagate it to the caller.

Parameters

p &Pool
The Pool instance used by this call (borrow).
db_name string
db_name (string)
col_name string
col_name (string)
doc_bytes string
doc_bytes (string)

Returns

int — a value of this type

(&Pool) find_first_string

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

Purpose

Operation on &Pool: find first string. Throws on failure; handle the error or propagate it to the caller.

Parameters

p &Pool
The Pool instance used by this call (borrow).
db_name string
db_name (string)
col_name string
col_name (string)
target_field string
target_field (string)

Returns

string — result string

(&Pool) drop_collection

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

Purpose

Operation on &Pool: drop collection.

Parameters

p &Pool
The Pool instance used by this call (borrow).
db_name string
db_name (string)
col_name string
col_name (string)

Returns

bool — true or false

(&Pool) close

XuAPI
pub fn (p &Pool) close()

Purpose

Operation on &Pool: close the resource.

Parameters

p &Pool
The Pool instance used by this call (borrow).

Returns

This call does not return a value.

encode_op_msg

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

Purpose

Encode op msg data.

Parameters

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

Returns

string — result string

decode_op_msg_doc

XuAPI
pub fn decode_op_msg_doc(raw string) string

Purpose

Decode op msg doc data. Throws on failure; handle the error or propagate it to the caller.

Parameters

raw string
raw (string)

Returns

string — result string

struct TlsClient

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

Purpose

Mongodb 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