Skip to content

SDK Integration Guide

Guide for integrating HeliosDB Nano SDKs into applications across multiple programming languages.

Table of Contents

  1. Python SDK
  2. TypeScript SDK
  3. Go SDK
  4. Rust SDK
  5. Framework Integration
  6. Common Patterns

Python SDK

Installation

Terminal window
pip install "git+https://github.com/HeliosDatabase/HeliosDB-SDKs.git#subdirectory=sdks/python" # not published on PyPI

Basic Usage

import asyncio
from heliosdb_client import Client
async def main():
# Connect to server
db = Client(base_url="http://localhost:8080", api_key="key")
# Execute query
result = await db.query("SELECT * FROM users WHERE id = $1", [1])
print(result.rows)
# Vector search
results = await db.vector_search("documents", "hello world", top_k=5)
for doc in results:
print(f"{doc.id}: {doc.score}")
# Close connection
await db.close()
asyncio.run(main())

API Reference

Query Methods:

# Execute query
result = await db.query(sql: str, params: List[Any]) -> QueryResult
result.rows: List[Dict]
result.columns: List[str]
# Execute statement (INSERT/UPDATE/DELETE)
affected = await db.execute(sql: str, params: List[Any]) -> int
# Natural language query
result, sql = await db.nl_query(question: str) -> Tuple[QueryResult, str]
# Time-travel query
result = await db.query_at(
sql: str,
timestamp: str, # ISO 8601
params: List[Any]
) -> QueryResult

Vector Methods:

# Vector search
results = await db.vector_search(
store: str,
query: str,
top_k: int = 10,
min_score: float = None,
filter: Dict = None
) -> List[VectorSearchResult]
# Store text with embedding
doc_id = await db.store_text(
store: str,
text: str,
metadata: Dict = None
) -> str
# Vector search by vector
results = await db.vector_search_by_vector(
store: str,
vector: List[float],
top_k: int = 10,
min_score: float = None
) -> List[VectorSearchResult]

Memory Methods:

# Add to memory
await db.memory_add(session_id: str, role: str, content: str) -> None
# Get from memory
messages = await db.memory_get(session_id: str, limit: int) -> List[Dict]
# Search memory
results = await db.memory_search(
session_id: str,
query: str,
top_k: int
) -> List[VectorSearchResult]
# Clear memory
await db.memory_clear(session_id: str) -> None

Flask/FastAPI Integration

FastAPI Example:

from fastapi import FastAPI
from heliosdb_client import Client
app = FastAPI()
db = Client(base_url="http://localhost:8080")
@app.get("/users/{user_id}")
async def get_user(user_id: int):
result = await db.query(
"SELECT * FROM users WHERE id = $1",
[user_id]
)
return result.rows[0] if result.rows else None
@app.post("/search")
async def search(query: str):
results = await db.vector_search("documents", query, top_k=10)
return results

SQLAlchemy Integration

from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String
# Connect via PostgreSQL protocol
engine = create_engine("postgresql://localhost:5432/mydb")
metadata = MetaData()
users = Table('users', metadata,
Column('id', Integer, primary_key=True),
Column('name', String),
Column('email', String)
)
# Use SQLAlchemy normally
with engine.connect() as conn:
result = conn.execute(users.select().where(users.c.id == 1))

TypeScript SDK

Installation

Terminal window
# @heliosdb/client is not published on npm; build it from source
git clone https://github.com/HeliosDatabase/HeliosDB-SDKs.git
(cd HeliosDB-SDKs/sdks/typescript && npm install && npm run build)
npm install ./HeliosDB-SDKs/sdks/typescript

Basic Usage

import { HeliosDBClient } from '@heliosdb/client';
async function main() {
const db = new HeliosDBClient({
baseUrl: 'http://localhost:8080',
apiKey: 'your-key'
});
// Query
const result = await db.query(
'SELECT * FROM users WHERE id = $1',
[1]
);
console.log(result.rows);
// Vector search
const docs = await db.vectorSearch(
'documents',
'hello world',
{ topK: 5 }
);
// Memory
const memory = db.memory('session_123');
await memory.add('user', 'Hello');
const messages = await memory.get(10);
await db.close();
}
main();

API Reference

Query Methods:

// Execute query
const result = await db.query(sql: string, params?: any[])
: Promise<QueryResult>
// Execute statement
const affected = await db.execute(sql: string, params?: any[])
: Promise<number>
// Natural language query
const [result, sql] = await db.nlQuery(question: string)
: Promise<[QueryResult, string]>
// Time-travel
const result = await db.queryAt(
sql: string,
timestamp: string,
params?: any[]
) : Promise<QueryResult>

Vector Methods:

// Vector search
const results = await db.vectorSearch(
store: string,
query: string,
options?: {
topK?: number,
minScore?: number,
filter?: Record<string, any>
}
) : Promise<VectorSearchResult[]>
// Store text
const docId = await db.storeText(
store: string,
text: string,
metadata?: Record<string, any>
) : Promise<string>
// Vector search by vector
const results = await db.vectorSearchByVector(
store: string,
vector: number[],
topK?: number
) : Promise<VectorSearchResult[]>

Express Integration

import express from 'express';
import { HeliosDBClient } from '@heliosdb/client';
const app = express();
const db = new HeliosDBClient({
baseUrl: 'http://localhost:8080'
});
app.get('/api/users/:id', async (req, res) => {
const result = await db.query(
'SELECT * FROM users WHERE id = $1',
[req.params.id]
);
res.json(result.rows[0]);
});
app.post('/api/search', async (req, res) => {
const results = await db.vectorSearch(
'documents',
req.body.query,
{ topK: 10 }
);
res.json(results);
});

Prisma Integration

import { PrismaClient } from '@prisma/client';
// Prisma can connect via PostgreSQL protocol
const prisma = new PrismaClient({
datasources: {
db: {
url: 'postgresql://localhost:5432/mydb'
}
}
});
// Use Prisma normally
const user = await prisma.users.findUnique({
where: { id: 1 }
});

Go SDK

Installation

Terminal window
go get github.com/HeliosDatabase/HeliosDB-SDKs/sdks/go

The package name is heliosdb. The client talks to the REST API (/v1/...) that heliosdb-nano start serves on its HTTP port (8080 by default). For plain SQL over the PostgreSQL wire protocol you can instead use any PostgreSQL driver (e.g. github.com/jackc/pgx/v5) against the same server — see GORM Integration below.

Basic Usage

package main
import (
"context"
"fmt"
"log"
heliosdb "github.com/HeliosDatabase/HeliosDB-SDKs/sdks/go"
)
func main() {
ctx := context.Background()
// Connect to the REST API served by `heliosdb-nano start` (HTTP port 8080)
db, err := heliosdb.NewClient("http://localhost:8080",
heliosdb.WithAPIKey("api-key"), // API-key authentication for the HTTP API is planned
)
if err != nil {
log.Fatal(err)
}
// Query
result, err := db.Query(ctx, "SELECT * FROM users WHERE id = $1", 1)
if err != nil {
log.Fatal(err)
}
fmt.Println(result.Columns, result.Rows)
// Vector search (text query, server-side embedding)
docs, err := db.VectorSearch(ctx, "documents", "hello world",
heliosdb.WithTopK(5))
if err != nil {
log.Fatal(err)
}
for _, d := range docs {
fmt.Println(d.ID, d.Score)
}
// Agent memory
mem := db.Memory("session_123")
if err := mem.Add(ctx, "user", "Hello"); err != nil {
log.Fatal(err)
}
messages, _ := mem.Get(ctx, 10)
fmt.Println(len(messages))
}

API Reference

// Construction and options
func NewClient(baseURL string, opts ...ClientOption) (*Client, error)
func WithAPIKey(key string) ClientOption
func WithBranch(branch string) ClientOption
func WithTimeout(d time.Duration) ClientOption
func WithHTTPClient(client *http.Client) ClientOption
// SQL
func (c *Client) Query(ctx context.Context, sql string, params ...interface{}) (*QueryResult, error)
func (c *Client) QueryOnBranch(ctx context.Context, branch, sql string, params ...interface{}) (*QueryResult, error)
func (c *Client) Exec(ctx context.Context, sql string, params ...interface{}) (int64, error)
func (c *Client) QueryAt(ctx context.Context, sql string, timestamp time.Time, params ...interface{}) (*QueryResult, error)
// Branches
func (c *Client) ListBranches(ctx context.Context) ([]Branch, error)
func (c *Client) CreateBranch(ctx context.Context, name, fromBranch string) (*Branch, error)
func (c *Client) MergeBranch(ctx context.Context, source, target string) error
// Vector stores
func (c *Client) VectorSearch(ctx context.Context, store, query string, opts ...VectorSearchOption) ([]VectorSearchResult, error)
func (c *Client) VectorSearchByVector(ctx context.Context, store string, vector []float32, opts ...VectorSearchOption) ([]VectorSearchResult, error)
func WithTopK(k int) VectorSearchOption
func WithMinScore(score float64) VectorSearchOption
func WithFilter(filter map[string]interface{}) VectorSearchOption
// Agent memory
func (c *Client) Memory(sessionID string) *AgentMemory
func (m *AgentMemory) Add(ctx context.Context, role, content string) error
func (m *AgentMemory) Get(ctx context.Context, limit int) ([]Message, error)
func (m *AgentMemory) Search(ctx context.Context, query string, topK int) ([]VectorSearchResult, error)

Non-2xx responses are returned as *heliosdb.APIError (fields StatusCode, Message). The complete surface is in the package source.

HTTP Server Integration

package main
import (
"encoding/json"
"log"
"net/http"
heliosdb "github.com/HeliosDatabase/HeliosDB-SDKs/sdks/go"
)
var db *heliosdb.Client
func getUserHandler(w http.ResponseWriter, r *http.Request) {
id := r.URL.Query().Get("id")
result, err := db.Query(r.Context(),
"SELECT * FROM users WHERE id = $1", id)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(result.Rows)
}
func main() {
var err error
db, err = heliosdb.NewClient("http://localhost:8080", heliosdb.WithAPIKey("key"))
if err != nil {
log.Fatal(err)
}
http.HandleFunc("/api/users", getUserHandler)
log.Fatal(http.ListenAndServe(":3000", nil))
}

GORM Integration

import "gorm.io/driver/postgres"
import "gorm.io/gorm"
// Connect via PostgreSQL
db, err := gorm.Open(
postgres.Open("postgresql://localhost:5432/mydb"),
&gorm.Config{},
)
// Use GORM normally
type User struct {
ID uint
Name string
Email string
}
var user User
db.First(&user, 1)

Rust SDK

Installation

Add to Cargo.toml:

[dependencies]
heliosdb-client = { git = "https://github.com/HeliosDatabase/HeliosDB-SDKs.git" } # sdks/rust; not on crates.io
tokio = { version = "1", features = ["full"] }

Basic Usage

use heliosdb_client::Client;
#[tokio::main]
async fn main() -> Result<()> {
let client = Client::new(ClientConfig {
base_url: "http://localhost:8080".to_string(),
api_key: Some("key".to_string()),
..Default::default()
})?;
// Query
let result = client.query("SELECT * FROM users WHERE id = $1", &[&1]).await?;
println!("{:?}", result.rows);
// Vector search
let results = client.vector_search("documents", "hello", 5, None, None).await?;
// Memory
let memory = client.memory("session_123");
memory.add("user", "Hello").await?;
Ok(())
}

API Reference

Query Methods:

pub async fn query(&self, sql: &str, params: &[&dyn ToSqlValue])
-> Result<QueryResult>
pub async fn execute(&self, sql: &str, params: &[&dyn ToSqlValue])
-> Result<i64>
pub async fn nl_query(&self, question: &str)
-> Result<(QueryResult, String)>
pub async fn query_at(&self, sql: &str, timestamp: &str,
params: &[&dyn ToSqlValue]) -> Result<QueryResult>

Vector Methods:

pub async fn vector_search(&self, store: &str, query: &str, top_k: usize,
min_score: Option<f64>, filter: Option<HashMap<String, Value>>)
-> Result<Vec<VectorSearchResult>>
pub async fn store_text(&self, store: &str, text: &str,
metadata: Option<HashMap<String, Value>>) -> Result<String>
pub async fn vector_search_by_vector(&self, store: &str, vector: Vec<f32>,
top_k: usize, min_score: Option<f64>)
-> Result<Vec<VectorSearchResult>>

Framework Integration

Web Frameworks

Axum (Rust)

use axum::{Router, routing::get, Json};
use heliosdb_client::Client;
let client = Arc::new(Client::new(config)?);
let app = Router::new()
.route("/users/:id", get(get_user))
.with_state(client);
async fn get_user(
State(db): State<Arc<Client>>,
Path(id): Path<i32>,
) -> Json<Vec<HashMap<String, Value>>> {
db.query("SELECT * FROM users WHERE id = $1", &[&id])
.await
.map(|r| r.rows)
.unwrap_or_default()
}

Django (Python)

settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'mydb',
'USER': 'user',
'PASSWORD': 'password',
'HOST': 'localhost',
'PORT': '5432',
}
}
# models.py
from django.db import models
class User(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField()

Spring Boot (Java)

application.properties
spring.datasource.url=jdbc:postgresql://localhost:5432/mydb
spring.datasource.username=user
spring.datasource.password=password
spring.datasource.driver-class-name=org.postgresql.Driver
spring.jpa.hibernate.ddl-auto=update

ORM Frameworks

FrameworkLanguageDriverResult
SQLAlchemyPythonpsycopg2Full
DieselRustpostgresFull
PrismaTypeScriptnode-postgresFull
GORMGopostgresFull
HibernateJavaPostgreSQL JDBCFull
Entity Framework.NETNpgsqlFull

Common Patterns

Connection Pooling

Rust (SQLx):

use sqlx::postgres::PgPoolOptions;
let pool = PgPoolOptions::new()
.max_connections(10)
.connect("postgresql://localhost:5432/mydb")
.await?;
let row = sqlx::query("SELECT * FROM users WHERE id = $1")
.bind(1)
.fetch_one(&pool)
.await?;

Python (asyncpg):

import asyncpg
pool = await asyncpg.create_pool(
'postgresql://localhost/mydb',
min_size=10,
max_size=20
)
async with pool.acquire() as connection:
result = await connection.fetch('SELECT * FROM users')

TypeScript (node-postgres):

import { Pool } from 'pg';
const pool = new Pool({
host: 'localhost',
port: 5432,
database: 'mydb',
max: 10,
});
const result = await pool.query('SELECT * FROM users WHERE id = $1', [1]);

Error Handling

Rust:

match client.query(sql, params).await {
Ok(result) => println!("{:?}", result),
Err(e) => eprintln!("Query error: {}", e),
}

Python:

try:
result = await db.query(sql, params)
except HeliosDBError as e:
print(f"Database error: {e}")

TypeScript:

try {
const result = await db.query(sql, params);
} catch (error) {
console.error('Database error:', error);
}

Batch Operations

Rust:

let mut tx = client.begin_transaction().await?;
for item in items {
tx.execute(
"INSERT INTO table VALUES ($1, $2)",
&[&item.id, &item.name]
).await?;
}
tx.commit().await?;

Python:

# Use async batch operations
await db.execute("BEGIN")
for item in items:
await db.execute("INSERT INTO table VALUES ($1, $2)",
[item.id, item.name])
await db.execute("COMMIT")

Migration Guides

From SQLite to HeliosDB Nano

  1. Schema: Copy SQL CREATE statements (mostly compatible)
  2. Data: Export from SQLite, import to HeliosDB Nano
  3. Connection: Update connection string to PostgreSQL format
  4. Queries: Most SQL queries are compatible

From PostgreSQL to HeliosDB Nano (Embedded)

  1. Schema: Export from PostgreSQL, import to HeliosDB Nano
  2. Data: Use pg_dump and import
  3. Code: Change client from network-based to embedded
  4. Features: Ensure used features are supported

Troubleshooting

Connection Issues

# Python: Test connection
import asyncio
from heliosdb_client import Client
async def test():
try:
db = Client(base_url="http://localhost:8080")
health = await db.health()
print(f"Connected: {health}")
except Exception as e:
print(f"Error: {e}")
asyncio.run(test())

Query Debugging

Log queries:

heliosdb.toml
[logging]
level = "debug"
queries = true

Analyze query plan:

EXPLAIN ANALYZE SELECT * FROM table WHERE ...;

Support