Skip to main content

EmbeddedDatabase

Struct EmbeddedDatabase 

Source
pub struct EmbeddedDatabase {
    pub storage: Arc<StorageEngine>,
    pub tenant_manager: Arc<TenantManager>,
    pub trigger_registry: Arc<TriggerRegistry>,
    pub function_registry: Arc<FunctionRegistry>,
    pub dump_manager: Arc<DumpManager>,
    pub session_manager: Arc<SessionManager>,
    pub lock_manager: Arc<LockManager>,
    pub dirty_tracker: Arc<DirtyTracker>,
    /* private fields */
}
Expand description

Embedded database instance

Provides a simple API for embedded database usage (like SQLite).

§Examples

use heliosdb_nano::EmbeddedDatabase;

let db = EmbeddedDatabase::new("./mydb.helio")?;
db.execute("CREATE TABLE test (id INT, name TEXT)")?;

Fields§

§storage: Arc<StorageEngine>

Storage engine (public for REPL access)

§tenant_manager: Arc<TenantManager>

Tenant manager for multi-tenancy and RLS (optional)

§trigger_registry: Arc<TriggerRegistry>

Trigger registry for trigger management and execution

§function_registry: Arc<FunctionRegistry>

Function registry for stored functions and procedures

§dump_manager: Arc<DumpManager>

Dump manager for database persistence

§session_manager: Arc<SessionManager>

Session manager for multi-user support

§lock_manager: Arc<LockManager>

Lock manager for concurrency control

§dirty_tracker: Arc<DirtyTracker>

Dirty tracker for tracking uncommitted changes

Implementations§

Source§

impl EmbeddedDatabase

Source

pub fn new(path: impl AsRef<Path>) -> Result<Self>

Create a new embedded database

§Arguments
  • path - Path to database directory
§Examples
use heliosdb_nano::EmbeddedDatabase;

let db = EmbeddedDatabase::new("./data")?;
Source

pub fn new_in_memory() -> Result<Self>

Create an in-memory database

Data is stored in RAM only. Useful for testing or caching.

§Examples
use heliosdb_nano::EmbeddedDatabase;

let db = EmbeddedDatabase::new_in_memory()?;
Source

pub fn with_config(config: Config) -> Result<Self>

Create an in-memory database with custom configuration

§Examples
use heliosdb_nano::{EmbeddedDatabase, Config};

let mut config = Config::in_memory();
config.compression.level = 6;  // Higher compression level
let db = EmbeddedDatabase::with_config(config)?;
Source

pub fn query_timeout_ms(&self) -> Option<u64>

Execute a SQL statement (POTENTIALLY UNSAFE - use execute_params for user input)

WARNING: This method does not protect against SQL injection. If you’re concatenating user input into the SQL string, use execute_params() instead.

§Arguments
  • sql - SQL statement to execute
§Examples
use heliosdb_nano::EmbeddedDatabase;

let db = EmbeddedDatabase::new("./data")?;
db.execute("CREATE TABLE users (id SERIAL, name TEXT)")?;
§Safety

Safe for hardcoded SQL strings. For queries with user input, use execute_params():

use heliosdb_nano::{EmbeddedDatabase, Value};

let db = EmbeddedDatabase::new("./data")?;
let user_input = "'; DROP TABLE users; --";

// UNSAFE - SQL injection risk!
// let sql = format!("SELECT * FROM users WHERE name = '{}'", user_input);
// db.execute(&sql)?;

// SAFE - uses parameterized query
db.execute_params(
    "SELECT * FROM users WHERE name = $1",
    &[Value::String(user_input.to_string())]
)?;

Get the configured query timeout in milliseconds (None = unlimited)

Source

pub fn execute_batch(&self, statements: &[&str]) -> Result<u64>

Execute multiple SQL statements in a single transaction (batch mode).

All statements share one BEGIN/COMMIT cycle, dramatically reducing commit overhead for bulk operations. If any statement fails, the entire batch is rolled back.

§Returns

Total number of rows affected across all statements.

Source

pub fn execute(&self, sql: &str) -> Result<u64>

Source

pub fn execute_returning(&self, sql: &str) -> Result<(u64, Vec<Tuple>)>

Execute a SQL statement with RETURNING clause support

Similar to execute, but returns the tuples from RETURNING clause if present. For INSERT/UPDATE/DELETE with RETURNING, returns the affected rows.

§Arguments
  • sql - The SQL statement to execute
§Returns

A tuple of (rows_affected, returned_tuples). If no RETURNING clause is present, returned_tuples will be empty.

§Example
use heliosdb_nano::EmbeddedDatabase;

let db = EmbeddedDatabase::new_in_memory()?;
db.execute("CREATE TABLE users (id INT, name TEXT)")?;

// INSERT with RETURNING
let (count, rows) = db.execute_returning(
    "INSERT INTO users (id, name) VALUES (1, 'Alice') RETURNING *"
)?;

assert_eq!(count, 1);
assert_eq!(rows.len(), 1);
Source

pub fn execute_params(&self, sql: &str, params: &[Value]) -> Result<u64>

Execute a SQL statement with parameters (SAFE - prevents SQL injection)

This method uses parameterized queries to safely execute SQL with user input. Parameters are referenced as $1, $2, $3, etc. in PostgreSQL style.

§Arguments
  • sql - SQL statement with parameter placeholders ($1, $2, etc.)
  • params - Parameter values in order
§Examples
use heliosdb_nano::{EmbeddedDatabase, Value};

let db = EmbeddedDatabase::new("./data")?;

// Create table
db.execute("CREATE TABLE users (id INT, name TEXT, email TEXT)")?;

// Safe INSERT with parameters
let user_name = "Alice";
let user_email = "alice@example.com";
db.execute_params(
    "INSERT INTO users (id, name, email) VALUES ($1, $2, $3)",
    &[
        Value::Int4(1),
        Value::String(user_name.to_string()),
        Value::String(user_email.to_string()),
    ]
)?;

// Safe UPDATE with parameters
db.execute_params(
    "UPDATE users SET email = $1 WHERE name = $2",
    &[
        Value::String("newemail@example.com".to_string()),
        Value::String("Alice".to_string()),
    ]
)?;

// Safe DELETE with parameters
db.execute_params(
    "DELETE FROM users WHERE id = $1",
    &[Value::Int4(1)]
)?;
§Security

This method prevents SQL injection by treating parameters as data, not code. Even malicious input like "'; DROP TABLE users; --" is safely handled.

Source

pub fn execute_params_returning( &self, sql: &str, params: &[Value], ) -> Result<(u64, Vec<Tuple>)>

Execute a parameterized SQL statement with RETURNING clause support

Similar to execute_params, but returns the tuples from RETURNING clause if present. For INSERT/UPDATE/DELETE with RETURNING, returns the affected rows.

§Arguments
  • sql - The SQL statement with $N parameter placeholders
  • params - The parameter values in order ($1, $2, etc.)
§Returns

A tuple of (rows_affected, returned_tuples). If no RETURNING clause is present, returned_tuples will be empty.

§Example
use heliosdb_nano::{EmbeddedDatabase, Value};

let db = EmbeddedDatabase::new("./data")?;

// INSERT with RETURNING
let (count, rows) = db.execute_params_returning(
    "INSERT INTO users (id, name) VALUES ($1, $2) RETURNING *",
    &[Value::Int4(1), Value::String("Alice".to_string())]
)?;

assert_eq!(count, 1);
assert_eq!(rows.len(), 1);
Source

pub fn query(&self, sql: &str, _params: &[&dyn Display]) -> Result<Vec<Tuple>>

Query data (POTENTIALLY UNSAFE - use query_params for user input)

WARNING: This method does not protect against SQL injection. Use query_params() for queries with user input.

§Arguments
  • sql - SQL query
  • params - Query parameters (DEPRECATED - not used, kept for backward compatibility)
§Examples
use heliosdb_nano::EmbeddedDatabase;

let db = EmbeddedDatabase::new("./data")?;
let results = db.query("SELECT * FROM users", &[])?;
Source

pub fn query_with_columns(&self, sql: &str) -> Result<(Vec<Tuple>, Vec<String>)>

Execute a query and return both result tuples and column names.

Unlike query(), this returns the actual column names from the query plan (e.g. table column names, aliases) instead of requiring the caller to generate generic names.

Source

pub fn dump_full(&self, path: &Path) -> Result<DumpMetadata>

Create a full dump of the database

Creates a complete binary dump of all tables, schemas, and data. The dump is compressed using Zstd by default.

§Arguments
  • path - File path where the dump will be written
§Returns

Metadata about the created dump including size and table count

Source

pub fn dump_sql(&self, path: &Path) -> Result<DumpMetadata>

Create a SQL dump of the database

Creates a text-based SQL dump compatible with SQLite and PostgreSQL. The output contains CREATE TABLE and INSERT statements that can be replayed to recreate the database.

§Arguments
  • path - File path where the SQL dump will be written
Source

pub fn dump_incremental(&self, path: &Path) -> Result<DumpMetadata>

Create an incremental dump of changed data

Dumps only data that has changed since the last dump. More efficient than full dumps for large databases with few changes.

§Arguments
  • path - File path where the incremental dump will be written
Source

pub fn dump_incremental_append(&self, path: &Path) -> Result<DumpMetadata>

Create an incremental dump in append mode

Appends changed data to an existing incremental dump file.

§Arguments
  • path - File path of the existing dump to append to
Source

pub fn restore_from_dump(&mut self, path: &Path) -> Result<()>

Restore the database from a dump file

Replays a dump file to restore tables and data. Supports both full dumps and incremental dumps created by this database.

§Arguments
  • path - Path to the dump file to restore from
Source

pub fn dump_full_compressed( &self, path: &Path, compression: DumpCompressionType, ) -> Result<DumpMetadata>

Create a full dump with specific compression algorithm

§Arguments
  • path - File path where the dump will be written
  • compression - Compression algorithm to use (None, Gzip, Zstd)
Source

pub fn dump_full_uncompressed(&self, path: &Path) -> Result<DumpMetadata>

Create a full dump without compression

Useful for debugging or when downstream tools don’t support compression.

§Arguments
  • path - File path where the uncompressed dump will be written
Source

pub fn dump_tables( &self, path: &Path, tables: Vec<&str>, ) -> Result<DumpMetadata>

Dump specific tables (partial dump)

Creates a dump containing only the specified tables.

§Arguments
  • path - File path where the dump will be written
  • tables - List of table names to include in the dump
Source

pub fn restore_tables(&mut self, path: &Path, _tables: Vec<&str>) -> Result<()>

Restore specific tables from a dump (partial restore)

§Arguments
  • path - Path to the dump file
  • _tables - List of table names to restore
Source

pub fn read_dump_metadata(&self, path: &Path) -> Result<DumpMetadata>

Read dump metadata without restoring

Retrieves metadata from a dump file including version, creation time, and table count without actually restoring any data.

§Arguments
  • path - Path to the dump file
Source

pub fn create_session( &self, user_name: &str, isolation: IsolationLevel, ) -> Result<SessionId>

Create a new session for a user with specified isolation level

Sessions provide isolated execution contexts for multi-user scenarios. Each session maintains its own transaction state and isolation guarantees.

§Arguments
  • user_name - Name of the user for this session
  • isolation - Transaction isolation level for the session
§Returns

A unique SessionId that identifies this session

§Examples
use heliosdb_nano::EmbeddedDatabase;
use heliosdb_nano::session::IsolationLevel;

let db = EmbeddedDatabase::new_in_memory()?;

// Create a session with snapshot isolation
let session_id = db.create_session("alice", IsolationLevel::Snapshot)?;

// Execute queries in the session context
db.execute_in_session(session_id, "CREATE TABLE test (id INT)")?;

// Clean up when done
db.destroy_session(session_id)?;
Source

pub fn destroy_session(&self, session_id: SessionId) -> Result<()>

Destroy an active session and release all resources

This terminates the session and releases all associated resources including active transactions, locks, and memory. Any uncommitted transaction is automatically rolled back.

§Arguments
  • session_id - ID of the session to destroy
Source

pub fn begin_transaction_for_session(&self, session_id: SessionId) -> Result<()>

Begin an explicit transaction for a specific session

Starts a new transaction within the session context. The transaction uses the isolation level specified when the session was created.

§Arguments
  • session_id - ID of the session to begin transaction in
§Errors

Returns an error if the session already has an active transaction.

Source

pub fn commit_transaction_for_session( &self, session_id: SessionId, ) -> Result<()>

Commit transaction for a specific session

Atomically applies all buffered writes from the session’s transaction to the database. After commit, the transaction is finalized.

§Arguments
  • session_id - ID of the session whose transaction to commit
§Errors

Returns an error if the session has no active transaction.

Source

pub fn rollback_transaction_for_session( &self, session_id: SessionId, ) -> Result<()>

Rollback transaction for a specific session

Discards all buffered writes from the session’s transaction without applying them. After rollback, the transaction is finalized and a new transaction can be started.

§Arguments
  • session_id - ID of the session whose transaction to rollback
§Errors

Returns an error if the session has no active transaction.

Source

pub fn execute_in_session( &self, session_id: SessionId, sql: &str, ) -> Result<u64>

Execute SQL in a specific session

Executes a SQL statement within the session’s context. If the session has an active transaction, the statement is executed within that transaction. Otherwise, an implicit auto-commit transaction is used.

For ReadCommitted isolation, each statement gets a fresh snapshot. For Snapshot isolation, all statements in a transaction see the same consistent snapshot.

§Arguments
  • session_id - ID of the session to execute in
  • sql - SQL statement to execute
§Returns

Number of rows affected by the statement

Source

pub fn query_in_session( &self, session_id: SessionId, sql: &str, _params: &[&dyn Display], ) -> Result<Vec<Tuple>>

Query data in a specific session

Executes a SELECT query within the session’s context. If the session has an active transaction, the query uses that transaction’s snapshot for consistent reads.

§Arguments
  • session_id - ID of the session to query in
  • sql - SQL SELECT query
  • _params - Query parameters (reserved for future use)
§Returns

Vector of tuples matching the query

Source

pub fn set_session_quota( &self, _user_name: &str, _max_sessions: usize, ) -> Result<()>

Set session quota for a user

Source

pub fn set_memory_quota( &self, _user_name: &str, _max_bytes: usize, ) -> Result<()>

Set memory quota for a user

Source

pub fn is_dirty(&self) -> bool

Check if database has uncommitted changes

Source

pub fn mark_table_dirty(&self, table: &str)

Mark a table as dirty (for testing)

Source

pub fn query_params(&self, sql: &str, params: &[Value]) -> Result<Vec<Tuple>>

Query data with parameters (SAFE - prevents SQL injection)

This method uses parameterized queries to safely execute SELECT queries with user input. Parameters are referenced as $1, $2, $3, etc. in PostgreSQL style.

§Arguments
  • sql - SQL query with parameter placeholders ($1, $2, etc.)
  • params - Parameter values in order
§Examples
use heliosdb_nano::{EmbeddedDatabase, Value};

let db = EmbeddedDatabase::new("./data")?;

// Create and populate table
db.execute("CREATE TABLE users (id INT, name TEXT, age INT)")?;
db.execute("INSERT INTO users VALUES (1, 'Alice', 30)")?;
db.execute("INSERT INTO users VALUES (2, 'Bob', 25)")?;

// Safe SELECT with single parameter
let results = db.query_params(
    "SELECT * FROM users WHERE name = $1",
    &[Value::String("Alice".to_string())]
)?;
println!("Found {} users named Alice", results.len());

// Safe SELECT with multiple parameters
let results = db.query_params(
    "SELECT * FROM users WHERE age > $1 AND name LIKE $2",
    &[
        Value::Int4(20),
        Value::String("%li%".to_string()),
    ]
)?;
println!("Found {} matching users", results.len());

// SQL injection attempt is safely handled
let malicious_input = "'; DROP TABLE users; --";
let results = db.query_params(
    "SELECT * FROM users WHERE name = $1",
    &[Value::String(malicious_input.to_string())]
)?;
// No users found, but table is safe!
println!("Found {} users (table still exists!)", results.len());
§Security

This method prevents SQL injection by treating parameters as data, not code. Even malicious input is safely handled as a literal value.

Source

pub fn begin(&self) -> Result<()>

Begin an explicit transaction

This method starts a new transaction. All subsequent SQL operations will be part of this transaction until commit() or rollback() is called.

§Examples
use heliosdb_nano::EmbeddedDatabase;

let db = EmbeddedDatabase::new("./data")?;

// Begin transaction
db.begin()?;

// Execute queries in transaction
db.execute("INSERT INTO users VALUES (1, 'Alice')")?;
db.execute("INSERT INTO users VALUES (2, 'Bob')")?;

// Commit changes
db.commit()?;
§Errors

Returns an error if a transaction is already active.

Source

pub fn commit(&self) -> Result<()>

Commit the current transaction

Permanently applies all changes made during the transaction.

§Examples
use heliosdb_nano::EmbeddedDatabase;

let db = EmbeddedDatabase::new("./data")?;

db.begin()?;
db.execute("DELETE FROM users WHERE id = 1")?;
db.commit()?; // Changes are now permanent
§Errors

Returns an error if no transaction is active.

Source

pub fn rollback(&self) -> Result<()>

Rollback the current transaction

Discards all changes made during the transaction.

§Examples
use heliosdb_nano::EmbeddedDatabase;

let db = EmbeddedDatabase::new("./data")?;

db.begin()?;
db.execute("DELETE FROM users")?;
// Oops, didn't mean to do that!
db.rollback()?; // Changes are discarded
§Errors

Returns an error if no transaction is active.

Source

pub fn in_transaction(&self) -> bool

Check if a transaction is currently active

Returns true if begin() has been called without a matching commit() or rollback().

§Examples
use heliosdb_nano::EmbeddedDatabase;

let db = EmbeddedDatabase::new("./data")?;

assert!(!db.in_transaction());

db.begin()?;
assert!(db.in_transaction());

db.commit()?;
assert!(!db.in_transaction());
Source

pub fn begin_transaction(&self) -> Result<Transaction<'_>>

👎Deprecated since 2.1.0:

Use begin(), commit(), and rollback() instead

Begin a transaction (DEPRECATED - use begin() instead)

This method is deprecated and will be removed in a future version. Use begin(), commit(), and rollback() instead for better transaction control.

§Examples
use heliosdb_nano::EmbeddedDatabase;

let db = EmbeddedDatabase::new("./data")?;
let tx = db.begin_transaction()?;
// ... perform operations
tx.commit()?;
Source

pub fn current_lsn(&self) -> Option<u64>

Get the current WAL LSN (Log Sequence Number)

Returns the current position in the Write-Ahead Log. Useful for debugging and transaction tracking.

Source

pub fn close(self) -> Result<()>

Close the database

Flushes pending data and releases resources. The database will also be cleaned up automatically when dropped.

Source

pub fn list_vector_stores(&self) -> Result<Vec<VectorStoreInfo>>

List all vector stores

Source

pub fn create_vector_store( &self, name: &str, dimensions: u32, ) -> Result<VectorStoreInfo>

Create a new vector store

Source

pub fn get_vector_store(&self, name: &str) -> Result<VectorStoreInfo>

Get vector store info

Source

pub fn delete_vector_store(&self, name: &str) -> Result<()>

Delete a vector store

Source

pub fn insert_vectors( &self, store: &str, vectors: Vec<Vec<f32>>, ) -> Result<Vec<String>>

Insert vectors into a store

Returns a list of generated vector IDs

Source

pub fn upsert_vectors( &self, store: &str, vectors: Vec<(String, Vec<f32>)>, ) -> Result<()>

Upsert vectors (insert or update)

Source

pub fn search_vectors( &self, store: &str, query: Vec<f32>, k: usize, ) -> Result<Vec<(String, f32)>>

Search for similar vectors

Returns (vector_id, distance) pairs sorted by similarity

Text search (requires text embedding - stub for now)

Source

pub fn store_texts( &self, _store: &str, _texts: Vec<String>, ) -> Result<Vec<String>>

Store texts for embedding (requires embedding model - stub for now)

Hybrid search (vector + text) - requires embedding model

Source

pub fn delete_vectors(&self, store: &str, ids: Vec<String>) -> Result<()>

Delete vectors by ID

Source

pub fn fetch_vectors( &self, _store: &str, _ids: Vec<String>, ) -> Result<Vec<(String, Vec<f32>)>>

Fetch vectors by ID (not yet implemented - requires storing raw vectors)

Source

pub fn list_agent_sessions(&self) -> Result<Vec<AgentSession>>

List agent sessions

Source

pub fn create_agent_session(&self, _name: &str) -> Result<AgentSession>

Create agent session

Source

pub fn get_agent_session(&self, _id: &str) -> Result<AgentSession>

Get agent session

Source

pub fn delete_agent_session(&self, _id: &str) -> Result<()>

Delete agent session

Source

pub fn add_agent_message( &self, _session_id: &str, _role: &str, _content: &str, ) -> Result<AgentMessage>

Add message to agent session

Source

pub fn get_agent_messages(&self, _session_id: &str) -> Result<Vec<AgentMessage>>

Get messages from agent session

Source

pub fn clear_agent_messages(&self, _session_id: &str) -> Result<()>

Clear agent session messages

Source

pub fn generate_schema(&self, _table_name: &str) -> Result<String>

Generate schema from data

Source

pub fn chat_completion( &self, _messages: Vec<(String, String)>, ) -> Result<String>

Get AI chat completion

Source

pub fn nl_to_sql(&self, _query: &str) -> Result<String>

Get NL to SQL conversion

Source

pub fn store_document( &self, _collection: &str, _id: &str, _content: &str, _metadata: Option<Value>, ) -> Result<()>

Store document

Source

pub fn get_document(&self, _collection: &str, _id: &str) -> Result<DocumentData>

Get document

Source

pub fn delete_document(&self, _collection: &str, _id: &str) -> Result<()>

Delete document

Source

pub fn update_document( &self, _collection: &str, _id: &str, _content: &str, _metadata: Option<Value>, ) -> Result<()>

Update document

Source

pub fn list_documents(&self, _collection: &str) -> Result<Vec<DocumentMetadata>>

List documents in collection

Source

pub fn search_documents( &self, _collection: &str, _query: &str, ) -> Result<Vec<DocumentData>>

Search documents

Source

pub fn create_collection(&self, _name: &str) -> Result<()>

Create collection

Source

pub fn delete_collection(&self, _name: &str) -> Result<()>

Delete collection

Source

pub fn list_collections(&self) -> Result<Vec<String>>

List collections

Source

pub fn batch_create_documents( &self, _collection: &str, _docs: Vec<DocumentData>, ) -> Result<Vec<String>>

Batch create documents

Source

pub fn batch_infer_schema(&self, _data: Vec<Vec<Value>>) -> Result<Schema>

Batch infer schema

Source

pub fn chat_completion_stream( &self, _messages: Vec<(String, String)>, ) -> Result<String>

Chat completion stream

Source

pub fn compare_schemas( &self, _schema1: &Schema, _schema2: &Schema, ) -> Result<Value>

Compare schemas

Source

pub fn create_embeddings(&self, _texts: Vec<String>) -> Result<Vec<Vec<f32>>>

Create embeddings

Source

pub fn create_document( &self, _collection: &str, _id: &str, _content: &str, _metadata: Option<Value>, ) -> Result<String>

Create document (alias for store_document)

Source

pub fn find_similar_documents( &self, _collection: &str, _query: &str, _limit: usize, ) -> Result<Vec<(DocumentData, f32)>>

Find similar documents

Source

pub fn fork_agent_session( &self, _session_id: &str, _new_name: &str, ) -> Result<AgentSession>

Fork agent session

Source

pub fn generate_schema_from_description( &self, _description: &str, ) -> Result<Schema>

Generate schema from description

Source

pub fn get_agent_context(&self, _session_id: &str) -> Result<Value>

Get agent context

Source

pub fn get_chat_model(&self, _model_id: &str) -> Result<Value>

Get chat model

Source

pub fn get_document_chunks( &self, _collection: &str, _id: &str, ) -> Result<Vec<(String, f32)>>

Get document chunks

Source

pub fn infer_schema(&self, _data: Vec<Vec<Value>>) -> Result<Schema>

Infer schema

Source

pub fn infer_schema_from_file(&self, _path: &str) -> Result<Schema>

Infer schema from file

Source

pub fn instantiate_schema_template( &self, _template_name: &str, _params: Value, ) -> Result<Schema>

Instantiate schema template

Source

pub fn list_chat_models(&self) -> Result<Vec<Value>>

List chat models

Source

pub fn list_schema_templates(&self) -> Result<Vec<Value>>

List schema templates

Source

pub fn optimize_schema(&self, _schema: &Schema) -> Result<Schema>

Optimize schema

Source

pub fn validate_schema(&self, _schema: &Schema) -> Result<bool>

Validate schema

RAG search (Retrieval Augmented Generation)

Source

pub fn rechunk_document( &self, _collection: &str, _id: &str, _chunk_size: usize, ) -> Result<Vec<String>>

Rechunk document

Source

pub fn search_agent_memory( &self, _session_id: &str, _query: &str, ) -> Result<Vec<(AgentMessage, f32)>>

Search agent memory

Source

pub fn summarize_agent_memory(&self, _session_id: &str) -> Result<String>

Summarize agent memory

Source

pub fn create_branch(&self, name: &str) -> Result<u64>

Create an isolated database branch (copy-on-write).

Source

pub fn switch_branch(&self, name: &str) -> Result<u64>

Switch the active branch.

Source

pub fn merge_branch(&self, source: &str) -> Result<u64>

Merge a branch into the current branch.

Source

pub fn drop_branch(&self, name: &str) -> Result<u64>

Drop a branch.

Source

pub fn list_branches(&self) -> Result<Vec<Tuple>>

List all branches.

Source

pub fn explain(&self, sql: &str) -> Result<Vec<Tuple>>

Return the query execution plan as a string.

Source

pub fn explain_analyze(&self, sql: &str) -> Result<Vec<Tuple>>

Return the query execution plan with runtime statistics.

Source

pub fn refresh_materialized_view(&self, name: &str) -> Result<u64>

Refresh a materialized view.

Source

pub fn reset_all_qps_windows(&self)

Reset QPS quota window for all tenants (synchronous version)

This is a synchronous alternative to start_qps_reset_task() that can be called manually or from a custom scheduler.

§Examples
use heliosdb_nano::EmbeddedDatabase;

let db = EmbeddedDatabase::new_in_memory()?;

// Manually reset QPS windows (e.g., from a timer)
db.reset_all_qps_windows();
Source

pub fn database_name_is_valid(&self, name: &str) -> bool

Bug 5 — validate a StartupMessage database parameter. Returns true for heliosdb / postgres (reserved) or any registered tenant; false for empty / unknown names. Used by the PG-wire startup handler to refuse connections to non-existent databases.

Source

pub async fn start_auto_refresh( &self, config: Option<AutoRefreshConfig>, ) -> Result<()>

Start the materialized view auto-refresh background worker

This enables automatic refresh of materialized views based on staleness thresholds and CPU availability. The worker runs in a background task.

§Arguments
  • config - Optional custom configuration. If None, uses database config defaults.
§Examples
use heliosdb_nano::EmbeddedDatabase;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let db = EmbeddedDatabase::new_in_memory()?;

    // Start with default config
    db.start_auto_refresh(None).await?;

    // Or with custom config
    let config = storage::AutoRefreshConfig::default()
        .with_enabled(true)
        .with_staleness_threshold(600);
    db.start_auto_refresh(Some(config)).await?;

    Ok(())
}
Source

pub async fn stop_auto_refresh(&self) -> Result<()>

Stop the materialized view auto-refresh background worker

Gracefully stops the worker and waits for any in-progress refreshes to complete.

Source

pub fn is_auto_refresh_running(&self) -> bool

Check if the auto-refresh worker is currently running

Source

pub fn mv_scheduler(&self) -> &Arc<MVScheduler>

Get the MV scheduler for manual scheduling operations

Source

pub fn check_mv_staleness_now(&self) -> Result<()>

Force an immediate staleness check and trigger refreshes as needed

This is useful for testing or when you want to ensure views are fresh without waiting for the next scheduled check.

Trait Implementations§

Source§

impl DatabaseInterface for EmbeddedDatabase

Source§

fn list_tables(&self) -> Result<Vec<String>>

List all tables
Source§

fn get_table_schema(&self, table: &str) -> Result<Schema>

Get table schema
Source§

fn scan_table(&self, table: &str) -> Result<Vec<Tuple>>

Scan all rows in a table
Source§

fn get_table_indexes(&self, table: &str) -> Result<Vec<IndexMetadata>>

Get table indexes
Source§

impl DatabaseRestoreInterface for EmbeddedDatabase

Source§

fn create_table(&mut self, name: &str, schema: Schema) -> Result<()>

Create table with schema
Source§

fn create_index(&mut self, table: &str, index: &IndexMetadata) -> Result<()>

Create index
Source§

fn insert_row(&mut self, table: &str, row: Tuple) -> Result<()>

Insert row
Source§

impl Drop for EmbeddedDatabase

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more