Skip to content

WASM Procedures: Host Functions

WASM Procedures: Host Functions

Part of: WASM Procedures User Guide


WASM procedures can call 50+ host functions provided by HeliosDB. These functions are grouped into categories:

SQL Execution Functions

exec_sql(sql: string) -> ResultSet

Execute a SQL query and return the result set.

Rust:

let result = exec_sql("SELECT * FROM users WHERE id = 123")?;
let name = result.get_string(0, 1)?;

JavaScript:

const result = execSql("SELECT * FROM users WHERE id = 123");
const name = result.getString(0, 1);

Python:

result = heliosdb.exec_sql("SELECT * FROM users WHERE id = 123")
name = result.rows[0][1]

Go:

result, err := heliosdb.ExecSQL("SELECT * FROM users WHERE id = 123")
name := result.GetString(0, 1)

exec_prepared(stmt_id: i64) -> ResultSet

Execute a prepared statement.

let stmt = prepare_statement("SELECT * FROM users WHERE id = ?")?;
let result = exec_prepared(stmt)?;

prepare_statement(sql: string) -> i64

Prepare a SQL statement for repeated execution.

let stmt = prepare_statement("INSERT INTO logs VALUES (?, ?)")?;
for msg in messages {
exec_prepared(stmt)?;
}

Transaction Functions

begin_transaction() -> Transaction

Begin a new database transaction.

let tx = begin_transaction()?;
// ... perform operations
commit_transaction(tx)?;

commit_transaction(tx: Transaction) -> Result<()>

Commit a transaction.

rollback_transaction(tx: Transaction) -> Result<()>

Rollback a transaction.

Complete Example:

fn atomic_operation() -> Result<(), String> {
let tx = begin_transaction()?;
match perform_operations() {
Ok(_) => commit_transaction(tx)?,
Err(e) => {
rollback_transaction(tx)?;
return Err(e);
}
}
Ok(())
}

Key-Value Operations

kv_get(key: bytes) -> Option<bytes>

Get a value from the key-value store.

let key = b"user:123";
if let Some(value) = kv_get(key)? {
let data = String::from_utf8(value)?;
// Process data
}

kv_set(key: bytes, value: bytes) -> Result<()>

Set a value in the key-value store.

let key = b"user:123";
let value = serde_json::to_vec(&user)?;
kv_set(key, &value)?;

kv_delete(key: bytes) -> Result<()>

Delete a key from the store.

kv_delete(b"user:123")?;

Document Operations

doc_get(collection: string, id: string) -> Option<JSON>

Get a document from a collection.

if let Some(doc) = doc_get("users", "user_123")? {
let user: User = serde_json::from_value(doc)?;
}

doc_insert(collection: string, document: JSON) -> string

Insert a document and return the ID.

let doc = serde_json::json!({
"name": "John Doe",
"email": "john@example.com"
});
let id = doc_insert("users", doc)?;

doc_update(collection: string, id: string, document: JSON) -> Result<()>

Update a document.

doc_delete(collection: string, id: string) -> Result<()>

Delete a document.

Graph Query Functions

graph_query(query: string) -> GraphResult

Execute a graph query.

let result = graph_query("MATCH (u:User)-[:FRIEND]->(f) WHERE u.id = 123 RETURN f")?;

graph_shortest_path(from: NodeId, to: NodeId) -> Path

Find shortest path between nodes.

Vector Search Functions

vector_search(collection: string, vector: Vec<f32>, top_k: i32) -> Vec<Match>

Perform vector similarity search.

let embedding = vec![0.1, 0.2, 0.3, ...]; // 768-dim vector
let matches = vector_search("embeddings", embedding, 10)?;
for m in matches {
println!("ID: {}, Score: {}", m.id, m.score);
}

vector_insert(collection: string, vector: Vec<f32>, metadata: JSON) -> string

Insert a vector with metadata.

HTTP Client Functions

http_get(url: string) -> HTTPResponse

Make an HTTP GET request.

let response = http_get("https://api.example.com/data")?;
let data: ApiResponse = serde_json::from_slice(&response.body)?;

http_post(url: string, body: bytes, headers: Map<string, string>) -> HTTPResponse

Make an HTTP POST request.

let headers = HashMap::from([
("Content-Type".to_string(), "application/json".to_string()),
]);
let body = serde_json::to_vec(&request)?;
let response = http_post("https://api.example.com/endpoint", &body, headers)?;

Logging Functions

log_trace(message: string)

log_debug(message: string)

log_info(message: string)

log_warn(message: string)

log_error(message: string)

Log messages at different levels.

log_info("Processing started");
log_debug(&format!("Processing user {}", user_id));
log_warn("Slow query detected");
log_error("Operation failed");

Metrics Functions

metric_increment(name: string, value: i64)

Increment a counter metric.

metric_increment("orders_processed", 1);

metric_gauge(name: string, value: f64)

Set a gauge metric.

metric_gauge("queue_size", queue.len() as f64);

metric_histogram(name: string, value: f64)

Record a histogram value.

let start = Instant::now();
// ... operation
metric_histogram("operation_duration_ms", start.elapsed().as_millis() as f64);

Cryptography Functions

sha256(data: bytes) -> bytes

Calculate SHA-256 hash.

let hash = sha256(password.as_bytes())?;
let hex_hash = hex::encode(hash);

sha512(data: bytes) -> bytes

Calculate SHA-512 hash.

blake3(data: bytes) -> bytes

Calculate BLAKE3 hash (faster than SHA).

random_bytes(count: i32) -> bytes

Generate cryptographically secure random bytes.

let salt = random_bytes(32)?;
let token = hex::encode(random_bytes(16)?);

Time Functions

current_timestamp() -> i64

Get current Unix timestamp in milliseconds.

let now = current_timestamp();

format_timestamp(timestamp: i64, format: string) -> string

Format a timestamp.

let formatted = format_timestamp(now, "%Y-%m-%d %H:%M:%S")?;

Navigation: