Skip to content

SDK Integration Guide

Guide for integrating HeliosDB-Lite 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

pip install heliosdb-client

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

npm install heliosdb-client

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

go get github.com/heliosdb/go-client

Basic Usage

package main

import (
    "context"
    "github.com/heliosdb/go-client"
)

func main() {
    ctx := context.Background()

    // Connect
    db := heliosdb.NewClient(
        "http://localhost:8080",
        "api-key",
    )
    defer db.Close()

    // Query
    result, err := db.Query(ctx,
        "SELECT * FROM users WHERE id = $1",
        1,
    )
    if err != nil {
        panic(err)
    }

    // Vector search
    docs, err := db.VectorSearch(ctx, "documents", "hello world",
        &heliosdb.SearchOptions{TopK: 5})

    // Memory
    mem := db.Memory("session_123")
    mem.Add(ctx, "user", "Hello")
    messages, _ := mem.Get(ctx, 10)
}

API Reference

Query Methods:

// Execute query
func (c *Client) Query(ctx context.Context, sql string, params ...interface{})
    (*QueryResult, error)

// Execute statement
func (c *Client) Execute(ctx context.Context, sql string, params ...interface{})
    (int64, error)

// Natural language query
func (c *Client) NLQuery(ctx context.Context, question string)
    (*QueryResult, string, error)

// Time-travel query
func (c *Client) QueryAt(ctx context.Context, sql, timestamp string,
    params ...interface{}) (*QueryResult, error)

Vector Methods:

// Vector search
func (c *Client) VectorSearch(ctx context.Context, store, query string,
    opts ...*SearchOptions) ([]VectorSearchResult, error)

// Store text
func (c *Client) StoreText(ctx context.Context, store, text string,
    metadata map[string]interface{}) (string, error)

// Vector search by vector
func (c *Client) VectorSearchByVector(ctx context.Context, store string,
    vector []float32, topK int) ([]VectorSearchResult, error)

HTTP Server Integration

package main

import (
    "net/http"
    "github.com/heliosdb/go-client"
)

var db = heliosdb.NewClient("http://localhost:8080", "key")

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(), 500)
        return
    }

    // Write JSON response
    json.NewEncoder(w).Encode(result.Rows)
}

func main() {
    http.HandleFunc("/api/users", getUserHandler)
    http.ListenAndServe(":8080", 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 = "3.0"
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

Framework Language Driver Status
SQLAlchemy Python psycopg2 ✅ Full
Diesel Rust postgres ✅ Full
Prisma TypeScript node-postgres ✅ Full
GORM Go postgres ✅ Full
Hibernate Java PostgreSQL JDBC ✅ Full
Entity Framework .NET Npgsql ✅ Full

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-Lite

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

From PostgreSQL to HeliosDB-Lite (Embedded)

  1. Schema: Export from PostgreSQL, import to HeliosDB-Lite
  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