SDK Integration Guide
SDK Integration Guide
Guide for integrating HeliosDB Nano SDKs into applications across multiple programming languages.
Table of Contents
Python SDK
Installation
pip install heliosdb-clientBasic Usage
import asynciofrom 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 queryresult = await db.query(sql: str, params: List[Any]) -> QueryResultresult.rows: List[Dict]result.columns: List[str]
# Execute statement (INSERT/UPDATE/DELETE)affected = await db.execute(sql: str, params: List[Any]) -> int
# Natural language queryresult, sql = await db.nl_query(question: str) -> Tuple[QueryResult, str]
# Time-travel queryresult = await db.query_at( sql: str, timestamp: str, # ISO 8601 params: List[Any]) -> QueryResultVector Methods:
# Vector searchresults = await db.vector_search( store: str, query: str, top_k: int = 10, min_score: float = None, filter: Dict = None) -> List[VectorSearchResult]
# Store text with embeddingdoc_id = await db.store_text( store: str, text: str, metadata: Dict = None) -> str
# Vector search by vectorresults = 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 memoryawait db.memory_add(session_id: str, role: str, content: str) -> None
# Get from memorymessages = await db.memory_get(session_id: str, limit: int) -> List[Dict]
# Search memoryresults = await db.memory_search( session_id: str, query: str, top_k: int) -> List[VectorSearchResult]
# Clear memoryawait db.memory_clear(session_id: str) -> NoneFlask/FastAPI Integration
FastAPI Example:
from fastapi import FastAPIfrom 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 resultsSQLAlchemy Integration
from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String
# Connect via PostgreSQL protocolengine = 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 normallywith engine.connect() as conn: result = conn.execute(users.select().where(users.c.id == 1))TypeScript SDK
Installation
npm install heliosdb-clientBasic 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 queryconst result = await db.query(sql: string, params?: any[]) : Promise<QueryResult>
// Execute statementconst affected = await db.execute(sql: string, params?: any[]) : Promise<number>
// Natural language queryconst [result, sql] = await db.nlQuery(question: string) : Promise<[QueryResult, string]>
// Time-travelconst result = await db.queryAt( sql: string, timestamp: string, params?: any[]) : Promise<QueryResult>Vector Methods:
// Vector searchconst results = await db.vectorSearch( store: string, query: string, options?: { topK?: number, minScore?: number, filter?: Record<string, any> }) : Promise<VectorSearchResult[]>
// Store textconst docId = await db.storeText( store: string, text: string, metadata?: Record<string, any>) : Promise<string>
// Vector search by vectorconst 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 protocolconst prisma = new PrismaClient({ datasources: { db: { url: 'postgresql://localhost:5432/mydb' } }});
// Use Prisma normallyconst user = await prisma.users.findUnique({ where: { id: 1 }});Go SDK
Installation
go get github.com/heliosdb/go-clientBasic 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 queryfunc (c *Client) Query(ctx context.Context, sql string, params ...interface{}) (*QueryResult, error)
// Execute statementfunc (c *Client) Execute(ctx context.Context, sql string, params ...interface{}) (int64, error)
// Natural language queryfunc (c *Client) NLQuery(ctx context.Context, question string) (*QueryResult, string, error)
// Time-travel queryfunc (c *Client) QueryAt(ctx context.Context, sql, timestamp string, params ...interface{}) (*QueryResult, error)Vector Methods:
// Vector searchfunc (c *Client) VectorSearch(ctx context.Context, store, query string, opts ...*SearchOptions) ([]VectorSearchResult, error)
// Store textfunc (c *Client) StoreText(ctx context.Context, store, text string, metadata map[string]interface{}) (string, error)
// Vector search by vectorfunc (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 PostgreSQLdb, err := gorm.Open( postgres.Open("postgresql://localhost:5432/mydb"), &gorm.Config{},)
// Use GORM normallytype User struct { ID uint Name string Email string}
var user Userdb.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)
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'mydb', 'USER': 'user', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': '5432', }}
# models.pyfrom django.db import models
class User(models.Model): name = models.CharField(max_length=100) email = models.EmailField()Spring Boot (Java)
spring.datasource.url=jdbc:postgresql://localhost:5432/mydbspring.datasource.username=userspring.datasource.password=passwordspring.datasource.driver-class-name=org.postgresql.Driverspring.jpa.hibernate.ddl-auto=updateORM 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 operationsawait 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
- Schema: Copy SQL CREATE statements (mostly compatible)
- Data: Export from SQLite, import to HeliosDB Nano
- Connection: Update connection string to PostgreSQL format
- Queries: Most SQL queries are compatible
From PostgreSQL to HeliosDB Nano (Embedded)
- Schema: Export from PostgreSQL, import to HeliosDB Nano
- Data: Use
pg_dumpand import - Code: Change client from network-based to embedded
- Features: Ensure used features are supported
Troubleshooting
Connection Issues
# Python: Test connectionimport asynciofrom 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:
[logging]level = "debug"queries = trueAnalyze query plan:
EXPLAIN ANALYZE SELECT * FROM table WHERE ...;